repo_name
stringclasses
6 values
pr_number
int64
512
78.9k
pr_title
stringlengths
3
144
pr_description
stringlengths
0
30.3k
author
stringlengths
2
21
date_created
timestamp[ns, tz=UTC]
date_merged
timestamp[ns, tz=UTC]
previous_commit
stringlengths
40
40
pr_commit
stringlengths
40
40
query
stringlengths
17
30.4k
filepath
stringlengths
9
210
before_content
stringlengths
0
112M
after_content
stringlengths
0
112M
label
int64
-1
1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/FromKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions Public Class FromKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInClassDeclarationTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterDimEqualsNewTest() VerifyRecommendationsMissing(<MethodBody>Dim x = New |</MethodBody>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterFromTest() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = New Goo From |</ClassDeclaration>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterWith1Test() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = New With |</ClassDeclaration>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterWith2Test() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = New Goo With |</ClassDeclaration>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterDimEqualsNewTypeNameTest() VerifyRecommendationsContain(<File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim x = new C | End Sub End Module</File>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterDimEqualsNewTypeNameAndParensTest() VerifyRecommendationsContain(<File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim x = new C() | End Sub End Module</File>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterDimAsNewTest() VerifyRecommendationsMissing(<MethodBody>Dim x As New |</MethodBody>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterDimAsNewTypeNameTest() VerifyRecommendationsContain(<File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim x as new C | End Sub End Module</File>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterDimAsNewTypeNameAndParensTest() VerifyRecommendationsContain(<MethodBody>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim x As new C() | End Sub End Module</MethodBody>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterAssignmentNewTest() VerifyRecommendationsMissing(<MethodBody>x = New |</MethodBody>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterAssignmentNewTypeNameTest() VerifyRecommendationsContain(<File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim b = New C | End Sub End Module</File>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterAssignmentNewTypeNameAndParensTest() VerifyRecommendationsContain(<MethodBody>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim x as C x = new C() | End Sub End Module</MethodBody>, "From") End Sub <WorkItem(542741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542741")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterLambdaHeaderTest() VerifyRecommendationsContain(<MethodBody>Dim q1 As Func(Of Integer()) = Function() |</MethodBody>, "From") End Sub <WorkItem(543291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543291")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoFromAfterDotTest() Dim code = <File> Class C Sub M() Dim c As New C.| End Sub End Class </File> VerifyRecommendationsMissing(code, "From") End Sub <WorkItem(542252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542252")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoFromIfNotCollectionInitializerTest() Dim code = <File> System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim y = New Goo() | End Sub End Module Class Goo End Class </File> VerifyRecommendationsMissing(code, "From") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub Dim b = New C | End Class</File>, "From") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub Dim b = New C _ | End Class</File>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub Dim b = New C _ ' Test | End Class</File>, "From") End Sub <WorkItem(4754, "https://github.com/dotnet/roslyn/issues/4754")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromForTypeInheritingCollectionInitializerPatternTest() Dim code = <File> Imports System.Collections Public Class SupportsAdd Implements IEnumerable Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Public Sub Add(x As Object) End Sub End Class Public Class DerivedSupportsAdd Inherits SupportsAdd End Class Class Program Sub Goo() Dim x = New DerivedSupportsAdd | End Sub End Class </File> VerifyRecommendationsContain(code, "From") End Sub <WorkItem(4754, "https://github.com/dotnet/roslyn/issues/4754")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromForTypeInheritingCollectionInitializerPatternInAccessibleTest() Dim code = <File> Imports System.Collections Public Class SupportsAdd Implements IEnumerable Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Protected Sub Add(x As Object) End Sub End Class Public Class DerivedSupportsAdd Inherits SupportsAdd End Class Class Program Sub Goo() Dim x = New DerivedSupportsAdd | End Sub End Class </File> VerifyRecommendationsMissing(code, "From") End Sub <WorkItem(4754, "https://github.com/dotnet/roslyn/issues/4754")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromForTypeInheritingCollectionInitializerPatternAccessibleTest() Dim code = <File> Imports System.Collections Public Class SupportsAdd Implements IEnumerable Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Protected Sub Add(x As Object) End Sub End Class Public Class DerivedSupportsAdd Inherits SupportsAdd Sub Goo() Dim x = New DerivedSupportsAdd | End Sub End Class</File> VerifyRecommendationsContain(code, "From") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions Public Class FromKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInClassDeclarationTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterDimEqualsNewTest() VerifyRecommendationsMissing(<MethodBody>Dim x = New |</MethodBody>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterFromTest() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = New Goo From |</ClassDeclaration>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterWith1Test() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = New With |</ClassDeclaration>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterWith2Test() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = New Goo With |</ClassDeclaration>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterDimEqualsNewTypeNameTest() VerifyRecommendationsContain(<File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim x = new C | End Sub End Module</File>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterDimEqualsNewTypeNameAndParensTest() VerifyRecommendationsContain(<File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim x = new C() | End Sub End Module</File>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterDimAsNewTest() VerifyRecommendationsMissing(<MethodBody>Dim x As New |</MethodBody>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterDimAsNewTypeNameTest() VerifyRecommendationsContain(<File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim x as new C | End Sub End Module</File>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterDimAsNewTypeNameAndParensTest() VerifyRecommendationsContain(<MethodBody>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim x As new C() | End Sub End Module</MethodBody>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterAssignmentNewTest() VerifyRecommendationsMissing(<MethodBody>x = New |</MethodBody>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterAssignmentNewTypeNameTest() VerifyRecommendationsContain(<File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim b = New C | End Sub End Module</File>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterAssignmentNewTypeNameAndParensTest() VerifyRecommendationsContain(<MethodBody>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub End Class Module Program Sub Main(args As String()) Dim x as C x = new C() | End Sub End Module</MethodBody>, "From") End Sub <WorkItem(542741, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542741")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromAfterLambdaHeaderTest() VerifyRecommendationsContain(<MethodBody>Dim q1 As Func(Of Integer()) = Function() |</MethodBody>, "From") End Sub <WorkItem(543291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543291")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoFromAfterDotTest() Dim code = <File> Class C Sub M() Dim c As New C.| End Sub End Class </File> VerifyRecommendationsMissing(code, "From") End Sub <WorkItem(542252, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542252")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoFromIfNotCollectionInitializerTest() Dim code = <File> System Imports System.Collections.Generic Imports System.Linq Module Program Sub Main(args As String()) Dim y = New Goo() | End Sub End Module Class Goo End Class </File> VerifyRecommendationsMissing(code, "From") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub Dim b = New C | End Class</File>, "From") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub Dim b = New C _ | End Class</File>, "From") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <File>Imports System.Collections.Generic Class C Implements IEnumerable(Of Integer) Public Sub Add(i As Integer) End Sub Dim b = New C _ ' Test | End Class</File>, "From") End Sub <WorkItem(4754, "https://github.com/dotnet/roslyn/issues/4754")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromForTypeInheritingCollectionInitializerPatternTest() Dim code = <File> Imports System.Collections Public Class SupportsAdd Implements IEnumerable Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Public Sub Add(x As Object) End Sub End Class Public Class DerivedSupportsAdd Inherits SupportsAdd End Class Class Program Sub Goo() Dim x = New DerivedSupportsAdd | End Sub End Class </File> VerifyRecommendationsContain(code, "From") End Sub <WorkItem(4754, "https://github.com/dotnet/roslyn/issues/4754")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromForTypeInheritingCollectionInitializerPatternInAccessibleTest() Dim code = <File> Imports System.Collections Public Class SupportsAdd Implements IEnumerable Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Protected Sub Add(x As Object) End Sub End Class Public Class DerivedSupportsAdd Inherits SupportsAdd End Class Class Program Sub Goo() Dim x = New DerivedSupportsAdd | End Sub End Class </File> VerifyRecommendationsMissing(code, "From") End Sub <WorkItem(4754, "https://github.com/dotnet/roslyn/issues/4754")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub FromForTypeInheritingCollectionInitializerPatternAccessibleTest() Dim code = <File> Imports System.Collections Public Class SupportsAdd Implements IEnumerable Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator Throw New NotImplementedException() End Function Protected Sub Add(x As Object) End Sub End Class Public Class DerivedSupportsAdd Inherits SupportsAdd Sub Goo() Dim x = New DerivedSupportsAdd | End Sub End Class</File> VerifyRecommendationsContain(code, "From") End Sub End Class End Namespace
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/EditorFeatures/VisualBasic/LineCommit/CommitBufferManagerFactory.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.ComponentModel.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit <Export(GetType(CommitBufferManagerFactory))> Friend Class CommitBufferManagerFactory Private ReadOnly _commitFormatter As ICommitFormatter Private ReadOnly _inlineRenameService As IInlineRenameService Private ReadOnly _threadingContext As IThreadingContext <ImportingConstructor()> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New(commitFormatter As ICommitFormatter, inlineRenameService As IInlineRenameService, threadingContext As IThreadingContext) _commitFormatter = commitFormatter _inlineRenameService = inlineRenameService _threadingContext = threadingContext End Sub Public Function CreateForBuffer(buffer As ITextBuffer) As CommitBufferManager Return buffer.Properties.GetOrCreateSingletonProperty(Function() New CommitBufferManager(buffer, _commitFormatter, _inlineRenameService, _threadingContext)) 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.ComponentModel.Composition Imports System.Diagnostics.CodeAnalysis Imports Microsoft.CodeAnalysis.Editor.Shared.Utilities Imports Microsoft.VisualStudio.Text Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.LineCommit <Export(GetType(CommitBufferManagerFactory))> Friend Class CommitBufferManagerFactory Private ReadOnly _commitFormatter As ICommitFormatter Private ReadOnly _inlineRenameService As IInlineRenameService Private ReadOnly _threadingContext As IThreadingContext <ImportingConstructor()> <SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification:="Used in test code: https://github.com/dotnet/roslyn/issues/42814")> Public Sub New(commitFormatter As ICommitFormatter, inlineRenameService As IInlineRenameService, threadingContext As IThreadingContext) _commitFormatter = commitFormatter _inlineRenameService = inlineRenameService _threadingContext = threadingContext End Sub Public Function CreateForBuffer(buffer As ITextBuffer) As CommitBufferManager Return buffer.Properties.GetOrCreateSingletonProperty(Function() New CommitBufferManager(buffer, _commitFormatter, _inlineRenameService, _threadingContext)) End Function End Class End Namespace
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Compilers/VisualBasic/Test/Semantic/SourceGeneration/GeneratorDriverTests.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.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities.TestGenerators Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class GeneratorDriverTests Inherits BasicTestBase <Fact> Public Sub Single_File_Is_Added() Dim generatorSource = " Public Class GeneratedClass End Class " Dim parseOptions = TestOptions.Regular Dim compilation = GetCompilation(parseOptions) Dim testGenerator As SingleFileTestGenerator = New SingleFileTestGenerator(generatorSource) Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify() Assert.Equal(2, outputCompilation.SyntaxTrees.Count()) Assert.NotEqual(compilation, outputCompilation) End Sub <Fact> Public Sub Can_Access_Additional_Files() Dim additionalText = New InMemoryAdditionalText("a\\file1.cs", "Hello World") Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i) End Sub, Sub(e) Assert.Equal("Hello World", e.AdditionalFiles.First().GetText().ToString())) Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), additionalTexts:=ImmutableArray.Create(Of AdditionalText)(additionalText), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify() End Sub <Fact> Public Sub Generator_Can_Be_Written_In_Visual_Basic() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As VBGenerator = New VBGenerator() Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify() Assert.Equal(2, outputCompilation.SyntaxTrees.Count()) Assert.NotEqual(compilation, outputCompilation) End Sub <Fact> Public Sub Generator_Can_See_Syntax() Dim source = " Imports System Namespace ANamespace Public Class AClass Public Sub AMethod(p as String) Throw New InvalidOperationException() End Sub End Class End Namespace " Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions, source) Dim testGenerator As VBGenerator = New VBGenerator() Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify() Assert.Equal(23, testGenerator._receiver._nodes.Count) Assert.IsType(GetType(CompilationUnitSyntax), testGenerator._receiver._nodes(0)) Assert.IsType(GetType(ClassStatementSyntax), testGenerator._receiver._nodes(8)) Assert.IsType(GetType(ThrowStatementSyntax), testGenerator._receiver._nodes(16)) Assert.IsType(GetType(EndBlockStatementSyntax), testGenerator._receiver._nodes(22)) End Sub <Fact> Public Sub Exception_During_Init() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i) Throw New Exception("Init Exception"), Sub(e) End Sub) Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify( Diagnostic("BC42501").WithArguments("CallbackGenerator", "Exception", "Init Exception").WithLocation(1, 1) ) End Sub <Fact> Public Sub Exception_During_Execute() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i) End Sub, Sub(e) Throw New Exception("Generate Exception")) Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify( Diagnostic("BC42502").WithArguments("CallbackGenerator", "Exception", "Generate Exception").WithLocation(1, 1) ) End Sub <Fact> Public Sub Exception_During_SyntaxWalk() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As VBGenerator = New VBGenerator() testGenerator._receiver._throw = True Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify( Diagnostic("BC42502").WithArguments("VBGenerator", "Exception", "Syntax Walk").WithLocation(1, 1) ) End Sub <Fact> Public Sub SyntaxTrees_Are_Lazy() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator = New SingleFileTestGenerator("Class C : End Class") Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) driver = driver.RunGenerators(compilation) Dim results = driver.GetRunResult() Dim tree = Assert.Single(results.GeneratedTrees) Dim rootFromTryGetRoot As SyntaxNode = Nothing Assert.False(tree.TryGetRoot(rootFromTryGetRoot)) Dim rootFromGetRoot = tree.GetRoot() Assert.NotNull(rootFromGetRoot) Assert.True(tree.TryGetRoot(rootFromTryGetRoot)) Assert.Same(rootFromGetRoot, rootFromTryGetRoot) End Sub <Fact> Public Sub Diagnostics_Respect_Suppression() Dim compilation As Compilation = GetCompilation(TestOptions.Regular) Dim gen As CallbackGenerator = New CallbackGenerator(Sub(c) End Sub, Sub(c) c.ReportDiagnostic(VBDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, True, 2)) c.ReportDiagnostic(VBDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, True, 3)) End Sub) VerifyDiagnosticsWithOptions(gen, compilation, Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)) Dim warnings As IDictionary(Of String, ReportDiagnostic) = New Dictionary(Of String, ReportDiagnostic)() warnings.Add("GEN001", ReportDiagnostic.Suppress) VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)), Diagnostic("GEN002").WithLocation(1, 1)) warnings.Clear() warnings.Add("GEN002", ReportDiagnostic.Suppress) VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)), Diagnostic("GEN001").WithLocation(1, 1)) warnings.Clear() warnings.Add("GEN001", ReportDiagnostic.Error) VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)), Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(True), Diagnostic("GEN002").WithLocation(1, 1)) warnings.Clear() warnings.Add("GEN002", ReportDiagnostic.Error) VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(True)) End Sub <Fact> Public Sub Diagnostics_Respect_Pragma_Suppression() Dim gen001 = VBDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, True, 2) VerifyDiagnosticsWithSource("'comment", gen001, TextSpan.FromBounds(1, 4), Diagnostic("GEN001", "com").WithLocation(1, 2)) VerifyDiagnosticsWithSource("#disable warning 'comment", gen001, TextSpan.FromBounds(19, 22), Diagnostic("GEN001", "com", isSuppressed:=True).WithLocation(2, 2)) VerifyDiagnosticsWithSource("#disable warning 'comment", gen001, New TextSpan(0, 0), Diagnostic("GEN001").WithLocation(1, 1)) VerifyDiagnosticsWithSource("#disable warning GEN001 'comment", gen001, TextSpan.FromBounds(26, 29), Diagnostic("GEN001", "com", isSuppressed:=True).WithLocation(2, 2)) VerifyDiagnosticsWithSource("#disable warning GEN001 'comment #enable warning GEN001 'another", gen001, TextSpan.FromBounds(60, 63), Diagnostic("GEN001", "ano").WithLocation(4, 2)) End Sub <Fact> Public Sub Enable_Incremental_Generators() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As VBIncrementalGenerator = New VBIncrementalGenerator() Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(New IncrementalGeneratorWrapper(testGenerator)), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify() Assert.Equal(1, outputCompilation.SyntaxTrees.Count()) Assert.Equal(compilation, compilation) Assert.True(testGenerator._initialized) End Sub <Fact> Public Sub Prefer_Incremental_Generators() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As VBIncrementalAndSourceGenerator = New VBIncrementalAndSourceGenerator() Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify() Assert.Equal(1, outputCompilation.SyntaxTrees.Count()) Assert.Equal(compilation, compilation) Assert.True(testGenerator._initialized) Assert.False(testGenerator._sourceInitialized) Assert.False(testGenerator._sourceExecuted) End Sub Shared Function GetCompilation(parseOptions As VisualBasicParseOptions, Optional source As String = "") As Compilation If (String.IsNullOrWhiteSpace(source)) Then source = " Public Class C End Class " End If Dim compilation As Compilation = CreateCompilation(source, options:=TestOptions.DebugDll, parseOptions:=parseOptions) compilation.VerifyDiagnostics() Assert.Single(compilation.SyntaxTrees) Return compilation End Function Shared Sub VerifyDiagnosticsWithOptions(generator As ISourceGenerator, compilation As Compilation, ParamArray expected As DiagnosticDescription()) compilation.VerifyDiagnostics() Assert.Single(compilation.SyntaxTrees) Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(generator), parseOptions:=TestOptions.Regular) Dim outputCompilation As Compilation = Nothing Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, diagnostics) outputCompilation.VerifyDiagnostics() diagnostics.Verify(expected) End Sub Shared Sub VerifyDiagnosticsWithSource(source As String, diag As Diagnostic, location As TextSpan, ParamArray expected As DiagnosticDescription()) Dim parseOptions = TestOptions.Regular source = source.Replace(Environment.NewLine, vbCrLf) Dim compilation As Compilation = CreateCompilation(source) compilation.VerifyDiagnostics() Assert.Single(compilation.SyntaxTrees) Dim gen As ISourceGenerator = New CallbackGenerator(Sub(c) End Sub, Sub(c) If location.IsEmpty Then c.ReportDiagnostic(diag) Else c.ReportDiagnostic(diag.WithLocation(CodeAnalysis.Location.Create(c.Compilation.SyntaxTrees.First(), location))) End If End Sub) Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions:=TestOptions.Regular) Dim outputCompilation As Compilation = Nothing Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, diagnostics) outputCompilation.VerifyDiagnostics() diagnostics.Verify(expected) End Sub End Class <Generator(LanguageNames.VisualBasic)> Friend Class VBGenerator Implements ISourceGenerator Public _receiver As Receiver = New Receiver() Public Sub Initialize(context As GeneratorInitializationContext) Implements ISourceGenerator.Initialize context.RegisterForSyntaxNotifications(Function() _receiver) End Sub Public Sub Execute(context As GeneratorExecutionContext) Implements ISourceGenerator.Execute context.AddSource("source.vb", " Public Class D End Class ") End Sub Class Receiver Implements ISyntaxReceiver Public _throw As Boolean Public _nodes As List(Of SyntaxNode) = New List(Of SyntaxNode)() Public Sub OnVisitSyntaxNode(syntaxNode As SyntaxNode) Implements ISyntaxReceiver.OnVisitSyntaxNode If (_throw) Then Throw New Exception("Syntax Walk") End If _nodes.Add(syntaxNode) End Sub End Class End Class <Generator(LanguageNames.VisualBasic)> Friend Class VBIncrementalGenerator Implements IIncrementalGenerator Public _initialized As Boolean Public Sub Initialize(context As IncrementalGeneratorInitializationContext) Implements IIncrementalGenerator.Initialize _initialized = True End Sub End Class <Generator(LanguageNames.VisualBasic)> Friend Class VBIncrementalAndSourceGenerator Implements IIncrementalGenerator Implements ISourceGenerator Public _initialized As Boolean Public _sourceInitialized As Boolean Public _sourceExecuted As Boolean Public Sub Initialize(context As IncrementalGeneratorInitializationContext) Implements IIncrementalGenerator.Initialize _initialized = True End Sub Public Sub Initialize(context As GeneratorInitializationContext) Implements ISourceGenerator.Initialize _sourceInitialized = True End Sub Public Sub Execute(context As GeneratorExecutionContext) Implements ISourceGenerator.Execute _sourceExecuted = True 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.Test.Utilities Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities.TestGenerators Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class GeneratorDriverTests Inherits BasicTestBase <Fact> Public Sub Single_File_Is_Added() Dim generatorSource = " Public Class GeneratedClass End Class " Dim parseOptions = TestOptions.Regular Dim compilation = GetCompilation(parseOptions) Dim testGenerator As SingleFileTestGenerator = New SingleFileTestGenerator(generatorSource) Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify() Assert.Equal(2, outputCompilation.SyntaxTrees.Count()) Assert.NotEqual(compilation, outputCompilation) End Sub <Fact> Public Sub Can_Access_Additional_Files() Dim additionalText = New InMemoryAdditionalText("a\\file1.cs", "Hello World") Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i) End Sub, Sub(e) Assert.Equal("Hello World", e.AdditionalFiles.First().GetText().ToString())) Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), additionalTexts:=ImmutableArray.Create(Of AdditionalText)(additionalText), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify() End Sub <Fact> Public Sub Generator_Can_Be_Written_In_Visual_Basic() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As VBGenerator = New VBGenerator() Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify() Assert.Equal(2, outputCompilation.SyntaxTrees.Count()) Assert.NotEqual(compilation, outputCompilation) End Sub <Fact> Public Sub Generator_Can_See_Syntax() Dim source = " Imports System Namespace ANamespace Public Class AClass Public Sub AMethod(p as String) Throw New InvalidOperationException() End Sub End Class End Namespace " Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions, source) Dim testGenerator As VBGenerator = New VBGenerator() Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify() Assert.Equal(23, testGenerator._receiver._nodes.Count) Assert.IsType(GetType(CompilationUnitSyntax), testGenerator._receiver._nodes(0)) Assert.IsType(GetType(ClassStatementSyntax), testGenerator._receiver._nodes(8)) Assert.IsType(GetType(ThrowStatementSyntax), testGenerator._receiver._nodes(16)) Assert.IsType(GetType(EndBlockStatementSyntax), testGenerator._receiver._nodes(22)) End Sub <Fact> Public Sub Exception_During_Init() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i) Throw New Exception("Init Exception"), Sub(e) End Sub) Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify( Diagnostic("BC42501").WithArguments("CallbackGenerator", "Exception", "Init Exception").WithLocation(1, 1) ) End Sub <Fact> Public Sub Exception_During_Execute() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As CallbackGenerator = New CallbackGenerator(Sub(i) End Sub, Sub(e) Throw New Exception("Generate Exception")) Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify( Diagnostic("BC42502").WithArguments("CallbackGenerator", "Exception", "Generate Exception").WithLocation(1, 1) ) End Sub <Fact> Public Sub Exception_During_SyntaxWalk() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As VBGenerator = New VBGenerator() testGenerator._receiver._throw = True Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify( Diagnostic("BC42502").WithArguments("VBGenerator", "Exception", "Syntax Walk").WithLocation(1, 1) ) End Sub <Fact> Public Sub SyntaxTrees_Are_Lazy() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator = New SingleFileTestGenerator("Class C : End Class") Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) driver = driver.RunGenerators(compilation) Dim results = driver.GetRunResult() Dim tree = Assert.Single(results.GeneratedTrees) Dim rootFromTryGetRoot As SyntaxNode = Nothing Assert.False(tree.TryGetRoot(rootFromTryGetRoot)) Dim rootFromGetRoot = tree.GetRoot() Assert.NotNull(rootFromGetRoot) Assert.True(tree.TryGetRoot(rootFromTryGetRoot)) Assert.Same(rootFromGetRoot, rootFromTryGetRoot) End Sub <Fact> Public Sub Diagnostics_Respect_Suppression() Dim compilation As Compilation = GetCompilation(TestOptions.Regular) Dim gen As CallbackGenerator = New CallbackGenerator(Sub(c) End Sub, Sub(c) c.ReportDiagnostic(VBDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, True, 2)) c.ReportDiagnostic(VBDiagnostic.Create("GEN002", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, True, 3)) End Sub) VerifyDiagnosticsWithOptions(gen, compilation, Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1)) Dim warnings As IDictionary(Of String, ReportDiagnostic) = New Dictionary(Of String, ReportDiagnostic)() warnings.Add("GEN001", ReportDiagnostic.Suppress) VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)), Diagnostic("GEN002").WithLocation(1, 1)) warnings.Clear() warnings.Add("GEN002", ReportDiagnostic.Suppress) VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)), Diagnostic("GEN001").WithLocation(1, 1)) warnings.Clear() warnings.Add("GEN001", ReportDiagnostic.Error) VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)), Diagnostic("GEN001").WithLocation(1, 1).WithWarningAsError(True), Diagnostic("GEN002").WithLocation(1, 1)) warnings.Clear() warnings.Add("GEN002", ReportDiagnostic.Error) VerifyDiagnosticsWithOptions(gen, compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)), Diagnostic("GEN001").WithLocation(1, 1), Diagnostic("GEN002").WithLocation(1, 1).WithWarningAsError(True)) End Sub <Fact> Public Sub Diagnostics_Respect_Pragma_Suppression() Dim gen001 = VBDiagnostic.Create("GEN001", "generators", "message", DiagnosticSeverity.Warning, DiagnosticSeverity.Warning, True, 2) VerifyDiagnosticsWithSource("'comment", gen001, TextSpan.FromBounds(1, 4), Diagnostic("GEN001", "com").WithLocation(1, 2)) VerifyDiagnosticsWithSource("#disable warning 'comment", gen001, TextSpan.FromBounds(19, 22), Diagnostic("GEN001", "com", isSuppressed:=True).WithLocation(2, 2)) VerifyDiagnosticsWithSource("#disable warning 'comment", gen001, New TextSpan(0, 0), Diagnostic("GEN001").WithLocation(1, 1)) VerifyDiagnosticsWithSource("#disable warning GEN001 'comment", gen001, TextSpan.FromBounds(26, 29), Diagnostic("GEN001", "com", isSuppressed:=True).WithLocation(2, 2)) VerifyDiagnosticsWithSource("#disable warning GEN001 'comment #enable warning GEN001 'another", gen001, TextSpan.FromBounds(60, 63), Diagnostic("GEN001", "ano").WithLocation(4, 2)) End Sub <Fact> Public Sub Enable_Incremental_Generators() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As VBIncrementalGenerator = New VBIncrementalGenerator() Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(New IncrementalGeneratorWrapper(testGenerator)), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify() Assert.Equal(1, outputCompilation.SyntaxTrees.Count()) Assert.Equal(compilation, compilation) Assert.True(testGenerator._initialized) End Sub <Fact> Public Sub Prefer_Incremental_Generators() Dim parseOptions = TestOptions.Regular Dim compilation As Compilation = GetCompilation(parseOptions) Dim testGenerator As VBIncrementalAndSourceGenerator = New VBIncrementalAndSourceGenerator() Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(Of ISourceGenerator)(testGenerator), parseOptions:=parseOptions) Dim outputCompilation As Compilation = Nothing Dim outputDiagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, outputDiagnostics) outputDiagnostics.Verify() Assert.Equal(1, outputCompilation.SyntaxTrees.Count()) Assert.Equal(compilation, compilation) Assert.True(testGenerator._initialized) Assert.False(testGenerator._sourceInitialized) Assert.False(testGenerator._sourceExecuted) End Sub Shared Function GetCompilation(parseOptions As VisualBasicParseOptions, Optional source As String = "") As Compilation If (String.IsNullOrWhiteSpace(source)) Then source = " Public Class C End Class " End If Dim compilation As Compilation = CreateCompilation(source, options:=TestOptions.DebugDll, parseOptions:=parseOptions) compilation.VerifyDiagnostics() Assert.Single(compilation.SyntaxTrees) Return compilation End Function Shared Sub VerifyDiagnosticsWithOptions(generator As ISourceGenerator, compilation As Compilation, ParamArray expected As DiagnosticDescription()) compilation.VerifyDiagnostics() Assert.Single(compilation.SyntaxTrees) Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(generator), parseOptions:=TestOptions.Regular) Dim outputCompilation As Compilation = Nothing Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, diagnostics) outputCompilation.VerifyDiagnostics() diagnostics.Verify(expected) End Sub Shared Sub VerifyDiagnosticsWithSource(source As String, diag As Diagnostic, location As TextSpan, ParamArray expected As DiagnosticDescription()) Dim parseOptions = TestOptions.Regular source = source.Replace(Environment.NewLine, vbCrLf) Dim compilation As Compilation = CreateCompilation(source) compilation.VerifyDiagnostics() Assert.Single(compilation.SyntaxTrees) Dim gen As ISourceGenerator = New CallbackGenerator(Sub(c) End Sub, Sub(c) If location.IsEmpty Then c.ReportDiagnostic(diag) Else c.ReportDiagnostic(diag.WithLocation(CodeAnalysis.Location.Create(c.Compilation.SyntaxTrees.First(), location))) End If End Sub) Dim driver As GeneratorDriver = VisualBasicGeneratorDriver.Create(ImmutableArray.Create(gen), parseOptions:=TestOptions.Regular) Dim outputCompilation As Compilation = Nothing Dim diagnostics As ImmutableArray(Of Diagnostic) = Nothing driver.RunGeneratorsAndUpdateCompilation(compilation, outputCompilation, diagnostics) outputCompilation.VerifyDiagnostics() diagnostics.Verify(expected) End Sub End Class <Generator(LanguageNames.VisualBasic)> Friend Class VBGenerator Implements ISourceGenerator Public _receiver As Receiver = New Receiver() Public Sub Initialize(context As GeneratorInitializationContext) Implements ISourceGenerator.Initialize context.RegisterForSyntaxNotifications(Function() _receiver) End Sub Public Sub Execute(context As GeneratorExecutionContext) Implements ISourceGenerator.Execute context.AddSource("source.vb", " Public Class D End Class ") End Sub Class Receiver Implements ISyntaxReceiver Public _throw As Boolean Public _nodes As List(Of SyntaxNode) = New List(Of SyntaxNode)() Public Sub OnVisitSyntaxNode(syntaxNode As SyntaxNode) Implements ISyntaxReceiver.OnVisitSyntaxNode If (_throw) Then Throw New Exception("Syntax Walk") End If _nodes.Add(syntaxNode) End Sub End Class End Class <Generator(LanguageNames.VisualBasic)> Friend Class VBIncrementalGenerator Implements IIncrementalGenerator Public _initialized As Boolean Public Sub Initialize(context As IncrementalGeneratorInitializationContext) Implements IIncrementalGenerator.Initialize _initialized = True End Sub End Class <Generator(LanguageNames.VisualBasic)> Friend Class VBIncrementalAndSourceGenerator Implements IIncrementalGenerator Implements ISourceGenerator Public _initialized As Boolean Public _sourceInitialized As Boolean Public _sourceExecuted As Boolean Public Sub Initialize(context As IncrementalGeneratorInitializationContext) Implements IIncrementalGenerator.Initialize _initialized = True End Sub Public Sub Initialize(context As GeneratorInitializationContext) Implements ISourceGenerator.Initialize _sourceInitialized = True End Sub Public Sub Execute(context As GeneratorExecutionContext) Implements ISourceGenerator.Execute _sourceExecuted = True End Sub End Class End Namespace
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Tools/ExternalAccess/FSharp/Internal/Editor/FSharpContentTypeLanguageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.VisualStudio.Utilities; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor { [ExportContentTypeLanguageService(FSharpContentTypeNames.FSharpContentType, LanguageNames.FSharp), Shared] internal class FSharpContentTypeLanguageService : IContentTypeLanguageService { private readonly IContentTypeRegistryService _contentTypeRegistry; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpContentTypeLanguageService(IContentTypeRegistryService contentTypeRegistry) { _contentTypeRegistry = contentTypeRegistry; } public IContentType GetDefaultContentType() { return _contentTypeRegistry.GetContentType(FSharpContentTypeNames.FSharpContentType); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Editor; using Microsoft.VisualStudio.Utilities; using Microsoft.CodeAnalysis.ExternalAccess.FSharp.Editor; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.ExternalAccess.FSharp.Internal.Editor { [ExportContentTypeLanguageService(FSharpContentTypeNames.FSharpContentType, LanguageNames.FSharp), Shared] internal class FSharpContentTypeLanguageService : IContentTypeLanguageService { private readonly IContentTypeRegistryService _contentTypeRegistry; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public FSharpContentTypeLanguageService(IContentTypeRegistryService contentTypeRegistry) { _contentTypeRegistry = contentTypeRegistry; } public IContentType GetDefaultContentType() { return _contentTypeRegistry.GetContentType(FSharpContentTypeNames.FSharpContentType); } } }
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Compilers/Core/Portable/Symbols/ILocalSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a local variable in method body. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface ILocalSymbol : ISymbol { /// <summary> /// Gets the type of this local variable. /// </summary> ITypeSymbol Type { get; } /// <summary> /// Gets the top-level nullability of this local variable. /// </summary> NullableAnnotation NullableAnnotation { get; } /// <summary> /// Returns true if this local variable was declared as "const" (i.e. is a constant declaration). /// Also returns true for an enum member. /// </summary> bool IsConst { get; } /// <summary> /// Returns true if this local is a ref local or a ref readonly local. /// Use <see cref="RefKind"/> to get more detailed information. /// </summary> bool IsRef { get; } /// <summary> /// Whether the variable is a ref or ref readonly local. /// </summary> RefKind RefKind { get; } /// <summary> /// Returns false if the local variable wasn't declared as "const", or constant value was omitted or erroneous. /// True otherwise. /// </summary> bool HasConstantValue { get; } /// <summary> /// Gets the constant value of this local variable. /// </summary> object? ConstantValue { get; } /// <summary> /// Returns true if this local variable is function return variable whose name is the function's name, /// whose type is the return type of the function and whose initial value is the default of its type. /// </summary> /// <remarks> /// Is always false for the C# local variable /// </remarks> bool IsFunctionValue { get; } /// <summary> /// Returns true if the local variable is declared with fixed-pointer-initializer (in unsafe context). /// </summary> bool IsFixed { 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.CodeAnalysis { /// <summary> /// Represents a local variable in method body. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface ILocalSymbol : ISymbol { /// <summary> /// Gets the type of this local variable. /// </summary> ITypeSymbol Type { get; } /// <summary> /// Gets the top-level nullability of this local variable. /// </summary> NullableAnnotation NullableAnnotation { get; } /// <summary> /// Returns true if this local variable was declared as "const" (i.e. is a constant declaration). /// Also returns true for an enum member. /// </summary> bool IsConst { get; } /// <summary> /// Returns true if this local is a ref local or a ref readonly local. /// Use <see cref="RefKind"/> to get more detailed information. /// </summary> bool IsRef { get; } /// <summary> /// Whether the variable is a ref or ref readonly local. /// </summary> RefKind RefKind { get; } /// <summary> /// Returns false if the local variable wasn't declared as "const", or constant value was omitted or erroneous. /// True otherwise. /// </summary> bool HasConstantValue { get; } /// <summary> /// Gets the constant value of this local variable. /// </summary> object? ConstantValue { get; } /// <summary> /// Returns true if this local variable is function return variable whose name is the function's name, /// whose type is the return type of the function and whose initial value is the default of its type. /// </summary> /// <remarks> /// Is always false for the C# local variable /// </remarks> bool IsFunctionValue { get; } /// <summary> /// Returns true if the local variable is declared with fixed-pointer-initializer (in unsafe context). /// </summary> bool IsFixed { get; } } }
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/LanguageServices/CSharpSyntaxKindsServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { [ExportLanguageServiceFactory(typeof(ISyntaxKindsService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxKindsServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSyntaxKindsServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => CSharpSyntaxKindsService.Instance; private sealed class CSharpSyntaxKindsService : CSharpSyntaxKinds, ISyntaxKindsService { public static new readonly CSharpSyntaxKindsService Instance = new(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Composition; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.LanguageServices; namespace Microsoft.CodeAnalysis.CSharp.LanguageServices { [ExportLanguageServiceFactory(typeof(ISyntaxKindsService), LanguageNames.CSharp), Shared] internal class CSharpSyntaxKindsServiceFactory : ILanguageServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpSyntaxKindsServiceFactory() { } public ILanguageService CreateLanguageService(HostLanguageServices languageServices) => CSharpSyntaxKindsService.Instance; private sealed class CSharpSyntaxKindsService : CSharpSyntaxKinds, ISyntaxKindsService { public static new readonly CSharpSyntaxKindsService Instance = new(); } } }
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/EditorFeatures/VisualBasicTest/Utils.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports System.Text Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests Friend Module Utils Friend Function ParseCode(code As String) As SyntaxTree Dim text = SourceText.From(code) Return SyntaxFactory.ParseSyntaxTree(text) End Function Friend Function StringFromLines(ParamArray lines As String()) As String Return String.Join(Environment.NewLine, lines) End Function Friend Function ParseLines(ParamArray lines As String()) As SyntaxTree Dim code = StringFromLines(lines) Return ParseCode(code) End Function Friend Function ParseExpression(expr As String) As SyntaxTree Dim format = "Class C1 " & vbCrLf & " Sub S1()" & vbCrLf & " Dim x = {0}" & vbCrLf & " End Sub" & vbCrLf & "End Class" Dim code = String.Format(format, expr) Return ParseCode(code) End Function Friend Function ParseStatement(statement As String) As SyntaxTree Dim format = StringFromLines( "Class C1", " Sub S1()", " {0}", " End Sub", "End Class") Dim code = String.Format(format, statement) Return ParseCode(code) End Function ''' <summary> ''' DFS search to find the first node of a given type. ''' </summary> <Extension()> Friend Function FindFirstNodeOfType(Of T As SyntaxNode)(node As SyntaxNode) As T If TypeOf (node) Is T Then Return CType(node, T) End If For Each child In node.ChildNodesAndTokens() If child.IsNode Then Dim foundNode = child.AsNode().FindFirstNodeOfType(Of T)() If foundNode IsNot Nothing Then Return foundNode End If End If Next Return Nothing End Function <Extension()> Friend Function DigToNthNodeOfType(Of T As SyntaxNode)(node As SyntaxNode, index As Integer) As T Return node.ChildNodesAndTokens().Where(Function(n) n.IsNode). Select(Function(n) n.AsNode()). OfType(Of T).ElementAt(index) End Function <Extension()> Friend Function DigToFirstNodeOfType(Of T As SyntaxNode)(node As SyntaxNode) As T Return node.ChildNodesAndTokens().Where(Function(n) n.IsNode). Select(Function(n) n.AsNode()). OfType(Of T).First() End Function <Extension()> Friend Function DigToFirstNodeOfType(Of T As SyntaxNode)(syntaxTree As SyntaxTree) As T Return syntaxTree.GetRoot().DigToFirstNodeOfType(Of T)() End Function <Extension()> Friend Function DigToLastNodeOfType(Of T As SyntaxNode)(node As SyntaxNode) As T Return node.ChildNodesAndTokens().Where(Function(n) n.IsNode). Select(Function(n) n.AsNode()). OfType(Of T).Last() End Function <Extension()> Friend Function DigToFirstTypeBlock(syntaxTree As SyntaxTree) As TypeBlockSyntax Return syntaxTree.GetRoot().ChildNodesAndTokens().Where(Function(n) n.IsNode). Select(Function(n) n.AsNode()). OfType(Of TypeBlockSyntax).First() End Function <Extension()> Friend Function DigToFirstNamespace(syntaxTree As SyntaxTree) As NamespaceBlockSyntax Return syntaxTree.GetRoot().ChildNodesAndTokens().Where(Function(n) n.IsNode). Select(Function(n) n.AsNode()). OfType(Of NamespaceBlockSyntax).First() End Function Friend Class TreeNodePair(Of T As SyntaxNode) Private ReadOnly _tree As SyntaxTree Private ReadOnly _node As T Public Sub New(syntaxTree As SyntaxTree, node As T) #If Not CODE_STYLE Then Contract.ThrowIfNull(syntaxTree) Contract.ThrowIfNull(node) #End If _tree = syntaxTree _node = node End Sub Public ReadOnly Property Tree As SyntaxTree Get Return _tree End Get End Property Public ReadOnly Property Node As T Get Return _node End Get End Property End Class Friend Class TreeNodePair Friend Shared Function Create(Of T As SyntaxNode)(syntaxTree As SyntaxTree, node As T) As TreeNodePair(Of T) Return New TreeNodePair(Of T)(syntaxTree, node) End Function End Class Private Function SplitIntoLines( text As String, separator As String, Optional removeLeadingLineBreaks As Boolean = True, Optional removeTrailingLineBreaks As Boolean = True) As IEnumerable(Of String) Dim lines = text.Split({separator}, StringSplitOptions.None).ToList() If removeLeadingLineBreaks Then While lines.Count > 0 If lines(0).Length = 0 Then lines.RemoveAt(0) Else Exit While End If End While End If If removeTrailingLineBreaks Then For i = lines.Count - 1 To 0 Step -1 If lines(i).Length = 0 Then lines.RemoveAt(i) Else Exit For End If Next End If Return lines End Function Private Function SurroundAndJoinLines( lines As IEnumerable(Of String), Optional leading As String = Nothing, Optional trailing As String = Nothing) As String Dim builder As New StringBuilder For Each line In lines If Not String.IsNullOrWhiteSpace(line) Then builder.Append(leading) End If builder.Append(line) builder.Append(trailing) Next Return builder.ToString() End Function <Extension()> Friend Function ConvertTestSourceTag(testSource As XElement) As String ' Line breaks in XML values are represented as line feeds. Dim lines = SplitIntoLines(testSource.NormalizedValue, vbCrLf) Dim importStatements = "Imports System" & vbCrLf & "Imports System.Collections.Generic" & vbCrLf & "Imports System.Linq" Select Case testSource.Name Case "ClassDeclaration" Return importStatements & vbCrLf & "Class C1" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & "End Class" Case "StructureDeclaration" Return importStatements & vbCrLf & "Structure S" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & "End Structure" Case "NamespaceDeclaration" Return importStatements & vbCrLf & "Namespace Roslyn" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & "End Namespace" Case "InterfaceDeclaration" Return importStatements & vbCrLf & "Interface IInterface" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & "End Interface" Case "EnumDeclaration" Return importStatements & vbCrLf & "Enum Goo" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & "End Enum" Case "ModuleDeclaration" Return importStatements & vbCrLf & "Module M1" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & "End Module" Case "MethodBody" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Sub Method()" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Sub" & vbCrLf & "End Class" Case "SharedMethodBody" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Shared Sub Method()" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Sub" & vbCrLf & "End Class" Case "PropertyGetter" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " ReadOnly Property P As Integer" & vbCrLf & " Get" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Get" & vbCrLf & " End Property" & vbCrLf & "End Class" Case "PropertyDeclaration" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Public Property P As String " & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Property" & vbCrLf & "End Class" Case "SharedPropertyGetter" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Shared ReadOnly Property P As Integer" & vbCrLf & " Get" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Get" & vbCrLf & " End Property" & vbCrLf & "End Class" Case "CustomEventDeclaration" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Custom Event TestEvent As EventHandler" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Event" & vbCrLf & "End Class" Case "EventAddHandler" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Custom Event TestEvent As EventHandler" & vbCrLf & " AddHandler(value As EventHandler)" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End AddHandler" & vbCrLf & " RemoveHandler(value As EventHandler)" & vbCrLf & " End RemoveHandler" & vbCrLf & " RaiseEvent(sender As Object, e As EventArgs)" & vbCrLf & " End RaiseEvent" & vbCrLf & " End Event" & vbCrLf & "End Class" Case "SharedEventAddHandler" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Shared Custom Event TestEvent As EventHandler" & vbCrLf & " AddHandler(value As EventHandler)" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End AddHandler" & vbCrLf & " RemoveHandler(value As EventHandler)" & vbCrLf & " End RemoveHandler" & vbCrLf & " RaiseEvent(sender As Object, e As EventArgs)" & vbCrLf & " End RaiseEvent" & vbCrLf & " End Event" & vbCrLf & "End Class" Case "ModuleMethodBody" Return importStatements & vbCrLf & "Module M1" & vbCrLf & " Sub Method()" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Sub" & vbCrLf & "End Module" Case "StructureMethodBody" Return importStatements & vbCrLf & "Structure S" & vbCrLf & " Sub Method()" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Sub" & vbCrLf & "End Structure" Case "File" Return testSource.NormalizedValue Case Else Throw New ArgumentException("Unexpected testSource XML tag.", NameOf(testSource)) End Select End Function End Module End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Runtime.CompilerServices Imports System.Text Imports Microsoft.CodeAnalysis.Editor.UnitTests.Extensions Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests Friend Module Utils Friend Function ParseCode(code As String) As SyntaxTree Dim text = SourceText.From(code) Return SyntaxFactory.ParseSyntaxTree(text) End Function Friend Function StringFromLines(ParamArray lines As String()) As String Return String.Join(Environment.NewLine, lines) End Function Friend Function ParseLines(ParamArray lines As String()) As SyntaxTree Dim code = StringFromLines(lines) Return ParseCode(code) End Function Friend Function ParseExpression(expr As String) As SyntaxTree Dim format = "Class C1 " & vbCrLf & " Sub S1()" & vbCrLf & " Dim x = {0}" & vbCrLf & " End Sub" & vbCrLf & "End Class" Dim code = String.Format(format, expr) Return ParseCode(code) End Function Friend Function ParseStatement(statement As String) As SyntaxTree Dim format = StringFromLines( "Class C1", " Sub S1()", " {0}", " End Sub", "End Class") Dim code = String.Format(format, statement) Return ParseCode(code) End Function ''' <summary> ''' DFS search to find the first node of a given type. ''' </summary> <Extension()> Friend Function FindFirstNodeOfType(Of T As SyntaxNode)(node As SyntaxNode) As T If TypeOf (node) Is T Then Return CType(node, T) End If For Each child In node.ChildNodesAndTokens() If child.IsNode Then Dim foundNode = child.AsNode().FindFirstNodeOfType(Of T)() If foundNode IsNot Nothing Then Return foundNode End If End If Next Return Nothing End Function <Extension()> Friend Function DigToNthNodeOfType(Of T As SyntaxNode)(node As SyntaxNode, index As Integer) As T Return node.ChildNodesAndTokens().Where(Function(n) n.IsNode). Select(Function(n) n.AsNode()). OfType(Of T).ElementAt(index) End Function <Extension()> Friend Function DigToFirstNodeOfType(Of T As SyntaxNode)(node As SyntaxNode) As T Return node.ChildNodesAndTokens().Where(Function(n) n.IsNode). Select(Function(n) n.AsNode()). OfType(Of T).First() End Function <Extension()> Friend Function DigToFirstNodeOfType(Of T As SyntaxNode)(syntaxTree As SyntaxTree) As T Return syntaxTree.GetRoot().DigToFirstNodeOfType(Of T)() End Function <Extension()> Friend Function DigToLastNodeOfType(Of T As SyntaxNode)(node As SyntaxNode) As T Return node.ChildNodesAndTokens().Where(Function(n) n.IsNode). Select(Function(n) n.AsNode()). OfType(Of T).Last() End Function <Extension()> Friend Function DigToFirstTypeBlock(syntaxTree As SyntaxTree) As TypeBlockSyntax Return syntaxTree.GetRoot().ChildNodesAndTokens().Where(Function(n) n.IsNode). Select(Function(n) n.AsNode()). OfType(Of TypeBlockSyntax).First() End Function <Extension()> Friend Function DigToFirstNamespace(syntaxTree As SyntaxTree) As NamespaceBlockSyntax Return syntaxTree.GetRoot().ChildNodesAndTokens().Where(Function(n) n.IsNode). Select(Function(n) n.AsNode()). OfType(Of NamespaceBlockSyntax).First() End Function Friend Class TreeNodePair(Of T As SyntaxNode) Private ReadOnly _tree As SyntaxTree Private ReadOnly _node As T Public Sub New(syntaxTree As SyntaxTree, node As T) #If Not CODE_STYLE Then Contract.ThrowIfNull(syntaxTree) Contract.ThrowIfNull(node) #End If _tree = syntaxTree _node = node End Sub Public ReadOnly Property Tree As SyntaxTree Get Return _tree End Get End Property Public ReadOnly Property Node As T Get Return _node End Get End Property End Class Friend Class TreeNodePair Friend Shared Function Create(Of T As SyntaxNode)(syntaxTree As SyntaxTree, node As T) As TreeNodePair(Of T) Return New TreeNodePair(Of T)(syntaxTree, node) End Function End Class Private Function SplitIntoLines( text As String, separator As String, Optional removeLeadingLineBreaks As Boolean = True, Optional removeTrailingLineBreaks As Boolean = True) As IEnumerable(Of String) Dim lines = text.Split({separator}, StringSplitOptions.None).ToList() If removeLeadingLineBreaks Then While lines.Count > 0 If lines(0).Length = 0 Then lines.RemoveAt(0) Else Exit While End If End While End If If removeTrailingLineBreaks Then For i = lines.Count - 1 To 0 Step -1 If lines(i).Length = 0 Then lines.RemoveAt(i) Else Exit For End If Next End If Return lines End Function Private Function SurroundAndJoinLines( lines As IEnumerable(Of String), Optional leading As String = Nothing, Optional trailing As String = Nothing) As String Dim builder As New StringBuilder For Each line In lines If Not String.IsNullOrWhiteSpace(line) Then builder.Append(leading) End If builder.Append(line) builder.Append(trailing) Next Return builder.ToString() End Function <Extension()> Friend Function ConvertTestSourceTag(testSource As XElement) As String ' Line breaks in XML values are represented as line feeds. Dim lines = SplitIntoLines(testSource.NormalizedValue, vbCrLf) Dim importStatements = "Imports System" & vbCrLf & "Imports System.Collections.Generic" & vbCrLf & "Imports System.Linq" Select Case testSource.Name Case "ClassDeclaration" Return importStatements & vbCrLf & "Class C1" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & "End Class" Case "StructureDeclaration" Return importStatements & vbCrLf & "Structure S" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & "End Structure" Case "NamespaceDeclaration" Return importStatements & vbCrLf & "Namespace Roslyn" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & "End Namespace" Case "InterfaceDeclaration" Return importStatements & vbCrLf & "Interface IInterface" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & "End Interface" Case "EnumDeclaration" Return importStatements & vbCrLf & "Enum Goo" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & "End Enum" Case "ModuleDeclaration" Return importStatements & vbCrLf & "Module M1" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & "End Module" Case "MethodBody" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Sub Method()" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Sub" & vbCrLf & "End Class" Case "SharedMethodBody" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Shared Sub Method()" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Sub" & vbCrLf & "End Class" Case "PropertyGetter" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " ReadOnly Property P As Integer" & vbCrLf & " Get" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Get" & vbCrLf & " End Property" & vbCrLf & "End Class" Case "PropertyDeclaration" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Public Property P As String " & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Property" & vbCrLf & "End Class" Case "SharedPropertyGetter" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Shared ReadOnly Property P As Integer" & vbCrLf & " Get" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Get" & vbCrLf & " End Property" & vbCrLf & "End Class" Case "CustomEventDeclaration" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Custom Event TestEvent As EventHandler" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Event" & vbCrLf & "End Class" Case "EventAddHandler" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Custom Event TestEvent As EventHandler" & vbCrLf & " AddHandler(value As EventHandler)" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End AddHandler" & vbCrLf & " RemoveHandler(value As EventHandler)" & vbCrLf & " End RemoveHandler" & vbCrLf & " RaiseEvent(sender As Object, e As EventArgs)" & vbCrLf & " End RaiseEvent" & vbCrLf & " End Event" & vbCrLf & "End Class" Case "SharedEventAddHandler" Return importStatements & vbCrLf & "Class C1" & vbCrLf & " Shared Custom Event TestEvent As EventHandler" & vbCrLf & " AddHandler(value As EventHandler)" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End AddHandler" & vbCrLf & " RemoveHandler(value As EventHandler)" & vbCrLf & " End RemoveHandler" & vbCrLf & " RaiseEvent(sender As Object, e As EventArgs)" & vbCrLf & " End RaiseEvent" & vbCrLf & " End Event" & vbCrLf & "End Class" Case "ModuleMethodBody" Return importStatements & vbCrLf & "Module M1" & vbCrLf & " Sub Method()" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Sub" & vbCrLf & "End Module" Case "StructureMethodBody" Return importStatements & vbCrLf & "Structure S" & vbCrLf & " Sub Method()" & vbCrLf & SurroundAndJoinLines(lines, " ", vbCrLf) & " End Sub" & vbCrLf & "End Structure" Case "File" Return testSource.NormalizedValue Case Else Throw New ArgumentException("Unexpected testSource XML tag.", NameOf(testSource)) End Select End Function End Module End Namespace
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/PropertyKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class PropertyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public PropertyKeywordRecommender() : base(SyntaxKind.PropertyKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsMemberAttributeContext(SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, 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.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class PropertyKeywordRecommender : AbstractSyntacticSingleKeywordRecommender { public PropertyKeywordRecommender() : base(SyntaxKind.PropertyKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) => context.IsMemberAttributeContext(SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, cancellationToken); } }
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/VisualStudio/Core/Def/ValueTracking/EmptyTreeViewItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class EmptyTreeViewItem : TreeViewItemBase { public static EmptyTreeViewItem Instance { get; } = new(); private EmptyTreeViewItem() { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.VisualStudio.LanguageServices.ValueTracking { internal class EmptyTreeViewItem : TreeViewItemBase { public static EmptyTreeViewItem Instance { get; } = new(); private EmptyTreeViewItem() { } } }
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Features/Core/Portable/ImplementAbstractClass/AbstractImplementAbstractClassCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ImplementAbstractClass { internal abstract class AbstractImplementAbstractClassCodeFixProvider<TClassNode> : CodeFixProvider where TClassNode : SyntaxNode { public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; protected AbstractImplementAbstractClassCodeFixProvider(string diagnosticId) => FixableDiagnosticIds = ImmutableArray.Create(diagnosticId); protected abstract SyntaxToken GetClassIdentifier(TClassNode classNode); public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; var document = context.Document; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(context.Span.Start); if (!token.Span.IntersectsWith(context.Span)) return; var classNode = token.Parent.GetAncestorOrThis<TClassNode>(); if (classNode == null) return; var data = await ImplementAbstractClassData.TryGetDataAsync( document, classNode, GetClassIdentifier(classNode), cancellationToken).ConfigureAwait(false); if (data == null) return; var abstractClassType = data.AbstractClassType; var id = GetCodeActionId(abstractClassType.ContainingAssembly.Name, abstractClassType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); context.RegisterCodeFix( new MyCodeAction( FeaturesResources.Implement_abstract_class, c => data.ImplementAbstractClassAsync(throughMember: null, canDelegateAllMembers: null, c), id), context.Diagnostics); foreach (var (through, canDelegateAllMembers) in data.GetDelegatableMembers()) { id = GetCodeActionId( abstractClassType.ContainingAssembly.Name, abstractClassType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), through.Name); context.RegisterCodeFix( new MyCodeAction( string.Format(FeaturesResources.Implement_through_0, through.Name), c => data.ImplementAbstractClassAsync(through, canDelegateAllMembers, c), id), context.Diagnostics); } } private static string GetCodeActionId(string assemblyName, string abstractTypeFullyQualifiedName, string through = "") => FeaturesResources.Implement_abstract_class + ";" + assemblyName + ";" + abstractTypeFullyQualifiedName + ";" + through; private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string id) : base(title, createChangedDocument, id) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.ImplementAbstractClass { internal abstract class AbstractImplementAbstractClassCodeFixProvider<TClassNode> : CodeFixProvider where TClassNode : SyntaxNode { public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } public sealed override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; protected AbstractImplementAbstractClassCodeFixProvider(string diagnosticId) => FixableDiagnosticIds = ImmutableArray.Create(diagnosticId); protected abstract SyntaxToken GetClassIdentifier(TClassNode classNode); public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { var cancellationToken = context.CancellationToken; var document = context.Document; var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var token = root.FindToken(context.Span.Start); if (!token.Span.IntersectsWith(context.Span)) return; var classNode = token.Parent.GetAncestorOrThis<TClassNode>(); if (classNode == null) return; var data = await ImplementAbstractClassData.TryGetDataAsync( document, classNode, GetClassIdentifier(classNode), cancellationToken).ConfigureAwait(false); if (data == null) return; var abstractClassType = data.AbstractClassType; var id = GetCodeActionId(abstractClassType.ContainingAssembly.Name, abstractClassType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); context.RegisterCodeFix( new MyCodeAction( FeaturesResources.Implement_abstract_class, c => data.ImplementAbstractClassAsync(throughMember: null, canDelegateAllMembers: null, c), id), context.Diagnostics); foreach (var (through, canDelegateAllMembers) in data.GetDelegatableMembers()) { id = GetCodeActionId( abstractClassType.ContainingAssembly.Name, abstractClassType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), through.Name); context.RegisterCodeFix( new MyCodeAction( string.Format(FeaturesResources.Implement_through_0, through.Name), c => data.ImplementAbstractClassAsync(through, canDelegateAllMembers, c), id), context.Diagnostics); } } private static string GetCodeActionId(string assemblyName, string abstractTypeFullyQualifiedName, string through = "") => FeaturesResources.Implement_abstract_class + ";" + assemblyName + ";" + abstractTypeFullyQualifiedName + ";" + through; private class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument, string id) : base(title, createChangedDocument, id) { } } } }
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/ExpressionEvaluator/Core/Source/ResultProvider/Portable/xlf/Resources.it.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="it" original="../Resources.resx"> <body> <trans-unit id="DynamicView"> <source>Dynamic View</source> <target state="translated">Visualizzazione dinamica</target> <note>IDynamicMetaObjectProvider and System.__ComObject expansion</note> </trans-unit> <trans-unit id="DynamicViewNotDynamic"> <source>Only COM or Dynamic objects can have Dynamic View</source> <target state="translated">La Visualizzazione dinamica è consentita solo per oggetti COM o dinamici</target> <note>Cannot use "dynamic" format specifier on a non-dynamic type</note> </trans-unit> <trans-unit id="DynamicViewValueWarning"> <source>Expanding the Dynamic View will get the dynamic members for the object</source> <target state="translated">Se si espande la Visualizzazione dinamica, si otterranno i membri dinamici per l'oggetto</target> <note>Warning reported in Dynamic View value</note> </trans-unit> <trans-unit id="ErrorName"> <source>Error</source> <target state="translated">Errore</target> <note>Error result name</note> </trans-unit> <trans-unit id="ExceptionThrown"> <source>'{0}' threw an exception of type '{1}'</source> <target state="translated">'{0}' ha generato un'eccezione di tipo '{1}'</target> <note>Threw an exception while evaluating a value.</note> </trans-unit> <trans-unit id="HostValueNotFound"> <source>Cannot provide the value: host value not found</source> <target state="translated">Non è possibile specificare il valore: il valore host non è stato trovato</target> <note /> </trans-unit> <trans-unit id="InvalidPointerDereference"> <source>Cannot dereference '{0}'. The pointer is not valid.</source> <target state="translated">Non è possibile dereferenziare '{0}'. Il puntatore non è valido.</target> <note>Invalid pointer dereference</note> </trans-unit> <trans-unit id="NativeView"> <source>Native View</source> <target state="translated">Visualizzazione nativa</target> <note>Native COM object expansion</note> </trans-unit> <trans-unit id="NativeViewNotNativeDebugging"> <source>To inspect the native object, enable native code debugging.</source> <target state="translated">Per ispezionare l'oggetto nativo, abilitare il debug del codice nativo.</target> <note>Display value of Native View node when native debugging is not enabled</note> </trans-unit> <trans-unit id="NonPublicMembers"> <source>Non-Public members</source> <target state="translated">Membri non pubblici</target> <note>Non-public type members</note> </trans-unit> <trans-unit id="RawView"> <source>Raw View</source> <target state="translated">Visualizzazione non elaborata</target> <note>DebuggerTypeProxy "Raw View"</note> </trans-unit> <trans-unit id="ResultsView"> <source>Results View</source> <target state="translated">Visualizzazione risultati</target> <note>IEnumerable results expansion</note> </trans-unit> <trans-unit id="ResultsViewNoSystemCore"> <source>Results View requires System.Core.dll to be referenced</source> <target state="translated">La Visualizzazione risultati richiede il riferimento a System.Core.dll</target> <note>"results" format specifier requires System.Core.dll</note> </trans-unit> <trans-unit id="ResultsViewNotEnumerable"> <source>Only Enumerable types can have Results View</source> <target state="translated">Solo i tipi Enumerable possono disporre di una Visualizzazione risultati</target> <note>Cannot use "results" format specifier on non-enumerable type</note> </trans-unit> <trans-unit id="ResultsViewValueWarning"> <source>Expanding the Results View will enumerate the IEnumerable</source> <target state="translated">L'espansione della Visualizzazione risultati enumera IEnumerable</target> <note>Warning reported in Results View value</note> </trans-unit> <trans-unit id="SharedMembers"> <source>Shared members</source> <target state="translated">Membri condivisi</target> <note>Shared type members (VB only)</note> </trans-unit> <trans-unit id="StaticMembers"> <source>Static members</source> <target state="translated">Membri statici</target> <note>Static type members (C# only)</note> </trans-unit> <trans-unit id="TypeVariablesName"> <source>Type variables</source> <target state="translated">Variabili di tipo</target> <note>Type variables result name</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="it" original="../Resources.resx"> <body> <trans-unit id="DynamicView"> <source>Dynamic View</source> <target state="translated">Visualizzazione dinamica</target> <note>IDynamicMetaObjectProvider and System.__ComObject expansion</note> </trans-unit> <trans-unit id="DynamicViewNotDynamic"> <source>Only COM or Dynamic objects can have Dynamic View</source> <target state="translated">La Visualizzazione dinamica è consentita solo per oggetti COM o dinamici</target> <note>Cannot use "dynamic" format specifier on a non-dynamic type</note> </trans-unit> <trans-unit id="DynamicViewValueWarning"> <source>Expanding the Dynamic View will get the dynamic members for the object</source> <target state="translated">Se si espande la Visualizzazione dinamica, si otterranno i membri dinamici per l'oggetto</target> <note>Warning reported in Dynamic View value</note> </trans-unit> <trans-unit id="ErrorName"> <source>Error</source> <target state="translated">Errore</target> <note>Error result name</note> </trans-unit> <trans-unit id="ExceptionThrown"> <source>'{0}' threw an exception of type '{1}'</source> <target state="translated">'{0}' ha generato un'eccezione di tipo '{1}'</target> <note>Threw an exception while evaluating a value.</note> </trans-unit> <trans-unit id="HostValueNotFound"> <source>Cannot provide the value: host value not found</source> <target state="translated">Non è possibile specificare il valore: il valore host non è stato trovato</target> <note /> </trans-unit> <trans-unit id="InvalidPointerDereference"> <source>Cannot dereference '{0}'. The pointer is not valid.</source> <target state="translated">Non è possibile dereferenziare '{0}'. Il puntatore non è valido.</target> <note>Invalid pointer dereference</note> </trans-unit> <trans-unit id="NativeView"> <source>Native View</source> <target state="translated">Visualizzazione nativa</target> <note>Native COM object expansion</note> </trans-unit> <trans-unit id="NativeViewNotNativeDebugging"> <source>To inspect the native object, enable native code debugging.</source> <target state="translated">Per ispezionare l'oggetto nativo, abilitare il debug del codice nativo.</target> <note>Display value of Native View node when native debugging is not enabled</note> </trans-unit> <trans-unit id="NonPublicMembers"> <source>Non-Public members</source> <target state="translated">Membri non pubblici</target> <note>Non-public type members</note> </trans-unit> <trans-unit id="RawView"> <source>Raw View</source> <target state="translated">Visualizzazione non elaborata</target> <note>DebuggerTypeProxy "Raw View"</note> </trans-unit> <trans-unit id="ResultsView"> <source>Results View</source> <target state="translated">Visualizzazione risultati</target> <note>IEnumerable results expansion</note> </trans-unit> <trans-unit id="ResultsViewNoSystemCore"> <source>Results View requires System.Core.dll to be referenced</source> <target state="translated">La Visualizzazione risultati richiede il riferimento a System.Core.dll</target> <note>"results" format specifier requires System.Core.dll</note> </trans-unit> <trans-unit id="ResultsViewNotEnumerable"> <source>Only Enumerable types can have Results View</source> <target state="translated">Solo i tipi Enumerable possono disporre di una Visualizzazione risultati</target> <note>Cannot use "results" format specifier on non-enumerable type</note> </trans-unit> <trans-unit id="ResultsViewValueWarning"> <source>Expanding the Results View will enumerate the IEnumerable</source> <target state="translated">L'espansione della Visualizzazione risultati enumera IEnumerable</target> <note>Warning reported in Results View value</note> </trans-unit> <trans-unit id="SharedMembers"> <source>Shared members</source> <target state="translated">Membri condivisi</target> <note>Shared type members (VB only)</note> </trans-unit> <trans-unit id="StaticMembers"> <source>Static members</source> <target state="translated">Membri statici</target> <note>Static type members (C# only)</note> </trans-unit> <trans-unit id="TypeVariablesName"> <source>Type variables</source> <target state="translated">Variabili di tipo</target> <note>Type variables result name</note> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Compilers/Test/Resources/Core/MetadataTests/Invalid/ClassLayout.il
// Microsoft (R) .NET Framework IL Disassembler. Version 4.0.30319.17626 // Metadata version: v4.0.30319 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly b { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows. .hash algorithm 0x00008004 .ver 0:0:0:0 } .module b.dll // MVID: {9602E904-A118-45CA-A74A-37A00531EABC} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00800000 // =============== CLASS MEMBERS DECLARATION =================== .class public sequential ansi sealed beforefieldinit S1 extends [mscorlib]System.ValueType { .pack 0x1 // modified in binary editor to be 0xffff (ilasm doesn't allow 0xffff) .size 0xaaaaaaaa } // end of class S1 .class public explicit ansi sealed beforefieldinit S2 extends [mscorlib]System.ValueType { .pack 2 .size 0xbbbbbbbb // modified in binary editor to be 0xffffffff (ilasm writes 0 instead of 0xffffffff) } // end of class S2 .class public sequential ansi sealed beforefieldinit S3 extends [mscorlib]System.ValueType { .pack 2 .size 1 } // end of class S3 .class public sequential ansi sealed beforefieldinit S4 extends [mscorlib]System.ValueType { .pack 0 .size 0x12345678 } // end of class S4 .class public sequential ansi sealed beforefieldinit S5 extends [mscorlib]System.Object { } // end of class S5 // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** // WARNING: Created Win32 resource file b.res
// Microsoft (R) .NET Framework IL Disassembler. Version 4.0.30319.17626 // Metadata version: v4.0.30319 .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly b { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78 // ....T..WrapNonEx 63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 ) // ceptionThrows. .hash algorithm 0x00008004 .ver 0:0:0:0 } .module b.dll // MVID: {9602E904-A118-45CA-A74A-37A00531EABC} .imagebase 0x10000000 .file alignment 0x00000200 .stackreserve 0x00100000 .subsystem 0x0003 // WINDOWS_CUI .corflags 0x00000001 // ILONLY // Image base: 0x00800000 // =============== CLASS MEMBERS DECLARATION =================== .class public sequential ansi sealed beforefieldinit S1 extends [mscorlib]System.ValueType { .pack 0x1 // modified in binary editor to be 0xffff (ilasm doesn't allow 0xffff) .size 0xaaaaaaaa } // end of class S1 .class public explicit ansi sealed beforefieldinit S2 extends [mscorlib]System.ValueType { .pack 2 .size 0xbbbbbbbb // modified in binary editor to be 0xffffffff (ilasm writes 0 instead of 0xffffffff) } // end of class S2 .class public sequential ansi sealed beforefieldinit S3 extends [mscorlib]System.ValueType { .pack 2 .size 1 } // end of class S3 .class public sequential ansi sealed beforefieldinit S4 extends [mscorlib]System.ValueType { .pack 0 .size 0x12345678 } // end of class S4 .class public sequential ansi sealed beforefieldinit S5 extends [mscorlib]System.Object { } // end of class S5 // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** // WARNING: Created Win32 resource file b.res
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceDelegateMethodSymbol.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' This class represent a compiler generated method of a delegate type that is based upon source delegate or event delegate declaration. ''' </summary> Friend Class SourceDelegateMethodSymbol Inherits SourceMethodSymbol ' Parameters. Private _parameters As ImmutableArray(Of ParameterSymbol) ' Return type. Void for a Sub. Private ReadOnly _returnType As TypeSymbol Protected Sub New(delegateType As NamedTypeSymbol, syntax As VisualBasicSyntaxNode, binder As Binder, flags As SourceMemberFlags, returnType As TypeSymbol) MyBase.New(delegateType, flags, binder.GetSyntaxReference(syntax), delegateType.Locations) Debug.Assert(TypeOf syntax Is DelegateStatementSyntax OrElse TypeOf syntax Is EventStatementSyntax) Debug.Assert(returnType IsNot Nothing) _returnType = returnType End Sub Protected Sub InitializeParameters(parameters As ImmutableArray(Of ParameterSymbol)) Debug.Assert(_parameters.IsDefault) Debug.Assert(Not parameters.IsDefault) _parameters = parameters End Sub Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _returnType End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol) Get Return OverriddenMembersResult(Of MethodSymbol).Empty End Get End Property Friend Shared Sub MakeDelegateMembers(delegateType As NamedTypeSymbol, syntax As VisualBasicSyntaxNode, parameterListOpt As ParameterListSyntax, binder As Binder, <Out> ByRef constructor As MethodSymbol, <Out> ByRef beginInvoke As MethodSymbol, <Out> ByRef endInvoke As MethodSymbol, <Out> ByRef invoke As MethodSymbol, diagnostics As BindingDiagnosticBag) Debug.Assert(TypeOf syntax Is DelegateStatementSyntax OrElse TypeOf syntax Is EventStatementSyntax) Dim returnType As TypeSymbol = BindReturnType(syntax, binder, diagnostics) ' reuse types to avoid reporting duplicate errors if missing: Dim voidType = binder.GetSpecialType(SpecialType.System_Void, syntax, diagnostics) Dim iAsyncResultType = binder.GetSpecialType(SpecialType.System_IAsyncResult, syntax, diagnostics) Dim objectType = binder.GetSpecialType(SpecialType.System_Object, syntax, diagnostics) Dim intPtrType = binder.GetSpecialType(SpecialType.System_IntPtr, syntax, diagnostics) Dim asyncCallbackType = binder.GetSpecialType(SpecialType.System_AsyncCallback, syntax, diagnostics) ' A delegate has the following members: (see CLI spec 13.6) ' (1) a method named Invoke with the specified signature Dim invokeMethod = New InvokeMethod(delegateType, returnType, syntax, binder, parameterListOpt, diagnostics) invoke = invokeMethod ' (2) a constructor with argument types (object, System.IntPtr) constructor = New Constructor(delegateType, voidType, objectType, intPtrType, syntax, binder) ' If this is a winmd compilation we don't want to add the begin/endInvoke members to the symbol If delegateType.IsCompilationOutputWinMdObj() Then beginInvoke = Nothing endInvoke = Nothing Else ' (3) BeginInvoke beginInvoke = New BeginInvokeMethod(invokeMethod, iAsyncResultType, objectType, asyncCallbackType, syntax, binder) ' and (4) EndInvoke methods endInvoke = New EndInvokeMethod(invokeMethod, iAsyncResultType, syntax, binder) End If End Sub Private Shared Function BindReturnType(syntax As VisualBasicSyntaxNode, binder As Binder, diagnostics As BindingDiagnosticBag) As TypeSymbol If syntax.Kind = SyntaxKind.DelegateFunctionStatement Then Dim delegateSyntax = DirectCast(syntax, DelegateStatementSyntax) Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing If binder.OptionStrict = OptionStrict.On Then getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitProc ElseIf binder.OptionStrict = OptionStrict.Custom Then getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumed1_WRN_MissingAsClauseinFunction End If Dim asClause = DirectCast(delegateSyntax.AsClause, SimpleAsClauseSyntax) Return binder.DecodeIdentifierType(delegateSyntax.Identifier, asClause, getErrorInfo, diagnostics) Else Return binder.GetSpecialType(SpecialType.System_Void, syntax, diagnostics) End If End Function ''' <summary> ''' Returns true if this method is an extension method. ''' </summary> Public NotOverridable Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is external method. ''' </summary> ''' <value> ''' <c>true</c> if this instance is external method; otherwise, <c>false</c>. ''' </value> Public NotOverridable Overrides ReadOnly Property IsExternalMethod As Boolean Get Return True End Get End Property Public NotOverridable Overrides Function GetDllImportData() As DllImportData Return Nothing End Function Friend NotOverridable Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes Get Return Reflection.MethodImplAttributes.Runtime End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property ''' <summary> ''' Get the type parameters on this method. If the method has not generic, ''' returns an empty list. ''' </summary> Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return ImmutableArray(Of TypeParameterSymbol).Empty End Get End Property ''' <summary> ''' Gets a value indicating whether the symbol was generated by the compiler ''' rather than declared explicitly. ''' </summary> Public NotOverridable Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean Get Return Me.MethodKind = MethodKind.Constructor End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Return ImmutableArray(Of String).Empty End Function Protected NotOverridable Overrides Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) ' delegate methods don't inherit attributes from the delegate type, only parameters and return types do Return Nothing End Function Private NotInheritable Class Constructor Inherits SourceDelegateMethodSymbol Public Sub New(delegateType As NamedTypeSymbol, voidType As TypeSymbol, objectType As TypeSymbol, intPtrType As TypeSymbol, syntax As VisualBasicSyntaxNode, binder As Binder) MyBase.New(delegateType, syntax, binder, flags:=SourceMemberFlags.MethodKindConstructor Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.MethodIsSub, returnType:=voidType) InitializeParameters(ImmutableArray.Create(Of ParameterSymbol)( New SynthesizedParameterSymbol(Me, objectType, 0, False, StringConstants.DelegateConstructorInstanceParameterName), New SynthesizedParameterSymbol(Me, intPtrType, 1, False, StringConstants.DelegateConstructorMethodParameterName))) End Sub Public Overrides ReadOnly Property Name As String Get Return WellKnownMemberNames.InstanceConstructorName End Get End Property Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) ' Constructor doesn't have return type attributes Return Nothing End Function End Class Private NotInheritable Class InvokeMethod Inherits SourceDelegateMethodSymbol Public Sub New(delegateType As NamedTypeSymbol, returnType As TypeSymbol, syntax As VisualBasicSyntaxNode, binder As Binder, parameterListOpt As ParameterListSyntax, diagnostics As BindingDiagnosticBag) MyBase.New(delegateType, syntax, binder, flags:=SourceMemberFlags.MethodKindDelegateInvoke Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable Or If(returnType.SpecialType = SpecialType.System_Void, SourceMemberFlags.MethodIsSub, Nothing), returnType:=returnType) InitializeParameters(binder.DecodeParameterListOfDelegateDeclaration(Me, parameterListOpt, diagnostics)) End Sub Public Overrides ReadOnly Property Name As String Get Return WellKnownMemberNames.DelegateInvokeName End Get End Property End Class Private NotInheritable Class BeginInvokeMethod Inherits SourceDelegateMethodSymbol Public Sub New(invoke As InvokeMethod, iAsyncResultType As TypeSymbol, objectType As TypeSymbol, asyncCallbackType As TypeSymbol, syntax As VisualBasicSyntaxNode, binder As Binder) MyBase.New(invoke.ContainingType, syntax, binder, flags:=SourceMemberFlags.MethodKindOrdinary Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable, returnType:=iAsyncResultType) Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance() Dim ordinal As Integer = 0 For Each parameter In invoke.Parameters ' Delegate parameters cannot be optional in VB. ' In error cases where the parameter is specified optional in source, the parameter ' will not have a True .IsOptional. ' This is ensured by 'CheckDelegateParameterModifier' Debug.Assert(Not parameter.IsOptional) parameters.Add(New SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(DirectCast(parameter, SourceParameterSymbol), Me, ordinal)) ordinal += 1 Next parameters.Add(New SynthesizedParameterSymbol(Me, asyncCallbackType, ordinal, False, StringConstants.DelegateMethodCallbackParameterName)) ordinal += 1 parameters.Add(New SynthesizedParameterSymbol(Me, objectType, ordinal, False, StringConstants.DelegateMethodInstanceParameterName)) InitializeParameters(parameters.ToImmutableAndFree()) End Sub Public Overrides ReadOnly Property Name As String Get Return WellKnownMemberNames.DelegateBeginInvokeName End Get End Property Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) ' BeginInvoke doesn't have return type attributes Return Nothing End Function End Class Private NotInheritable Class EndInvokeMethod Inherits SourceDelegateMethodSymbol Public Sub New(invoke As InvokeMethod, iAsyncResultType As TypeSymbol, syntax As VisualBasicSyntaxNode, binder As Binder) MyBase.New(invoke.ContainingType, syntax, binder, flags:=SourceMemberFlags.MethodKindOrdinary Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable Or If(invoke.ReturnType.SpecialType = SpecialType.System_Void, SourceMemberFlags.MethodIsSub, Nothing), returnType:=invoke.ReturnType) Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance() Dim ordinal = 0 For Each parameter In invoke.Parameters ' Delegate parameters cannot be optional in VB. ' In error cases where the parameter is specified optional in source, the parameter ' will not have a True .IsOptional. ' This is ensured by 'CheckDelegateParameterModifier' Debug.Assert(Not parameter.IsOptional) If parameter.IsByRef Then parameters.Add(New SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(DirectCast(parameter, SourceParameterSymbol), Me, ordinal)) ordinal += 1 End If Next parameters.Add(New SynthesizedParameterSymbol(Me, iAsyncResultType, parameters.Count, False, StringConstants.DelegateMethodResultParameterName)) InitializeParameters(parameters.ToImmutableAndFree()) End Sub Public Overrides ReadOnly Property Name As String Get Return WellKnownMemberNames.DelegateEndInvokeName End Get End Property Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) ' EndInvoke doesn't have return type attributes Return Nothing End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Runtime.InteropServices Imports System.Threading Imports Microsoft.CodeAnalysis.PooledObjects Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports TypeKind = Microsoft.CodeAnalysis.TypeKind Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' This class represent a compiler generated method of a delegate type that is based upon source delegate or event delegate declaration. ''' </summary> Friend Class SourceDelegateMethodSymbol Inherits SourceMethodSymbol ' Parameters. Private _parameters As ImmutableArray(Of ParameterSymbol) ' Return type. Void for a Sub. Private ReadOnly _returnType As TypeSymbol Protected Sub New(delegateType As NamedTypeSymbol, syntax As VisualBasicSyntaxNode, binder As Binder, flags As SourceMemberFlags, returnType As TypeSymbol) MyBase.New(delegateType, flags, binder.GetSyntaxReference(syntax), delegateType.Locations) Debug.Assert(TypeOf syntax Is DelegateStatementSyntax OrElse TypeOf syntax Is EventStatementSyntax) Debug.Assert(returnType IsNot Nothing) _returnType = returnType End Sub Protected Sub InitializeParameters(parameters As ImmutableArray(Of ParameterSymbol)) Debug.Assert(_parameters.IsDefault) Debug.Assert(Not parameters.IsDefault) _parameters = parameters End Sub Public Overrides ReadOnly Property ReturnType As TypeSymbol Get Return _returnType End Get End Property Public Overrides ReadOnly Property Parameters As ImmutableArray(Of ParameterSymbol) Get Return _parameters End Get End Property Friend Overrides ReadOnly Property OverriddenMembers As OverriddenMembersResult(Of MethodSymbol) Get Return OverriddenMembersResult(Of MethodSymbol).Empty End Get End Property Friend Shared Sub MakeDelegateMembers(delegateType As NamedTypeSymbol, syntax As VisualBasicSyntaxNode, parameterListOpt As ParameterListSyntax, binder As Binder, <Out> ByRef constructor As MethodSymbol, <Out> ByRef beginInvoke As MethodSymbol, <Out> ByRef endInvoke As MethodSymbol, <Out> ByRef invoke As MethodSymbol, diagnostics As BindingDiagnosticBag) Debug.Assert(TypeOf syntax Is DelegateStatementSyntax OrElse TypeOf syntax Is EventStatementSyntax) Dim returnType As TypeSymbol = BindReturnType(syntax, binder, diagnostics) ' reuse types to avoid reporting duplicate errors if missing: Dim voidType = binder.GetSpecialType(SpecialType.System_Void, syntax, diagnostics) Dim iAsyncResultType = binder.GetSpecialType(SpecialType.System_IAsyncResult, syntax, diagnostics) Dim objectType = binder.GetSpecialType(SpecialType.System_Object, syntax, diagnostics) Dim intPtrType = binder.GetSpecialType(SpecialType.System_IntPtr, syntax, diagnostics) Dim asyncCallbackType = binder.GetSpecialType(SpecialType.System_AsyncCallback, syntax, diagnostics) ' A delegate has the following members: (see CLI spec 13.6) ' (1) a method named Invoke with the specified signature Dim invokeMethod = New InvokeMethod(delegateType, returnType, syntax, binder, parameterListOpt, diagnostics) invoke = invokeMethod ' (2) a constructor with argument types (object, System.IntPtr) constructor = New Constructor(delegateType, voidType, objectType, intPtrType, syntax, binder) ' If this is a winmd compilation we don't want to add the begin/endInvoke members to the symbol If delegateType.IsCompilationOutputWinMdObj() Then beginInvoke = Nothing endInvoke = Nothing Else ' (3) BeginInvoke beginInvoke = New BeginInvokeMethod(invokeMethod, iAsyncResultType, objectType, asyncCallbackType, syntax, binder) ' and (4) EndInvoke methods endInvoke = New EndInvokeMethod(invokeMethod, iAsyncResultType, syntax, binder) End If End Sub Private Shared Function BindReturnType(syntax As VisualBasicSyntaxNode, binder As Binder, diagnostics As BindingDiagnosticBag) As TypeSymbol If syntax.Kind = SyntaxKind.DelegateFunctionStatement Then Dim delegateSyntax = DirectCast(syntax, DelegateStatementSyntax) Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing If binder.OptionStrict = OptionStrict.On Then getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitProc ElseIf binder.OptionStrict = OptionStrict.Custom Then getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumed1_WRN_MissingAsClauseinFunction End If Dim asClause = DirectCast(delegateSyntax.AsClause, SimpleAsClauseSyntax) Return binder.DecodeIdentifierType(delegateSyntax.Identifier, asClause, getErrorInfo, diagnostics) Else Return binder.GetSpecialType(SpecialType.System_Void, syntax, diagnostics) End If End Function ''' <summary> ''' Returns true if this method is an extension method. ''' </summary> Public NotOverridable Overrides ReadOnly Property IsExtensionMethod As Boolean Get Return False End Get End Property Friend Overrides ReadOnly Property MayBeReducibleExtensionMethod As Boolean Get Return False End Get End Property ''' <summary> ''' Gets a value indicating whether this instance is external method. ''' </summary> ''' <value> ''' <c>true</c> if this instance is external method; otherwise, <c>false</c>. ''' </value> Public NotOverridable Overrides ReadOnly Property IsExternalMethod As Boolean Get Return True End Get End Property Public NotOverridable Overrides Function GetDllImportData() As DllImportData Return Nothing End Function Friend NotOverridable Overrides ReadOnly Property ImplementationAttributes As Reflection.MethodImplAttributes Get Return Reflection.MethodImplAttributes.Runtime End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get Return ImmutableArray(Of SyntaxReference).Empty End Get End Property ''' <summary> ''' Get the type parameters on this method. If the method has not generic, ''' returns an empty list. ''' </summary> Public Overrides ReadOnly Property TypeParameters As ImmutableArray(Of TypeParameterSymbol) Get Return ImmutableArray(Of TypeParameterSymbol).Empty End Get End Property ''' <summary> ''' Gets a value indicating whether the symbol was generated by the compiler ''' rather than declared explicitly. ''' </summary> Public NotOverridable Overrides ReadOnly Property IsImplicitlyDeclared As Boolean Get Return True End Get End Property Friend Overrides ReadOnly Property GenerateDebugInfoImpl As Boolean Get Return False End Get End Property Friend NotOverridable Overrides ReadOnly Property HasSpecialName As Boolean Get Return Me.MethodKind = MethodKind.Constructor End Get End Property Friend Overrides Function GetAppliedConditionalSymbols() As ImmutableArray(Of String) Return ImmutableArray(Of String).Empty End Function Protected NotOverridable Overrides Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) ' delegate methods don't inherit attributes from the delegate type, only parameters and return types do Return Nothing End Function Private NotInheritable Class Constructor Inherits SourceDelegateMethodSymbol Public Sub New(delegateType As NamedTypeSymbol, voidType As TypeSymbol, objectType As TypeSymbol, intPtrType As TypeSymbol, syntax As VisualBasicSyntaxNode, binder As Binder) MyBase.New(delegateType, syntax, binder, flags:=SourceMemberFlags.MethodKindConstructor Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.MethodIsSub, returnType:=voidType) InitializeParameters(ImmutableArray.Create(Of ParameterSymbol)( New SynthesizedParameterSymbol(Me, objectType, 0, False, StringConstants.DelegateConstructorInstanceParameterName), New SynthesizedParameterSymbol(Me, intPtrType, 1, False, StringConstants.DelegateConstructorMethodParameterName))) End Sub Public Overrides ReadOnly Property Name As String Get Return WellKnownMemberNames.InstanceConstructorName End Get End Property Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) ' Constructor doesn't have return type attributes Return Nothing End Function End Class Private NotInheritable Class InvokeMethod Inherits SourceDelegateMethodSymbol Public Sub New(delegateType As NamedTypeSymbol, returnType As TypeSymbol, syntax As VisualBasicSyntaxNode, binder As Binder, parameterListOpt As ParameterListSyntax, diagnostics As BindingDiagnosticBag) MyBase.New(delegateType, syntax, binder, flags:=SourceMemberFlags.MethodKindDelegateInvoke Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable Or If(returnType.SpecialType = SpecialType.System_Void, SourceMemberFlags.MethodIsSub, Nothing), returnType:=returnType) InitializeParameters(binder.DecodeParameterListOfDelegateDeclaration(Me, parameterListOpt, diagnostics)) End Sub Public Overrides ReadOnly Property Name As String Get Return WellKnownMemberNames.DelegateInvokeName End Get End Property End Class Private NotInheritable Class BeginInvokeMethod Inherits SourceDelegateMethodSymbol Public Sub New(invoke As InvokeMethod, iAsyncResultType As TypeSymbol, objectType As TypeSymbol, asyncCallbackType As TypeSymbol, syntax As VisualBasicSyntaxNode, binder As Binder) MyBase.New(invoke.ContainingType, syntax, binder, flags:=SourceMemberFlags.MethodKindOrdinary Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable, returnType:=iAsyncResultType) Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance() Dim ordinal As Integer = 0 For Each parameter In invoke.Parameters ' Delegate parameters cannot be optional in VB. ' In error cases where the parameter is specified optional in source, the parameter ' will not have a True .IsOptional. ' This is ensured by 'CheckDelegateParameterModifier' Debug.Assert(Not parameter.IsOptional) parameters.Add(New SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(DirectCast(parameter, SourceParameterSymbol), Me, ordinal)) ordinal += 1 Next parameters.Add(New SynthesizedParameterSymbol(Me, asyncCallbackType, ordinal, False, StringConstants.DelegateMethodCallbackParameterName)) ordinal += 1 parameters.Add(New SynthesizedParameterSymbol(Me, objectType, ordinal, False, StringConstants.DelegateMethodInstanceParameterName)) InitializeParameters(parameters.ToImmutableAndFree()) End Sub Public Overrides ReadOnly Property Name As String Get Return WellKnownMemberNames.DelegateBeginInvokeName End Get End Property Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) ' BeginInvoke doesn't have return type attributes Return Nothing End Function End Class Private NotInheritable Class EndInvokeMethod Inherits SourceDelegateMethodSymbol Public Sub New(invoke As InvokeMethod, iAsyncResultType As TypeSymbol, syntax As VisualBasicSyntaxNode, binder As Binder) MyBase.New(invoke.ContainingType, syntax, binder, flags:=SourceMemberFlags.MethodKindOrdinary Or SourceMemberFlags.AccessibilityPublic Or SourceMemberFlags.Overridable Or If(invoke.ReturnType.SpecialType = SpecialType.System_Void, SourceMemberFlags.MethodIsSub, Nothing), returnType:=invoke.ReturnType) Dim parameters = ArrayBuilder(Of ParameterSymbol).GetInstance() Dim ordinal = 0 For Each parameter In invoke.Parameters ' Delegate parameters cannot be optional in VB. ' In error cases where the parameter is specified optional in source, the parameter ' will not have a True .IsOptional. ' This is ensured by 'CheckDelegateParameterModifier' Debug.Assert(Not parameter.IsOptional) If parameter.IsByRef Then parameters.Add(New SourceDelegateClonedParameterSymbolForBeginAndEndInvoke(DirectCast(parameter, SourceParameterSymbol), Me, ordinal)) ordinal += 1 End If Next parameters.Add(New SynthesizedParameterSymbol(Me, iAsyncResultType, parameters.Count, False, StringConstants.DelegateMethodResultParameterName)) InitializeParameters(parameters.ToImmutableAndFree()) End Sub Public Overrides ReadOnly Property Name As String Get Return WellKnownMemberNames.DelegateEndInvokeName End Get End Property Protected Overrides Function GetReturnTypeAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) ' EndInvoke doesn't have return type attributes Return Nothing End Function End Class End Class End Namespace
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Features/Core/Portable/NavigateTo/INavigateToSearchResult.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Navigation; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.NavigateTo { internal interface INavigateToSearchResult { string AdditionalInformation { get; } string Kind { get; } NavigateToMatchKind MatchKind { get; } bool IsCaseSensitive { get; } string Name { get; } ImmutableArray<TextSpan> NameMatchSpans { get; } string SecondarySort { get; } string Summary { get; } INavigableItem NavigableItem { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.NavigateTo { internal interface INavigateToSearchResult { string AdditionalInformation { get; } string Kind { get; } NavigateToMatchKind MatchKind { get; } bool IsCaseSensitive { get; } string Name { get; } ImmutableArray<TextSpan> NameMatchSpans { get; } string SecondarySort { get; } string Summary { get; } INavigableItem NavigableItem { get; } } }
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Features/Core/Portable/QuickInfo/QuickInfoSectionKinds.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// The set of well known kinds used for the <see cref="QuickInfoSection.Kind"/> property. /// These tags influence the presentation of quick info section. /// </summary> public static class QuickInfoSectionKinds { public const string Description = nameof(Description); public const string DocumentationComments = nameof(DocumentationComments); public const string RemarksDocumentationComments = nameof(RemarksDocumentationComments); public const string ReturnsDocumentationComments = nameof(ReturnsDocumentationComments); public const string ValueDocumentationComments = nameof(ValueDocumentationComments); public const string TypeParameters = nameof(TypeParameters); public const string AnonymousTypes = nameof(AnonymousTypes); public const string Usage = nameof(Usage); public const string Exception = nameof(Exception); public const string Text = nameof(Text); public const string Captures = nameof(Captures); internal const string NullabilityAnalysis = nameof(NullabilityAnalysis); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis.QuickInfo { /// <summary> /// The set of well known kinds used for the <see cref="QuickInfoSection.Kind"/> property. /// These tags influence the presentation of quick info section. /// </summary> public static class QuickInfoSectionKinds { public const string Description = nameof(Description); public const string DocumentationComments = nameof(DocumentationComments); public const string RemarksDocumentationComments = nameof(RemarksDocumentationComments); public const string ReturnsDocumentationComments = nameof(ReturnsDocumentationComments); public const string ValueDocumentationComments = nameof(ValueDocumentationComments); public const string TypeParameters = nameof(TypeParameters); public const string AnonymousTypes = nameof(AnonymousTypes); public const string Usage = nameof(Usage); public const string Exception = nameof(Exception); public const string Text = nameof(Text); public const string Captures = nameof(Captures); internal const string NullabilityAnalysis = nameof(NullabilityAnalysis); } }
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Compilers/CSharp/Portable/Utilities/ValueSetFactory.SByteTC.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct SByteTC : INumericTC<sbyte> { sbyte INumericTC<sbyte>.MinValue => sbyte.MinValue; sbyte INumericTC<sbyte>.MaxValue => sbyte.MaxValue; sbyte INumericTC<sbyte>.Zero => 0; bool INumericTC<sbyte>.Related(BinaryOperatorKind relation, sbyte left, sbyte right) { switch (relation) { case Equal: return left == right; case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } sbyte INumericTC<sbyte>.Next(sbyte value) { Debug.Assert(value != sbyte.MaxValue); return (sbyte)(value + 1); } sbyte INumericTC<sbyte>.Prev(sbyte value) { Debug.Assert(value != sbyte.MinValue); return (sbyte)(value - 1); } sbyte INumericTC<sbyte>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (sbyte)0 : constantValue.SByteValue; public ConstantValue ToConstantValue(sbyte value) => ConstantValue.Create(value); string INumericTC<sbyte>.ToString(sbyte value) => value.ToString(); sbyte INumericTC<sbyte>.Random(Random random) { return (sbyte)random.Next(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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; namespace Microsoft.CodeAnalysis.CSharp { using static BinaryOperatorKind; internal static partial class ValueSetFactory { private struct SByteTC : INumericTC<sbyte> { sbyte INumericTC<sbyte>.MinValue => sbyte.MinValue; sbyte INumericTC<sbyte>.MaxValue => sbyte.MaxValue; sbyte INumericTC<sbyte>.Zero => 0; bool INumericTC<sbyte>.Related(BinaryOperatorKind relation, sbyte left, sbyte right) { switch (relation) { case Equal: return left == right; case GreaterThanOrEqual: return left >= right; case GreaterThan: return left > right; case LessThanOrEqual: return left <= right; case LessThan: return left < right; default: throw new ArgumentException("relation"); } } sbyte INumericTC<sbyte>.Next(sbyte value) { Debug.Assert(value != sbyte.MaxValue); return (sbyte)(value + 1); } sbyte INumericTC<sbyte>.Prev(sbyte value) { Debug.Assert(value != sbyte.MinValue); return (sbyte)(value - 1); } sbyte INumericTC<sbyte>.FromConstantValue(ConstantValue constantValue) => constantValue.IsBad ? (sbyte)0 : constantValue.SByteValue; public ConstantValue ToConstantValue(sbyte value) => ConstantValue.Create(value); string INumericTC<sbyte>.ToString(sbyte value) => value.ToString(); sbyte INumericTC<sbyte>.Random(Random random) { return (sbyte)random.Next(); } } } }
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/EditorFeatures/CSharpTest/ImplementInterface/ImplementExplicitlyTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ImplementInterface; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementInterface { public class ImplementExplicitlyTests : AbstractCSharpCodeActionTest { private const int SingleMember = 0; private const int SameInterface = 1; private const int AllInterfaces = 2; protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpImplementExplicitlyCodeRefactoringProvider(); protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestSingleMember() { await TestInRegularAndScriptAsync( @" interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } class C : IGoo, IBar { public void [||]Goo1() { } public void Goo2() { } public void Bar() { } }", @" interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } class C : IGoo, IBar { void IGoo.Goo1() { } public void Goo2() { } public void Bar() { } }", index: SingleMember); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestSameInterface() { await TestInRegularAndScriptAsync( @" interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } class C : IGoo, IBar { public void [||]Goo1() { } public void Goo2() { } public void Bar() { } }", @" interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } class C : IGoo, IBar { void IGoo.Goo1() { } void IGoo.Goo2() { } public void Bar() { } }", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestAllInterfaces() { await TestInRegularAndScriptAsync( @" interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } class C : IGoo, IBar { public void [||]Goo1() { } public void Goo2() { } public void Bar() { } }", @" interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } class C : IGoo, IBar { void IGoo.Goo1() { } void IGoo.Goo2() { } void IBar.Bar() { } }", index: AllInterfaces); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestProperty() { await TestInRegularAndScriptAsync( @" interface IGoo { int Goo1 { get; } } class C : IGoo { public int [||]Goo1 { get { } } }", @" interface IGoo { int Goo1 { get; } } class C : IGoo { int IGoo.Goo1 { get { } } }", index: SingleMember); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEvent() { await TestInRegularAndScriptAsync( @" interface IGoo { event Action E; } class C : IGoo { public event Action [||]E { add { } remove { } } }", @" interface IGoo { event Action E; } class C : IGoo { event Action IGoo.E { add { } remove { } } }", index: SingleMember); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNotOnExplicitMember() { await TestMissingAsync( @" interface IGoo { void Goo1(); } class C : IGoo { void IGoo.[||]Goo1() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNotOnUnboundImplicitImpl() { await TestMissingAsync( @" interface IGoo { void Goo1(); } class C { public void [||]Goo1() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUpdateReferences_InsideDeclarations_Explicit() { await TestInRegularAndScriptAsync( @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { public int [||]Prop { get { return this.Prop; } set { this.Prop = value; } } public int M(int i) { return this.M(i); } public event Action Ev { add { this.Ev += value; } remove { this.Ev -= value; } } }", @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { int IGoo.Prop { get { return ((IGoo)this).Prop; } set { ((IGoo)this).Prop = value; } } int IGoo.M(int i) { return ((IGoo)this).M(i); } event Action IGoo.Ev { add { ((IGoo)this).Ev += value; } remove { ((IGoo)this).Ev -= value; } } }", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUpdateReferences_InsideDeclarations_Implicit() { await TestInRegularAndScriptAsync( @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { public int [||]Prop { get { return Prop; } set { Prop = value; } } public int M(int i) { return M(i); } public event Action Ev { add { Ev += value; } remove { Ev -= value; } } }", @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { int IGoo.Prop { get { return ((IGoo)this).Prop; } set { ((IGoo)this).Prop = value; } } int IGoo.M(int i) { return ((IGoo)this).M(i); } event Action IGoo.Ev { add { ((IGoo)this).Ev += value; } remove { ((IGoo)this).Ev -= value; } } }", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUpdateReferences_InternalImplicit() { await TestInRegularAndScriptAsync( @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { public int [||]Prop { get { } set { } } public int M(int i) { } public event Action Ev { add { } remove { } } void InternalImplicit() { var v = Prop; Prop = 1; Prop++; ++Prop; M(0); M(M(0)); Ev += () => {}; var v1 = nameof(Prop); } }", @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { int IGoo.Prop { get { } set { } } int IGoo.M(int i) { } event Action IGoo.Ev { add { } remove { } } void InternalImplicit() { var v = ((IGoo)this).Prop; ((IGoo)this).Prop = 1; ((IGoo)this).Prop++; ++((IGoo)this).Prop; ((IGoo)this).M(0); ((IGoo)this).M(((IGoo)this).M(0)); ((IGoo)this).Ev += () => {}; var v1 = nameof(((IGoo)this).Prop); } }", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUpdateReferences_InternalExplicit() { await TestInRegularAndScriptAsync( @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { public int [||]Prop { get { } set { } } public int M(int i) { } public event Action Ev { add { } remove { } } void InternalExplicit() { var v = this.Prop; this.Prop = 1; this.Prop++; ++this.Prop; this.M(0); this.M(this.M(0)); this.Ev += () => {}; var v1 = nameof(this.Prop); } }", @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { int IGoo.Prop { get { } set { } } int IGoo.M(int i) { } event Action IGoo.Ev { add { } remove { } } void InternalExplicit() { var v = ((IGoo)this).Prop; ((IGoo)this).Prop = 1; ((IGoo)this).Prop++; ++((IGoo)this).Prop; ((IGoo)this).M(0); ((IGoo)this).M(((IGoo)this).M(0)); ((IGoo)this).Ev += () => {}; var v1 = nameof(((IGoo)this).Prop); } }", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUpdateReferences_External() { await TestInRegularAndScriptAsync( @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { public int [||]Prop { get { } set { } } public int M(int i) { } public event Action Ev { add { } remove { } } } class T { void External(C c) { var v = c.Prop; c.Prop = 1; c.Prop++; ++c.Prop; c.M(0); c.M(c.M(0)); c.Ev += () => {}; new C { Prop = 1 }; var v1 = nameof(c.Prop); } }", @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { int IGoo.Prop { get { } set { } } int IGoo.M(int i) { } event Action IGoo.Ev { add { } remove { } } } class T { void External(C c) { var v = ((IGoo)c).Prop; ((IGoo)c).Prop = 1; ((IGoo)c).Prop++; ++((IGoo)c).Prop; ((IGoo)c).M(0); ((IGoo)c).M(((IGoo)c).M(0)); ((IGoo)c).Ev += () => {}; new C { Prop = 1 }; var v1 = nameof(((IGoo)c).Prop); } }", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUpdateReferences_CrossLanguage() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""A1""> <Document FilePath=""File.cs""> using System; public interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } public class C : IGoo { public int [||]Prop { get { } set { } } public int M(int i) { } public event Action Ev { add { } remove { } } } </Document> </Project> <Project Language=""Visual Basic"" CommonReferences=""true"" AssemblyName=""A2""> <ProjectReference>A1</ProjectReference> <Document> class T sub External(c1 as C) dim v = c1.Prop c1.Prop = 1 c1.M(0) c1.M(c1.M(0)) dim x = new C() with { .Prop = 1 } dim v1 = nameof(c1.Prop) end sub end class </Document> </Project> </Workspace> ", @" <Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""A1""> <Document FilePath=""File.cs""> using System; public interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } public class C : IGoo { int IGoo.Prop { get { } set { } } int IGoo.M(int i) { } event Action IGoo.Ev { add { } remove { } } } </Document> </Project> <Project Language=""Visual Basic"" CommonReferences=""true"" AssemblyName=""A2""> <ProjectReference>A1</ProjectReference> <Document> class T sub External(c1 as C) dim v = DirectCast(c1, IGoo).Prop DirectCast(c1, IGoo).Prop = 1 DirectCast(c1, IGoo).M(0) DirectCast(c1, IGoo).M(DirectCast(c1, IGoo).M(0)) dim x = new C() with { .Prop = 1 } dim v1 = nameof(c1.Prop) end sub end class </Document> </Project> </Workspace> ", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMemberWhichImplementsMultipleMembers() { await TestInRegularAndScriptAsync( @" interface IGoo { int M(int i); } interface IBar { int M(int i); } class C : IGoo, IBar { public int [||]M(int i) { throw new System.Exception(); } }", @" interface IGoo { int M(int i); } interface IBar { int M(int i); } class C : IGoo, IBar { int IGoo.M(int i) { throw new System.Exception(); } int IBar.M(int i) { throw new System.Exception(); } }", index: SingleMember); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMemberWhichImplementsMultipleMembers2() { await TestInRegularAndScriptAsync( @" interface IGoo { int M(int i); } interface IBar { int M(int i); } class C : IGoo, IBar { public int [||]M(int i) { return this.M(1); } }", @" interface IGoo { int M(int i); } interface IBar { int M(int i); } class C : IGoo, IBar { int IGoo.M(int i) { return ((IGoo)this).M(1); } int IBar.M(int i) { return ((IGoo)this).M(1); } }", index: SingleMember); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.ImplementInterface; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ImplementInterface { public class ImplementExplicitlyTests : AbstractCSharpCodeActionTest { private const int SingleMember = 0; private const int SameInterface = 1; private const int AllInterfaces = 2; protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new CSharpImplementExplicitlyCodeRefactoringProvider(); protected override ImmutableArray<CodeAction> MassageActions(ImmutableArray<CodeAction> actions) => FlattenActions(actions); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestSingleMember() { await TestInRegularAndScriptAsync( @" interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } class C : IGoo, IBar { public void [||]Goo1() { } public void Goo2() { } public void Bar() { } }", @" interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } class C : IGoo, IBar { void IGoo.Goo1() { } public void Goo2() { } public void Bar() { } }", index: SingleMember); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestSameInterface() { await TestInRegularAndScriptAsync( @" interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } class C : IGoo, IBar { public void [||]Goo1() { } public void Goo2() { } public void Bar() { } }", @" interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } class C : IGoo, IBar { void IGoo.Goo1() { } void IGoo.Goo2() { } public void Bar() { } }", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestAllInterfaces() { await TestInRegularAndScriptAsync( @" interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } class C : IGoo, IBar { public void [||]Goo1() { } public void Goo2() { } public void Bar() { } }", @" interface IGoo { void Goo1(); void Goo2(); } interface IBar { void Bar(); } class C : IGoo, IBar { void IGoo.Goo1() { } void IGoo.Goo2() { } void IBar.Bar() { } }", index: AllInterfaces); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestProperty() { await TestInRegularAndScriptAsync( @" interface IGoo { int Goo1 { get; } } class C : IGoo { public int [||]Goo1 { get { } } }", @" interface IGoo { int Goo1 { get; } } class C : IGoo { int IGoo.Goo1 { get { } } }", index: SingleMember); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestEvent() { await TestInRegularAndScriptAsync( @" interface IGoo { event Action E; } class C : IGoo { public event Action [||]E { add { } remove { } } }", @" interface IGoo { event Action E; } class C : IGoo { event Action IGoo.E { add { } remove { } } }", index: SingleMember); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNotOnExplicitMember() { await TestMissingAsync( @" interface IGoo { void Goo1(); } class C : IGoo { void IGoo.[||]Goo1() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestNotOnUnboundImplicitImpl() { await TestMissingAsync( @" interface IGoo { void Goo1(); } class C { public void [||]Goo1() { } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUpdateReferences_InsideDeclarations_Explicit() { await TestInRegularAndScriptAsync( @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { public int [||]Prop { get { return this.Prop; } set { this.Prop = value; } } public int M(int i) { return this.M(i); } public event Action Ev { add { this.Ev += value; } remove { this.Ev -= value; } } }", @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { int IGoo.Prop { get { return ((IGoo)this).Prop; } set { ((IGoo)this).Prop = value; } } int IGoo.M(int i) { return ((IGoo)this).M(i); } event Action IGoo.Ev { add { ((IGoo)this).Ev += value; } remove { ((IGoo)this).Ev -= value; } } }", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUpdateReferences_InsideDeclarations_Implicit() { await TestInRegularAndScriptAsync( @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { public int [||]Prop { get { return Prop; } set { Prop = value; } } public int M(int i) { return M(i); } public event Action Ev { add { Ev += value; } remove { Ev -= value; } } }", @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { int IGoo.Prop { get { return ((IGoo)this).Prop; } set { ((IGoo)this).Prop = value; } } int IGoo.M(int i) { return ((IGoo)this).M(i); } event Action IGoo.Ev { add { ((IGoo)this).Ev += value; } remove { ((IGoo)this).Ev -= value; } } }", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUpdateReferences_InternalImplicit() { await TestInRegularAndScriptAsync( @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { public int [||]Prop { get { } set { } } public int M(int i) { } public event Action Ev { add { } remove { } } void InternalImplicit() { var v = Prop; Prop = 1; Prop++; ++Prop; M(0); M(M(0)); Ev += () => {}; var v1 = nameof(Prop); } }", @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { int IGoo.Prop { get { } set { } } int IGoo.M(int i) { } event Action IGoo.Ev { add { } remove { } } void InternalImplicit() { var v = ((IGoo)this).Prop; ((IGoo)this).Prop = 1; ((IGoo)this).Prop++; ++((IGoo)this).Prop; ((IGoo)this).M(0); ((IGoo)this).M(((IGoo)this).M(0)); ((IGoo)this).Ev += () => {}; var v1 = nameof(((IGoo)this).Prop); } }", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUpdateReferences_InternalExplicit() { await TestInRegularAndScriptAsync( @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { public int [||]Prop { get { } set { } } public int M(int i) { } public event Action Ev { add { } remove { } } void InternalExplicit() { var v = this.Prop; this.Prop = 1; this.Prop++; ++this.Prop; this.M(0); this.M(this.M(0)); this.Ev += () => {}; var v1 = nameof(this.Prop); } }", @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { int IGoo.Prop { get { } set { } } int IGoo.M(int i) { } event Action IGoo.Ev { add { } remove { } } void InternalExplicit() { var v = ((IGoo)this).Prop; ((IGoo)this).Prop = 1; ((IGoo)this).Prop++; ++((IGoo)this).Prop; ((IGoo)this).M(0); ((IGoo)this).M(((IGoo)this).M(0)); ((IGoo)this).Ev += () => {}; var v1 = nameof(((IGoo)this).Prop); } }", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUpdateReferences_External() { await TestInRegularAndScriptAsync( @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { public int [||]Prop { get { } set { } } public int M(int i) { } public event Action Ev { add { } remove { } } } class T { void External(C c) { var v = c.Prop; c.Prop = 1; c.Prop++; ++c.Prop; c.M(0); c.M(c.M(0)); c.Ev += () => {}; new C { Prop = 1 }; var v1 = nameof(c.Prop); } }", @" using System; interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } class C : IGoo { int IGoo.Prop { get { } set { } } int IGoo.M(int i) { } event Action IGoo.Ev { add { } remove { } } } class T { void External(C c) { var v = ((IGoo)c).Prop; ((IGoo)c).Prop = 1; ((IGoo)c).Prop++; ++((IGoo)c).Prop; ((IGoo)c).M(0); ((IGoo)c).M(((IGoo)c).M(0)); ((IGoo)c).Ev += () => {}; new C { Prop = 1 }; var v1 = nameof(((IGoo)c).Prop); } }", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestUpdateReferences_CrossLanguage() { await TestInRegularAndScriptAsync( @" <Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""A1""> <Document FilePath=""File.cs""> using System; public interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } public class C : IGoo { public int [||]Prop { get { } set { } } public int M(int i) { } public event Action Ev { add { } remove { } } } </Document> </Project> <Project Language=""Visual Basic"" CommonReferences=""true"" AssemblyName=""A2""> <ProjectReference>A1</ProjectReference> <Document> class T sub External(c1 as C) dim v = c1.Prop c1.Prop = 1 c1.M(0) c1.M(c1.M(0)) dim x = new C() with { .Prop = 1 } dim v1 = nameof(c1.Prop) end sub end class </Document> </Project> </Workspace> ", @" <Workspace> <Project Language=""C#"" CommonReferences=""true"" AssemblyName=""A1""> <Document FilePath=""File.cs""> using System; public interface IGoo { int Prop { get; set; } int M(int i); event Action Ev; } public class C : IGoo { int IGoo.Prop { get { } set { } } int IGoo.M(int i) { } event Action IGoo.Ev { add { } remove { } } } </Document> </Project> <Project Language=""Visual Basic"" CommonReferences=""true"" AssemblyName=""A2""> <ProjectReference>A1</ProjectReference> <Document> class T sub External(c1 as C) dim v = DirectCast(c1, IGoo).Prop DirectCast(c1, IGoo).Prop = 1 DirectCast(c1, IGoo).M(0) DirectCast(c1, IGoo).M(DirectCast(c1, IGoo).M(0)) dim x = new C() with { .Prop = 1 } dim v1 = nameof(c1.Prop) end sub end class </Document> </Project> </Workspace> ", index: SameInterface); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMemberWhichImplementsMultipleMembers() { await TestInRegularAndScriptAsync( @" interface IGoo { int M(int i); } interface IBar { int M(int i); } class C : IGoo, IBar { public int [||]M(int i) { throw new System.Exception(); } }", @" interface IGoo { int M(int i); } interface IBar { int M(int i); } class C : IGoo, IBar { int IGoo.M(int i) { throw new System.Exception(); } int IBar.M(int i) { throw new System.Exception(); } }", index: SingleMember); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsImplementInterface)] public async Task TestMemberWhichImplementsMultipleMembers2() { await TestInRegularAndScriptAsync( @" interface IGoo { int M(int i); } interface IBar { int M(int i); } class C : IGoo, IBar { public int [||]M(int i) { return this.M(1); } }", @" interface IGoo { int M(int i); } interface IBar { int M(int i); } class C : IGoo, IBar { int IGoo.M(int i) { return ((IGoo)this).M(1); } int IBar.M(int i) { return ((IGoo)this).M(1); } }", index: SingleMember); } } }
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/VisualStudio/VisualStudioDiagnosticsToolWindow/xlf/VisualStudioDiagnosticsWindow.vsct.zh-Hant.xlf
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../VisualStudioDiagnosticsWindow.vsct"> <body> <trans-unit id="cmdIDRoslynDiagnosticWindow|CommandName"> <source>cmdIDRoslynDiagnosticWindow</source> <target state="translated">cmdIDRoslynDiagnosticWindow</target> <note /> </trans-unit> <trans-unit id="cmdIDRoslynDiagnosticWindow|ButtonText"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 診斷</target> <note /> </trans-unit> </body> </file> </xliff>
<?xml version="1.0" encoding="utf-8"?> <xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.2" xsi:schemaLocation="urn:oasis:names:tc:xliff:document:1.2 xliff-core-1.2-transitional.xsd"> <file datatype="xml" source-language="en" target-language="zh-Hant" original="../VisualStudioDiagnosticsWindow.vsct"> <body> <trans-unit id="cmdIDRoslynDiagnosticWindow|CommandName"> <source>cmdIDRoslynDiagnosticWindow</source> <target state="translated">cmdIDRoslynDiagnosticWindow</target> <note /> </trans-unit> <trans-unit id="cmdIDRoslynDiagnosticWindow|ButtonText"> <source>Roslyn Diagnostics</source> <target state="translated">Roslyn 診斷</target> <note /> </trans-unit> </body> </file> </xliff>
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Compilers/CSharp/Portable/CodeGen/EmitStatement.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CSharp.Binder; namespace Microsoft.CodeAnalysis.CSharp.CodeGen { internal partial class CodeGenerator { private void EmitStatement(BoundStatement statement) { switch (statement.Kind) { case BoundKind.Block: EmitBlock((BoundBlock)statement); break; case BoundKind.Scope: EmitScope((BoundScope)statement); break; case BoundKind.SequencePoint: this.EmitSequencePointStatement((BoundSequencePoint)statement); break; case BoundKind.SequencePointWithSpan: this.EmitSequencePointStatement((BoundSequencePointWithSpan)statement); break; case BoundKind.SavePreviousSequencePoint: this.EmitSavePreviousSequencePoint((BoundSavePreviousSequencePoint)statement); break; case BoundKind.RestorePreviousSequencePoint: this.EmitRestorePreviousSequencePoint((BoundRestorePreviousSequencePoint)statement); break; case BoundKind.StepThroughSequencePoint: this.EmitStepThroughSequencePoint((BoundStepThroughSequencePoint)statement); break; case BoundKind.ExpressionStatement: EmitExpression(((BoundExpressionStatement)statement).Expression, false); break; case BoundKind.StatementList: EmitStatementList((BoundStatementList)statement); break; case BoundKind.ReturnStatement: EmitReturnStatement((BoundReturnStatement)statement); break; case BoundKind.GotoStatement: EmitGotoStatement((BoundGotoStatement)statement); break; case BoundKind.LabelStatement: EmitLabelStatement((BoundLabelStatement)statement); break; case BoundKind.ConditionalGoto: EmitConditionalGoto((BoundConditionalGoto)statement); break; case BoundKind.ThrowStatement: EmitThrowStatement((BoundThrowStatement)statement); break; case BoundKind.TryStatement: EmitTryStatement((BoundTryStatement)statement); break; case BoundKind.SwitchDispatch: EmitSwitchDispatch((BoundSwitchDispatch)statement); break; case BoundKind.StateMachineScope: EmitStateMachineScope((BoundStateMachineScope)statement); break; case BoundKind.NoOpStatement: EmitNoOpStatement((BoundNoOpStatement)statement); break; default: // Code gen should not be invoked if there are errors. throw ExceptionUtilities.UnexpectedValue(statement.Kind); } #if DEBUG if (_stackLocals == null || _stackLocals.Count == 0) { _builder.AssertStackEmpty(); } #endif ReleaseExpressionTemps(); } private int EmitStatementAndCountInstructions(BoundStatement statement) { int n = _builder.InstructionsEmitted; this.EmitStatement(statement); return _builder.InstructionsEmitted - n; } private void EmitStatementList(BoundStatementList list) { for (int i = 0, n = list.Statements.Length; i < n; i++) { EmitStatement(list.Statements[i]); } } private void EmitNoOpStatement(BoundNoOpStatement statement) { switch (statement.Flavor) { case NoOpStatementFlavor.Default: if (_ilEmitStyle == ILEmitStyle.Debug) { _builder.EmitOpCode(ILOpCode.Nop); } break; case NoOpStatementFlavor.AwaitYieldPoint: Debug.Assert((_asyncYieldPoints == null) == (_asyncResumePoints == null)); if (_asyncYieldPoints == null) { _asyncYieldPoints = ArrayBuilder<int>.GetInstance(); _asyncResumePoints = ArrayBuilder<int>.GetInstance(); } Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count); _asyncYieldPoints.Add(_builder.AllocateILMarker()); break; case NoOpStatementFlavor.AwaitResumePoint: Debug.Assert(_asyncYieldPoints != null); Debug.Assert(_asyncYieldPoints != null); _asyncResumePoints.Add(_builder.AllocateILMarker()); Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count); break; default: throw ExceptionUtilities.UnexpectedValue(statement.Flavor); } } private void EmitThrowStatement(BoundThrowStatement node) { EmitThrow(node.ExpressionOpt); } private void EmitThrow(BoundExpression thrown) { if (thrown != null) { this.EmitExpression(thrown, true); var exprType = thrown.Type; // Expression type will be null for "throw null;". if (exprType?.TypeKind == TypeKind.TypeParameter) { this.EmitBox(exprType, thrown.Syntax); } } _builder.EmitThrow(isRethrow: thrown == null); } private void EmitConditionalGoto(BoundConditionalGoto boundConditionalGoto) { object label = boundConditionalGoto.Label; Debug.Assert(label != null); EmitCondBranch(boundConditionalGoto.Condition, ref label, boundConditionalGoto.JumpIfTrue); } // 3.17 The brfalse instruction transfers control to target if value (of type int32, int64, object reference, managed //pointer, unmanaged pointer or native int) is zero (false). If value is non-zero (true), execution continues at //the next instruction. private static bool CanPassToBrfalse(TypeSymbol ts) { if (ts.IsEnumType()) { // valid enums are all primitives return true; } var tc = ts.PrimitiveTypeCode; switch (tc) { case Microsoft.Cci.PrimitiveTypeCode.Float32: case Microsoft.Cci.PrimitiveTypeCode.Float64: return false; case Microsoft.Cci.PrimitiveTypeCode.NotPrimitive: // if this is a generic type param, verifier will want us to box // EmitCondBranch knows that return ts.IsReferenceType; default: Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Invalid); Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Void); return true; } } private static BoundExpression TryReduce(BoundBinaryOperator condition, ref bool sense) { var opKind = condition.OperatorKind.Operator(); Debug.Assert(opKind == BinaryOperatorKind.Equal || opKind == BinaryOperatorKind.NotEqual); BoundExpression nonConstOp; BoundExpression constOp = (condition.Left.ConstantValue != null) ? condition.Left : null; if (constOp != null) { nonConstOp = condition.Right; } else { constOp = (condition.Right.ConstantValue != null) ? condition.Right : null; if (constOp == null) { return null; } nonConstOp = condition.Left; } var nonConstType = nonConstOp.Type; if (!CanPassToBrfalse(nonConstType)) { return null; } bool isBool = nonConstType.PrimitiveTypeCode == Microsoft.Cci.PrimitiveTypeCode.Boolean; bool isZero = constOp.ConstantValue.IsDefaultValue; // bool is special, only it can be compared to true and false... if (!isBool && !isZero) { return null; } // if comparing to zero, flip the sense if (isZero) { sense = !sense; } // if comparing != flip the sense if (opKind == BinaryOperatorKind.NotEqual) { sense = !sense; } return nonConstOp; } private const int IL_OP_CODE_ROW_LENGTH = 4; private static readonly ILOpCode[] s_condJumpOpCodes = new ILOpCode[] { // < <= > >= ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Signed ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt, // Signed Invert ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un, // Unsigned ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Unsigned Invert ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Float ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Float Invert }; /// <summary> /// Produces opcode for a jump that corresponds to given operation and sense. /// Also produces a reverse opcode - opcode for the same condition with inverted sense. /// </summary> private static ILOpCode CodeForJump(BoundBinaryOperator op, bool sense, out ILOpCode revOpCode) { int opIdx; switch (op.OperatorKind.Operator()) { case BinaryOperatorKind.Equal: revOpCode = !sense ? ILOpCode.Beq : ILOpCode.Bne_un; return sense ? ILOpCode.Beq : ILOpCode.Bne_un; case BinaryOperatorKind.NotEqual: revOpCode = !sense ? ILOpCode.Bne_un : ILOpCode.Beq; return sense ? ILOpCode.Bne_un : ILOpCode.Beq; case BinaryOperatorKind.LessThan: opIdx = 0; break; case BinaryOperatorKind.LessThanOrEqual: opIdx = 1; break; case BinaryOperatorKind.GreaterThan: opIdx = 2; break; case BinaryOperatorKind.GreaterThanOrEqual: opIdx = 3; break; default: throw ExceptionUtilities.UnexpectedValue(op.OperatorKind.Operator()); } if (IsUnsignedBinaryOperator(op)) { opIdx += 2 * IL_OP_CODE_ROW_LENGTH; //unsigned } else if (IsFloat(op.OperatorKind)) { opIdx += 4 * IL_OP_CODE_ROW_LENGTH; //float } int revOpIdx = opIdx; if (!sense) { opIdx += IL_OP_CODE_ROW_LENGTH; //invert op } else { revOpIdx += IL_OP_CODE_ROW_LENGTH; //invert rev } revOpCode = s_condJumpOpCodes[revOpIdx]; return s_condJumpOpCodes[opIdx]; } // generate a jump to dest if (condition == sense) is true private void EmitCondBranch(BoundExpression condition, ref object dest, bool sense) { _recursionDepth++; if (_recursionDepth > 1) { StackGuard.EnsureSufficientExecutionStack(_recursionDepth); EmitCondBranchCore(condition, ref dest, sense); } else { EmitCondBranchCoreWithStackGuard(condition, ref dest, sense); } _recursionDepth--; } private void EmitCondBranchCoreWithStackGuard(BoundExpression condition, ref object dest, bool sense) { Debug.Assert(_recursionDepth == 1); try { EmitCondBranchCore(condition, ref dest, sense); Debug.Assert(_recursionDepth == 1); } catch (InsufficientExecutionStackException) { _diagnostics.Add(ErrorCode.ERR_InsufficientStack, BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(condition)); throw new EmitCancelledException(); } } private void EmitCondBranchCore(BoundExpression condition, ref object dest, bool sense) { oneMoreTime: ILOpCode ilcode; if (condition.ConstantValue != null) { bool taken = condition.ConstantValue.IsDefaultValue != sense; if (taken) { dest = dest ?? new object(); _builder.EmitBranch(ILOpCode.Br, dest); } else { // otherwise this branch will never be taken, so just fall through... } return; } switch (condition.Kind) { case BoundKind.BinaryOperator: var binOp = (BoundBinaryOperator)condition; bool testBothArgs = sense; switch (binOp.OperatorKind.OperatorWithLogical()) { case BinaryOperatorKind.LogicalOr: testBothArgs = !testBothArgs; // Fall through goto case BinaryOperatorKind.LogicalAnd; case BinaryOperatorKind.LogicalAnd: if (testBothArgs) { // gotoif(a != sense) fallThrough // gotoif(b == sense) dest // fallThrough: object fallThrough = null; EmitCondBranch(binOp.Left, ref fallThrough, !sense); EmitCondBranch(binOp.Right, ref dest, sense); if (fallThrough != null) { _builder.MarkLabel(fallThrough); } } else { // gotoif(a == sense) labDest // gotoif(b == sense) labDest EmitCondBranch(binOp.Left, ref dest, sense); condition = binOp.Right; goto oneMoreTime; } return; case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: var reduced = TryReduce(binOp, ref sense); if (reduced != null) { condition = reduced; goto oneMoreTime; } // Fall through goto case BinaryOperatorKind.LessThan; case BinaryOperatorKind.LessThan: case BinaryOperatorKind.LessThanOrEqual: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.GreaterThanOrEqual: EmitExpression(binOp.Left, true); EmitExpression(binOp.Right, true); ILOpCode revOpCode; ilcode = CodeForJump(binOp, sense, out revOpCode); dest = dest ?? new object(); _builder.EmitBranch(ilcode, dest, revOpCode); return; } // none of above. // then it is regular binary expression - Or, And, Xor ... goto default; case BoundKind.LoweredConditionalAccess: { var ca = (BoundLoweredConditionalAccess)condition; var receiver = ca.Receiver; var receiverType = receiver.Type; // we need a copy if we deal with nonlocal value (to capture the value) // or if we deal with stack local (reads are destructive) var complexCase = !receiverType.IsReferenceType || LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) || (receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol)) || (ca.WhenNullOpt?.IsDefaultValue() == false); if (complexCase) { goto default; } if (sense) { // gotoif(receiver != null) fallThrough // gotoif(receiver.Access) dest // fallThrough: object fallThrough = null; EmitCondBranch(receiver, ref fallThrough, sense: false); // receiver is a reference type, and we only intend to read it EmitReceiverRef(receiver, AddressKind.ReadOnly); EmitCondBranch(ca.WhenNotNull, ref dest, sense: true); if (fallThrough != null) { _builder.MarkLabel(fallThrough); } } else { // gotoif(receiver == null) labDest // gotoif(!receiver.Access) labDest EmitCondBranch(receiver, ref dest, sense: false); // receiver is a reference type, and we only intend to read it EmitReceiverRef(receiver, AddressKind.ReadOnly); condition = ca.WhenNotNull; goto oneMoreTime; } } return; case BoundKind.UnaryOperator: var unOp = (BoundUnaryOperator)condition; if (unOp.OperatorKind == UnaryOperatorKind.BoolLogicalNegation) { sense = !sense; condition = unOp.Operand; goto oneMoreTime; } goto default; case BoundKind.IsOperator: var isOp = (BoundIsOperator)condition; var operand = isOp.Operand; EmitExpression(operand, true); Debug.Assert((object)operand.Type != null); if (!operand.Type.IsVerifierReference()) { // box the operand for isinst if it is not a verifier reference EmitBox(operand.Type, operand.Syntax); } _builder.EmitOpCode(ILOpCode.Isinst); EmitSymbolToken(isOp.TargetType.Type, isOp.TargetType.Syntax); ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse; dest = dest ?? new object(); _builder.EmitBranch(ilcode, dest); return; case BoundKind.Sequence: var seq = (BoundSequence)condition; EmitSequenceCondBranch(seq, ref dest, sense); return; default: EmitExpression(condition, true); var conditionType = condition.Type; if (conditionType.IsReferenceType && !conditionType.IsVerifierReference()) { EmitBox(conditionType, condition.Syntax); } ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse; dest = dest ?? new object(); _builder.EmitBranch(ilcode, dest); return; } } private void EmitSequenceCondBranch(BoundSequence sequence, ref object dest, bool sense) { DefineLocals(sequence); EmitSideEffects(sequence); EmitCondBranch(sequence.Value, ref dest, sense); // sequence is used as a value, can release all locals FreeLocals(sequence); } private void EmitLabelStatement(BoundLabelStatement boundLabelStatement) { _builder.MarkLabel(boundLabelStatement.Label); } private void EmitGotoStatement(BoundGotoStatement boundGotoStatement) { _builder.EmitBranch(ILOpCode.Br, boundGotoStatement.Label); } // used by HandleReturn method which tries to inject // indirect ret sequence as a last statement in the block // that is the last statement of the current method // NOTE: it is important that there is no code after this "ret" // it is desirable, for debug purposes, that this ret is emitted inside top level { } private bool IsLastBlockInMethod(BoundBlock block) { if (_boundBody == block) { return true; } //sometimes top level node is a statement list containing //epilogue and then a block. If we are having that block, it will do. var list = _boundBody as BoundStatementList; if (list != null && list.Statements.LastOrDefault() == block) { return true; } return false; } private void EmitBlock(BoundBlock block) { var hasLocals = !block.Locals.IsEmpty; if (hasLocals) { _builder.OpenLocalScope(); foreach (var local in block.Locals) { Debug.Assert(local.RefKind == RefKind.None || local.SynthesizedKind.IsLongLived(), "A ref local ended up in a block and claims it is shortlived. That is dangerous. Are we sure it is short lived?"); var declaringReferences = local.DeclaringSyntaxReferences; DefineLocal(local, !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : block.Syntax); } } EmitStatements(block.Statements); if (_indirectReturnState == IndirectReturnState.Needed && IsLastBlockInMethod(block)) { HandleReturn(); } if (hasLocals) { foreach (var local in block.Locals) { FreeLocal(local); } _builder.CloseLocalScope(); } } private void EmitStatements(ImmutableArray<BoundStatement> statements) { foreach (var statement in statements) { EmitStatement(statement); } } private void EmitScope(BoundScope block) { Debug.Assert(!block.Locals.IsEmpty); _builder.OpenLocalScope(); foreach (var local in block.Locals) { Debug.Assert(local.Name != null); Debug.Assert(local.SynthesizedKind == SynthesizedLocalKind.UserDefined && (local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchSection || local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchExpressionArm)); if (!local.IsConst && !IsStackLocal(local)) { _builder.AddLocalToScope(_builder.LocalSlotManager.GetLocal(local)); } } EmitStatements(block.Statements); _builder.CloseLocalScope(); } private void EmitStateMachineScope(BoundStateMachineScope scope) { _builder.OpenLocalScope(ScopeType.StateMachineVariable); foreach (var field in scope.Fields) { if (field.SlotIndex >= 0) { _builder.DefineUserDefinedStateMachineHoistedLocal(field.SlotIndex); } } EmitStatement(scope.Statement); _builder.CloseLocalScope(); } // There are two ways a value can be returned from a function: // - Using ret opcode // - Store return value if any to a predefined temp and jump to the epilogue block // Sometimes ret is not an option (try/catch etc.). We also do this when emitting // debuggable code. This function is a stub for the logic that decides that. private bool ShouldUseIndirectReturn() { // If the method/lambda body is a block we define a sequence point for the closing brace of the body // and associate it with the ret instruction. If there is a return statement we need to store the value // to a long-lived synthesized local since a sequence point requires an empty evaluation stack. // // The emitted pattern is: // <evaluate return statement expression> // stloc $ReturnValue // ldloc $ReturnValue // sequence point // ret // // Do not emit this pattern if the method doesn't include user code or doesn't have a block body. return _ilEmitStyle == ILEmitStyle.Debug && _method.GenerateDebugInfo && _methodBodySyntaxOpt?.IsKind(SyntaxKind.Block) == true || _builder.InExceptionHandler; } // Compiler generated return mapped to a block is very likely the synthetic return // that was added at the end of the last block of a void method by analysis. // This is likely to be the last return in the method, so if we have not yet // emitted return sequence, it is convenient to do it right here (if we can). private bool CanHandleReturnLabel(BoundReturnStatement boundReturnStatement) { return boundReturnStatement.WasCompilerGenerated && (boundReturnStatement.Syntax.IsKind(SyntaxKind.Block) || _method?.IsImplicitConstructor == true) && !_builder.InExceptionHandler; } private void EmitReturnStatement(BoundReturnStatement boundReturnStatement) { var expressionOpt = boundReturnStatement.ExpressionOpt; if (boundReturnStatement.RefKind == RefKind.None) { this.EmitExpression(expressionOpt, true); } else { // NOTE: passing "ReadOnlyStrict" here. // we should never return an address of a copy var unexpectedTemp = this.EmitAddress(expressionOpt, this._method.RefKind == RefKind.RefReadOnly ? AddressKind.ReadOnlyStrict : AddressKind.Writeable); Debug.Assert(unexpectedTemp == null, "ref-returning a temp?"); } if (ShouldUseIndirectReturn()) { if (expressionOpt != null) { _builder.EmitLocalStore(LazyReturnTemp); } if (_indirectReturnState != IndirectReturnState.Emitted && CanHandleReturnLabel(boundReturnStatement)) { HandleReturn(); } else { _builder.EmitBranch(ILOpCode.Br, s_returnLabel); if (_indirectReturnState == IndirectReturnState.NotNeeded) { _indirectReturnState = IndirectReturnState.Needed; } } } else { if (_indirectReturnState == IndirectReturnState.Needed && CanHandleReturnLabel(boundReturnStatement)) { if (expressionOpt != null) { _builder.EmitLocalStore(LazyReturnTemp); } HandleReturn(); } else { if (expressionOpt != null) { // Ensure the return type has been translated. (Necessary // for cases of untranslated anonymous types.) _module.Translate(expressionOpt.Type, boundReturnStatement.Syntax, _diagnostics); } _builder.EmitRet(expressionOpt == null); } } } private void EmitTryStatement(BoundTryStatement statement, bool emitCatchesOnly = false) { Debug.Assert(!statement.CatchBlocks.IsDefault); // Stack must be empty at beginning of try block. _builder.AssertStackEmpty(); // IL requires catches and finally block to be distinct try // blocks so if the source contained both a catch and // a finally, nested scopes are emitted. bool emitNestedScopes = (!emitCatchesOnly && (statement.CatchBlocks.Length > 0) && (statement.FinallyBlockOpt != null)); _builder.OpenLocalScope(ScopeType.TryCatchFinally); _builder.OpenLocalScope(ScopeType.Try); // IL requires catches and finally block to be distinct try // blocks so if the source contained both a catch and // a finally, nested scopes are emitted. _tryNestingLevel++; if (emitNestedScopes) { EmitTryStatement(statement, emitCatchesOnly: true); } else { EmitBlock(statement.TryBlock); } _tryNestingLevel--; // Close the Try scope _builder.CloseLocalScope(); if (!emitNestedScopes) { foreach (var catchBlock in statement.CatchBlocks) { EmitCatchBlock(catchBlock); } } if (!emitCatchesOnly && (statement.FinallyBlockOpt != null)) { _builder.OpenLocalScope(statement.PreferFaultHandler ? ScopeType.Fault : ScopeType.Finally); EmitBlock(statement.FinallyBlockOpt); // close Finally scope _builder.CloseLocalScope(); // close the whole try statement scope _builder.CloseLocalScope(); // in a case where we emit surrogate Finally using Fault, we emit code like this // // try{ // . . . // } fault { // finallyBlock; // } // finallyBlock; // // This is where the second copy of finallyBlock is emitted. if (statement.PreferFaultHandler) { var finallyClone = FinallyCloner.MakeFinallyClone(statement); EmitBlock(finallyClone); } } else { // close the whole try statement scope _builder.CloseLocalScope(); } } /// <remarks> /// The interesting part in the following method is the support for exception filters. /// === Example: /// /// try /// { /// TryBlock /// } /// catch (ExceptionType ex) when (Condition) /// { /// Handler /// } /// /// gets emitted as something like ===> /// /// Try /// TryBlock /// Filter /// var tmp = Pop() as {ExceptionType} /// if (tmp == null) /// { /// Push 0 /// } /// else /// { /// ex = tmp /// Push Condition ? 1 : 0 /// } /// End Filter // leaves 1 or 0 on the stack /// Catch // gets called after finalization of nested exception frames if condition above produced 1 /// Pop // CLR pushes the exception object again /// variable ex can be used here /// Handler /// EndCatch /// /// When evaluating `Condition` requires additional statements be executed first, those /// statements are stored in `catchBlock.ExceptionFilterPrologueOpt` and emitted before the condition. /// </remarks> private void EmitCatchBlock(BoundCatchBlock catchBlock) { object typeCheckFailedLabel = null; _builder.AdjustStack(1); // Account for exception on the stack. // Open appropriate exception handler scope. (Catch or Filter) // if it is a Filter, emit prologue that checks if the type on the stack // converts to what we want. if (catchBlock.ExceptionFilterOpt == null) { var exceptionType = ((object)catchBlock.ExceptionTypeOpt != null) ? _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics) : _module.GetSpecialType(SpecialType.System_Object, catchBlock.Syntax, _diagnostics); _builder.OpenLocalScope(ScopeType.Catch, exceptionType); RecordAsyncCatchHandlerOffset(catchBlock); // Dev12 inserts the sequence point on catch clause without a filter, just before // the exception object is assigned to the variable. // // Also in Dev12 the exception variable scope span starts right after the stloc instruction and // ends right before leave instruction. So when stopped at the sequence point Dev12 inserts, // the exception variable is not visible. if (_emitPdbSequencePoints) { var syntax = catchBlock.Syntax as CatchClauseSyntax; if (syntax != null) { TextSpan spSpan; var declaration = syntax.Declaration; if (declaration == null) { spSpan = syntax.CatchKeyword.Span; } else { spSpan = TextSpan.FromBounds(syntax.SpanStart, syntax.Declaration.Span.End); } this.EmitSequencePoint(catchBlock.SyntaxTree, spSpan); } } } else { _builder.OpenLocalScope(ScopeType.Filter); RecordAsyncCatchHandlerOffset(catchBlock); // Filtering starts with simulating regular catch through a // type check. If this is not our type then we are done. var typeCheckPassedLabel = new object(); typeCheckFailedLabel = new object(); if ((object)catchBlock.ExceptionTypeOpt != null) { var exceptionType = _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics); _builder.EmitOpCode(ILOpCode.Isinst); _builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics); _builder.EmitOpCode(ILOpCode.Dup); _builder.EmitBranch(ILOpCode.Brtrue, typeCheckPassedLabel); _builder.EmitOpCode(ILOpCode.Pop); _builder.EmitIntConstant(0); _builder.EmitBranch(ILOpCode.Br, typeCheckFailedLabel); } else { // no formal exception type means we always pass the check } _builder.MarkLabel(typeCheckPassedLabel); } foreach (var local in catchBlock.Locals) { var declaringReferences = local.DeclaringSyntaxReferences; var localSyntax = !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : catchBlock.Syntax; DefineLocal(local, localSyntax); } var exceptionSourceOpt = catchBlock.ExceptionSourceOpt; if (exceptionSourceOpt != null) { // here we have our exception on the stack in a form of a reference type (O) // it means that we have to "unbox" it before storing to the local // if exception's type is a generic type parameter. if (!exceptionSourceOpt.Type.IsVerifierReference()) { Debug.Assert(exceptionSourceOpt.Type.IsTypeParameter()); // only expecting type parameters _builder.EmitOpCode(ILOpCode.Unbox_any); EmitSymbolToken(exceptionSourceOpt.Type, exceptionSourceOpt.Syntax); } BoundExpression exceptionSource = exceptionSourceOpt; while (exceptionSource.Kind == BoundKind.Sequence) { var seq = (BoundSequence)exceptionSource; Debug.Assert(seq.Locals.IsDefaultOrEmpty); EmitSideEffects(seq); exceptionSource = seq.Value; } switch (exceptionSource.Kind) { case BoundKind.Local: var exceptionSourceLocal = (BoundLocal)exceptionSource; Debug.Assert(exceptionSourceLocal.LocalSymbol.RefKind == RefKind.None); if (!IsStackLocal(exceptionSourceLocal.LocalSymbol)) { _builder.EmitLocalStore(GetLocal(exceptionSourceLocal)); } break; case BoundKind.FieldAccess: var left = (BoundFieldAccess)exceptionSource; Debug.Assert(!left.FieldSymbol.IsStatic, "Not supported"); Debug.Assert(!left.ReceiverOpt.Type.IsTypeParameter()); var stateMachineField = left.FieldSymbol as StateMachineFieldSymbol; if (((object)stateMachineField != null) && (stateMachineField.SlotIndex >= 0)) { _builder.DefineUserDefinedStateMachineHoistedLocal(stateMachineField.SlotIndex); } // When assigning to a field // we need to push param address below the exception var temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax); _builder.EmitLocalStore(temp); var receiverTemp = EmitReceiverRef(left.ReceiverOpt, AddressKind.Writeable); Debug.Assert(receiverTemp == null); _builder.EmitLocalLoad(temp); FreeTemp(temp); EmitFieldStore(left); break; default: throw ExceptionUtilities.UnexpectedValue(exceptionSource.Kind); } } else { _builder.EmitOpCode(ILOpCode.Pop); } if (catchBlock.ExceptionFilterPrologueOpt != null) { Debug.Assert(_builder.IsStackEmpty); EmitStatements(catchBlock.ExceptionFilterPrologueOpt.Statements); } // Emit the actual filter expression, if we have one, and normalize // results. if (catchBlock.ExceptionFilterOpt != null) { EmitCondExpr(catchBlock.ExceptionFilterOpt, true); // Normalize the return value because values other than 0 or 1 // produce unspecified results. _builder.EmitIntConstant(0); _builder.EmitOpCode(ILOpCode.Cgt_un); _builder.MarkLabel(typeCheckFailedLabel); // Now we are starting the actual handler _builder.MarkFilterConditionEnd(); // Pop the exception; it should have already been stored to the // variable by the filter. _builder.EmitOpCode(ILOpCode.Pop); } EmitBlock(catchBlock.Body); _builder.CloseLocalScope(); } private void RecordAsyncCatchHandlerOffset(BoundCatchBlock catchBlock) { if (catchBlock.IsSynthesizedAsyncCatchAll) { Debug.Assert(_asyncCatchHandlerOffset < 0); // only one expected _asyncCatchHandlerOffset = _builder.AllocateILMarker(); } } private void EmitSwitchDispatch(BoundSwitchDispatch dispatch) { // Switch expression must have a valid switch governing type Debug.Assert((object)dispatch.Expression.Type != null); Debug.Assert(dispatch.Expression.Type.IsValidV6SwitchGoverningType()); // We must have rewritten nullable switch expression into non-nullable constructs. Debug.Assert(!dispatch.Expression.Type.IsNullableType()); // This must be used only for nontrivial dispatches. Debug.Assert(dispatch.Cases.Any()); EmitSwitchHeader( dispatch.Expression, dispatch.Cases.Select(p => new KeyValuePair<ConstantValue, object>(p.value, p.label)).ToArray(), dispatch.DefaultLabel, dispatch.EqualityMethod); } private void EmitSwitchHeader( BoundExpression expression, KeyValuePair<ConstantValue, object>[] switchCaseLabels, LabelSymbol fallThroughLabel, MethodSymbol equalityMethod) { Debug.Assert(expression.ConstantValue == null); Debug.Assert((object)expression.Type != null && expression.Type.IsValidV6SwitchGoverningType()); Debug.Assert(switchCaseLabels.Length > 0); Debug.Assert(switchCaseLabels != null); LocalDefinition temp = null; LocalOrParameter key; BoundSequence sequence = null; if (expression.Kind == BoundKind.Sequence) { sequence = (BoundSequence)expression; DefineLocals(sequence); EmitSideEffects(sequence); expression = sequence.Value; } if (expression.Kind == BoundKind.SequencePointExpression) { var sequencePointExpression = (BoundSequencePointExpression)expression; EmitSequencePoint(sequencePointExpression); expression = sequencePointExpression.Expression; } switch (expression.Kind) { case BoundKind.Local: var local = ((BoundLocal)expression).LocalSymbol; if (local.RefKind == RefKind.None && !IsStackLocal(local)) { key = this.GetLocal(local); break; } goto default; case BoundKind.Parameter: var parameter = (BoundParameter)expression; if (parameter.ParameterSymbol.RefKind == RefKind.None) { key = ParameterSlot(parameter); break; } goto default; default: EmitExpression(expression, true); temp = AllocateTemp(expression.Type, expression.Syntax); _builder.EmitLocalStore(temp); key = temp; break; } // Emit switch jump table if (expression.Type.SpecialType != SpecialType.System_String) { _builder.EmitIntegerSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Type.EnumUnderlyingTypeOrSelf().PrimitiveTypeCode); } else { this.EmitStringSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Syntax, equalityMethod); } if (temp != null) { FreeTemp(temp); } if (sequence != null) { // sequence was used as a value, can release all its locals. FreeLocals(sequence); } } private void EmitStringSwitchJumpTable( KeyValuePair<ConstantValue, object>[] switchCaseLabels, LabelSymbol fallThroughLabel, LocalOrParameter key, SyntaxNode syntaxNode, MethodSymbol equalityMethod) { LocalDefinition keyHash = null; // Condition is necessary, but not sufficient (e.g. might be missing a special or well-known member). if (SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(_module, switchCaseLabels.Length)) { Debug.Assert(_module.SupportsPrivateImplClass); var privateImplClass = _module.GetPrivateImplClass(syntaxNode, _diagnostics); Cci.IReference stringHashMethodRef = privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName); // Heuristics and well-known member availability determine the existence // of this helper. Rather than reproduce that (language-specific) logic here, // we simply check for the information we really want - whether the helper is // available. if (stringHashMethodRef != null) { // static uint ComputeStringHash(string s) // pop 1 (s) // push 1 (uint return value) // stackAdjustment = (pushCount - popCount) = 0 _builder.EmitLoad(key); _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); _builder.EmitToken(stringHashMethodRef, syntaxNode, _diagnostics); var UInt32Type = _module.Compilation.GetSpecialType(SpecialType.System_UInt32); keyHash = AllocateTemp(UInt32Type, syntaxNode); _builder.EmitLocalStore(keyHash); } } Cci.IReference stringEqualityMethodRef = _module.Translate(equalityMethod, syntaxNode, _diagnostics); Cci.IMethodReference stringLengthRef = null; var stringLengthMethod = _module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__Length) as MethodSymbol; if (stringLengthMethod != null && !stringLengthMethod.HasUseSiteError) { stringLengthRef = _module.Translate(stringLengthMethod, syntaxNode, _diagnostics); } SwitchStringJumpTableEmitter.EmitStringCompareAndBranch emitStringCondBranchDelegate = (keyArg, stringConstant, targetLabel) => { if (stringConstant == ConstantValue.Null) { // if (key == null) // goto targetLabel _builder.EmitLoad(keyArg); _builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue); } else if (stringConstant.StringValue.Length == 0 && stringLengthRef != null) { // if (key != null && key.Length == 0) // goto targetLabel object skipToNext = new object(); _builder.EmitLoad(keyArg); _builder.EmitBranch(ILOpCode.Brfalse, skipToNext, ILOpCode.Brtrue); _builder.EmitLoad(keyArg); // Stack: key --> length _builder.EmitOpCode(ILOpCode.Call, 0); var diag = DiagnosticBag.GetInstance(); _builder.EmitToken(stringLengthRef, null, diag); Debug.Assert(diag.IsEmptyWithoutResolution); diag.Free(); _builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue); _builder.MarkLabel(skipToNext); } else { this.EmitStringCompareAndBranch(key, syntaxNode, stringConstant, targetLabel, stringEqualityMethodRef); } }; _builder.EmitStringSwitchJumpTable( caseLabels: switchCaseLabels, fallThroughLabel: fallThroughLabel, key: key, keyHash: keyHash, emitStringCondBranchDelegate: emitStringCondBranchDelegate, computeStringHashcodeDelegate: SynthesizedStringSwitchHashMethod.ComputeStringHash); if (keyHash != null) { FreeTemp(keyHash); } } /// <summary> /// Delegate to emit string compare call and conditional branch based on the compare result. /// </summary> /// <param name="key">Key to compare</param> /// <param name="syntaxNode">Node for diagnostics.</param> /// <param name="stringConstant">Case constant to compare the key against</param> /// <param name="targetLabel">Target label to branch to if key = stringConstant</param> /// <param name="stringEqualityMethodRef">String equality method</param> private void EmitStringCompareAndBranch(LocalOrParameter key, SyntaxNode syntaxNode, ConstantValue stringConstant, object targetLabel, Microsoft.Cci.IReference stringEqualityMethodRef) { // Emit compare and branch: // if (key == stringConstant) // goto targetLabel; Debug.Assert(stringEqualityMethodRef != null); #if DEBUG var assertDiagnostics = DiagnosticBag.GetInstance(); Debug.Assert(stringEqualityMethodRef == _module.Translate((MethodSymbol)_module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__op_Equality), (CSharpSyntaxNode)syntaxNode, assertDiagnostics)); assertDiagnostics.Free(); #endif // static bool String.Equals(string a, string b) // pop 2 (a, b) // push 1 (bool return value) // stackAdjustment = (pushCount - popCount) = -1 _builder.EmitLoad(key); _builder.EmitConstantValue(stringConstant); _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1); _builder.EmitToken(stringEqualityMethodRef, syntaxNode, _diagnostics); // Branch to targetLabel if String.Equals returned true. _builder.EmitBranch(ILOpCode.Brtrue, targetLabel, ILOpCode.Brfalse); } /// <summary> /// Gets already declared and initialized local. /// </summary> private LocalDefinition GetLocal(BoundLocal localExpression) { var symbol = localExpression.LocalSymbol; return GetLocal(symbol); } private LocalDefinition GetLocal(LocalSymbol symbol) { return _builder.LocalSlotManager.GetLocal(symbol); } private LocalDefinition DefineLocal(LocalSymbol local, SyntaxNode syntaxNode) { var dynamicTransformFlags = !local.IsCompilerGenerated && local.Type.ContainsDynamic() ? CSharpCompilation.DynamicTransformsEncoder.Encode(local.Type, RefKind.None, 0) : ImmutableArray<bool>.Empty; var tupleElementNames = !local.IsCompilerGenerated && local.Type.ContainsTupleNames() ? CSharpCompilation.TupleNamesEncoder.Encode(local.Type) : ImmutableArray<string>.Empty; if (local.IsConst) { Debug.Assert(local.HasConstantValue); MetadataConstant compileTimeValue = _module.CreateConstant(local.Type, local.ConstantValue, syntaxNode, _diagnostics); LocalConstantDefinition localConstantDef = new LocalConstantDefinition( local.Name, local.Locations.FirstOrDefault() ?? Location.None, compileTimeValue, dynamicTransformFlags: dynamicTransformFlags, tupleElementNames: tupleElementNames); _builder.AddLocalConstantToScope(localConstantDef); return null; } if (IsStackLocal(local)) { return null; } LocalSlotConstraints constraints; Cci.ITypeReference translatedType; if (local.DeclarationKind == LocalDeclarationKind.FixedVariable && local.IsPinned) // Excludes pointer local and string local in fixed string case. { Debug.Assert(local.RefKind == RefKind.None); Debug.Assert(local.TypeWithAnnotations.Type.IsPointerType()); constraints = LocalSlotConstraints.ByRef | LocalSlotConstraints.Pinned; PointerTypeSymbol pointerType = (PointerTypeSymbol)local.Type; TypeSymbol pointedAtType = pointerType.PointedAtType; // We can't declare a reference to void, so if the pointed-at type is void, use native int // (represented here by IntPtr) instead. translatedType = pointedAtType.IsVoidType() ? _module.GetSpecialType(SpecialType.System_IntPtr, syntaxNode, _diagnostics) : _module.Translate(pointedAtType, syntaxNode, _diagnostics); } else { constraints = (local.IsPinned ? LocalSlotConstraints.Pinned : LocalSlotConstraints.None) | (local.RefKind != RefKind.None ? LocalSlotConstraints.ByRef : LocalSlotConstraints.None); translatedType = _module.Translate(local.Type, syntaxNode, _diagnostics); } // Even though we don't need the token immediately, we will need it later when signature for the local is emitted. // Also, requesting the token has side-effect of registering types used, which is critical for embedded types (NoPia, VBCore, etc). _module.GetFakeSymbolTokenForIL(translatedType, syntaxNode, _diagnostics); LocalDebugId localId; var name = GetLocalDebugName(local, out localId); var localDef = _builder.LocalSlotManager.DeclareLocal( type: translatedType, symbol: local, name: name, kind: local.SynthesizedKind, id: localId, pdbAttributes: local.SynthesizedKind.PdbAttributes(), constraints: constraints, dynamicTransformFlags: dynamicTransformFlags, tupleElementNames: tupleElementNames, isSlotReusable: local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release)); // If named, add it to the local debug scope. if (localDef.Name != null && !(local.SynthesizedKind == SynthesizedLocalKind.UserDefined && // Visibility scope of such locals is represented by BoundScope node. (local.ScopeDesignatorOpt?.Kind() is SyntaxKind.SwitchSection or SyntaxKind.SwitchExpressionArm))) { _builder.AddLocalToScope(localDef); } return localDef; } /// <summary> /// Gets the name and id of the local that are going to be generated into the debug metadata. /// </summary> private string GetLocalDebugName(ILocalSymbolInternal local, out LocalDebugId localId) { localId = LocalDebugId.None; if (local.IsImportedFromMetadata) { return local.Name; } var localKind = local.SynthesizedKind; // only user-defined locals should be named during lowering: Debug.Assert((local.Name == null) == (localKind != SynthesizedLocalKind.UserDefined)); // Generating debug names for instrumentation payloads should be allowed, as described in https://github.com/dotnet/roslyn/issues/11024. // For now, skip naming locals generated by instrumentation as they might not have a local syntax offset. // Locals generated by instrumentation might exist in methods which do not contain a body (auto property initializers). if (!localKind.IsLongLived() || localKind == SynthesizedLocalKind.InstrumentationPayload) { return null; } if (_ilEmitStyle == ILEmitStyle.Debug) { var syntax = local.GetDeclaratorSyntax(); int syntaxOffset = _method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(syntax), syntax.SyntaxTree); int ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(localKind, syntaxOffset); // user-defined locals should have 0 ordinal: Debug.Assert(ordinal == 0 || localKind != SynthesizedLocalKind.UserDefined); localId = new LocalDebugId(syntaxOffset, ordinal); } return local.Name ?? GeneratedNames.MakeSynthesizedLocalName(localKind, ref _uniqueNameId); } private bool IsSlotReusable(LocalSymbol local) { return local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release); } /// <summary> /// Releases a local. /// </summary> private void FreeLocal(LocalSymbol local) { // TODO: releasing named locals is NYI. if (local.Name == null && IsSlotReusable(local) && !IsStackLocal(local)) { _builder.LocalSlotManager.FreeLocal(local); } } /// <summary> /// Allocates a temp without identity. /// </summary> private LocalDefinition AllocateTemp(TypeSymbol type, SyntaxNode syntaxNode, LocalSlotConstraints slotConstraints = LocalSlotConstraints.None) { return _builder.LocalSlotManager.AllocateSlot( _module.Translate(type, syntaxNode, _diagnostics), slotConstraints); } /// <summary> /// Frees a temp. /// </summary> private void FreeTemp(LocalDefinition temp) { _builder.LocalSlotManager.FreeSlot(temp); } /// <summary> /// Frees an optional temp. /// </summary> private void FreeOptTemp(LocalDefinition temp) { if (temp != null) { FreeTemp(temp); } } /// <summary> /// Clones all labels used in a finally block. /// This allows creating an emittable clone of finally. /// It is safe to do because no branches can go in or out of the finally handler. /// </summary> private class FinallyCloner : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private Dictionary<LabelSymbol, GeneratedLabelSymbol> _labelClones; private FinallyCloner() { } /// <summary> /// The argument is BoundTryStatement (and not a BoundBlock) specifically /// to support only Finally blocks where it is guaranteed to not have incoming or leaving branches. /// </summary> public static BoundBlock MakeFinallyClone(BoundTryStatement node) { var cloner = new FinallyCloner(); return (BoundBlock)cloner.Visit(node.FinallyBlockOpt); } public override BoundNode VisitLabelStatement(BoundLabelStatement node) { return node.Update(GetLabelClone(node.Label)); } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { var labelClone = GetLabelClone(node.Label); // expressions do not contain labels or branches BoundExpression caseExpressionOpt = node.CaseExpressionOpt; // expressions do not contain labels or branches BoundLabel labelExpressionOpt = node.LabelExpressionOpt; return node.Update(labelClone, caseExpressionOpt, labelExpressionOpt); } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { var labelClone = GetLabelClone(node.Label); // expressions do not contain labels or branches BoundExpression condition = node.Condition; return node.Update(condition, node.JumpIfTrue, labelClone); } public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node) { // expressions do not contain labels or branches BoundExpression expression = node.Expression; var defaultClone = GetLabelClone(node.DefaultLabel); var casesBuilder = ArrayBuilder<(ConstantValue, LabelSymbol)>.GetInstance(); foreach (var (value, label) in node.Cases) { casesBuilder.Add((value, GetLabelClone(label))); } return node.Update(expression, casesBuilder.ToImmutableAndFree(), defaultClone, node.EqualityMethod); } public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) { // expressions do not contain labels or branches return node; } private GeneratedLabelSymbol GetLabelClone(LabelSymbol label) { var labelClones = _labelClones; if (labelClones == null) { _labelClones = labelClones = new Dictionary<LabelSymbol, GeneratedLabelSymbol>(); } GeneratedLabelSymbol clone; if (!labelClones.TryGetValue(label, out clone)) { clone = new GeneratedLabelSymbol("cloned_" + label.Name); labelClones.Add(label, clone); } return clone; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection.Metadata; using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; using static Microsoft.CodeAnalysis.CSharp.Binder; namespace Microsoft.CodeAnalysis.CSharp.CodeGen { internal partial class CodeGenerator { private void EmitStatement(BoundStatement statement) { switch (statement.Kind) { case BoundKind.Block: EmitBlock((BoundBlock)statement); break; case BoundKind.Scope: EmitScope((BoundScope)statement); break; case BoundKind.SequencePoint: this.EmitSequencePointStatement((BoundSequencePoint)statement); break; case BoundKind.SequencePointWithSpan: this.EmitSequencePointStatement((BoundSequencePointWithSpan)statement); break; case BoundKind.SavePreviousSequencePoint: this.EmitSavePreviousSequencePoint((BoundSavePreviousSequencePoint)statement); break; case BoundKind.RestorePreviousSequencePoint: this.EmitRestorePreviousSequencePoint((BoundRestorePreviousSequencePoint)statement); break; case BoundKind.StepThroughSequencePoint: this.EmitStepThroughSequencePoint((BoundStepThroughSequencePoint)statement); break; case BoundKind.ExpressionStatement: EmitExpression(((BoundExpressionStatement)statement).Expression, false); break; case BoundKind.StatementList: EmitStatementList((BoundStatementList)statement); break; case BoundKind.ReturnStatement: EmitReturnStatement((BoundReturnStatement)statement); break; case BoundKind.GotoStatement: EmitGotoStatement((BoundGotoStatement)statement); break; case BoundKind.LabelStatement: EmitLabelStatement((BoundLabelStatement)statement); break; case BoundKind.ConditionalGoto: EmitConditionalGoto((BoundConditionalGoto)statement); break; case BoundKind.ThrowStatement: EmitThrowStatement((BoundThrowStatement)statement); break; case BoundKind.TryStatement: EmitTryStatement((BoundTryStatement)statement); break; case BoundKind.SwitchDispatch: EmitSwitchDispatch((BoundSwitchDispatch)statement); break; case BoundKind.StateMachineScope: EmitStateMachineScope((BoundStateMachineScope)statement); break; case BoundKind.NoOpStatement: EmitNoOpStatement((BoundNoOpStatement)statement); break; default: // Code gen should not be invoked if there are errors. throw ExceptionUtilities.UnexpectedValue(statement.Kind); } #if DEBUG if (_stackLocals == null || _stackLocals.Count == 0) { _builder.AssertStackEmpty(); } #endif ReleaseExpressionTemps(); } private int EmitStatementAndCountInstructions(BoundStatement statement) { int n = _builder.InstructionsEmitted; this.EmitStatement(statement); return _builder.InstructionsEmitted - n; } private void EmitStatementList(BoundStatementList list) { for (int i = 0, n = list.Statements.Length; i < n; i++) { EmitStatement(list.Statements[i]); } } private void EmitNoOpStatement(BoundNoOpStatement statement) { switch (statement.Flavor) { case NoOpStatementFlavor.Default: if (_ilEmitStyle == ILEmitStyle.Debug) { _builder.EmitOpCode(ILOpCode.Nop); } break; case NoOpStatementFlavor.AwaitYieldPoint: Debug.Assert((_asyncYieldPoints == null) == (_asyncResumePoints == null)); if (_asyncYieldPoints == null) { _asyncYieldPoints = ArrayBuilder<int>.GetInstance(); _asyncResumePoints = ArrayBuilder<int>.GetInstance(); } Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count); _asyncYieldPoints.Add(_builder.AllocateILMarker()); break; case NoOpStatementFlavor.AwaitResumePoint: Debug.Assert(_asyncYieldPoints != null); Debug.Assert(_asyncYieldPoints != null); _asyncResumePoints.Add(_builder.AllocateILMarker()); Debug.Assert(_asyncYieldPoints.Count == _asyncResumePoints.Count); break; default: throw ExceptionUtilities.UnexpectedValue(statement.Flavor); } } private void EmitThrowStatement(BoundThrowStatement node) { EmitThrow(node.ExpressionOpt); } private void EmitThrow(BoundExpression thrown) { if (thrown != null) { this.EmitExpression(thrown, true); var exprType = thrown.Type; // Expression type will be null for "throw null;". if (exprType?.TypeKind == TypeKind.TypeParameter) { this.EmitBox(exprType, thrown.Syntax); } } _builder.EmitThrow(isRethrow: thrown == null); } private void EmitConditionalGoto(BoundConditionalGoto boundConditionalGoto) { object label = boundConditionalGoto.Label; Debug.Assert(label != null); EmitCondBranch(boundConditionalGoto.Condition, ref label, boundConditionalGoto.JumpIfTrue); } // 3.17 The brfalse instruction transfers control to target if value (of type int32, int64, object reference, managed //pointer, unmanaged pointer or native int) is zero (false). If value is non-zero (true), execution continues at //the next instruction. private static bool CanPassToBrfalse(TypeSymbol ts) { if (ts.IsEnumType()) { // valid enums are all primitives return true; } var tc = ts.PrimitiveTypeCode; switch (tc) { case Microsoft.Cci.PrimitiveTypeCode.Float32: case Microsoft.Cci.PrimitiveTypeCode.Float64: return false; case Microsoft.Cci.PrimitiveTypeCode.NotPrimitive: // if this is a generic type param, verifier will want us to box // EmitCondBranch knows that return ts.IsReferenceType; default: Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Invalid); Debug.Assert(tc != Microsoft.Cci.PrimitiveTypeCode.Void); return true; } } private static BoundExpression TryReduce(BoundBinaryOperator condition, ref bool sense) { var opKind = condition.OperatorKind.Operator(); Debug.Assert(opKind == BinaryOperatorKind.Equal || opKind == BinaryOperatorKind.NotEqual); BoundExpression nonConstOp; BoundExpression constOp = (condition.Left.ConstantValue != null) ? condition.Left : null; if (constOp != null) { nonConstOp = condition.Right; } else { constOp = (condition.Right.ConstantValue != null) ? condition.Right : null; if (constOp == null) { return null; } nonConstOp = condition.Left; } var nonConstType = nonConstOp.Type; if (!CanPassToBrfalse(nonConstType)) { return null; } bool isBool = nonConstType.PrimitiveTypeCode == Microsoft.Cci.PrimitiveTypeCode.Boolean; bool isZero = constOp.ConstantValue.IsDefaultValue; // bool is special, only it can be compared to true and false... if (!isBool && !isZero) { return null; } // if comparing to zero, flip the sense if (isZero) { sense = !sense; } // if comparing != flip the sense if (opKind == BinaryOperatorKind.NotEqual) { sense = !sense; } return nonConstOp; } private const int IL_OP_CODE_ROW_LENGTH = 4; private static readonly ILOpCode[] s_condJumpOpCodes = new ILOpCode[] { // < <= > >= ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Signed ILOpCode.Bge, ILOpCode.Bgt, ILOpCode.Ble, ILOpCode.Blt, // Signed Invert ILOpCode.Blt_un, ILOpCode.Ble_un, ILOpCode.Bgt_un, ILOpCode.Bge_un, // Unsigned ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Unsigned Invert ILOpCode.Blt, ILOpCode.Ble, ILOpCode.Bgt, ILOpCode.Bge, // Float ILOpCode.Bge_un, ILOpCode.Bgt_un, ILOpCode.Ble_un, ILOpCode.Blt_un, // Float Invert }; /// <summary> /// Produces opcode for a jump that corresponds to given operation and sense. /// Also produces a reverse opcode - opcode for the same condition with inverted sense. /// </summary> private static ILOpCode CodeForJump(BoundBinaryOperator op, bool sense, out ILOpCode revOpCode) { int opIdx; switch (op.OperatorKind.Operator()) { case BinaryOperatorKind.Equal: revOpCode = !sense ? ILOpCode.Beq : ILOpCode.Bne_un; return sense ? ILOpCode.Beq : ILOpCode.Bne_un; case BinaryOperatorKind.NotEqual: revOpCode = !sense ? ILOpCode.Bne_un : ILOpCode.Beq; return sense ? ILOpCode.Bne_un : ILOpCode.Beq; case BinaryOperatorKind.LessThan: opIdx = 0; break; case BinaryOperatorKind.LessThanOrEqual: opIdx = 1; break; case BinaryOperatorKind.GreaterThan: opIdx = 2; break; case BinaryOperatorKind.GreaterThanOrEqual: opIdx = 3; break; default: throw ExceptionUtilities.UnexpectedValue(op.OperatorKind.Operator()); } if (IsUnsignedBinaryOperator(op)) { opIdx += 2 * IL_OP_CODE_ROW_LENGTH; //unsigned } else if (IsFloat(op.OperatorKind)) { opIdx += 4 * IL_OP_CODE_ROW_LENGTH; //float } int revOpIdx = opIdx; if (!sense) { opIdx += IL_OP_CODE_ROW_LENGTH; //invert op } else { revOpIdx += IL_OP_CODE_ROW_LENGTH; //invert rev } revOpCode = s_condJumpOpCodes[revOpIdx]; return s_condJumpOpCodes[opIdx]; } // generate a jump to dest if (condition == sense) is true private void EmitCondBranch(BoundExpression condition, ref object dest, bool sense) { _recursionDepth++; if (_recursionDepth > 1) { StackGuard.EnsureSufficientExecutionStack(_recursionDepth); EmitCondBranchCore(condition, ref dest, sense); } else { EmitCondBranchCoreWithStackGuard(condition, ref dest, sense); } _recursionDepth--; } private void EmitCondBranchCoreWithStackGuard(BoundExpression condition, ref object dest, bool sense) { Debug.Assert(_recursionDepth == 1); try { EmitCondBranchCore(condition, ref dest, sense); Debug.Assert(_recursionDepth == 1); } catch (InsufficientExecutionStackException) { _diagnostics.Add(ErrorCode.ERR_InsufficientStack, BoundTreeVisitor.CancelledByStackGuardException.GetTooLongOrComplexExpressionErrorLocation(condition)); throw new EmitCancelledException(); } } private void EmitCondBranchCore(BoundExpression condition, ref object dest, bool sense) { oneMoreTime: ILOpCode ilcode; if (condition.ConstantValue != null) { bool taken = condition.ConstantValue.IsDefaultValue != sense; if (taken) { dest = dest ?? new object(); _builder.EmitBranch(ILOpCode.Br, dest); } else { // otherwise this branch will never be taken, so just fall through... } return; } switch (condition.Kind) { case BoundKind.BinaryOperator: var binOp = (BoundBinaryOperator)condition; bool testBothArgs = sense; switch (binOp.OperatorKind.OperatorWithLogical()) { case BinaryOperatorKind.LogicalOr: testBothArgs = !testBothArgs; // Fall through goto case BinaryOperatorKind.LogicalAnd; case BinaryOperatorKind.LogicalAnd: if (testBothArgs) { // gotoif(a != sense) fallThrough // gotoif(b == sense) dest // fallThrough: object fallThrough = null; EmitCondBranch(binOp.Left, ref fallThrough, !sense); EmitCondBranch(binOp.Right, ref dest, sense); if (fallThrough != null) { _builder.MarkLabel(fallThrough); } } else { // gotoif(a == sense) labDest // gotoif(b == sense) labDest EmitCondBranch(binOp.Left, ref dest, sense); condition = binOp.Right; goto oneMoreTime; } return; case BinaryOperatorKind.Equal: case BinaryOperatorKind.NotEqual: var reduced = TryReduce(binOp, ref sense); if (reduced != null) { condition = reduced; goto oneMoreTime; } // Fall through goto case BinaryOperatorKind.LessThan; case BinaryOperatorKind.LessThan: case BinaryOperatorKind.LessThanOrEqual: case BinaryOperatorKind.GreaterThan: case BinaryOperatorKind.GreaterThanOrEqual: EmitExpression(binOp.Left, true); EmitExpression(binOp.Right, true); ILOpCode revOpCode; ilcode = CodeForJump(binOp, sense, out revOpCode); dest = dest ?? new object(); _builder.EmitBranch(ilcode, dest, revOpCode); return; } // none of above. // then it is regular binary expression - Or, And, Xor ... goto default; case BoundKind.LoweredConditionalAccess: { var ca = (BoundLoweredConditionalAccess)condition; var receiver = ca.Receiver; var receiverType = receiver.Type; // we need a copy if we deal with nonlocal value (to capture the value) // or if we deal with stack local (reads are destructive) var complexCase = !receiverType.IsReferenceType || LocalRewriter.CanChangeValueBetweenReads(receiver, localsMayBeAssignedOrCaptured: false) || (receiver.Kind == BoundKind.Local && IsStackLocal(((BoundLocal)receiver).LocalSymbol)) || (ca.WhenNullOpt?.IsDefaultValue() == false); if (complexCase) { goto default; } if (sense) { // gotoif(receiver != null) fallThrough // gotoif(receiver.Access) dest // fallThrough: object fallThrough = null; EmitCondBranch(receiver, ref fallThrough, sense: false); // receiver is a reference type, and we only intend to read it EmitReceiverRef(receiver, AddressKind.ReadOnly); EmitCondBranch(ca.WhenNotNull, ref dest, sense: true); if (fallThrough != null) { _builder.MarkLabel(fallThrough); } } else { // gotoif(receiver == null) labDest // gotoif(!receiver.Access) labDest EmitCondBranch(receiver, ref dest, sense: false); // receiver is a reference type, and we only intend to read it EmitReceiverRef(receiver, AddressKind.ReadOnly); condition = ca.WhenNotNull; goto oneMoreTime; } } return; case BoundKind.UnaryOperator: var unOp = (BoundUnaryOperator)condition; if (unOp.OperatorKind == UnaryOperatorKind.BoolLogicalNegation) { sense = !sense; condition = unOp.Operand; goto oneMoreTime; } goto default; case BoundKind.IsOperator: var isOp = (BoundIsOperator)condition; var operand = isOp.Operand; EmitExpression(operand, true); Debug.Assert((object)operand.Type != null); if (!operand.Type.IsVerifierReference()) { // box the operand for isinst if it is not a verifier reference EmitBox(operand.Type, operand.Syntax); } _builder.EmitOpCode(ILOpCode.Isinst); EmitSymbolToken(isOp.TargetType.Type, isOp.TargetType.Syntax); ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse; dest = dest ?? new object(); _builder.EmitBranch(ilcode, dest); return; case BoundKind.Sequence: var seq = (BoundSequence)condition; EmitSequenceCondBranch(seq, ref dest, sense); return; default: EmitExpression(condition, true); var conditionType = condition.Type; if (conditionType.IsReferenceType && !conditionType.IsVerifierReference()) { EmitBox(conditionType, condition.Syntax); } ilcode = sense ? ILOpCode.Brtrue : ILOpCode.Brfalse; dest = dest ?? new object(); _builder.EmitBranch(ilcode, dest); return; } } private void EmitSequenceCondBranch(BoundSequence sequence, ref object dest, bool sense) { DefineLocals(sequence); EmitSideEffects(sequence); EmitCondBranch(sequence.Value, ref dest, sense); // sequence is used as a value, can release all locals FreeLocals(sequence); } private void EmitLabelStatement(BoundLabelStatement boundLabelStatement) { _builder.MarkLabel(boundLabelStatement.Label); } private void EmitGotoStatement(BoundGotoStatement boundGotoStatement) { _builder.EmitBranch(ILOpCode.Br, boundGotoStatement.Label); } // used by HandleReturn method which tries to inject // indirect ret sequence as a last statement in the block // that is the last statement of the current method // NOTE: it is important that there is no code after this "ret" // it is desirable, for debug purposes, that this ret is emitted inside top level { } private bool IsLastBlockInMethod(BoundBlock block) { if (_boundBody == block) { return true; } //sometimes top level node is a statement list containing //epilogue and then a block. If we are having that block, it will do. var list = _boundBody as BoundStatementList; if (list != null && list.Statements.LastOrDefault() == block) { return true; } return false; } private void EmitBlock(BoundBlock block) { var hasLocals = !block.Locals.IsEmpty; if (hasLocals) { _builder.OpenLocalScope(); foreach (var local in block.Locals) { Debug.Assert(local.RefKind == RefKind.None || local.SynthesizedKind.IsLongLived(), "A ref local ended up in a block and claims it is shortlived. That is dangerous. Are we sure it is short lived?"); var declaringReferences = local.DeclaringSyntaxReferences; DefineLocal(local, !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : block.Syntax); } } EmitStatements(block.Statements); if (_indirectReturnState == IndirectReturnState.Needed && IsLastBlockInMethod(block)) { HandleReturn(); } if (hasLocals) { foreach (var local in block.Locals) { FreeLocal(local); } _builder.CloseLocalScope(); } } private void EmitStatements(ImmutableArray<BoundStatement> statements) { foreach (var statement in statements) { EmitStatement(statement); } } private void EmitScope(BoundScope block) { Debug.Assert(!block.Locals.IsEmpty); _builder.OpenLocalScope(); foreach (var local in block.Locals) { Debug.Assert(local.Name != null); Debug.Assert(local.SynthesizedKind == SynthesizedLocalKind.UserDefined && (local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchSection || local.ScopeDesignatorOpt?.Kind() == SyntaxKind.SwitchExpressionArm)); if (!local.IsConst && !IsStackLocal(local)) { _builder.AddLocalToScope(_builder.LocalSlotManager.GetLocal(local)); } } EmitStatements(block.Statements); _builder.CloseLocalScope(); } private void EmitStateMachineScope(BoundStateMachineScope scope) { _builder.OpenLocalScope(ScopeType.StateMachineVariable); foreach (var field in scope.Fields) { if (field.SlotIndex >= 0) { _builder.DefineUserDefinedStateMachineHoistedLocal(field.SlotIndex); } } EmitStatement(scope.Statement); _builder.CloseLocalScope(); } // There are two ways a value can be returned from a function: // - Using ret opcode // - Store return value if any to a predefined temp and jump to the epilogue block // Sometimes ret is not an option (try/catch etc.). We also do this when emitting // debuggable code. This function is a stub for the logic that decides that. private bool ShouldUseIndirectReturn() { // If the method/lambda body is a block we define a sequence point for the closing brace of the body // and associate it with the ret instruction. If there is a return statement we need to store the value // to a long-lived synthesized local since a sequence point requires an empty evaluation stack. // // The emitted pattern is: // <evaluate return statement expression> // stloc $ReturnValue // ldloc $ReturnValue // sequence point // ret // // Do not emit this pattern if the method doesn't include user code or doesn't have a block body. return _ilEmitStyle == ILEmitStyle.Debug && _method.GenerateDebugInfo && _methodBodySyntaxOpt?.IsKind(SyntaxKind.Block) == true || _builder.InExceptionHandler; } // Compiler generated return mapped to a block is very likely the synthetic return // that was added at the end of the last block of a void method by analysis. // This is likely to be the last return in the method, so if we have not yet // emitted return sequence, it is convenient to do it right here (if we can). private bool CanHandleReturnLabel(BoundReturnStatement boundReturnStatement) { return boundReturnStatement.WasCompilerGenerated && (boundReturnStatement.Syntax.IsKind(SyntaxKind.Block) || _method?.IsImplicitConstructor == true) && !_builder.InExceptionHandler; } private void EmitReturnStatement(BoundReturnStatement boundReturnStatement) { var expressionOpt = boundReturnStatement.ExpressionOpt; if (boundReturnStatement.RefKind == RefKind.None) { this.EmitExpression(expressionOpt, true); } else { // NOTE: passing "ReadOnlyStrict" here. // we should never return an address of a copy var unexpectedTemp = this.EmitAddress(expressionOpt, this._method.RefKind == RefKind.RefReadOnly ? AddressKind.ReadOnlyStrict : AddressKind.Writeable); Debug.Assert(unexpectedTemp == null, "ref-returning a temp?"); } if (ShouldUseIndirectReturn()) { if (expressionOpt != null) { _builder.EmitLocalStore(LazyReturnTemp); } if (_indirectReturnState != IndirectReturnState.Emitted && CanHandleReturnLabel(boundReturnStatement)) { HandleReturn(); } else { _builder.EmitBranch(ILOpCode.Br, s_returnLabel); if (_indirectReturnState == IndirectReturnState.NotNeeded) { _indirectReturnState = IndirectReturnState.Needed; } } } else { if (_indirectReturnState == IndirectReturnState.Needed && CanHandleReturnLabel(boundReturnStatement)) { if (expressionOpt != null) { _builder.EmitLocalStore(LazyReturnTemp); } HandleReturn(); } else { if (expressionOpt != null) { // Ensure the return type has been translated. (Necessary // for cases of untranslated anonymous types.) _module.Translate(expressionOpt.Type, boundReturnStatement.Syntax, _diagnostics); } _builder.EmitRet(expressionOpt == null); } } } private void EmitTryStatement(BoundTryStatement statement, bool emitCatchesOnly = false) { Debug.Assert(!statement.CatchBlocks.IsDefault); // Stack must be empty at beginning of try block. _builder.AssertStackEmpty(); // IL requires catches and finally block to be distinct try // blocks so if the source contained both a catch and // a finally, nested scopes are emitted. bool emitNestedScopes = (!emitCatchesOnly && (statement.CatchBlocks.Length > 0) && (statement.FinallyBlockOpt != null)); _builder.OpenLocalScope(ScopeType.TryCatchFinally); _builder.OpenLocalScope(ScopeType.Try); // IL requires catches and finally block to be distinct try // blocks so if the source contained both a catch and // a finally, nested scopes are emitted. _tryNestingLevel++; if (emitNestedScopes) { EmitTryStatement(statement, emitCatchesOnly: true); } else { EmitBlock(statement.TryBlock); } _tryNestingLevel--; // Close the Try scope _builder.CloseLocalScope(); if (!emitNestedScopes) { foreach (var catchBlock in statement.CatchBlocks) { EmitCatchBlock(catchBlock); } } if (!emitCatchesOnly && (statement.FinallyBlockOpt != null)) { _builder.OpenLocalScope(statement.PreferFaultHandler ? ScopeType.Fault : ScopeType.Finally); EmitBlock(statement.FinallyBlockOpt); // close Finally scope _builder.CloseLocalScope(); // close the whole try statement scope _builder.CloseLocalScope(); // in a case where we emit surrogate Finally using Fault, we emit code like this // // try{ // . . . // } fault { // finallyBlock; // } // finallyBlock; // // This is where the second copy of finallyBlock is emitted. if (statement.PreferFaultHandler) { var finallyClone = FinallyCloner.MakeFinallyClone(statement); EmitBlock(finallyClone); } } else { // close the whole try statement scope _builder.CloseLocalScope(); } } /// <remarks> /// The interesting part in the following method is the support for exception filters. /// === Example: /// /// try /// { /// TryBlock /// } /// catch (ExceptionType ex) when (Condition) /// { /// Handler /// } /// /// gets emitted as something like ===> /// /// Try /// TryBlock /// Filter /// var tmp = Pop() as {ExceptionType} /// if (tmp == null) /// { /// Push 0 /// } /// else /// { /// ex = tmp /// Push Condition ? 1 : 0 /// } /// End Filter // leaves 1 or 0 on the stack /// Catch // gets called after finalization of nested exception frames if condition above produced 1 /// Pop // CLR pushes the exception object again /// variable ex can be used here /// Handler /// EndCatch /// /// When evaluating `Condition` requires additional statements be executed first, those /// statements are stored in `catchBlock.ExceptionFilterPrologueOpt` and emitted before the condition. /// </remarks> private void EmitCatchBlock(BoundCatchBlock catchBlock) { object typeCheckFailedLabel = null; _builder.AdjustStack(1); // Account for exception on the stack. // Open appropriate exception handler scope. (Catch or Filter) // if it is a Filter, emit prologue that checks if the type on the stack // converts to what we want. if (catchBlock.ExceptionFilterOpt == null) { var exceptionType = ((object)catchBlock.ExceptionTypeOpt != null) ? _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics) : _module.GetSpecialType(SpecialType.System_Object, catchBlock.Syntax, _diagnostics); _builder.OpenLocalScope(ScopeType.Catch, exceptionType); RecordAsyncCatchHandlerOffset(catchBlock); // Dev12 inserts the sequence point on catch clause without a filter, just before // the exception object is assigned to the variable. // // Also in Dev12 the exception variable scope span starts right after the stloc instruction and // ends right before leave instruction. So when stopped at the sequence point Dev12 inserts, // the exception variable is not visible. if (_emitPdbSequencePoints) { var syntax = catchBlock.Syntax as CatchClauseSyntax; if (syntax != null) { TextSpan spSpan; var declaration = syntax.Declaration; if (declaration == null) { spSpan = syntax.CatchKeyword.Span; } else { spSpan = TextSpan.FromBounds(syntax.SpanStart, syntax.Declaration.Span.End); } this.EmitSequencePoint(catchBlock.SyntaxTree, spSpan); } } } else { _builder.OpenLocalScope(ScopeType.Filter); RecordAsyncCatchHandlerOffset(catchBlock); // Filtering starts with simulating regular catch through a // type check. If this is not our type then we are done. var typeCheckPassedLabel = new object(); typeCheckFailedLabel = new object(); if ((object)catchBlock.ExceptionTypeOpt != null) { var exceptionType = _module.Translate(catchBlock.ExceptionTypeOpt, catchBlock.Syntax, _diagnostics); _builder.EmitOpCode(ILOpCode.Isinst); _builder.EmitToken(exceptionType, catchBlock.Syntax, _diagnostics); _builder.EmitOpCode(ILOpCode.Dup); _builder.EmitBranch(ILOpCode.Brtrue, typeCheckPassedLabel); _builder.EmitOpCode(ILOpCode.Pop); _builder.EmitIntConstant(0); _builder.EmitBranch(ILOpCode.Br, typeCheckFailedLabel); } else { // no formal exception type means we always pass the check } _builder.MarkLabel(typeCheckPassedLabel); } foreach (var local in catchBlock.Locals) { var declaringReferences = local.DeclaringSyntaxReferences; var localSyntax = !declaringReferences.IsEmpty ? (CSharpSyntaxNode)declaringReferences[0].GetSyntax() : catchBlock.Syntax; DefineLocal(local, localSyntax); } var exceptionSourceOpt = catchBlock.ExceptionSourceOpt; if (exceptionSourceOpt != null) { // here we have our exception on the stack in a form of a reference type (O) // it means that we have to "unbox" it before storing to the local // if exception's type is a generic type parameter. if (!exceptionSourceOpt.Type.IsVerifierReference()) { Debug.Assert(exceptionSourceOpt.Type.IsTypeParameter()); // only expecting type parameters _builder.EmitOpCode(ILOpCode.Unbox_any); EmitSymbolToken(exceptionSourceOpt.Type, exceptionSourceOpt.Syntax); } BoundExpression exceptionSource = exceptionSourceOpt; while (exceptionSource.Kind == BoundKind.Sequence) { var seq = (BoundSequence)exceptionSource; Debug.Assert(seq.Locals.IsDefaultOrEmpty); EmitSideEffects(seq); exceptionSource = seq.Value; } switch (exceptionSource.Kind) { case BoundKind.Local: var exceptionSourceLocal = (BoundLocal)exceptionSource; Debug.Assert(exceptionSourceLocal.LocalSymbol.RefKind == RefKind.None); if (!IsStackLocal(exceptionSourceLocal.LocalSymbol)) { _builder.EmitLocalStore(GetLocal(exceptionSourceLocal)); } break; case BoundKind.FieldAccess: var left = (BoundFieldAccess)exceptionSource; Debug.Assert(!left.FieldSymbol.IsStatic, "Not supported"); Debug.Assert(!left.ReceiverOpt.Type.IsTypeParameter()); var stateMachineField = left.FieldSymbol as StateMachineFieldSymbol; if (((object)stateMachineField != null) && (stateMachineField.SlotIndex >= 0)) { _builder.DefineUserDefinedStateMachineHoistedLocal(stateMachineField.SlotIndex); } // When assigning to a field // we need to push param address below the exception var temp = AllocateTemp(exceptionSource.Type, exceptionSource.Syntax); _builder.EmitLocalStore(temp); var receiverTemp = EmitReceiverRef(left.ReceiverOpt, AddressKind.Writeable); Debug.Assert(receiverTemp == null); _builder.EmitLocalLoad(temp); FreeTemp(temp); EmitFieldStore(left); break; default: throw ExceptionUtilities.UnexpectedValue(exceptionSource.Kind); } } else { _builder.EmitOpCode(ILOpCode.Pop); } if (catchBlock.ExceptionFilterPrologueOpt != null) { Debug.Assert(_builder.IsStackEmpty); EmitStatements(catchBlock.ExceptionFilterPrologueOpt.Statements); } // Emit the actual filter expression, if we have one, and normalize // results. if (catchBlock.ExceptionFilterOpt != null) { EmitCondExpr(catchBlock.ExceptionFilterOpt, true); // Normalize the return value because values other than 0 or 1 // produce unspecified results. _builder.EmitIntConstant(0); _builder.EmitOpCode(ILOpCode.Cgt_un); _builder.MarkLabel(typeCheckFailedLabel); // Now we are starting the actual handler _builder.MarkFilterConditionEnd(); // Pop the exception; it should have already been stored to the // variable by the filter. _builder.EmitOpCode(ILOpCode.Pop); } EmitBlock(catchBlock.Body); _builder.CloseLocalScope(); } private void RecordAsyncCatchHandlerOffset(BoundCatchBlock catchBlock) { if (catchBlock.IsSynthesizedAsyncCatchAll) { Debug.Assert(_asyncCatchHandlerOffset < 0); // only one expected _asyncCatchHandlerOffset = _builder.AllocateILMarker(); } } private void EmitSwitchDispatch(BoundSwitchDispatch dispatch) { // Switch expression must have a valid switch governing type Debug.Assert((object)dispatch.Expression.Type != null); Debug.Assert(dispatch.Expression.Type.IsValidV6SwitchGoverningType()); // We must have rewritten nullable switch expression into non-nullable constructs. Debug.Assert(!dispatch.Expression.Type.IsNullableType()); // This must be used only for nontrivial dispatches. Debug.Assert(dispatch.Cases.Any()); EmitSwitchHeader( dispatch.Expression, dispatch.Cases.Select(p => new KeyValuePair<ConstantValue, object>(p.value, p.label)).ToArray(), dispatch.DefaultLabel, dispatch.EqualityMethod); } private void EmitSwitchHeader( BoundExpression expression, KeyValuePair<ConstantValue, object>[] switchCaseLabels, LabelSymbol fallThroughLabel, MethodSymbol equalityMethod) { Debug.Assert(expression.ConstantValue == null); Debug.Assert((object)expression.Type != null && expression.Type.IsValidV6SwitchGoverningType()); Debug.Assert(switchCaseLabels.Length > 0); Debug.Assert(switchCaseLabels != null); LocalDefinition temp = null; LocalOrParameter key; BoundSequence sequence = null; if (expression.Kind == BoundKind.Sequence) { sequence = (BoundSequence)expression; DefineLocals(sequence); EmitSideEffects(sequence); expression = sequence.Value; } if (expression.Kind == BoundKind.SequencePointExpression) { var sequencePointExpression = (BoundSequencePointExpression)expression; EmitSequencePoint(sequencePointExpression); expression = sequencePointExpression.Expression; } switch (expression.Kind) { case BoundKind.Local: var local = ((BoundLocal)expression).LocalSymbol; if (local.RefKind == RefKind.None && !IsStackLocal(local)) { key = this.GetLocal(local); break; } goto default; case BoundKind.Parameter: var parameter = (BoundParameter)expression; if (parameter.ParameterSymbol.RefKind == RefKind.None) { key = ParameterSlot(parameter); break; } goto default; default: EmitExpression(expression, true); temp = AllocateTemp(expression.Type, expression.Syntax); _builder.EmitLocalStore(temp); key = temp; break; } // Emit switch jump table if (expression.Type.SpecialType != SpecialType.System_String) { _builder.EmitIntegerSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Type.EnumUnderlyingTypeOrSelf().PrimitiveTypeCode); } else { this.EmitStringSwitchJumpTable(switchCaseLabels, fallThroughLabel, key, expression.Syntax, equalityMethod); } if (temp != null) { FreeTemp(temp); } if (sequence != null) { // sequence was used as a value, can release all its locals. FreeLocals(sequence); } } private void EmitStringSwitchJumpTable( KeyValuePair<ConstantValue, object>[] switchCaseLabels, LabelSymbol fallThroughLabel, LocalOrParameter key, SyntaxNode syntaxNode, MethodSymbol equalityMethod) { LocalDefinition keyHash = null; // Condition is necessary, but not sufficient (e.g. might be missing a special or well-known member). if (SwitchStringJumpTableEmitter.ShouldGenerateHashTableSwitch(_module, switchCaseLabels.Length)) { Debug.Assert(_module.SupportsPrivateImplClass); var privateImplClass = _module.GetPrivateImplClass(syntaxNode, _diagnostics); Cci.IReference stringHashMethodRef = privateImplClass.GetMethod(PrivateImplementationDetails.SynthesizedStringHashFunctionName); // Heuristics and well-known member availability determine the existence // of this helper. Rather than reproduce that (language-specific) logic here, // we simply check for the information we really want - whether the helper is // available. if (stringHashMethodRef != null) { // static uint ComputeStringHash(string s) // pop 1 (s) // push 1 (uint return value) // stackAdjustment = (pushCount - popCount) = 0 _builder.EmitLoad(key); _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: 0); _builder.EmitToken(stringHashMethodRef, syntaxNode, _diagnostics); var UInt32Type = _module.Compilation.GetSpecialType(SpecialType.System_UInt32); keyHash = AllocateTemp(UInt32Type, syntaxNode); _builder.EmitLocalStore(keyHash); } } Cci.IReference stringEqualityMethodRef = _module.Translate(equalityMethod, syntaxNode, _diagnostics); Cci.IMethodReference stringLengthRef = null; var stringLengthMethod = _module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__Length) as MethodSymbol; if (stringLengthMethod != null && !stringLengthMethod.HasUseSiteError) { stringLengthRef = _module.Translate(stringLengthMethod, syntaxNode, _diagnostics); } SwitchStringJumpTableEmitter.EmitStringCompareAndBranch emitStringCondBranchDelegate = (keyArg, stringConstant, targetLabel) => { if (stringConstant == ConstantValue.Null) { // if (key == null) // goto targetLabel _builder.EmitLoad(keyArg); _builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue); } else if (stringConstant.StringValue.Length == 0 && stringLengthRef != null) { // if (key != null && key.Length == 0) // goto targetLabel object skipToNext = new object(); _builder.EmitLoad(keyArg); _builder.EmitBranch(ILOpCode.Brfalse, skipToNext, ILOpCode.Brtrue); _builder.EmitLoad(keyArg); // Stack: key --> length _builder.EmitOpCode(ILOpCode.Call, 0); var diag = DiagnosticBag.GetInstance(); _builder.EmitToken(stringLengthRef, null, diag); Debug.Assert(diag.IsEmptyWithoutResolution); diag.Free(); _builder.EmitBranch(ILOpCode.Brfalse, targetLabel, ILOpCode.Brtrue); _builder.MarkLabel(skipToNext); } else { this.EmitStringCompareAndBranch(key, syntaxNode, stringConstant, targetLabel, stringEqualityMethodRef); } }; _builder.EmitStringSwitchJumpTable( caseLabels: switchCaseLabels, fallThroughLabel: fallThroughLabel, key: key, keyHash: keyHash, emitStringCondBranchDelegate: emitStringCondBranchDelegate, computeStringHashcodeDelegate: SynthesizedStringSwitchHashMethod.ComputeStringHash); if (keyHash != null) { FreeTemp(keyHash); } } /// <summary> /// Delegate to emit string compare call and conditional branch based on the compare result. /// </summary> /// <param name="key">Key to compare</param> /// <param name="syntaxNode">Node for diagnostics.</param> /// <param name="stringConstant">Case constant to compare the key against</param> /// <param name="targetLabel">Target label to branch to if key = stringConstant</param> /// <param name="stringEqualityMethodRef">String equality method</param> private void EmitStringCompareAndBranch(LocalOrParameter key, SyntaxNode syntaxNode, ConstantValue stringConstant, object targetLabel, Microsoft.Cci.IReference stringEqualityMethodRef) { // Emit compare and branch: // if (key == stringConstant) // goto targetLabel; Debug.Assert(stringEqualityMethodRef != null); #if DEBUG var assertDiagnostics = DiagnosticBag.GetInstance(); Debug.Assert(stringEqualityMethodRef == _module.Translate((MethodSymbol)_module.Compilation.GetSpecialTypeMember(SpecialMember.System_String__op_Equality), (CSharpSyntaxNode)syntaxNode, assertDiagnostics)); assertDiagnostics.Free(); #endif // static bool String.Equals(string a, string b) // pop 2 (a, b) // push 1 (bool return value) // stackAdjustment = (pushCount - popCount) = -1 _builder.EmitLoad(key); _builder.EmitConstantValue(stringConstant); _builder.EmitOpCode(ILOpCode.Call, stackAdjustment: -1); _builder.EmitToken(stringEqualityMethodRef, syntaxNode, _diagnostics); // Branch to targetLabel if String.Equals returned true. _builder.EmitBranch(ILOpCode.Brtrue, targetLabel, ILOpCode.Brfalse); } /// <summary> /// Gets already declared and initialized local. /// </summary> private LocalDefinition GetLocal(BoundLocal localExpression) { var symbol = localExpression.LocalSymbol; return GetLocal(symbol); } private LocalDefinition GetLocal(LocalSymbol symbol) { return _builder.LocalSlotManager.GetLocal(symbol); } private LocalDefinition DefineLocal(LocalSymbol local, SyntaxNode syntaxNode) { var dynamicTransformFlags = !local.IsCompilerGenerated && local.Type.ContainsDynamic() ? CSharpCompilation.DynamicTransformsEncoder.Encode(local.Type, RefKind.None, 0) : ImmutableArray<bool>.Empty; var tupleElementNames = !local.IsCompilerGenerated && local.Type.ContainsTupleNames() ? CSharpCompilation.TupleNamesEncoder.Encode(local.Type) : ImmutableArray<string>.Empty; if (local.IsConst) { Debug.Assert(local.HasConstantValue); MetadataConstant compileTimeValue = _module.CreateConstant(local.Type, local.ConstantValue, syntaxNode, _diagnostics); LocalConstantDefinition localConstantDef = new LocalConstantDefinition( local.Name, local.Locations.FirstOrDefault() ?? Location.None, compileTimeValue, dynamicTransformFlags: dynamicTransformFlags, tupleElementNames: tupleElementNames); _builder.AddLocalConstantToScope(localConstantDef); return null; } if (IsStackLocal(local)) { return null; } LocalSlotConstraints constraints; Cci.ITypeReference translatedType; if (local.DeclarationKind == LocalDeclarationKind.FixedVariable && local.IsPinned) // Excludes pointer local and string local in fixed string case. { Debug.Assert(local.RefKind == RefKind.None); Debug.Assert(local.TypeWithAnnotations.Type.IsPointerType()); constraints = LocalSlotConstraints.ByRef | LocalSlotConstraints.Pinned; PointerTypeSymbol pointerType = (PointerTypeSymbol)local.Type; TypeSymbol pointedAtType = pointerType.PointedAtType; // We can't declare a reference to void, so if the pointed-at type is void, use native int // (represented here by IntPtr) instead. translatedType = pointedAtType.IsVoidType() ? _module.GetSpecialType(SpecialType.System_IntPtr, syntaxNode, _diagnostics) : _module.Translate(pointedAtType, syntaxNode, _diagnostics); } else { constraints = (local.IsPinned ? LocalSlotConstraints.Pinned : LocalSlotConstraints.None) | (local.RefKind != RefKind.None ? LocalSlotConstraints.ByRef : LocalSlotConstraints.None); translatedType = _module.Translate(local.Type, syntaxNode, _diagnostics); } // Even though we don't need the token immediately, we will need it later when signature for the local is emitted. // Also, requesting the token has side-effect of registering types used, which is critical for embedded types (NoPia, VBCore, etc). _module.GetFakeSymbolTokenForIL(translatedType, syntaxNode, _diagnostics); LocalDebugId localId; var name = GetLocalDebugName(local, out localId); var localDef = _builder.LocalSlotManager.DeclareLocal( type: translatedType, symbol: local, name: name, kind: local.SynthesizedKind, id: localId, pdbAttributes: local.SynthesizedKind.PdbAttributes(), constraints: constraints, dynamicTransformFlags: dynamicTransformFlags, tupleElementNames: tupleElementNames, isSlotReusable: local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release)); // If named, add it to the local debug scope. if (localDef.Name != null && !(local.SynthesizedKind == SynthesizedLocalKind.UserDefined && // Visibility scope of such locals is represented by BoundScope node. (local.ScopeDesignatorOpt?.Kind() is SyntaxKind.SwitchSection or SyntaxKind.SwitchExpressionArm))) { _builder.AddLocalToScope(localDef); } return localDef; } /// <summary> /// Gets the name and id of the local that are going to be generated into the debug metadata. /// </summary> private string GetLocalDebugName(ILocalSymbolInternal local, out LocalDebugId localId) { localId = LocalDebugId.None; if (local.IsImportedFromMetadata) { return local.Name; } var localKind = local.SynthesizedKind; // only user-defined locals should be named during lowering: Debug.Assert((local.Name == null) == (localKind != SynthesizedLocalKind.UserDefined)); // Generating debug names for instrumentation payloads should be allowed, as described in https://github.com/dotnet/roslyn/issues/11024. // For now, skip naming locals generated by instrumentation as they might not have a local syntax offset. // Locals generated by instrumentation might exist in methods which do not contain a body (auto property initializers). if (!localKind.IsLongLived() || localKind == SynthesizedLocalKind.InstrumentationPayload) { return null; } if (_ilEmitStyle == ILEmitStyle.Debug) { var syntax = local.GetDeclaratorSyntax(); int syntaxOffset = _method.CalculateLocalSyntaxOffset(LambdaUtilities.GetDeclaratorPosition(syntax), syntax.SyntaxTree); int ordinal = _synthesizedLocalOrdinals.AssignLocalOrdinal(localKind, syntaxOffset); // user-defined locals should have 0 ordinal: Debug.Assert(ordinal == 0 || localKind != SynthesizedLocalKind.UserDefined); localId = new LocalDebugId(syntaxOffset, ordinal); } return local.Name ?? GeneratedNames.MakeSynthesizedLocalName(localKind, ref _uniqueNameId); } private bool IsSlotReusable(LocalSymbol local) { return local.SynthesizedKind.IsSlotReusable(_ilEmitStyle != ILEmitStyle.Release); } /// <summary> /// Releases a local. /// </summary> private void FreeLocal(LocalSymbol local) { // TODO: releasing named locals is NYI. if (local.Name == null && IsSlotReusable(local) && !IsStackLocal(local)) { _builder.LocalSlotManager.FreeLocal(local); } } /// <summary> /// Allocates a temp without identity. /// </summary> private LocalDefinition AllocateTemp(TypeSymbol type, SyntaxNode syntaxNode, LocalSlotConstraints slotConstraints = LocalSlotConstraints.None) { return _builder.LocalSlotManager.AllocateSlot( _module.Translate(type, syntaxNode, _diagnostics), slotConstraints); } /// <summary> /// Frees a temp. /// </summary> private void FreeTemp(LocalDefinition temp) { _builder.LocalSlotManager.FreeSlot(temp); } /// <summary> /// Frees an optional temp. /// </summary> private void FreeOptTemp(LocalDefinition temp) { if (temp != null) { FreeTemp(temp); } } /// <summary> /// Clones all labels used in a finally block. /// This allows creating an emittable clone of finally. /// It is safe to do because no branches can go in or out of the finally handler. /// </summary> private class FinallyCloner : BoundTreeRewriterWithStackGuardWithoutRecursionOnTheLeftOfBinaryOperator { private Dictionary<LabelSymbol, GeneratedLabelSymbol> _labelClones; private FinallyCloner() { } /// <summary> /// The argument is BoundTryStatement (and not a BoundBlock) specifically /// to support only Finally blocks where it is guaranteed to not have incoming or leaving branches. /// </summary> public static BoundBlock MakeFinallyClone(BoundTryStatement node) { var cloner = new FinallyCloner(); return (BoundBlock)cloner.Visit(node.FinallyBlockOpt); } public override BoundNode VisitLabelStatement(BoundLabelStatement node) { return node.Update(GetLabelClone(node.Label)); } public override BoundNode VisitGotoStatement(BoundGotoStatement node) { var labelClone = GetLabelClone(node.Label); // expressions do not contain labels or branches BoundExpression caseExpressionOpt = node.CaseExpressionOpt; // expressions do not contain labels or branches BoundLabel labelExpressionOpt = node.LabelExpressionOpt; return node.Update(labelClone, caseExpressionOpt, labelExpressionOpt); } public override BoundNode VisitConditionalGoto(BoundConditionalGoto node) { var labelClone = GetLabelClone(node.Label); // expressions do not contain labels or branches BoundExpression condition = node.Condition; return node.Update(condition, node.JumpIfTrue, labelClone); } public override BoundNode VisitSwitchDispatch(BoundSwitchDispatch node) { // expressions do not contain labels or branches BoundExpression expression = node.Expression; var defaultClone = GetLabelClone(node.DefaultLabel); var casesBuilder = ArrayBuilder<(ConstantValue, LabelSymbol)>.GetInstance(); foreach (var (value, label) in node.Cases) { casesBuilder.Add((value, GetLabelClone(label))); } return node.Update(expression, casesBuilder.ToImmutableAndFree(), defaultClone, node.EqualityMethod); } public override BoundNode VisitExpressionStatement(BoundExpressionStatement node) { // expressions do not contain labels or branches return node; } private GeneratedLabelSymbol GetLabelClone(LabelSymbol label) { var labelClones = _labelClones; if (labelClones == null) { _labelClones = labelClones = new Dictionary<LabelSymbol, GeneratedLabelSymbol>(); } GeneratedLabelSymbol clone; if (!labelClones.TryGetValue(label, out clone)) { clone = new GeneratedLabelSymbol("cloned_" + label.Name); labelClones.Add(label, clone); } return clone; } } } }
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Workspaces/Core/Portable/Shared/Utilities/AsyncBatchingWorkQueue`1.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Roslyn.Utilities { /// <inheritdoc cref="AsyncBatchingWorkQueue{TItem, TResult}"/> internal class AsyncBatchingWorkQueue<TItem> : AsyncBatchingWorkQueue<TItem, VoidResult> { public AsyncBatchingWorkQueue( TimeSpan delay, Func<ImmutableArray<TItem>, CancellationToken, ValueTask> processBatchAsync, IAsynchronousOperationListener asyncListener, CancellationToken cancellationToken) : this(delay, processBatchAsync, equalityComparer: null, asyncListener, cancellationToken) { } public AsyncBatchingWorkQueue( TimeSpan delay, Func<ImmutableArray<TItem>, CancellationToken, ValueTask> processBatchAsync, IEqualityComparer<TItem>? equalityComparer, IAsynchronousOperationListener asyncListener, CancellationToken cancellationToken) : base(delay, Convert(processBatchAsync), equalityComparer, asyncListener, cancellationToken) { } private static Func<ImmutableArray<TItem>, CancellationToken, ValueTask<VoidResult>> Convert(Func<ImmutableArray<TItem>, CancellationToken, ValueTask> processBatchAsync) => async (items, ct) => { await processBatchAsync(items, ct).ConfigureAwait(false); return default; }; public new Task WaitUntilCurrentBatchCompletesAsync() => base.WaitUntilCurrentBatchCompletesAsync(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.TestHooks; namespace Roslyn.Utilities { /// <inheritdoc cref="AsyncBatchingWorkQueue{TItem, TResult}"/> internal class AsyncBatchingWorkQueue<TItem> : AsyncBatchingWorkQueue<TItem, VoidResult> { public AsyncBatchingWorkQueue( TimeSpan delay, Func<ImmutableArray<TItem>, CancellationToken, ValueTask> processBatchAsync, IAsynchronousOperationListener asyncListener, CancellationToken cancellationToken) : this(delay, processBatchAsync, equalityComparer: null, asyncListener, cancellationToken) { } public AsyncBatchingWorkQueue( TimeSpan delay, Func<ImmutableArray<TItem>, CancellationToken, ValueTask> processBatchAsync, IEqualityComparer<TItem>? equalityComparer, IAsynchronousOperationListener asyncListener, CancellationToken cancellationToken) : base(delay, Convert(processBatchAsync), equalityComparer, asyncListener, cancellationToken) { } private static Func<ImmutableArray<TItem>, CancellationToken, ValueTask<VoidResult>> Convert(Func<ImmutableArray<TItem>, CancellationToken, ValueTask> processBatchAsync) => async (items, ct) => { await processBatchAsync(items, ct).ConfigureAwait(false); return default; }; public new Task WaitUntilCurrentBatchCompletesAsync() => base.WaitUntilCurrentBatchCompletesAsync(); } }
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Compilers/VisualBasic/Test/Symbol/StaticLocalDeclarationTests.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.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class StaticLocalDeclarationTests Inherits BasicTestBase <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Valid_BasicParsingWithDim() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static Dim x As Integer = 1 Console.WriteLine(x) x = x + 1 End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics() End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Valid_BasicParsingWithoutDim() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static x As Integer = 1 Console.WriteLine(x) x = x + 1 End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics() End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Error_StaticLocal_DuplicationDeclarations_InSameScopes() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InSameScopes() StaticLocal_DuplicationDeclarations_InSameScopes() End Sub Sub StaticLocal_DuplicationDeclarations_InSameScopes() Static x As Integer = 1 Console.WriteLine(x) Static x As Integer = 2 'Err Console.WriteLine(x) End Sub End Module </file> </compilation> 'This should present a single error BC31401: Static local variable 'x' is already declared. Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31401: Static local variable 'x' is already declared. Static x As Integer = 2 'Err ~ </expected>) End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Error_StaticLocal_DuplicationDeclarationsConflictWithLocal1() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_ConflictDeclarations() StaticLocal_ConflictDeclarations() End Sub Sub StaticLocal_ConflictDeclarations() Static x As Integer = 1 'Err Console.WriteLine(x) Dim x As Integer = 2 Console.WriteLine(x) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30288: Local variable 'x' is already declared in the current block. Dim x As Integer = 2 ~ </expected>) End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Error_StaticLocal_DuplicationDeclarationsConflictWithLocal2() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_ConflictDeclarations() StaticLocal_ConflictDeclarations() End Sub Sub StaticLocal_ConflictDeclarations() Dim x As Integer = 1 Console.WriteLine(x) Static x As Integer = 2 'Err Console.WriteLine(x) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30288: Local variable 'x' is already declared in the current block. Static x As Integer = 2 'Err ~ </expected>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() Try Dim y As Integer = 1 Static x As Integer = 1 Catch ex As Exception Dim y As Integer = 2 Static x As Integer = 2 'Error End Try End Sub End Module </file> </compilation> 'This should present a single error BC31401: Static local variable 'x' is already declared. Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(1) StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(2) End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(a As Integer) Select Case a Case 1 Dim y As Integer = 1 Static x As Integer = 1 Case 2 Dim y As Integer = 1 Static x As Integer = 1 'Error End Select End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_If() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopes_If() End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_If() If True Then Dim y As Integer = 1 Static x As Integer = 1 Else Dim y As Integer = 2 Static x As Integer = 2 'Error End If End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_For() 'Show differences between static local and normal local Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopes_For() StaticLocal_DuplicationDeclarations_InDifferentScopes_For() End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_For() Dim y As Integer = 1 Static x As Integer = 1 'Warning Hide in enclosing block For i = 1 To 2 Dim y As Integer = 2 'Warning Hide in enclosing block Static x As Integer = 3 'Error Next End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BlockLocalShadowing1, "y").WithArguments("y"), Diagnostic(ERRID.ERR_BlockLocalShadowing1, "x").WithArguments("x"), Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InGeneric() 'Cannot declare in generic method Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() Dim x as new UDTest() x.Goo(of Integer)() x.Goo(of Integer)() End Sub End Module Public Class UDTest Public Sub Goo(of t) Static SLItem as integer = 1 SLItem +=1 End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadStaticLocalInGenericMethod, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InStructure() 'Cannot declare in Structure Type Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() Dim x As New UDTest() x.Goo() x.Goo() End Sub End Module Public Structure UDTest Public Sub Goo() Static SLItem As Integer = 1 SLItem += 1 End Sub End Structure </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadStaticLocalInStruct, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_WithModifiers() 'Errors in conjunction with access modifiers Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AccessModifiers() End Sub Sub AccessModifiers() 'These are prettylisted with Access Modified beforehand Public Static SLItem1 As String = "" Private Static SLItem2 As String = "" Protected Static SLItem3 As String = "" Friend Static SLItem4 As String = "" Protected Friend Static SLItem5 As String = "" Static Shared SLItem6 Static Dim SLItem_Valid1 As String = "" 'Valid End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Public").WithArguments("Public"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Private").WithArguments("Private"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Protected").WithArguments("Protected"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Friend").WithArguments("Friend"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Protected").WithArguments("Protected"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Friend").WithArguments("Friend"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Shared").WithArguments("Shared"), Diagnostic(ERRID.WRN_UnusedLocal, "SLItem6").WithArguments("SLItem6")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_OutsideOfMethod() 'Static Locals outside of method bodies Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AccessModifiers() AccessModifiers() End Sub Static SLItem_Valid1 As String = "" 'Invalid Sub AccessModifiers() Static SLItem_Valid1 As String = "" 'Valid End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadDimFlags1, "Static").WithArguments("Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_TryingToAccessStaticLocalFromOutsideMethod() 'trying to access SL from oUtside method not possible Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() 'trying to access SL from oUtside method not possible StaticLocalInSub() StaticLocalInSub.slItem = 2 'ERROR StaticLocalInSub2() StaticLocalInSub2.slItem = 2 'ERROR End Sub Sub StaticLocalInSub() Static SLItem1 = 1 SLItem1 += 1 End Sub Public Sub StaticLocalInSub2() 'With Method Accessibility set to Public Static SLItem1 = 1 SLItem1 += 1 End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_VoidValue, "StaticLocalInSub"), Diagnostic(ERRID.ERR_VoidValue, "StaticLocalInSub2")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_HideLocalInCatchBlock() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() 'trying to access SL from oUtside method not possible Test4_Err() End Sub Public Sub Test4_Err() Static sl1 As String = "" Try Throw New Exception("Test") Catch sl1 As Exception 'Err sl1 &amp;= "InCatch" 'Err - this is the exception instance not the static local Finally End Try End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BlockLocalShadowing1, "sl1").WithArguments("sl1"), Diagnostic(ERRID.ERR_BinaryOperands3, "sl1 &= ""InCatch""").WithArguments("&", "System.Exception", "String")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Keyword_NameClashInIdentifier() 'declare UnEscaped identifier called static Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AvoidingNameConflicts1() End Sub Sub AvoidingNameConflicts1() Static Static as double = 1 'Error End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "as"), Diagnostic(ERRID.ERR_DuplicateSpecifier, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Keyword_NameTypeClash() 'declare escaped identifier and type called static along with static Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AvoidingNameConflicts() End Sub Sub AvoidingNameConflicts() Static [Static] As New [Static] End Sub End Module Class Static 'Error Clash With Keyword End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InLambda_SingleLine() 'Single Line Lambda Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() InSingleLineLambda() End Sub Sub InSingleLineLambda() Static sl1 As Integer = 0 'Declaring Static in Single Line Lambda Dim l1 = Sub() static x1 As Integer = 0 'Error Dim l2 = Function() static x2 As Integer = 0 'Error 'Using Lifted Locals in Lambda's Dim l3 = Sub() sl1 += 1 Dim l4 = Function() (sl1 + 1) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_SubDisallowsStatement, "static x1 As Integer = 0")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InLambda_MultiLine() 'Multi-Line Lambda Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() InMultiLineLambda() End Sub Sub InMultiLineLambda() Static sl1 As Integer = 0 'Declaring Static in MultiLine Dim l1 = Sub() static x1 As Integer = 0 'Error End Sub Dim l2 = Function() static x2 As Integer = 0 'Error Return x2 End Function 'Using Lifted Locals in Lambda's Dim l3 = Sub() sl1 += 1 End Sub Dim l4 = Function() sl1 += 1 Return sl1 End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StaticInLambda, "static"), Diagnostic(ERRID.ERR_StaticInLambda, "static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalInTryCatchBlockScope() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() test(False) test(True) End Sub Sub test(ThrowException As Boolean) Try If ThrowException Then Throw New Exception End If Catch ex As Exception Static sl As Integer = 1 sl += 1 End Try Console.WriteLine(SL.tostring) 'Error Outside Scope End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "SL").WithArguments("SL")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_SpecialType_ArgIterator() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static SLItem2 As ArgIterator End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "ArgIterator").WithArguments("System.ArgIterator"), Diagnostic(ERRID.WRN_UnusedLocal, "SLItem2").WithArguments("SLItem2")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_SpecialType_TypedReference() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static SLItem2 As TypedReference = Nothing End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "TypedReference").WithArguments("System.TypedReference")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalWithRangeVariables() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() test() test() End Sub Sub test() Static sl As Integer = 1 Dim x = From sl In {1, 2, 3} Select sl 'Error Same Scope Console.WriteLine(sl.ToString) sl += 1 End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedQueryableSource, "{1, 2, 3}").WithArguments("Integer()"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal1, "sl").WithArguments("sl"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal1, "sl").WithArguments("sl")) 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.Text Imports Microsoft.CodeAnalysis.VisualBasic Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.UnitTests Public Class StaticLocalDeclarationTests Inherits BasicTestBase <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Valid_BasicParsingWithDim() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static Dim x As Integer = 1 Console.WriteLine(x) x = x + 1 End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics() End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Valid_BasicParsingWithoutDim() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static x As Integer = 1 Console.WriteLine(x) x = x + 1 End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics() End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Error_StaticLocal_DuplicationDeclarations_InSameScopes() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InSameScopes() StaticLocal_DuplicationDeclarations_InSameScopes() End Sub Sub StaticLocal_DuplicationDeclarations_InSameScopes() Static x As Integer = 1 Console.WriteLine(x) Static x As Integer = 2 'Err Console.WriteLine(x) End Sub End Module </file> </compilation> 'This should present a single error BC31401: Static local variable 'x' is already declared. Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC31401: Static local variable 'x' is already declared. Static x As Integer = 2 'Err ~ </expected>) End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Error_StaticLocal_DuplicationDeclarationsConflictWithLocal1() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_ConflictDeclarations() StaticLocal_ConflictDeclarations() End Sub Sub StaticLocal_ConflictDeclarations() Static x As Integer = 1 'Err Console.WriteLine(x) Dim x As Integer = 2 Console.WriteLine(x) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30288: Local variable 'x' is already declared in the current block. Dim x As Integer = 2 ~ </expected>) End Sub <Fact> <WorkItem(15925, "DevDiv_Projects/Roslyn")> Public Sub Error_StaticLocal_DuplicationDeclarationsConflictWithLocal2() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_ConflictDeclarations() StaticLocal_ConflictDeclarations() End Sub Sub StaticLocal_ConflictDeclarations() Dim x As Integer = 1 Console.WriteLine(x) Static x As Integer = 2 'Err Console.WriteLine(x) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) CompilationUtils.AssertTheseDiagnostics(compilation, <expected> BC30288: Local variable 'x' is already declared in the current block. Static x As Integer = 2 'Err ~ </expected>) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_tryCatch() Try Dim y As Integer = 1 Static x As Integer = 1 Catch ex As Exception Dim y As Integer = 2 Static x As Integer = 2 'Error End Try End Sub End Module </file> </compilation> 'This should present a single error BC31401: Static local variable 'x' is already declared. Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(1) StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(2) End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopesSelectCase(a As Integer) Select Case a Case 1 Dim y As Integer = 1 Static x As Integer = 1 Case 2 Dim y As Integer = 1 Static x As Integer = 1 'Error End Select End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_If() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopes_If() End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_If() If True Then Dim y As Integer = 1 Static x As Integer = 1 Else Dim y As Integer = 2 Static x As Integer = 2 'Error End If End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_DuplicationDeclarations_InDifferentScopes_For() 'Show differences between static local and normal local Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() StaticLocal_DuplicationDeclarations_InDifferentScopes_For() StaticLocal_DuplicationDeclarations_InDifferentScopes_For() End Sub Sub StaticLocal_DuplicationDeclarations_InDifferentScopes_For() Dim y As Integer = 1 Static x As Integer = 1 'Warning Hide in enclosing block For i = 1 To 2 Dim y As Integer = 2 'Warning Hide in enclosing block Static x As Integer = 3 'Error Next End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BlockLocalShadowing1, "y").WithArguments("y"), Diagnostic(ERRID.ERR_BlockLocalShadowing1, "x").WithArguments("x"), Diagnostic(ERRID.ERR_DuplicateLocalStatic1, "x").WithArguments("x")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InGeneric() 'Cannot declare in generic method Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() Dim x as new UDTest() x.Goo(of Integer)() x.Goo(of Integer)() End Sub End Module Public Class UDTest Public Sub Goo(of t) Static SLItem as integer = 1 SLItem +=1 End Sub End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadStaticLocalInGenericMethod, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InStructure() 'Cannot declare in Structure Type Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() Dim x As New UDTest() x.Goo() x.Goo() End Sub End Module Public Structure UDTest Public Sub Goo() Static SLItem As Integer = 1 SLItem += 1 End Sub End Structure </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadStaticLocalInStruct, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_WithModifiers() 'Errors in conjunction with access modifiers Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AccessModifiers() End Sub Sub AccessModifiers() 'These are prettylisted with Access Modified beforehand Public Static SLItem1 As String = "" Private Static SLItem2 As String = "" Protected Static SLItem3 As String = "" Friend Static SLItem4 As String = "" Protected Friend Static SLItem5 As String = "" Static Shared SLItem6 Static Dim SLItem_Valid1 As String = "" 'Valid End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Public").WithArguments("Public"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Private").WithArguments("Private"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Protected").WithArguments("Protected"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Friend").WithArguments("Friend"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Protected").WithArguments("Protected"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Friend").WithArguments("Friend"), Diagnostic(ERRID.ERR_BadLocalDimFlags1, "Shared").WithArguments("Shared"), Diagnostic(ERRID.WRN_UnusedLocal, "SLItem6").WithArguments("SLItem6")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_OutsideOfMethod() 'Static Locals outside of method bodies Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AccessModifiers() AccessModifiers() End Sub Static SLItem_Valid1 As String = "" 'Invalid Sub AccessModifiers() Static SLItem_Valid1 As String = "" 'Valid End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BadDimFlags1, "Static").WithArguments("Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_TryingToAccessStaticLocalFromOutsideMethod() 'trying to access SL from oUtside method not possible Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() 'trying to access SL from oUtside method not possible StaticLocalInSub() StaticLocalInSub.slItem = 2 'ERROR StaticLocalInSub2() StaticLocalInSub2.slItem = 2 'ERROR End Sub Sub StaticLocalInSub() Static SLItem1 = 1 SLItem1 += 1 End Sub Public Sub StaticLocalInSub2() 'With Method Accessibility set to Public Static SLItem1 = 1 SLItem1 += 1 End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_VoidValue, "StaticLocalInSub"), Diagnostic(ERRID.ERR_VoidValue, "StaticLocalInSub2")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_HideLocalInCatchBlock() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() 'trying to access SL from oUtside method not possible Test4_Err() End Sub Public Sub Test4_Err() Static sl1 As String = "" Try Throw New Exception("Test") Catch sl1 As Exception 'Err sl1 &amp;= "InCatch" 'Err - this is the exception instance not the static local Finally End Try End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_BlockLocalShadowing1, "sl1").WithArguments("sl1"), Diagnostic(ERRID.ERR_BinaryOperands3, "sl1 &= ""InCatch""").WithArguments("&", "System.Exception", "String")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Keyword_NameClashInIdentifier() 'declare UnEscaped identifier called static Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AvoidingNameConflicts1() End Sub Sub AvoidingNameConflicts1() Static Static as double = 1 'Error End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "as"), Diagnostic(ERRID.ERR_DuplicateSpecifier, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Keyword_NameTypeClash() 'declare escaped identifier and type called static along with static Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() AvoidingNameConflicts() End Sub Sub AvoidingNameConflicts() Static [Static] As New [Static] End Sub End Module Class Static 'Error Clash With Keyword End Class </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_InvalidUseOfKeyword, "Static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InLambda_SingleLine() 'Single Line Lambda Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() InSingleLineLambda() End Sub Sub InSingleLineLambda() Static sl1 As Integer = 0 'Declaring Static in Single Line Lambda Dim l1 = Sub() static x1 As Integer = 0 'Error Dim l2 = Function() static x2 As Integer = 0 'Error 'Using Lifted Locals in Lambda's Dim l3 = Sub() sl1 += 1 Dim l4 = Function() (sl1 + 1) End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedExpression, ""), Diagnostic(ERRID.ERR_SubDisallowsStatement, "static x1 As Integer = 0")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalDeclaration_Negative_InLambda_MultiLine() 'Multi-Line Lambda Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Module Module1 Sub Main() InMultiLineLambda() End Sub Sub InMultiLineLambda() Static sl1 As Integer = 0 'Declaring Static in MultiLine Dim l1 = Sub() static x1 As Integer = 0 'Error End Sub Dim l2 = Function() static x2 As Integer = 0 'Error Return x2 End Function 'Using Lifted Locals in Lambda's Dim l3 = Sub() sl1 += 1 End Sub Dim l4 = Function() sl1 += 1 Return sl1 End Function End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_StaticInLambda, "static"), Diagnostic(ERRID.ERR_StaticInLambda, "static")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalInTryCatchBlockScope() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() test(False) test(True) End Sub Sub test(ThrowException As Boolean) Try If ThrowException Then Throw New Exception End If Catch ex As Exception Static sl As Integer = 1 sl += 1 End Try Console.WriteLine(SL.tostring) 'Error Outside Scope End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_NameNotDeclared1, "SL").WithArguments("SL")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_SpecialType_ArgIterator() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static SLItem2 As ArgIterator End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "ArgIterator").WithArguments("System.ArgIterator"), Diagnostic(ERRID.WRN_UnusedLocal, "SLItem2").WithArguments("SLItem2")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocal_SpecialType_TypedReference() Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() Goo() Goo() End Sub Sub Goo() Static SLItem2 As TypedReference = Nothing End Sub End Module </file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_RestrictedType1, "TypedReference").WithArguments("System.TypedReference")) End Sub <WorkItem(15925, "DevDiv_Projects/Roslyn")> <Fact()> Public Sub Error_StaticLocalWithRangeVariables() 'The Use of Static Locals within Try/Catch/Finally Blocks Dim compilationDef = <compilation name="StaticLocaltest"> <file name="a.vb"> Imports System Module Module1 Sub Main() test() test() End Sub Sub test() Static sl As Integer = 1 Dim x = From sl In {1, 2, 3} Select sl 'Error Same Scope Console.WriteLine(sl.ToString) sl += 1 End Sub End Module</file> </compilation> Dim compilation = CompilationUtils.CreateCompilationWithMscorlib40AndVBRuntime(compilationDef) compilation.VerifyDiagnostics(Diagnostic(ERRID.ERR_ExpectedQueryableSource, "{1, 2, 3}").WithArguments("Integer()"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal1, "sl").WithArguments("sl"), Diagnostic(ERRID.ERR_IterationVariableShadowLocal1, "sl").WithArguments("sl")) End Sub End Class End Namespace
-1
dotnet/roslyn
56,030
Remove RemoveUnusedReferences command hotkey
Resolves https://github.com/dotnet/roslyn/issues/56028
JoeRobich
2021-08-31T17:18:07Z
2021-08-31T18:42:08Z
e01c311bd91e6290eefe9be9eeef76c64b08b2d5
2be2c34f110e7ce2f4cfd8e4b1f8153603087679
Remove RemoveUnusedReferences command hotkey. Resolves https://github.com/dotnet/roslyn/issues/56028
./src/Analyzers/CSharp/CodeFixes/QualifyMemberAccess/CSharpQualifyMemberAccessCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.QualifyMemberAccess; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.QualifyMemberAccess { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.QualifyMemberAccess), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.RemoveUnnecessaryCast)] internal class CSharpQualifyMemberAccessCodeFixProvider : AbstractQualifyMemberAccessCodeFixprovider<SimpleNameSyntax, InvocationExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpQualifyMemberAccessCodeFixProvider() { } protected override SimpleNameSyntax GetNode(Diagnostic diagnostic, CancellationToken cancellationToken) { var node = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken); switch (node) { case SimpleNameSyntax simpleNameSyntax: return simpleNameSyntax; case InvocationExpressionSyntax invocationExpressionSyntax: return invocationExpressionSyntax.Expression as SimpleNameSyntax; default: return null; } } protected override string GetTitle() => CSharpCodeFixesResources.Add_this; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.QualifyMemberAccess; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.QualifyMemberAccess { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.QualifyMemberAccess), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.RemoveUnnecessaryCast)] internal class CSharpQualifyMemberAccessCodeFixProvider : AbstractQualifyMemberAccessCodeFixprovider<SimpleNameSyntax, InvocationExpressionSyntax> { [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpQualifyMemberAccessCodeFixProvider() { } protected override SimpleNameSyntax GetNode(Diagnostic diagnostic, CancellationToken cancellationToken) { var node = diagnostic.Location.FindNode(getInnermostNodeForTie: true, cancellationToken); switch (node) { case SimpleNameSyntax simpleNameSyntax: return simpleNameSyntax; case InvocationExpressionSyntax invocationExpressionSyntax: return invocationExpressionSyntax.Expression as SimpleNameSyntax; default: return null; } } protected override string GetTitle() => CSharpCodeFixesResources.Add_this; } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/Core/CodeAnalysisTest/DefaultAnalyzerAssemblyLoaderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.UnitTests { [CollectionDefinition(Name)] public class AssemblyLoadTestFixtureCollection : ICollectionFixture<AssemblyLoadTestFixture> { public const string Name = nameof(AssemblyLoadTestFixtureCollection); private AssemblyLoadTestFixtureCollection() { } } [Collection(AssemblyLoadTestFixtureCollection.Name)] public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel); private readonly ITestOutputHelper _output; private readonly AssemblyLoadTestFixture _testFixture; public DefaultAnalyzerAssemblyLoaderTests(ITestOutputHelper output, AssemblyLoadTestFixture testFixture) { _output = output; _testFixture = testFixture; } [Fact, WorkItem(32226, "https://github.com/dotnet/roslyn/issues/32226")] public void LoadWithDependency() { var analyzerDependencyFile = _testFixture.AnalyzerDependency; var analyzerMainFile = _testFixture.AnalyzerWithDependency; var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(analyzerDependencyFile.Path); var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader); analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader); analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages(); Assert.Equal(1, analyzers.Length); Assert.Equal("TestAnalyzer", analyzers[0].ToString()); Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length); Assert.NotNull(analyzerDependencyReference.GetAssembly()); } [Fact] public void AddDependencyLocationThrowsOnNull() { var loader = new DefaultAnalyzerAssemblyLoader(); Assert.Throws<ArgumentNullException>("fullPath", () => loader.AddDependencyLocation(null)); Assert.Throws<ArgumentException>("fullPath", () => loader.AddDependencyLocation("a")); } [Fact] public void ThrowsForMissingFile() { var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".dll"); var loader = new DefaultAnalyzerAssemblyLoader(); Assert.ThrowsAny<Exception>(() => loader.LoadFromPath(path)); } [Fact] public void BasicLoad() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); Assert.NotNull(alpha); } [Fact] public void AssemblyLoading() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); var a = alpha.CreateInstance("Alpha.A")!; a.GetType().GetMethod("Write")!.Invoke(a, new object[] { sb, "Test A" }); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; b.GetType().GetMethod("Write")!.Invoke(b, new object[] { sb, "Test B" }); var expected = @"Delta: Gamma: Alpha: Test A Delta: Gamma: Beta: Test B "; var actual = sb.ToString(); Assert.Equal(expected, actual); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_AssemblyLocationNotAdded() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assert.Throws<FileNotFoundException>(() => loader.LoadFromPath(_testFixture.Beta.Path)); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_DependencyLocationNotAdded() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); // We don't pass Alpha's path to AddDependencyLocation here, and therefore expect // calling Beta.B.Write to fail. loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; var writeMethod = b.GetType().GetMethod("Write")!; var exception = Assert.Throws<TargetInvocationException>( () => writeMethod.Invoke(b, new object[] { sb, "Test B" })); Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException); var actual = sb.ToString(); Assert.Equal(@"", actual); } [Fact] public void AssemblyLoading_MultipleVersions() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(2, alcs.Length); Assert.Equal(new[] { ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) }, alcs[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); Assert.Equal(new[] { ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path) }, alcs[1].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MultipleLoaders() { StringBuilder sb = new StringBuilder(); var loader1 = new DefaultAnalyzerAssemblyLoader(); loader1.AddDependencyLocation(_testFixture.Gamma.Path); loader1.AddDependencyLocation(_testFixture.Delta1.Path); var loader2 = new DefaultAnalyzerAssemblyLoader(); loader2.AddDependencyLocation(_testFixture.Epsilon.Path); loader2.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader1.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader2.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs1 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader1); Assert.Equal(1, alcs1.Length); Assert.Equal(new[] { ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) }, alcs1[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); var alcs2 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader2); Assert.Equal(1, alcs2.Length); Assert.Equal(new[] { ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path) }, alcs2[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MissingVersion() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; var eWrite = e.GetType().GetMethod("Write")!; var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { var exception = Assert.Throws<TargetInvocationException>(() => eWrite.Invoke(e, new object[] { sb, "Test E" })); Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException); } else { eWrite.Invoke(e, new object[] { sb, "Test E" }); Assert.Equal( @"Delta: Gamma: Test G ", actual); } } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; if (ExecutionConditionUtil.IsCoreClr) { var ex = Assert.ThrowsAny<Exception>(() => analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb })); Assert.True(ex is MissingMethodException or TargetInvocationException, $@"Unexpected exception type: ""{ex.GetType()}"""); } else { analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal("42", sb.ToString()); } } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_02() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal(ExecutionConditionUtil.IsCoreClr ? "1" : "42", sb.ToString()); } [ConditionalFact(typeof(WindowsOnly), typeof(CoreClrOnly))] public void AssemblyLoading_NativeDependency() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.AnalyzerWithNativeDependency.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerWithNativeDependency.Path); var analyzer = analyzerAssembly.CreateInstance("Class1")!; var result = analyzer.GetType().GetMethod("GetFileAttributes")!.Invoke(analyzer, new[] { _testFixture.AnalyzerWithNativeDependency.Path }); Assert.Equal(0, Marshal.GetLastWin32Error()); Assert.Equal(FileAttributes.Archive, (FileAttributes)result!); } #if NETCOREAPP [Fact] public void VerifyCompilerAssemblySimpleNames() { var caAssembly = typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly; var caReferences = caAssembly.GetReferencedAssemblies(); var allReferenceSimpleNames = ArrayBuilder<string>.GetInstance(); allReferenceSimpleNames.Add(caAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in caReferences) { allReferenceSimpleNames.Add(reference.Name ?? throw new InvalidOperationException()); } var csAssembly = typeof(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode).Assembly; allReferenceSimpleNames.Add(csAssembly.GetName().Name ?? throw new InvalidOperationException()); var csReferences = csAssembly.GetReferencedAssemblies(); foreach (var reference in csReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } var vbAssembly = typeof(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode).Assembly; var vbReferences = vbAssembly.GetReferencedAssemblies(); allReferenceSimpleNames.Add(vbAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in vbReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } if (!DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames.SetEquals(allReferenceSimpleNames)) { allReferenceSimpleNames.Sort(); var allNames = string.Join(",\r\n ", allReferenceSimpleNames.Select(name => $@"""{name}""")); _output.WriteLine(" internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames ="); _output.WriteLine(" ImmutableHashSet.Create("); _output.WriteLine(" StringComparer.OrdinalIgnoreCase,"); _output.WriteLine($" {allNames});"); allReferenceSimpleNames.Free(); Assert.True(false, $"{nameof(DefaultAnalyzerAssemblyLoader)}.{nameof(DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames)} is not up to date. Paste in the standard output of this test to update it."); } else { allReferenceSimpleNames.Free(); } } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.UnitTests { [CollectionDefinition(Name)] public class AssemblyLoadTestFixtureCollection : ICollectionFixture<AssemblyLoadTestFixture> { public const string Name = nameof(AssemblyLoadTestFixtureCollection); private AssemblyLoadTestFixtureCollection() { } } [Collection(AssemblyLoadTestFixtureCollection.Name)] public sealed class DefaultAnalyzerAssemblyLoaderTests : TestBase { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel); private readonly ITestOutputHelper _output; private readonly AssemblyLoadTestFixture _testFixture; public DefaultAnalyzerAssemblyLoaderTests(ITestOutputHelper output, AssemblyLoadTestFixture testFixture) { _output = output; _testFixture = testFixture; } [Fact, WorkItem(32226, "https://github.com/dotnet/roslyn/issues/32226")] public void LoadWithDependency() { var analyzerDependencyFile = _testFixture.AnalyzerDependency; var analyzerMainFile = _testFixture.AnalyzerWithDependency; var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(analyzerDependencyFile.Path); var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader); analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader); analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages(); Assert.Equal(1, analyzers.Length); Assert.Equal("TestAnalyzer", analyzers[0].ToString()); Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length); Assert.NotNull(analyzerDependencyReference.GetAssembly()); } [Fact] public void AddDependencyLocationThrowsOnNull() { var loader = new DefaultAnalyzerAssemblyLoader(); Assert.Throws<ArgumentNullException>("fullPath", () => loader.AddDependencyLocation(null)); Assert.Throws<ArgumentException>("fullPath", () => loader.AddDependencyLocation("a")); } [Fact] public void ThrowsForMissingFile() { var path = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName() + ".dll"); var loader = new DefaultAnalyzerAssemblyLoader(); Assert.ThrowsAny<Exception>(() => loader.LoadFromPath(path)); } [Fact] public void BasicLoad() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); Assert.NotNull(alpha); } [Fact] public void AssemblyLoading() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Alpha.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assembly alpha = loader.LoadFromPath(_testFixture.Alpha.Path); var a = alpha.CreateInstance("Alpha.A")!; a.GetType().GetMethod("Write")!.Invoke(a, new object[] { sb, "Test A" }); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; b.GetType().GetMethod("Write")!.Invoke(b, new object[] { sb, "Test B" }); var expected = @"Delta: Gamma: Alpha: Test A Delta: Gamma: Beta: Test B "; var actual = sb.ToString(); Assert.Equal(expected, actual); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_AssemblyLocationNotAdded() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); Assert.Throws<FileNotFoundException>(() => loader.LoadFromPath(_testFixture.Beta.Path)); } [ConditionalFact(typeof(CoreClrOnly))] public void AssemblyLoading_DependencyLocationNotAdded() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); // We don't pass Alpha's path to AddDependencyLocation here, and therefore expect // calling Beta.B.Write to fail. loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Beta.Path); Assembly beta = loader.LoadFromPath(_testFixture.Beta.Path); var b = beta.CreateInstance("Beta.B")!; var writeMethod = b.GetType().GetMethod("Write")!; var exception = Assert.Throws<TargetInvocationException>( () => writeMethod.Invoke(b, new object[] { sb, "Test B" })); Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException); var actual = sb.ToString(); Assert.Equal(@"", actual); } [Fact] public void AssemblyLoading_MultipleVersions() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader); Assert.Equal(2, alcs.Length); Assert.Equal(new[] { ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) }, alcs[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); Assert.Equal(new[] { ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path) }, alcs[1].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MultipleLoaders() { StringBuilder sb = new StringBuilder(); var loader1 = new DefaultAnalyzerAssemblyLoader(); loader1.AddDependencyLocation(_testFixture.Gamma.Path); loader1.AddDependencyLocation(_testFixture.Delta1.Path); var loader2 = new DefaultAnalyzerAssemblyLoader(); loader2.AddDependencyLocation(_testFixture.Epsilon.Path); loader2.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader1.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader2.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; e.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); #if NETCOREAPP var alcs1 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader1); Assert.Equal(1, alcs1.Length); Assert.Equal(new[] { ("Delta", "1.0.0.0", _testFixture.Delta1.Path), ("Gamma", "0.0.0.0", _testFixture.Gamma.Path) }, alcs1[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); var alcs2 = DefaultAnalyzerAssemblyLoader.TestAccessor.GetOrderedLoadContexts(loader2); Assert.Equal(1, alcs2.Length); Assert.Equal(new[] { ("Delta", "2.0.0.0", _testFixture.Delta2.Path), ("Epsilon", "0.0.0.0", _testFixture.Epsilon.Path) }, alcs2[0].Assemblies.Select(a => (a.GetName().Name!, a.GetName().Version!.ToString(), a.Location)).Order()); #endif var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_MultipleVersions_MissingVersion() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G")!; g.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E")!; var eWrite = e.GetType().GetMethod("Write")!; var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { var exception = Assert.Throws<TargetInvocationException>(() => eWrite.Invoke(e, new object[] { sb, "Test E" })); Assert.IsAssignableFrom<FileNotFoundException>(exception.InnerException); } else { eWrite.Invoke(e, new object[] { sb, "Test E" }); Assert.Equal( @"Delta: Gamma: Test G ", actual); } } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_01() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable1.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; if (ExecutionConditionUtil.IsCoreClr) { var ex = Assert.ThrowsAny<Exception>(() => analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb })); Assert.True(ex is MissingMethodException or TargetInvocationException, $@"Unexpected exception type: ""{ex.GetType()}"""); } else { analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal("42", sb.ToString()); } } [Fact] public void AssemblyLoading_AnalyzerReferencesSystemCollectionsImmutable_02() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.UserSystemCollectionsImmutable.Path); loader.AddDependencyLocation(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerReferencesSystemCollectionsImmutable2.Path); var analyzer = analyzerAssembly.CreateInstance("Analyzer")!; analyzer.GetType().GetMethod("Method")!.Invoke(analyzer, new object[] { sb }); Assert.Equal(ExecutionConditionUtil.IsCoreClr ? "1" : "42", sb.ToString()); } [ConditionalFact(typeof(WindowsOnly), typeof(CoreClrOnly))] public void AssemblyLoading_NativeDependency() { var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.AnalyzerWithNativeDependency.Path); Assembly analyzerAssembly = loader.LoadFromPath(_testFixture.AnalyzerWithNativeDependency.Path); var analyzer = analyzerAssembly.CreateInstance("Class1")!; var result = analyzer.GetType().GetMethod("GetFileAttributes")!.Invoke(analyzer, new[] { _testFixture.AnalyzerWithNativeDependency.Path }); Assert.Equal(0, Marshal.GetLastWin32Error()); Assert.Equal(FileAttributes.Archive, (FileAttributes)result!); } [Fact] public void AssemblyLoading_Delete() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); var tempDir = Temp.CreateDirectory(); var deltaCopy = tempDir.CreateFile("Delta.dll").CopyContentFrom(_testFixture.Delta1.Path); loader.AddDependencyLocation(deltaCopy.Path); Assembly delta = loader.LoadFromPath(deltaCopy.Path); try { File.Delete(deltaCopy.Path); } catch (UnauthorizedAccessException) { return; } // The above call may or may not throw depending on the platform configuration. // If it doesn't throw, we might as well check that things are still functioning reasonably. var d = delta.CreateInstance("Delta.D"); d!.GetType().GetMethod("Write")!.Invoke(d, new object[] { sb, "Test D" }); var actual = sb.ToString(); Assert.Equal( @"Delta: Test D ", actual); } #if NETCOREAPP [Fact] public void VerifyCompilerAssemblySimpleNames() { var caAssembly = typeof(Microsoft.CodeAnalysis.SyntaxNode).Assembly; var caReferences = caAssembly.GetReferencedAssemblies(); var allReferenceSimpleNames = ArrayBuilder<string>.GetInstance(); allReferenceSimpleNames.Add(caAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in caReferences) { allReferenceSimpleNames.Add(reference.Name ?? throw new InvalidOperationException()); } var csAssembly = typeof(Microsoft.CodeAnalysis.CSharp.CSharpSyntaxNode).Assembly; allReferenceSimpleNames.Add(csAssembly.GetName().Name ?? throw new InvalidOperationException()); var csReferences = csAssembly.GetReferencedAssemblies(); foreach (var reference in csReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } var vbAssembly = typeof(Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxNode).Assembly; var vbReferences = vbAssembly.GetReferencedAssemblies(); allReferenceSimpleNames.Add(vbAssembly.GetName().Name ?? throw new InvalidOperationException()); foreach (var reference in vbReferences) { var name = reference.Name ?? throw new InvalidOperationException(); if (!allReferenceSimpleNames.Contains(name, StringComparer.OrdinalIgnoreCase)) { allReferenceSimpleNames.Add(name); } } if (!DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames.SetEquals(allReferenceSimpleNames)) { allReferenceSimpleNames.Sort(); var allNames = string.Join(",\r\n ", allReferenceSimpleNames.Select(name => $@"""{name}""")); _output.WriteLine(" internal static readonly ImmutableHashSet<string> CompilerAssemblySimpleNames ="); _output.WriteLine(" ImmutableHashSet.Create("); _output.WriteLine(" StringComparer.OrdinalIgnoreCase,"); _output.WriteLine($" {allNames});"); allReferenceSimpleNames.Free(); Assert.True(false, $"{nameof(DefaultAnalyzerAssemblyLoader)}.{nameof(DefaultAnalyzerAssemblyLoader.CompilerAssemblySimpleNames)} is not up to date. Paste in the standard output of this test to update it."); } else { allReferenceSimpleNames.Free(); } } #endif } }
1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/Core/CodeAnalysisTest/ShadowCopyAnalyzerAssemblyLoaderTests.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.IO; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { [Collection(AssemblyLoadTestFixtureCollection.Name)] public sealed class ShadowCopyAnalyzerAssemblyLoaderTests : TestBase { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel); private readonly AssemblyLoadTestFixture _testFixture; public ShadowCopyAnalyzerAssemblyLoaderTests(AssemblyLoadTestFixture testFixture) { _testFixture = testFixture; } [Fact, WorkItem(32226, "https://github.com/dotnet/roslyn/issues/32226")] public void LoadWithDependency() { var analyzerDependencyFile = _testFixture.AnalyzerDependency; var analyzerMainFile = _testFixture.AnalyzerWithDependency; var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(analyzerDependencyFile.Path); var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader); analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader); analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages(); Assert.Equal(1, analyzers.Length); Assert.Equal("TestAnalyzer", analyzers[0].ToString()); Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length); Assert.NotNull(analyzerDependencyReference.GetAssembly()); } [Fact] public void AssemblyLoading_MultipleVersions() { StringBuilder sb = new StringBuilder(); var loader = new DefaultAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G"); g!.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E"); e!.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.IO; using System.Reflection; using System.Text; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests { [Collection(AssemblyLoadTestFixtureCollection.Name)] public sealed class ShadowCopyAnalyzerAssemblyLoaderTests : TestBase { private static readonly CSharpCompilationOptions s_dllWithMaxWarningLevel = new(OutputKind.DynamicallyLinkedLibrary, warningLevel: CodeAnalysis.Diagnostic.MaxWarningLevel); private readonly AssemblyLoadTestFixture _testFixture; public ShadowCopyAnalyzerAssemblyLoaderTests(AssemblyLoadTestFixture testFixture) { _testFixture = testFixture; } [Fact, WorkItem(32226, "https://github.com/dotnet/roslyn/issues/32226")] public void LoadWithDependency() { var analyzerDependencyFile = _testFixture.AnalyzerDependency; var analyzerMainFile = _testFixture.AnalyzerWithDependency; var loader = new ShadowCopyAnalyzerAssemblyLoader(); loader.AddDependencyLocation(analyzerDependencyFile.Path); var analyzerMainReference = new AnalyzerFileReference(analyzerMainFile.Path, loader); analyzerMainReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzerDependencyReference = new AnalyzerFileReference(analyzerDependencyFile.Path, loader); analyzerDependencyReference.AnalyzerLoadFailed += (_, e) => AssertEx.Fail(e.Exception!.Message); var analyzers = analyzerMainReference.GetAnalyzersForAllLanguages(); Assert.Equal(1, analyzers.Length); Assert.Equal("TestAnalyzer", analyzers[0].ToString()); Assert.Equal(0, analyzerDependencyReference.GetAnalyzersForAllLanguages().Length); Assert.NotNull(analyzerDependencyReference.GetAssembly()); } [Fact] public void AssemblyLoading_MultipleVersions() { StringBuilder sb = new StringBuilder(); var loader = new ShadowCopyAnalyzerAssemblyLoader(); loader.AddDependencyLocation(_testFixture.Gamma.Path); loader.AddDependencyLocation(_testFixture.Delta1.Path); loader.AddDependencyLocation(_testFixture.Epsilon.Path); loader.AddDependencyLocation(_testFixture.Delta2.Path); Assembly gamma = loader.LoadFromPath(_testFixture.Gamma.Path); var g = gamma.CreateInstance("Gamma.G"); g!.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); Assembly epsilon = loader.LoadFromPath(_testFixture.Epsilon.Path); var e = epsilon.CreateInstance("Epsilon.E"); e!.GetType().GetMethod("Write")!.Invoke(e, new object[] { sb, "Test E" }); var actual = sb.ToString(); if (ExecutionConditionUtil.IsCoreClr) { Assert.Equal( @"Delta: Gamma: Test G Delta.2: Epsilon: Test E ", actual); } else { Assert.Equal( @"Delta: Gamma: Test G Delta: Epsilon: Test E ", actual); } } [Fact] public void AssemblyLoading_Delete() { StringBuilder sb = new StringBuilder(); var loader = new ShadowCopyAnalyzerAssemblyLoader(); var tempDir = Temp.CreateDirectory(); var gammaCopy = tempDir.CreateFile("Gamma.dll").CopyContentFrom(_testFixture.Gamma.Path); var deltaCopy = tempDir.CreateFile("Delta.dll").CopyContentFrom(_testFixture.Delta1.Path); loader.AddDependencyLocation(deltaCopy.Path); loader.AddDependencyLocation(gammaCopy.Path); Assembly gamma = loader.LoadFromPath(gammaCopy.Path); var g = gamma.CreateInstance("Gamma.G"); g!.GetType().GetMethod("Write")!.Invoke(g, new object[] { sb, "Test G" }); File.Delete(gammaCopy.Path); File.Delete(deltaCopy.Path); var actual = sb.ToString(); Assert.Equal( @"Delta: Gamma: Test G ", actual); } } }
1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/Core/Portable/DiagnosticAnalyzer/DefaultAnalyzerAssemblyLoader.Desktop.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #if !NETCOREAPP using System; using System.Reflection; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Loads analyzer assemblies from their original locations in the file system. /// Assemblies will only be loaded from the locations specified when the loader /// is instantiated. /// </summary> /// <remarks> /// This type is meant to be used in scenarios where it is OK for the analyzer /// assemblies to be locked on disk for the lifetime of the host; for example, /// csc.exe and vbc.exe. In scenarios where support for updating or deleting /// the analyzer on disk is required a different loader should be used. /// </remarks> internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { private int _hookedAssemblyResolve; protected override Assembly LoadFromPathImpl(string fullPath) { if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0) { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } return LoadImpl(fullPath); } protected virtual Assembly LoadImpl(string fullPath) => Assembly.LoadFrom(fullPath); private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { try { return Load(AppDomain.CurrentDomain.ApplyPolicy(args.Name)); } catch { return null; } } } } #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. #nullable disable #if !NETCOREAPP using System; using System.Reflection; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Loads analyzer assemblies from their original locations in the file system. /// Assemblies will only be loaded from the locations specified when the loader /// is instantiated. /// </summary> /// <remarks> /// This type is meant to be used in scenarios where it is OK for the analyzer /// assemblies to be locked on disk for the lifetime of the host; for example, /// csc.exe and vbc.exe. In scenarios where support for updating or deleting /// the analyzer on disk is required a different loader should be used. /// </remarks> internal class DefaultAnalyzerAssemblyLoader : AnalyzerAssemblyLoader { private int _hookedAssemblyResolve; protected override Assembly LoadFromPathImpl(string fullPath) { if (Interlocked.CompareExchange(ref _hookedAssemblyResolve, 0, 1) == 0) { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } var pathToLoad = GetPathToLoad(fullPath); return Assembly.LoadFrom(pathToLoad); } private Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { try { return Load(AppDomain.CurrentDomain.ApplyPolicy(args.Name)); } catch { return null; } } } } #endif
1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/VisualStudio/Core/Def/Implementation/ProjectSystem/Interop/IAnalyzerHost.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("9A37496A-F2CB-49A8-A684-7DEAAD2B0F07")] internal interface IAnalyzerHost { void AddAnalyzerReference([MarshalAs(UnmanagedType.LPWStr)] string analyzerAssemblyFullPath); void RemoveAnalyzerReference([MarshalAs(UnmanagedType.LPWStr)] string analyzerAssemblyFullPath); void SetRuleSetFile([MarshalAs(UnmanagedType.LPWStr)] string ruleSetFileFullPath); void AddAdditionalFile([MarshalAs(UnmanagedType.LPWStr)] string additionalFilePath); void RemoveAdditionalFile([MarshalAs(UnmanagedType.LPWStr)] string additionalFilePath); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Runtime.InteropServices; namespace Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem.Interop { [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("9A37496A-F2CB-49A8-A684-7DEAAD2B0F07")] internal interface IAnalyzerHost { void AddAnalyzerReference([MarshalAs(UnmanagedType.LPWStr)] string analyzerAssemblyFullPath); void RemoveAnalyzerReference([MarshalAs(UnmanagedType.LPWStr)] string analyzerAssemblyFullPath); void SetRuleSetFile([MarshalAs(UnmanagedType.LPWStr)] string ruleSetFileFullPath); void AddAdditionalFile([MarshalAs(UnmanagedType.LPWStr)] string additionalFilePath); void RemoveAdditionalFile([MarshalAs(UnmanagedType.LPWStr)] string additionalFilePath); } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Features/CSharp/Portable/ChangeSignature/ChangeSignatureFormattingRule.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.ChangeSignature { internal sealed class ChangeSignatureFormattingRule : BaseFormattingRule { private static readonly ImmutableArray<SyntaxKind> s_allowableKinds = ImmutableArray.Create( SyntaxKind.ParameterList, SyntaxKind.ArgumentList, SyntaxKind.BracketedParameterList, SyntaxKind.BracketedArgumentList, SyntaxKind.AttributeArgumentList); public override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation) { nextOperation.Invoke(); if (s_allowableKinds.Contains(node.Kind())) { AddChangeSignatureIndentOperation(list, node); } } private static void AddChangeSignatureIndentOperation(List<IndentBlockOperation> list, SyntaxNode node) { if (node.Parent != null) { var baseToken = node.Parent.GetFirstToken(); var startToken = node.GetFirstToken(); var endToken = node.GetLastToken(); var span = CommonFormattingHelpers.GetSpanIncludingTrailingAndLeadingTriviaOfAdjacentTokens(startToken, endToken); span = TextSpan.FromBounds(Math.Max(baseToken.Span.End, span.Start), span.End); list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(baseToken, startToken, endToken, span, indentationDelta: 1, option: IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine)); } } public override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { if (previousToken.Kind() == SyntaxKind.CommaToken && s_allowableKinds.Contains(previousToken.Parent.Kind())) { return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines); } return base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.ChangeSignature { internal sealed class ChangeSignatureFormattingRule : BaseFormattingRule { private static readonly ImmutableArray<SyntaxKind> s_allowableKinds = ImmutableArray.Create( SyntaxKind.ParameterList, SyntaxKind.ArgumentList, SyntaxKind.BracketedParameterList, SyntaxKind.BracketedArgumentList, SyntaxKind.AttributeArgumentList); public override void AddIndentBlockOperations(List<IndentBlockOperation> list, SyntaxNode node, in NextIndentBlockOperationAction nextOperation) { nextOperation.Invoke(); if (s_allowableKinds.Contains(node.Kind())) { AddChangeSignatureIndentOperation(list, node); } } private static void AddChangeSignatureIndentOperation(List<IndentBlockOperation> list, SyntaxNode node) { if (node.Parent != null) { var baseToken = node.Parent.GetFirstToken(); var startToken = node.GetFirstToken(); var endToken = node.GetLastToken(); var span = CommonFormattingHelpers.GetSpanIncludingTrailingAndLeadingTriviaOfAdjacentTokens(startToken, endToken); span = TextSpan.FromBounds(Math.Max(baseToken.Span.End, span.Start), span.End); list.Add(FormattingOperations.CreateRelativeIndentBlockOperation(baseToken, startToken, endToken, span, indentationDelta: 1, option: IndentBlockOption.RelativeToFirstTokenOnBaseTokenLine)); } } public override AdjustNewLinesOperation GetAdjustNewLinesOperation(in SyntaxToken previousToken, in SyntaxToken currentToken, in NextGetAdjustNewLinesOperation nextOperation) { if (previousToken.Kind() == SyntaxKind.CommaToken && s_allowableKinds.Contains(previousToken.Parent.Kind())) { return FormattingOperations.CreateAdjustNewLinesOperation(0, AdjustNewLinesOption.PreserveLines); } return base.GetAdjustNewLinesOperation(in previousToken, in currentToken, in nextOperation); } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/Core/Portable/SymbolDisplay/ObjectDisplayExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .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 { internal static class ObjectDisplayExtensions { /// <summary> /// Determines if a flag is set on the <see cref="ObjectDisplayOptions"/> enum. /// </summary> /// <param name="options">The value to check.</param> /// <param name="flag">An enum field that specifies the flag.</param> /// <returns>Whether the <paramref name="flag"/> is set on the <paramref name="options"/>.</returns> internal static bool IncludesOption(this ObjectDisplayOptions options, ObjectDisplayOptions flag) { return (options & flag) == flag; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .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 { internal static class ObjectDisplayExtensions { /// <summary> /// Determines if a flag is set on the <see cref="ObjectDisplayOptions"/> enum. /// </summary> /// <param name="options">The value to check.</param> /// <param name="flag">An enum field that specifies the flag.</param> /// <returns>Whether the <paramref name="flag"/> is set on the <paramref name="options"/>.</returns> internal static bool IncludesOption(this ObjectDisplayOptions options, ObjectDisplayOptions flag) { return (options & flag) == flag; } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Workspaces/SharedUtilitiesAndExtensions/Compiler/CSharp/Formatting/CSharpSyntaxFormattingService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Diagnostics; #if !CODE_STYLE using System; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; #endif namespace Microsoft.CodeAnalysis.CSharp.Formatting { #if !CODE_STYLE [ExportLanguageService(typeof(ISyntaxFormattingService), LanguageNames.CSharp), Shared] #endif internal class CSharpSyntaxFormattingService : AbstractSyntaxFormattingService { private readonly ImmutableList<AbstractFormattingRule> _rules; #if CODE_STYLE public static readonly CSharpSyntaxFormattingService Instance = new(); #else [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] #endif public CSharpSyntaxFormattingService() { _rules = ImmutableList.Create<AbstractFormattingRule>( new WrappingFormattingRule(), new SpacingFormattingRule(), new NewLineUserSettingFormattingRule(), new IndentUserSettingsFormattingRule(), new ElasticTriviaFormattingRule(), new EndOfFileTokenFormattingRule(), new StructuredTriviaFormattingRule(), new IndentBlockFormattingRule(), new SuppressFormattingRule(), new AnchorIndentationFormattingRule(), new QueryExpressionFormattingRule(), new TokenBasedFormattingRule(), DefaultOperationProvider.Instance); } public override IEnumerable<AbstractFormattingRule> GetDefaultFormattingRules() => _rules; protected override IFormattingResult CreateAggregatedFormattingResult(SyntaxNode node, IList<AbstractFormattingResult> results, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? formattingSpans = null) => new AggregatedFormattingResult(node, results, formattingSpans); protected override AbstractFormattingResult Format(SyntaxNode node, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> formattingRules, SyntaxToken token1, SyntaxToken token2, CancellationToken cancellationToken) => new CSharpFormatEngine(node, options, formattingRules, token1, token2).Format(cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Threading; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Formatting.Rules; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Diagnostics; #if !CODE_STYLE using System; using System.Composition; using Microsoft.CodeAnalysis.Host.Mef; #endif namespace Microsoft.CodeAnalysis.CSharp.Formatting { #if !CODE_STYLE [ExportLanguageService(typeof(ISyntaxFormattingService), LanguageNames.CSharp), Shared] #endif internal class CSharpSyntaxFormattingService : AbstractSyntaxFormattingService { private readonly ImmutableList<AbstractFormattingRule> _rules; #if CODE_STYLE public static readonly CSharpSyntaxFormattingService Instance = new(); #else [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] #endif public CSharpSyntaxFormattingService() { _rules = ImmutableList.Create<AbstractFormattingRule>( new WrappingFormattingRule(), new SpacingFormattingRule(), new NewLineUserSettingFormattingRule(), new IndentUserSettingsFormattingRule(), new ElasticTriviaFormattingRule(), new EndOfFileTokenFormattingRule(), new StructuredTriviaFormattingRule(), new IndentBlockFormattingRule(), new SuppressFormattingRule(), new AnchorIndentationFormattingRule(), new QueryExpressionFormattingRule(), new TokenBasedFormattingRule(), DefaultOperationProvider.Instance); } public override IEnumerable<AbstractFormattingRule> GetDefaultFormattingRules() => _rules; protected override IFormattingResult CreateAggregatedFormattingResult(SyntaxNode node, IList<AbstractFormattingResult> results, SimpleIntervalTree<TextSpan, TextSpanIntervalIntrospector>? formattingSpans = null) => new AggregatedFormattingResult(node, results, formattingSpans); protected override AbstractFormattingResult Format(SyntaxNode node, AnalyzerConfigOptions options, IEnumerable<AbstractFormattingRule> formattingRules, SyntaxToken token1, SyntaxToken token2, CancellationToken cancellationToken) => new CSharpFormatEngine(node, options, formattingRules, token1, token2).Format(cancellationToken); } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/Core/Portable/Emit/ModulePropertiesForSerialization.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection.PortableExecutable; namespace Microsoft.Cci { /// <summary> /// This class is used to store the module serialization properties for a compilation. /// </summary> internal sealed class ModulePropertiesForSerialization { /// <summary> /// The alignment factor (in bytes) that is used to align the raw data of sections in the image file. /// The value should be a power of 2 between 512 and 64K, inclusive. The default is 512. /// </summary> public readonly int FileAlignment; /// <summary> /// The alignment (in bytes) of sections when they are loaded into memory. /// It must be greater than or equal to <see cref="FileAlignment"/>. /// The default is the page size for the architecture. /// </summary> public readonly int SectionAlignment; /// <summary> /// Identifies the version of the CLR that is required to load this module or assembly. /// </summary> public readonly string TargetRuntimeVersion; /// <summary> /// Specifies the target CPU. <see cref="Machine.Unknown"/> means AnyCPU. /// </summary> public readonly Machine Machine; /// <summary> /// A globally unique persistent identifier for this module. /// </summary> public readonly Guid PersistentIdentifier; /// <summary> /// The preferred memory address at which the module is to be loaded at runtime. /// </summary> public readonly ulong BaseAddress; /// <summary> /// The size of the virtual memory to reserve for the initial process heap. /// Must fit into 32 bits if the target platform is 32 bit. /// </summary> public readonly ulong SizeOfHeapReserve; /// <summary> /// The size of the virtual memory initially committed for the initial process heap. /// Must fit into 32 bits if the target platform is 32 bit. /// </summary> public readonly ulong SizeOfHeapCommit; /// <summary> /// The size of the virtual memory to reserve for the initial thread's stack. /// Must fit into 32 bits if the target platform is 32 bit. /// </summary> public readonly ulong SizeOfStackReserve; public readonly ulong SizeOfStackCommit; public readonly ushort MajorSubsystemVersion; public readonly ushort MinorSubsystemVersion; /// <summary> /// The first part of a two part version number indicating the version of the linker that produced this module. For example, the 8 in 8.0. /// </summary> public readonly byte LinkerMajorVersion; /// <summary> /// The first part of a two part version number indicating the version of the linker that produced this module. For example, the 0 in 8.0. /// </summary> public readonly byte LinkerMinorVersion; /// <summary> /// Flags that control the behavior of the target operating system. CLI implementations are supposed to ignore this, but some operating system pay attention. /// </summary> public DllCharacteristics DllCharacteristics { get; } public Characteristics ImageCharacteristics { get; } public Subsystem Subsystem { get; } public CorFlags CorFlags { get; } public const ulong DefaultExeBaseAddress32Bit = 0x00400000; public const ulong DefaultExeBaseAddress64Bit = 0x0000000140000000; public const ulong DefaultDllBaseAddress32Bit = 0x10000000; public const ulong DefaultDllBaseAddress64Bit = 0x0000000180000000; public const ulong DefaultSizeOfHeapReserve32Bit = 0x00100000; public const ulong DefaultSizeOfHeapReserve64Bit = 0x00400000; public const ulong DefaultSizeOfHeapCommit32Bit = 0x1000; public const ulong DefaultSizeOfHeapCommit64Bit = 0x2000; public const ulong DefaultSizeOfStackReserve32Bit = 0x00100000; public const ulong DefaultSizeOfStackReserve64Bit = 0x00400000; public const ulong DefaultSizeOfStackCommit32Bit = 0x1000; public const ulong DefaultSizeOfStackCommit64Bit = 0x4000; public const ushort DefaultFileAlignment32Bit = 0x200; public const ushort DefaultFileAlignment64Bit = 0x200; //both 32 and 64 bit binaries used this value in the native stack. public const ushort DefaultSectionAlignment = 0x2000; internal ModulePropertiesForSerialization( Guid persistentIdentifier, CorFlags corFlags, int fileAlignment, int sectionAlignment, string targetRuntimeVersion, Machine machine, ulong baseAddress, ulong sizeOfHeapReserve, ulong sizeOfHeapCommit, ulong sizeOfStackReserve, ulong sizeOfStackCommit, DllCharacteristics dllCharacteristics, Characteristics imageCharacteristics, Subsystem subsystem, ushort majorSubsystemVersion, ushort minorSubsystemVersion, byte linkerMajorVersion, byte linkerMinorVersion) { this.PersistentIdentifier = persistentIdentifier; this.FileAlignment = fileAlignment; this.SectionAlignment = sectionAlignment; this.TargetRuntimeVersion = targetRuntimeVersion; this.Machine = machine; this.BaseAddress = baseAddress; this.SizeOfHeapReserve = sizeOfHeapReserve; this.SizeOfHeapCommit = sizeOfHeapCommit; this.SizeOfStackReserve = sizeOfStackReserve; this.SizeOfStackCommit = sizeOfStackCommit; this.LinkerMajorVersion = linkerMajorVersion; this.LinkerMinorVersion = linkerMinorVersion; this.MajorSubsystemVersion = majorSubsystemVersion; this.MinorSubsystemVersion = minorSubsystemVersion; this.ImageCharacteristics = imageCharacteristics; this.Subsystem = subsystem; this.DllCharacteristics = dllCharacteristics; this.CorFlags = corFlags; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Reflection.PortableExecutable; namespace Microsoft.Cci { /// <summary> /// This class is used to store the module serialization properties for a compilation. /// </summary> internal sealed class ModulePropertiesForSerialization { /// <summary> /// The alignment factor (in bytes) that is used to align the raw data of sections in the image file. /// The value should be a power of 2 between 512 and 64K, inclusive. The default is 512. /// </summary> public readonly int FileAlignment; /// <summary> /// The alignment (in bytes) of sections when they are loaded into memory. /// It must be greater than or equal to <see cref="FileAlignment"/>. /// The default is the page size for the architecture. /// </summary> public readonly int SectionAlignment; /// <summary> /// Identifies the version of the CLR that is required to load this module or assembly. /// </summary> public readonly string TargetRuntimeVersion; /// <summary> /// Specifies the target CPU. <see cref="Machine.Unknown"/> means AnyCPU. /// </summary> public readonly Machine Machine; /// <summary> /// A globally unique persistent identifier for this module. /// </summary> public readonly Guid PersistentIdentifier; /// <summary> /// The preferred memory address at which the module is to be loaded at runtime. /// </summary> public readonly ulong BaseAddress; /// <summary> /// The size of the virtual memory to reserve for the initial process heap. /// Must fit into 32 bits if the target platform is 32 bit. /// </summary> public readonly ulong SizeOfHeapReserve; /// <summary> /// The size of the virtual memory initially committed for the initial process heap. /// Must fit into 32 bits if the target platform is 32 bit. /// </summary> public readonly ulong SizeOfHeapCommit; /// <summary> /// The size of the virtual memory to reserve for the initial thread's stack. /// Must fit into 32 bits if the target platform is 32 bit. /// </summary> public readonly ulong SizeOfStackReserve; public readonly ulong SizeOfStackCommit; public readonly ushort MajorSubsystemVersion; public readonly ushort MinorSubsystemVersion; /// <summary> /// The first part of a two part version number indicating the version of the linker that produced this module. For example, the 8 in 8.0. /// </summary> public readonly byte LinkerMajorVersion; /// <summary> /// The first part of a two part version number indicating the version of the linker that produced this module. For example, the 0 in 8.0. /// </summary> public readonly byte LinkerMinorVersion; /// <summary> /// Flags that control the behavior of the target operating system. CLI implementations are supposed to ignore this, but some operating system pay attention. /// </summary> public DllCharacteristics DllCharacteristics { get; } public Characteristics ImageCharacteristics { get; } public Subsystem Subsystem { get; } public CorFlags CorFlags { get; } public const ulong DefaultExeBaseAddress32Bit = 0x00400000; public const ulong DefaultExeBaseAddress64Bit = 0x0000000140000000; public const ulong DefaultDllBaseAddress32Bit = 0x10000000; public const ulong DefaultDllBaseAddress64Bit = 0x0000000180000000; public const ulong DefaultSizeOfHeapReserve32Bit = 0x00100000; public const ulong DefaultSizeOfHeapReserve64Bit = 0x00400000; public const ulong DefaultSizeOfHeapCommit32Bit = 0x1000; public const ulong DefaultSizeOfHeapCommit64Bit = 0x2000; public const ulong DefaultSizeOfStackReserve32Bit = 0x00100000; public const ulong DefaultSizeOfStackReserve64Bit = 0x00400000; public const ulong DefaultSizeOfStackCommit32Bit = 0x1000; public const ulong DefaultSizeOfStackCommit64Bit = 0x4000; public const ushort DefaultFileAlignment32Bit = 0x200; public const ushort DefaultFileAlignment64Bit = 0x200; //both 32 and 64 bit binaries used this value in the native stack. public const ushort DefaultSectionAlignment = 0x2000; internal ModulePropertiesForSerialization( Guid persistentIdentifier, CorFlags corFlags, int fileAlignment, int sectionAlignment, string targetRuntimeVersion, Machine machine, ulong baseAddress, ulong sizeOfHeapReserve, ulong sizeOfHeapCommit, ulong sizeOfStackReserve, ulong sizeOfStackCommit, DllCharacteristics dllCharacteristics, Characteristics imageCharacteristics, Subsystem subsystem, ushort majorSubsystemVersion, ushort minorSubsystemVersion, byte linkerMajorVersion, byte linkerMinorVersion) { this.PersistentIdentifier = persistentIdentifier; this.FileAlignment = fileAlignment; this.SectionAlignment = sectionAlignment; this.TargetRuntimeVersion = targetRuntimeVersion; this.Machine = machine; this.BaseAddress = baseAddress; this.SizeOfHeapReserve = sizeOfHeapReserve; this.SizeOfHeapCommit = sizeOfHeapCommit; this.SizeOfStackReserve = sizeOfStackReserve; this.SizeOfStackCommit = sizeOfStackCommit; this.LinkerMajorVersion = linkerMajorVersion; this.LinkerMinorVersion = linkerMinorVersion; this.MajorSubsystemVersion = majorSubsystemVersion; this.MinorSubsystemVersion = minorSubsystemVersion; this.ImageCharacteristics = imageCharacteristics; this.Subsystem = subsystem; this.DllCharacteristics = dllCharacteristics; this.CorFlags = corFlags; } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Features/Core/Portable/GenerateMember/GenerateParameterizedMember/AbstractGenerateMethodService.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal partial class AbstractGenerateMethodService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> { internal new class State : AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>.State { public static async Task<State> GenerateMethodStateAsync( TService service, SemanticDocument document, SyntaxNode interfaceNode, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeMethodAsync(service, document, interfaceNode, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private Task<bool> TryInitializeMethodAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { // Cases that we deal with currently: // // 1) expr.Goo // 2) expr->Goo // 3) Goo // 4) expr.Goo() // 5) expr->Goo() // 6) Goo() // 7) ReturnType Explicit.Interface.Goo() // // In the first 3 invocationExpressionOpt will be null and we'll have to infer a // delegate type in order to figure out the right method signature to generate. In // the next 3 invocationExpressionOpt will be non null and will be used to figure // out the types/name of the parameters to generate. In the last one, we're going to // generate into an interface. if (service.IsExplicitInterfaceGeneration(node)) { if (!TryInitializeExplicitInterface(service, document, node, cancellationToken)) { return SpecializedTasks.False; } } else if (service.IsSimpleNameGeneration(node)) { if (!TryInitializeSimpleName(service, document, (TSimpleNameSyntax)node, cancellationToken)) { return SpecializedTasks.False; } } return TryFinishInitializingStateAsync(service, document, cancellationToken); } private bool TryInitializeExplicitInterface( TService service, SemanticDocument document, SyntaxNode methodDeclaration, CancellationToken cancellationToken) { MethodKind = MethodKind.Ordinary; if (!service.TryInitializeExplicitInterfaceState( document, methodDeclaration, cancellationToken, out var identifierToken, out var methodSymbol, out var typeToGenerateIn)) { return false; } if (methodSymbol.ExplicitInterfaceImplementations.Any()) { return false; } IdentifierToken = identifierToken; TypeToGenerateIn = typeToGenerateIn; cancellationToken.ThrowIfCancellationRequested(); var semanticModel = document.SemanticModel; ContainingType = semanticModel.GetEnclosingNamedType(methodDeclaration.SpanStart, cancellationToken); if (ContainingType == null) { return false; } if (!ContainingType.Interfaces.Contains(TypeToGenerateIn)) { return false; } SignatureInfo = new MethodSignatureInfo(document, this, methodSymbol); return true; } private bool TryInitializeSimpleName( TService service, SemanticDocument semanticDocument, TSimpleNameSyntax simpleName, CancellationToken cancellationToken) { MethodKind = MethodKind.Ordinary; SimpleNameOpt = simpleName; if (!service.TryInitializeSimpleNameState( semanticDocument, simpleName, cancellationToken, out var identifierToken, out var simpleNameOrMemberAccessExpression, out var invocationExpressionOpt, out var isInConditionalExpression)) { return false; } IdentifierToken = identifierToken; SimpleNameOrMemberAccessExpression = simpleNameOrMemberAccessExpression; InvocationExpressionOpt = invocationExpressionOpt; IsInConditionalAccessExpression = isInConditionalExpression; if (string.IsNullOrWhiteSpace(IdentifierToken.ValueText)) { return false; } // If we're not in a type, don't even bother. NOTE(cyrusn): We'll have to rethink this // for C# Script. cancellationToken.ThrowIfCancellationRequested(); var semanticModel = semanticDocument.SemanticModel; ContainingType = semanticModel.GetEnclosingNamedType(SimpleNameOpt.SpanStart, cancellationToken); if (ContainingType == null) { return false; } if (InvocationExpressionOpt != null) { SignatureInfo = service.CreateInvocationMethodInfo(semanticDocument, this); } else { var typeInference = semanticDocument.Document.GetLanguageService<ITypeInferenceService>(); var delegateType = typeInference.InferDelegateType(semanticModel, SimpleNameOrMemberAccessExpression, cancellationToken); if (delegateType != null && delegateType.DelegateInvokeMethod != null) { SignatureInfo = new MethodSignatureInfo(semanticDocument, this, delegateType.DelegateInvokeMethod); } else { // We don't have and invocation expression or a delegate, but we may have a special expression without parenthesis. Lets see // if the type inference service can directly infer the type for our expression. var expressionType = service.DetermineReturnTypeForSimpleNameOrMemberAccessExpression(typeInference, semanticModel, SimpleNameOrMemberAccessExpression, cancellationToken); if (expressionType == null) { return false; } SignatureInfo = new MethodSignatureInfo(semanticDocument, this, CreateMethodSymbolWithReturnType(expressionType)); } } // Now, try to bind the invocation and see if it succeeds or not. if it succeeds and // binds uniquely, then we don't need to offer this quick fix. cancellationToken.ThrowIfCancellationRequested(); // If the name bound with errors, then this is a candidate for generate method. var semanticInfo = semanticModel.GetSymbolInfo(SimpleNameOrMemberAccessExpression, cancellationToken); if (semanticInfo.GetAllSymbols().Any(s => s.Kind is SymbolKind.Local or SymbolKind.Parameter) && !service.AreSpecialOptionsActive(semanticModel)) { // if the name bound to something in scope then we don't want to generate the // method because it will be shadowed by what's in scope. Unless we are in a // special state such as Option Strict On where we want to generate fixes even // if we shadow types. return false; } // Check if the symbol is on the list of valid symbols for this language. cancellationToken.ThrowIfCancellationRequested(); if (semanticInfo.Symbol != null && !service.IsValidSymbol(semanticInfo.Symbol, semanticModel)) { return false; } // Either we found no matches, or this was ambiguous. Either way, we might be able // to generate a method here. Determine where the user wants to generate the method // into, and if it's valid then proceed. cancellationToken.ThrowIfCancellationRequested(); if (!TryDetermineTypeToGenerateIn( semanticDocument, ContainingType, SimpleNameOrMemberAccessExpression, cancellationToken, out var typeToGenerateIn, out var isStatic)) { return false; } var semanticFacts = semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); IsWrittenTo = semanticFacts.IsWrittenTo(semanticModel, InvocationExpressionOpt ?? SimpleNameOrMemberAccessExpression, cancellationToken); TypeToGenerateIn = typeToGenerateIn; IsStatic = isStatic; MethodGenerationKind = MethodGenerationKind.Member; return true; } private static IMethodSymbol CreateMethodSymbolWithReturnType( ITypeSymbol expressionType) { return CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: default, modifiers: default, returnType: expressionType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: null, typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters: ImmutableArray<IParameterSymbol>.Empty); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateParameterizedMember { internal partial class AbstractGenerateMethodService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax> { internal new class State : AbstractGenerateParameterizedMemberService<TService, TSimpleNameSyntax, TExpressionSyntax, TInvocationExpressionSyntax>.State { public static async Task<State> GenerateMethodStateAsync( TService service, SemanticDocument document, SyntaxNode interfaceNode, CancellationToken cancellationToken) { var state = new State(); if (!await state.TryInitializeMethodAsync(service, document, interfaceNode, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private Task<bool> TryInitializeMethodAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { // Cases that we deal with currently: // // 1) expr.Goo // 2) expr->Goo // 3) Goo // 4) expr.Goo() // 5) expr->Goo() // 6) Goo() // 7) ReturnType Explicit.Interface.Goo() // // In the first 3 invocationExpressionOpt will be null and we'll have to infer a // delegate type in order to figure out the right method signature to generate. In // the next 3 invocationExpressionOpt will be non null and will be used to figure // out the types/name of the parameters to generate. In the last one, we're going to // generate into an interface. if (service.IsExplicitInterfaceGeneration(node)) { if (!TryInitializeExplicitInterface(service, document, node, cancellationToken)) { return SpecializedTasks.False; } } else if (service.IsSimpleNameGeneration(node)) { if (!TryInitializeSimpleName(service, document, (TSimpleNameSyntax)node, cancellationToken)) { return SpecializedTasks.False; } } return TryFinishInitializingStateAsync(service, document, cancellationToken); } private bool TryInitializeExplicitInterface( TService service, SemanticDocument document, SyntaxNode methodDeclaration, CancellationToken cancellationToken) { MethodKind = MethodKind.Ordinary; if (!service.TryInitializeExplicitInterfaceState( document, methodDeclaration, cancellationToken, out var identifierToken, out var methodSymbol, out var typeToGenerateIn)) { return false; } if (methodSymbol.ExplicitInterfaceImplementations.Any()) { return false; } IdentifierToken = identifierToken; TypeToGenerateIn = typeToGenerateIn; cancellationToken.ThrowIfCancellationRequested(); var semanticModel = document.SemanticModel; ContainingType = semanticModel.GetEnclosingNamedType(methodDeclaration.SpanStart, cancellationToken); if (ContainingType == null) { return false; } if (!ContainingType.Interfaces.Contains(TypeToGenerateIn)) { return false; } SignatureInfo = new MethodSignatureInfo(document, this, methodSymbol); return true; } private bool TryInitializeSimpleName( TService service, SemanticDocument semanticDocument, TSimpleNameSyntax simpleName, CancellationToken cancellationToken) { MethodKind = MethodKind.Ordinary; SimpleNameOpt = simpleName; if (!service.TryInitializeSimpleNameState( semanticDocument, simpleName, cancellationToken, out var identifierToken, out var simpleNameOrMemberAccessExpression, out var invocationExpressionOpt, out var isInConditionalExpression)) { return false; } IdentifierToken = identifierToken; SimpleNameOrMemberAccessExpression = simpleNameOrMemberAccessExpression; InvocationExpressionOpt = invocationExpressionOpt; IsInConditionalAccessExpression = isInConditionalExpression; if (string.IsNullOrWhiteSpace(IdentifierToken.ValueText)) { return false; } // If we're not in a type, don't even bother. NOTE(cyrusn): We'll have to rethink this // for C# Script. cancellationToken.ThrowIfCancellationRequested(); var semanticModel = semanticDocument.SemanticModel; ContainingType = semanticModel.GetEnclosingNamedType(SimpleNameOpt.SpanStart, cancellationToken); if (ContainingType == null) { return false; } if (InvocationExpressionOpt != null) { SignatureInfo = service.CreateInvocationMethodInfo(semanticDocument, this); } else { var typeInference = semanticDocument.Document.GetLanguageService<ITypeInferenceService>(); var delegateType = typeInference.InferDelegateType(semanticModel, SimpleNameOrMemberAccessExpression, cancellationToken); if (delegateType != null && delegateType.DelegateInvokeMethod != null) { SignatureInfo = new MethodSignatureInfo(semanticDocument, this, delegateType.DelegateInvokeMethod); } else { // We don't have and invocation expression or a delegate, but we may have a special expression without parenthesis. Lets see // if the type inference service can directly infer the type for our expression. var expressionType = service.DetermineReturnTypeForSimpleNameOrMemberAccessExpression(typeInference, semanticModel, SimpleNameOrMemberAccessExpression, cancellationToken); if (expressionType == null) { return false; } SignatureInfo = new MethodSignatureInfo(semanticDocument, this, CreateMethodSymbolWithReturnType(expressionType)); } } // Now, try to bind the invocation and see if it succeeds or not. if it succeeds and // binds uniquely, then we don't need to offer this quick fix. cancellationToken.ThrowIfCancellationRequested(); // If the name bound with errors, then this is a candidate for generate method. var semanticInfo = semanticModel.GetSymbolInfo(SimpleNameOrMemberAccessExpression, cancellationToken); if (semanticInfo.GetAllSymbols().Any(s => s.Kind is SymbolKind.Local or SymbolKind.Parameter) && !service.AreSpecialOptionsActive(semanticModel)) { // if the name bound to something in scope then we don't want to generate the // method because it will be shadowed by what's in scope. Unless we are in a // special state such as Option Strict On where we want to generate fixes even // if we shadow types. return false; } // Check if the symbol is on the list of valid symbols for this language. cancellationToken.ThrowIfCancellationRequested(); if (semanticInfo.Symbol != null && !service.IsValidSymbol(semanticInfo.Symbol, semanticModel)) { return false; } // Either we found no matches, or this was ambiguous. Either way, we might be able // to generate a method here. Determine where the user wants to generate the method // into, and if it's valid then proceed. cancellationToken.ThrowIfCancellationRequested(); if (!TryDetermineTypeToGenerateIn( semanticDocument, ContainingType, SimpleNameOrMemberAccessExpression, cancellationToken, out var typeToGenerateIn, out var isStatic)) { return false; } var semanticFacts = semanticDocument.Document.GetLanguageService<ISemanticFactsService>(); IsWrittenTo = semanticFacts.IsWrittenTo(semanticModel, InvocationExpressionOpt ?? SimpleNameOrMemberAccessExpression, cancellationToken); TypeToGenerateIn = typeToGenerateIn; IsStatic = isStatic; MethodGenerationKind = MethodGenerationKind.Member; return true; } private static IMethodSymbol CreateMethodSymbolWithReturnType( ITypeSymbol expressionType) { return CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: ImmutableArray<AttributeData>.Empty, accessibility: default, modifiers: default, returnType: expressionType, refKind: RefKind.None, explicitInterfaceImplementations: default, name: null, typeParameters: ImmutableArray<ITypeParameterSymbol>.Empty, parameters: ImmutableArray<IParameterSymbol>.Empty); } } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/CSharp/Test/Emit/Attributes/AttributeTests_Assembly.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AssemblyAttributeTests : CSharpTestBase { private readonly string _netModuleName = GetUniqueName() + ".netmodule"; [Fact] public void VersionAttribute() { string s = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal(new Version(1, 2, 3, 4), other.Assembly.Identity.Version); } [Fact] public void VersionAttribute_FourParts() { string s = @"[assembly: System.Reflection.AssemblyVersion(""1.22.333.4444"")] public class C {}"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, r => { Assert.Equal(new Version(1, 22, 333, 4444), r.Version); }); } [Fact] public void VersionAttribute_TwoParts() { var s = @"[assembly: System.Reflection.AssemblyVersion(""1.2"")] public class C {}"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, r => { Assert.Equal(1, r.Version.Major); Assert.Equal(2, r.Version.Minor); Assert.Equal(0, r.Version.Build); Assert.Equal(0, r.Version.Revision); }); } [Fact] public void VersionAttribute_WildCard() { var now = DateTime.Now; int days, seconds; VersionTestHelpers.GetDefaultVersion(now, out days, out seconds); var s = @"[assembly: System.Reflection.AssemblyVersion(""10101.0.*"")] public class C {}"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll.WithCurrentLocalTime(now)); VerifyAssemblyTable(comp, r => { Assert.Equal(10101, r.Version.Major); Assert.Equal(0, r.Version.Minor); Assert.Equal(days, r.Version.Build); Assert.Equal(seconds, r.Version.Revision); }); } [Fact] public void VersionAttribute_Overflow() { var s = @"[assembly: System.Reflection.AssemblyVersion(""10101.0.*"")] public class C {}"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll.WithCurrentLocalTime(new DateTime(2300, 1, 1))); VerifyAssemblyTable(comp, r => { Assert.Equal(10101, r.Version.Major); Assert.Equal(0, r.Version.Minor); Assert.Equal(65535, r.Version.Build); Assert.Equal(0, r.Version.Revision); }); } [Fact, WorkItem(545947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545947")] public void VersionAttributeErr() { string s = @"[assembly: System.Reflection.AssemblyVersion(""1.*"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics( // (1,46): error CS7034: The specified version string does not conform to the required format - major[.minor[.build[.revision]]] // [assembly: System.Reflection.AssemblyVersion("1.*")] public class C {} Diagnostic(ErrorCode.ERR_InvalidVersionFormat, @"""1.*""").WithLocation(1, 46)); s = @"[assembly: System.Reflection.AssemblyVersion(""-1"")] public class C {}"; other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics( // (1,46): error CS7034: The specified version string does not conform to the required format - major[.minor[.build[.revision]]] // [assembly: System.Reflection.AssemblyVersion("-1")] public class C {} Diagnostic(ErrorCode.ERR_InvalidVersionFormat, @"""-1""").WithLocation(1, 46)); } [Fact, WorkItem(22660, "https://github.com/dotnet/roslyn/issues/22660")] public void VersionAttributeWithWildcardAndDeterminism() { string s = @"[assembly: System.Reflection.AssemblyVersion(""1.1.1.*"")]"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll.WithDeterministic(true)); comp.VerifyDiagnostics( // (1,46): error CS8357: The specified version string contains wildcards, which are not compatible with determinism. Either remove wildcards from the version string, or disable determinism for this compilation // [assembly: System.Reflection.AssemblyVersion("1.1.1.*")] Diagnostic(ErrorCode.ERR_InvalidVersionFormatDeterministic, @"""1.1.1.*""").WithLocation(1, 46) ); } [Fact] public void FileVersionAttribute() { string s = @"[assembly: System.Reflection.AssemblyFileVersion(""1.2.3.4"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("1.2.3.4", ((SourceAssemblySymbol)other.Assembly).FileVersion); } [Fact] public void FileVersionAttribute_MissingParts() { string s = @"[assembly: System.Reflection.AssemblyFileVersion(""1.2"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("1.2", ((SourceAssemblySymbol)other.Assembly).FileVersion); } [Fact] public void FileVersionAttribute_MaxValue() { string s = @"[assembly: System.Reflection.AssemblyFileVersion(""65535.65535.65535.65535"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("65535.65535.65535.65535", ((SourceAssemblySymbol)other.Assembly).FileVersion); } [Fact] public void FileVersionAttributeWrn_Wildcard() { string s = @"[assembly: System.Reflection.AssemblyFileVersion(""1.2.*"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_InvalidVersionFormat, @"""1.2.*""")); // Confirm that suppressing the old alink warning 1607 shuts off WRN_ConflictingMachineAssembly var warnings = new Dictionary<string, ReportDiagnostic>(); warnings.Add(MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn), ReportDiagnostic.Suppress); other = other.WithOptions(other.Options.WithSpecificDiagnosticOptions(warnings)); other.VerifyEmitDiagnostics(); } [Fact] public void FileVersionAttributeWarning_OutOfRange() { string s = @"[assembly: System.Reflection.AssemblyFileVersion(""1.65536"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_InvalidVersionFormat, @"""1.65536""")); // Confirm that suppressing the old alink warning 1607 shuts off WRN_ConflictingMachineAssembly var warnings = new Dictionary<string, ReportDiagnostic>(); warnings.Add(MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn), ReportDiagnostic.Suppress); other = other.WithOptions(other.Options.WithSpecificDiagnosticOptions(warnings)); other.VerifyEmitDiagnostics(); } [Fact, WorkItem(545947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545947"), WorkItem(546971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546971"), WorkItem(22660, "https://github.com/dotnet/roslyn/issues/22660")] public void SatelliteContractVersionAttributeErr() { string s = @"[assembly: System.Resources.SatelliteContractVersionAttribute(""1.2.3.A"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics( // (1,63): error CS7058: The specified version string does not conform to the required format - major.minor.build.revision (without wildcards) // [assembly: System.Resources.SatelliteContractVersionAttribute("1.2.3.A")] public class C {} Diagnostic(ErrorCode.ERR_InvalidVersionFormat2, @"""1.2.3.A""").WithLocation(1, 63) ); s = @"[assembly: System.Resources.SatelliteContractVersionAttribute(""1.2.*"")] public class C {}"; other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics( // (1,63): error CS7058: The specified version string does not conform to the required format - major.minor.build.revision (without wildcards) // [assembly: System.Resources.SatelliteContractVersionAttribute("1.2.*")] public class C {} Diagnostic(ErrorCode.ERR_InvalidVersionFormat2, @"""1.2.*""").WithLocation(1, 63) ); s = @"[assembly: System.Resources.SatelliteContractVersionAttribute(""1"")] public class C {}"; other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics(); } [Fact] public void TitleAttribute() { string s = @"[assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("One Hundred Years of Solitude", ((SourceAssemblySymbol)other.Assembly).Title); } [Fact] public void TitleAttributeNull() { string s = @"[assembly: System.Reflection.AssemblyTitle(null)] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Null(((SourceAssemblySymbol)other.Assembly).Title); } [Fact] public void DescriptionAttribute() { string s = @"[assembly: System.Reflection.AssemblyDescription(""A classic of magical realist literature"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("A classic of magical realist literature", ((SourceAssemblySymbol)other.Assembly).Description); } [Fact] public void CultureAttribute() { string s = @"[assembly: System.Reflection.AssemblyCulture(""pt-BR"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("pt-BR", (other.Assembly.Identity.CultureName)); } [Fact] public void CultureAttribute02() { string s = @"[assembly: System.Reflection.AssemblyCultureAttribute("""")]"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, r => { Assert.True(r.Culture.IsNil); }); s = @"[assembly: System.Reflection.AssemblyCulture(null)] public class C { static void Main() { } }"; comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, r => { Assert.True(r.Culture.IsNil); }); s = @"[assembly: System.Reflection.AssemblyCultureAttribute(""zh-CN"")]"; comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, null, strData: "zh-CN"); } [Fact, WorkItem(545949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545949")] public void CultureAttribute03() { // Executables cannot be satellite assemblies; culture should always be empty string s = @"[assembly: System.Reflection.AssemblyCulture(null)] public class C { static void Main() { } }"; var comp = CreateCompilation(s, options: TestOptions.ReleaseExe); VerifyAssemblyTable(comp, r => { Assert.True(r.Culture.IsNil); }); s = @"[assembly: System.Reflection.AssemblyCulture("""")] public class C { static void Main() { } }"; comp = CreateCompilation(s, options: TestOptions.ReleaseExe); VerifyAssemblyTable(comp, r => { Assert.True(r.Culture.IsNil); }); } [Fact, WorkItem(545949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545949")] public void CultureAttributeErr() { string s = @"[assembly: System.Reflection.AssemblyCulture(""pt-BR"")] public class C { static void Main() { } }"; var comp = CreateCompilation(s, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (1,46): error CS7059: Executables cannot be satellite assemblies; culture should always be empty // [assembly: System.Reflection.AssemblyCulture("pt-BR")] public class C { static void Main() { } } Diagnostic(ErrorCode.ERR_InvalidAssemblyCultureForExe, @"""pt-BR""").WithLocation(1, 46)); } [WorkItem(1032718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032718")] [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10839")] public void MismatchedSurrogateInAssemblyCultureAttribute() { string s = @"[assembly: System.Reflection.AssemblyCultureAttribute(""\uD800"")]"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); CompileAndVerify(comp, verify: Verification.Fails, symbolValidator: m => { var utf8 = new System.Text.UTF8Encoding(false, false); Assert.Equal(utf8.GetString(utf8.GetBytes("\uD800")), m.ContainingAssembly.Identity.CultureName); }); } [Fact, WorkItem(1034455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1034455")] public void NulCharInAssemblyCultureAttribute() { string s = @"[assembly: System.Reflection.AssemblyCultureAttribute(""\0"")]"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (1,55): error CS7100: Assembly culture strings may not contain embedded NUL characters. // [assembly: System.Reflection.AssemblyCultureAttribute("\0")] Diagnostic(ErrorCode.ERR_InvalidAssemblyCulture, @"""\0""").WithLocation(1, 55)); } [Fact] public void CultureAttributeMismatch() { var neutral = CreateCompilationWithMscorlib40( @" public class neutral {} ", options: TestOptions.ReleaseDll, assemblyName: "neutral"); var neutralRef = new CSharpCompilationReference(neutral); var de = CreateCompilationWithMscorlib40( @" [assembly: System.Reflection.AssemblyCultureAttribute(""de"")] public class de {} ", options: TestOptions.ReleaseDll, assemblyName: "de"); var deRef = new CSharpCompilationReference(de); var en_us = CreateCompilationWithMscorlib40( @" [assembly: System.Reflection.AssemblyCultureAttribute(""en-us"")] public class en_us {} ", options: TestOptions.ReleaseDll, assemblyName: "en_us"); var en_usRef = new CSharpCompilationReference(en_us); CSharpCompilation compilation; string assemblyNameBase = Guid.NewGuid().ToString(); compilation = CreateCompilationWithMscorlib40( @" [assembly: System.Reflection.AssemblyCultureAttribute(""en-US"")] public class en_US { void M(de x) {} } ", new MetadataReference[] { deRef, neutralRef }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "10"); CompileAndVerify(compilation).VerifyDiagnostics( // warning CS8009: Referenced assembly 'de, Version=0.0.0.0, Culture=de, PublicKeyToken=null' has different culture setting of 'de'. Diagnostic(ErrorCode.WRN_RefCultureMismatch).WithArguments("de, Version=0.0.0.0, Culture=de, PublicKeyToken=null", "de") ); compilation = compilation.WithOptions(TestOptions.ReleaseModule); compilation.VerifyEmitDiagnostics(); compilation = CreateCompilationWithMscorlib40("", new MetadataReference[] { compilation.EmitToImageReference() }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "20"); CompileAndVerify(compilation, verify: Verification.Skipped).VerifyDiagnostics( // warning CS8009: Referenced assembly 'de, Version=0.0.0.0, Culture=de, PublicKeyToken=null' has different culture setting of 'de'. Diagnostic(ErrorCode.WRN_RefCultureMismatch).WithArguments("de, Version=0.0.0.0, Culture=de, PublicKeyToken=null", "de") ); // Confirm that suppressing the old alink warning 1607 shuts off WRN_RefCultureMismatch var warnings = new Dictionary<string, ReportDiagnostic>(); warnings.Add(MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn), ReportDiagnostic.Suppress); compilation = compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)); compilation.VerifyEmitDiagnostics(); compilation = CreateCompilationWithMscorlib40( @" [assembly: System.Reflection.AssemblyCultureAttribute(""en-US"")] public class Test { void M(en_us x) {} } ", new MetadataReference[] { en_usRef }, options: TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "23"); compilation.VerifyEmitDiagnostics(); compilation = compilation.WithOptions(TestOptions.ReleaseModule); compilation.VerifyEmitDiagnostics(); compilation = CreateCompilationWithMscorlib40("", new MetadataReference[] { compilation.EmitToImageReference() }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "25"); compilation.VerifyEmitDiagnostics(); compilation = CreateCompilationWithMscorlib40( @" [assembly: System.Reflection.AssemblyCultureAttribute(""en-US"")] public class en_US { void M(neutral x) {} } ", new MetadataReference[] { deRef, neutralRef }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "30"); CompileAndVerify(compilation).VerifyDiagnostics(); compilation = compilation.WithOptions(TestOptions.ReleaseModule); compilation.VerifyEmitDiagnostics(); compilation = CreateCompilationWithMscorlib40("", new MetadataReference[] { compilation.EmitToImageReference() }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "40"); CompileAndVerify(compilation, sourceSymbolValidator: m => { Assert.Equal(1, m.GetReferencedAssemblySymbols().Length); var naturalRef = m.ContainingAssembly.Modules[1].GetReferencedAssemblySymbols()[1]; Assert.True(naturalRef.IsMissing); Assert.Equal("neutral, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", naturalRef.ToTestDisplayString()); }, symbolValidator: m => { Assert.Equal(2, ((PEModuleSymbol)m).GetReferencedAssemblySymbols().Length); Assert.Equal("neutral, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", m.GetReferencedAssemblySymbols()[1].ToTestDisplayString()); }, verify: Verification.Skipped).VerifyDiagnostics(); compilation = CreateCompilationWithMscorlib40( @" public class neutral { void M(de x) {} } ", new MetadataReference[] { deRef }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "50"); CompileAndVerify(compilation).VerifyDiagnostics( // warning CS8009: Referenced assembly 'de, Version=0.0.0.0, Culture=de, PublicKeyToken=null' has different culture setting of 'de'. Diagnostic(ErrorCode.WRN_RefCultureMismatch).WithArguments("de, Version=0.0.0.0, Culture=de, PublicKeyToken=null", "de") ); compilation = compilation.WithOptions(TestOptions.ReleaseModule); compilation.VerifyEmitDiagnostics(); compilation = CreateCompilationWithMscorlib40("", new MetadataReference[] { compilation.EmitToImageReference() }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "60"); CompileAndVerify(compilation, verify: Verification.Skipped).VerifyDiagnostics( // warning CS8009: Referenced assembly 'de, Version=0.0.0.0, Culture=de, PublicKeyToken=null' has different culture setting of 'de'. Diagnostic(ErrorCode.WRN_RefCultureMismatch).WithArguments("de, Version=0.0.0.0, Culture=de, PublicKeyToken=null", "de") ); } [Fact] public void CompanyAttribute() { string s = @"[assembly: System.Reflection.AssemblyCompany(""MossBrain"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("MossBrain", ((SourceAssemblySymbol)other.Assembly).Company); s = @"[assembly: System.Reflection.AssemblyCompany(""微软"")] public class C {}"; other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("微软", ((SourceAssemblySymbol)other.Assembly).Company); } [Fact] public void ProductAttribute() { string s = @"[assembly: System.Reflection.AssemblyProduct(""Sound Cannon"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("Sound Cannon", ((SourceAssemblySymbol)other.Assembly).Product); } [Fact] public void CopyrightAttribute() { string s = @"[assembly: System.Reflection.AssemblyCopyright(""مايكروسوفت"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("مايكروسوفت", ((SourceAssemblySymbol)other.Assembly).Copyright); } [Fact] public void TrademarkAttribute() { string s = @"[assembly: System.Reflection.AssemblyTrademark(""circle R"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("circle R", ((SourceAssemblySymbol)other.Assembly).Trademark); s = @"[assembly: System.Reflection.AssemblyTrademark("""")] namespace N {}"; other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("", ((SourceAssemblySymbol)other.Assembly).Trademark); } [Fact] public void InformationalVersionAttribute() { string s = @"[assembly: System.Reflection.AssemblyInformationalVersion(""1.2.3garbage"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyEmitDiagnostics(); Assert.Equal("1.2.3garbage", ((SourceAssemblySymbol)other.Assembly).InformationalVersion); } [Fact, WorkItem(529921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529921")] public void AlgorithmIdAttribute() { var hash_module = TestReferences.SymbolsTests.netModule.hash_module; var hash_resources = new[] {new ResourceDescription("hash_resource", "snKey.snk", () => new MemoryStream(TestResources.General.snKey, writable: false), true)}; CSharpCompilation compilation; compilation = CreateCompilation( @" class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { hash_module }); CompileAndVerify(compilation, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(AssemblyHashAlgorithm.Sha1, assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0x6C, 0x9C, 0x3E, 0xDA, 0x60, 0x0F, 0x81, 0x93, 0x4A, 0xC1, 0x0D, 0x41, 0xB3, 0xE9, 0xB2, 0xB7, 0x2D, 0xEE, 0x59, 0xA8 }, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0x7F, 0x28, 0xEA, 0xD1, 0xF4, 0xA1, 0x7C, 0xB8, 0x0C, 0x14, 0xC0, 0x2E, 0x8C, 0xFF, 0x10, 0xEC, 0xB3, 0xC2, 0xA5, 0x1D }, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.None)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { hash_module }); CompileAndVerify(compilation, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(AssemblyHashAlgorithm.None, assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0x6C, 0x9C, 0x3E, 0xDA, 0x60, 0x0F, 0x81, 0x93, 0x4A, 0xC1, 0x0D, 0x41, 0xB3, 0xE9, 0xB2, 0xB7, 0x2D, 0xEE, 0x59, 0xA8 }, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0x7F, 0x28, 0xEA, 0xD1, 0xF4, 0xA1, 0x7C, 0xB8, 0x0C, 0x14, 0xC0, 0x2E, 0x8C, 0xFF, 0x10, 0xEC, 0xB3, 0xC2, 0xA5, 0x1D }, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute((uint)System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { hash_module }); CompileAndVerify(compilation, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(AssemblyHashAlgorithm.MD5, assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0x24, 0x22, 0x03, 0xC3, 0x94, 0xD5, 0xC2, 0xD9, 0x99, 0xB3, 0x6D, 0x59, 0xB2, 0xCA, 0x23, 0xBC }, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0x8D, 0xFE, 0xBF, 0x49, 0x8D, 0x62, 0x2A, 0x88, 0x89, 0xD1, 0x0E, 0x00, 0x9E, 0x29, 0x72, 0xF1 }, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { hash_module }); CompileAndVerify(compilation, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(AssemblyHashAlgorithm.Sha1, assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0x6C, 0x9C, 0x3E, 0xDA, 0x60, 0x0F, 0x81, 0x93, 0x4A, 0xC1, 0x0D, 0x41, 0xB3, 0xE9, 0xB2, 0xB7, 0x2D, 0xEE, 0x59, 0xA8 }, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0x7F, 0x28, 0xEA, 0xD1, 0xF4, 0xA1, 0x7C, 0xB8, 0x0C, 0x14, 0xC0, 0x2E, 0x8C, 0xFF, 0x10, 0xEC, 0xB3, 0xC2, 0xA5, 0x1D }, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA256)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { MscorlibRef_v4_0_30316_17626, hash_module }); CompileAndVerify(compilation, verify: Verification.Fails, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA256, (System.Configuration.Assemblies.AssemblyHashAlgorithm)assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0xA2, 0x32, 0x3F, 0x0D, 0xF4, 0xB8, 0xED, 0x5A, 0x1B, 0x7B, 0xBE, 0x14, 0x4F, 0xEC, 0xBF, 0x88, 0x23, 0x61, 0xEB, 0x40, 0xF7, 0xF9, 0x46, 0xEF, 0x68, 0x3B, 0x70, 0x29, 0xCF, 0x12, 0x05, 0x35 }, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0xCC, 0xAE, 0xA0, 0xB4, 0x9E, 0xAE, 0x28, 0xE0, 0xA3, 0x46, 0xE9, 0xCF, 0xF3, 0xEF, 0xEA, 0xF7, 0x1D, 0xDE, 0x62, 0x8F, 0xD6, 0xF4, 0x87, 0x76, 0x1A, 0xC3, 0x6F, 0xAD, 0x10, 0x1C, 0x10, 0xAC}, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA384)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { MscorlibRef_v4_0_30316_17626, hash_module }); CompileAndVerify(compilation, verify: Verification.Fails, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA384, (System.Configuration.Assemblies.AssemblyHashAlgorithm)assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0xB6, 0x35, 0x9B, 0xBE, 0x82, 0x89, 0xFF, 0x01, 0x22, 0x8B, 0x56, 0x5E, 0x9B, 0x15, 0x5D, 0x10, 0x68, 0x83, 0xF7, 0x75, 0x4E, 0xA6, 0x30, 0xF7, 0x8D, 0x39, 0x9A, 0xB7, 0xE8, 0xB6, 0x47, 0x1F, 0xF6, 0xFD, 0x1E, 0x64, 0x63, 0x6B, 0xE7, 0xF4, 0xBE, 0xA7, 0x21, 0xED, 0xFC, 0x82, 0x38, 0x95}, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0x45, 0x05, 0x2E, 0x90, 0x9B, 0x61, 0xA3, 0xF8, 0x60, 0xD2, 0x86, 0xCB, 0x10, 0x33, 0xC9, 0x86, 0x68, 0xA5, 0xEE, 0x4A, 0xCF, 0x21, 0x10, 0xA9, 0x8F, 0x14, 0x62, 0x8D, 0x3E, 0x7D, 0xFD, 0x7E, 0xE6, 0x23, 0x6F, 0x2D, 0xBA, 0x04, 0xE7, 0x13, 0xE4, 0x5E, 0x8C, 0xEB, 0x80, 0x68, 0xA3, 0x17}, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA512)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { MscorlibRef_v4_0_30316_17626, hash_module }); CompileAndVerify(compilation, verify: Verification.Fails, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA512, (System.Configuration.Assemblies.AssemblyHashAlgorithm)assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0x5F, 0x4D, 0x7E, 0x63, 0xC9, 0x87, 0xD9, 0xEB, 0x4F, 0x5C, 0xFD, 0x96, 0x3F, 0x25, 0x58, 0x74, 0x86, 0xDF, 0x97, 0x75, 0x93, 0xEE, 0xC2, 0x5F, 0xFD, 0x8A, 0x40, 0x5C, 0x92, 0x5E, 0xB5, 0x07, 0xD6, 0x12, 0xE9, 0x21, 0x55, 0xCE, 0xD7, 0xE5, 0x15, 0xF5, 0xBA, 0xBC, 0x1B, 0x31, 0xAD, 0x3C, 0x5E, 0xE0, 0x91, 0x98, 0xC2, 0xE0, 0x96, 0xBB, 0xAD, 0x0D, 0x4E, 0xF4, 0x91, 0x53, 0x3D, 0x84}, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0x79, 0xFE, 0x97, 0xAB, 0x08, 0x8E, 0xDF, 0x74, 0xC2, 0xEF, 0x84, 0xBB, 0xFC, 0x74, 0xAC, 0x60, 0x18, 0x6E, 0x1A, 0xD2, 0xC5, 0x94, 0xE0, 0xDA, 0xE0, 0x45, 0x33, 0x43, 0x99, 0xF0, 0xF3, 0xF1, 0x72, 0x05, 0x4B, 0x0F, 0x37, 0x50, 0xC5, 0xD9, 0xCE, 0x29, 0x82, 0x4C, 0xF7, 0xE6, 0x94, 0x5F, 0xE5, 0x07, 0x2B, 0x4A, 0x18, 0x09, 0x56, 0xC9, 0x52, 0x69, 0x7D, 0xC4, 0x48, 0x63, 0x70, 0xF2}, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); var hash_module_Comp = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)] public class Test {}", options: TestOptions.ReleaseModule); compilation = CreateCompilation( @" class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { hash_module_Comp.EmitToImageReference() }); CompileAndVerify(compilation, validator: (peAssembly) => { var peReader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = peReader.GetAssemblyDefinition(); Assert.Equal(AssemblyHashAlgorithm.MD5, assembly.HashAlgorithm); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345)] class Program { void M() {} } ", options: TestOptions.ReleaseDll); // no error reported if we don't need to hash compilation.VerifyEmitDiagnostics(); compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { hash_module }); compilation.VerifyEmitDiagnostics( // error CS8013: Cryptographic failure while creating hashes. Diagnostic(ErrorCode.ERR_CryptoHashFailed)); compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345)] class Program { void M() {} } ", options: TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics(hash_resources, // error CS8013: Cryptographic failure while creating hashes. Diagnostic(ErrorCode.ERR_CryptoHashFailed)); string s = @"[assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)] public class C {}"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(comp.GetDiagnostics()); var attrs = comp.Assembly.GetAttributes(); Assert.Equal(1, attrs.Length); VerifyAssemblyTable(comp, r => { Assert.Equal(AssemblyHashAlgorithm.MD5, r.HashAlgorithm); }); s = @"[assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.None)] public class C {}"; comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, r => { Assert.Equal(AssemblyHashAlgorithm.None, r.HashAlgorithm); }); s = @"[assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345)] public class C {}"; comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, r => { Assert.Equal(12345, (int)r.HashAlgorithm); }); } [Fact] public void AssemblyFlagsAttribute() { string s = @"using System.Reflection; [assembly: AssemblyFlags(AssemblyNameFlags.EnableJITcompileOptimizer | AssemblyNameFlags.Retargetable)] public class C {} "; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(comp.GetDiagnostics()); var attrs = comp.Assembly.GetAttributes(); Assert.Equal(1, attrs.Length); var flags = System.Reflection.AssemblyNameFlags.EnableJITcompileOptimizer | System.Reflection.AssemblyNameFlags.Retargetable; VerifyAssemblyTable(comp, r => { Assert.Equal((int)flags, (int)r.Flags); }); } [Fact, WorkItem(546635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546635")] public void AssemblyFlagsAttribute02() { string s = @"[assembly: System.Reflection.AssemblyFlags(12345)] public class C {} "; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); // Both native & Roslyn PEVerifier fail: [MD]: Error: Invalid Assembly flags (0x3038). [token:0x20000001] VerifyAssemblyTable(comp, r => { Assert.Equal((uint)(12345 - 1), (uint)r.Flags); }); comp.VerifyDiagnostics( // (1,12): warning CS0618: 'System.Reflection.AssemblyFlagsAttribute.AssemblyFlagsAttribute(int)' is obsolete: 'This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202' // [assembly: System.Reflection.AssemblyFlags(12345)] public class C {} Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "System.Reflection.AssemblyFlags(12345)").WithArguments("System.Reflection.AssemblyFlagsAttribute.AssemblyFlagsAttribute(int)", "This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")); } [Fact] public void AssemblyFlagsAttribute03() { string s = @"[assembly: System.Reflection.AssemblyFlags(12345U)] public class C {} "; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); // Both native & Roslyn PEVerifier fail: [MD]: Error: Invalid Assembly flags (0x3038). [token:0x20000001] VerifyAssemblyTable(comp, r => { Assert.Equal((uint)(12345 - 1), (uint)r.Flags); }); comp.VerifyDiagnostics( // (1,12): warning CS0618: 'System.Reflection.AssemblyFlagsAttribute.AssemblyFlagsAttribute(int)' is obsolete: 'This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202' // [assembly: System.Reflection.AssemblyFlags(12345)] public class C {} Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "System.Reflection.AssemblyFlags(12345U)").WithArguments("System.Reflection.AssemblyFlagsAttribute.AssemblyFlagsAttribute(uint)", "This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")); } #region "Metadata Verifier (TODO: consolidate with others)" internal void VerifyAssemblyTable( CSharpCompilation compilation, Action<AssemblyDefinition> verifier, string strData = null, byte[] blobData = null, Guid guidData = default(Guid), string uddData = null) { var stream = new MemoryStream(); Assert.True(compilation.Emit(stream).Success); stream.Position = 0; using (var metadata = ModuleMetadata.CreateFromStream(stream)) { var peReader = metadata.MetadataReader; AssemblyDefinition row = peReader.GetAssemblyDefinition(); verifier?.Invoke(row); // Locale // temp if (strData != null) { Assert.Equal(strData, peReader.GetString(row.Culture)); } // PublicKey //Assert.Equal((uint)0, row.PublicKey); } } #endregion #region NetModule Assembly attribute tests #region Helpers private static readonly string s_defaultNetModuleSourceHeader = @"using System; using System.Reflection; using System.Security.Permissions; [assembly: AssemblyTitle(""AssemblyTitle"")] [assembly: FileIOPermission(SecurityAction.RequestOptional)] [assembly: UserDefinedAssemblyAttrNoAllowMultiple(""UserDefinedAssemblyAttrNoAllowMultiple"")] [assembly: UserDefinedAssemblyAttrAllowMultiple(""UserDefinedAssemblyAttrAllowMultiple"")] "; private static readonly string s_defaultNetModuleSourceBody = @" public class NetModuleClass { } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public class UserDefinedAssemblyAttrNoAllowMultipleAttribute : Attribute { public string Text { get; set; } public string Text2 { get; set; } public UserDefinedAssemblyAttrNoAllowMultipleAttribute(string text) { Text = text; } public UserDefinedAssemblyAttrNoAllowMultipleAttribute(int text) { Text = text.ToString(); } public UserDefinedAssemblyAttrNoAllowMultipleAttribute(object text) { Text = text.ToString(); } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public class UserDefinedAssemblyAttrAllowMultipleAttribute : Attribute { public string Text { get; set; } public string Text2 { get; set; } public UserDefinedAssemblyAttrAllowMultipleAttribute(string text) { Text = text; } public UserDefinedAssemblyAttrAllowMultipleAttribute(int text) { Text = text.ToString(); } public UserDefinedAssemblyAttrAllowMultipleAttribute(object text) { Text = text.ToString(); } } "; private MetadataReference GetNetModuleWithAssemblyAttributesRef(string source = null, IEnumerable<MetadataReference> references = null) { string assemblyName = GetUniqueName(); return GetNetModuleWithAssemblyAttributes(source, references, assemblyName).GetReference(display: assemblyName + ".netmodule"); } private ModuleMetadata GetNetModuleWithAssemblyAttributes(string source = null, IEnumerable<MetadataReference> references = null, string assemblyName = null) { source = source ?? s_defaultNetModuleSourceHeader + s_defaultNetModuleSourceBody; var netmoduleCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseModule, references: references, assemblyName: assemblyName); return ModuleMetadata.CreateFromImage(netmoduleCompilation.EmitToArray()); } private void TestDuplicateAssemblyAttributesNotEmitted(CSharpCompilation compilation, int expectedSrcAttrCount, int expectedDuplicateAttrCount, string attrTypeName) { // SOURCE ATTRIBUTES var sourceAttributes = compilation.Assembly .GetAttributes() .Where(a => string.Equals(a.AttributeClass.Name, attrTypeName, StringComparison.Ordinal)); Assert.Equal(expectedSrcAttrCount, sourceAttributes.Count()); // EMITTED ATTRIBUTES CompileAndVerify(compilation, symbolValidator: module => { // We should get only unique netmodule/assembly attributes here, duplicate ones should not be emitted. var expectedEmittedAttrsCount = expectedSrcAttrCount - expectedDuplicateAttrCount; var metadataAttributes = module.ContainingAssembly .GetAttributes() .Where(a => string.Equals(a.AttributeClass.Name, attrTypeName, StringComparison.Ordinal)); Assert.Equal(expectedEmittedAttrsCount, metadataAttributes.Count()); var uniqueAttributes = new HashSet<CSharpAttributeData>(comparer: CommonAttributeDataComparer.Instance); foreach (var attr in metadataAttributes) { Assert.True(uniqueAttributes.Add(attr)); } }); } #endregion [Fact] public void AssemblyAttributesFromNetModule() { string consoleappSource = @" class Program { static void Main(string[] args) { } } "; var netModuleWithAssemblyAttributes = GetNetModuleWithAssemblyAttributes(); PEModule peModule = netModuleWithAssemblyAttributes.Module; var metadataReader = peModule.GetMetadataReader(); Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)); Assert.Equal(18, metadataReader.CustomAttributes.Count); Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count); EntityHandle token = peModule.GetTypeRef(peModule.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.False(token.IsNil); //could the type ref be located? If not then the attribute's not there. var consoleappCompilation = CreateCompilationWithMscorlib40( consoleappSource, references: new[] { netModuleWithAssemblyAttributes.GetReference() }, options: TestOptions.ReleaseExe); Assert.NotNull(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHere")); Assert.NotNull(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHereM")); var diagnostics = consoleappCompilation.GetDiagnostics(); var attrs = consoleappCompilation.Assembly.GetAttributes(); Assert.Equal(4, attrs.Length); foreach (var a in attrs) { switch (a.AttributeClass.Name) { case "AssemblyTitleAttribute": Assert.Equal(@"System.Reflection.AssemblyTitleAttribute(""AssemblyTitle"")", a.ToString()); break; case "FileIOPermissionAttribute": Assert.Equal(@"System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()); break; case "UserDefinedAssemblyAttrNoAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()); break; case "UserDefinedAssemblyAttrAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()); break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } var exeMetadata = AssemblyMetadata.CreateFromImage(consoleappCompilation.EmitToArray()); peModule = exeMetadata.GetAssembly().ManifestModule; metadataReader = peModule.GetMetadataReader(); Assert.Equal(1, metadataReader.GetTableRowCount(TableIndex.ModuleRef)); Assert.Equal(3, metadataReader.GetTableRowCount(TableIndex.ExportedType)); Assert.Equal(6, metadataReader.CustomAttributes.Count); Assert.Equal(1, metadataReader.DeclarativeSecurityAttributes.Count); token = peModule.GetTypeRef(peModule.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.True(token.IsNil); //could the type ref be located? If not then the attribute's not there. consoleappCompilation = CreateCompilationWithMscorlib40( consoleappSource, references: new[] { netModuleWithAssemblyAttributes.GetReference() }, options: TestOptions.ReleaseModule); Assert.Equal(0, consoleappCompilation.Assembly.GetAttributes().Length); var modMetadata = ModuleMetadata.CreateFromImage(consoleappCompilation.EmitToArray()); peModule = modMetadata.Module; metadataReader = peModule.GetMetadataReader(); Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ModuleRef)); Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)); Assert.Equal(0, metadataReader.CustomAttributes.Count); Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count); token = peModule.GetTypeRef(peModule.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.True(token.IsNil); //could the type ref be located? If not then the attribute's not there. } [Fact] [WorkItem(10550, "https://github.com/dotnet/roslyn/issues/10550")] public void AssemblyAttributesFromNetModule_WithoutAssemblyAttributesGoHereTypes() { string netModuleSource = @"using System; using System.Reflection; [assembly: UserDefinedAssemblyAttrNoAllowMultiple(""UserDefinedAssemblyAttrNoAllowMultiple"")] [assembly: UserDefinedAssemblyAttrAllowMultiple(""UserDefinedAssemblyAttrAllowMultiple"")] public class NetModuleClass { } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public class UserDefinedAssemblyAttrNoAllowMultipleAttribute : Attribute { public UserDefinedAssemblyAttrNoAllowMultipleAttribute(string text) {} } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public class UserDefinedAssemblyAttrAllowMultipleAttribute : Attribute { public UserDefinedAssemblyAttrAllowMultipleAttribute(string text) {} } "; string consoleappSource = @" class Program { static void Main(string[] args) { } } "; var netmoduleCompilation = CreateEmptyCompilation(netModuleSource, options: TestOptions.ReleaseModule, references: new[] { MinCorlibRef }); Assert.Null(netmoduleCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHere")); Assert.Null(netmoduleCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHereM")); var netModuleWithAssemblyAttributes = ModuleMetadata.CreateFromImage(netmoduleCompilation.EmitToArray()); PEModule peModule = netModuleWithAssemblyAttributes.Module; var metadataReader = peModule.GetMetadataReader(); Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)); Assert.Equal(4, metadataReader.CustomAttributes.Count); Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count); EntityHandle token = peModule.GetTypeRef(peModule.GetAssemblyRef("mincorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.False(token.IsNil); //could the type ref be located? If not then the attribute's not there. var consoleappCompilation = CreateEmptyCompilation( consoleappSource, references: new[] { MinCorlibRef, netModuleWithAssemblyAttributes.GetReference() }, options: TestOptions.ReleaseExe); Assert.Null(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHere")); Assert.Null(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHereM")); consoleappCompilation.GetDiagnostics().Verify(); var attrs = consoleappCompilation.Assembly.GetAttributes(); Assert.Equal(2, attrs.Length); foreach (var a in attrs) { switch (a.AttributeClass.Name) { case "UserDefinedAssemblyAttrNoAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()); break; case "UserDefinedAssemblyAttrAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()); break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } var exeMetadata = AssemblyMetadata.CreateFromImage(consoleappCompilation.EmitToArray()); peModule = exeMetadata.GetAssembly().ManifestModule; metadataReader = peModule.GetMetadataReader(); Assert.Equal(1, metadataReader.GetTableRowCount(TableIndex.ModuleRef)); Assert.Equal(3, metadataReader.GetTableRowCount(TableIndex.ExportedType)); Assert.Equal(2, metadataReader.CustomAttributes.Count); Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count); token = peModule.GetTypeRef(peModule.GetAssemblyRef("mincorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.True(token.IsNil); //could the type ref be located? If not then the attribute's not there. consoleappCompilation = CreateEmptyCompilation( consoleappSource, references: new[] { MinCorlibRef, netModuleWithAssemblyAttributes.GetReference() }, options: TestOptions.ReleaseModule); Assert.Equal(0, consoleappCompilation.Assembly.GetAttributes().Length); var modMetadata = ModuleMetadata.CreateFromImage(consoleappCompilation.EmitToArray()); peModule = modMetadata.Module; metadataReader = peModule.GetMetadataReader(); Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ModuleRef)); Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)); Assert.Equal(0, metadataReader.CustomAttributes.Count); Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count); token = peModule.GetTypeRef(peModule.GetAssemblyRef("mincorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.True(token.IsNil); //could the type ref be located? If not then the attribute's not there. } [Fact] public void AssemblyAttributesFromNetModuleDropIdentical() { string consoleappSource = @" [assembly: UserDefinedAssemblyAttrNoAllowMultiple(""UserDefinedAssemblyAttrNoAllowMultiple"")] [assembly: UserDefinedAssemblyAttrAllowMultiple(""UserDefinedAssemblyAttrAllowMultiple"")] class Program { static void Main(string[] args) { } } "; var consoleappCompilation = CreateCompilationWithMscorlib40(consoleappSource, references: new[] { GetNetModuleWithAssemblyAttributesRef() }, options: TestOptions.ReleaseExe); var diagnostics = consoleappCompilation.GetDiagnostics(); TestDuplicateAssemblyAttributesNotEmitted(consoleappCompilation, expectedSrcAttrCount: 2, expectedDuplicateAttrCount: 1, attrTypeName: "UserDefinedAssemblyAttrAllowMultipleAttribute"); TestDuplicateAssemblyAttributesNotEmitted(consoleappCompilation, expectedSrcAttrCount: 2, expectedDuplicateAttrCount: 1, attrTypeName: "UserDefinedAssemblyAttrNoAllowMultipleAttribute"); var attrs = consoleappCompilation.Assembly.GetAttributes(); foreach (var a in attrs) { switch (a.AttributeClass.Name) { case "AssemblyTitleAttribute": Assert.Equal(@"System.Reflection.AssemblyTitleAttribute(""AssemblyTitle"")", a.ToString()); break; case "FileIOPermissionAttribute": Assert.Equal(@"System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()); break; case "UserDefinedAssemblyAttrNoAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()); break; case "UserDefinedAssemblyAttrAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()); break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } } [Fact] public void AssemblyAttributesFromNetModuleDropSpecial() { string consoleappSource = @" using System.Reflection; [assembly: AssemblyTitle(""AssemblyTitle (from source)"")] class Program { static void Main(string[] args) { } } "; var consoleappCompilation = CreateCompilationWithMscorlib40(consoleappSource, references: new[] { GetNetModuleWithAssemblyAttributesRef() }, options: TestOptions.ReleaseExe); TestDuplicateAssemblyAttributesNotEmitted(consoleappCompilation, expectedSrcAttrCount: 2, expectedDuplicateAttrCount: 1, attrTypeName: "AssemblyTitleAttribute"); CompileAndVerify(consoleappCompilation, symbolValidator: module => { foreach (var a in module.ContainingAssembly.GetAttributes()) { switch (a.AttributeClass.Name) { case "AssemblyTitleAttribute": Assert.Equal(@"System.Reflection.AssemblyTitleAttribute(""AssemblyTitle (from source)"")", a.ToString()); break; case "FileIOPermissionAttribute": Assert.Equal(@"System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()); break; case "UserDefinedAssemblyAttrNoAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()); break; case "UserDefinedAssemblyAttrAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()); break; case "CompilationRelaxationsAttribute": case "RuntimeCompatibilityAttribute": case "DebuggableAttribute": // synthesized attributes break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } }); } [Fact] public void AssemblyAttributesFromNetModuleAddMulti() { string consoleappSource = @" [assembly: UserDefinedAssemblyAttrAllowMultiple(""UserDefinedAssemblyAttrAllowMultiple (from source)"")] class Program { static void Main(string[] args) { } } "; var consoleappCompilation = CreateCompilationWithMscorlib40(consoleappSource, references: new[] { GetNetModuleWithAssemblyAttributesRef() }, options: TestOptions.ReleaseExe); var diagnostics = consoleappCompilation.GetDiagnostics(); var attrs = consoleappCompilation.Assembly.GetAttributes(); Assert.Equal(5, attrs.Length); foreach (var a in attrs) { switch (a.AttributeClass.Name) { case "AssemblyTitleAttribute": Assert.Equal(@"System.Reflection.AssemblyTitleAttribute(""AssemblyTitle"")", a.ToString()); break; case "FileIOPermissionAttribute": Assert.Equal(@"System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()); break; case "UserDefinedAssemblyAttrNoAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()); break; case "UserDefinedAssemblyAttrAllowMultipleAttribute": Assert.True( (@"UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")" == a.ToString()) || (@"UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple (from source)"")" == a.ToString()), "Unexpected attribute construction"); break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromNetModuleBadMulti() { string consoleappSource = @" [assembly: UserDefinedAssemblyAttrNoAllowMultiple(""UserDefinedAssemblyAttrNoAllowMultiple (from source)"")] class Program { static void Main(string[] args) { } } "; var netmodule1Ref = GetNetModuleWithAssemblyAttributesRef(); var compilation = CreateCompilationWithMscorlib40(consoleappSource, references: new[] { netmodule1Ref }, options: TestOptions.ReleaseExe); var diagnostics = compilation.GetDiagnostics(); compilation.VerifyDiagnostics( // error CS7061: Duplicate 'UserDefinedAssemblyAttrNoAllowMultipleAttribute' attribute in 'Test.netmodule' Diagnostic(ErrorCode.ERR_DuplicateAttributeInNetModule).WithArguments("UserDefinedAssemblyAttrNoAllowMultipleAttribute", netmodule1Ref.Display)); var attrs = compilation.Assembly.GetAttributes(); // even duplicates are preserved in source. Assert.Equal(5, attrs.Length); string netmodule2Source = @" [assembly: UserDefinedAssemblyAttrNoAllowMultiple(""UserDefinedAssemblyAttrNoAllowMultiple (from source)"")] "; compilation = CreateCompilationWithMscorlib40(netmodule2Source, options: TestOptions.ReleaseModule, references: new[] { netmodule1Ref }); compilation.VerifyDiagnostics(); var netmodule2Ref = compilation.EmitToImageReference(); attrs = compilation.Assembly.GetAttributes(); Assert.Equal(1, attrs.Length); compilation = CreateCompilationWithMscorlib40("", options: TestOptions.ReleaseDll, references: new[] { netmodule1Ref, netmodule2Ref }); compilation.VerifyDiagnostics( // error CS7061: Duplicate 'UserDefinedAssemblyAttrNoAllowMultipleAttribute' attribute in 'Test.netmodule' Diagnostic(ErrorCode.ERR_DuplicateAttributeInNetModule).WithArguments("UserDefinedAssemblyAttrNoAllowMultipleAttribute", netmodule1Ref.Display)); attrs = compilation.Assembly.GetAttributes(); // even duplicates are preserved in source. Assert.Equal(5, attrs.Length); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void InternalsVisibleToAttributeDropIdentical() { var source = @" using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo(""Assembly2"")] [assembly:InternalsVisibleTo(""Assembly2"")] "; var compilation = CreateCompilation(source); CompileAndVerify(compilation); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 2, expectedDuplicateAttrCount: 1, attrTypeName: "InternalsVisibleToAttribute"); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromSourceDropIdentical() { // Attribute with AllowMultiple = True string source = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str2"", Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str1"", Text = ""str1"")] // unique class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { GetNetModuleWithAssemblyAttributesRef() }, options: TestOptions.ReleaseDll); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 20, expectedDuplicateAttrCount: 5, attrTypeName: "UserDefinedAssemblyAttrAllowMultipleAttribute"); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromSourceDropIdentical_02() { // Attribute with AllowMultiple = False string source1 = @" [assembly: UserDefinedAssemblyAttrNoAllowMultipleAttribute(0)] // unique "; string source2 = @" [assembly: UserDefinedAssemblyAttrNoAllowMultipleAttribute(0)] // duplicate ignored, no error because identical "; string defaultHeaderString = @" using System; "; var defsRef = CreateCompilationWithMscorlib40(defaultHeaderString + s_defaultNetModuleSourceBody).ToMetadataReference(); MetadataReference netmodule1Ref = GetNetModuleWithAssemblyAttributesRef(source2, references: new[] { defsRef }); var compilation = CreateCompilationWithMscorlib40(source1, references: new[] { defsRef, netmodule1Ref }, options: TestOptions.ReleaseDll); // duplicate ignored, no error because identical compilation.VerifyDiagnostics(); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 2, expectedDuplicateAttrCount: 1, attrTypeName: "UserDefinedAssemblyAttrNoAllowMultipleAttribute"); MetadataReference netmodule2Ref = GetNetModuleWithAssemblyAttributesRef(source1, references: new[] { defsRef }); compilation = CreateCompilationWithMscorlib40("", references: new[] { defsRef, netmodule1Ref, netmodule2Ref }, options: TestOptions.ReleaseDll); // duplicate ignored, no error because identical compilation.VerifyDiagnostics(); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 2, expectedDuplicateAttrCount: 1, attrTypeName: "UserDefinedAssemblyAttrNoAllowMultipleAttribute"); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromNetModuleDropIdentical_01() { // Duplicate ignored attributes in netmodule string netmoduleAttributes = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str2"", Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str1"", Text = ""str1"")] // unique "; MetadataReference netmoduleRef = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader + netmoduleAttributes + s_defaultNetModuleSourceBody); string source = @" class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { netmoduleRef }, options: TestOptions.ReleaseDll); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 20, expectedDuplicateAttrCount: 5, attrTypeName: "UserDefinedAssemblyAttrAllowMultipleAttribute"); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromNetModuleDropIdentical_02() { string netmodule1Attributes = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str2"", Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str1"", Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // unique "; string netmodule2Attributes = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate "; string netmodule3Attributes = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate "; string defaultBodyString = @" using System; "; MetadataReference netmoduleDefsRef = GetNetModuleWithAssemblyAttributesRef(defaultBodyString + s_defaultNetModuleSourceBody); MetadataReference netmodule0Ref = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader, references: new[] { netmoduleDefsRef }); MetadataReference netmodule1Ref = GetNetModuleWithAssemblyAttributesRef(netmodule1Attributes, references: new[] { netmoduleDefsRef }); MetadataReference netmodule2Ref = GetNetModuleWithAssemblyAttributesRef(netmodule2Attributes, references: new[] { netmoduleDefsRef }); MetadataReference netmodule3Ref = GetNetModuleWithAssemblyAttributesRef(netmodule3Attributes, references: new[] { netmoduleDefsRef }); string source = @" class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { netmoduleDefsRef, netmodule0Ref, netmodule1Ref, netmodule2Ref, netmodule3Ref }, options: TestOptions.ReleaseDll); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 21, expectedDuplicateAttrCount: 6, attrTypeName: "UserDefinedAssemblyAttrAllowMultipleAttribute"); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromSourceAndNetModuleDropIdentical_01() { // All duplicate ignored attributes in netmodule string netmoduleAttributes = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate "; MetadataReference netmoduleRef = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader + netmoduleAttributes + s_defaultNetModuleSourceBody); string source = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str2"", Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str1"", Text = ""str1"")] // unique class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { netmoduleRef }, options: TestOptions.ReleaseDll); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 20, expectedDuplicateAttrCount: 5, attrTypeName: "UserDefinedAssemblyAttrAllowMultipleAttribute"); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromSourceAndNetModuleDropIdentical_02() { // Duplicate ignored attributes in netmodule & source string netmoduleAttributes = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate "; MetadataReference netmoduleRef = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader + netmoduleAttributes + s_defaultNetModuleSourceBody); string source = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str2"", Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str1"", Text = ""str1"")] // unique class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { netmoduleRef }, options: TestOptions.ReleaseDll); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 25, expectedDuplicateAttrCount: 10, attrTypeName: "UserDefinedAssemblyAttrAllowMultipleAttribute"); } [ConditionalFact(typeof(NoUsedAssembliesValidation))] // The test hook is blocked by https://github.com/dotnet/roslyn/issues/39969 [WorkItem(546825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546825")] [WorkItem(39969, "https://github.com/dotnet/roslyn/issues/39969")] public void Bug16910() { string mod = @" public static class Extensions { public static bool EB(this bool b) { return b; } } "; string app = @" public class Test { } "; var netModuleRef = GetNetModuleWithAssemblyAttributesRef(mod, new[] { TestMetadata.Net40.SystemCore }); var appCompilation = CreateCompilationWithMscorlib40(app, references: new[] { netModuleRef }, options: TestOptions.ReleaseDll); var diagnostics = appCompilation.GetDiagnostics(); Assert.False(diagnostics.Any()); } [ConditionalFact(typeof(DesktopOnly)), WorkItem(530585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530585")] public void Bug16465() { string mod = @" using System.Configuration.Assemblies; using System.Reflection; [assembly: AssemblyAlgorithmId(AssemblyHashAlgorithm.SHA1)] [assembly: AssemblyCulture(""en-US"")] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyFlags(AssemblyNameFlags.EnableJITcompileOptimizer | AssemblyNameFlags.Retargetable | AssemblyNameFlags.EnableJITcompileTracking)] [assembly: AssemblyVersion(""1.2.3.4"")] [assembly: AssemblyFileVersion(""4.3.2.1"")] [assembly: AssemblyTitle(""HELLO"")] [assembly: AssemblyDescription(""World"")] [assembly: AssemblyCompany(""MS"")] [assembly: AssemblyProduct(""Roslyn"")] [assembly: AssemblyInformationalVersion(""Info"")] [assembly: AssemblyCopyright(""Roslyn"")] [assembly: AssemblyTrademark(""Roslyn"")] class Program1 { static void Main(string[] args) { } } "; string app = @" public class Test { } "; var netModuleRef = GetNetModuleWithAssemblyAttributesRef(mod, new[] { SystemCoreRef }); var appCompilation = CreateCompilationWithMscorlib40(app, references: new[] { netModuleRef }, options: TestOptions.ReleaseDll); var module = (PEModuleSymbol)appCompilation.Assembly.Modules[1]; var metadata = module.Module; EntityHandle token = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHere"); Assert.False(token.IsNil); //could the type ref be located? If not then the attribute's not there. var attributes = module.GetCustomAttributesForToken(token); var builder = new System.Text.StringBuilder(); builder.AppendLine(); foreach (var attr in attributes) { builder.AppendLine(attr.ToString()); } builder.AppendLine(); var expectedStr = @" System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1) System.Reflection.AssemblyCultureAttribute(""en-US"") System.Reflection.AssemblyDelaySignAttribute(true) System.Reflection.AssemblyFlagsAttribute(System.Reflection.AssemblyNameFlags.None | System.Reflection.AssemblyNameFlags.EnableJITcompileOptimizer | System.Reflection.AssemblyNameFlags.EnableJITcompileTracking | System.Reflection.AssemblyNameFlags.Retargetable) System.Reflection.AssemblyVersionAttribute(""1.2.3.4"") System.Reflection.AssemblyFileVersionAttribute(""4.3.2.1"") System.Reflection.AssemblyTitleAttribute(""HELLO"") System.Reflection.AssemblyDescriptionAttribute(""World"") System.Reflection.AssemblyCompanyAttribute(""MS"") System.Reflection.AssemblyProductAttribute(""Roslyn"") System.Reflection.AssemblyInformationalVersionAttribute(""Info"") System.Reflection.AssemblyCopyrightAttribute(""Roslyn"") System.Reflection.AssemblyTrademarkAttribute(""Roslyn"") ".Trim(); var actualStr = builder.ToString().Trim(); Assert.True(expectedStr.Equals(actualStr), AssertEx.GetAssertMessage(expectedStr, actualStr)); } #endregion #region CompilationRelaxationsAttribute, RuntimeCompatibilityAttribute [Fact, WorkItem(545527, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545527")] public void CompilationRelaxationsAndRuntimeCompatibility_MultiModule() { string moduleSrc = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)] "; var module = CreateCompilation(moduleSrc, options: TestOptions.ReleaseModule, assemblyName: "M"); string assemblySrc = @" public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module.EmitToImageReference() }, assemblyName: "C"); CompileAndVerify(assembly, symbolValidator: moduleSymbol => { var attrs = moduleSymbol.ContainingAssembly.GetAttributes().Select(a => a.ToString()).ToArray(); AssertEx.SetEqual(new[] { "System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)", "System.Runtime.CompilerServices.CompilationRelaxationsAttribute(System.Runtime.CompilerServices.CompilationRelaxations.NoStringInterning)" }, attrs); }); } [Fact, WorkItem(546460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546460")] public void RuntimeCompatibilityAttribute_False() { // the attribute suppresses WRN_UnreachableGeneralCatch since catch {} can catch an object not derived from Exception string source = @" using System.Runtime.CompilerServices; [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)] class C { public static void Main() { try { } catch (System.Exception) { } catch { } } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(546460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546460")] public void RuntimeCompatibilityAttribute_Default() { string source = @" using System.Runtime.CompilerServices; [assembly: RuntimeCompatibilityAttribute()] class C { public static void Main() { try { } catch (System.Exception) { } catch { } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,9): warning CS1058: A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a System.Runtime.CompilerServices.RuntimeWrappedException. Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch")); } [Fact, WorkItem(546460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546460")] public void RuntimeCompatibilityAttribute_GeneralNotLast() { string source = @" using System.Runtime.CompilerServices; [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)] class C { public static void Main() { try { } catch { } catch (System.Exception) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,9): error CS1017: Catch clauses cannot follow the general catch clause of a try statement Diagnostic(ErrorCode.ERR_TooManyCatches, "catch")); } [Fact] public void RuntimeCompatibilityAttribute_False_MultiModule() { string moduleSrc = @" using System.Runtime.CompilerServices; [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)] "; var module = CreateCompilation(moduleSrc, options: TestOptions.ReleaseModule, assemblyName: "M"); string assemblySrc = @" class C { public static void Main() { try { } catch (System.Exception) { } catch { } } } "; var assembly = CreateCompilation(assemblySrc, new[] { module.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics(); } [Fact] public void RuntimeCompatibility_Duplicates_Error1() { string moduleSrc1 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)] "; var module1 = CreateCompilation(moduleSrc1, options: TestOptions.ReleaseModule, assemblyName: "M1"); string moduleSrc2 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module2 = CreateCompilation(moduleSrc2, options: TestOptions.ReleaseModule, assemblyName: "M2"); string assemblySrc = @" public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module1.EmitToImageReference(), module2.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics( // error CS7061: Duplicate 'RuntimeCompatibilityAttribute' attribute in 'M1.netmodule' Diagnostic(ErrorCode.ERR_DuplicateAttributeInNetModule).WithArguments("RuntimeCompatibilityAttribute", "M1.netmodule")); } [Fact] public void RuntimeCompatibility_Duplicates_Error2() { string moduleSrc1 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)] "; var module1 = CreateCompilation(moduleSrc1, options: TestOptions.ReleaseModule, assemblyName: "M1"); string assemblySrc = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module1.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics( // error CS7061: Duplicate 'RuntimeCompatibilityAttribute' attribute in 'M1.netmodule' Diagnostic(ErrorCode.ERR_DuplicateAttributeInNetModule).WithArguments("RuntimeCompatibilityAttribute", "M1.netmodule")); } [Fact] public void CompilationRelaxations_Duplicates_Error1() { string moduleSrc1 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(2)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module1 = CreateCompilation(moduleSrc1, options: TestOptions.ReleaseModule, assemblyName: "M1"); string moduleSrc2 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(6)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module2 = CreateCompilation(moduleSrc2, options: TestOptions.ReleaseModule, assemblyName: "M2"); string assemblySrc = @" public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module1.EmitToImageReference(), module2.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics( // error CS7061: Duplicate 'CompilationRelaxationsAttribute' attribute in 'M1.netmodule' Diagnostic(ErrorCode.ERR_DuplicateAttributeInNetModule).WithArguments("CompilationRelaxationsAttribute", "M1.netmodule")); } [Fact] public void CompilationRelaxations_Duplicates_Error2() { string moduleSrc1 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(2)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module1 = CreateCompilation(moduleSrc1, options: TestOptions.ReleaseModule, assemblyName: "M1"); string assemblySrc = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(6)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module1.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics( // error CS7061: Duplicate 'CompilationRelaxationsAttribute' attribute in 'M1.netmodule' Diagnostic(ErrorCode.ERR_DuplicateAttributeInNetModule).WithArguments("CompilationRelaxationsAttribute", "M1.netmodule")); } [Fact] public void CompilationRelaxations_Duplicates_SameValue1() { string moduleSrc1 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(2)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module1 = CreateCompilation(moduleSrc1, options: TestOptions.ReleaseModule, assemblyName: "M1"); string moduleSrc2 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(2)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module2 = CreateCompilation(moduleSrc2, options: TestOptions.ReleaseModule, assemblyName: "M2"); string assemblySrc = @" public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module1.EmitToImageReference(), module2.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics(); } [Fact] public void CompilationRelaxations_Duplicates_SameValue2() { string moduleSrc1 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(2)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module1 = CreateCompilation(moduleSrc1, options: TestOptions.ReleaseModule, assemblyName: "M1"); string assemblySrc = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(2)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module1.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics(); } #endregion [Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")] public void Bug530579_1() { var mod1Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var mod2Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var compMod1 = CreateCompilation(mod1Source, options: TestOptions.ReleaseModule, assemblyName: "M1"); var compMod2 = CreateCompilation(mod2Source, options: TestOptions.ReleaseModule, assemblyName: "M2"); var appCompilation = CreateCompilation(source, references: new MetadataReference[] { compMod1.EmitToImageReference(), compMod2.EmitToImageReference() }, options: TestOptions.ReleaseDll); Assert.Equal(3, appCompilation.Assembly.Modules.Length); CompileAndVerify(appCompilation, symbolValidator: (ModuleSymbol m) => { var list = GetAssemblyDescriptionAttributes(m.ContainingAssembly).ToArray(); Assert.Equal(1, list.Length); Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(\"Module1\")", list[0].ToString()); }).VerifyDiagnostics(); } private static IEnumerable<CSharpAttributeData> GetAssemblyDescriptionAttributes(AssemblySymbol assembly) { return assembly.GetAttributes().Where(data => data.IsTargetAttribute(assembly, AttributeDescription.AssemblyDescriptionAttribute)); } [Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")] public void Bug530579_2() { var mod1Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var mod2Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module2\")]"; var source = ""; var compMod1 = CreateCompilation(mod1Source, options: TestOptions.ReleaseModule, assemblyName: "M1"); var compMod2 = CreateCompilation(mod2Source, options: TestOptions.ReleaseModule, assemblyName: "M2"); var appCompilation = CreateCompilation(source, references: new MetadataReference[] { compMod1.EmitToImageReference(), compMod2.EmitToImageReference() }, options: TestOptions.ReleaseDll); Assert.Equal(3, appCompilation.Assembly.Modules.Length); CompileAndVerify(appCompilation, symbolValidator: (ModuleSymbol m) => { var list = GetAssemblyDescriptionAttributes(m.ContainingAssembly).ToArray(); Assert.Equal(1, list.Length); Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(\"Module2\")", list[0].ToString()); }).VerifyDiagnostics( // warning CS7090: Attribute 'System.Reflection.AssemblyDescriptionAttribute' from .NET module 'M1.netmodule' is overridden. Diagnostic(ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden).WithArguments("System.Reflection.AssemblyDescriptionAttribute", "M1.netmodule") ); } [Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")] public void Bug530579_3() { var mod1Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var mod2Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module2\")]"; var source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module3\")]"; var compMod1 = CreateCompilation(mod1Source, options: TestOptions.ReleaseModule, assemblyName: "M1"); var compMod2 = CreateCompilation(mod2Source, options: TestOptions.ReleaseModule, assemblyName: "M2"); var appCompilation = CreateCompilation(source, references: new MetadataReference[] { compMod1.EmitToImageReference(), compMod2.EmitToImageReference() }, options: TestOptions.ReleaseDll); Assert.Equal(3, appCompilation.Assembly.Modules.Length); CompileAndVerify(appCompilation, symbolValidator: (ModuleSymbol m) => { var list = GetAssemblyDescriptionAttributes(m.ContainingAssembly).ToArray(); Assert.Equal(1, list.Length); Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(\"Module3\")", list[0].ToString()); }).VerifyDiagnostics( // warning CS7090: Attribute 'System.Reflection.AssemblyDescriptionAttribute' from .NET module 'M2.netmodule' is overridden. Diagnostic(ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden).WithArguments("System.Reflection.AssemblyDescriptionAttribute", "M2.netmodule"), // warning CS7090: Attribute 'System.Reflection.AssemblyDescriptionAttribute' from .NET module 'M1.netmodule' is overridden. Diagnostic(ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden).WithArguments("System.Reflection.AssemblyDescriptionAttribute", "M1.netmodule") ); } [Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")] public void Bug530579_4() { var mod1Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var mod2Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module2\")]"; var source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var compMod1 = CreateCompilation(mod1Source, options: TestOptions.ReleaseModule, assemblyName: "M1"); var compMod2 = CreateCompilation(mod2Source, options: TestOptions.ReleaseModule, assemblyName: "M2"); var appCompilation = CreateCompilation(source, references: new MetadataReference[] { compMod1.EmitToImageReference(), compMod2.EmitToImageReference() }, options: TestOptions.ReleaseDll); Assert.Equal(3, appCompilation.Assembly.Modules.Length); CompileAndVerify(appCompilation, symbolValidator: (ModuleSymbol m) => { var list = GetAssemblyDescriptionAttributes(m.ContainingAssembly).ToArray(); Assert.Equal(1, list.Length); Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(\"Module1\")", list[0].ToString()); }).VerifyDiagnostics( // warning CS7090: Attribute 'System.Reflection.AssemblyDescriptionAttribute' from .NET module 'M2.netmodule' is overridden. Diagnostic(ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden).WithArguments("System.Reflection.AssemblyDescriptionAttribute", "M2.netmodule") ); } [Fact, WorkItem(649346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649346")] public void Bug649346() { var mod1Source = "[assembly:System.Reflection.AssemblyFileVersionAttribute(\"1.2.3.4\")]"; var source = @"[assembly:System.Reflection.AssemblyFileVersionAttribute(""4.3.2.1"")] class C { static void Main() {} }"; var compMod1 = CreateCompilation(mod1Source, options: TestOptions.ReleaseModule, assemblyName: "M1"); var appCompilation = CreateCompilation(source, references: new MetadataReference[] { compMod1.EmitToImageReference() }, options: TestOptions.ReleaseExe); Assert.Equal(2, appCompilation.Assembly.Modules.Length); CompileAndVerify(appCompilation, symbolValidator: (ModuleSymbol m) => { // var list = new ArrayBuilder<AttributeData>(); var asm = m.ContainingAssembly; var attrs = m.ContainingAssembly.GetAttributes(); var attrlist = attrs.Where(a => a.IsTargetAttribute(asm, AttributeDescription.AssemblyFileVersionAttribute)); Assert.Equal(1, attrlist.Count()); Assert.Equal("System.Reflection.AssemblyFileVersionAttribute(\"4.3.2.1\")", attrlist.First().ToString()); }).VerifyDiagnostics( // warning CS7090: Attribute 'System.Reflection.AssemblyFileVersionAttribute' from module 'M1.netmodule' will be ignored in favor of the instance appearing in source Diagnostic(ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden).WithArguments("System.Reflection.AssemblyFileVersionAttribute", "M1.netmodule") ); } [Fact, WorkItem(1082421, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1082421")] public void Bug1082421() { const string s = @" using static System.Math; [assembly: A(Log)] static class Logo { public const int Height = 32; public const int Width = 32; } "; var compilation = CreateCompilation(s, options: TestOptions.ReleaseDll); compilation.GetDiagnostics(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class AssemblyAttributeTests : CSharpTestBase { private readonly string _netModuleName = GetUniqueName() + ".netmodule"; [Fact] public void VersionAttribute() { string s = @"[assembly: System.Reflection.AssemblyVersion(""1.2.3.4"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal(new Version(1, 2, 3, 4), other.Assembly.Identity.Version); } [Fact] public void VersionAttribute_FourParts() { string s = @"[assembly: System.Reflection.AssemblyVersion(""1.22.333.4444"")] public class C {}"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, r => { Assert.Equal(new Version(1, 22, 333, 4444), r.Version); }); } [Fact] public void VersionAttribute_TwoParts() { var s = @"[assembly: System.Reflection.AssemblyVersion(""1.2"")] public class C {}"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, r => { Assert.Equal(1, r.Version.Major); Assert.Equal(2, r.Version.Minor); Assert.Equal(0, r.Version.Build); Assert.Equal(0, r.Version.Revision); }); } [Fact] public void VersionAttribute_WildCard() { var now = DateTime.Now; int days, seconds; VersionTestHelpers.GetDefaultVersion(now, out days, out seconds); var s = @"[assembly: System.Reflection.AssemblyVersion(""10101.0.*"")] public class C {}"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll.WithCurrentLocalTime(now)); VerifyAssemblyTable(comp, r => { Assert.Equal(10101, r.Version.Major); Assert.Equal(0, r.Version.Minor); Assert.Equal(days, r.Version.Build); Assert.Equal(seconds, r.Version.Revision); }); } [Fact] public void VersionAttribute_Overflow() { var s = @"[assembly: System.Reflection.AssemblyVersion(""10101.0.*"")] public class C {}"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll.WithCurrentLocalTime(new DateTime(2300, 1, 1))); VerifyAssemblyTable(comp, r => { Assert.Equal(10101, r.Version.Major); Assert.Equal(0, r.Version.Minor); Assert.Equal(65535, r.Version.Build); Assert.Equal(0, r.Version.Revision); }); } [Fact, WorkItem(545947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545947")] public void VersionAttributeErr() { string s = @"[assembly: System.Reflection.AssemblyVersion(""1.*"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics( // (1,46): error CS7034: The specified version string does not conform to the required format - major[.minor[.build[.revision]]] // [assembly: System.Reflection.AssemblyVersion("1.*")] public class C {} Diagnostic(ErrorCode.ERR_InvalidVersionFormat, @"""1.*""").WithLocation(1, 46)); s = @"[assembly: System.Reflection.AssemblyVersion(""-1"")] public class C {}"; other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics( // (1,46): error CS7034: The specified version string does not conform to the required format - major[.minor[.build[.revision]]] // [assembly: System.Reflection.AssemblyVersion("-1")] public class C {} Diagnostic(ErrorCode.ERR_InvalidVersionFormat, @"""-1""").WithLocation(1, 46)); } [Fact, WorkItem(22660, "https://github.com/dotnet/roslyn/issues/22660")] public void VersionAttributeWithWildcardAndDeterminism() { string s = @"[assembly: System.Reflection.AssemblyVersion(""1.1.1.*"")]"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll.WithDeterministic(true)); comp.VerifyDiagnostics( // (1,46): error CS8357: The specified version string contains wildcards, which are not compatible with determinism. Either remove wildcards from the version string, or disable determinism for this compilation // [assembly: System.Reflection.AssemblyVersion("1.1.1.*")] Diagnostic(ErrorCode.ERR_InvalidVersionFormatDeterministic, @"""1.1.1.*""").WithLocation(1, 46) ); } [Fact] public void FileVersionAttribute() { string s = @"[assembly: System.Reflection.AssemblyFileVersion(""1.2.3.4"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("1.2.3.4", ((SourceAssemblySymbol)other.Assembly).FileVersion); } [Fact] public void FileVersionAttribute_MissingParts() { string s = @"[assembly: System.Reflection.AssemblyFileVersion(""1.2"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("1.2", ((SourceAssemblySymbol)other.Assembly).FileVersion); } [Fact] public void FileVersionAttribute_MaxValue() { string s = @"[assembly: System.Reflection.AssemblyFileVersion(""65535.65535.65535.65535"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("65535.65535.65535.65535", ((SourceAssemblySymbol)other.Assembly).FileVersion); } [Fact] public void FileVersionAttributeWrn_Wildcard() { string s = @"[assembly: System.Reflection.AssemblyFileVersion(""1.2.*"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_InvalidVersionFormat, @"""1.2.*""")); // Confirm that suppressing the old alink warning 1607 shuts off WRN_ConflictingMachineAssembly var warnings = new Dictionary<string, ReportDiagnostic>(); warnings.Add(MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn), ReportDiagnostic.Suppress); other = other.WithOptions(other.Options.WithSpecificDiagnosticOptions(warnings)); other.VerifyEmitDiagnostics(); } [Fact] public void FileVersionAttributeWarning_OutOfRange() { string s = @"[assembly: System.Reflection.AssemblyFileVersion(""1.65536"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics(Diagnostic(ErrorCode.WRN_InvalidVersionFormat, @"""1.65536""")); // Confirm that suppressing the old alink warning 1607 shuts off WRN_ConflictingMachineAssembly var warnings = new Dictionary<string, ReportDiagnostic>(); warnings.Add(MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn), ReportDiagnostic.Suppress); other = other.WithOptions(other.Options.WithSpecificDiagnosticOptions(warnings)); other.VerifyEmitDiagnostics(); } [Fact, WorkItem(545947, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545947"), WorkItem(546971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546971"), WorkItem(22660, "https://github.com/dotnet/roslyn/issues/22660")] public void SatelliteContractVersionAttributeErr() { string s = @"[assembly: System.Resources.SatelliteContractVersionAttribute(""1.2.3.A"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics( // (1,63): error CS7058: The specified version string does not conform to the required format - major.minor.build.revision (without wildcards) // [assembly: System.Resources.SatelliteContractVersionAttribute("1.2.3.A")] public class C {} Diagnostic(ErrorCode.ERR_InvalidVersionFormat2, @"""1.2.3.A""").WithLocation(1, 63) ); s = @"[assembly: System.Resources.SatelliteContractVersionAttribute(""1.2.*"")] public class C {}"; other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics( // (1,63): error CS7058: The specified version string does not conform to the required format - major.minor.build.revision (without wildcards) // [assembly: System.Resources.SatelliteContractVersionAttribute("1.2.*")] public class C {} Diagnostic(ErrorCode.ERR_InvalidVersionFormat2, @"""1.2.*""").WithLocation(1, 63) ); s = @"[assembly: System.Resources.SatelliteContractVersionAttribute(""1"")] public class C {}"; other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyDiagnostics(); } [Fact] public void TitleAttribute() { string s = @"[assembly: System.Reflection.AssemblyTitle(""One Hundred Years of Solitude"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("One Hundred Years of Solitude", ((SourceAssemblySymbol)other.Assembly).Title); } [Fact] public void TitleAttributeNull() { string s = @"[assembly: System.Reflection.AssemblyTitle(null)] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Null(((SourceAssemblySymbol)other.Assembly).Title); } [Fact] public void DescriptionAttribute() { string s = @"[assembly: System.Reflection.AssemblyDescription(""A classic of magical realist literature"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("A classic of magical realist literature", ((SourceAssemblySymbol)other.Assembly).Description); } [Fact] public void CultureAttribute() { string s = @"[assembly: System.Reflection.AssemblyCulture(""pt-BR"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("pt-BR", (other.Assembly.Identity.CultureName)); } [Fact] public void CultureAttribute02() { string s = @"[assembly: System.Reflection.AssemblyCultureAttribute("""")]"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, r => { Assert.True(r.Culture.IsNil); }); s = @"[assembly: System.Reflection.AssemblyCulture(null)] public class C { static void Main() { } }"; comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, r => { Assert.True(r.Culture.IsNil); }); s = @"[assembly: System.Reflection.AssemblyCultureAttribute(""zh-CN"")]"; comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, null, strData: "zh-CN"); } [Fact, WorkItem(545949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545949")] public void CultureAttribute03() { // Executables cannot be satellite assemblies; culture should always be empty string s = @"[assembly: System.Reflection.AssemblyCulture(null)] public class C { static void Main() { } }"; var comp = CreateCompilation(s, options: TestOptions.ReleaseExe); VerifyAssemblyTable(comp, r => { Assert.True(r.Culture.IsNil); }); s = @"[assembly: System.Reflection.AssemblyCulture("""")] public class C { static void Main() { } }"; comp = CreateCompilation(s, options: TestOptions.ReleaseExe); VerifyAssemblyTable(comp, r => { Assert.True(r.Culture.IsNil); }); } [Fact, WorkItem(545949, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545949")] public void CultureAttributeErr() { string s = @"[assembly: System.Reflection.AssemblyCulture(""pt-BR"")] public class C { static void Main() { } }"; var comp = CreateCompilation(s, options: TestOptions.ReleaseExe); comp.VerifyDiagnostics( // (1,46): error CS7059: Executables cannot be satellite assemblies; culture should always be empty // [assembly: System.Reflection.AssemblyCulture("pt-BR")] public class C { static void Main() { } } Diagnostic(ErrorCode.ERR_InvalidAssemblyCultureForExe, @"""pt-BR""").WithLocation(1, 46)); } [WorkItem(1032718, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1032718")] [ConditionalFact(typeof(ClrOnly), Reason = "https://github.com/mono/mono/issues/10839")] public void MismatchedSurrogateInAssemblyCultureAttribute() { string s = @"[assembly: System.Reflection.AssemblyCultureAttribute(""\uD800"")]"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); CompileAndVerify(comp, verify: Verification.Fails, symbolValidator: m => { var utf8 = new System.Text.UTF8Encoding(false, false); Assert.Equal(utf8.GetString(utf8.GetBytes("\uD800")), m.ContainingAssembly.Identity.CultureName); }); } [Fact, WorkItem(1034455, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1034455")] public void NulCharInAssemblyCultureAttribute() { string s = @"[assembly: System.Reflection.AssemblyCultureAttribute(""\0"")]"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); comp.VerifyDiagnostics( // (1,55): error CS7100: Assembly culture strings may not contain embedded NUL characters. // [assembly: System.Reflection.AssemblyCultureAttribute("\0")] Diagnostic(ErrorCode.ERR_InvalidAssemblyCulture, @"""\0""").WithLocation(1, 55)); } [Fact] public void CultureAttributeMismatch() { var neutral = CreateCompilationWithMscorlib40( @" public class neutral {} ", options: TestOptions.ReleaseDll, assemblyName: "neutral"); var neutralRef = new CSharpCompilationReference(neutral); var de = CreateCompilationWithMscorlib40( @" [assembly: System.Reflection.AssemblyCultureAttribute(""de"")] public class de {} ", options: TestOptions.ReleaseDll, assemblyName: "de"); var deRef = new CSharpCompilationReference(de); var en_us = CreateCompilationWithMscorlib40( @" [assembly: System.Reflection.AssemblyCultureAttribute(""en-us"")] public class en_us {} ", options: TestOptions.ReleaseDll, assemblyName: "en_us"); var en_usRef = new CSharpCompilationReference(en_us); CSharpCompilation compilation; string assemblyNameBase = Guid.NewGuid().ToString(); compilation = CreateCompilationWithMscorlib40( @" [assembly: System.Reflection.AssemblyCultureAttribute(""en-US"")] public class en_US { void M(de x) {} } ", new MetadataReference[] { deRef, neutralRef }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "10"); CompileAndVerify(compilation).VerifyDiagnostics( // warning CS8009: Referenced assembly 'de, Version=0.0.0.0, Culture=de, PublicKeyToken=null' has different culture setting of 'de'. Diagnostic(ErrorCode.WRN_RefCultureMismatch).WithArguments("de, Version=0.0.0.0, Culture=de, PublicKeyToken=null", "de") ); compilation = compilation.WithOptions(TestOptions.ReleaseModule); compilation.VerifyEmitDiagnostics(); compilation = CreateCompilationWithMscorlib40("", new MetadataReference[] { compilation.EmitToImageReference() }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "20"); CompileAndVerify(compilation, verify: Verification.Skipped).VerifyDiagnostics( // warning CS8009: Referenced assembly 'de, Version=0.0.0.0, Culture=de, PublicKeyToken=null' has different culture setting of 'de'. Diagnostic(ErrorCode.WRN_RefCultureMismatch).WithArguments("de, Version=0.0.0.0, Culture=de, PublicKeyToken=null", "de") ); // Confirm that suppressing the old alink warning 1607 shuts off WRN_RefCultureMismatch var warnings = new Dictionary<string, ReportDiagnostic>(); warnings.Add(MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn), ReportDiagnostic.Suppress); compilation = compilation.WithOptions(compilation.Options.WithSpecificDiagnosticOptions(warnings)); compilation.VerifyEmitDiagnostics(); compilation = CreateCompilationWithMscorlib40( @" [assembly: System.Reflection.AssemblyCultureAttribute(""en-US"")] public class Test { void M(en_us x) {} } ", new MetadataReference[] { en_usRef }, options: TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "23"); compilation.VerifyEmitDiagnostics(); compilation = compilation.WithOptions(TestOptions.ReleaseModule); compilation.VerifyEmitDiagnostics(); compilation = CreateCompilationWithMscorlib40("", new MetadataReference[] { compilation.EmitToImageReference() }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "25"); compilation.VerifyEmitDiagnostics(); compilation = CreateCompilationWithMscorlib40( @" [assembly: System.Reflection.AssemblyCultureAttribute(""en-US"")] public class en_US { void M(neutral x) {} } ", new MetadataReference[] { deRef, neutralRef }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "30"); CompileAndVerify(compilation).VerifyDiagnostics(); compilation = compilation.WithOptions(TestOptions.ReleaseModule); compilation.VerifyEmitDiagnostics(); compilation = CreateCompilationWithMscorlib40("", new MetadataReference[] { compilation.EmitToImageReference() }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "40"); CompileAndVerify(compilation, sourceSymbolValidator: m => { Assert.Equal(1, m.GetReferencedAssemblySymbols().Length); var naturalRef = m.ContainingAssembly.Modules[1].GetReferencedAssemblySymbols()[1]; Assert.True(naturalRef.IsMissing); Assert.Equal("neutral, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", naturalRef.ToTestDisplayString()); }, symbolValidator: m => { Assert.Equal(2, ((PEModuleSymbol)m).GetReferencedAssemblySymbols().Length); Assert.Equal("neutral, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null", m.GetReferencedAssemblySymbols()[1].ToTestDisplayString()); }, verify: Verification.Skipped).VerifyDiagnostics(); compilation = CreateCompilationWithMscorlib40( @" public class neutral { void M(de x) {} } ", new MetadataReference[] { deRef }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "50"); CompileAndVerify(compilation).VerifyDiagnostics( // warning CS8009: Referenced assembly 'de, Version=0.0.0.0, Culture=de, PublicKeyToken=null' has different culture setting of 'de'. Diagnostic(ErrorCode.WRN_RefCultureMismatch).WithArguments("de, Version=0.0.0.0, Culture=de, PublicKeyToken=null", "de") ); compilation = compilation.WithOptions(TestOptions.ReleaseModule); compilation.VerifyEmitDiagnostics(); compilation = CreateCompilationWithMscorlib40("", new MetadataReference[] { compilation.EmitToImageReference() }, TestOptions.ReleaseDll, assemblyName: assemblyNameBase + "60"); CompileAndVerify(compilation, verify: Verification.Skipped).VerifyDiagnostics( // warning CS8009: Referenced assembly 'de, Version=0.0.0.0, Culture=de, PublicKeyToken=null' has different culture setting of 'de'. Diagnostic(ErrorCode.WRN_RefCultureMismatch).WithArguments("de, Version=0.0.0.0, Culture=de, PublicKeyToken=null", "de") ); } [Fact] public void CompanyAttribute() { string s = @"[assembly: System.Reflection.AssemblyCompany(""MossBrain"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("MossBrain", ((SourceAssemblySymbol)other.Assembly).Company); s = @"[assembly: System.Reflection.AssemblyCompany(""微软"")] public class C {}"; other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("微软", ((SourceAssemblySymbol)other.Assembly).Company); } [Fact] public void ProductAttribute() { string s = @"[assembly: System.Reflection.AssemblyProduct(""Sound Cannon"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("Sound Cannon", ((SourceAssemblySymbol)other.Assembly).Product); } [Fact] public void CopyrightAttribute() { string s = @"[assembly: System.Reflection.AssemblyCopyright(""مايكروسوفت"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("مايكروسوفت", ((SourceAssemblySymbol)other.Assembly).Copyright); } [Fact] public void TrademarkAttribute() { string s = @"[assembly: System.Reflection.AssemblyTrademark(""circle R"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("circle R", ((SourceAssemblySymbol)other.Assembly).Trademark); s = @"[assembly: System.Reflection.AssemblyTrademark("""")] namespace N {}"; other = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(other.GetDiagnostics()); Assert.Equal("", ((SourceAssemblySymbol)other.Assembly).Trademark); } [Fact] public void InformationalVersionAttribute() { string s = @"[assembly: System.Reflection.AssemblyInformationalVersion(""1.2.3garbage"")] public class C {}"; var other = CreateCompilation(s, options: TestOptions.ReleaseDll); other.VerifyEmitDiagnostics(); Assert.Equal("1.2.3garbage", ((SourceAssemblySymbol)other.Assembly).InformationalVersion); } [Fact, WorkItem(529921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529921")] public void AlgorithmIdAttribute() { var hash_module = TestReferences.SymbolsTests.netModule.hash_module; var hash_resources = new[] {new ResourceDescription("hash_resource", "snKey.snk", () => new MemoryStream(TestResources.General.snKey, writable: false), true)}; CSharpCompilation compilation; compilation = CreateCompilation( @" class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { hash_module }); CompileAndVerify(compilation, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(AssemblyHashAlgorithm.Sha1, assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0x6C, 0x9C, 0x3E, 0xDA, 0x60, 0x0F, 0x81, 0x93, 0x4A, 0xC1, 0x0D, 0x41, 0xB3, 0xE9, 0xB2, 0xB7, 0x2D, 0xEE, 0x59, 0xA8 }, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0x7F, 0x28, 0xEA, 0xD1, 0xF4, 0xA1, 0x7C, 0xB8, 0x0C, 0x14, 0xC0, 0x2E, 0x8C, 0xFF, 0x10, 0xEC, 0xB3, 0xC2, 0xA5, 0x1D }, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.None)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { hash_module }); CompileAndVerify(compilation, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(AssemblyHashAlgorithm.None, assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0x6C, 0x9C, 0x3E, 0xDA, 0x60, 0x0F, 0x81, 0x93, 0x4A, 0xC1, 0x0D, 0x41, 0xB3, 0xE9, 0xB2, 0xB7, 0x2D, 0xEE, 0x59, 0xA8 }, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0x7F, 0x28, 0xEA, 0xD1, 0xF4, 0xA1, 0x7C, 0xB8, 0x0C, 0x14, 0xC0, 0x2E, 0x8C, 0xFF, 0x10, 0xEC, 0xB3, 0xC2, 0xA5, 0x1D }, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute((uint)System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { hash_module }); CompileAndVerify(compilation, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(AssemblyHashAlgorithm.MD5, assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0x24, 0x22, 0x03, 0xC3, 0x94, 0xD5, 0xC2, 0xD9, 0x99, 0xB3, 0x6D, 0x59, 0xB2, 0xCA, 0x23, 0xBC }, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0x8D, 0xFE, 0xBF, 0x49, 0x8D, 0x62, 0x2A, 0x88, 0x89, 0xD1, 0x0E, 0x00, 0x9E, 0x29, 0x72, 0xF1 }, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { hash_module }); CompileAndVerify(compilation, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(AssemblyHashAlgorithm.Sha1, assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0x6C, 0x9C, 0x3E, 0xDA, 0x60, 0x0F, 0x81, 0x93, 0x4A, 0xC1, 0x0D, 0x41, 0xB3, 0xE9, 0xB2, 0xB7, 0x2D, 0xEE, 0x59, 0xA8 }, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0x7F, 0x28, 0xEA, 0xD1, 0xF4, 0xA1, 0x7C, 0xB8, 0x0C, 0x14, 0xC0, 0x2E, 0x8C, 0xFF, 0x10, 0xEC, 0xB3, 0xC2, 0xA5, 0x1D }, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA256)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { MscorlibRef_v4_0_30316_17626, hash_module }); CompileAndVerify(compilation, verify: Verification.Fails, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA256, (System.Configuration.Assemblies.AssemblyHashAlgorithm)assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0xA2, 0x32, 0x3F, 0x0D, 0xF4, 0xB8, 0xED, 0x5A, 0x1B, 0x7B, 0xBE, 0x14, 0x4F, 0xEC, 0xBF, 0x88, 0x23, 0x61, 0xEB, 0x40, 0xF7, 0xF9, 0x46, 0xEF, 0x68, 0x3B, 0x70, 0x29, 0xCF, 0x12, 0x05, 0x35 }, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0xCC, 0xAE, 0xA0, 0xB4, 0x9E, 0xAE, 0x28, 0xE0, 0xA3, 0x46, 0xE9, 0xCF, 0xF3, 0xEF, 0xEA, 0xF7, 0x1D, 0xDE, 0x62, 0x8F, 0xD6, 0xF4, 0x87, 0x76, 0x1A, 0xC3, 0x6F, 0xAD, 0x10, 0x1C, 0x10, 0xAC}, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA384)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { MscorlibRef_v4_0_30316_17626, hash_module }); CompileAndVerify(compilation, verify: Verification.Fails, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA384, (System.Configuration.Assemblies.AssemblyHashAlgorithm)assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0xB6, 0x35, 0x9B, 0xBE, 0x82, 0x89, 0xFF, 0x01, 0x22, 0x8B, 0x56, 0x5E, 0x9B, 0x15, 0x5D, 0x10, 0x68, 0x83, 0xF7, 0x75, 0x4E, 0xA6, 0x30, 0xF7, 0x8D, 0x39, 0x9A, 0xB7, 0xE8, 0xB6, 0x47, 0x1F, 0xF6, 0xFD, 0x1E, 0x64, 0x63, 0x6B, 0xE7, 0xF4, 0xBE, 0xA7, 0x21, 0xED, 0xFC, 0x82, 0x38, 0x95}, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0x45, 0x05, 0x2E, 0x90, 0x9B, 0x61, 0xA3, 0xF8, 0x60, 0xD2, 0x86, 0xCB, 0x10, 0x33, 0xC9, 0x86, 0x68, 0xA5, 0xEE, 0x4A, 0xCF, 0x21, 0x10, 0xA9, 0x8F, 0x14, 0x62, 0x8D, 0x3E, 0x7D, 0xFD, 0x7E, 0xE6, 0x23, 0x6F, 0x2D, 0xBA, 0x04, 0xE7, 0x13, 0xE4, 0x5E, 0x8C, 0xEB, 0x80, 0x68, 0xA3, 0x17}, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateEmptyCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA512)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { MscorlibRef_v4_0_30316_17626, hash_module }); CompileAndVerify(compilation, verify: Verification.Fails, manifestResources: hash_resources, validator: (peAssembly) => { var reader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = reader.GetAssemblyDefinition(); Assert.Equal(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA512, (System.Configuration.Assemblies.AssemblyHashAlgorithm)assembly.HashAlgorithm); var file1 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(1)); Assert.Equal(new byte[] { 0x5F, 0x4D, 0x7E, 0x63, 0xC9, 0x87, 0xD9, 0xEB, 0x4F, 0x5C, 0xFD, 0x96, 0x3F, 0x25, 0x58, 0x74, 0x86, 0xDF, 0x97, 0x75, 0x93, 0xEE, 0xC2, 0x5F, 0xFD, 0x8A, 0x40, 0x5C, 0x92, 0x5E, 0xB5, 0x07, 0xD6, 0x12, 0xE9, 0x21, 0x55, 0xCE, 0xD7, 0xE5, 0x15, 0xF5, 0xBA, 0xBC, 0x1B, 0x31, 0xAD, 0x3C, 0x5E, 0xE0, 0x91, 0x98, 0xC2, 0xE0, 0x96, 0xBB, 0xAD, 0x0D, 0x4E, 0xF4, 0x91, 0x53, 0x3D, 0x84}, reader.GetBlobBytes(file1.HashValue)); var file2 = reader.GetAssemblyFile(MetadataTokens.AssemblyFileHandle(2)); Assert.Equal(new byte[] { 0x79, 0xFE, 0x97, 0xAB, 0x08, 0x8E, 0xDF, 0x74, 0xC2, 0xEF, 0x84, 0xBB, 0xFC, 0x74, 0xAC, 0x60, 0x18, 0x6E, 0x1A, 0xD2, 0xC5, 0x94, 0xE0, 0xDA, 0xE0, 0x45, 0x33, 0x43, 0x99, 0xF0, 0xF3, 0xF1, 0x72, 0x05, 0x4B, 0x0F, 0x37, 0x50, 0xC5, 0xD9, 0xCE, 0x29, 0x82, 0x4C, 0xF7, 0xE6, 0x94, 0x5F, 0xE5, 0x07, 0x2B, 0x4A, 0x18, 0x09, 0x56, 0xC9, 0x52, 0x69, 0x7D, 0xC4, 0x48, 0x63, 0x70, 0xF2}, reader.GetBlobBytes(file2.HashValue)); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); var hash_module_Comp = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)] public class Test {}", options: TestOptions.ReleaseModule); compilation = CreateCompilation( @" class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { hash_module_Comp.EmitToImageReference() }); CompileAndVerify(compilation, validator: (peAssembly) => { var peReader = peAssembly.ManifestModule.GetMetadataReader(); AssemblyDefinition assembly = peReader.GetAssemblyDefinition(); Assert.Equal(AssemblyHashAlgorithm.MD5, assembly.HashAlgorithm); Assert.Null(peAssembly.ManifestModule.FindTargetAttributes(peAssembly.Handle, AttributeDescription.AssemblyAlgorithmIdAttribute)); }); compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345)] class Program { void M() {} } ", options: TestOptions.ReleaseDll); // no error reported if we don't need to hash compilation.VerifyEmitDiagnostics(); compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345)] class Program { void M(Test x) {} } ", options: TestOptions.ReleaseDll, references: new[] { hash_module }); compilation.VerifyEmitDiagnostics( // error CS8013: Cryptographic failure while creating hashes. Diagnostic(ErrorCode.ERR_CryptoHashFailed)); compilation = CreateCompilation( @" [assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345)] class Program { void M() {} } ", options: TestOptions.ReleaseDll); compilation.VerifyEmitDiagnostics(hash_resources, // error CS8013: Cryptographic failure while creating hashes. Diagnostic(ErrorCode.ERR_CryptoHashFailed)); string s = @"[assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.MD5)] public class C {}"; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(comp.GetDiagnostics()); var attrs = comp.Assembly.GetAttributes(); Assert.Equal(1, attrs.Length); VerifyAssemblyTable(comp, r => { Assert.Equal(AssemblyHashAlgorithm.MD5, r.HashAlgorithm); }); s = @"[assembly: System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.None)] public class C {}"; comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, r => { Assert.Equal(AssemblyHashAlgorithm.None, r.HashAlgorithm); }); s = @"[assembly: System.Reflection.AssemblyAlgorithmIdAttribute(12345)] public class C {}"; comp = CreateCompilation(s, options: TestOptions.ReleaseDll); VerifyAssemblyTable(comp, r => { Assert.Equal(12345, (int)r.HashAlgorithm); }); } [Fact] public void AssemblyFlagsAttribute() { string s = @"using System.Reflection; [assembly: AssemblyFlags(AssemblyNameFlags.EnableJITcompileOptimizer | AssemblyNameFlags.Retargetable)] public class C {} "; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); Assert.Empty(comp.GetDiagnostics()); var attrs = comp.Assembly.GetAttributes(); Assert.Equal(1, attrs.Length); var flags = System.Reflection.AssemblyNameFlags.EnableJITcompileOptimizer | System.Reflection.AssemblyNameFlags.Retargetable; VerifyAssemblyTable(comp, r => { Assert.Equal((int)flags, (int)r.Flags); }); } [Fact, WorkItem(546635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546635")] public void AssemblyFlagsAttribute02() { string s = @"[assembly: System.Reflection.AssemblyFlags(12345)] public class C {} "; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); // Both native & Roslyn PEVerifier fail: [MD]: Error: Invalid Assembly flags (0x3038). [token:0x20000001] VerifyAssemblyTable(comp, r => { Assert.Equal((uint)(12345 - 1), (uint)r.Flags); }); comp.VerifyDiagnostics( // (1,12): warning CS0618: 'System.Reflection.AssemblyFlagsAttribute.AssemblyFlagsAttribute(int)' is obsolete: 'This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202' // [assembly: System.Reflection.AssemblyFlags(12345)] public class C {} Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "System.Reflection.AssemblyFlags(12345)").WithArguments("System.Reflection.AssemblyFlagsAttribute.AssemblyFlagsAttribute(int)", "This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")); } [Fact] public void AssemblyFlagsAttribute03() { string s = @"[assembly: System.Reflection.AssemblyFlags(12345U)] public class C {} "; var comp = CreateCompilation(s, options: TestOptions.ReleaseDll); // Both native & Roslyn PEVerifier fail: [MD]: Error: Invalid Assembly flags (0x3038). [token:0x20000001] VerifyAssemblyTable(comp, r => { Assert.Equal((uint)(12345 - 1), (uint)r.Flags); }); comp.VerifyDiagnostics( // (1,12): warning CS0618: 'System.Reflection.AssemblyFlagsAttribute.AssemblyFlagsAttribute(int)' is obsolete: 'This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202' // [assembly: System.Reflection.AssemblyFlags(12345)] public class C {} Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "System.Reflection.AssemblyFlags(12345U)").WithArguments("System.Reflection.AssemblyFlagsAttribute.AssemblyFlagsAttribute(uint)", "This constructor has been deprecated. Please use AssemblyFlagsAttribute(AssemblyNameFlags) instead. http://go.microsoft.com/fwlink/?linkid=14202")); } #region "Metadata Verifier (TODO: consolidate with others)" internal void VerifyAssemblyTable( CSharpCompilation compilation, Action<AssemblyDefinition> verifier, string strData = null, byte[] blobData = null, Guid guidData = default(Guid), string uddData = null) { var stream = new MemoryStream(); Assert.True(compilation.Emit(stream).Success); stream.Position = 0; using (var metadata = ModuleMetadata.CreateFromStream(stream)) { var peReader = metadata.MetadataReader; AssemblyDefinition row = peReader.GetAssemblyDefinition(); verifier?.Invoke(row); // Locale // temp if (strData != null) { Assert.Equal(strData, peReader.GetString(row.Culture)); } // PublicKey //Assert.Equal((uint)0, row.PublicKey); } } #endregion #region NetModule Assembly attribute tests #region Helpers private static readonly string s_defaultNetModuleSourceHeader = @"using System; using System.Reflection; using System.Security.Permissions; [assembly: AssemblyTitle(""AssemblyTitle"")] [assembly: FileIOPermission(SecurityAction.RequestOptional)] [assembly: UserDefinedAssemblyAttrNoAllowMultiple(""UserDefinedAssemblyAttrNoAllowMultiple"")] [assembly: UserDefinedAssemblyAttrAllowMultiple(""UserDefinedAssemblyAttrAllowMultiple"")] "; private static readonly string s_defaultNetModuleSourceBody = @" public class NetModuleClass { } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public class UserDefinedAssemblyAttrNoAllowMultipleAttribute : Attribute { public string Text { get; set; } public string Text2 { get; set; } public UserDefinedAssemblyAttrNoAllowMultipleAttribute(string text) { Text = text; } public UserDefinedAssemblyAttrNoAllowMultipleAttribute(int text) { Text = text.ToString(); } public UserDefinedAssemblyAttrNoAllowMultipleAttribute(object text) { Text = text.ToString(); } } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public class UserDefinedAssemblyAttrAllowMultipleAttribute : Attribute { public string Text { get; set; } public string Text2 { get; set; } public UserDefinedAssemblyAttrAllowMultipleAttribute(string text) { Text = text; } public UserDefinedAssemblyAttrAllowMultipleAttribute(int text) { Text = text.ToString(); } public UserDefinedAssemblyAttrAllowMultipleAttribute(object text) { Text = text.ToString(); } } "; private MetadataReference GetNetModuleWithAssemblyAttributesRef(string source = null, IEnumerable<MetadataReference> references = null) { string assemblyName = GetUniqueName(); return GetNetModuleWithAssemblyAttributes(source, references, assemblyName).GetReference(display: assemblyName + ".netmodule"); } private ModuleMetadata GetNetModuleWithAssemblyAttributes(string source = null, IEnumerable<MetadataReference> references = null, string assemblyName = null) { source = source ?? s_defaultNetModuleSourceHeader + s_defaultNetModuleSourceBody; var netmoduleCompilation = CreateCompilationWithMscorlib40(source, options: TestOptions.ReleaseModule, references: references, assemblyName: assemblyName); return ModuleMetadata.CreateFromImage(netmoduleCompilation.EmitToArray()); } private void TestDuplicateAssemblyAttributesNotEmitted(CSharpCompilation compilation, int expectedSrcAttrCount, int expectedDuplicateAttrCount, string attrTypeName) { // SOURCE ATTRIBUTES var sourceAttributes = compilation.Assembly .GetAttributes() .Where(a => string.Equals(a.AttributeClass.Name, attrTypeName, StringComparison.Ordinal)); Assert.Equal(expectedSrcAttrCount, sourceAttributes.Count()); // EMITTED ATTRIBUTES CompileAndVerify(compilation, symbolValidator: module => { // We should get only unique netmodule/assembly attributes here, duplicate ones should not be emitted. var expectedEmittedAttrsCount = expectedSrcAttrCount - expectedDuplicateAttrCount; var metadataAttributes = module.ContainingAssembly .GetAttributes() .Where(a => string.Equals(a.AttributeClass.Name, attrTypeName, StringComparison.Ordinal)); Assert.Equal(expectedEmittedAttrsCount, metadataAttributes.Count()); var uniqueAttributes = new HashSet<CSharpAttributeData>(comparer: CommonAttributeDataComparer.Instance); foreach (var attr in metadataAttributes) { Assert.True(uniqueAttributes.Add(attr)); } }); } #endregion [Fact] public void AssemblyAttributesFromNetModule() { string consoleappSource = @" class Program { static void Main(string[] args) { } } "; var netModuleWithAssemblyAttributes = GetNetModuleWithAssemblyAttributes(); PEModule peModule = netModuleWithAssemblyAttributes.Module; var metadataReader = peModule.GetMetadataReader(); Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)); Assert.Equal(18, metadataReader.CustomAttributes.Count); Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count); EntityHandle token = peModule.GetTypeRef(peModule.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.False(token.IsNil); //could the type ref be located? If not then the attribute's not there. var consoleappCompilation = CreateCompilationWithMscorlib40( consoleappSource, references: new[] { netModuleWithAssemblyAttributes.GetReference() }, options: TestOptions.ReleaseExe); Assert.NotNull(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHere")); Assert.NotNull(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHereM")); var diagnostics = consoleappCompilation.GetDiagnostics(); var attrs = consoleappCompilation.Assembly.GetAttributes(); Assert.Equal(4, attrs.Length); foreach (var a in attrs) { switch (a.AttributeClass.Name) { case "AssemblyTitleAttribute": Assert.Equal(@"System.Reflection.AssemblyTitleAttribute(""AssemblyTitle"")", a.ToString()); break; case "FileIOPermissionAttribute": Assert.Equal(@"System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()); break; case "UserDefinedAssemblyAttrNoAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()); break; case "UserDefinedAssemblyAttrAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()); break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } var exeMetadata = AssemblyMetadata.CreateFromImage(consoleappCompilation.EmitToArray()); peModule = exeMetadata.GetAssembly().ManifestModule; metadataReader = peModule.GetMetadataReader(); Assert.Equal(1, metadataReader.GetTableRowCount(TableIndex.ModuleRef)); Assert.Equal(3, metadataReader.GetTableRowCount(TableIndex.ExportedType)); Assert.Equal(6, metadataReader.CustomAttributes.Count); Assert.Equal(1, metadataReader.DeclarativeSecurityAttributes.Count); token = peModule.GetTypeRef(peModule.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.True(token.IsNil); //could the type ref be located? If not then the attribute's not there. consoleappCompilation = CreateCompilationWithMscorlib40( consoleappSource, references: new[] { netModuleWithAssemblyAttributes.GetReference() }, options: TestOptions.ReleaseModule); Assert.Equal(0, consoleappCompilation.Assembly.GetAttributes().Length); var modMetadata = ModuleMetadata.CreateFromImage(consoleappCompilation.EmitToArray()); peModule = modMetadata.Module; metadataReader = peModule.GetMetadataReader(); Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ModuleRef)); Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)); Assert.Equal(0, metadataReader.CustomAttributes.Count); Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count); token = peModule.GetTypeRef(peModule.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.True(token.IsNil); //could the type ref be located? If not then the attribute's not there. } [Fact] [WorkItem(10550, "https://github.com/dotnet/roslyn/issues/10550")] public void AssemblyAttributesFromNetModule_WithoutAssemblyAttributesGoHereTypes() { string netModuleSource = @"using System; using System.Reflection; [assembly: UserDefinedAssemblyAttrNoAllowMultiple(""UserDefinedAssemblyAttrNoAllowMultiple"")] [assembly: UserDefinedAssemblyAttrAllowMultiple(""UserDefinedAssemblyAttrAllowMultiple"")] public class NetModuleClass { } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)] public class UserDefinedAssemblyAttrNoAllowMultipleAttribute : Attribute { public UserDefinedAssemblyAttrNoAllowMultipleAttribute(string text) {} } [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] public class UserDefinedAssemblyAttrAllowMultipleAttribute : Attribute { public UserDefinedAssemblyAttrAllowMultipleAttribute(string text) {} } "; string consoleappSource = @" class Program { static void Main(string[] args) { } } "; var netmoduleCompilation = CreateEmptyCompilation(netModuleSource, options: TestOptions.ReleaseModule, references: new[] { MinCorlibRef }); Assert.Null(netmoduleCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHere")); Assert.Null(netmoduleCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHereM")); var netModuleWithAssemblyAttributes = ModuleMetadata.CreateFromImage(netmoduleCompilation.EmitToArray()); PEModule peModule = netModuleWithAssemblyAttributes.Module; var metadataReader = peModule.GetMetadataReader(); Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)); Assert.Equal(4, metadataReader.CustomAttributes.Count); Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count); EntityHandle token = peModule.GetTypeRef(peModule.GetAssemblyRef("mincorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.False(token.IsNil); //could the type ref be located? If not then the attribute's not there. var consoleappCompilation = CreateEmptyCompilation( consoleappSource, references: new[] { MinCorlibRef, netModuleWithAssemblyAttributes.GetReference() }, options: TestOptions.ReleaseExe); Assert.Null(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHere")); Assert.Null(consoleappCompilation.GetTypeByMetadataName("System.Runtime.CompilerServices.AssemblyAttributesGoHereM")); consoleappCompilation.GetDiagnostics().Verify(); var attrs = consoleappCompilation.Assembly.GetAttributes(); Assert.Equal(2, attrs.Length); foreach (var a in attrs) { switch (a.AttributeClass.Name) { case "UserDefinedAssemblyAttrNoAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()); break; case "UserDefinedAssemblyAttrAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()); break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } var exeMetadata = AssemblyMetadata.CreateFromImage(consoleappCompilation.EmitToArray()); peModule = exeMetadata.GetAssembly().ManifestModule; metadataReader = peModule.GetMetadataReader(); Assert.Equal(1, metadataReader.GetTableRowCount(TableIndex.ModuleRef)); Assert.Equal(3, metadataReader.GetTableRowCount(TableIndex.ExportedType)); Assert.Equal(2, metadataReader.CustomAttributes.Count); Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count); token = peModule.GetTypeRef(peModule.GetAssemblyRef("mincorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.True(token.IsNil); //could the type ref be located? If not then the attribute's not there. consoleappCompilation = CreateEmptyCompilation( consoleappSource, references: new[] { MinCorlibRef, netModuleWithAssemblyAttributes.GetReference() }, options: TestOptions.ReleaseModule); Assert.Equal(0, consoleappCompilation.Assembly.GetAttributes().Length); var modMetadata = ModuleMetadata.CreateFromImage(consoleappCompilation.EmitToArray()); peModule = modMetadata.Module; metadataReader = peModule.GetMetadataReader(); Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ModuleRef)); Assert.Equal(0, metadataReader.GetTableRowCount(TableIndex.ExportedType)); Assert.Equal(0, metadataReader.CustomAttributes.Count); Assert.Equal(0, metadataReader.DeclarativeSecurityAttributes.Count); token = peModule.GetTypeRef(peModule.GetAssemblyRef("mincorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHereM"); Assert.True(token.IsNil); //could the type ref be located? If not then the attribute's not there. } [Fact] public void AssemblyAttributesFromNetModuleDropIdentical() { string consoleappSource = @" [assembly: UserDefinedAssemblyAttrNoAllowMultiple(""UserDefinedAssemblyAttrNoAllowMultiple"")] [assembly: UserDefinedAssemblyAttrAllowMultiple(""UserDefinedAssemblyAttrAllowMultiple"")] class Program { static void Main(string[] args) { } } "; var consoleappCompilation = CreateCompilationWithMscorlib40(consoleappSource, references: new[] { GetNetModuleWithAssemblyAttributesRef() }, options: TestOptions.ReleaseExe); var diagnostics = consoleappCompilation.GetDiagnostics(); TestDuplicateAssemblyAttributesNotEmitted(consoleappCompilation, expectedSrcAttrCount: 2, expectedDuplicateAttrCount: 1, attrTypeName: "UserDefinedAssemblyAttrAllowMultipleAttribute"); TestDuplicateAssemblyAttributesNotEmitted(consoleappCompilation, expectedSrcAttrCount: 2, expectedDuplicateAttrCount: 1, attrTypeName: "UserDefinedAssemblyAttrNoAllowMultipleAttribute"); var attrs = consoleappCompilation.Assembly.GetAttributes(); foreach (var a in attrs) { switch (a.AttributeClass.Name) { case "AssemblyTitleAttribute": Assert.Equal(@"System.Reflection.AssemblyTitleAttribute(""AssemblyTitle"")", a.ToString()); break; case "FileIOPermissionAttribute": Assert.Equal(@"System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()); break; case "UserDefinedAssemblyAttrNoAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()); break; case "UserDefinedAssemblyAttrAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()); break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } } [Fact] public void AssemblyAttributesFromNetModuleDropSpecial() { string consoleappSource = @" using System.Reflection; [assembly: AssemblyTitle(""AssemblyTitle (from source)"")] class Program { static void Main(string[] args) { } } "; var consoleappCompilation = CreateCompilationWithMscorlib40(consoleappSource, references: new[] { GetNetModuleWithAssemblyAttributesRef() }, options: TestOptions.ReleaseExe); TestDuplicateAssemblyAttributesNotEmitted(consoleappCompilation, expectedSrcAttrCount: 2, expectedDuplicateAttrCount: 1, attrTypeName: "AssemblyTitleAttribute"); CompileAndVerify(consoleappCompilation, symbolValidator: module => { foreach (var a in module.ContainingAssembly.GetAttributes()) { switch (a.AttributeClass.Name) { case "AssemblyTitleAttribute": Assert.Equal(@"System.Reflection.AssemblyTitleAttribute(""AssemblyTitle (from source)"")", a.ToString()); break; case "FileIOPermissionAttribute": Assert.Equal(@"System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()); break; case "UserDefinedAssemblyAttrNoAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()); break; case "UserDefinedAssemblyAttrAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")", a.ToString()); break; case "CompilationRelaxationsAttribute": case "RuntimeCompatibilityAttribute": case "DebuggableAttribute": // synthesized attributes break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } }); } [Fact] public void AssemblyAttributesFromNetModuleAddMulti() { string consoleappSource = @" [assembly: UserDefinedAssemblyAttrAllowMultiple(""UserDefinedAssemblyAttrAllowMultiple (from source)"")] class Program { static void Main(string[] args) { } } "; var consoleappCompilation = CreateCompilationWithMscorlib40(consoleappSource, references: new[] { GetNetModuleWithAssemblyAttributesRef() }, options: TestOptions.ReleaseExe); var diagnostics = consoleappCompilation.GetDiagnostics(); var attrs = consoleappCompilation.Assembly.GetAttributes(); Assert.Equal(5, attrs.Length); foreach (var a in attrs) { switch (a.AttributeClass.Name) { case "AssemblyTitleAttribute": Assert.Equal(@"System.Reflection.AssemblyTitleAttribute(""AssemblyTitle"")", a.ToString()); break; case "FileIOPermissionAttribute": Assert.Equal(@"System.Security.Permissions.FileIOPermissionAttribute(System.Security.Permissions.SecurityAction.RequestOptional)", a.ToString()); break; case "UserDefinedAssemblyAttrNoAllowMultipleAttribute": Assert.Equal(@"UserDefinedAssemblyAttrNoAllowMultipleAttribute(""UserDefinedAssemblyAttrNoAllowMultiple"")", a.ToString()); break; case "UserDefinedAssemblyAttrAllowMultipleAttribute": Assert.True( (@"UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple"")" == a.ToString()) || (@"UserDefinedAssemblyAttrAllowMultipleAttribute(""UserDefinedAssemblyAttrAllowMultiple (from source)"")" == a.ToString()), "Unexpected attribute construction"); break; default: Assert.Equal("Unexpected Attr", a.AttributeClass.Name); break; } } } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromNetModuleBadMulti() { string consoleappSource = @" [assembly: UserDefinedAssemblyAttrNoAllowMultiple(""UserDefinedAssemblyAttrNoAllowMultiple (from source)"")] class Program { static void Main(string[] args) { } } "; var netmodule1Ref = GetNetModuleWithAssemblyAttributesRef(); var compilation = CreateCompilationWithMscorlib40(consoleappSource, references: new[] { netmodule1Ref }, options: TestOptions.ReleaseExe); var diagnostics = compilation.GetDiagnostics(); compilation.VerifyDiagnostics( // error CS7061: Duplicate 'UserDefinedAssemblyAttrNoAllowMultipleAttribute' attribute in 'Test.netmodule' Diagnostic(ErrorCode.ERR_DuplicateAttributeInNetModule).WithArguments("UserDefinedAssemblyAttrNoAllowMultipleAttribute", netmodule1Ref.Display)); var attrs = compilation.Assembly.GetAttributes(); // even duplicates are preserved in source. Assert.Equal(5, attrs.Length); string netmodule2Source = @" [assembly: UserDefinedAssemblyAttrNoAllowMultiple(""UserDefinedAssemblyAttrNoAllowMultiple (from source)"")] "; compilation = CreateCompilationWithMscorlib40(netmodule2Source, options: TestOptions.ReleaseModule, references: new[] { netmodule1Ref }); compilation.VerifyDiagnostics(); var netmodule2Ref = compilation.EmitToImageReference(); attrs = compilation.Assembly.GetAttributes(); Assert.Equal(1, attrs.Length); compilation = CreateCompilationWithMscorlib40("", options: TestOptions.ReleaseDll, references: new[] { netmodule1Ref, netmodule2Ref }); compilation.VerifyDiagnostics( // error CS7061: Duplicate 'UserDefinedAssemblyAttrNoAllowMultipleAttribute' attribute in 'Test.netmodule' Diagnostic(ErrorCode.ERR_DuplicateAttributeInNetModule).WithArguments("UserDefinedAssemblyAttrNoAllowMultipleAttribute", netmodule1Ref.Display)); attrs = compilation.Assembly.GetAttributes(); // even duplicates are preserved in source. Assert.Equal(5, attrs.Length); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void InternalsVisibleToAttributeDropIdentical() { var source = @" using System.Runtime.CompilerServices; [assembly:InternalsVisibleTo(""Assembly2"")] [assembly:InternalsVisibleTo(""Assembly2"")] "; var compilation = CreateCompilation(source); CompileAndVerify(compilation); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 2, expectedDuplicateAttrCount: 1, attrTypeName: "InternalsVisibleToAttribute"); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromSourceDropIdentical() { // Attribute with AllowMultiple = True string source = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str2"", Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str1"", Text = ""str1"")] // unique class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { GetNetModuleWithAssemblyAttributesRef() }, options: TestOptions.ReleaseDll); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 20, expectedDuplicateAttrCount: 5, attrTypeName: "UserDefinedAssemblyAttrAllowMultipleAttribute"); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromSourceDropIdentical_02() { // Attribute with AllowMultiple = False string source1 = @" [assembly: UserDefinedAssemblyAttrNoAllowMultipleAttribute(0)] // unique "; string source2 = @" [assembly: UserDefinedAssemblyAttrNoAllowMultipleAttribute(0)] // duplicate ignored, no error because identical "; string defaultHeaderString = @" using System; "; var defsRef = CreateCompilationWithMscorlib40(defaultHeaderString + s_defaultNetModuleSourceBody).ToMetadataReference(); MetadataReference netmodule1Ref = GetNetModuleWithAssemblyAttributesRef(source2, references: new[] { defsRef }); var compilation = CreateCompilationWithMscorlib40(source1, references: new[] { defsRef, netmodule1Ref }, options: TestOptions.ReleaseDll); // duplicate ignored, no error because identical compilation.VerifyDiagnostics(); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 2, expectedDuplicateAttrCount: 1, attrTypeName: "UserDefinedAssemblyAttrNoAllowMultipleAttribute"); MetadataReference netmodule2Ref = GetNetModuleWithAssemblyAttributesRef(source1, references: new[] { defsRef }); compilation = CreateCompilationWithMscorlib40("", references: new[] { defsRef, netmodule1Ref, netmodule2Ref }, options: TestOptions.ReleaseDll); // duplicate ignored, no error because identical compilation.VerifyDiagnostics(); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 2, expectedDuplicateAttrCount: 1, attrTypeName: "UserDefinedAssemblyAttrNoAllowMultipleAttribute"); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromNetModuleDropIdentical_01() { // Duplicate ignored attributes in netmodule string netmoduleAttributes = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str2"", Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str1"", Text = ""str1"")] // unique "; MetadataReference netmoduleRef = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader + netmoduleAttributes + s_defaultNetModuleSourceBody); string source = @" class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { netmoduleRef }, options: TestOptions.ReleaseDll); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 20, expectedDuplicateAttrCount: 5, attrTypeName: "UserDefinedAssemblyAttrAllowMultipleAttribute"); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromNetModuleDropIdentical_02() { string netmodule1Attributes = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str2"", Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str1"", Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // unique "; string netmodule2Attributes = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate "; string netmodule3Attributes = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate "; string defaultBodyString = @" using System; "; MetadataReference netmoduleDefsRef = GetNetModuleWithAssemblyAttributesRef(defaultBodyString + s_defaultNetModuleSourceBody); MetadataReference netmodule0Ref = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader, references: new[] { netmoduleDefsRef }); MetadataReference netmodule1Ref = GetNetModuleWithAssemblyAttributesRef(netmodule1Attributes, references: new[] { netmoduleDefsRef }); MetadataReference netmodule2Ref = GetNetModuleWithAssemblyAttributesRef(netmodule2Attributes, references: new[] { netmoduleDefsRef }); MetadataReference netmodule3Ref = GetNetModuleWithAssemblyAttributesRef(netmodule3Attributes, references: new[] { netmoduleDefsRef }); string source = @" class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { netmoduleDefsRef, netmodule0Ref, netmodule1Ref, netmodule2Ref, netmodule3Ref }, options: TestOptions.ReleaseDll); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 21, expectedDuplicateAttrCount: 6, attrTypeName: "UserDefinedAssemblyAttrAllowMultipleAttribute"); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromSourceAndNetModuleDropIdentical_01() { // All duplicate ignored attributes in netmodule string netmoduleAttributes = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate "; MetadataReference netmoduleRef = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader + netmoduleAttributes + s_defaultNetModuleSourceBody); string source = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str2"", Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str1"", Text = ""str1"")] // unique class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { netmoduleRef }, options: TestOptions.ReleaseDll); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 20, expectedDuplicateAttrCount: 5, attrTypeName: "UserDefinedAssemblyAttrAllowMultipleAttribute"); } [Fact, WorkItem(546939, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546939")] public void AssemblyAttributesFromSourceAndNetModuleDropIdentical_02() { // Duplicate ignored attributes in netmodule & source string netmoduleAttributes = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate "; MetadataReference netmoduleRef = GetNetModuleWithAssemblyAttributesRef(s_defaultNetModuleSourceHeader + netmoduleAttributes + s_defaultNetModuleSourceBody); string source = @" [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(1)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0)] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)0)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute((object)null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(null)] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str2"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str2"", Text = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // unique [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text = ""str1"", Text2 = ""str1"")] // duplicate [assembly: UserDefinedAssemblyAttrAllowMultipleAttribute(0, Text2 = ""str1"", Text = ""str1"")] // unique class Program { static void Main(string[] args) { } }"; var compilation = CreateCompilationWithMscorlib40(source, references: new[] { netmoduleRef }, options: TestOptions.ReleaseDll); TestDuplicateAssemblyAttributesNotEmitted(compilation, expectedSrcAttrCount: 25, expectedDuplicateAttrCount: 10, attrTypeName: "UserDefinedAssemblyAttrAllowMultipleAttribute"); } [ConditionalFact(typeof(NoUsedAssembliesValidation))] // The test hook is blocked by https://github.com/dotnet/roslyn/issues/39969 [WorkItem(546825, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546825")] [WorkItem(39969, "https://github.com/dotnet/roslyn/issues/39969")] public void Bug16910() { string mod = @" public static class Extensions { public static bool EB(this bool b) { return b; } } "; string app = @" public class Test { } "; var netModuleRef = GetNetModuleWithAssemblyAttributesRef(mod, new[] { TestMetadata.Net40.SystemCore }); var appCompilation = CreateCompilationWithMscorlib40(app, references: new[] { netModuleRef }, options: TestOptions.ReleaseDll); var diagnostics = appCompilation.GetDiagnostics(); Assert.False(diagnostics.Any()); } [ConditionalFact(typeof(DesktopOnly)), WorkItem(530585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530585")] public void Bug16465() { string mod = @" using System.Configuration.Assemblies; using System.Reflection; [assembly: AssemblyAlgorithmId(AssemblyHashAlgorithm.SHA1)] [assembly: AssemblyCulture(""en-US"")] [assembly: AssemblyDelaySign(true)] [assembly: AssemblyFlags(AssemblyNameFlags.EnableJITcompileOptimizer | AssemblyNameFlags.Retargetable | AssemblyNameFlags.EnableJITcompileTracking)] [assembly: AssemblyVersion(""1.2.3.4"")] [assembly: AssemblyFileVersion(""4.3.2.1"")] [assembly: AssemblyTitle(""HELLO"")] [assembly: AssemblyDescription(""World"")] [assembly: AssemblyCompany(""MS"")] [assembly: AssemblyProduct(""Roslyn"")] [assembly: AssemblyInformationalVersion(""Info"")] [assembly: AssemblyCopyright(""Roslyn"")] [assembly: AssemblyTrademark(""Roslyn"")] class Program1 { static void Main(string[] args) { } } "; string app = @" public class Test { } "; var netModuleRef = GetNetModuleWithAssemblyAttributesRef(mod, new[] { SystemCoreRef }); var appCompilation = CreateCompilationWithMscorlib40(app, references: new[] { netModuleRef }, options: TestOptions.ReleaseDll); var module = (PEModuleSymbol)appCompilation.Assembly.Modules[1]; var metadata = module.Module; EntityHandle token = metadata.GetTypeRef(metadata.GetAssemblyRef("mscorlib"), "System.Runtime.CompilerServices", "AssemblyAttributesGoHere"); Assert.False(token.IsNil); //could the type ref be located? If not then the attribute's not there. var attributes = module.GetCustomAttributesForToken(token); var builder = new System.Text.StringBuilder(); builder.AppendLine(); foreach (var attr in attributes) { builder.AppendLine(attr.ToString()); } builder.AppendLine(); var expectedStr = @" System.Reflection.AssemblyAlgorithmIdAttribute(System.Configuration.Assemblies.AssemblyHashAlgorithm.SHA1) System.Reflection.AssemblyCultureAttribute(""en-US"") System.Reflection.AssemblyDelaySignAttribute(true) System.Reflection.AssemblyFlagsAttribute(System.Reflection.AssemblyNameFlags.None | System.Reflection.AssemblyNameFlags.EnableJITcompileOptimizer | System.Reflection.AssemblyNameFlags.EnableJITcompileTracking | System.Reflection.AssemblyNameFlags.Retargetable) System.Reflection.AssemblyVersionAttribute(""1.2.3.4"") System.Reflection.AssemblyFileVersionAttribute(""4.3.2.1"") System.Reflection.AssemblyTitleAttribute(""HELLO"") System.Reflection.AssemblyDescriptionAttribute(""World"") System.Reflection.AssemblyCompanyAttribute(""MS"") System.Reflection.AssemblyProductAttribute(""Roslyn"") System.Reflection.AssemblyInformationalVersionAttribute(""Info"") System.Reflection.AssemblyCopyrightAttribute(""Roslyn"") System.Reflection.AssemblyTrademarkAttribute(""Roslyn"") ".Trim(); var actualStr = builder.ToString().Trim(); Assert.True(expectedStr.Equals(actualStr), AssertEx.GetAssertMessage(expectedStr, actualStr)); } #endregion #region CompilationRelaxationsAttribute, RuntimeCompatibilityAttribute [Fact, WorkItem(545527, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545527")] public void CompilationRelaxationsAndRuntimeCompatibility_MultiModule() { string moduleSrc = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)] "; var module = CreateCompilation(moduleSrc, options: TestOptions.ReleaseModule, assemblyName: "M"); string assemblySrc = @" public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module.EmitToImageReference() }, assemblyName: "C"); CompileAndVerify(assembly, symbolValidator: moduleSymbol => { var attrs = moduleSymbol.ContainingAssembly.GetAttributes().Select(a => a.ToString()).ToArray(); AssertEx.SetEqual(new[] { "System.Diagnostics.DebuggableAttribute(System.Diagnostics.DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)", "System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)", "System.Runtime.CompilerServices.CompilationRelaxationsAttribute(System.Runtime.CompilerServices.CompilationRelaxations.NoStringInterning)" }, attrs); }); } [Fact, WorkItem(546460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546460")] public void RuntimeCompatibilityAttribute_False() { // the attribute suppresses WRN_UnreachableGeneralCatch since catch {} can catch an object not derived from Exception string source = @" using System.Runtime.CompilerServices; [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)] class C { public static void Main() { try { } catch (System.Exception) { } catch { } } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(546460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546460")] public void RuntimeCompatibilityAttribute_Default() { string source = @" using System.Runtime.CompilerServices; [assembly: RuntimeCompatibilityAttribute()] class C { public static void Main() { try { } catch (System.Exception) { } catch { } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,9): warning CS1058: A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a System.Runtime.CompilerServices.RuntimeWrappedException. Diagnostic(ErrorCode.WRN_UnreachableGeneralCatch, "catch")); } [Fact, WorkItem(546460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546460")] public void RuntimeCompatibilityAttribute_GeneralNotLast() { string source = @" using System.Runtime.CompilerServices; [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)] class C { public static void Main() { try { } catch { } catch (System.Exception) { } } } "; CreateCompilation(source).VerifyDiagnostics( // (12,9): error CS1017: Catch clauses cannot follow the general catch clause of a try statement Diagnostic(ErrorCode.ERR_TooManyCatches, "catch")); } [Fact] public void RuntimeCompatibilityAttribute_False_MultiModule() { string moduleSrc = @" using System.Runtime.CompilerServices; [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)] "; var module = CreateCompilation(moduleSrc, options: TestOptions.ReleaseModule, assemblyName: "M"); string assemblySrc = @" class C { public static void Main() { try { } catch (System.Exception) { } catch { } } } "; var assembly = CreateCompilation(assemblySrc, new[] { module.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics(); } [Fact] public void RuntimeCompatibility_Duplicates_Error1() { string moduleSrc1 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)] "; var module1 = CreateCompilation(moduleSrc1, options: TestOptions.ReleaseModule, assemblyName: "M1"); string moduleSrc2 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module2 = CreateCompilation(moduleSrc2, options: TestOptions.ReleaseModule, assemblyName: "M2"); string assemblySrc = @" public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module1.EmitToImageReference(), module2.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics( // error CS7061: Duplicate 'RuntimeCompatibilityAttribute' attribute in 'M1.netmodule' Diagnostic(ErrorCode.ERR_DuplicateAttributeInNetModule).WithArguments("RuntimeCompatibilityAttribute", "M1.netmodule")); } [Fact] public void RuntimeCompatibility_Duplicates_Error2() { string moduleSrc1 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = false)] "; var module1 = CreateCompilation(moduleSrc1, options: TestOptions.ReleaseModule, assemblyName: "M1"); string assemblySrc = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(CompilationRelaxations.NoStringInterning)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module1.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics( // error CS7061: Duplicate 'RuntimeCompatibilityAttribute' attribute in 'M1.netmodule' Diagnostic(ErrorCode.ERR_DuplicateAttributeInNetModule).WithArguments("RuntimeCompatibilityAttribute", "M1.netmodule")); } [Fact] public void CompilationRelaxations_Duplicates_Error1() { string moduleSrc1 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(2)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module1 = CreateCompilation(moduleSrc1, options: TestOptions.ReleaseModule, assemblyName: "M1"); string moduleSrc2 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(6)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module2 = CreateCompilation(moduleSrc2, options: TestOptions.ReleaseModule, assemblyName: "M2"); string assemblySrc = @" public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module1.EmitToImageReference(), module2.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics( // error CS7061: Duplicate 'CompilationRelaxationsAttribute' attribute in 'M1.netmodule' Diagnostic(ErrorCode.ERR_DuplicateAttributeInNetModule).WithArguments("CompilationRelaxationsAttribute", "M1.netmodule")); } [Fact] public void CompilationRelaxations_Duplicates_Error2() { string moduleSrc1 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(2)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module1 = CreateCompilation(moduleSrc1, options: TestOptions.ReleaseModule, assemblyName: "M1"); string assemblySrc = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(6)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module1.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics( // error CS7061: Duplicate 'CompilationRelaxationsAttribute' attribute in 'M1.netmodule' Diagnostic(ErrorCode.ERR_DuplicateAttributeInNetModule).WithArguments("CompilationRelaxationsAttribute", "M1.netmodule")); } [Fact] public void CompilationRelaxations_Duplicates_SameValue1() { string moduleSrc1 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(2)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module1 = CreateCompilation(moduleSrc1, options: TestOptions.ReleaseModule, assemblyName: "M1"); string moduleSrc2 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(2)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module2 = CreateCompilation(moduleSrc2, options: TestOptions.ReleaseModule, assemblyName: "M2"); string assemblySrc = @" public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module1.EmitToImageReference(), module2.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics(); } [Fact] public void CompilationRelaxations_Duplicates_SameValue2() { string moduleSrc1 = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(2)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] "; var module1 = CreateCompilation(moduleSrc1, options: TestOptions.ReleaseModule, assemblyName: "M1"); string assemblySrc = @" using System.Runtime.CompilerServices; [assembly: CompilationRelaxationsAttribute(2)] [assembly: RuntimeCompatibilityAttribute(WrapNonExceptionThrows = true)] public class C { } "; var assembly = CreateCompilation(assemblySrc, new[] { module1.EmitToImageReference() }, assemblyName: "C"); assembly.VerifyDiagnostics(); } #endregion [Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")] public void Bug530579_1() { var mod1Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var mod2Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var compMod1 = CreateCompilation(mod1Source, options: TestOptions.ReleaseModule, assemblyName: "M1"); var compMod2 = CreateCompilation(mod2Source, options: TestOptions.ReleaseModule, assemblyName: "M2"); var appCompilation = CreateCompilation(source, references: new MetadataReference[] { compMod1.EmitToImageReference(), compMod2.EmitToImageReference() }, options: TestOptions.ReleaseDll); Assert.Equal(3, appCompilation.Assembly.Modules.Length); CompileAndVerify(appCompilation, symbolValidator: (ModuleSymbol m) => { var list = GetAssemblyDescriptionAttributes(m.ContainingAssembly).ToArray(); Assert.Equal(1, list.Length); Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(\"Module1\")", list[0].ToString()); }).VerifyDiagnostics(); } private static IEnumerable<CSharpAttributeData> GetAssemblyDescriptionAttributes(AssemblySymbol assembly) { return assembly.GetAttributes().Where(data => data.IsTargetAttribute(assembly, AttributeDescription.AssemblyDescriptionAttribute)); } [Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")] public void Bug530579_2() { var mod1Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var mod2Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module2\")]"; var source = ""; var compMod1 = CreateCompilation(mod1Source, options: TestOptions.ReleaseModule, assemblyName: "M1"); var compMod2 = CreateCompilation(mod2Source, options: TestOptions.ReleaseModule, assemblyName: "M2"); var appCompilation = CreateCompilation(source, references: new MetadataReference[] { compMod1.EmitToImageReference(), compMod2.EmitToImageReference() }, options: TestOptions.ReleaseDll); Assert.Equal(3, appCompilation.Assembly.Modules.Length); CompileAndVerify(appCompilation, symbolValidator: (ModuleSymbol m) => { var list = GetAssemblyDescriptionAttributes(m.ContainingAssembly).ToArray(); Assert.Equal(1, list.Length); Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(\"Module2\")", list[0].ToString()); }).VerifyDiagnostics( // warning CS7090: Attribute 'System.Reflection.AssemblyDescriptionAttribute' from .NET module 'M1.netmodule' is overridden. Diagnostic(ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden).WithArguments("System.Reflection.AssemblyDescriptionAttribute", "M1.netmodule") ); } [Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")] public void Bug530579_3() { var mod1Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var mod2Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module2\")]"; var source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module3\")]"; var compMod1 = CreateCompilation(mod1Source, options: TestOptions.ReleaseModule, assemblyName: "M1"); var compMod2 = CreateCompilation(mod2Source, options: TestOptions.ReleaseModule, assemblyName: "M2"); var appCompilation = CreateCompilation(source, references: new MetadataReference[] { compMod1.EmitToImageReference(), compMod2.EmitToImageReference() }, options: TestOptions.ReleaseDll); Assert.Equal(3, appCompilation.Assembly.Modules.Length); CompileAndVerify(appCompilation, symbolValidator: (ModuleSymbol m) => { var list = GetAssemblyDescriptionAttributes(m.ContainingAssembly).ToArray(); Assert.Equal(1, list.Length); Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(\"Module3\")", list[0].ToString()); }).VerifyDiagnostics( // warning CS7090: Attribute 'System.Reflection.AssemblyDescriptionAttribute' from .NET module 'M2.netmodule' is overridden. Diagnostic(ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden).WithArguments("System.Reflection.AssemblyDescriptionAttribute", "M2.netmodule"), // warning CS7090: Attribute 'System.Reflection.AssemblyDescriptionAttribute' from .NET module 'M1.netmodule' is overridden. Diagnostic(ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden).WithArguments("System.Reflection.AssemblyDescriptionAttribute", "M1.netmodule") ); } [Fact, WorkItem(530579, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530579")] public void Bug530579_4() { var mod1Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var mod2Source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module2\")]"; var source = "[assembly:System.Reflection.AssemblyDescriptionAttribute(\"Module1\")]"; var compMod1 = CreateCompilation(mod1Source, options: TestOptions.ReleaseModule, assemblyName: "M1"); var compMod2 = CreateCompilation(mod2Source, options: TestOptions.ReleaseModule, assemblyName: "M2"); var appCompilation = CreateCompilation(source, references: new MetadataReference[] { compMod1.EmitToImageReference(), compMod2.EmitToImageReference() }, options: TestOptions.ReleaseDll); Assert.Equal(3, appCompilation.Assembly.Modules.Length); CompileAndVerify(appCompilation, symbolValidator: (ModuleSymbol m) => { var list = GetAssemblyDescriptionAttributes(m.ContainingAssembly).ToArray(); Assert.Equal(1, list.Length); Assert.Equal("System.Reflection.AssemblyDescriptionAttribute(\"Module1\")", list[0].ToString()); }).VerifyDiagnostics( // warning CS7090: Attribute 'System.Reflection.AssemblyDescriptionAttribute' from .NET module 'M2.netmodule' is overridden. Diagnostic(ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden).WithArguments("System.Reflection.AssemblyDescriptionAttribute", "M2.netmodule") ); } [Fact, WorkItem(649346, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649346")] public void Bug649346() { var mod1Source = "[assembly:System.Reflection.AssemblyFileVersionAttribute(\"1.2.3.4\")]"; var source = @"[assembly:System.Reflection.AssemblyFileVersionAttribute(""4.3.2.1"")] class C { static void Main() {} }"; var compMod1 = CreateCompilation(mod1Source, options: TestOptions.ReleaseModule, assemblyName: "M1"); var appCompilation = CreateCompilation(source, references: new MetadataReference[] { compMod1.EmitToImageReference() }, options: TestOptions.ReleaseExe); Assert.Equal(2, appCompilation.Assembly.Modules.Length); CompileAndVerify(appCompilation, symbolValidator: (ModuleSymbol m) => { // var list = new ArrayBuilder<AttributeData>(); var asm = m.ContainingAssembly; var attrs = m.ContainingAssembly.GetAttributes(); var attrlist = attrs.Where(a => a.IsTargetAttribute(asm, AttributeDescription.AssemblyFileVersionAttribute)); Assert.Equal(1, attrlist.Count()); Assert.Equal("System.Reflection.AssemblyFileVersionAttribute(\"4.3.2.1\")", attrlist.First().ToString()); }).VerifyDiagnostics( // warning CS7090: Attribute 'System.Reflection.AssemblyFileVersionAttribute' from module 'M1.netmodule' will be ignored in favor of the instance appearing in source Diagnostic(ErrorCode.WRN_AssemblyAttributeFromModuleIsOverridden).WithArguments("System.Reflection.AssemblyFileVersionAttribute", "M1.netmodule") ); } [Fact, WorkItem(1082421, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1082421")] public void Bug1082421() { const string s = @" using static System.Math; [assembly: A(Log)] static class Logo { public const int Height = 32; public const int Width = 32; } "; var compilation = CreateCompilation(s, options: TestOptions.ReleaseDll); compilation.GetDiagnostics(); } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/Core/Portable/Symbols/INamedTypeSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.Immutable; using System.Reflection; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a type other than an array, a pointer, a type parameter. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface INamedTypeSymbol : ITypeSymbol { /// <summary> /// Returns the arity of this type, or the number of type parameters it takes. /// A non-generic type has zero arity. /// </summary> int Arity { get; } /// <summary> /// True if this type or some containing type has type parameters. /// </summary> bool IsGenericType { get; } /// <summary> /// True if this is a reference to an <em>unbound</em> generic type. A generic type is /// considered <em>unbound</em> if all of the type argument lists in its fully qualified /// name are empty. Note that the type arguments of an unbound generic type will be /// returned as error types because they do not really have type arguments. An unbound /// generic type yields null for its BaseType and an empty result for its Interfaces. /// </summary> bool IsUnboundGenericType { get; } /// <summary> /// Returns true if the type is a Script class. /// It might be an interactive submission class or a Script class in a csx file. /// </summary> bool IsScriptClass { get; } /// <summary> /// Returns true if the type is the implicit class that holds onto invalid global members (like methods or /// statements in a non script file). /// </summary> bool IsImplicitClass { get; } /// <summary> /// Specifies that the class or interface is imported from another module. See /// <see cref="TypeAttributes.Import"/> and <see cref="ComImportAttribute"/> /// </summary> bool IsComImport { get; } /// <summary> /// Returns collection of names of members declared within this type. /// </summary> IEnumerable<string> MemberNames { get; } /// <summary> /// Returns the type parameters that this type has. If this is a non-generic type, /// returns an empty ImmutableArray. /// </summary> ImmutableArray<ITypeParameterSymbol> TypeParameters { get; } /// <summary> /// Returns the type arguments that have been substituted for the type parameters. /// If nothing has been substituted for a given type parameter, /// then the type parameter itself is considered the type argument. /// </summary> ImmutableArray<ITypeSymbol> TypeArguments { get; } /// <summary> /// Returns the top-level nullability of the type arguments that have been substituted /// for the type parameters. If nothing has been substituted for a given type parameter, /// then <see cref="NullableAnnotation.None"/> is returned for that type argument. /// </summary> ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations { get; } /// <summary> /// Returns custom modifiers for the type argument that has been substituted for the type parameter. /// The modifiers correspond to the type argument at the same ordinal within the <see cref="TypeArguments"/> /// array. Returns an empty array if there are no modifiers. /// </summary> ImmutableArray<CustomModifier> GetTypeArgumentCustomModifiers(int ordinal); /// <summary> /// Get the original definition of this type symbol. If this symbol is derived from another /// symbol by (say) type substitution, this gets the original symbol, as it was defined in /// source or metadata. /// </summary> new INamedTypeSymbol OriginalDefinition { get; } /// <summary> /// For delegate types, gets the delegate's invoke method. Returns null on /// all other kinds of types. Note that it is possible to have an ill-formed /// delegate type imported from metadata which does not have an Invoke method. /// Such a type will be classified as a delegate but its DelegateInvokeMethod /// would be null. /// </summary> IMethodSymbol? DelegateInvokeMethod { get; } /// <summary> /// For enum types, gets the underlying type. Returns null on all other /// kinds of types. /// </summary> INamedTypeSymbol? EnumUnderlyingType { get; } /// <summary> /// Returns the type symbol that this type was constructed from. This type symbol /// has the same containing type (if any), but has type arguments that are the same /// as the type parameters (although its containing type might not). /// </summary> INamedTypeSymbol ConstructedFrom { get; } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments">The immediate type arguments to be replaced for type /// parameters in the type.</param> INamedTypeSymbol Construct(params ITypeSymbol[] typeArguments); /// <summary> /// Returns a constructed type given its type arguments and type argument nullable annotations. /// </summary> INamedTypeSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations); /// <summary> /// Returns an unbound generic type of this named type. /// </summary> INamedTypeSymbol ConstructUnboundGenericType(); /// <summary> /// Get the instance constructors for this type. /// </summary> ImmutableArray<IMethodSymbol> InstanceConstructors { get; } /// <summary> /// Get the static constructors for this type. /// </summary> ImmutableArray<IMethodSymbol> StaticConstructors { get; } /// <summary> /// Get the both instance and static constructors for this type. /// </summary> ImmutableArray<IMethodSymbol> Constructors { get; } /// <summary> /// For implicitly declared delegate types returns the EventSymbol that caused this /// delegate type to be generated. /// For all other types returns null. /// Note, the set of possible associated symbols might be expanded in the future to /// reflect changes in the languages. /// </summary> ISymbol? AssociatedSymbol { get; } /// <summary> /// Determines if the symbol might contain extension methods. /// If false, the symbol does not contain extension methods. /// </summary> bool MightContainExtensionMethods { get; } /// <summary> /// If this is a tuple type with element names, returns the symbol for the tuple type without names. /// Otherwise, returns null. /// The type argument corresponding to the type of the extension field (VT[8].Rest), /// which is at the 8th (one based) position is always a symbol for another tuple, /// rather than its underlying type. /// </summary> INamedTypeSymbol? TupleUnderlyingType { get; } /// <summary> /// Returns fields that represent tuple elements for types that are tuples. /// /// If this type is not a tuple, then returns default. /// </summary> ImmutableArray<IFieldSymbol> TupleElements { get; } /// <summary> /// True if the type is serializable (has Serializable metadata flag). /// </summary> bool IsSerializable { get; } /// <summary> /// If this is a native integer, returns the symbol for the underlying type, /// either <see cref="System.IntPtr"/> or <see cref="System.UIntPtr"/>. /// Otherwise, returns null. /// </summary> INamedTypeSymbol? NativeIntegerUnderlyingType { 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.Generic; using System.Collections.Immutable; using System.Reflection; using System.Runtime.InteropServices; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents a type other than an array, a pointer, a type parameter. /// </summary> /// <remarks> /// This interface is reserved for implementation by its associated APIs. We reserve the right to /// change it in the future. /// </remarks> public interface INamedTypeSymbol : ITypeSymbol { /// <summary> /// Returns the arity of this type, or the number of type parameters it takes. /// A non-generic type has zero arity. /// </summary> int Arity { get; } /// <summary> /// True if this type or some containing type has type parameters. /// </summary> bool IsGenericType { get; } /// <summary> /// True if this is a reference to an <em>unbound</em> generic type. A generic type is /// considered <em>unbound</em> if all of the type argument lists in its fully qualified /// name are empty. Note that the type arguments of an unbound generic type will be /// returned as error types because they do not really have type arguments. An unbound /// generic type yields null for its BaseType and an empty result for its Interfaces. /// </summary> bool IsUnboundGenericType { get; } /// <summary> /// Returns true if the type is a Script class. /// It might be an interactive submission class or a Script class in a csx file. /// </summary> bool IsScriptClass { get; } /// <summary> /// Returns true if the type is the implicit class that holds onto invalid global members (like methods or /// statements in a non script file). /// </summary> bool IsImplicitClass { get; } /// <summary> /// Specifies that the class or interface is imported from another module. See /// <see cref="TypeAttributes.Import"/> and <see cref="ComImportAttribute"/> /// </summary> bool IsComImport { get; } /// <summary> /// Returns collection of names of members declared within this type. /// </summary> IEnumerable<string> MemberNames { get; } /// <summary> /// Returns the type parameters that this type has. If this is a non-generic type, /// returns an empty ImmutableArray. /// </summary> ImmutableArray<ITypeParameterSymbol> TypeParameters { get; } /// <summary> /// Returns the type arguments that have been substituted for the type parameters. /// If nothing has been substituted for a given type parameter, /// then the type parameter itself is considered the type argument. /// </summary> ImmutableArray<ITypeSymbol> TypeArguments { get; } /// <summary> /// Returns the top-level nullability of the type arguments that have been substituted /// for the type parameters. If nothing has been substituted for a given type parameter, /// then <see cref="NullableAnnotation.None"/> is returned for that type argument. /// </summary> ImmutableArray<NullableAnnotation> TypeArgumentNullableAnnotations { get; } /// <summary> /// Returns custom modifiers for the type argument that has been substituted for the type parameter. /// The modifiers correspond to the type argument at the same ordinal within the <see cref="TypeArguments"/> /// array. Returns an empty array if there are no modifiers. /// </summary> ImmutableArray<CustomModifier> GetTypeArgumentCustomModifiers(int ordinal); /// <summary> /// Get the original definition of this type symbol. If this symbol is derived from another /// symbol by (say) type substitution, this gets the original symbol, as it was defined in /// source or metadata. /// </summary> new INamedTypeSymbol OriginalDefinition { get; } /// <summary> /// For delegate types, gets the delegate's invoke method. Returns null on /// all other kinds of types. Note that it is possible to have an ill-formed /// delegate type imported from metadata which does not have an Invoke method. /// Such a type will be classified as a delegate but its DelegateInvokeMethod /// would be null. /// </summary> IMethodSymbol? DelegateInvokeMethod { get; } /// <summary> /// For enum types, gets the underlying type. Returns null on all other /// kinds of types. /// </summary> INamedTypeSymbol? EnumUnderlyingType { get; } /// <summary> /// Returns the type symbol that this type was constructed from. This type symbol /// has the same containing type (if any), but has type arguments that are the same /// as the type parameters (although its containing type might not). /// </summary> INamedTypeSymbol ConstructedFrom { get; } /// <summary> /// Returns a constructed type given its type arguments. /// </summary> /// <param name="typeArguments">The immediate type arguments to be replaced for type /// parameters in the type.</param> INamedTypeSymbol Construct(params ITypeSymbol[] typeArguments); /// <summary> /// Returns a constructed type given its type arguments and type argument nullable annotations. /// </summary> INamedTypeSymbol Construct(ImmutableArray<ITypeSymbol> typeArguments, ImmutableArray<NullableAnnotation> typeArgumentNullableAnnotations); /// <summary> /// Returns an unbound generic type of this named type. /// </summary> INamedTypeSymbol ConstructUnboundGenericType(); /// <summary> /// Get the instance constructors for this type. /// </summary> ImmutableArray<IMethodSymbol> InstanceConstructors { get; } /// <summary> /// Get the static constructors for this type. /// </summary> ImmutableArray<IMethodSymbol> StaticConstructors { get; } /// <summary> /// Get the both instance and static constructors for this type. /// </summary> ImmutableArray<IMethodSymbol> Constructors { get; } /// <summary> /// For implicitly declared delegate types returns the EventSymbol that caused this /// delegate type to be generated. /// For all other types returns null. /// Note, the set of possible associated symbols might be expanded in the future to /// reflect changes in the languages. /// </summary> ISymbol? AssociatedSymbol { get; } /// <summary> /// Determines if the symbol might contain extension methods. /// If false, the symbol does not contain extension methods. /// </summary> bool MightContainExtensionMethods { get; } /// <summary> /// If this is a tuple type with element names, returns the symbol for the tuple type without names. /// Otherwise, returns null. /// The type argument corresponding to the type of the extension field (VT[8].Rest), /// which is at the 8th (one based) position is always a symbol for another tuple, /// rather than its underlying type. /// </summary> INamedTypeSymbol? TupleUnderlyingType { get; } /// <summary> /// Returns fields that represent tuple elements for types that are tuples. /// /// If this type is not a tuple, then returns default. /// </summary> ImmutableArray<IFieldSymbol> TupleElements { get; } /// <summary> /// True if the type is serializable (has Serializable metadata flag). /// </summary> bool IsSerializable { get; } /// <summary> /// If this is a native integer, returns the symbol for the underlying type, /// either <see cref="System.IntPtr"/> or <see cref="System.UIntPtr"/>. /// Otherwise, returns null. /// </summary> INamedTypeSymbol? NativeIntegerUnderlyingType { get; } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Features/LanguageServer/Protocol/CSharpVisualBasicLanguageServerFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.LanguageServer.Handler; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Protocol; using StreamJsonRpc; namespace Microsoft.CodeAnalysis.LanguageServer { [Export(typeof(ILanguageServerFactory)), Shared] internal class CSharpVisualBasicLanguageServerFactory : ILanguageServerFactory { public const string UserVisibleName = "Roslyn Language Server Client"; private readonly RequestDispatcherFactory _dispatcherFactory; private readonly IAsynchronousOperationListenerProvider _listenerProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpVisualBasicLanguageServerFactory(RequestDispatcherFactory dispatcherFactory, IAsynchronousOperationListenerProvider listenerProvider) { _dispatcherFactory = dispatcherFactory; _listenerProvider = listenerProvider; } public ILanguageServerTarget Create( JsonRpc jsonRpc, ICapabilitiesProvider capabilitiesProvider, ILspWorkspaceRegistrationService workspaceRegistrationService, ILspLogger logger) { return new LanguageServerTarget( _dispatcherFactory, jsonRpc, capabilitiesProvider, workspaceRegistrationService, _listenerProvider, logger, ProtocolConstants.RoslynLspLanguages, clientName: null, userVisibleServerName: UserVisibleName, telemetryServerTypeName: this.GetType().Name); } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.LanguageServer.Handler; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.VisualStudio.LanguageServer.Protocol; using StreamJsonRpc; namespace Microsoft.CodeAnalysis.LanguageServer { [Export(typeof(ILanguageServerFactory)), Shared] internal class CSharpVisualBasicLanguageServerFactory : ILanguageServerFactory { public const string UserVisibleName = "Roslyn Language Server Client"; private readonly RequestDispatcherFactory _dispatcherFactory; private readonly IAsynchronousOperationListenerProvider _listenerProvider; [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpVisualBasicLanguageServerFactory(RequestDispatcherFactory dispatcherFactory, IAsynchronousOperationListenerProvider listenerProvider) { _dispatcherFactory = dispatcherFactory; _listenerProvider = listenerProvider; } public ILanguageServerTarget Create( JsonRpc jsonRpc, ICapabilitiesProvider capabilitiesProvider, ILspWorkspaceRegistrationService workspaceRegistrationService, ILspLogger logger) { return new LanguageServerTarget( _dispatcherFactory, jsonRpc, capabilitiesProvider, workspaceRegistrationService, _listenerProvider, logger, ProtocolConstants.RoslynLspLanguages, clientName: null, userVisibleServerName: UserVisibleName, telemetryServerTypeName: this.GetType().Name); } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Features/Core/Portable/TodoComments/AbstractTodoCommentService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.TodoComments { internal abstract class AbstractTodoCommentService : ITodoCommentService { protected abstract bool PreprocessorHasComment(SyntaxTrivia trivia); protected abstract bool IsSingleLineComment(SyntaxTrivia trivia); protected abstract bool IsMultilineComment(SyntaxTrivia trivia); protected abstract bool IsIdentifierCharacter(char ch); protected abstract string GetNormalizedText(string message); protected abstract int GetCommentStartingIndex(string message); protected abstract void AppendTodoComments(ImmutableArray<TodoCommentDescriptor> commentDescriptors, SyntacticDocument document, SyntaxTrivia trivia, ArrayBuilder<TodoComment> todoList); public async Task<ImmutableArray<TodoComment>> GetTodoCommentsAsync( Document document, ImmutableArray<TodoCommentDescriptor> commentDescriptors, CancellationToken cancellationToken) { if (commentDescriptors.IsEmpty) return ImmutableArray<TodoComment>.Empty; cancellationToken.ThrowIfCancellationRequested(); // strongly hold onto text and tree var syntaxDoc = await SyntacticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); // reuse list using var _ = ArrayBuilder<TodoComment>.GetInstance(out var todoList); foreach (var trivia in syntaxDoc.Root.DescendantTrivia()) { cancellationToken.ThrowIfCancellationRequested(); if (!ContainsComments(trivia)) continue; AppendTodoComments(commentDescriptors, syntaxDoc, trivia, todoList); } return todoList.ToImmutable(); } private bool ContainsComments(SyntaxTrivia trivia) => PreprocessorHasComment(trivia) || IsSingleLineComment(trivia) || IsMultilineComment(trivia); protected void AppendTodoCommentInfoFromSingleLine( ImmutableArray<TodoCommentDescriptor> commentDescriptors, string message, int start, ArrayBuilder<TodoComment> todoList) { var index = GetCommentStartingIndex(message); if (index >= message.Length) { return; } var normalized = GetNormalizedText(message); foreach (var commentDescriptor in commentDescriptors) { var token = commentDescriptor.Text; if (string.Compare( normalized, index, token, indexB: 0, length: token.Length, comparisonType: StringComparison.OrdinalIgnoreCase) != 0) { continue; } if ((message.Length > index + token.Length) && IsIdentifierCharacter(message[index + token.Length])) { // they wrote something like: // todoboo // instead of // todo continue; } todoList.Add(new TodoComment(commentDescriptor, message[index..], start + index)); } } protected void ProcessMultilineComment( ImmutableArray<TodoCommentDescriptor> commentDescriptors, SyntacticDocument document, SyntaxTrivia trivia, int postfixLength, ArrayBuilder<TodoComment> todoList) { // this is okay since we know it is already alive var text = document.Text; var fullSpan = trivia.FullSpan; var fullString = trivia.ToFullString(); var startLine = text.Lines.GetLineFromPosition(fullSpan.Start); var endLine = text.Lines.GetLineFromPosition(fullSpan.End); // single line multiline comments if (startLine.LineNumber == endLine.LineNumber) { var message = postfixLength == 0 ? fullString : fullString.Substring(0, fullSpan.Length - postfixLength); AppendTodoCommentInfoFromSingleLine(commentDescriptors, message, fullSpan.Start, todoList); return; } // multiline var startMessage = text.ToString(TextSpan.FromBounds(fullSpan.Start, startLine.End)); AppendTodoCommentInfoFromSingleLine(commentDescriptors, startMessage, fullSpan.Start, todoList); for (var lineNumber = startLine.LineNumber + 1; lineNumber < endLine.LineNumber; lineNumber++) { var line = text.Lines[lineNumber]; var message = line.ToString(); AppendTodoCommentInfoFromSingleLine(commentDescriptors, message, line.Start, todoList); } var length = fullSpan.End - endLine.Start; if (length >= postfixLength) { length -= postfixLength; } var endMessage = text.ToString(new TextSpan(endLine.Start, length)); AppendTodoCommentInfoFromSingleLine(commentDescriptors, endMessage, endLine.Start, todoList); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using System.Threading.Tasks; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.TodoComments { internal abstract class AbstractTodoCommentService : ITodoCommentService { protected abstract bool PreprocessorHasComment(SyntaxTrivia trivia); protected abstract bool IsSingleLineComment(SyntaxTrivia trivia); protected abstract bool IsMultilineComment(SyntaxTrivia trivia); protected abstract bool IsIdentifierCharacter(char ch); protected abstract string GetNormalizedText(string message); protected abstract int GetCommentStartingIndex(string message); protected abstract void AppendTodoComments(ImmutableArray<TodoCommentDescriptor> commentDescriptors, SyntacticDocument document, SyntaxTrivia trivia, ArrayBuilder<TodoComment> todoList); public async Task<ImmutableArray<TodoComment>> GetTodoCommentsAsync( Document document, ImmutableArray<TodoCommentDescriptor> commentDescriptors, CancellationToken cancellationToken) { if (commentDescriptors.IsEmpty) return ImmutableArray<TodoComment>.Empty; cancellationToken.ThrowIfCancellationRequested(); // strongly hold onto text and tree var syntaxDoc = await SyntacticDocument.CreateAsync(document, cancellationToken).ConfigureAwait(false); // reuse list using var _ = ArrayBuilder<TodoComment>.GetInstance(out var todoList); foreach (var trivia in syntaxDoc.Root.DescendantTrivia()) { cancellationToken.ThrowIfCancellationRequested(); if (!ContainsComments(trivia)) continue; AppendTodoComments(commentDescriptors, syntaxDoc, trivia, todoList); } return todoList.ToImmutable(); } private bool ContainsComments(SyntaxTrivia trivia) => PreprocessorHasComment(trivia) || IsSingleLineComment(trivia) || IsMultilineComment(trivia); protected void AppendTodoCommentInfoFromSingleLine( ImmutableArray<TodoCommentDescriptor> commentDescriptors, string message, int start, ArrayBuilder<TodoComment> todoList) { var index = GetCommentStartingIndex(message); if (index >= message.Length) { return; } var normalized = GetNormalizedText(message); foreach (var commentDescriptor in commentDescriptors) { var token = commentDescriptor.Text; if (string.Compare( normalized, index, token, indexB: 0, length: token.Length, comparisonType: StringComparison.OrdinalIgnoreCase) != 0) { continue; } if ((message.Length > index + token.Length) && IsIdentifierCharacter(message[index + token.Length])) { // they wrote something like: // todoboo // instead of // todo continue; } todoList.Add(new TodoComment(commentDescriptor, message[index..], start + index)); } } protected void ProcessMultilineComment( ImmutableArray<TodoCommentDescriptor> commentDescriptors, SyntacticDocument document, SyntaxTrivia trivia, int postfixLength, ArrayBuilder<TodoComment> todoList) { // this is okay since we know it is already alive var text = document.Text; var fullSpan = trivia.FullSpan; var fullString = trivia.ToFullString(); var startLine = text.Lines.GetLineFromPosition(fullSpan.Start); var endLine = text.Lines.GetLineFromPosition(fullSpan.End); // single line multiline comments if (startLine.LineNumber == endLine.LineNumber) { var message = postfixLength == 0 ? fullString : fullString.Substring(0, fullSpan.Length - postfixLength); AppendTodoCommentInfoFromSingleLine(commentDescriptors, message, fullSpan.Start, todoList); return; } // multiline var startMessage = text.ToString(TextSpan.FromBounds(fullSpan.Start, startLine.End)); AppendTodoCommentInfoFromSingleLine(commentDescriptors, startMessage, fullSpan.Start, todoList); for (var lineNumber = startLine.LineNumber + 1; lineNumber < endLine.LineNumber; lineNumber++) { var line = text.Lines[lineNumber]; var message = line.ToString(); AppendTodoCommentInfoFromSingleLine(commentDescriptors, message, line.Start, todoList); } var length = fullSpan.End - endLine.Start; if (length >= postfixLength) { length -= postfixLength; } var endMessage = text.ToString(new TextSpan(endLine.Start, length)); AppendTodoCommentInfoFromSingleLine(commentDescriptors, endMessage, endLine.Start, todoList); } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Workspaces/Core/Portable/CodeGeneration/AbstractFlagsEnumGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal abstract class AbstractFlagsEnumGenerator : IComparer<(IFieldSymbol field, ulong value)> { protected abstract SyntaxGenerator GetSyntaxGenerator(); protected abstract SyntaxNode CreateExplicitlyCastedLiteralValue(INamedTypeSymbol enumType, SpecialType underlyingSpecialType, object? constantValue); protected abstract bool IsValidName(INamedTypeSymbol enumType, string name); public SyntaxNode? TryCreateEnumConstantValue(INamedTypeSymbol enumType, object constantValue) { // Code copied from System.Enum. var isFlagsEnum = IsFlagsEnum(enumType); if (isFlagsEnum) { return CreateFlagsEnumConstantValue(enumType, constantValue); } else { // Try to see if its one of the enum values. If so, add that. Otherwise, just add // the literal value of the enum. return CreateNonFlagsEnumConstantValue(enumType, constantValue); } } private static bool IsFlagsEnum(INamedTypeSymbol typeSymbol) { if (typeSymbol.TypeKind != TypeKind.Enum) { return false; } foreach (var attribute in typeSymbol.GetAttributes()) { var ctor = attribute.AttributeConstructor; if (ctor != null) { var type = ctor.ContainingType; if (!ctor.Parameters.Any() && type.Name == "FlagsAttribute") { var containingSymbol = type.ContainingSymbol; if (containingSymbol.Kind == SymbolKind.Namespace && containingSymbol.Name == "System" && ((INamespaceSymbol)containingSymbol.ContainingSymbol).IsGlobalNamespace) { return true; } } } } return false; } private SyntaxNode? CreateFlagsEnumConstantValue(INamedTypeSymbol enumType, object constantValue) { // These values are sorted by value. Don't change this. var allFieldsAndValues = new List<(IFieldSymbol field, ulong value)>(); GetSortedEnumFieldsAndValues(enumType, allFieldsAndValues); var usedFieldsAndValues = new List<(IFieldSymbol field, ulong value)>(); return CreateFlagsEnumConstantValue(enumType, constantValue, allFieldsAndValues, usedFieldsAndValues); } private SyntaxNode? CreateFlagsEnumConstantValue( INamedTypeSymbol enumType, object constantValue, List<(IFieldSymbol field, ulong value)> allFieldsAndValues, List<(IFieldSymbol field, ulong value)> usedFieldsAndValues) { Contract.ThrowIfNull(enumType.EnumUnderlyingType); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; var constantValueULong = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, underlyingSpecialType); var result = constantValueULong; // We will not optimize this code further to keep it maintainable. There are some // boundary checks that can be applied to minimize the comparisons required. This code // works the same for the best/worst case. In general the number of items in an enum are // sufficiently small and not worth the optimization. for (var index = allFieldsAndValues.Count - 1; index >= 0 && result != 0; index--) { var fieldAndValue = allFieldsAndValues[index]; var valueAtIndex = fieldAndValue.value; if (valueAtIndex != 0 && (result & valueAtIndex) == valueAtIndex) { result -= valueAtIndex; usedFieldsAndValues.Add(fieldAndValue); } } var syntaxFactory = GetSyntaxGenerator(); // We were able to represent this number as a bitwise OR of valid flags. if (result == 0 && usedFieldsAndValues.Count > 0) { // We want to emit the fields in lower to higher value. So we walk backward. SyntaxNode? finalNode = null; for (var i = usedFieldsAndValues.Count - 1; i >= 0; i--) { var field = usedFieldsAndValues[i]; var node = CreateMemberAccessExpression(field.field, enumType, underlyingSpecialType); if (finalNode == null) { finalNode = node; } else { finalNode = syntaxFactory.BitwiseOrExpression(finalNode, node); } } return finalNode; } else { // We couldn't find fields to OR together to make the value. // If we had 0 as the value, and there's an enum value equal to 0, then use that. var zeroField = GetZeroField(allFieldsAndValues); if (constantValueULong == 0 && zeroField != null) { return CreateMemberAccessExpression(zeroField, enumType, underlyingSpecialType); } else { // Add anything else in as a literal value. return CreateExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, constantValue); } } } private SyntaxNode CreateMemberAccessExpression( IFieldSymbol field, INamedTypeSymbol enumType, SpecialType underlyingSpecialType) { if (IsValidName(enumType, field.Name)) { var syntaxFactory = GetSyntaxGenerator(); return syntaxFactory.MemberAccessExpression( syntaxFactory.TypeExpression(enumType), syntaxFactory.IdentifierName(field.Name)); } else { return CreateExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, field.ConstantValue); } } private static IFieldSymbol? GetZeroField(List<(IFieldSymbol field, ulong value)> allFieldsAndValues) { for (var i = allFieldsAndValues.Count - 1; i >= 0; i--) { var (field, value) = allFieldsAndValues[i]; if (value == 0) { return field; } } return null; } private void GetSortedEnumFieldsAndValues( INamedTypeSymbol enumType, List<(IFieldSymbol field, ulong value)> allFieldsAndValues) { Contract.ThrowIfNull(enumType.EnumUnderlyingType); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; foreach (var field in enumType.GetMembers().OfType<IFieldSymbol>()) { if (field is { HasConstantValue: true, ConstantValue: not null }) { var value = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(field.ConstantValue, underlyingSpecialType); allFieldsAndValues.Add((field, value)); } } allFieldsAndValues.Sort(this); } private SyntaxNode CreateNonFlagsEnumConstantValue(INamedTypeSymbol enumType, object constantValue) { Contract.ThrowIfNull(enumType.EnumUnderlyingType); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; var constantValueULong = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, underlyingSpecialType); // See if there's a member with this value. If so, then use that. foreach (var field in enumType.GetMembers().OfType<IFieldSymbol>()) { if (field is { HasConstantValue: true, ConstantValue: not null }) { var fieldValue = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(field.ConstantValue, underlyingSpecialType); if (constantValueULong == fieldValue) { return CreateMemberAccessExpression(field, enumType, underlyingSpecialType); } } } // Otherwise, just add the enum as a literal. return CreateExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, constantValue); } int IComparer<(IFieldSymbol field, ulong value)>.Compare((IFieldSymbol field, ulong value) x, (IFieldSymbol field, ulong value) y) { unchecked { return (long)x.value < (long)y.value ? -1 : (long)x.value > (long)y.value ? 1 : -x.field.Name.CompareTo(y.field.Name); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editing; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal abstract class AbstractFlagsEnumGenerator : IComparer<(IFieldSymbol field, ulong value)> { protected abstract SyntaxGenerator GetSyntaxGenerator(); protected abstract SyntaxNode CreateExplicitlyCastedLiteralValue(INamedTypeSymbol enumType, SpecialType underlyingSpecialType, object? constantValue); protected abstract bool IsValidName(INamedTypeSymbol enumType, string name); public SyntaxNode? TryCreateEnumConstantValue(INamedTypeSymbol enumType, object constantValue) { // Code copied from System.Enum. var isFlagsEnum = IsFlagsEnum(enumType); if (isFlagsEnum) { return CreateFlagsEnumConstantValue(enumType, constantValue); } else { // Try to see if its one of the enum values. If so, add that. Otherwise, just add // the literal value of the enum. return CreateNonFlagsEnumConstantValue(enumType, constantValue); } } private static bool IsFlagsEnum(INamedTypeSymbol typeSymbol) { if (typeSymbol.TypeKind != TypeKind.Enum) { return false; } foreach (var attribute in typeSymbol.GetAttributes()) { var ctor = attribute.AttributeConstructor; if (ctor != null) { var type = ctor.ContainingType; if (!ctor.Parameters.Any() && type.Name == "FlagsAttribute") { var containingSymbol = type.ContainingSymbol; if (containingSymbol.Kind == SymbolKind.Namespace && containingSymbol.Name == "System" && ((INamespaceSymbol)containingSymbol.ContainingSymbol).IsGlobalNamespace) { return true; } } } } return false; } private SyntaxNode? CreateFlagsEnumConstantValue(INamedTypeSymbol enumType, object constantValue) { // These values are sorted by value. Don't change this. var allFieldsAndValues = new List<(IFieldSymbol field, ulong value)>(); GetSortedEnumFieldsAndValues(enumType, allFieldsAndValues); var usedFieldsAndValues = new List<(IFieldSymbol field, ulong value)>(); return CreateFlagsEnumConstantValue(enumType, constantValue, allFieldsAndValues, usedFieldsAndValues); } private SyntaxNode? CreateFlagsEnumConstantValue( INamedTypeSymbol enumType, object constantValue, List<(IFieldSymbol field, ulong value)> allFieldsAndValues, List<(IFieldSymbol field, ulong value)> usedFieldsAndValues) { Contract.ThrowIfNull(enumType.EnumUnderlyingType); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; var constantValueULong = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, underlyingSpecialType); var result = constantValueULong; // We will not optimize this code further to keep it maintainable. There are some // boundary checks that can be applied to minimize the comparisons required. This code // works the same for the best/worst case. In general the number of items in an enum are // sufficiently small and not worth the optimization. for (var index = allFieldsAndValues.Count - 1; index >= 0 && result != 0; index--) { var fieldAndValue = allFieldsAndValues[index]; var valueAtIndex = fieldAndValue.value; if (valueAtIndex != 0 && (result & valueAtIndex) == valueAtIndex) { result -= valueAtIndex; usedFieldsAndValues.Add(fieldAndValue); } } var syntaxFactory = GetSyntaxGenerator(); // We were able to represent this number as a bitwise OR of valid flags. if (result == 0 && usedFieldsAndValues.Count > 0) { // We want to emit the fields in lower to higher value. So we walk backward. SyntaxNode? finalNode = null; for (var i = usedFieldsAndValues.Count - 1; i >= 0; i--) { var field = usedFieldsAndValues[i]; var node = CreateMemberAccessExpression(field.field, enumType, underlyingSpecialType); if (finalNode == null) { finalNode = node; } else { finalNode = syntaxFactory.BitwiseOrExpression(finalNode, node); } } return finalNode; } else { // We couldn't find fields to OR together to make the value. // If we had 0 as the value, and there's an enum value equal to 0, then use that. var zeroField = GetZeroField(allFieldsAndValues); if (constantValueULong == 0 && zeroField != null) { return CreateMemberAccessExpression(zeroField, enumType, underlyingSpecialType); } else { // Add anything else in as a literal value. return CreateExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, constantValue); } } } private SyntaxNode CreateMemberAccessExpression( IFieldSymbol field, INamedTypeSymbol enumType, SpecialType underlyingSpecialType) { if (IsValidName(enumType, field.Name)) { var syntaxFactory = GetSyntaxGenerator(); return syntaxFactory.MemberAccessExpression( syntaxFactory.TypeExpression(enumType), syntaxFactory.IdentifierName(field.Name)); } else { return CreateExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, field.ConstantValue); } } private static IFieldSymbol? GetZeroField(List<(IFieldSymbol field, ulong value)> allFieldsAndValues) { for (var i = allFieldsAndValues.Count - 1; i >= 0; i--) { var (field, value) = allFieldsAndValues[i]; if (value == 0) { return field; } } return null; } private void GetSortedEnumFieldsAndValues( INamedTypeSymbol enumType, List<(IFieldSymbol field, ulong value)> allFieldsAndValues) { Contract.ThrowIfNull(enumType.EnumUnderlyingType); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; foreach (var field in enumType.GetMembers().OfType<IFieldSymbol>()) { if (field is { HasConstantValue: true, ConstantValue: not null }) { var value = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(field.ConstantValue, underlyingSpecialType); allFieldsAndValues.Add((field, value)); } } allFieldsAndValues.Sort(this); } private SyntaxNode CreateNonFlagsEnumConstantValue(INamedTypeSymbol enumType, object constantValue) { Contract.ThrowIfNull(enumType.EnumUnderlyingType); var underlyingSpecialType = enumType.EnumUnderlyingType.SpecialType; var constantValueULong = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(constantValue, underlyingSpecialType); // See if there's a member with this value. If so, then use that. foreach (var field in enumType.GetMembers().OfType<IFieldSymbol>()) { if (field is { HasConstantValue: true, ConstantValue: not null }) { var fieldValue = EnumUtilities.ConvertEnumUnderlyingTypeToUInt64(field.ConstantValue, underlyingSpecialType); if (constantValueULong == fieldValue) { return CreateMemberAccessExpression(field, enumType, underlyingSpecialType); } } } // Otherwise, just add the enum as a literal. return CreateExplicitlyCastedLiteralValue(enumType, underlyingSpecialType, constantValue); } int IComparer<(IFieldSymbol field, ulong value)>.Compare((IFieldSymbol field, ulong value) x, (IFieldSymbol field, ulong value) y) { unchecked { return (long)x.value < (long)y.value ? -1 : (long)x.value > (long)y.value ? 1 : -x.field.Name.CompareTo(y.field.Name); } } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Features/Core/Portable/Shared/TestHooks/Legacy/ListenerForwarders.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.AsynchronousOperationListener))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.AsynchronousOperationListenerProvider))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.EmptyAsyncToken))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsynchronousOperationListenerProvider))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsynchronousOperationWaiter))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsynchronousOperationListener))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsyncToken))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.TaskExtensions))]
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Runtime.CompilerServices; [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.AsynchronousOperationListener))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.AsynchronousOperationListenerProvider))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.EmptyAsyncToken))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsynchronousOperationListenerProvider))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsynchronousOperationWaiter))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsynchronousOperationListener))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.IAsyncToken))] [assembly: TypeForwardedTo(typeof(Microsoft.CodeAnalysis.Shared.TestHooks.TaskExtensions))]
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Features/CSharp/Portable/UseExplicitTypeForConst/UseExplicitTypeForConstCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.UseExplicitTypeForConst { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseExplicitTypeForConst), Shared] internal sealed class UseExplicitTypeForConstCodeFixProvider : CodeFixProvider { private const string CS0822 = nameof(CS0822); // Implicitly-typed variables cannot be constant [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseExplicitTypeForConstCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(CS0822); public override FixAllProvider GetFixAllProvider() { // This code fix addresses a very specific compiler error. It's unlikely there will be more than 1 of them at a time. return null; } public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); if (root.FindNode(context.Span) is VariableDeclarationSyntax variableDeclaration && variableDeclaration.Variables.Count == 1) { var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); var type = semanticModel.GetTypeInfo(variableDeclaration.Type, context.CancellationToken).ConvertedType; if (type == null || type.TypeKind == TypeKind.Error || type.IsAnonymousType) { return; } context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Span, type, c)), context.Diagnostics); } } private static async Task<Document> FixAsync( Document document, TextSpan span, ITypeSymbol type, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var variableDeclaration = (VariableDeclarationSyntax)root.FindNode(span); var newRoot = root.ReplaceNode(variableDeclaration.Type, type.GenerateTypeSyntax(allowVar: false)); return document.WithSyntaxRoot(newRoot); } private sealed class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_explicit_type_instead_of_var, createChangedDocument, nameof(CSharpAnalyzersResources.Use_explicit_type_instead_of_var)) { } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.UseExplicitTypeForConst { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.UseExplicitTypeForConst), Shared] internal sealed class UseExplicitTypeForConstCodeFixProvider : CodeFixProvider { private const string CS0822 = nameof(CS0822); // Implicitly-typed variables cannot be constant [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public UseExplicitTypeForConstCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(CS0822); public override FixAllProvider GetFixAllProvider() { // This code fix addresses a very specific compiler error. It's unlikely there will be more than 1 of them at a time. return null; } public override async Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); if (root.FindNode(context.Span) is VariableDeclarationSyntax variableDeclaration && variableDeclaration.Variables.Count == 1) { var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); var type = semanticModel.GetTypeInfo(variableDeclaration.Type, context.CancellationToken).ConvertedType; if (type == null || type.TypeKind == TypeKind.Error || type.IsAnonymousType) { return; } context.RegisterCodeFix( new MyCodeAction(c => FixAsync(context.Document, context.Span, type, c)), context.Diagnostics); } } private static async Task<Document> FixAsync( Document document, TextSpan span, ITypeSymbol type, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var variableDeclaration = (VariableDeclarationSyntax)root.FindNode(span); var newRoot = root.ReplaceNode(variableDeclaration.Type, type.GenerateTypeSyntax(allowVar: false)); return document.WithSyntaxRoot(newRoot); } private sealed class MyCodeAction : CodeAction.DocumentChangeAction { public MyCodeAction(Func<CancellationToken, Task<Document>> createChangedDocument) : base(CSharpAnalyzersResources.Use_explicit_type_instead_of_var, createChangedDocument, nameof(CSharpAnalyzersResources.Use_explicit_type_instead_of_var)) { } } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/Core/Portable/SourceGeneration/Nodes/IIncrementalGeneratorOutputNode.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Internal representation of an incremental output /// </summary> internal interface IIncrementalGeneratorOutputNode { IncrementalGeneratorOutputKind Kind { get; } void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken); } /// <summary> /// Represents the various output kinds of an <see cref="IIncrementalGenerator"/>. /// </summary> /// <remarks> /// Can be passed as a bit field when creating a <see cref="GeneratorDriver"/> to selectively disable outputs. /// </remarks> [Flags] public enum IncrementalGeneratorOutputKind { /// <summary> /// Represents no output kinds. Can be used when creating a driver to indicate that no outputs should be disabled. /// </summary> None = 0, /// <summary> /// A regular source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// or <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> Source = 0b1, /// <summary> /// A post-initialization output, which will be visible to later phases, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(Action{IncrementalGeneratorPostInitializationContext})"/> /// </summary> PostInit = 0b10, /// <summary> /// An Implementation only source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// or <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> Implementation = 0b100 } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace Microsoft.CodeAnalysis { /// <summary> /// Internal representation of an incremental output /// </summary> internal interface IIncrementalGeneratorOutputNode { IncrementalGeneratorOutputKind Kind { get; } void AppendOutputs(IncrementalExecutionContext context, CancellationToken cancellationToken); } /// <summary> /// Represents the various output kinds of an <see cref="IIncrementalGenerator"/>. /// </summary> /// <remarks> /// Can be passed as a bit field when creating a <see cref="GeneratorDriver"/> to selectively disable outputs. /// </remarks> [Flags] public enum IncrementalGeneratorOutputKind { /// <summary> /// Represents no output kinds. Can be used when creating a driver to indicate that no outputs should be disabled. /// </summary> None = 0, /// <summary> /// A regular source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// or <see cref="IncrementalGeneratorInitializationContext.RegisterSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> Source = 0b1, /// <summary> /// A post-initialization output, which will be visible to later phases, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterPostInitializationOutput(Action{IncrementalGeneratorPostInitializationContext})"/> /// </summary> PostInit = 0b10, /// <summary> /// An Implementation only source output, registered via <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValueProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// or <see cref="IncrementalGeneratorInitializationContext.RegisterImplementationSourceOutput{TSource}(IncrementalValuesProvider{TSource}, Action{SourceProductionContext, TSource})"/> /// </summary> Implementation = 0b100 } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/Core/Portable/MetadataReference/MetadataReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.IO; using System.Reflection; using System.Reflection.PortableExecutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents metadata image reference. /// </summary> /// <remarks> /// Represents a logical location of the image, not the content of the image. /// The content might change in time. A snapshot is taken when the compiler queries the reference for its metadata. /// </remarks> public abstract class MetadataReference { public MetadataReferenceProperties Properties { get; } protected MetadataReference(MetadataReferenceProperties properties) { this.Properties = properties; } /// <summary> /// Path or name used in error messages to identity the reference. /// </summary> public virtual string? Display { get { return null; } } /// <summary> /// Returns true if this reference is an unresolved reference. /// </summary> internal virtual bool IsUnresolved { get { return false; } } /// <summary> /// Returns an instance of the reference with specified aliases. /// </summary> /// <param name="aliases">The new aliases for the reference.</param> /// <exception cref="ArgumentException">Alias is invalid for the metadata kind.</exception> public MetadataReference WithAliases(IEnumerable<string> aliases) { return WithAliases(ImmutableArray.CreateRange(aliases)); } /// <summary> /// Returns an instance of the reference with specified interop types embedding. /// </summary> /// <param name="value">The new value for <see cref="MetadataReferenceProperties.EmbedInteropTypes"/>.</param> /// <exception cref="ArgumentException">Interop types can't be embedded from modules.</exception> public MetadataReference WithEmbedInteropTypes(bool value) { return WithProperties(Properties.WithEmbedInteropTypes(value)); } /// <summary> /// Returns an instance of the reference with specified aliases. /// </summary> /// <param name="aliases">The new aliases for the reference.</param> /// <exception cref="ArgumentException">Alias is invalid for the metadata kind.</exception> public MetadataReference WithAliases(ImmutableArray<string> aliases) { return WithProperties(Properties.WithAliases(aliases)); } /// <summary> /// Returns an instance of the reference with specified properties, or this instance if properties haven't changed. /// </summary> /// <param name="properties">The new properties for the reference.</param> /// <exception cref="ArgumentException">Specified values not valid for this reference.</exception> public MetadataReference WithProperties(MetadataReferenceProperties properties) { if (properties == this.Properties) { return this; } return WithPropertiesImplReturningMetadataReference(properties); } internal abstract MetadataReference WithPropertiesImplReturningMetadataReference(MetadataReferenceProperties properties); /// <summary> /// Creates a reference to a single-module assembly or a standalone module stored in memory. /// </summary> /// <param name="peImage">Assembly image.</param> /// <param name="properties">Reference properties (extern aliases, type embedding, <see cref="MetadataImageKind"/>).</param> /// <param name="documentation">Provides XML documentation for symbol found in the reference.</param> /// <param name="filePath">Optional path that describes the location of the metadata. The file doesn't need to exist on disk. The path is opaque to the compiler.</param> /// <remarks> /// Performance considerations: /// <para> /// It is recommended to use <see cref="AssemblyMetadata.CreateFromImage(ImmutableArray{byte})"/> or <see cref="ModuleMetadata.CreateFromImage(ImmutableArray{byte})"/> /// API when creating multiple references to the same metadata. /// Reusing <see cref="Metadata"/> object to create multiple references allows for sharing data across these references. /// </para> /// <para> /// The method pins <paramref name="peImage"/> in managed heap. The pinned memory is released /// when the resulting reference becomes unreachable and GC collects it. To control the lifetime of the pinned memory /// deterministically use <see cref="AssemblyMetadata.CreateFromImage(ImmutableArray{byte})"/> /// to create an <see cref="IDisposable"/> metadata object and /// <see cref="AssemblyMetadata.GetReference(DocumentationProvider, ImmutableArray{string}, bool, string, string)"/> to get a reference to it. /// </para> /// <para> /// The method creates a reference to a single-module assembly. To create a reference to a multi-module assembly or a stand-alone module use /// <see cref="ModuleMetadata.CreateFromImage(ImmutableArray{byte})"/> and <see cref="ModuleMetadata.GetReference(DocumentationProvider, string, string)"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> public static PortableExecutableReference CreateFromImage( ImmutableArray<byte> peImage, MetadataReferenceProperties properties = default, DocumentationProvider? documentation = null, string? filePath = null) { var metadata = AssemblyMetadata.CreateFromImage(peImage); return new MetadataImageReference(metadata, properties, documentation, filePath, display: null); } /// <summary> /// Creates a reference to a single-module assembly or a standalone module stored in memory. /// </summary> /// <param name="peImage">Assembly image.</param> /// <param name="properties">Reference properties (extern aliases, type embedding, <see cref="MetadataImageKind"/>).</param> /// <param name="documentation">Provides XML documentation for symbol found in the reference.</param> /// <param name="filePath">Optional path that describes the location of the metadata. The file doesn't need to exist on disk. The path is opaque to the compiler.</param> /// <remarks> /// Performance considerations: /// <para> /// It is recommended to use <see cref="AssemblyMetadata.CreateFromImage(IEnumerable{byte})"/> or <see cref="ModuleMetadata.CreateFromImage(IEnumerable{byte})"/> /// API when creating multiple references to the same metadata. /// Reusing <see cref="Metadata"/> object to create multiple references allows for sharing data across these references. /// </para> /// <para> /// The method makes a copy of the data and pins it. To avoid making a copy use an overload that takes an <see cref="ImmutableArray{T}"/>. /// The pinned memory is released when the resulting reference becomes unreachable and GC collects it. To control the lifetime of the pinned memory /// deterministically use <see cref="AssemblyMetadata.CreateFromStream(Stream, PEStreamOptions)"/> /// to create an <see cref="IDisposable"/> metadata object and /// <see cref="AssemblyMetadata.GetReference(DocumentationProvider, ImmutableArray{string}, bool, string, string)"/> to get a reference to it. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> public static PortableExecutableReference CreateFromImage( IEnumerable<byte> peImage, MetadataReferenceProperties properties = default, DocumentationProvider? documentation = null, string? filePath = null) { var metadata = AssemblyMetadata.CreateFromImage(peImage); return new MetadataImageReference(metadata, properties, documentation, filePath, display: null); } /// <summary> /// Creates a reference to a single-module assembly or a stand-alone module from data in specified stream. /// Reads the content of the stream into memory and closes the stream upon return. /// </summary> /// <param name="peStream">Assembly image.</param> /// <param name="properties">Reference properties (extern aliases, type embedding, <see cref="MetadataImageKind"/>).</param> /// <param name="documentation">Provides XML documentation for symbol found in the reference.</param> /// <param name="filePath">Optional path that describes the location of the metadata. The file doesn't need to exist on disk. The path is opaque to the compiler.</param> /// <exception cref="ArgumentException"><paramref name="peStream"/> doesn't support read and seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="IOException">An error occurred while reading the stream.</exception> /// <remarks> /// Performance considerations: /// <para> /// It is recommended to use <see cref="AssemblyMetadata.CreateFromStream(Stream, PEStreamOptions)"/> or <see cref="ModuleMetadata.CreateFromStream(Stream, PEStreamOptions)"/> /// API when creating multiple references to the same metadata. /// Reusing <see cref="Metadata"/> object to create multiple references allows for sharing data across these references. /// </para> /// <para> /// The method eagerly reads the entire content of <paramref name="peStream"/> into native heap. The native memory block is released /// when the resulting reference becomes unreachable and GC collects it. To decrease memory footprint of the reference and/or manage /// the lifetime deterministically use <see cref="AssemblyMetadata.CreateFromStream(Stream, PEStreamOptions)"/> /// to create an <see cref="IDisposable"/> metadata object and /// <see cref="AssemblyMetadata.GetReference(DocumentationProvider, ImmutableArray{string}, bool, string, string)"/> /// to get a reference to it. /// </para> /// </remarks> public static PortableExecutableReference CreateFromStream( Stream peStream, MetadataReferenceProperties properties = default, DocumentationProvider? documentation = null, string? filePath = null) { // Prefetch data and close the stream. var metadata = AssemblyMetadata.CreateFromStream(peStream, PEStreamOptions.PrefetchEntireImage); return new MetadataImageReference(metadata, properties, documentation, filePath, display: null); } /// <summary> /// Creates a reference to an assembly or standalone module stored in a file. /// Reads the content of the file into memory. /// </summary> /// <param name="path">Path to the assembly file.</param> /// <param name="properties">Reference properties (extern aliases, type embedding, <see cref="MetadataImageKind"/>).</param> /// <param name="documentation">Provides XML documentation for symbol found in the reference.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is invalid.</exception> /// <exception cref="IOException">An error occurred while reading the file.</exception> /// <remarks> /// Performance considerations: /// <para> /// It is recommended to use <see cref="AssemblyMetadata.CreateFromFile(string)"/> or <see cref="ModuleMetadata.CreateFromFile(string)"/> /// API when creating multiple references to the same file. /// Reusing <see cref="Metadata"/> object allows for sharing data across these references. /// </para> /// <para> /// The method eagerly reads the entire content of the file into native heap. The native memory block is released /// when the resulting reference becomes unreachable and GC collects it. To decrease memory footprint of the reference and/or manage /// the lifetime deterministically use <see cref="AssemblyMetadata.CreateFromFile(string)"/> /// to create an <see cref="IDisposable"/> metadata object and /// <see cref="AssemblyMetadata.GetReference(DocumentationProvider, ImmutableArray{string}, bool, string, string)"/> /// to get a reference to it. /// </para> /// </remarks> public static PortableExecutableReference CreateFromFile( string path, MetadataReferenceProperties properties = default, DocumentationProvider? documentation = null) => CreateFromFile( StandardFileSystem.Instance.OpenFileWithNormalizedException(path, FileMode.Open, FileAccess.Read, FileShare.Read), path, properties, documentation); internal static PortableExecutableReference CreateFromFile( Stream peStream, string path, MetadataReferenceProperties properties = default, DocumentationProvider? documentation = null) { // prefetch image, close stream to avoid locking it: var module = ModuleMetadata.CreateFromStream(peStream, PEStreamOptions.PrefetchEntireImage); if (properties.Kind == MetadataImageKind.Module) { return new MetadataImageReference(module, properties, documentation, path, display: null); } // any additional modules constituting the assembly will be read lazily: var assemblyMetadata = AssemblyMetadata.CreateFromFile(module, path); return new MetadataImageReference(assemblyMetadata, properties, documentation, path, display: null); } /// <summary> /// Creates a reference to a loaded assembly. /// </summary> /// <param name="assembly">Path to the module file.</param> /// <exception cref="ArgumentNullException"><paramref name="assembly"/> is null.</exception> /// <exception cref="NotSupportedException"><paramref name="assembly"/> is dynamic, doesn't have a location, or the platform doesn't support reading from the location.</exception> /// <remarks> /// Performance considerations: /// <para> /// It is recommended to use <see cref="AssemblyMetadata.CreateFromFile(string)"/> API when creating multiple references to the same assembly. /// Reusing <see cref="AssemblyMetadata"/> object allows for sharing data across these references. /// </para> /// </remarks> [Obsolete("Use CreateFromFile(assembly.Location) instead", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public static MetadataReference CreateFromAssembly(Assembly assembly) { return CreateFromAssemblyInternal(assembly); } internal static MetadataReference CreateFromAssemblyInternal(Assembly assembly) { return CreateFromAssemblyInternal(assembly, default(MetadataReferenceProperties)); } /// <summary> /// Creates a reference to a loaded assembly. /// </summary> /// <param name="assembly">Path to the module file.</param> /// <param name="properties">Reference properties (extern aliases, type embedding).</param> /// <param name="documentation">Provides XML documentation for symbol found in the reference.</param> /// <exception cref="ArgumentNullException"><paramref name="assembly"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="properties"/>.<see cref="MetadataReferenceProperties.Kind"/> is not <see cref="MetadataImageKind.Assembly"/>.</exception> /// <exception cref="NotSupportedException"><paramref name="assembly"/> is dynamic, doesn't have a location, or the platform doesn't support reading from the location.</exception> /// <remarks> /// Performance considerations: /// <para> /// It is recommended to use <see cref="AssemblyMetadata.CreateFromFile(string)"/> API when creating multiple references to the same assembly. /// Reusing <see cref="AssemblyMetadata"/> object allows for sharing data across these references. /// </para> /// </remarks> [Obsolete("Use CreateFromFile(assembly.Location) instead", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public static MetadataReference CreateFromAssembly( Assembly assembly, MetadataReferenceProperties properties, DocumentationProvider? documentation = null) { return CreateFromAssemblyInternal(assembly, properties, documentation); } internal static PortableExecutableReference CreateFromAssemblyInternal( Assembly assembly, MetadataReferenceProperties properties, DocumentationProvider? documentation = null) { // Note: returns MetadataReference and not PortableExecutableReference so that we can in future support assemblies that // which are not backed by PE image. if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } if (assembly.IsDynamic) { throw new NotSupportedException(CodeAnalysisResources.CantCreateReferenceToDynamicAssembly); } if (properties.Kind != MetadataImageKind.Assembly) { throw new ArgumentException(CodeAnalysisResources.CantCreateModuleReferenceToAssembly, nameof(properties)); } string location = assembly.Location; if (string.IsNullOrEmpty(location)) { throw new NotSupportedException(CodeAnalysisResources.CantCreateReferenceToAssemblyWithoutLocation); } Stream peStream = StandardFileSystem.Instance.OpenFileWithNormalizedException(location, FileMode.Open, FileAccess.Read, FileShare.Read); // The file is locked by the CLR assembly loader, so we can create a lazily read metadata, // which might also lock the file until the reference is GC'd. var metadata = AssemblyMetadata.CreateFromStream(peStream); return new MetadataImageReference(metadata, properties, documentation, location, display: null); } internal static bool HasMetadata(Assembly assembly) { return !assembly.IsDynamic && !string.IsNullOrEmpty(assembly.Location); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel; using System.IO; using System.Reflection; using System.Reflection.PortableExecutable; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { /// <summary> /// Represents metadata image reference. /// </summary> /// <remarks> /// Represents a logical location of the image, not the content of the image. /// The content might change in time. A snapshot is taken when the compiler queries the reference for its metadata. /// </remarks> public abstract class MetadataReference { public MetadataReferenceProperties Properties { get; } protected MetadataReference(MetadataReferenceProperties properties) { this.Properties = properties; } /// <summary> /// Path or name used in error messages to identity the reference. /// </summary> public virtual string? Display { get { return null; } } /// <summary> /// Returns true if this reference is an unresolved reference. /// </summary> internal virtual bool IsUnresolved { get { return false; } } /// <summary> /// Returns an instance of the reference with specified aliases. /// </summary> /// <param name="aliases">The new aliases for the reference.</param> /// <exception cref="ArgumentException">Alias is invalid for the metadata kind.</exception> public MetadataReference WithAliases(IEnumerable<string> aliases) { return WithAliases(ImmutableArray.CreateRange(aliases)); } /// <summary> /// Returns an instance of the reference with specified interop types embedding. /// </summary> /// <param name="value">The new value for <see cref="MetadataReferenceProperties.EmbedInteropTypes"/>.</param> /// <exception cref="ArgumentException">Interop types can't be embedded from modules.</exception> public MetadataReference WithEmbedInteropTypes(bool value) { return WithProperties(Properties.WithEmbedInteropTypes(value)); } /// <summary> /// Returns an instance of the reference with specified aliases. /// </summary> /// <param name="aliases">The new aliases for the reference.</param> /// <exception cref="ArgumentException">Alias is invalid for the metadata kind.</exception> public MetadataReference WithAliases(ImmutableArray<string> aliases) { return WithProperties(Properties.WithAliases(aliases)); } /// <summary> /// Returns an instance of the reference with specified properties, or this instance if properties haven't changed. /// </summary> /// <param name="properties">The new properties for the reference.</param> /// <exception cref="ArgumentException">Specified values not valid for this reference.</exception> public MetadataReference WithProperties(MetadataReferenceProperties properties) { if (properties == this.Properties) { return this; } return WithPropertiesImplReturningMetadataReference(properties); } internal abstract MetadataReference WithPropertiesImplReturningMetadataReference(MetadataReferenceProperties properties); /// <summary> /// Creates a reference to a single-module assembly or a standalone module stored in memory. /// </summary> /// <param name="peImage">Assembly image.</param> /// <param name="properties">Reference properties (extern aliases, type embedding, <see cref="MetadataImageKind"/>).</param> /// <param name="documentation">Provides XML documentation for symbol found in the reference.</param> /// <param name="filePath">Optional path that describes the location of the metadata. The file doesn't need to exist on disk. The path is opaque to the compiler.</param> /// <remarks> /// Performance considerations: /// <para> /// It is recommended to use <see cref="AssemblyMetadata.CreateFromImage(ImmutableArray{byte})"/> or <see cref="ModuleMetadata.CreateFromImage(ImmutableArray{byte})"/> /// API when creating multiple references to the same metadata. /// Reusing <see cref="Metadata"/> object to create multiple references allows for sharing data across these references. /// </para> /// <para> /// The method pins <paramref name="peImage"/> in managed heap. The pinned memory is released /// when the resulting reference becomes unreachable and GC collects it. To control the lifetime of the pinned memory /// deterministically use <see cref="AssemblyMetadata.CreateFromImage(ImmutableArray{byte})"/> /// to create an <see cref="IDisposable"/> metadata object and /// <see cref="AssemblyMetadata.GetReference(DocumentationProvider, ImmutableArray{string}, bool, string, string)"/> to get a reference to it. /// </para> /// <para> /// The method creates a reference to a single-module assembly. To create a reference to a multi-module assembly or a stand-alone module use /// <see cref="ModuleMetadata.CreateFromImage(ImmutableArray{byte})"/> and <see cref="ModuleMetadata.GetReference(DocumentationProvider, string, string)"/>. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> public static PortableExecutableReference CreateFromImage( ImmutableArray<byte> peImage, MetadataReferenceProperties properties = default, DocumentationProvider? documentation = null, string? filePath = null) { var metadata = AssemblyMetadata.CreateFromImage(peImage); return new MetadataImageReference(metadata, properties, documentation, filePath, display: null); } /// <summary> /// Creates a reference to a single-module assembly or a standalone module stored in memory. /// </summary> /// <param name="peImage">Assembly image.</param> /// <param name="properties">Reference properties (extern aliases, type embedding, <see cref="MetadataImageKind"/>).</param> /// <param name="documentation">Provides XML documentation for symbol found in the reference.</param> /// <param name="filePath">Optional path that describes the location of the metadata. The file doesn't need to exist on disk. The path is opaque to the compiler.</param> /// <remarks> /// Performance considerations: /// <para> /// It is recommended to use <see cref="AssemblyMetadata.CreateFromImage(IEnumerable{byte})"/> or <see cref="ModuleMetadata.CreateFromImage(IEnumerable{byte})"/> /// API when creating multiple references to the same metadata. /// Reusing <see cref="Metadata"/> object to create multiple references allows for sharing data across these references. /// </para> /// <para> /// The method makes a copy of the data and pins it. To avoid making a copy use an overload that takes an <see cref="ImmutableArray{T}"/>. /// The pinned memory is released when the resulting reference becomes unreachable and GC collects it. To control the lifetime of the pinned memory /// deterministically use <see cref="AssemblyMetadata.CreateFromStream(Stream, PEStreamOptions)"/> /// to create an <see cref="IDisposable"/> metadata object and /// <see cref="AssemblyMetadata.GetReference(DocumentationProvider, ImmutableArray{string}, bool, string, string)"/> to get a reference to it. /// </para> /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="peImage"/> is null.</exception> public static PortableExecutableReference CreateFromImage( IEnumerable<byte> peImage, MetadataReferenceProperties properties = default, DocumentationProvider? documentation = null, string? filePath = null) { var metadata = AssemblyMetadata.CreateFromImage(peImage); return new MetadataImageReference(metadata, properties, documentation, filePath, display: null); } /// <summary> /// Creates a reference to a single-module assembly or a stand-alone module from data in specified stream. /// Reads the content of the stream into memory and closes the stream upon return. /// </summary> /// <param name="peStream">Assembly image.</param> /// <param name="properties">Reference properties (extern aliases, type embedding, <see cref="MetadataImageKind"/>).</param> /// <param name="documentation">Provides XML documentation for symbol found in the reference.</param> /// <param name="filePath">Optional path that describes the location of the metadata. The file doesn't need to exist on disk. The path is opaque to the compiler.</param> /// <exception cref="ArgumentException"><paramref name="peStream"/> doesn't support read and seek operations.</exception> /// <exception cref="ArgumentNullException"><paramref name="peStream"/> is null.</exception> /// <exception cref="IOException">An error occurred while reading the stream.</exception> /// <remarks> /// Performance considerations: /// <para> /// It is recommended to use <see cref="AssemblyMetadata.CreateFromStream(Stream, PEStreamOptions)"/> or <see cref="ModuleMetadata.CreateFromStream(Stream, PEStreamOptions)"/> /// API when creating multiple references to the same metadata. /// Reusing <see cref="Metadata"/> object to create multiple references allows for sharing data across these references. /// </para> /// <para> /// The method eagerly reads the entire content of <paramref name="peStream"/> into native heap. The native memory block is released /// when the resulting reference becomes unreachable and GC collects it. To decrease memory footprint of the reference and/or manage /// the lifetime deterministically use <see cref="AssemblyMetadata.CreateFromStream(Stream, PEStreamOptions)"/> /// to create an <see cref="IDisposable"/> metadata object and /// <see cref="AssemblyMetadata.GetReference(DocumentationProvider, ImmutableArray{string}, bool, string, string)"/> /// to get a reference to it. /// </para> /// </remarks> public static PortableExecutableReference CreateFromStream( Stream peStream, MetadataReferenceProperties properties = default, DocumentationProvider? documentation = null, string? filePath = null) { // Prefetch data and close the stream. var metadata = AssemblyMetadata.CreateFromStream(peStream, PEStreamOptions.PrefetchEntireImage); return new MetadataImageReference(metadata, properties, documentation, filePath, display: null); } /// <summary> /// Creates a reference to an assembly or standalone module stored in a file. /// Reads the content of the file into memory. /// </summary> /// <param name="path">Path to the assembly file.</param> /// <param name="properties">Reference properties (extern aliases, type embedding, <see cref="MetadataImageKind"/>).</param> /// <param name="documentation">Provides XML documentation for symbol found in the reference.</param> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="path"/> is invalid.</exception> /// <exception cref="IOException">An error occurred while reading the file.</exception> /// <remarks> /// Performance considerations: /// <para> /// It is recommended to use <see cref="AssemblyMetadata.CreateFromFile(string)"/> or <see cref="ModuleMetadata.CreateFromFile(string)"/> /// API when creating multiple references to the same file. /// Reusing <see cref="Metadata"/> object allows for sharing data across these references. /// </para> /// <para> /// The method eagerly reads the entire content of the file into native heap. The native memory block is released /// when the resulting reference becomes unreachable and GC collects it. To decrease memory footprint of the reference and/or manage /// the lifetime deterministically use <see cref="AssemblyMetadata.CreateFromFile(string)"/> /// to create an <see cref="IDisposable"/> metadata object and /// <see cref="AssemblyMetadata.GetReference(DocumentationProvider, ImmutableArray{string}, bool, string, string)"/> /// to get a reference to it. /// </para> /// </remarks> public static PortableExecutableReference CreateFromFile( string path, MetadataReferenceProperties properties = default, DocumentationProvider? documentation = null) => CreateFromFile( StandardFileSystem.Instance.OpenFileWithNormalizedException(path, FileMode.Open, FileAccess.Read, FileShare.Read), path, properties, documentation); internal static PortableExecutableReference CreateFromFile( Stream peStream, string path, MetadataReferenceProperties properties = default, DocumentationProvider? documentation = null) { // prefetch image, close stream to avoid locking it: var module = ModuleMetadata.CreateFromStream(peStream, PEStreamOptions.PrefetchEntireImage); if (properties.Kind == MetadataImageKind.Module) { return new MetadataImageReference(module, properties, documentation, path, display: null); } // any additional modules constituting the assembly will be read lazily: var assemblyMetadata = AssemblyMetadata.CreateFromFile(module, path); return new MetadataImageReference(assemblyMetadata, properties, documentation, path, display: null); } /// <summary> /// Creates a reference to a loaded assembly. /// </summary> /// <param name="assembly">Path to the module file.</param> /// <exception cref="ArgumentNullException"><paramref name="assembly"/> is null.</exception> /// <exception cref="NotSupportedException"><paramref name="assembly"/> is dynamic, doesn't have a location, or the platform doesn't support reading from the location.</exception> /// <remarks> /// Performance considerations: /// <para> /// It is recommended to use <see cref="AssemblyMetadata.CreateFromFile(string)"/> API when creating multiple references to the same assembly. /// Reusing <see cref="AssemblyMetadata"/> object allows for sharing data across these references. /// </para> /// </remarks> [Obsolete("Use CreateFromFile(assembly.Location) instead", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public static MetadataReference CreateFromAssembly(Assembly assembly) { return CreateFromAssemblyInternal(assembly); } internal static MetadataReference CreateFromAssemblyInternal(Assembly assembly) { return CreateFromAssemblyInternal(assembly, default(MetadataReferenceProperties)); } /// <summary> /// Creates a reference to a loaded assembly. /// </summary> /// <param name="assembly">Path to the module file.</param> /// <param name="properties">Reference properties (extern aliases, type embedding).</param> /// <param name="documentation">Provides XML documentation for symbol found in the reference.</param> /// <exception cref="ArgumentNullException"><paramref name="assembly"/> is null.</exception> /// <exception cref="ArgumentException"><paramref name="properties"/>.<see cref="MetadataReferenceProperties.Kind"/> is not <see cref="MetadataImageKind.Assembly"/>.</exception> /// <exception cref="NotSupportedException"><paramref name="assembly"/> is dynamic, doesn't have a location, or the platform doesn't support reading from the location.</exception> /// <remarks> /// Performance considerations: /// <para> /// It is recommended to use <see cref="AssemblyMetadata.CreateFromFile(string)"/> API when creating multiple references to the same assembly. /// Reusing <see cref="AssemblyMetadata"/> object allows for sharing data across these references. /// </para> /// </remarks> [Obsolete("Use CreateFromFile(assembly.Location) instead", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public static MetadataReference CreateFromAssembly( Assembly assembly, MetadataReferenceProperties properties, DocumentationProvider? documentation = null) { return CreateFromAssemblyInternal(assembly, properties, documentation); } internal static PortableExecutableReference CreateFromAssemblyInternal( Assembly assembly, MetadataReferenceProperties properties, DocumentationProvider? documentation = null) { // Note: returns MetadataReference and not PortableExecutableReference so that we can in future support assemblies that // which are not backed by PE image. if (assembly == null) { throw new ArgumentNullException(nameof(assembly)); } if (assembly.IsDynamic) { throw new NotSupportedException(CodeAnalysisResources.CantCreateReferenceToDynamicAssembly); } if (properties.Kind != MetadataImageKind.Assembly) { throw new ArgumentException(CodeAnalysisResources.CantCreateModuleReferenceToAssembly, nameof(properties)); } string location = assembly.Location; if (string.IsNullOrEmpty(location)) { throw new NotSupportedException(CodeAnalysisResources.CantCreateReferenceToAssemblyWithoutLocation); } Stream peStream = StandardFileSystem.Instance.OpenFileWithNormalizedException(location, FileMode.Open, FileAccess.Read, FileShare.Read); // The file is locked by the CLR assembly loader, so we can create a lazily read metadata, // which might also lock the file until the reference is GC'd. var metadata = AssemblyMetadata.CreateFromStream(peStream); return new MetadataImageReference(metadata, properties, documentation, location, display: null); } internal static bool HasMetadata(Assembly assembly) { return !assembly.IsDynamic && !string.IsNullOrEmpty(assembly.Location); } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/CSharp/Portable/Emitter/Model/SpecializedFieldReference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Represents a reference to a field of a generic type instantiation. /// e.g. /// A{int}.Field /// A{int}.B{string}.C.Field /// </summary> internal sealed class SpecializedFieldReference : TypeMemberReference, Cci.ISpecializedFieldReference { private readonly FieldSymbol _underlyingField; public SpecializedFieldReference(FieldSymbol underlyingField) { Debug.Assert((object)underlyingField != null); _underlyingField = underlyingField; } protected override Symbol UnderlyingSymbol { get { return _underlyingField; } } public override void Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.ISpecializedFieldReference)this); } Cci.IFieldReference Cci.ISpecializedFieldReference.UnspecializedVersion { get { Debug.Assert(_underlyingField.OriginalDefinition.IsDefinition); return _underlyingField.OriginalDefinition.GetCciAdapter(); } } Cci.ISpecializedFieldReference Cci.IFieldReference.AsSpecializedFieldReference { get { return this; } } Cci.ITypeReference Cci.IFieldReference.GetType(EmitContext context) { TypeWithAnnotations oldType = _underlyingField.TypeWithAnnotations; var customModifiers = oldType.CustomModifiers; var type = ((PEModuleBuilder)context.Module).Translate(oldType.Type, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics); if (customModifiers.Length == 0) { return type; } else { return new Cci.ModifiedTypeReference(type, ImmutableArray<Cci.ICustomModifier>.CastUp(customModifiers)); } } Cci.IFieldDefinition Cci.IFieldReference.GetResolvedField(EmitContext context) { return null; } bool Cci.IFieldReference.IsContextualNamedEntity { get { return false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.Emit; namespace Microsoft.CodeAnalysis.CSharp.Emit { /// <summary> /// Represents a reference to a field of a generic type instantiation. /// e.g. /// A{int}.Field /// A{int}.B{string}.C.Field /// </summary> internal sealed class SpecializedFieldReference : TypeMemberReference, Cci.ISpecializedFieldReference { private readonly FieldSymbol _underlyingField; public SpecializedFieldReference(FieldSymbol underlyingField) { Debug.Assert((object)underlyingField != null); _underlyingField = underlyingField; } protected override Symbol UnderlyingSymbol { get { return _underlyingField; } } public override void Dispatch(Cci.MetadataVisitor visitor) { visitor.Visit((Cci.ISpecializedFieldReference)this); } Cci.IFieldReference Cci.ISpecializedFieldReference.UnspecializedVersion { get { Debug.Assert(_underlyingField.OriginalDefinition.IsDefinition); return _underlyingField.OriginalDefinition.GetCciAdapter(); } } Cci.ISpecializedFieldReference Cci.IFieldReference.AsSpecializedFieldReference { get { return this; } } Cci.ITypeReference Cci.IFieldReference.GetType(EmitContext context) { TypeWithAnnotations oldType = _underlyingField.TypeWithAnnotations; var customModifiers = oldType.CustomModifiers; var type = ((PEModuleBuilder)context.Module).Translate(oldType.Type, syntaxNodeOpt: (CSharpSyntaxNode)context.SyntaxNode, diagnostics: context.Diagnostics); if (customModifiers.Length == 0) { return type; } else { return new Cci.ModifiedTypeReference(type, ImmutableArray<Cci.ICustomModifier>.CastUp(customModifiers)); } } Cci.IFieldDefinition Cci.IFieldReference.GetResolvedField(EmitContext context) { return null; } bool Cci.IFieldReference.IsContextualNamedEntity { get { return false; } } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Tools/BuildBoss/SolutionCheckerUtil.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace BuildBoss { internal sealed class SolutionCheckerUtil : ICheckerUtil { private struct SolutionProjectData { internal ProjectEntry ProjectEntry; internal ProjectData ProjectData; internal SolutionProjectData(ProjectEntry entry, ProjectData data) { ProjectEntry = entry; ProjectData = data; } } internal string SolutionFilePath { get; } internal string SolutionPath { get; } internal bool IsPrimarySolution { get; } internal SolutionCheckerUtil(string solutionFilePath, bool isPrimarySolution) { SolutionFilePath = solutionFilePath; IsPrimarySolution = isPrimarySolution; SolutionPath = Path.GetDirectoryName(SolutionFilePath); } public bool Check(TextWriter textWriter) { var allGood = true; allGood &= CheckDuplicate(textWriter, out var map); allGood &= CheckProjects(textWriter, map); allGood &= CheckProjectSystemGuid(textWriter, map.Values); return allGood; } private bool CheckProjects(TextWriter textWriter, Dictionary<ProjectKey, SolutionProjectData> map) { var solutionMap = new Dictionary<ProjectKey, ProjectData>(); foreach (var pair in map) { solutionMap.Add(pair.Key, pair.Value.ProjectData); } var allGood = true; var count = 0; foreach (var data in map.Values.OrderBy(x => x.ProjectEntry.Name)) { var projectWriter = new StringWriter(); var projectData = data.ProjectData; projectWriter.WriteLine($"Processing {projectData.Key.FileName}"); var util = new ProjectCheckerUtil(projectData, solutionMap, IsPrimarySolution); if (!util.Check(projectWriter)) { allGood = false; textWriter.WriteLine(projectWriter.ToString()); } count++; } textWriter.WriteLine($"Processed {count} projects"); return allGood; } private bool CheckDuplicate(TextWriter textWriter, out Dictionary<ProjectKey, SolutionProjectData> map) { map = new Dictionary<ProjectKey, SolutionProjectData>(); var allGood = true; foreach (var projectEntry in SolutionUtil.ParseProjects(SolutionFilePath)) { if (projectEntry.IsFolder) { continue; } var projectFilePath = Path.Combine(SolutionPath, projectEntry.RelativeFilePath); var projectData = new ProjectData(projectFilePath); if (map.ContainsKey(projectData.Key)) { textWriter.WriteLine($"Duplicate project detected {projectData.FileName}"); allGood = false; } else { map.Add(projectData.Key, new SolutionProjectData(projectEntry, projectData)); } } return allGood; } /// <summary> /// Ensure solution files have the proper project system GUID. /// </summary> private bool CheckProjectSystemGuid(TextWriter textWriter, IEnumerable<SolutionProjectData> dataList) { Guid getExpectedGuid(ProjectData data) { var util = data.ProjectUtil; switch (ProjectEntryUtil.GetProjectFileType(data.FilePath)) { case ProjectFileType.CSharp: return ProjectEntryUtil.ManagedProjectSystemCSharp; case ProjectFileType.Basic: return ProjectEntryUtil.ManagedProjectSystemVisualBasic; case ProjectFileType.Shared: return ProjectEntryUtil.SharedProject; default: throw new Exception($"Invalid file path {data.FilePath}"); } } var allGood = true; foreach (var data in dataList.Where(x => x.ProjectEntry.ProjectType != ProjectFileType.Tool)) { var guid = getExpectedGuid(data.ProjectData); if (guid != data.ProjectEntry.TypeGuid) { var name = data.ProjectData.FileName; textWriter.WriteLine($"Project {name} should have GUID {guid} but has {data.ProjectEntry.TypeGuid}"); allGood = false; } } return allGood; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace BuildBoss { internal sealed class SolutionCheckerUtil : ICheckerUtil { private struct SolutionProjectData { internal ProjectEntry ProjectEntry; internal ProjectData ProjectData; internal SolutionProjectData(ProjectEntry entry, ProjectData data) { ProjectEntry = entry; ProjectData = data; } } internal string SolutionFilePath { get; } internal string SolutionPath { get; } internal bool IsPrimarySolution { get; } internal SolutionCheckerUtil(string solutionFilePath, bool isPrimarySolution) { SolutionFilePath = solutionFilePath; IsPrimarySolution = isPrimarySolution; SolutionPath = Path.GetDirectoryName(SolutionFilePath); } public bool Check(TextWriter textWriter) { var allGood = true; allGood &= CheckDuplicate(textWriter, out var map); allGood &= CheckProjects(textWriter, map); allGood &= CheckProjectSystemGuid(textWriter, map.Values); return allGood; } private bool CheckProjects(TextWriter textWriter, Dictionary<ProjectKey, SolutionProjectData> map) { var solutionMap = new Dictionary<ProjectKey, ProjectData>(); foreach (var pair in map) { solutionMap.Add(pair.Key, pair.Value.ProjectData); } var allGood = true; var count = 0; foreach (var data in map.Values.OrderBy(x => x.ProjectEntry.Name)) { var projectWriter = new StringWriter(); var projectData = data.ProjectData; projectWriter.WriteLine($"Processing {projectData.Key.FileName}"); var util = new ProjectCheckerUtil(projectData, solutionMap, IsPrimarySolution); if (!util.Check(projectWriter)) { allGood = false; textWriter.WriteLine(projectWriter.ToString()); } count++; } textWriter.WriteLine($"Processed {count} projects"); return allGood; } private bool CheckDuplicate(TextWriter textWriter, out Dictionary<ProjectKey, SolutionProjectData> map) { map = new Dictionary<ProjectKey, SolutionProjectData>(); var allGood = true; foreach (var projectEntry in SolutionUtil.ParseProjects(SolutionFilePath)) { if (projectEntry.IsFolder) { continue; } var projectFilePath = Path.Combine(SolutionPath, projectEntry.RelativeFilePath); var projectData = new ProjectData(projectFilePath); if (map.ContainsKey(projectData.Key)) { textWriter.WriteLine($"Duplicate project detected {projectData.FileName}"); allGood = false; } else { map.Add(projectData.Key, new SolutionProjectData(projectEntry, projectData)); } } return allGood; } /// <summary> /// Ensure solution files have the proper project system GUID. /// </summary> private bool CheckProjectSystemGuid(TextWriter textWriter, IEnumerable<SolutionProjectData> dataList) { Guid getExpectedGuid(ProjectData data) { var util = data.ProjectUtil; switch (ProjectEntryUtil.GetProjectFileType(data.FilePath)) { case ProjectFileType.CSharp: return ProjectEntryUtil.ManagedProjectSystemCSharp; case ProjectFileType.Basic: return ProjectEntryUtil.ManagedProjectSystemVisualBasic; case ProjectFileType.Shared: return ProjectEntryUtil.SharedProject; default: throw new Exception($"Invalid file path {data.FilePath}"); } } var allGood = true; foreach (var data in dataList.Where(x => x.ProjectEntry.ProjectType != ProjectFileType.Tool)) { var guid = getExpectedGuid(data.ProjectData); if (guid != data.ProjectEntry.TypeGuid) { var name = data.ProjectData.FileName; textWriter.WriteLine($"Project {name} should have GUID {guid} but has {data.ProjectEntry.TypeGuid}"); allGood = false; } } return allGood; } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/Core/Portable/InternalUtilities/StringTable.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; #if DEBUG using System.Diagnostics; #endif namespace Roslyn.Utilities { /// <summary> /// This is basically a lossy cache of strings that is searchable by /// strings, string sub ranges, character array ranges or string-builder. /// </summary> internal class StringTable { // entry in the caches private struct Entry { // hash code of the entry public int HashCode; // full text of the item public string Text; } // TODO: Need to tweak the size with more scenarios. // for now this is what works well enough with // Roslyn C# compiler project // Size of local cache. private const int LocalSizeBits = 11; private const int LocalSize = (1 << LocalSizeBits); private const int LocalSizeMask = LocalSize - 1; // max size of shared cache. private const int SharedSizeBits = 16; private const int SharedSize = (1 << SharedSizeBits); private const int SharedSizeMask = SharedSize - 1; // size of bucket in shared cache. (local cache has bucket size 1). private const int SharedBucketBits = 4; private const int SharedBucketSize = (1 << SharedBucketBits); private const int SharedBucketSizeMask = SharedBucketSize - 1; // local (L1) cache // simple fast and not threadsafe cache // with limited size and "last add wins" expiration policy // // The main purpose of the local cache is to use in long lived // single threaded operations with lots of locality (like parsing). // Local cache is smaller (and thus faster) and is not affected // by cache misses on other threads. private readonly Entry[] _localTable = new Entry[LocalSize]; // shared (L2) threadsafe cache // slightly slower than local cache // we read this cache when having a miss in local cache // writes to local cache will update shared cache as well. private static readonly Entry[] s_sharedTable = new Entry[SharedSize]; // essentially a random number // the usage pattern will randomly use and increment this // the counter is not static to avoid interlocked operations and cross-thread traffic private int _localRandom = Environment.TickCount; // same as above but for users that go directly with unbuffered shared cache. private static int s_sharedRandom = Environment.TickCount; internal StringTable() : this(null) { } // implement Poolable object pattern #region "Poolable" private StringTable(ObjectPool<StringTable>? pool) { _pool = pool; } private readonly ObjectPool<StringTable>? _pool; private static readonly ObjectPool<StringTable> s_staticPool = CreatePool(); private static ObjectPool<StringTable> CreatePool() { var pool = new ObjectPool<StringTable>(pool => new StringTable(pool), Environment.ProcessorCount * 2); return pool; } public static StringTable GetInstance() { return s_staticPool.Allocate(); } public void Free() { // leave cache content in the cache, just return it to the pool // Array.Clear(this.localTable, 0, this.localTable.Length); // Array.Clear(sharedTable, 0, sharedTable.Length); _pool?.Free(this); } #endregion // Poolable internal string Add(char[] chars, int start, int len) { var span = chars.AsSpan(start, len); var hashCode = Hash.GetFNVHashCode(chars, start, len); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (StringTable.TextEquals(result, span)) { return result; } } string? shared = FindSharedEntry(chars, start, len, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, start, len, hashCode); } internal string Add(string chars, int start, int len) { var hashCode = Hash.GetFNVHashCode(chars, start, len); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (StringTable.TextEquals(result, chars, start, len)) { return result; } } string? shared = FindSharedEntry(chars, start, len, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, start, len, hashCode); } internal string Add(char chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null) { var result = arr[idx].Text; if (text.Length == 1 && text[0] == chars) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, hashCode); } internal string Add(StringBuilder chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (StringTable.TextEquals(result, chars)) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, hashCode); } internal string Add(string chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (result == chars) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } AddCore(chars, hashCode); return chars; } private static string? FindSharedEntry(char[] chars, int start, int len, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars.AsSpan(start, len))) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(string chars, int start, int len, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars, start, len)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntryASCII(int hashCode, ReadOnlySpan<byte> asciiChars) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEqualsASCII(e, asciiChars)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(char chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; if (e != null) { if (e.Length == 1 && e[0] == chars) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(StringBuilder chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(string chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && e == chars) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private string AddItem(char[] chars, int start, int len, int hashCode) { var text = new String(chars, start, len); AddCore(text, hashCode); return text; } private string AddItem(string chars, int start, int len, int hashCode) { var text = chars.Substring(start, len); AddCore(text, hashCode); return text; } private string AddItem(char chars, int hashCode) { var text = new String(chars, 1); AddCore(text, hashCode); return text; } private string AddItem(StringBuilder chars, int hashCode) { var text = chars.ToString(); AddCore(text, hashCode); return text; } private void AddCore(string chars, int hashCode) { // add to the shared table first (in case someone looks for same item) AddSharedEntry(hashCode, chars); // add to the local table too var arr = _localTable; var idx = LocalIdxFromHash(hashCode); arr[idx].HashCode = hashCode; arr[idx].Text = chars; } private void AddSharedEntry(int hashCode, string text) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Text == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = LocalNextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Text, text); } internal static string AddShared(StringBuilder chars) { var hashCode = Hash.GetFNVHashCode(chars); string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { return shared; } return AddSharedSlow(hashCode, chars); } private static string AddSharedSlow(int hashCode, StringBuilder builder) { string text = builder.ToString(); AddSharedSlow(hashCode, text); return text; } internal static string AddSharedUTF8(ReadOnlySpan<byte> bytes) { int hashCode = Hash.GetFNVHashCode(bytes, out bool isAscii); if (isAscii) { string? shared = FindSharedEntryASCII(hashCode, bytes); if (shared != null) { return shared; } } return AddSharedSlow(hashCode, bytes, isAscii); } private static string AddSharedSlow(int hashCode, ReadOnlySpan<byte> utf8Bytes, bool isAscii) { string text; unsafe { fixed (byte* bytes = &utf8Bytes.GetPinnableReference()) { text = Encoding.UTF8.GetString(bytes, utf8Bytes.Length); } } // Don't add non-ascii strings to table. The hashCode we have here is not correct and we won't find them again. // Non-ascii in UTF8-encoded parts of metadata (the only use of this at the moment) is assumed to be rare in // practice. If that turns out to be wrong, we could decode to pooled memory and rehash here. if (isAscii) { AddSharedSlow(hashCode, text); } return text; } private static void AddSharedSlow(int hashCode, string text) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Text == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = SharedNextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Text, text); } private static int LocalIdxFromHash(int hash) { return hash & LocalSizeMask; } private static int SharedIdxFromHash(int hash) { // we can afford to mix some more hash bits here return (hash ^ (hash >> LocalSizeBits)) & SharedSizeMask; } private int LocalNextRandom() { return _localRandom++; } private static int SharedNextRandom() { return Interlocked.Increment(ref StringTable.s_sharedRandom); } internal static bool TextEquals(string array, string text, int start, int length) { if (array.Length != length) { return false; } // use array.Length to eliminate the range check for (var i = 0; i < array.Length; i++) { if (array[i] != text[start + i]) { return false; } } return true; } internal static bool TextEquals(string array, StringBuilder text) { if (array.Length != text.Length) { return false; } // interestingly, stringbuilder holds the list of chunks by the tail // so accessing positions at the beginning may cost more than those at the end. for (var i = array.Length - 1; i >= 0; i--) { if (array[i] != text[i]) { return false; } } return true; } internal static bool TextEqualsASCII(string text, ReadOnlySpan<byte> ascii) { #if DEBUG for (var i = 0; i < ascii.Length; i++) { Debug.Assert((ascii[i] & 0x80) == 0, $"The {nameof(ascii)} input to this method must be valid ASCII."); } #endif if (ascii.Length != text.Length) { return false; } for (var i = 0; i < ascii.Length; i++) { if (ascii[i] != text[i]) { return false; } } return true; } internal static bool TextEquals(string array, ReadOnlySpan<char> text) => text.Equals(array.AsSpan(), StringComparison.Ordinal); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis; #if DEBUG using System.Diagnostics; #endif namespace Roslyn.Utilities { /// <summary> /// This is basically a lossy cache of strings that is searchable by /// strings, string sub ranges, character array ranges or string-builder. /// </summary> internal class StringTable { // entry in the caches private struct Entry { // hash code of the entry public int HashCode; // full text of the item public string Text; } // TODO: Need to tweak the size with more scenarios. // for now this is what works well enough with // Roslyn C# compiler project // Size of local cache. private const int LocalSizeBits = 11; private const int LocalSize = (1 << LocalSizeBits); private const int LocalSizeMask = LocalSize - 1; // max size of shared cache. private const int SharedSizeBits = 16; private const int SharedSize = (1 << SharedSizeBits); private const int SharedSizeMask = SharedSize - 1; // size of bucket in shared cache. (local cache has bucket size 1). private const int SharedBucketBits = 4; private const int SharedBucketSize = (1 << SharedBucketBits); private const int SharedBucketSizeMask = SharedBucketSize - 1; // local (L1) cache // simple fast and not threadsafe cache // with limited size and "last add wins" expiration policy // // The main purpose of the local cache is to use in long lived // single threaded operations with lots of locality (like parsing). // Local cache is smaller (and thus faster) and is not affected // by cache misses on other threads. private readonly Entry[] _localTable = new Entry[LocalSize]; // shared (L2) threadsafe cache // slightly slower than local cache // we read this cache when having a miss in local cache // writes to local cache will update shared cache as well. private static readonly Entry[] s_sharedTable = new Entry[SharedSize]; // essentially a random number // the usage pattern will randomly use and increment this // the counter is not static to avoid interlocked operations and cross-thread traffic private int _localRandom = Environment.TickCount; // same as above but for users that go directly with unbuffered shared cache. private static int s_sharedRandom = Environment.TickCount; internal StringTable() : this(null) { } // implement Poolable object pattern #region "Poolable" private StringTable(ObjectPool<StringTable>? pool) { _pool = pool; } private readonly ObjectPool<StringTable>? _pool; private static readonly ObjectPool<StringTable> s_staticPool = CreatePool(); private static ObjectPool<StringTable> CreatePool() { var pool = new ObjectPool<StringTable>(pool => new StringTable(pool), Environment.ProcessorCount * 2); return pool; } public static StringTable GetInstance() { return s_staticPool.Allocate(); } public void Free() { // leave cache content in the cache, just return it to the pool // Array.Clear(this.localTable, 0, this.localTable.Length); // Array.Clear(sharedTable, 0, sharedTable.Length); _pool?.Free(this); } #endregion // Poolable internal string Add(char[] chars, int start, int len) { var span = chars.AsSpan(start, len); var hashCode = Hash.GetFNVHashCode(chars, start, len); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (StringTable.TextEquals(result, span)) { return result; } } string? shared = FindSharedEntry(chars, start, len, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, start, len, hashCode); } internal string Add(string chars, int start, int len) { var hashCode = Hash.GetFNVHashCode(chars, start, len); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (StringTable.TextEquals(result, chars, start, len)) { return result; } } string? shared = FindSharedEntry(chars, start, len, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, start, len, hashCode); } internal string Add(char chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null) { var result = arr[idx].Text; if (text.Length == 1 && text[0] == chars) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, hashCode); } internal string Add(StringBuilder chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (StringTable.TextEquals(result, chars)) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } return AddItem(chars, hashCode); } internal string Add(string chars) { var hashCode = Hash.GetFNVHashCode(chars); // capture array to avoid extra range checks var arr = _localTable; var idx = LocalIdxFromHash(hashCode); var text = arr[idx].Text; if (text != null && arr[idx].HashCode == hashCode) { var result = arr[idx].Text; if (result == chars) { return result; } } string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { // PERF: the following code does element-wise assignment of a struct // because current JIT produces better code compared to // arr[idx] = new Entry(...) arr[idx].HashCode = hashCode; arr[idx].Text = shared; return shared; } AddCore(chars, hashCode); return chars; } private static string? FindSharedEntry(char[] chars, int start, int len, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars.AsSpan(start, len))) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(string chars, int start, int len, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars, start, len)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntryASCII(int hashCode, ReadOnlySpan<byte> asciiChars) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEqualsASCII(e, asciiChars)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(char chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; if (e != null) { if (e.Length == 1 && e[0] == chars) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(StringBuilder chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && TextEquals(e, chars)) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private static string? FindSharedEntry(string chars, int hashCode) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); string? e = null; // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode for (int i = 1; i < SharedBucketSize + 1; i++) { e = arr[idx].Text; int hash = arr[idx].HashCode; if (e != null) { if (hash == hashCode && e == chars) { break; } // this is not e we are looking for e = null; } else { // once we see unfilled entry, the rest of the bucket will be empty break; } idx = (idx + i) & SharedSizeMask; } return e; } private string AddItem(char[] chars, int start, int len, int hashCode) { var text = new String(chars, start, len); AddCore(text, hashCode); return text; } private string AddItem(string chars, int start, int len, int hashCode) { var text = chars.Substring(start, len); AddCore(text, hashCode); return text; } private string AddItem(char chars, int hashCode) { var text = new String(chars, 1); AddCore(text, hashCode); return text; } private string AddItem(StringBuilder chars, int hashCode) { var text = chars.ToString(); AddCore(text, hashCode); return text; } private void AddCore(string chars, int hashCode) { // add to the shared table first (in case someone looks for same item) AddSharedEntry(hashCode, chars); // add to the local table too var arr = _localTable; var idx = LocalIdxFromHash(hashCode); arr[idx].HashCode = hashCode; arr[idx].Text = chars; } private void AddSharedEntry(int hashCode, string text) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Text == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = LocalNextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Text, text); } internal static string AddShared(StringBuilder chars) { var hashCode = Hash.GetFNVHashCode(chars); string? shared = FindSharedEntry(chars, hashCode); if (shared != null) { return shared; } return AddSharedSlow(hashCode, chars); } private static string AddSharedSlow(int hashCode, StringBuilder builder) { string text = builder.ToString(); AddSharedSlow(hashCode, text); return text; } internal static string AddSharedUTF8(ReadOnlySpan<byte> bytes) { int hashCode = Hash.GetFNVHashCode(bytes, out bool isAscii); if (isAscii) { string? shared = FindSharedEntryASCII(hashCode, bytes); if (shared != null) { return shared; } } return AddSharedSlow(hashCode, bytes, isAscii); } private static string AddSharedSlow(int hashCode, ReadOnlySpan<byte> utf8Bytes, bool isAscii) { string text; unsafe { fixed (byte* bytes = &utf8Bytes.GetPinnableReference()) { text = Encoding.UTF8.GetString(bytes, utf8Bytes.Length); } } // Don't add non-ascii strings to table. The hashCode we have here is not correct and we won't find them again. // Non-ascii in UTF8-encoded parts of metadata (the only use of this at the moment) is assumed to be rare in // practice. If that turns out to be wrong, we could decode to pooled memory and rehash here. if (isAscii) { AddSharedSlow(hashCode, text); } return text; } private static void AddSharedSlow(int hashCode, string text) { var arr = s_sharedTable; int idx = SharedIdxFromHash(hashCode); // try finding an empty spot in the bucket // we use quadratic probing here // bucket positions are (n^2 + n)/2 relative to the masked hashcode int curIdx = idx; for (int i = 1; i < SharedBucketSize + 1; i++) { if (arr[curIdx].Text == null) { idx = curIdx; goto foundIdx; } curIdx = (curIdx + i) & SharedSizeMask; } // or pick a random victim within the bucket range // and replace with new entry var i1 = SharedNextRandom() & SharedBucketSizeMask; idx = (idx + ((i1 * i1 + i1) / 2)) & SharedSizeMask; foundIdx: arr[idx].HashCode = hashCode; Volatile.Write(ref arr[idx].Text, text); } private static int LocalIdxFromHash(int hash) { return hash & LocalSizeMask; } private static int SharedIdxFromHash(int hash) { // we can afford to mix some more hash bits here return (hash ^ (hash >> LocalSizeBits)) & SharedSizeMask; } private int LocalNextRandom() { return _localRandom++; } private static int SharedNextRandom() { return Interlocked.Increment(ref StringTable.s_sharedRandom); } internal static bool TextEquals(string array, string text, int start, int length) { if (array.Length != length) { return false; } // use array.Length to eliminate the range check for (var i = 0; i < array.Length; i++) { if (array[i] != text[start + i]) { return false; } } return true; } internal static bool TextEquals(string array, StringBuilder text) { if (array.Length != text.Length) { return false; } // interestingly, stringbuilder holds the list of chunks by the tail // so accessing positions at the beginning may cost more than those at the end. for (var i = array.Length - 1; i >= 0; i--) { if (array[i] != text[i]) { return false; } } return true; } internal static bool TextEqualsASCII(string text, ReadOnlySpan<byte> ascii) { #if DEBUG for (var i = 0; i < ascii.Length; i++) { Debug.Assert((ascii[i] & 0x80) == 0, $"The {nameof(ascii)} input to this method must be valid ASCII."); } #endif if (ascii.Length != text.Length) { return false; } for (var i = 0; i < ascii.Length; i++) { if (ascii[i] != text[i]) { return false; } } return true; } internal static bool TextEquals(string array, ReadOnlySpan<char> text) => text.Equals(array.AsSpan(), StringComparison.Ordinal); } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/CSharp/Portable/Symbols/Synthesized/InterpolatedStringBuilderLocalSymbol.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.CompilerServices; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A synthesized local variable with a val escape scope. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal sealed class SynthesizedLocalWithValEscape : SynthesizedLocal { public SynthesizedLocalWithValEscape( MethodSymbol? containingMethod, TypeWithAnnotations typeWithAnnotations, SynthesizedLocalKind kind, uint valEscapeScope, SyntaxNode? syntaxOpt = null, bool isPinned = false, RefKind refKind = RefKind.None #if DEBUG , [CallerLineNumber] int createdAtLineNumber = 0, [CallerFilePath] string? createdAtFilePath = null #endif ) : base(containingMethod, typeWithAnnotations, kind, syntaxOpt, isPinned, refKind #if DEBUG , createdAtLineNumber, createdAtFilePath #endif ) { ValEscapeScope = valEscapeScope; } internal override uint ValEscapeScope { 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.Runtime.CompilerServices; using System.Diagnostics; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// A synthesized local variable with a val escape scope. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(),nq}")] internal sealed class SynthesizedLocalWithValEscape : SynthesizedLocal { public SynthesizedLocalWithValEscape( MethodSymbol? containingMethod, TypeWithAnnotations typeWithAnnotations, SynthesizedLocalKind kind, uint valEscapeScope, SyntaxNode? syntaxOpt = null, bool isPinned = false, RefKind refKind = RefKind.None #if DEBUG , [CallerLineNumber] int createdAtLineNumber = 0, [CallerFilePath] string? createdAtFilePath = null #endif ) : base(containingMethod, typeWithAnnotations, kind, syntaxOpt, isPinned, refKind #if DEBUG , createdAtLineNumber, createdAtFilePath #endif ) { ValEscapeScope = valEscapeScope; } internal override uint ValEscapeScope { get; } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Features/Core/Portable/FindUsages/DefinitionItem.DetachedDefinitionItem.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.FindUsages { internal partial class DefinitionItem { internal readonly struct DetachedDefinitionItem { public readonly ImmutableArray<string> Tags; public readonly ImmutableDictionary<string, string> Properties; public readonly ImmutableDictionary<string, string> DisplayableProperties; public readonly ImmutableArray<TaggedText> NameDisplayParts; public readonly ImmutableArray<TaggedText> DisplayParts; public readonly ImmutableArray<TaggedText> OriginationParts; public readonly bool DisplayIfNoReferences; public readonly ImmutableArray<DocumentIdSpan> SourceSpans; public DetachedDefinitionItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, ImmutableDictionary<string, string> displayableProperties, bool displayIfNoReferences) { Tags = tags; DisplayParts = displayParts; NameDisplayParts = nameDisplayParts; OriginationParts = originationParts; Properties = properties; DisplayableProperties = displayableProperties; DisplayIfNoReferences = displayIfNoReferences; SourceSpans = sourceSpans.SelectAsArray(ss => new DocumentIdSpan(ss)); } public async Task<DefaultDefinitionItem?> TryRehydrateAsync(CancellationToken cancellationToken) { using var converted = TemporaryArray<DocumentSpan>.Empty; foreach (var ss in SourceSpans) { var documentSpan = await ss.TryRehydrateAsync(cancellationToken).ConfigureAwait(false); if (documentSpan == null) return null; converted.Add(documentSpan.Value); } return new DefaultDefinitionItem( Tags, DisplayParts, NameDisplayParts, OriginationParts, converted.ToImmutableAndClear(), Properties, DisplayableProperties, DisplayIfNoReferences); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Shared.Collections; namespace Microsoft.CodeAnalysis.FindUsages { internal partial class DefinitionItem { internal readonly struct DetachedDefinitionItem { public readonly ImmutableArray<string> Tags; public readonly ImmutableDictionary<string, string> Properties; public readonly ImmutableDictionary<string, string> DisplayableProperties; public readonly ImmutableArray<TaggedText> NameDisplayParts; public readonly ImmutableArray<TaggedText> DisplayParts; public readonly ImmutableArray<TaggedText> OriginationParts; public readonly bool DisplayIfNoReferences; public readonly ImmutableArray<DocumentIdSpan> SourceSpans; public DetachedDefinitionItem( ImmutableArray<string> tags, ImmutableArray<TaggedText> displayParts, ImmutableArray<TaggedText> nameDisplayParts, ImmutableArray<TaggedText> originationParts, ImmutableArray<DocumentSpan> sourceSpans, ImmutableDictionary<string, string> properties, ImmutableDictionary<string, string> displayableProperties, bool displayIfNoReferences) { Tags = tags; DisplayParts = displayParts; NameDisplayParts = nameDisplayParts; OriginationParts = originationParts; Properties = properties; DisplayableProperties = displayableProperties; DisplayIfNoReferences = displayIfNoReferences; SourceSpans = sourceSpans.SelectAsArray(ss => new DocumentIdSpan(ss)); } public async Task<DefaultDefinitionItem?> TryRehydrateAsync(CancellationToken cancellationToken) { using var converted = TemporaryArray<DocumentSpan>.Empty; foreach (var ss in SourceSpans) { var documentSpan = await ss.TryRehydrateAsync(cancellationToken).ConfigureAwait(false); if (documentSpan == null) return null; converted.Add(documentSpan.Value); } return new DefaultDefinitionItem( Tags, DisplayParts, NameDisplayParts, OriginationParts, converted.ToImmutableAndClear(), Properties, DisplayableProperties, DisplayIfNoReferences); } } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/EditorFeatures/CSharpTest/Semantics/SpeculationAnalyzerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Semantics; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Semantics { public class SpeculationAnalyzerTests : SpeculationAnalyzerTestsBase { [Fact] public void SpeculationAnalyzerDifferentOverloads() { Test(@" class Program { void Vain(int arg = 3) { } void Vain(string arg) { } void Main() { [|Vain(5)|]; } } ", "Vain(string.Empty)", true); } [Fact, WorkItem(672396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672396")] public void SpeculationAnalyzerExtensionMethodExplicitInvocation() { Test(@" static class Program { public static void Vain(this int arg) { } static void Main() { [|5.Vain()|]; } } ", "Vain(5)", false); } [Fact] public void SpeculationAnalyzerImplicitBaseClassConversion() { Test(@" using System; class Program { void Main() { Exception ex = [|(Exception)new InvalidOperationException()|]; } } ", "new InvalidOperationException()", false); } [Fact] public void SpeculationAnalyzerImplicitNumericConversion() { Test(@" class Program { void Main() { long i = [|(long)5|]; } } ", "5", false); } [Fact] public void SpeculationAnalyzerImplicitUserConversion() { Test(@" class From { public static implicit operator To(From from) { return new To(); } } class To { } class Program { void Main() { To to = [|(To)new From()|]; } } ", "new From()", true); } [Fact] public void SpeculationAnalyzerExplicitConversion() { Test(@" using System; class Program { void Main() { Exception ex1 = new InvalidOperationException(); var ex2 = [|(InvalidOperationException)ex1|]; } } ", "ex1", true); } [Fact] public void SpeculationAnalyzerArrayImplementingNonGenericInterface() { Test(@" using System.Collections; class Program { void Main() { var a = new[] { 1, 2, 3 }; [|((IEnumerable)a).GetEnumerator()|]; } } ", "a.GetEnumerator()", false); } [Fact] public void SpeculationAnalyzerVirtualMethodWithBaseConversion() { Test(@" using System; using System.IO; class Program { void Main() { var s = new MemoryStream(); [|((Stream)s).Flush()|]; } } ", "s.Flush()", false); } [Fact] public void SpeculationAnalyzerNonVirtualMethodImplementingInterface() { Test(@" using System; class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); var d = new Class(); [|((IComparable)c).CompareTo(d)|]; } } ", "c.CompareTo(d)", true); } [Fact] public void SpeculationAnalyzerSealedClassImplementingInterface() { Test(@" using System; sealed class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); var d = new Class(); [|((IComparable)c).CompareTo(d)|]; } } ", "((IComparable)c).CompareTo(d)", semanticChanges: false); } [Fact] public void SpeculationAnalyzerValueTypeImplementingInterface() { Test(@" using System; class Program { void Main() { decimal d = 5; [|((IComparable<decimal>)d).CompareTo(6)|]; } } ", "d.CompareTo(6)", false); } [Fact] public void SpeculationAnalyzerBinaryExpressionIntVsLong() { Test(@" class Program { void Main() { var r = [|1+1L|]; } } ", "1+1", true); } [Fact] public void SpeculationAnalyzerQueryExpressionSelectType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) select (long)i|]; } } ", "from i in Enumerable.Range(0, 3) select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionFromType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in new long[0] select i|]; } } ", "from i in new int[0] select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionGroupByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) group (long)i by i|]; } } ", "from i in Enumerable.Range(0, 3) group i by i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionOrderByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = from i in Enumerable.Range(0, 3) orderby [|(long)i|] select i; } } ", "i", true); } [Fact] public void SpeculationAnalyzerDifferentAttributeConstructors() { Test(@" using System; class AnAttribute : Attribute { public AnAttribute(string a, long b) { } public AnAttribute(int a, int b) { } } class Program { [An([|""5""|], 6)] static void Main() { } } ", "5", false, "6"); // Note: the answer should have been that the replacement does change semantics (true), // however to have enough context one must analyze AttributeSyntax instead of separate ExpressionSyntaxes it contains, // which is not supported in SpeculationAnalyzer, but possible with GetSpeculativeSemanticModel API } [Fact] public void SpeculationAnalyzerCollectionInitializers() { Test(@" using System.Collections; class Collection : IEnumerable { public IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } public void Add(string s) { } public void Add(int i) { } void Main() { var c = new Collection { [|""5""|] }; } } ", "5", true); } [Fact, WorkItem(1088815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088815")] public void SpeculationAnalyzerBrokenCode() { Test(@" public interface IRogueAction { public string Name { get; private set; } protected IRogueAction(string name) { [|this.Name|] = name; } } ", "Name", semanticChanges: false, isBrokenCode: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithNeededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(int)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithUnneededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(Directions)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: false); } [Fact, WorkItem(19987, "https://github.com/dotnet/roslyn/issues/19987")] public void SpeculationAnalyzerSwitchCaseWithRedundantCast() { Test(@" class Program { static void Main(string[] arts) { var x = 1f; switch (x) { case [|(float) 1|]: System.Console.WriteLine(""one""); break; default: System.Console.WriteLine(""not one""); break; } } } ", "1", semanticChanges: false); } [Fact, WorkItem(19987, "https://github.com/dotnet/roslyn/issues/19987")] public void SpeculationAnalyzerSwitchCaseWithRequiredCast() { Test(@" class Program { static void Main(string[] arts) { object x = 1f; switch (x) { case [|(float) 1|]: // without the case, object x does not match int 1 System.Console.WriteLine(""one""); break; default: System.Console.WriteLine(""not one""); break; } } } ", "1", semanticChanges: true); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerIndexerPropertyWithRedundantCast() { Test(code: @" class Indexer { public int this[int x] { get { return x; } } } class A { public Indexer Foo { get; } = new Indexer(); } class B : A { } class Program { static void Main(string[] args) { var b = new B(); var y = ([|(A)b|]).Foo[1]; } } ", replacementExpression: "b", semanticChanges: false); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerIndexerPropertyWithRequiredCast() { Test(code: @" class Indexer { public int this[int x] { get { return x; } } } class A { public Indexer Foo { get; } = new Indexer(); } class B : A { public new Indexer Foo { get; } = new Indexer(); } class Program { static void Main(string[] args) { var b = new B(); var y = ([|(A)b|]).Foo[1]; } } ", replacementExpression: "b", semanticChanges: true); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerDelegatePropertyWithRedundantCast() { Test(code: @" public delegate void MyDelegate(); class A { public MyDelegate Foo { get; } } class B : A { } class Program { static void Main(string[] args) { var b = new B(); ([|(A)b|]).Foo(); } } ", replacementExpression: "b", semanticChanges: false); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerDelegatePropertyWithRequiredCast() { Test(code: @" public delegate void MyDelegate(); class A { public MyDelegate Foo { get; } } class B : A { public new MyDelegate Foo { get; } } class Program { static void Main(string[] args) { var b = new B(); ([|(A)b|]).Foo(); } } ", replacementExpression: "b", semanticChanges: true); } protected override SyntaxTree Parse(string text) => SyntaxFactory.ParseSyntaxTree(text); protected override bool IsExpressionNode(SyntaxNode node) => node is ExpressionSyntax; protected override Compilation CreateCompilation(SyntaxTree tree) { return CSharpCompilation.Create( CompilationName, new[] { tree }, References, TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new[] { KeyValuePairUtil.Create("CS0219", ReportDiagnostic.Suppress) })); } protected override bool CompilationSucceeded(Compilation compilation, Stream temporaryStream) { var langCompilation = compilation; static bool isProblem(Diagnostic d) => d.Severity >= DiagnosticSeverity.Warning; return !langCompilation.GetDiagnostics().Any(isProblem) && !langCompilation.Emit(temporaryStream).Diagnostics.Any(isProblem); } protected override bool ReplacementChangesSemantics(SyntaxNode initialNode, SyntaxNode replacementNode, SemanticModel initialModel) => new SpeculationAnalyzer((ExpressionSyntax)initialNode, (ExpressionSyntax)replacementNode, initialModel, CancellationToken.None).ReplacementChangesSemantics(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.IO; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Editor.UnitTests.Semantics; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Semantics { public class SpeculationAnalyzerTests : SpeculationAnalyzerTestsBase { [Fact] public void SpeculationAnalyzerDifferentOverloads() { Test(@" class Program { void Vain(int arg = 3) { } void Vain(string arg) { } void Main() { [|Vain(5)|]; } } ", "Vain(string.Empty)", true); } [Fact, WorkItem(672396, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/672396")] public void SpeculationAnalyzerExtensionMethodExplicitInvocation() { Test(@" static class Program { public static void Vain(this int arg) { } static void Main() { [|5.Vain()|]; } } ", "Vain(5)", false); } [Fact] public void SpeculationAnalyzerImplicitBaseClassConversion() { Test(@" using System; class Program { void Main() { Exception ex = [|(Exception)new InvalidOperationException()|]; } } ", "new InvalidOperationException()", false); } [Fact] public void SpeculationAnalyzerImplicitNumericConversion() { Test(@" class Program { void Main() { long i = [|(long)5|]; } } ", "5", false); } [Fact] public void SpeculationAnalyzerImplicitUserConversion() { Test(@" class From { public static implicit operator To(From from) { return new To(); } } class To { } class Program { void Main() { To to = [|(To)new From()|]; } } ", "new From()", true); } [Fact] public void SpeculationAnalyzerExplicitConversion() { Test(@" using System; class Program { void Main() { Exception ex1 = new InvalidOperationException(); var ex2 = [|(InvalidOperationException)ex1|]; } } ", "ex1", true); } [Fact] public void SpeculationAnalyzerArrayImplementingNonGenericInterface() { Test(@" using System.Collections; class Program { void Main() { var a = new[] { 1, 2, 3 }; [|((IEnumerable)a).GetEnumerator()|]; } } ", "a.GetEnumerator()", false); } [Fact] public void SpeculationAnalyzerVirtualMethodWithBaseConversion() { Test(@" using System; using System.IO; class Program { void Main() { var s = new MemoryStream(); [|((Stream)s).Flush()|]; } } ", "s.Flush()", false); } [Fact] public void SpeculationAnalyzerNonVirtualMethodImplementingInterface() { Test(@" using System; class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); var d = new Class(); [|((IComparable)c).CompareTo(d)|]; } } ", "c.CompareTo(d)", true); } [Fact] public void SpeculationAnalyzerSealedClassImplementingInterface() { Test(@" using System; sealed class Class : IComparable { public int CompareTo(object other) { return 1; } } class Program { static void Main() { var c = new Class(); var d = new Class(); [|((IComparable)c).CompareTo(d)|]; } } ", "((IComparable)c).CompareTo(d)", semanticChanges: false); } [Fact] public void SpeculationAnalyzerValueTypeImplementingInterface() { Test(@" using System; class Program { void Main() { decimal d = 5; [|((IComparable<decimal>)d).CompareTo(6)|]; } } ", "d.CompareTo(6)", false); } [Fact] public void SpeculationAnalyzerBinaryExpressionIntVsLong() { Test(@" class Program { void Main() { var r = [|1+1L|]; } } ", "1+1", true); } [Fact] public void SpeculationAnalyzerQueryExpressionSelectType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) select (long)i|]; } } ", "from i in Enumerable.Range(0, 3) select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionFromType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in new long[0] select i|]; } } ", "from i in new int[0] select i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionGroupByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = [|from i in Enumerable.Range(0, 3) group (long)i by i|]; } } ", "from i in Enumerable.Range(0, 3) group i by i", true); } [Fact] public void SpeculationAnalyzerQueryExpressionOrderByType() { Test(@" using System.Linq; class Program { static void Main(string[] args) { var items = from i in Enumerable.Range(0, 3) orderby [|(long)i|] select i; } } ", "i", true); } [Fact] public void SpeculationAnalyzerDifferentAttributeConstructors() { Test(@" using System; class AnAttribute : Attribute { public AnAttribute(string a, long b) { } public AnAttribute(int a, int b) { } } class Program { [An([|""5""|], 6)] static void Main() { } } ", "5", false, "6"); // Note: the answer should have been that the replacement does change semantics (true), // however to have enough context one must analyze AttributeSyntax instead of separate ExpressionSyntaxes it contains, // which is not supported in SpeculationAnalyzer, but possible with GetSpeculativeSemanticModel API } [Fact] public void SpeculationAnalyzerCollectionInitializers() { Test(@" using System.Collections; class Collection : IEnumerable { public IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } public void Add(string s) { } public void Add(int i) { } void Main() { var c = new Collection { [|""5""|] }; } } ", "5", true); } [Fact, WorkItem(1088815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1088815")] public void SpeculationAnalyzerBrokenCode() { Test(@" public interface IRogueAction { public string Name { get; private set; } protected IRogueAction(string name) { [|this.Name|] = name; } } ", "Name", semanticChanges: false, isBrokenCode: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithNeededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(int)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: true); } [Fact, WorkItem(8111, "https://github.com/dotnet/roslyn/issues/8111")] public void SpeculationAnalyzerAnonymousObjectMemberDeclaredWithUnneededCast() { Test(@" class Program { static void Main(string[] args) { object thing = new { shouldBeAnInt = [|(Directions)Directions.South|] }; } public enum Directions { North, East, South, West } } ", "Directions.South", semanticChanges: false); } [Fact, WorkItem(19987, "https://github.com/dotnet/roslyn/issues/19987")] public void SpeculationAnalyzerSwitchCaseWithRedundantCast() { Test(@" class Program { static void Main(string[] arts) { var x = 1f; switch (x) { case [|(float) 1|]: System.Console.WriteLine(""one""); break; default: System.Console.WriteLine(""not one""); break; } } } ", "1", semanticChanges: false); } [Fact, WorkItem(19987, "https://github.com/dotnet/roslyn/issues/19987")] public void SpeculationAnalyzerSwitchCaseWithRequiredCast() { Test(@" class Program { static void Main(string[] arts) { object x = 1f; switch (x) { case [|(float) 1|]: // without the case, object x does not match int 1 System.Console.WriteLine(""one""); break; default: System.Console.WriteLine(""not one""); break; } } } ", "1", semanticChanges: true); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerIndexerPropertyWithRedundantCast() { Test(code: @" class Indexer { public int this[int x] { get { return x; } } } class A { public Indexer Foo { get; } = new Indexer(); } class B : A { } class Program { static void Main(string[] args) { var b = new B(); var y = ([|(A)b|]).Foo[1]; } } ", replacementExpression: "b", semanticChanges: false); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerIndexerPropertyWithRequiredCast() { Test(code: @" class Indexer { public int this[int x] { get { return x; } } } class A { public Indexer Foo { get; } = new Indexer(); } class B : A { public new Indexer Foo { get; } = new Indexer(); } class Program { static void Main(string[] args) { var b = new B(); var y = ([|(A)b|]).Foo[1]; } } ", replacementExpression: "b", semanticChanges: true); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerDelegatePropertyWithRedundantCast() { Test(code: @" public delegate void MyDelegate(); class A { public MyDelegate Foo { get; } } class B : A { } class Program { static void Main(string[] args) { var b = new B(); ([|(A)b|]).Foo(); } } ", replacementExpression: "b", semanticChanges: false); } [Fact, WorkItem(28412, "https://github.com/dotnet/roslyn/issues/28412")] public void SpeculationAnalyzerDelegatePropertyWithRequiredCast() { Test(code: @" public delegate void MyDelegate(); class A { public MyDelegate Foo { get; } } class B : A { public new MyDelegate Foo { get; } } class Program { static void Main(string[] args) { var b = new B(); ([|(A)b|]).Foo(); } } ", replacementExpression: "b", semanticChanges: true); } protected override SyntaxTree Parse(string text) => SyntaxFactory.ParseSyntaxTree(text); protected override bool IsExpressionNode(SyntaxNode node) => node is ExpressionSyntax; protected override Compilation CreateCompilation(SyntaxTree tree) { return CSharpCompilation.Create( CompilationName, new[] { tree }, References, TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(new[] { KeyValuePairUtil.Create("CS0219", ReportDiagnostic.Suppress) })); } protected override bool CompilationSucceeded(Compilation compilation, Stream temporaryStream) { var langCompilation = compilation; static bool isProblem(Diagnostic d) => d.Severity >= DiagnosticSeverity.Warning; return !langCompilation.GetDiagnostics().Any(isProblem) && !langCompilation.Emit(temporaryStream).Diagnostics.Any(isProblem); } protected override bool ReplacementChangesSemantics(SyntaxNode initialNode, SyntaxNode replacementNode, SemanticModel initialModel) => new SpeculationAnalyzer((ExpressionSyntax)initialNode, (ExpressionSyntax)replacementNode, initialModel, CancellationToken.None).ReplacementChangesSemantics(); } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/Test/Resources/Core/SymbolsTests/CustomModifiers/CppCli.cpp
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //cl /clr:safe /LD CppCli.cpp using namespace System; namespace CppCli { public interface class CppInterface1 { public: void Method1(const int x); void Method2(const int x); }; // Identical, but distinct from, CppInterface1 public interface class CppInterface2 { public: void Method1(const int x); void Method2(const int x); }; public ref class CppBase1 { public: virtual void VirtualMethod(const int x) { Console::WriteLine("CppBase1::VirtualMethod({0})", x); } void NonVirtualMethod(const int x) { Console::WriteLine("CppBase1::NonVirtualMethod({0})", x); } }; public ref class CppBase2 { public: virtual void Method1(const int x) { Console::WriteLine("CppBase2::Method1({0})", x); } void Method2(const int x) { Console::WriteLine("CppBase2::Method2({0})", x); } }; public interface class CppBestMatchInterface { public: void Method(const int x, int y); }; public ref class CppBestMatchBase1 { public: virtual void Method(int x, const int y) { Console::WriteLine("CppBestMatchBase1::Method({0},{1})", x, y); } }; public ref class CppBestMatchBase2 : CppBestMatchBase1 { public: virtual void Method(const int x, const int y) new { Console::WriteLine("CppBestMatchBase2::Method({0},{1})", x, y); } }; public interface class CppIndexerInterface { public: property int default[const int] { int get(const int i); void set(const int i, int value); } }; public ref class CppIndexerBase { public: virtual property int default[const int] { int get(const int i) { Console::WriteLine("CppBase1::Item.get({0})", i); return 0; } void set(const int i, int value) { Console::WriteLine("CppBase1::Item.set({0})", 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. //cl /clr:safe /LD CppCli.cpp using namespace System; namespace CppCli { public interface class CppInterface1 { public: void Method1(const int x); void Method2(const int x); }; // Identical, but distinct from, CppInterface1 public interface class CppInterface2 { public: void Method1(const int x); void Method2(const int x); }; public ref class CppBase1 { public: virtual void VirtualMethod(const int x) { Console::WriteLine("CppBase1::VirtualMethod({0})", x); } void NonVirtualMethod(const int x) { Console::WriteLine("CppBase1::NonVirtualMethod({0})", x); } }; public ref class CppBase2 { public: virtual void Method1(const int x) { Console::WriteLine("CppBase2::Method1({0})", x); } void Method2(const int x) { Console::WriteLine("CppBase2::Method2({0})", x); } }; public interface class CppBestMatchInterface { public: void Method(const int x, int y); }; public ref class CppBestMatchBase1 { public: virtual void Method(int x, const int y) { Console::WriteLine("CppBestMatchBase1::Method({0},{1})", x, y); } }; public ref class CppBestMatchBase2 : CppBestMatchBase1 { public: virtual void Method(const int x, const int y) new { Console::WriteLine("CppBestMatchBase2::Method({0},{1})", x, y); } }; public interface class CppIndexerInterface { public: property int default[const int] { int get(const int i); void set(const int i, int value); } }; public ref class CppIndexerBase { public: virtual property int default[const int] { int get(const int i) { Console::WriteLine("CppBase1::Item.get({0})", i); return 0; } void set(const int i, int value) { Console::WriteLine("CppBase1::Item.set({0})", i); } } }; }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Features/Core/Portable/Shared/Extensions/ISymbolExtensions_Sorting.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Globalization; using System.Linq; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal partial class ISymbolExtensions2 { [Obsolete("Use overload without ISymbolDisplayService")] public static ImmutableArray<TSymbol> Sort<TSymbol>( this ImmutableArray<TSymbol> symbols, ISymbolDisplayService symbolDisplayService, SemanticModel semanticModel, int position) where TSymbol : ISymbol { return Sort(symbols, semanticModel, position); } public static ImmutableArray<TSymbol> Sort<TSymbol>( this ImmutableArray<TSymbol> symbols, SemanticModel semanticModel, int position) where TSymbol : ISymbol { var symbolToParameterTypeNames = new ConcurrentDictionary<TSymbol, string[]>(); string[] getParameterTypeNames(TSymbol s) => GetParameterTypeNames(s, semanticModel, position); return symbols.OrderBy((s1, s2) => Compare(s1, s2, symbolToParameterTypeNames, getParameterTypeNames)) .ToImmutableArray(); } private static INamedTypeSymbol GetNamedType(ITypeSymbol type) => type switch { INamedTypeSymbol namedType => namedType, IArrayTypeSymbol arrayType => GetNamedType(arrayType.ElementType), IPointerTypeSymbol pointerType => GetNamedType(pointerType.PointedAtType), _ => null, }; private static int CompareParameters( ImmutableArray<IParameterSymbol> xParameters, string[] xTypeNames, ImmutableArray<IParameterSymbol> yParameters, string[] yTypeNames) { // * Order by the number of parameters // * If the same number of parameters... // * Sort alphabetically by parameter type name // * Params parameters are sorted at the end // * Parameter types with type parameters are after those if (xParameters.IsDefault || yParameters.IsDefault) { return xParameters.IsDefault && yParameters.IsDefault ? 0 : xParameters.IsDefault ? -1 : 1; } var diff = xParameters.Length - yParameters.Length; if (diff != 0) { return diff; } var paramCount = xParameters.Length; for (var i = 0; i < paramCount; i++) { var xParam = xParameters[i]; var yParam = yParameters[i]; var xParamType = GetNamedType(xParam.Type); var yParamType = GetNamedType(yParam.Type); if (xParamType != null && yParamType != null) { diff = CompareNamedTypes(xParamType, yParamType); if (diff != 0) { return diff; } } if (xParam.IsParams != yParam.IsParams) { return xParam.IsParams ? 1 : -1; } diff = CultureInfo.CurrentUICulture.CompareInfo.Compare(xTypeNames[i], yTypeNames[i], CompareOptions.StringSort); if (diff != 0) { return diff; } } return 0; } private static int CompareProperties(IPropertySymbol xProperty, string[] xTypeNames, IPropertySymbol yProperty, string[] yTypeNames) => CompareParameters(xProperty.Parameters, xTypeNames, yProperty.Parameters, yTypeNames); private static int CompareMethods(IMethodSymbol xMethod, string[] xTypeNames, IMethodSymbol yMethod, string[] yTypeNames) { // * Order by arity // * Order by parameters var diff = xMethod.Arity - yMethod.Arity; if (diff != 0) { return diff; } return CompareParameters(xMethod.Parameters, xTypeNames, yMethod.Parameters, yTypeNames); } private static int CompareEvents(IEventSymbol xEvent, string[] xTypeNames, IEventSymbol yEvent, string[] yTypeNames) => CompareParameters(GetMethodOrIndexerOrEventParameters(xEvent), xTypeNames, GetMethodOrIndexerOrEventParameters(yEvent), yTypeNames); private static int CompareNamedTypes(INamedTypeSymbol xNamedType, INamedTypeSymbol yNamedType) { // For named types, we sort on arity. return xNamedType.Arity - yNamedType.Arity; } private static string[] GetParameterTypeNames( ISymbol symbol, SemanticModel semanticModel, int position) { return GetMethodOrIndexerOrEventParameters(symbol) .Select(p => p.Type.ToMinimalDisplayString(semanticModel, position)) .ToArray(); } private static ImmutableArray<IParameterSymbol> GetMethodOrIndexerOrEventParameters(ISymbol symbol) { if (symbol is IEventSymbol ev) { var type = ev.Type as INamedTypeSymbol; if (type.IsDelegateType()) { return type.DelegateInvokeMethod.Parameters; } } return symbol.GetParameters(); } private static int Compare<TSymbol>( TSymbol s1, TSymbol s2, ConcurrentDictionary<TSymbol, string[]> symbolToParameterTypeNames, Func<TSymbol, string[]> getParameterTypeNames) where TSymbol : ISymbol { var symbol1ParameterTypeNames = symbolToParameterTypeNames.GetOrAdd(s1, getParameterTypeNames); var symbol2ParameterTypeNames = symbolToParameterTypeNames.GetOrAdd(s2, getParameterTypeNames); // Order named types before methods and properties, and methods before properties. if (s1.Kind == SymbolKind.NamedType || s2.Kind == SymbolKind.NamedType) { return s1.Kind == s2.Kind ? CompareNamedTypes((INamedTypeSymbol)s1, (INamedTypeSymbol)s2) : s1.Kind == SymbolKind.NamedType ? -1 : 1; } if (s1.Kind == SymbolKind.Method || s2.Kind == SymbolKind.Method) { return s1.Kind == s2.Kind ? CompareMethods((IMethodSymbol)s1, symbol1ParameterTypeNames, (IMethodSymbol)s2, symbol2ParameterTypeNames) : s1.Kind == SymbolKind.Method ? -1 : 1; } if (s1.Kind == SymbolKind.Property || s2.Kind == SymbolKind.Property) { return s1.Kind == s2.Kind ? CompareProperties((IPropertySymbol)s1, symbol1ParameterTypeNames, (IPropertySymbol)s2, symbol2ParameterTypeNames) : s1.Kind == SymbolKind.Property ? -1 : 1; } if (s1.Kind == SymbolKind.Event || s2.Kind == SymbolKind.Event) { return s1.Kind == s2.Kind ? CompareEvents((IEventSymbol)s1, symbol1ParameterTypeNames, (IEventSymbol)s2, symbol2ParameterTypeNames) : s1.Kind == SymbolKind.Event ? -1 : 1; } throw ExceptionUtilities.UnexpectedValue((s1.Kind, s2.Kind)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Globalization; using System.Linq; using Microsoft.CodeAnalysis.LanguageServices; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.Shared.Extensions { internal partial class ISymbolExtensions2 { [Obsolete("Use overload without ISymbolDisplayService")] public static ImmutableArray<TSymbol> Sort<TSymbol>( this ImmutableArray<TSymbol> symbols, ISymbolDisplayService symbolDisplayService, SemanticModel semanticModel, int position) where TSymbol : ISymbol { return Sort(symbols, semanticModel, position); } public static ImmutableArray<TSymbol> Sort<TSymbol>( this ImmutableArray<TSymbol> symbols, SemanticModel semanticModel, int position) where TSymbol : ISymbol { var symbolToParameterTypeNames = new ConcurrentDictionary<TSymbol, string[]>(); string[] getParameterTypeNames(TSymbol s) => GetParameterTypeNames(s, semanticModel, position); return symbols.OrderBy((s1, s2) => Compare(s1, s2, symbolToParameterTypeNames, getParameterTypeNames)) .ToImmutableArray(); } private static INamedTypeSymbol GetNamedType(ITypeSymbol type) => type switch { INamedTypeSymbol namedType => namedType, IArrayTypeSymbol arrayType => GetNamedType(arrayType.ElementType), IPointerTypeSymbol pointerType => GetNamedType(pointerType.PointedAtType), _ => null, }; private static int CompareParameters( ImmutableArray<IParameterSymbol> xParameters, string[] xTypeNames, ImmutableArray<IParameterSymbol> yParameters, string[] yTypeNames) { // * Order by the number of parameters // * If the same number of parameters... // * Sort alphabetically by parameter type name // * Params parameters are sorted at the end // * Parameter types with type parameters are after those if (xParameters.IsDefault || yParameters.IsDefault) { return xParameters.IsDefault && yParameters.IsDefault ? 0 : xParameters.IsDefault ? -1 : 1; } var diff = xParameters.Length - yParameters.Length; if (diff != 0) { return diff; } var paramCount = xParameters.Length; for (var i = 0; i < paramCount; i++) { var xParam = xParameters[i]; var yParam = yParameters[i]; var xParamType = GetNamedType(xParam.Type); var yParamType = GetNamedType(yParam.Type); if (xParamType != null && yParamType != null) { diff = CompareNamedTypes(xParamType, yParamType); if (diff != 0) { return diff; } } if (xParam.IsParams != yParam.IsParams) { return xParam.IsParams ? 1 : -1; } diff = CultureInfo.CurrentUICulture.CompareInfo.Compare(xTypeNames[i], yTypeNames[i], CompareOptions.StringSort); if (diff != 0) { return diff; } } return 0; } private static int CompareProperties(IPropertySymbol xProperty, string[] xTypeNames, IPropertySymbol yProperty, string[] yTypeNames) => CompareParameters(xProperty.Parameters, xTypeNames, yProperty.Parameters, yTypeNames); private static int CompareMethods(IMethodSymbol xMethod, string[] xTypeNames, IMethodSymbol yMethod, string[] yTypeNames) { // * Order by arity // * Order by parameters var diff = xMethod.Arity - yMethod.Arity; if (diff != 0) { return diff; } return CompareParameters(xMethod.Parameters, xTypeNames, yMethod.Parameters, yTypeNames); } private static int CompareEvents(IEventSymbol xEvent, string[] xTypeNames, IEventSymbol yEvent, string[] yTypeNames) => CompareParameters(GetMethodOrIndexerOrEventParameters(xEvent), xTypeNames, GetMethodOrIndexerOrEventParameters(yEvent), yTypeNames); private static int CompareNamedTypes(INamedTypeSymbol xNamedType, INamedTypeSymbol yNamedType) { // For named types, we sort on arity. return xNamedType.Arity - yNamedType.Arity; } private static string[] GetParameterTypeNames( ISymbol symbol, SemanticModel semanticModel, int position) { return GetMethodOrIndexerOrEventParameters(symbol) .Select(p => p.Type.ToMinimalDisplayString(semanticModel, position)) .ToArray(); } private static ImmutableArray<IParameterSymbol> GetMethodOrIndexerOrEventParameters(ISymbol symbol) { if (symbol is IEventSymbol ev) { var type = ev.Type as INamedTypeSymbol; if (type.IsDelegateType()) { return type.DelegateInvokeMethod.Parameters; } } return symbol.GetParameters(); } private static int Compare<TSymbol>( TSymbol s1, TSymbol s2, ConcurrentDictionary<TSymbol, string[]> symbolToParameterTypeNames, Func<TSymbol, string[]> getParameterTypeNames) where TSymbol : ISymbol { var symbol1ParameterTypeNames = symbolToParameterTypeNames.GetOrAdd(s1, getParameterTypeNames); var symbol2ParameterTypeNames = symbolToParameterTypeNames.GetOrAdd(s2, getParameterTypeNames); // Order named types before methods and properties, and methods before properties. if (s1.Kind == SymbolKind.NamedType || s2.Kind == SymbolKind.NamedType) { return s1.Kind == s2.Kind ? CompareNamedTypes((INamedTypeSymbol)s1, (INamedTypeSymbol)s2) : s1.Kind == SymbolKind.NamedType ? -1 : 1; } if (s1.Kind == SymbolKind.Method || s2.Kind == SymbolKind.Method) { return s1.Kind == s2.Kind ? CompareMethods((IMethodSymbol)s1, symbol1ParameterTypeNames, (IMethodSymbol)s2, symbol2ParameterTypeNames) : s1.Kind == SymbolKind.Method ? -1 : 1; } if (s1.Kind == SymbolKind.Property || s2.Kind == SymbolKind.Property) { return s1.Kind == s2.Kind ? CompareProperties((IPropertySymbol)s1, symbol1ParameterTypeNames, (IPropertySymbol)s2, symbol2ParameterTypeNames) : s1.Kind == SymbolKind.Property ? -1 : 1; } if (s1.Kind == SymbolKind.Event || s2.Kind == SymbolKind.Event) { return s1.Kind == s2.Kind ? CompareEvents((IEventSymbol)s1, symbol1ParameterTypeNames, (IEventSymbol)s2, symbol2ParameterTypeNames) : s1.Kind == SymbolKind.Event ? -1 : 1; } throw ExceptionUtilities.UnexpectedValue((s1.Kind, s2.Kind)); } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/CSharp/Portable/Symbols/Retargeting/RetargetingSymbolTranslator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting { internal enum RetargetOptions : byte { RetargetPrimitiveTypesByName = 0, RetargetPrimitiveTypesByTypeCode = 1, } internal partial class RetargetingModuleSymbol { /// <summary> /// Retargeting map from underlying module to this one. /// </summary> private readonly ConcurrentDictionary<Symbol, Symbol> _symbolMap = new ConcurrentDictionary<Symbol, Symbol>(concurrencyLevel: 2, capacity: 4); private readonly Func<Symbol, RetargetingMethodSymbol> _createRetargetingMethod; private readonly Func<Symbol, RetargetingNamespaceSymbol> _createRetargetingNamespace; private readonly Func<Symbol, RetargetingTypeParameterSymbol> _createRetargetingTypeParameter; private readonly Func<Symbol, RetargetingNamedTypeSymbol> _createRetargetingNamedType; private readonly Func<Symbol, FieldSymbol> _createRetargetingField; private readonly Func<Symbol, RetargetingPropertySymbol> _createRetargetingProperty; private readonly Func<Symbol, RetargetingEventSymbol> _createRetargetingEvent; private RetargetingMethodSymbol CreateRetargetingMethod(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); return new RetargetingMethodSymbol(this, (MethodSymbol)symbol); } private RetargetingNamespaceSymbol CreateRetargetingNamespace(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); return new RetargetingNamespaceSymbol(this, (NamespaceSymbol)symbol); } private RetargetingNamedTypeSymbol CreateRetargetingNamedType(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); return new RetargetingNamedTypeSymbol(this, (NamedTypeSymbol)symbol); } private FieldSymbol CreateRetargetingField(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); if (symbol is TupleErrorFieldSymbol tupleErrorField) { var correspondingTupleField = tupleErrorField.CorrespondingTupleField; Debug.Assert(correspondingTupleField is TupleErrorFieldSymbol); var retargetedCorrespondingDefaultFieldOpt = (correspondingTupleField == (object)tupleErrorField) ? null : (TupleErrorFieldSymbol)RetargetingTranslator.Retarget(correspondingTupleField); return new TupleErrorFieldSymbol( RetargetingTranslator.Retarget(tupleErrorField.ContainingType, RetargetOptions.RetargetPrimitiveTypesByName), tupleErrorField.Name, tupleErrorField.TupleElementIndex, tupleErrorField.Locations.IsEmpty ? null : tupleErrorField.Locations[0], this.RetargetingTranslator.Retarget(tupleErrorField.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), tupleErrorField.GetUseSiteInfo().DiagnosticInfo, tupleErrorField.IsImplicitlyDeclared, retargetedCorrespondingDefaultFieldOpt); } return new RetargetingFieldSymbol(this, (FieldSymbol)symbol); } private RetargetingPropertySymbol CreateRetargetingProperty(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); return new RetargetingPropertySymbol(this, (PropertySymbol)symbol); } private RetargetingEventSymbol CreateRetargetingEvent(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); return new RetargetingEventSymbol(this, (EventSymbol)symbol); } private RetargetingTypeParameterSymbol CreateRetargetingTypeParameter(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); return new RetargetingTypeParameterSymbol(this, (TypeParameterSymbol)symbol); } internal class RetargetingSymbolTranslator : CSharpSymbolVisitor<RetargetOptions, Symbol> { private readonly RetargetingModuleSymbol _retargetingModule; public RetargetingSymbolTranslator(RetargetingModuleSymbol retargetingModule) { Debug.Assert((object)retargetingModule != null); _retargetingModule = retargetingModule; } /// <summary> /// Retargeting map from underlying module to the retargeting module. /// </summary> private ConcurrentDictionary<Symbol, Symbol> SymbolMap { get { return _retargetingModule._symbolMap; } } /// <summary> /// RetargetingAssemblySymbol owning retargetingModule. /// </summary> private RetargetingAssemblySymbol RetargetingAssembly { get { return _retargetingModule._retargetingAssembly; } } /// <summary> /// The underlying ModuleSymbol for retargetingModule. /// </summary> private SourceModuleSymbol UnderlyingModule { get { return _retargetingModule._underlyingModule; } } /// <summary> /// The map that captures information about what assembly should be retargeted /// to what assembly. Key is the AssemblySymbol referenced by the underlying module, /// value is the corresponding AssemblySymbol referenced by the retargeting module, and /// corresponding retargeting map for symbols. /// </summary> private Dictionary<AssemblySymbol, DestinationData> RetargetingAssemblyMap { get { return _retargetingModule._retargetingAssemblyMap; } } public Symbol Retarget(Symbol symbol) { Debug.Assert(symbol.Kind != SymbolKind.NamedType || ((NamedTypeSymbol)symbol).PrimitiveTypeCode == Cci.PrimitiveTypeCode.NotPrimitive); return symbol.Accept(this, RetargetOptions.RetargetPrimitiveTypesByName); } public MarshalPseudoCustomAttributeData Retarget(MarshalPseudoCustomAttributeData marshallingInfo) { // Retarget by type code - primitive types are encoded in short form in an attribute signature: return marshallingInfo?.WithTranslatedTypes<TypeSymbol, RetargetingSymbolTranslator>( (type, translator) => translator.Retarget(type, RetargetOptions.RetargetPrimitiveTypesByTypeCode), this); } public TypeSymbol Retarget(TypeSymbol symbol, RetargetOptions options) { return (TypeSymbol)symbol.Accept(this, options); } public TypeWithAnnotations Retarget(TypeWithAnnotations underlyingType, RetargetOptions options, NamedTypeSymbol asDynamicIfNoPiaContainingType = null) { var newTypeSymbol = Retarget(underlyingType.Type, options); if ((object)asDynamicIfNoPiaContainingType != null) { newTypeSymbol = newTypeSymbol.AsDynamicIfNoPia(asDynamicIfNoPiaContainingType); } bool modifiersHaveChanged; var newModifiers = RetargetModifiers(underlyingType.CustomModifiers, out modifiersHaveChanged); if (modifiersHaveChanged || !TypeSymbol.Equals(underlyingType.Type, newTypeSymbol, TypeCompareKind.ConsiderEverything2)) { return underlyingType.WithTypeAndModifiers(newTypeSymbol, newModifiers); } return underlyingType; } public NamespaceSymbol Retarget(NamespaceSymbol ns) { return (NamespaceSymbol)this.SymbolMap.GetOrAdd(ns, _retargetingModule._createRetargetingNamespace); } private NamedTypeSymbol RetargetNamedTypeDefinition(NamedTypeSymbol type, RetargetOptions options) { Debug.Assert(type.IsDefinition); if (type.IsNativeIntegerType) { var result = RetargetNamedTypeDefinition(type.NativeIntegerUnderlyingType, options); return result.SpecialType == SpecialType.None ? result : result.AsNativeInteger(); } // Before we do anything else, check if we need to do special retargeting // for primitive type references encoded with enum values in metadata signatures. if (options == RetargetOptions.RetargetPrimitiveTypesByTypeCode) { Cci.PrimitiveTypeCode typeCode = type.PrimitiveTypeCode; if (typeCode != Cci.PrimitiveTypeCode.NotPrimitive) { return RetargetingAssembly.GetPrimitiveType(typeCode); } } if (type.Kind == SymbolKind.ErrorType) { return Retarget((ErrorTypeSymbol)type); } AssemblySymbol retargetFrom = type.ContainingAssembly; // Deal with "to be local" NoPia types leaking through source module. // These are the types that are coming from assemblies linked (/l-ed) // by the compilation that created the source module. bool isLocalType; if (ReferenceEquals(retargetFrom, this.RetargetingAssembly.UnderlyingAssembly)) { Debug.Assert(!retargetFrom.IsLinked); isLocalType = type.IsExplicitDefinitionOfNoPiaLocalType; } else { isLocalType = retargetFrom.IsLinked; } if (isLocalType) { return RetargetNoPiaLocalType(type); } // Perform general retargeting. if (ReferenceEquals(retargetFrom, this.RetargetingAssembly.UnderlyingAssembly)) { return RetargetNamedTypeDefinitionFromUnderlyingAssembly(type); } // Does this type come from one of the retargeted assemblies? DestinationData destination; if (!this.RetargetingAssemblyMap.TryGetValue(retargetFrom, out destination)) { // No need to retarget return type; } // Retarget from one assembly to another type = PerformTypeRetargeting(ref destination, type); this.RetargetingAssemblyMap[retargetFrom] = destination; return type; } private NamedTypeSymbol RetargetNamedTypeDefinitionFromUnderlyingAssembly(NamedTypeSymbol type) { // The type is defined in the underlying assembly. var module = type.ContainingModule; if (ReferenceEquals(module, this.UnderlyingModule)) { Debug.Assert(module.Ordinal == 0); Debug.Assert(!type.IsExplicitDefinitionOfNoPiaLocalType); var container = type.ContainingType; while ((object)container != null) { if (container.IsExplicitDefinitionOfNoPiaLocalType) { // Types nested into local types are not supported. return (NamedTypeSymbol)this.SymbolMap.GetOrAdd(type, new UnsupportedMetadataTypeSymbol()); } container = container.ContainingType; } return (NamedTypeSymbol)this.SymbolMap.GetOrAdd(type, _retargetingModule._createRetargetingNamedType); } else { // The type is defined in one of the added modules Debug.Assert(module.Ordinal > 0); PEModuleSymbol addedModule = (PEModuleSymbol)this.RetargetingAssembly.Modules[module.Ordinal]; Debug.Assert(ReferenceEquals(((PEModuleSymbol)module).Module, addedModule.Module)); return RetargetNamedTypeDefinition((PENamedTypeSymbol)type, addedModule); } } private NamedTypeSymbol RetargetNoPiaLocalType(NamedTypeSymbol type) { NamedTypeSymbol cached; var map = this.RetargetingAssembly.NoPiaUnificationMap; if (map.TryGetValue(type, out cached)) { return cached; } NamedTypeSymbol result; if (type.ContainingSymbol.Kind != SymbolKind.NamedType && type.Arity == 0) { // Get type's identity bool isInterface = type.IsInterface; bool hasGuid = false; string interfaceGuid = null; string scope = null; if (isInterface) { // Get type's Guid hasGuid = type.GetGuidString(out interfaceGuid); } MetadataTypeName name = MetadataTypeName.FromFullName(type.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), forcedArity: type.Arity); string identifier = null; if ((object)type.ContainingModule == (object)_retargetingModule.UnderlyingModule) { // This is a local type explicitly declared in source. Get information from TypeIdentifier attribute. foreach (var attrData in type.GetAttributes()) { int signatureIndex = attrData.GetTargetAttributeSignatureIndex(type, AttributeDescription.TypeIdentifierAttribute); if (signatureIndex != -1) { Debug.Assert(signatureIndex == 0 || signatureIndex == 1); if (signatureIndex == 1 && attrData.CommonConstructorArguments.Length == 2) { scope = attrData.CommonConstructorArguments[0].ValueInternal as string; identifier = attrData.CommonConstructorArguments[1].ValueInternal as string; } break; } } } else { Debug.Assert((object)type.ContainingAssembly != (object)RetargetingAssembly.UnderlyingAssembly); // Note, this logic should match the one in EmbeddedType.Cci.IReference.GetAttributes. // Here we are trying to predict what attributes we will emit on embedded type, which corresponds the // type we are retargeting. That function actually emits the attributes. if (!(hasGuid && isInterface)) { type.ContainingAssembly.GetGuidString(out scope); identifier = name.FullName; } } result = MetadataDecoder.SubstituteNoPiaLocalType( ref name, isInterface, type.BaseTypeNoUseSiteDiagnostics, interfaceGuid, scope, identifier, RetargetingAssembly); Debug.Assert((object)result != null); } else { // TODO: report better error? result = new UnsupportedMetadataTypeSymbol(); } cached = map.GetOrAdd(type, result); return cached; } private static NamedTypeSymbol RetargetNamedTypeDefinition(PENamedTypeSymbol type, PEModuleSymbol addedModule) { Debug.Assert(!type.ContainingModule.Equals(addedModule) && ReferenceEquals(((PEModuleSymbol)type.ContainingModule).Module, addedModule.Module)); TypeSymbol cached; if (addedModule.TypeHandleToTypeMap.TryGetValue(type.Handle, out cached)) { return (NamedTypeSymbol)cached; } NamedTypeSymbol result; NamedTypeSymbol containingType = type.ContainingType; MetadataTypeName mdName; if ((object)containingType != null) { // Nested type. We need to retarget // the enclosing type and then go back and get the type we are interested in. NamedTypeSymbol scope = RetargetNamedTypeDefinition((PENamedTypeSymbol)containingType, addedModule); mdName = MetadataTypeName.FromTypeName(type.MetadataName, forcedArity: type.Arity); result = scope.LookupMetadataType(ref mdName); Debug.Assert((object)result != null && result.Arity == type.Arity); } else { string namespaceName = type.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat); mdName = MetadataTypeName.FromNamespaceAndTypeName(namespaceName, type.MetadataName, forcedArity: type.Arity); result = addedModule.LookupTopLevelMetadataType(ref mdName); Debug.Assert(result.Arity == type.Arity); } return result; } private static NamedTypeSymbol PerformTypeRetargeting( ref DestinationData destination, NamedTypeSymbol type) { NamedTypeSymbol result; if (!destination.SymbolMap.TryGetValue(type, out result)) { // Lookup by name as a TypeRef. NamedTypeSymbol containingType = type.ContainingType; NamedTypeSymbol result1; MetadataTypeName mdName; if ((object)containingType != null) { // This happens if type is a nested class. We need to retarget // the enclosing class and then go back and get the type we are interested in. NamedTypeSymbol scope = PerformTypeRetargeting(ref destination, containingType); mdName = MetadataTypeName.FromTypeName(type.MetadataName, forcedArity: type.Arity); result1 = scope.LookupMetadataType(ref mdName); Debug.Assert((object)result1 != null && result1.Arity == type.Arity); } else { string namespaceName = type.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat); mdName = MetadataTypeName.FromNamespaceAndTypeName(namespaceName, type.MetadataName, forcedArity: type.Arity); result1 = destination.To.LookupTopLevelMetadataType(ref mdName, digThroughForwardedTypes: true); Debug.Assert(result1.Arity == type.Arity); } result = destination.SymbolMap.GetOrAdd(type, result1); Debug.Assert(TypeSymbol.Equals(result1, result, TypeCompareKind.ConsiderEverything2)); } return result; } public NamedTypeSymbol Retarget(NamedTypeSymbol type, RetargetOptions options) { NamedTypeSymbol originalDefinition = type.OriginalDefinition; NamedTypeSymbol newDefinition = RetargetNamedTypeDefinition(originalDefinition, options); if (ReferenceEquals(type, originalDefinition)) { return newDefinition; } if (newDefinition.Kind == SymbolKind.ErrorType && !newDefinition.IsGenericType) { return newDefinition; } Debug.Assert(originalDefinition.Arity == 0 || !ReferenceEquals(type.ConstructedFrom, type)); if (type.IsUnboundGenericType) { if (ReferenceEquals(newDefinition, originalDefinition)) { return type; } return newDefinition.AsUnboundGenericType(); } Debug.Assert((object)type.ContainingType == null || !type.ContainingType.IsUnboundGenericType()); // This must be a generic instantiation (i.e. constructed type). NamedTypeSymbol genericType = type; var oldArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); int startOfNonInterfaceArguments = int.MaxValue; // Collect generic arguments for the type and its containers. while ((object)genericType != null) { if (startOfNonInterfaceArguments == int.MaxValue && !genericType.IsInterface) { startOfNonInterfaceArguments = oldArguments.Count; } oldArguments.AddRange(genericType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); genericType = genericType.ContainingType; } bool anythingRetargeted = !originalDefinition.Equals(newDefinition); // retarget the arguments var newArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(oldArguments.Count); foreach (var arg in oldArguments) { var newArg = Retarget(arg, RetargetOptions.RetargetPrimitiveTypesByTypeCode); // generic instantiation is a signature if (!anythingRetargeted && !newArg.IsSameAs(arg)) { anythingRetargeted = true; } newArguments.Add(newArg); } // See if it is or its enclosing type is a non-interface closed over NoPia local types. bool noPiaIllegalGenericInstantiation = IsNoPiaIllegalGenericInstantiation(oldArguments, newArguments, startOfNonInterfaceArguments); oldArguments.Free(); NamedTypeSymbol constructedType; if (!anythingRetargeted) { // Nothing was retargeted, return original type symbol. constructedType = type; } else { // Create symbol for new constructed type and return it. // need to collect type parameters in the same order as we have arguments, // but this should be done for the new definition. genericType = newDefinition; ArrayBuilder<TypeParameterSymbol> newParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(newArguments.Count); // Collect generic arguments for the type and its containers. while ((object)genericType != null) { if (genericType.Arity > 0) { newParameters.AddRange(genericType.TypeParameters); } genericType = genericType.ContainingType; } Debug.Assert(newParameters.Count == newArguments.Count); TypeMap substitution = new TypeMap(newParameters.ToImmutableAndFree(), newArguments.ToImmutable()); constructedType = substitution.SubstituteNamedType(newDefinition).WithTupleDataFrom(type); } newArguments.Free(); if (noPiaIllegalGenericInstantiation) { return new NoPiaIllegalGenericInstantiationSymbol(_retargetingModule, constructedType); } return constructedType; } private bool IsNoPiaIllegalGenericInstantiation(ArrayBuilder<TypeWithAnnotations> oldArguments, ArrayBuilder<TypeWithAnnotations> newArguments, int startOfNonInterfaceArguments) { // TODO: Do we need to check constraints on type parameters as well? if (this.UnderlyingModule.ContainsExplicitDefinitionOfNoPiaLocalTypes) { for (int i = startOfNonInterfaceArguments; i < oldArguments.Count; i++) { if (IsOrClosedOverAnExplicitLocalType(oldArguments[i].Type)) { return true; } } } ImmutableArray<AssemblySymbol> assembliesToEmbedTypesFrom = this.UnderlyingModule.GetAssembliesToEmbedTypesFrom(); if (assembliesToEmbedTypesFrom.Length > 0) { for (int i = startOfNonInterfaceArguments; i < oldArguments.Count; i++) { if (MetadataDecoder.IsOrClosedOverATypeFromAssemblies(oldArguments[i].Type, assembliesToEmbedTypesFrom)) { return true; } } } ImmutableArray<AssemblySymbol> linkedAssemblies = RetargetingAssembly.GetLinkedReferencedAssemblies(); if (!linkedAssemblies.IsDefaultOrEmpty) { for (int i = startOfNonInterfaceArguments; i < newArguments.Count; i++) { if (MetadataDecoder.IsOrClosedOverATypeFromAssemblies(newArguments[i].Type, linkedAssemblies)) { return true; } } } return false; } /// <summary> /// Perform a check whether the type or at least one of its generic arguments /// is an explicitly defined local type. The check is performed recursively. /// </summary> private bool IsOrClosedOverAnExplicitLocalType(TypeSymbol symbol) { switch (symbol.Kind) { case SymbolKind.TypeParameter: return false; case SymbolKind.ArrayType: return IsOrClosedOverAnExplicitLocalType(((ArrayTypeSymbol)symbol).ElementType); case SymbolKind.PointerType: return IsOrClosedOverAnExplicitLocalType(((PointerTypeSymbol)symbol).PointedAtType); case SymbolKind.DynamicType: return false; case SymbolKind.ErrorType: case SymbolKind.NamedType: var namedType = (NamedTypeSymbol)symbol; if ((object)symbol.OriginalDefinition.ContainingModule == (object)_retargetingModule.UnderlyingModule && namedType.IsExplicitDefinitionOfNoPiaLocalType) { return true; } do { foreach (var argument in namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { if (IsOrClosedOverAnExplicitLocalType(argument.Type)) { return true; } } namedType = namedType.ContainingType; } while ((object)namedType != null); return false; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } public virtual TypeParameterSymbol Retarget(TypeParameterSymbol typeParameter) { return (TypeParameterSymbol)this.SymbolMap.GetOrAdd(typeParameter, _retargetingModule._createRetargetingTypeParameter); } public ArrayTypeSymbol Retarget(ArrayTypeSymbol type) { TypeWithAnnotations oldElement = type.ElementTypeWithAnnotations; TypeWithAnnotations newElement = Retarget(oldElement, RetargetOptions.RetargetPrimitiveTypesByTypeCode); if (oldElement.IsSameAs(newElement)) { return type; } if (type.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(this.RetargetingAssembly, newElement); } return ArrayTypeSymbol.CreateMDArray(this.RetargetingAssembly, newElement, type.Rank, type.Sizes, type.LowerBounds); } internal ImmutableArray<CustomModifier> RetargetModifiers(ImmutableArray<CustomModifier> oldModifiers, out bool modifiersHaveChanged) { ArrayBuilder<CustomModifier> newModifiers = null; for (int i = 0; i < oldModifiers.Length; i++) { var oldModifier = oldModifiers[i]; NamedTypeSymbol oldModifierSymbol = ((CSharpCustomModifier)oldModifier).ModifierSymbol; NamedTypeSymbol newModifierSymbol = Retarget(oldModifierSymbol, RetargetOptions.RetargetPrimitiveTypesByName); // should be retargeted by name if (!newModifierSymbol.Equals(oldModifierSymbol)) { if (newModifiers == null) { newModifiers = ArrayBuilder<CustomModifier>.GetInstance(oldModifiers.Length); newModifiers.AddRange(oldModifiers, i); } newModifiers.Add(oldModifier.IsOptional ? CSharpCustomModifier.CreateOptional(newModifierSymbol) : CSharpCustomModifier.CreateRequired(newModifierSymbol)); } else if (newModifiers != null) { newModifiers.Add(oldModifier); } } Debug.Assert(newModifiers == null || newModifiers.Count == oldModifiers.Length); modifiersHaveChanged = (newModifiers != null); return modifiersHaveChanged ? newModifiers.ToImmutableAndFree() : oldModifiers; } public PointerTypeSymbol Retarget(PointerTypeSymbol type) { TypeWithAnnotations oldPointed = type.PointedAtTypeWithAnnotations; TypeWithAnnotations newPointed = Retarget(oldPointed, RetargetOptions.RetargetPrimitiveTypesByTypeCode); if (oldPointed.IsSameAs(newPointed)) { return type; } return new PointerTypeSymbol(newPointed); } public FunctionPointerTypeSymbol Retarget(FunctionPointerTypeSymbol type) { var signature = type.Signature; var newReturn = Retarget(signature.ReturnTypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); var newRefModifiers = RetargetModifiers(signature.RefCustomModifiers, out bool symbolModified); symbolModified = symbolModified || !signature.ReturnTypeWithAnnotations.IsSameAs(newReturn); var newParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> newParamModifiers = default; var paramCount = signature.ParameterCount; if (paramCount > 0) { var newParameterTypesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(paramCount); var newParameterCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(paramCount); bool parametersModified = false; foreach (var parameter in signature.Parameters) { var newParameterType = Retarget(parameter.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); var newModifiers = RetargetModifiers(parameter.RefCustomModifiers, out bool customModifiersChanged); newParameterTypesBuilder.Add(newParameterType); newParameterCustomModifiersBuilder.Add(newModifiers); parametersModified = parametersModified || !parameter.TypeWithAnnotations.IsSameAs(newParameterType) || customModifiersChanged; } if (parametersModified) { newParameterTypes = newParameterTypesBuilder.ToImmutableAndFree(); newParamModifiers = newParameterCustomModifiersBuilder.ToImmutableAndFree(); symbolModified = true; } else { newParameterTypesBuilder.Free(); newParameterCustomModifiersBuilder.Free(); newParameterTypes = signature.ParameterTypesWithAnnotations; } } if (symbolModified) { return type.SubstituteTypeSymbol(newReturn, newParameterTypes, newRefModifiers, newParamModifiers); } else { return type; } } public static ErrorTypeSymbol Retarget(ErrorTypeSymbol type) { // TODO: if it is a missing symbol error but no longer missing in the target assembly, then we can resolve it here. var useSiteDiagnostic = type.GetUseSiteInfo().DiagnosticInfo; if (useSiteDiagnostic?.Severity == DiagnosticSeverity.Error) { return type; } // A retargeted error symbol must trigger an error on use so that a dependent compilation won't // improperly succeed. We therefore ensure we have a use-site diagnostic. return (type as ExtendedErrorTypeSymbol)?.AsUnreported() ?? // preserve diagnostic information if possible new ExtendedErrorTypeSymbol(type, type.ResultKind, type.ErrorInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_ErrorInReferencedAssembly, type.ContainingAssembly?.Identity.GetDisplayName() ?? string.Empty), true); } public ImmutableArray<Symbol> Retarget(ImmutableArray<Symbol> arr) { var symbols = ArrayBuilder<Symbol>.GetInstance(arr.Length); foreach (var s in arr) { symbols.Add(Retarget(s)); } return symbols.ToImmutableAndFree(); } public ImmutableArray<NamedTypeSymbol> Retarget(ImmutableArray<NamedTypeSymbol> sequence) { var result = ArrayBuilder<NamedTypeSymbol>.GetInstance(sequence.Length); foreach (var nts in sequence) { // If there is an error type in the base type list, it will end up in the interface list (rather // than as the base class), so it might end up passing through here. If it is specified using // a primitive type keyword, then it will have a primitive type code, even if corlib is missing. Debug.Assert(nts.TypeKind == TypeKind.Error || nts.PrimitiveTypeCode == Cci.PrimitiveTypeCode.NotPrimitive); result.Add(Retarget(nts, RetargetOptions.RetargetPrimitiveTypesByName)); } return result.ToImmutableAndFree(); } public ImmutableArray<TypeSymbol> Retarget(ImmutableArray<TypeSymbol> sequence) { var result = ArrayBuilder<TypeSymbol>.GetInstance(sequence.Length); foreach (var ts in sequence) { // In incorrect code, a type parameter constraint list can contain primitive types. Debug.Assert(ts.TypeKind == TypeKind.Error || ts.PrimitiveTypeCode == Cci.PrimitiveTypeCode.NotPrimitive); result.Add(Retarget(ts, RetargetOptions.RetargetPrimitiveTypesByName)); } return result.ToImmutableAndFree(); } public ImmutableArray<TypeWithAnnotations> Retarget(ImmutableArray<TypeWithAnnotations> sequence) { var result = ArrayBuilder<TypeWithAnnotations>.GetInstance(sequence.Length); foreach (var ts in sequence) { result.Add(Retarget(ts, RetargetOptions.RetargetPrimitiveTypesByName)); } return result.ToImmutableAndFree(); } public ImmutableArray<TypeParameterSymbol> Retarget(ImmutableArray<TypeParameterSymbol> list) { var parameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(list.Length); foreach (var tps in list) { parameters.Add(Retarget(tps)); } return parameters.ToImmutableAndFree(); } public MethodSymbol Retarget(MethodSymbol method) { Debug.Assert(ReferenceEquals(method.ContainingModule, this.UnderlyingModule)); Debug.Assert(ReferenceEquals(method, method.OriginalDefinition)); return (MethodSymbol)this.SymbolMap.GetOrAdd(method, _retargetingModule._createRetargetingMethod); } public MethodSymbol Retarget(MethodSymbol method, IEqualityComparer<MethodSymbol> retargetedMethodComparer) { Debug.Assert((object)method == method.ConstructedFrom); if (ReferenceEquals(method.ContainingModule, this.UnderlyingModule) && ReferenceEquals(method, method.OriginalDefinition)) { return Retarget(method); } var containingType = method.ContainingType; var retargetedType = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName); if (ReferenceEquals(retargetedType, containingType)) { return method; } if (!containingType.IsDefinition) { Debug.Assert(!retargetedType.IsDefinition); var retargetedDefinition = Retarget(method.OriginalDefinition, retargetedMethodComparer); if (retargetedDefinition is null) { return null; } return retargetedDefinition.AsMember(retargetedType); } Debug.Assert(retargetedType.IsDefinition); // NB: may return null if the method cannot be found in the retargeted type (e.g. removed in a subsequent version) return FindMethodInRetargetedType(method, retargetedType, retargetedMethodComparer); } public FieldSymbol Retarget(FieldSymbol field) { return (FieldSymbol)this.SymbolMap.GetOrAdd(field, _retargetingModule._createRetargetingField); } public PropertySymbol Retarget(PropertySymbol property) { Debug.Assert(ReferenceEquals(property.ContainingModule, this.UnderlyingModule)); Debug.Assert(ReferenceEquals(property, property.OriginalDefinition)); return (PropertySymbol)this.SymbolMap.GetOrAdd(property, _retargetingModule._createRetargetingProperty); } public PropertySymbol Retarget(PropertySymbol property, IEqualityComparer<PropertySymbol> retargetedPropertyComparer) { if (ReferenceEquals(property.ContainingModule, this.UnderlyingModule) && ReferenceEquals(property, property.OriginalDefinition)) { return Retarget(property); } var containingType = property.ContainingType; var retargetedType = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName); // NB: may return null if the property cannot be found in the retargeted type (e.g. removed in a subsequent version) return ReferenceEquals(retargetedType, containingType) ? property : FindPropertyInRetargetedType(property, retargetedType, retargetedPropertyComparer); } public EventSymbol Retarget(EventSymbol @event) { if (ReferenceEquals(@event.ContainingModule, this.UnderlyingModule) && ReferenceEquals(@event, @event.OriginalDefinition)) { return (EventSymbol)this.SymbolMap.GetOrAdd(@event, _retargetingModule._createRetargetingEvent); } var containingType = @event.ContainingType; var retargetedType = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName); // NB: may return null if the event cannot be found in the retargeted type (e.g. removed in a subsequent version) return ReferenceEquals(retargetedType, containingType) ? @event : FindEventInRetargetedType(@event, retargetedType); } private MethodSymbol FindMethodInRetargetedType(MethodSymbol method, NamedTypeSymbol retargetedType, IEqualityComparer<MethodSymbol> retargetedMethodComparer) { return RetargetedTypeMethodFinder.Find(this, method, retargetedType, retargetedMethodComparer); } private class RetargetedTypeMethodFinder : RetargetingSymbolTranslator { private readonly NamedTypeSymbol _retargetedType; private readonly MethodSymbol _toFind; private RetargetedTypeMethodFinder(RetargetingModuleSymbol retargetingModule, NamedTypeSymbol retargetedType, MethodSymbol toFind) : base(retargetingModule) { _retargetedType = retargetedType; _toFind = toFind; } public static MethodSymbol Find(RetargetingSymbolTranslator translator, MethodSymbol method, NamedTypeSymbol retargetedType, IEqualityComparer<MethodSymbol> retargetedMethodComparer) { if (!method.IsGenericMethod && !retargetedType.IsGenericType) { return FindWorker(translator, method, retargetedType, retargetedMethodComparer); } // A generic method or a method in generic type needs special handling because its signature is very likely // to refer to method's or type's type parameters. var finder = new RetargetedTypeMethodFinder(translator._retargetingModule, retargetedType, method); return FindWorker(finder, method, retargetedType, retargetedMethodComparer); } private static MethodSymbol FindWorker ( RetargetingSymbolTranslator translator, MethodSymbol method, NamedTypeSymbol retargetedType, IEqualityComparer<MethodSymbol> retargetedMethodComparer ) { bool modifiersHaveChanged_Ignored; //ignored var targetParamsBuilder = ArrayBuilder<ParameterSymbol>.GetInstance(method.Parameters.Length); foreach (var param in method.Parameters) { targetParamsBuilder.Add( new SignatureOnlyParameterSymbol( translator.Retarget(param.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), translator.RetargetModifiers(param.RefCustomModifiers, out modifiersHaveChanged_Ignored), param.IsParams, param.RefKind)); } // We will be using this symbol only for the purpose of method signature comparison, // IndexedTypeParameterSymbols should work just fine as the type parameters for the method. // We can't produce "real" TypeParameterSymbols without finding the method first and this // is what we are trying to do right now. var targetMethod = new SignatureOnlyMethodSymbol( method.Name, retargetedType, method.MethodKind, method.CallingConvention, IndexedTypeParameterSymbol.TakeSymbols(method.Arity), targetParamsBuilder.ToImmutableAndFree(), method.RefKind, method.IsInitOnly, method.IsStatic, translator.Retarget(method.ReturnTypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), translator.RetargetModifiers(method.RefCustomModifiers, out modifiersHaveChanged_Ignored), ImmutableArray<MethodSymbol>.Empty); foreach (var retargetedMember in retargetedType.GetMembers(method.Name)) { if (retargetedMember.Kind == SymbolKind.Method) { var retargetedMethod = (MethodSymbol)retargetedMember; if (retargetedMethodComparer.Equals(retargetedMethod, targetMethod)) { return retargetedMethod; } } } return null; } public override TypeParameterSymbol Retarget(TypeParameterSymbol typeParameter) { if (typeParameter.TypeParameterKind == TypeParameterKind.Method) { Debug.Assert((object)typeParameter.ContainingSymbol == _toFind); // The method symbol we are building will be using IndexedTypeParameterSymbols as // its type parameters, therefore, we should return them here as well. return IndexedTypeParameterSymbol.GetTypeParameter(typeParameter.Ordinal); } NamedTypeSymbol containingType = _toFind.ContainingType; NamedTypeSymbol retargetedContainingType = _retargetedType; do { if ((object)containingType == typeParameter.ContainingSymbol) { return retargetedContainingType.TypeParameters[typeParameter.Ordinal]; } containingType = containingType.ContainingType; retargetedContainingType = retargetedContainingType.ContainingType; } while (containingType is object); throw ExceptionUtilities.Unreachable; } } private PropertySymbol FindPropertyInRetargetedType(PropertySymbol property, NamedTypeSymbol retargetedType, IEqualityComparer<PropertySymbol> retargetedPropertyComparer) { bool modifiersHaveChanged_Ignored; //ignored var targetParamsBuilder = ArrayBuilder<ParameterSymbol>.GetInstance(property.Parameters.Length); foreach (var param in property.Parameters) { targetParamsBuilder.Add( new SignatureOnlyParameterSymbol( Retarget(param.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), RetargetModifiers(param.RefCustomModifiers, out modifiersHaveChanged_Ignored), param.IsParams, param.RefKind)); } var targetProperty = new SignatureOnlyPropertySymbol( property.Name, retargetedType, targetParamsBuilder.ToImmutableAndFree(), property.RefKind, Retarget(property.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), RetargetModifiers(property.RefCustomModifiers, out modifiersHaveChanged_Ignored), property.IsStatic, ImmutableArray<PropertySymbol>.Empty); foreach (var retargetedMember in retargetedType.GetMembers(property.Name)) { if (retargetedMember.Kind == SymbolKind.Property) { var retargetedProperty = (PropertySymbol)retargetedMember; if (retargetedPropertyComparer.Equals(retargetedProperty, targetProperty)) { return retargetedProperty; } } } return null; } private EventSymbol FindEventInRetargetedType(EventSymbol @event, NamedTypeSymbol retargetedType) { var targetType = Retarget(@event.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); foreach (var retargetedMember in retargetedType.GetMembers(@event.Name)) { if (retargetedMember.Kind == SymbolKind.Event) { var retargetedEvent = (EventSymbol)retargetedMember; if (TypeSymbol.Equals(retargetedEvent.Type, targetType.Type, TypeCompareKind.ConsiderEverything2)) { return retargetedEvent; } } } return null; } internal ImmutableArray<CustomModifier> RetargetModifiers( ImmutableArray<CustomModifier> oldModifiers, ref ImmutableArray<CustomModifier> lazyCustomModifiers) { if (lazyCustomModifiers.IsDefault) { bool modifiersHaveChanged; ImmutableArray<CustomModifier> newModifiers = this.RetargetModifiers(oldModifiers, out modifiersHaveChanged); ImmutableInterlocked.InterlockedCompareExchange(ref lazyCustomModifiers, newModifiers, default(ImmutableArray<CustomModifier>)); } return lazyCustomModifiers; } private ImmutableArray<CSharpAttributeData> RetargetAttributes(ImmutableArray<CSharpAttributeData> oldAttributes) { return oldAttributes.SelectAsArray((a, t) => t.RetargetAttributeData(a), this); } internal IEnumerable<CSharpAttributeData> RetargetAttributes(IEnumerable<CSharpAttributeData> attributes) { #if DEBUG SynthesizedAttributeData x = null; SourceAttributeData y = x; // Code below relies on the fact that SynthesizedAttributeData derives from SourceAttributeData. x = (SynthesizedAttributeData)y; #endif foreach (var attributeData in attributes) { yield return this.RetargetAttributeData(attributeData); } } private CSharpAttributeData RetargetAttributeData(CSharpAttributeData oldAttributeData) { SourceAttributeData oldAttribute = (SourceAttributeData)oldAttributeData; MethodSymbol oldAttributeCtor = oldAttribute.AttributeConstructor; MethodSymbol newAttributeCtor = (object)oldAttributeCtor == null ? null : Retarget(oldAttributeCtor, MemberSignatureComparer.RetargetedExplicitImplementationComparer); NamedTypeSymbol oldAttributeType = oldAttribute.AttributeClass; NamedTypeSymbol newAttributeType; if ((object)newAttributeCtor != null) { newAttributeType = newAttributeCtor.ContainingType; } else if ((object)oldAttributeType != null) { newAttributeType = Retarget(oldAttributeType, RetargetOptions.RetargetPrimitiveTypesByTypeCode); } else { newAttributeType = null; } ImmutableArray<TypedConstant> oldAttributeCtorArguments = oldAttribute.CommonConstructorArguments; ImmutableArray<TypedConstant> newAttributeCtorArguments = RetargetAttributeConstructorArguments(oldAttributeCtorArguments); ImmutableArray<KeyValuePair<string, TypedConstant>> oldAttributeNamedArguments = oldAttribute.CommonNamedArguments; ImmutableArray<KeyValuePair<string, TypedConstant>> newAttributeNamedArguments = RetargetAttributeNamedArguments(oldAttributeNamedArguments); // Must create a RetargetingAttributeData even if the types and // arguments are unchanged since the AttributeData instance is // used to resolve System.Type which may require retargeting. return new RetargetingAttributeData( oldAttribute.ApplicationSyntaxReference, newAttributeType, newAttributeCtor, newAttributeCtorArguments, oldAttribute.ConstructorArgumentsSourceIndices, newAttributeNamedArguments, oldAttribute.HasErrors, oldAttribute.IsConditionallyOmitted); } private ImmutableArray<TypedConstant> RetargetAttributeConstructorArguments(ImmutableArray<TypedConstant> constructorArguments) { ImmutableArray<TypedConstant> retargetedArguments = constructorArguments; bool argumentsHaveChanged = false; if (!constructorArguments.IsDefault && constructorArguments.Any()) { var newArguments = ArrayBuilder<TypedConstant>.GetInstance(constructorArguments.Length); foreach (TypedConstant oldArgument in constructorArguments) { TypedConstant retargetedArgument = RetargetTypedConstant(oldArgument, ref argumentsHaveChanged); newArguments.Add(retargetedArgument); } if (argumentsHaveChanged) { retargetedArguments = newArguments.ToImmutable(); } newArguments.Free(); } return retargetedArguments; } private TypedConstant RetargetTypedConstant(TypedConstant oldConstant, ref bool typedConstantChanged) { TypeSymbol oldConstantType = (TypeSymbol)oldConstant.TypeInternal; TypeSymbol newConstantType = (object)oldConstantType == null ? null : Retarget(oldConstantType, RetargetOptions.RetargetPrimitiveTypesByTypeCode); if (oldConstant.Kind == TypedConstantKind.Array) { var newArray = RetargetAttributeConstructorArguments(oldConstant.Values); if (!TypeSymbol.Equals(newConstantType, oldConstantType, TypeCompareKind.ConsiderEverything2) || newArray != oldConstant.Values) { typedConstantChanged = true; return new TypedConstant(newConstantType, newArray); } else { return oldConstant; } } object newConstantValue; object oldConstantValue = oldConstant.ValueInternal; if ((oldConstant.Kind == TypedConstantKind.Type) && (oldConstantValue != null)) { newConstantValue = Retarget((TypeSymbol)oldConstantValue, RetargetOptions.RetargetPrimitiveTypesByTypeCode); } else { newConstantValue = oldConstantValue; } if (!TypeSymbol.Equals(newConstantType, oldConstantType, TypeCompareKind.ConsiderEverything2) || newConstantValue != oldConstantValue) { typedConstantChanged = true; return new TypedConstant(newConstantType, oldConstant.Kind, newConstantValue); } else { return oldConstant; } } private ImmutableArray<KeyValuePair<string, TypedConstant>> RetargetAttributeNamedArguments(ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments) { var retargetedArguments = namedArguments; bool argumentsHaveChanged = false; if (namedArguments.Any()) { var newArguments = ArrayBuilder<KeyValuePair<string, TypedConstant>>.GetInstance(namedArguments.Length); foreach (KeyValuePair<string, TypedConstant> oldArgument in namedArguments) { TypedConstant oldConstant = oldArgument.Value; bool typedConstantChanged = false; TypedConstant newConstant = RetargetTypedConstant(oldConstant, ref typedConstantChanged); if (typedConstantChanged) { newArguments.Add(new KeyValuePair<string, TypedConstant>(oldArgument.Key, newConstant)); argumentsHaveChanged = true; } else { newArguments.Add(oldArgument); } } if (argumentsHaveChanged) { retargetedArguments = newArguments.ToImmutable(); } newArguments.Free(); } return retargetedArguments; } // Get the retargeted attributes internal ImmutableArray<CSharpAttributeData> GetRetargetedAttributes( ImmutableArray<CSharpAttributeData> underlyingAttributes, ref ImmutableArray<CSharpAttributeData> lazyCustomAttributes) { if (lazyCustomAttributes.IsDefault) { // Retarget the attributes ImmutableArray<CSharpAttributeData> retargetedAttributes = this.RetargetAttributes(underlyingAttributes); ImmutableInterlocked.InterlockedCompareExchange(ref lazyCustomAttributes, retargetedAttributes, default(ImmutableArray<CSharpAttributeData>)); } return lazyCustomAttributes; } public override Symbol VisitModule(ModuleSymbol symbol, RetargetOptions options) { // We shouldn't run into any other module, but the underlying module Debug.Assert(ReferenceEquals(symbol, _retargetingModule.UnderlyingModule)); return _retargetingModule; } public override Symbol VisitNamespace(NamespaceSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitNamedType(NamedTypeSymbol symbol, RetargetOptions options) { return Retarget(symbol, options); } public override Symbol VisitArrayType(ArrayTypeSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitPointerType(PointerTypeSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitFunctionPointerType(FunctionPointerTypeSymbol symbol, RetargetOptions argument) { return Retarget(symbol); } public override Symbol VisitMethod(MethodSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitParameter(ParameterSymbol symbol, RetargetOptions options) { throw ExceptionUtilities.Unreachable; } public override Symbol VisitField(FieldSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitProperty(PropertySymbol symbol, RetargetOptions argument) { return Retarget(symbol); } public override Symbol VisitTypeParameter(TypeParameterSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitErrorType(ErrorTypeSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitEvent(EventSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol, RetargetOptions argument) { // TODO(cyrusn): What's the right thing to do here? return symbol; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting { internal enum RetargetOptions : byte { RetargetPrimitiveTypesByName = 0, RetargetPrimitiveTypesByTypeCode = 1, } internal partial class RetargetingModuleSymbol { /// <summary> /// Retargeting map from underlying module to this one. /// </summary> private readonly ConcurrentDictionary<Symbol, Symbol> _symbolMap = new ConcurrentDictionary<Symbol, Symbol>(concurrencyLevel: 2, capacity: 4); private readonly Func<Symbol, RetargetingMethodSymbol> _createRetargetingMethod; private readonly Func<Symbol, RetargetingNamespaceSymbol> _createRetargetingNamespace; private readonly Func<Symbol, RetargetingTypeParameterSymbol> _createRetargetingTypeParameter; private readonly Func<Symbol, RetargetingNamedTypeSymbol> _createRetargetingNamedType; private readonly Func<Symbol, FieldSymbol> _createRetargetingField; private readonly Func<Symbol, RetargetingPropertySymbol> _createRetargetingProperty; private readonly Func<Symbol, RetargetingEventSymbol> _createRetargetingEvent; private RetargetingMethodSymbol CreateRetargetingMethod(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); return new RetargetingMethodSymbol(this, (MethodSymbol)symbol); } private RetargetingNamespaceSymbol CreateRetargetingNamespace(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); return new RetargetingNamespaceSymbol(this, (NamespaceSymbol)symbol); } private RetargetingNamedTypeSymbol CreateRetargetingNamedType(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); return new RetargetingNamedTypeSymbol(this, (NamedTypeSymbol)symbol); } private FieldSymbol CreateRetargetingField(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); if (symbol is TupleErrorFieldSymbol tupleErrorField) { var correspondingTupleField = tupleErrorField.CorrespondingTupleField; Debug.Assert(correspondingTupleField is TupleErrorFieldSymbol); var retargetedCorrespondingDefaultFieldOpt = (correspondingTupleField == (object)tupleErrorField) ? null : (TupleErrorFieldSymbol)RetargetingTranslator.Retarget(correspondingTupleField); return new TupleErrorFieldSymbol( RetargetingTranslator.Retarget(tupleErrorField.ContainingType, RetargetOptions.RetargetPrimitiveTypesByName), tupleErrorField.Name, tupleErrorField.TupleElementIndex, tupleErrorField.Locations.IsEmpty ? null : tupleErrorField.Locations[0], this.RetargetingTranslator.Retarget(tupleErrorField.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), tupleErrorField.GetUseSiteInfo().DiagnosticInfo, tupleErrorField.IsImplicitlyDeclared, retargetedCorrespondingDefaultFieldOpt); } return new RetargetingFieldSymbol(this, (FieldSymbol)symbol); } private RetargetingPropertySymbol CreateRetargetingProperty(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); return new RetargetingPropertySymbol(this, (PropertySymbol)symbol); } private RetargetingEventSymbol CreateRetargetingEvent(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); return new RetargetingEventSymbol(this, (EventSymbol)symbol); } private RetargetingTypeParameterSymbol CreateRetargetingTypeParameter(Symbol symbol) { Debug.Assert(ReferenceEquals(symbol.ContainingModule, _underlyingModule)); return new RetargetingTypeParameterSymbol(this, (TypeParameterSymbol)symbol); } internal class RetargetingSymbolTranslator : CSharpSymbolVisitor<RetargetOptions, Symbol> { private readonly RetargetingModuleSymbol _retargetingModule; public RetargetingSymbolTranslator(RetargetingModuleSymbol retargetingModule) { Debug.Assert((object)retargetingModule != null); _retargetingModule = retargetingModule; } /// <summary> /// Retargeting map from underlying module to the retargeting module. /// </summary> private ConcurrentDictionary<Symbol, Symbol> SymbolMap { get { return _retargetingModule._symbolMap; } } /// <summary> /// RetargetingAssemblySymbol owning retargetingModule. /// </summary> private RetargetingAssemblySymbol RetargetingAssembly { get { return _retargetingModule._retargetingAssembly; } } /// <summary> /// The underlying ModuleSymbol for retargetingModule. /// </summary> private SourceModuleSymbol UnderlyingModule { get { return _retargetingModule._underlyingModule; } } /// <summary> /// The map that captures information about what assembly should be retargeted /// to what assembly. Key is the AssemblySymbol referenced by the underlying module, /// value is the corresponding AssemblySymbol referenced by the retargeting module, and /// corresponding retargeting map for symbols. /// </summary> private Dictionary<AssemblySymbol, DestinationData> RetargetingAssemblyMap { get { return _retargetingModule._retargetingAssemblyMap; } } public Symbol Retarget(Symbol symbol) { Debug.Assert(symbol.Kind != SymbolKind.NamedType || ((NamedTypeSymbol)symbol).PrimitiveTypeCode == Cci.PrimitiveTypeCode.NotPrimitive); return symbol.Accept(this, RetargetOptions.RetargetPrimitiveTypesByName); } public MarshalPseudoCustomAttributeData Retarget(MarshalPseudoCustomAttributeData marshallingInfo) { // Retarget by type code - primitive types are encoded in short form in an attribute signature: return marshallingInfo?.WithTranslatedTypes<TypeSymbol, RetargetingSymbolTranslator>( (type, translator) => translator.Retarget(type, RetargetOptions.RetargetPrimitiveTypesByTypeCode), this); } public TypeSymbol Retarget(TypeSymbol symbol, RetargetOptions options) { return (TypeSymbol)symbol.Accept(this, options); } public TypeWithAnnotations Retarget(TypeWithAnnotations underlyingType, RetargetOptions options, NamedTypeSymbol asDynamicIfNoPiaContainingType = null) { var newTypeSymbol = Retarget(underlyingType.Type, options); if ((object)asDynamicIfNoPiaContainingType != null) { newTypeSymbol = newTypeSymbol.AsDynamicIfNoPia(asDynamicIfNoPiaContainingType); } bool modifiersHaveChanged; var newModifiers = RetargetModifiers(underlyingType.CustomModifiers, out modifiersHaveChanged); if (modifiersHaveChanged || !TypeSymbol.Equals(underlyingType.Type, newTypeSymbol, TypeCompareKind.ConsiderEverything2)) { return underlyingType.WithTypeAndModifiers(newTypeSymbol, newModifiers); } return underlyingType; } public NamespaceSymbol Retarget(NamespaceSymbol ns) { return (NamespaceSymbol)this.SymbolMap.GetOrAdd(ns, _retargetingModule._createRetargetingNamespace); } private NamedTypeSymbol RetargetNamedTypeDefinition(NamedTypeSymbol type, RetargetOptions options) { Debug.Assert(type.IsDefinition); if (type.IsNativeIntegerType) { var result = RetargetNamedTypeDefinition(type.NativeIntegerUnderlyingType, options); return result.SpecialType == SpecialType.None ? result : result.AsNativeInteger(); } // Before we do anything else, check if we need to do special retargeting // for primitive type references encoded with enum values in metadata signatures. if (options == RetargetOptions.RetargetPrimitiveTypesByTypeCode) { Cci.PrimitiveTypeCode typeCode = type.PrimitiveTypeCode; if (typeCode != Cci.PrimitiveTypeCode.NotPrimitive) { return RetargetingAssembly.GetPrimitiveType(typeCode); } } if (type.Kind == SymbolKind.ErrorType) { return Retarget((ErrorTypeSymbol)type); } AssemblySymbol retargetFrom = type.ContainingAssembly; // Deal with "to be local" NoPia types leaking through source module. // These are the types that are coming from assemblies linked (/l-ed) // by the compilation that created the source module. bool isLocalType; if (ReferenceEquals(retargetFrom, this.RetargetingAssembly.UnderlyingAssembly)) { Debug.Assert(!retargetFrom.IsLinked); isLocalType = type.IsExplicitDefinitionOfNoPiaLocalType; } else { isLocalType = retargetFrom.IsLinked; } if (isLocalType) { return RetargetNoPiaLocalType(type); } // Perform general retargeting. if (ReferenceEquals(retargetFrom, this.RetargetingAssembly.UnderlyingAssembly)) { return RetargetNamedTypeDefinitionFromUnderlyingAssembly(type); } // Does this type come from one of the retargeted assemblies? DestinationData destination; if (!this.RetargetingAssemblyMap.TryGetValue(retargetFrom, out destination)) { // No need to retarget return type; } // Retarget from one assembly to another type = PerformTypeRetargeting(ref destination, type); this.RetargetingAssemblyMap[retargetFrom] = destination; return type; } private NamedTypeSymbol RetargetNamedTypeDefinitionFromUnderlyingAssembly(NamedTypeSymbol type) { // The type is defined in the underlying assembly. var module = type.ContainingModule; if (ReferenceEquals(module, this.UnderlyingModule)) { Debug.Assert(module.Ordinal == 0); Debug.Assert(!type.IsExplicitDefinitionOfNoPiaLocalType); var container = type.ContainingType; while ((object)container != null) { if (container.IsExplicitDefinitionOfNoPiaLocalType) { // Types nested into local types are not supported. return (NamedTypeSymbol)this.SymbolMap.GetOrAdd(type, new UnsupportedMetadataTypeSymbol()); } container = container.ContainingType; } return (NamedTypeSymbol)this.SymbolMap.GetOrAdd(type, _retargetingModule._createRetargetingNamedType); } else { // The type is defined in one of the added modules Debug.Assert(module.Ordinal > 0); PEModuleSymbol addedModule = (PEModuleSymbol)this.RetargetingAssembly.Modules[module.Ordinal]; Debug.Assert(ReferenceEquals(((PEModuleSymbol)module).Module, addedModule.Module)); return RetargetNamedTypeDefinition((PENamedTypeSymbol)type, addedModule); } } private NamedTypeSymbol RetargetNoPiaLocalType(NamedTypeSymbol type) { NamedTypeSymbol cached; var map = this.RetargetingAssembly.NoPiaUnificationMap; if (map.TryGetValue(type, out cached)) { return cached; } NamedTypeSymbol result; if (type.ContainingSymbol.Kind != SymbolKind.NamedType && type.Arity == 0) { // Get type's identity bool isInterface = type.IsInterface; bool hasGuid = false; string interfaceGuid = null; string scope = null; if (isInterface) { // Get type's Guid hasGuid = type.GetGuidString(out interfaceGuid); } MetadataTypeName name = MetadataTypeName.FromFullName(type.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat), forcedArity: type.Arity); string identifier = null; if ((object)type.ContainingModule == (object)_retargetingModule.UnderlyingModule) { // This is a local type explicitly declared in source. Get information from TypeIdentifier attribute. foreach (var attrData in type.GetAttributes()) { int signatureIndex = attrData.GetTargetAttributeSignatureIndex(type, AttributeDescription.TypeIdentifierAttribute); if (signatureIndex != -1) { Debug.Assert(signatureIndex == 0 || signatureIndex == 1); if (signatureIndex == 1 && attrData.CommonConstructorArguments.Length == 2) { scope = attrData.CommonConstructorArguments[0].ValueInternal as string; identifier = attrData.CommonConstructorArguments[1].ValueInternal as string; } break; } } } else { Debug.Assert((object)type.ContainingAssembly != (object)RetargetingAssembly.UnderlyingAssembly); // Note, this logic should match the one in EmbeddedType.Cci.IReference.GetAttributes. // Here we are trying to predict what attributes we will emit on embedded type, which corresponds the // type we are retargeting. That function actually emits the attributes. if (!(hasGuid && isInterface)) { type.ContainingAssembly.GetGuidString(out scope); identifier = name.FullName; } } result = MetadataDecoder.SubstituteNoPiaLocalType( ref name, isInterface, type.BaseTypeNoUseSiteDiagnostics, interfaceGuid, scope, identifier, RetargetingAssembly); Debug.Assert((object)result != null); } else { // TODO: report better error? result = new UnsupportedMetadataTypeSymbol(); } cached = map.GetOrAdd(type, result); return cached; } private static NamedTypeSymbol RetargetNamedTypeDefinition(PENamedTypeSymbol type, PEModuleSymbol addedModule) { Debug.Assert(!type.ContainingModule.Equals(addedModule) && ReferenceEquals(((PEModuleSymbol)type.ContainingModule).Module, addedModule.Module)); TypeSymbol cached; if (addedModule.TypeHandleToTypeMap.TryGetValue(type.Handle, out cached)) { return (NamedTypeSymbol)cached; } NamedTypeSymbol result; NamedTypeSymbol containingType = type.ContainingType; MetadataTypeName mdName; if ((object)containingType != null) { // Nested type. We need to retarget // the enclosing type and then go back and get the type we are interested in. NamedTypeSymbol scope = RetargetNamedTypeDefinition((PENamedTypeSymbol)containingType, addedModule); mdName = MetadataTypeName.FromTypeName(type.MetadataName, forcedArity: type.Arity); result = scope.LookupMetadataType(ref mdName); Debug.Assert((object)result != null && result.Arity == type.Arity); } else { string namespaceName = type.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat); mdName = MetadataTypeName.FromNamespaceAndTypeName(namespaceName, type.MetadataName, forcedArity: type.Arity); result = addedModule.LookupTopLevelMetadataType(ref mdName); Debug.Assert(result.Arity == type.Arity); } return result; } private static NamedTypeSymbol PerformTypeRetargeting( ref DestinationData destination, NamedTypeSymbol type) { NamedTypeSymbol result; if (!destination.SymbolMap.TryGetValue(type, out result)) { // Lookup by name as a TypeRef. NamedTypeSymbol containingType = type.ContainingType; NamedTypeSymbol result1; MetadataTypeName mdName; if ((object)containingType != null) { // This happens if type is a nested class. We need to retarget // the enclosing class and then go back and get the type we are interested in. NamedTypeSymbol scope = PerformTypeRetargeting(ref destination, containingType); mdName = MetadataTypeName.FromTypeName(type.MetadataName, forcedArity: type.Arity); result1 = scope.LookupMetadataType(ref mdName); Debug.Assert((object)result1 != null && result1.Arity == type.Arity); } else { string namespaceName = type.ContainingNamespace.ToDisplayString(SymbolDisplayFormat.QualifiedNameOnlyFormat); mdName = MetadataTypeName.FromNamespaceAndTypeName(namespaceName, type.MetadataName, forcedArity: type.Arity); result1 = destination.To.LookupTopLevelMetadataType(ref mdName, digThroughForwardedTypes: true); Debug.Assert(result1.Arity == type.Arity); } result = destination.SymbolMap.GetOrAdd(type, result1); Debug.Assert(TypeSymbol.Equals(result1, result, TypeCompareKind.ConsiderEverything2)); } return result; } public NamedTypeSymbol Retarget(NamedTypeSymbol type, RetargetOptions options) { NamedTypeSymbol originalDefinition = type.OriginalDefinition; NamedTypeSymbol newDefinition = RetargetNamedTypeDefinition(originalDefinition, options); if (ReferenceEquals(type, originalDefinition)) { return newDefinition; } if (newDefinition.Kind == SymbolKind.ErrorType && !newDefinition.IsGenericType) { return newDefinition; } Debug.Assert(originalDefinition.Arity == 0 || !ReferenceEquals(type.ConstructedFrom, type)); if (type.IsUnboundGenericType) { if (ReferenceEquals(newDefinition, originalDefinition)) { return type; } return newDefinition.AsUnboundGenericType(); } Debug.Assert((object)type.ContainingType == null || !type.ContainingType.IsUnboundGenericType()); // This must be a generic instantiation (i.e. constructed type). NamedTypeSymbol genericType = type; var oldArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); int startOfNonInterfaceArguments = int.MaxValue; // Collect generic arguments for the type and its containers. while ((object)genericType != null) { if (startOfNonInterfaceArguments == int.MaxValue && !genericType.IsInterface) { startOfNonInterfaceArguments = oldArguments.Count; } oldArguments.AddRange(genericType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics); genericType = genericType.ContainingType; } bool anythingRetargeted = !originalDefinition.Equals(newDefinition); // retarget the arguments var newArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(oldArguments.Count); foreach (var arg in oldArguments) { var newArg = Retarget(arg, RetargetOptions.RetargetPrimitiveTypesByTypeCode); // generic instantiation is a signature if (!anythingRetargeted && !newArg.IsSameAs(arg)) { anythingRetargeted = true; } newArguments.Add(newArg); } // See if it is or its enclosing type is a non-interface closed over NoPia local types. bool noPiaIllegalGenericInstantiation = IsNoPiaIllegalGenericInstantiation(oldArguments, newArguments, startOfNonInterfaceArguments); oldArguments.Free(); NamedTypeSymbol constructedType; if (!anythingRetargeted) { // Nothing was retargeted, return original type symbol. constructedType = type; } else { // Create symbol for new constructed type and return it. // need to collect type parameters in the same order as we have arguments, // but this should be done for the new definition. genericType = newDefinition; ArrayBuilder<TypeParameterSymbol> newParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(newArguments.Count); // Collect generic arguments for the type and its containers. while ((object)genericType != null) { if (genericType.Arity > 0) { newParameters.AddRange(genericType.TypeParameters); } genericType = genericType.ContainingType; } Debug.Assert(newParameters.Count == newArguments.Count); TypeMap substitution = new TypeMap(newParameters.ToImmutableAndFree(), newArguments.ToImmutable()); constructedType = substitution.SubstituteNamedType(newDefinition).WithTupleDataFrom(type); } newArguments.Free(); if (noPiaIllegalGenericInstantiation) { return new NoPiaIllegalGenericInstantiationSymbol(_retargetingModule, constructedType); } return constructedType; } private bool IsNoPiaIllegalGenericInstantiation(ArrayBuilder<TypeWithAnnotations> oldArguments, ArrayBuilder<TypeWithAnnotations> newArguments, int startOfNonInterfaceArguments) { // TODO: Do we need to check constraints on type parameters as well? if (this.UnderlyingModule.ContainsExplicitDefinitionOfNoPiaLocalTypes) { for (int i = startOfNonInterfaceArguments; i < oldArguments.Count; i++) { if (IsOrClosedOverAnExplicitLocalType(oldArguments[i].Type)) { return true; } } } ImmutableArray<AssemblySymbol> assembliesToEmbedTypesFrom = this.UnderlyingModule.GetAssembliesToEmbedTypesFrom(); if (assembliesToEmbedTypesFrom.Length > 0) { for (int i = startOfNonInterfaceArguments; i < oldArguments.Count; i++) { if (MetadataDecoder.IsOrClosedOverATypeFromAssemblies(oldArguments[i].Type, assembliesToEmbedTypesFrom)) { return true; } } } ImmutableArray<AssemblySymbol> linkedAssemblies = RetargetingAssembly.GetLinkedReferencedAssemblies(); if (!linkedAssemblies.IsDefaultOrEmpty) { for (int i = startOfNonInterfaceArguments; i < newArguments.Count; i++) { if (MetadataDecoder.IsOrClosedOverATypeFromAssemblies(newArguments[i].Type, linkedAssemblies)) { return true; } } } return false; } /// <summary> /// Perform a check whether the type or at least one of its generic arguments /// is an explicitly defined local type. The check is performed recursively. /// </summary> private bool IsOrClosedOverAnExplicitLocalType(TypeSymbol symbol) { switch (symbol.Kind) { case SymbolKind.TypeParameter: return false; case SymbolKind.ArrayType: return IsOrClosedOverAnExplicitLocalType(((ArrayTypeSymbol)symbol).ElementType); case SymbolKind.PointerType: return IsOrClosedOverAnExplicitLocalType(((PointerTypeSymbol)symbol).PointedAtType); case SymbolKind.DynamicType: return false; case SymbolKind.ErrorType: case SymbolKind.NamedType: var namedType = (NamedTypeSymbol)symbol; if ((object)symbol.OriginalDefinition.ContainingModule == (object)_retargetingModule.UnderlyingModule && namedType.IsExplicitDefinitionOfNoPiaLocalType) { return true; } do { foreach (var argument in namedType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics) { if (IsOrClosedOverAnExplicitLocalType(argument.Type)) { return true; } } namedType = namedType.ContainingType; } while ((object)namedType != null); return false; default: throw ExceptionUtilities.UnexpectedValue(symbol.Kind); } } public virtual TypeParameterSymbol Retarget(TypeParameterSymbol typeParameter) { return (TypeParameterSymbol)this.SymbolMap.GetOrAdd(typeParameter, _retargetingModule._createRetargetingTypeParameter); } public ArrayTypeSymbol Retarget(ArrayTypeSymbol type) { TypeWithAnnotations oldElement = type.ElementTypeWithAnnotations; TypeWithAnnotations newElement = Retarget(oldElement, RetargetOptions.RetargetPrimitiveTypesByTypeCode); if (oldElement.IsSameAs(newElement)) { return type; } if (type.IsSZArray) { return ArrayTypeSymbol.CreateSZArray(this.RetargetingAssembly, newElement); } return ArrayTypeSymbol.CreateMDArray(this.RetargetingAssembly, newElement, type.Rank, type.Sizes, type.LowerBounds); } internal ImmutableArray<CustomModifier> RetargetModifiers(ImmutableArray<CustomModifier> oldModifiers, out bool modifiersHaveChanged) { ArrayBuilder<CustomModifier> newModifiers = null; for (int i = 0; i < oldModifiers.Length; i++) { var oldModifier = oldModifiers[i]; NamedTypeSymbol oldModifierSymbol = ((CSharpCustomModifier)oldModifier).ModifierSymbol; NamedTypeSymbol newModifierSymbol = Retarget(oldModifierSymbol, RetargetOptions.RetargetPrimitiveTypesByName); // should be retargeted by name if (!newModifierSymbol.Equals(oldModifierSymbol)) { if (newModifiers == null) { newModifiers = ArrayBuilder<CustomModifier>.GetInstance(oldModifiers.Length); newModifiers.AddRange(oldModifiers, i); } newModifiers.Add(oldModifier.IsOptional ? CSharpCustomModifier.CreateOptional(newModifierSymbol) : CSharpCustomModifier.CreateRequired(newModifierSymbol)); } else if (newModifiers != null) { newModifiers.Add(oldModifier); } } Debug.Assert(newModifiers == null || newModifiers.Count == oldModifiers.Length); modifiersHaveChanged = (newModifiers != null); return modifiersHaveChanged ? newModifiers.ToImmutableAndFree() : oldModifiers; } public PointerTypeSymbol Retarget(PointerTypeSymbol type) { TypeWithAnnotations oldPointed = type.PointedAtTypeWithAnnotations; TypeWithAnnotations newPointed = Retarget(oldPointed, RetargetOptions.RetargetPrimitiveTypesByTypeCode); if (oldPointed.IsSameAs(newPointed)) { return type; } return new PointerTypeSymbol(newPointed); } public FunctionPointerTypeSymbol Retarget(FunctionPointerTypeSymbol type) { var signature = type.Signature; var newReturn = Retarget(signature.ReturnTypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); var newRefModifiers = RetargetModifiers(signature.RefCustomModifiers, out bool symbolModified); symbolModified = symbolModified || !signature.ReturnTypeWithAnnotations.IsSameAs(newReturn); var newParameterTypes = ImmutableArray<TypeWithAnnotations>.Empty; ImmutableArray<ImmutableArray<CustomModifier>> newParamModifiers = default; var paramCount = signature.ParameterCount; if (paramCount > 0) { var newParameterTypesBuilder = ArrayBuilder<TypeWithAnnotations>.GetInstance(paramCount); var newParameterCustomModifiersBuilder = ArrayBuilder<ImmutableArray<CustomModifier>>.GetInstance(paramCount); bool parametersModified = false; foreach (var parameter in signature.Parameters) { var newParameterType = Retarget(parameter.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); var newModifiers = RetargetModifiers(parameter.RefCustomModifiers, out bool customModifiersChanged); newParameterTypesBuilder.Add(newParameterType); newParameterCustomModifiersBuilder.Add(newModifiers); parametersModified = parametersModified || !parameter.TypeWithAnnotations.IsSameAs(newParameterType) || customModifiersChanged; } if (parametersModified) { newParameterTypes = newParameterTypesBuilder.ToImmutableAndFree(); newParamModifiers = newParameterCustomModifiersBuilder.ToImmutableAndFree(); symbolModified = true; } else { newParameterTypesBuilder.Free(); newParameterCustomModifiersBuilder.Free(); newParameterTypes = signature.ParameterTypesWithAnnotations; } } if (symbolModified) { return type.SubstituteTypeSymbol(newReturn, newParameterTypes, newRefModifiers, newParamModifiers); } else { return type; } } public static ErrorTypeSymbol Retarget(ErrorTypeSymbol type) { // TODO: if it is a missing symbol error but no longer missing in the target assembly, then we can resolve it here. var useSiteDiagnostic = type.GetUseSiteInfo().DiagnosticInfo; if (useSiteDiagnostic?.Severity == DiagnosticSeverity.Error) { return type; } // A retargeted error symbol must trigger an error on use so that a dependent compilation won't // improperly succeed. We therefore ensure we have a use-site diagnostic. return (type as ExtendedErrorTypeSymbol)?.AsUnreported() ?? // preserve diagnostic information if possible new ExtendedErrorTypeSymbol(type, type.ResultKind, type.ErrorInfo ?? new CSDiagnosticInfo(ErrorCode.ERR_ErrorInReferencedAssembly, type.ContainingAssembly?.Identity.GetDisplayName() ?? string.Empty), true); } public ImmutableArray<Symbol> Retarget(ImmutableArray<Symbol> arr) { var symbols = ArrayBuilder<Symbol>.GetInstance(arr.Length); foreach (var s in arr) { symbols.Add(Retarget(s)); } return symbols.ToImmutableAndFree(); } public ImmutableArray<NamedTypeSymbol> Retarget(ImmutableArray<NamedTypeSymbol> sequence) { var result = ArrayBuilder<NamedTypeSymbol>.GetInstance(sequence.Length); foreach (var nts in sequence) { // If there is an error type in the base type list, it will end up in the interface list (rather // than as the base class), so it might end up passing through here. If it is specified using // a primitive type keyword, then it will have a primitive type code, even if corlib is missing. Debug.Assert(nts.TypeKind == TypeKind.Error || nts.PrimitiveTypeCode == Cci.PrimitiveTypeCode.NotPrimitive); result.Add(Retarget(nts, RetargetOptions.RetargetPrimitiveTypesByName)); } return result.ToImmutableAndFree(); } public ImmutableArray<TypeSymbol> Retarget(ImmutableArray<TypeSymbol> sequence) { var result = ArrayBuilder<TypeSymbol>.GetInstance(sequence.Length); foreach (var ts in sequence) { // In incorrect code, a type parameter constraint list can contain primitive types. Debug.Assert(ts.TypeKind == TypeKind.Error || ts.PrimitiveTypeCode == Cci.PrimitiveTypeCode.NotPrimitive); result.Add(Retarget(ts, RetargetOptions.RetargetPrimitiveTypesByName)); } return result.ToImmutableAndFree(); } public ImmutableArray<TypeWithAnnotations> Retarget(ImmutableArray<TypeWithAnnotations> sequence) { var result = ArrayBuilder<TypeWithAnnotations>.GetInstance(sequence.Length); foreach (var ts in sequence) { result.Add(Retarget(ts, RetargetOptions.RetargetPrimitiveTypesByName)); } return result.ToImmutableAndFree(); } public ImmutableArray<TypeParameterSymbol> Retarget(ImmutableArray<TypeParameterSymbol> list) { var parameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(list.Length); foreach (var tps in list) { parameters.Add(Retarget(tps)); } return parameters.ToImmutableAndFree(); } public MethodSymbol Retarget(MethodSymbol method) { Debug.Assert(ReferenceEquals(method.ContainingModule, this.UnderlyingModule)); Debug.Assert(ReferenceEquals(method, method.OriginalDefinition)); return (MethodSymbol)this.SymbolMap.GetOrAdd(method, _retargetingModule._createRetargetingMethod); } public MethodSymbol Retarget(MethodSymbol method, IEqualityComparer<MethodSymbol> retargetedMethodComparer) { Debug.Assert((object)method == method.ConstructedFrom); if (ReferenceEquals(method.ContainingModule, this.UnderlyingModule) && ReferenceEquals(method, method.OriginalDefinition)) { return Retarget(method); } var containingType = method.ContainingType; var retargetedType = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName); if (ReferenceEquals(retargetedType, containingType)) { return method; } if (!containingType.IsDefinition) { Debug.Assert(!retargetedType.IsDefinition); var retargetedDefinition = Retarget(method.OriginalDefinition, retargetedMethodComparer); if (retargetedDefinition is null) { return null; } return retargetedDefinition.AsMember(retargetedType); } Debug.Assert(retargetedType.IsDefinition); // NB: may return null if the method cannot be found in the retargeted type (e.g. removed in a subsequent version) return FindMethodInRetargetedType(method, retargetedType, retargetedMethodComparer); } public FieldSymbol Retarget(FieldSymbol field) { return (FieldSymbol)this.SymbolMap.GetOrAdd(field, _retargetingModule._createRetargetingField); } public PropertySymbol Retarget(PropertySymbol property) { Debug.Assert(ReferenceEquals(property.ContainingModule, this.UnderlyingModule)); Debug.Assert(ReferenceEquals(property, property.OriginalDefinition)); return (PropertySymbol)this.SymbolMap.GetOrAdd(property, _retargetingModule._createRetargetingProperty); } public PropertySymbol Retarget(PropertySymbol property, IEqualityComparer<PropertySymbol> retargetedPropertyComparer) { if (ReferenceEquals(property.ContainingModule, this.UnderlyingModule) && ReferenceEquals(property, property.OriginalDefinition)) { return Retarget(property); } var containingType = property.ContainingType; var retargetedType = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName); // NB: may return null if the property cannot be found in the retargeted type (e.g. removed in a subsequent version) return ReferenceEquals(retargetedType, containingType) ? property : FindPropertyInRetargetedType(property, retargetedType, retargetedPropertyComparer); } public EventSymbol Retarget(EventSymbol @event) { if (ReferenceEquals(@event.ContainingModule, this.UnderlyingModule) && ReferenceEquals(@event, @event.OriginalDefinition)) { return (EventSymbol)this.SymbolMap.GetOrAdd(@event, _retargetingModule._createRetargetingEvent); } var containingType = @event.ContainingType; var retargetedType = Retarget(containingType, RetargetOptions.RetargetPrimitiveTypesByName); // NB: may return null if the event cannot be found in the retargeted type (e.g. removed in a subsequent version) return ReferenceEquals(retargetedType, containingType) ? @event : FindEventInRetargetedType(@event, retargetedType); } private MethodSymbol FindMethodInRetargetedType(MethodSymbol method, NamedTypeSymbol retargetedType, IEqualityComparer<MethodSymbol> retargetedMethodComparer) { return RetargetedTypeMethodFinder.Find(this, method, retargetedType, retargetedMethodComparer); } private class RetargetedTypeMethodFinder : RetargetingSymbolTranslator { private readonly NamedTypeSymbol _retargetedType; private readonly MethodSymbol _toFind; private RetargetedTypeMethodFinder(RetargetingModuleSymbol retargetingModule, NamedTypeSymbol retargetedType, MethodSymbol toFind) : base(retargetingModule) { _retargetedType = retargetedType; _toFind = toFind; } public static MethodSymbol Find(RetargetingSymbolTranslator translator, MethodSymbol method, NamedTypeSymbol retargetedType, IEqualityComparer<MethodSymbol> retargetedMethodComparer) { if (!method.IsGenericMethod && !retargetedType.IsGenericType) { return FindWorker(translator, method, retargetedType, retargetedMethodComparer); } // A generic method or a method in generic type needs special handling because its signature is very likely // to refer to method's or type's type parameters. var finder = new RetargetedTypeMethodFinder(translator._retargetingModule, retargetedType, method); return FindWorker(finder, method, retargetedType, retargetedMethodComparer); } private static MethodSymbol FindWorker ( RetargetingSymbolTranslator translator, MethodSymbol method, NamedTypeSymbol retargetedType, IEqualityComparer<MethodSymbol> retargetedMethodComparer ) { bool modifiersHaveChanged_Ignored; //ignored var targetParamsBuilder = ArrayBuilder<ParameterSymbol>.GetInstance(method.Parameters.Length); foreach (var param in method.Parameters) { targetParamsBuilder.Add( new SignatureOnlyParameterSymbol( translator.Retarget(param.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), translator.RetargetModifiers(param.RefCustomModifiers, out modifiersHaveChanged_Ignored), param.IsParams, param.RefKind)); } // We will be using this symbol only for the purpose of method signature comparison, // IndexedTypeParameterSymbols should work just fine as the type parameters for the method. // We can't produce "real" TypeParameterSymbols without finding the method first and this // is what we are trying to do right now. var targetMethod = new SignatureOnlyMethodSymbol( method.Name, retargetedType, method.MethodKind, method.CallingConvention, IndexedTypeParameterSymbol.TakeSymbols(method.Arity), targetParamsBuilder.ToImmutableAndFree(), method.RefKind, method.IsInitOnly, method.IsStatic, translator.Retarget(method.ReturnTypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), translator.RetargetModifiers(method.RefCustomModifiers, out modifiersHaveChanged_Ignored), ImmutableArray<MethodSymbol>.Empty); foreach (var retargetedMember in retargetedType.GetMembers(method.Name)) { if (retargetedMember.Kind == SymbolKind.Method) { var retargetedMethod = (MethodSymbol)retargetedMember; if (retargetedMethodComparer.Equals(retargetedMethod, targetMethod)) { return retargetedMethod; } } } return null; } public override TypeParameterSymbol Retarget(TypeParameterSymbol typeParameter) { if (typeParameter.TypeParameterKind == TypeParameterKind.Method) { Debug.Assert((object)typeParameter.ContainingSymbol == _toFind); // The method symbol we are building will be using IndexedTypeParameterSymbols as // its type parameters, therefore, we should return them here as well. return IndexedTypeParameterSymbol.GetTypeParameter(typeParameter.Ordinal); } NamedTypeSymbol containingType = _toFind.ContainingType; NamedTypeSymbol retargetedContainingType = _retargetedType; do { if ((object)containingType == typeParameter.ContainingSymbol) { return retargetedContainingType.TypeParameters[typeParameter.Ordinal]; } containingType = containingType.ContainingType; retargetedContainingType = retargetedContainingType.ContainingType; } while (containingType is object); throw ExceptionUtilities.Unreachable; } } private PropertySymbol FindPropertyInRetargetedType(PropertySymbol property, NamedTypeSymbol retargetedType, IEqualityComparer<PropertySymbol> retargetedPropertyComparer) { bool modifiersHaveChanged_Ignored; //ignored var targetParamsBuilder = ArrayBuilder<ParameterSymbol>.GetInstance(property.Parameters.Length); foreach (var param in property.Parameters) { targetParamsBuilder.Add( new SignatureOnlyParameterSymbol( Retarget(param.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), RetargetModifiers(param.RefCustomModifiers, out modifiersHaveChanged_Ignored), param.IsParams, param.RefKind)); } var targetProperty = new SignatureOnlyPropertySymbol( property.Name, retargetedType, targetParamsBuilder.ToImmutableAndFree(), property.RefKind, Retarget(property.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode), RetargetModifiers(property.RefCustomModifiers, out modifiersHaveChanged_Ignored), property.IsStatic, ImmutableArray<PropertySymbol>.Empty); foreach (var retargetedMember in retargetedType.GetMembers(property.Name)) { if (retargetedMember.Kind == SymbolKind.Property) { var retargetedProperty = (PropertySymbol)retargetedMember; if (retargetedPropertyComparer.Equals(retargetedProperty, targetProperty)) { return retargetedProperty; } } } return null; } private EventSymbol FindEventInRetargetedType(EventSymbol @event, NamedTypeSymbol retargetedType) { var targetType = Retarget(@event.TypeWithAnnotations, RetargetOptions.RetargetPrimitiveTypesByTypeCode); foreach (var retargetedMember in retargetedType.GetMembers(@event.Name)) { if (retargetedMember.Kind == SymbolKind.Event) { var retargetedEvent = (EventSymbol)retargetedMember; if (TypeSymbol.Equals(retargetedEvent.Type, targetType.Type, TypeCompareKind.ConsiderEverything2)) { return retargetedEvent; } } } return null; } internal ImmutableArray<CustomModifier> RetargetModifiers( ImmutableArray<CustomModifier> oldModifiers, ref ImmutableArray<CustomModifier> lazyCustomModifiers) { if (lazyCustomModifiers.IsDefault) { bool modifiersHaveChanged; ImmutableArray<CustomModifier> newModifiers = this.RetargetModifiers(oldModifiers, out modifiersHaveChanged); ImmutableInterlocked.InterlockedCompareExchange(ref lazyCustomModifiers, newModifiers, default(ImmutableArray<CustomModifier>)); } return lazyCustomModifiers; } private ImmutableArray<CSharpAttributeData> RetargetAttributes(ImmutableArray<CSharpAttributeData> oldAttributes) { return oldAttributes.SelectAsArray((a, t) => t.RetargetAttributeData(a), this); } internal IEnumerable<CSharpAttributeData> RetargetAttributes(IEnumerable<CSharpAttributeData> attributes) { #if DEBUG SynthesizedAttributeData x = null; SourceAttributeData y = x; // Code below relies on the fact that SynthesizedAttributeData derives from SourceAttributeData. x = (SynthesizedAttributeData)y; #endif foreach (var attributeData in attributes) { yield return this.RetargetAttributeData(attributeData); } } private CSharpAttributeData RetargetAttributeData(CSharpAttributeData oldAttributeData) { SourceAttributeData oldAttribute = (SourceAttributeData)oldAttributeData; MethodSymbol oldAttributeCtor = oldAttribute.AttributeConstructor; MethodSymbol newAttributeCtor = (object)oldAttributeCtor == null ? null : Retarget(oldAttributeCtor, MemberSignatureComparer.RetargetedExplicitImplementationComparer); NamedTypeSymbol oldAttributeType = oldAttribute.AttributeClass; NamedTypeSymbol newAttributeType; if ((object)newAttributeCtor != null) { newAttributeType = newAttributeCtor.ContainingType; } else if ((object)oldAttributeType != null) { newAttributeType = Retarget(oldAttributeType, RetargetOptions.RetargetPrimitiveTypesByTypeCode); } else { newAttributeType = null; } ImmutableArray<TypedConstant> oldAttributeCtorArguments = oldAttribute.CommonConstructorArguments; ImmutableArray<TypedConstant> newAttributeCtorArguments = RetargetAttributeConstructorArguments(oldAttributeCtorArguments); ImmutableArray<KeyValuePair<string, TypedConstant>> oldAttributeNamedArguments = oldAttribute.CommonNamedArguments; ImmutableArray<KeyValuePair<string, TypedConstant>> newAttributeNamedArguments = RetargetAttributeNamedArguments(oldAttributeNamedArguments); // Must create a RetargetingAttributeData even if the types and // arguments are unchanged since the AttributeData instance is // used to resolve System.Type which may require retargeting. return new RetargetingAttributeData( oldAttribute.ApplicationSyntaxReference, newAttributeType, newAttributeCtor, newAttributeCtorArguments, oldAttribute.ConstructorArgumentsSourceIndices, newAttributeNamedArguments, oldAttribute.HasErrors, oldAttribute.IsConditionallyOmitted); } private ImmutableArray<TypedConstant> RetargetAttributeConstructorArguments(ImmutableArray<TypedConstant> constructorArguments) { ImmutableArray<TypedConstant> retargetedArguments = constructorArguments; bool argumentsHaveChanged = false; if (!constructorArguments.IsDefault && constructorArguments.Any()) { var newArguments = ArrayBuilder<TypedConstant>.GetInstance(constructorArguments.Length); foreach (TypedConstant oldArgument in constructorArguments) { TypedConstant retargetedArgument = RetargetTypedConstant(oldArgument, ref argumentsHaveChanged); newArguments.Add(retargetedArgument); } if (argumentsHaveChanged) { retargetedArguments = newArguments.ToImmutable(); } newArguments.Free(); } return retargetedArguments; } private TypedConstant RetargetTypedConstant(TypedConstant oldConstant, ref bool typedConstantChanged) { TypeSymbol oldConstantType = (TypeSymbol)oldConstant.TypeInternal; TypeSymbol newConstantType = (object)oldConstantType == null ? null : Retarget(oldConstantType, RetargetOptions.RetargetPrimitiveTypesByTypeCode); if (oldConstant.Kind == TypedConstantKind.Array) { var newArray = RetargetAttributeConstructorArguments(oldConstant.Values); if (!TypeSymbol.Equals(newConstantType, oldConstantType, TypeCompareKind.ConsiderEverything2) || newArray != oldConstant.Values) { typedConstantChanged = true; return new TypedConstant(newConstantType, newArray); } else { return oldConstant; } } object newConstantValue; object oldConstantValue = oldConstant.ValueInternal; if ((oldConstant.Kind == TypedConstantKind.Type) && (oldConstantValue != null)) { newConstantValue = Retarget((TypeSymbol)oldConstantValue, RetargetOptions.RetargetPrimitiveTypesByTypeCode); } else { newConstantValue = oldConstantValue; } if (!TypeSymbol.Equals(newConstantType, oldConstantType, TypeCompareKind.ConsiderEverything2) || newConstantValue != oldConstantValue) { typedConstantChanged = true; return new TypedConstant(newConstantType, oldConstant.Kind, newConstantValue); } else { return oldConstant; } } private ImmutableArray<KeyValuePair<string, TypedConstant>> RetargetAttributeNamedArguments(ImmutableArray<KeyValuePair<string, TypedConstant>> namedArguments) { var retargetedArguments = namedArguments; bool argumentsHaveChanged = false; if (namedArguments.Any()) { var newArguments = ArrayBuilder<KeyValuePair<string, TypedConstant>>.GetInstance(namedArguments.Length); foreach (KeyValuePair<string, TypedConstant> oldArgument in namedArguments) { TypedConstant oldConstant = oldArgument.Value; bool typedConstantChanged = false; TypedConstant newConstant = RetargetTypedConstant(oldConstant, ref typedConstantChanged); if (typedConstantChanged) { newArguments.Add(new KeyValuePair<string, TypedConstant>(oldArgument.Key, newConstant)); argumentsHaveChanged = true; } else { newArguments.Add(oldArgument); } } if (argumentsHaveChanged) { retargetedArguments = newArguments.ToImmutable(); } newArguments.Free(); } return retargetedArguments; } // Get the retargeted attributes internal ImmutableArray<CSharpAttributeData> GetRetargetedAttributes( ImmutableArray<CSharpAttributeData> underlyingAttributes, ref ImmutableArray<CSharpAttributeData> lazyCustomAttributes) { if (lazyCustomAttributes.IsDefault) { // Retarget the attributes ImmutableArray<CSharpAttributeData> retargetedAttributes = this.RetargetAttributes(underlyingAttributes); ImmutableInterlocked.InterlockedCompareExchange(ref lazyCustomAttributes, retargetedAttributes, default(ImmutableArray<CSharpAttributeData>)); } return lazyCustomAttributes; } public override Symbol VisitModule(ModuleSymbol symbol, RetargetOptions options) { // We shouldn't run into any other module, but the underlying module Debug.Assert(ReferenceEquals(symbol, _retargetingModule.UnderlyingModule)); return _retargetingModule; } public override Symbol VisitNamespace(NamespaceSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitNamedType(NamedTypeSymbol symbol, RetargetOptions options) { return Retarget(symbol, options); } public override Symbol VisitArrayType(ArrayTypeSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitPointerType(PointerTypeSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitFunctionPointerType(FunctionPointerTypeSymbol symbol, RetargetOptions argument) { return Retarget(symbol); } public override Symbol VisitMethod(MethodSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitParameter(ParameterSymbol symbol, RetargetOptions options) { throw ExceptionUtilities.Unreachable; } public override Symbol VisitField(FieldSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitProperty(PropertySymbol symbol, RetargetOptions argument) { return Retarget(symbol); } public override Symbol VisitTypeParameter(TypeParameterSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitErrorType(ErrorTypeSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitEvent(EventSymbol symbol, RetargetOptions options) { return Retarget(symbol); } public override Symbol VisitDynamicType(DynamicTypeSymbol symbol, RetargetOptions argument) { // TODO(cyrusn): What's the right thing to do here? return symbol; } } } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/ExpressionEvaluator/VisualBasic/Test/ExpressionCompiler/DteeTests.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.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class DteeTests Inherits ExpressionCompilerTestBase Private Const s_dteeEntryPointSource = " Imports System.Collections Class HostProc Sub BreakForDebugger() End Sub End Class " Private Const s_dteeEntryPointName = "HostProc.BreakForDebugger" <Fact> Public Sub IsDteeEntryPoint() Const source = " Class HostProc Sub BreakForDebugger() End Sub End Class Class AppDomain Sub ExecuteAssembly() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}) Dim [global] = comp.GlobalNamespace Dim m1 = [global].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [global].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.True(EvaluationContext.IsDteeEntryPoint(m1)) Assert.True(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub IsDteeEntryPoint_Namespace() Const source = " Namespace N Class HostProc Sub BreakForDebugger() End Sub End Class Class AppDomain Sub ExecuteAssembly() End Sub End Class End Namespace " Dim comp = CreateCompilationWithMscorlib40({source}) Dim [namespace] = comp.GlobalNamespace.GetMember(Of NamespaceSymbol)("N") Dim m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.True(EvaluationContext.IsDteeEntryPoint(m1)) Assert.True(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub IsDteeEntryPoint_CaseSensitive() Const source = " Namespace N1 Class HostProc Sub breakfordebugger() End Sub End Class Class AppDomain Sub executeassembly() End Sub End Class End Namespace Namespace N2 Class hostproc Sub BreakForDebugger() End Sub End Class Class appdomain Sub ExecuteAssembly() End Sub End Class End Namespace " Dim comp = CreateCompilationWithMscorlib40({source}) Dim [global] = comp.GlobalNamespace Dim [namespace] = [global].GetMember(Of NamespaceSymbol)("N1") Dim m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.False(EvaluationContext.IsDteeEntryPoint(m1)) Assert.False(EvaluationContext.IsDteeEntryPoint(m2)) [namespace] = [global].GetMember(Of NamespaceSymbol)("N2") m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.False(EvaluationContext.IsDteeEntryPoint(m1)) Assert.False(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub DteeEntryPointImportsIgnored() Dim comp = CreateCompilationWithMscorlib40({s_dteeEntryPointSource}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName()) WithRuntimeInstance(comp, {MscorlibRef}, Sub(runtime) Dim lazyAssemblyReaders = MakeLazyAssemblyReaders(runtime) Dim evalContext = CreateMethodContext(runtime, s_dteeEntryPointName, lazyAssemblyReaders:=lazyAssemblyReaders) Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing ImportsDebugInfoTests.GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("", rootNamespace.Name) Assert.Equal("", currentNamespace.Name) Assert.True(typesAndNamespaces.IsDefault) Assert.Null(aliases) Assert.Null(xmlNamespaces) End Sub) End Sub <Fact> Public Sub ImportStrings_DefaultNamespaces() Dim source1 = " Class C1 Sub M() ' Need a method to which we can attach import custom debug info. End Sub End Class " Dim source2 = " Class C2 Sub M() ' Need a method to which we can attach import custom debug info. End Sub End Class " Dim module1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll.WithRootNamespace("root1")).ToModuleInstance() Dim module2 = CreateCompilationWithMscorlib40({source2}, options:=TestOptions.DebugDll.WithRootNamespace("root2")).ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({module1, module2, MscorlibRef.ToModuleInstance()}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "root1", "root2") End Sub <Fact> Public Sub ImportStrings_ModuleNamespaces() Dim source1 = " Namespace N1 Module M End Module End Namespace Namespace N2 Namespace N3 Module M End Module End Namespace End Namespace Namespace N4 Class C End Class End Namespace " Dim source2 = " Namespace N1 ' Also imported for source1 Module M2 End Module End Namespace Namespace N5 Namespace N6 Module M End Module End Namespace End Namespace Namespace N7 Class C End Class End Namespace " Dim module1 = CreateCompilationWithMscorlib40({source1}, {MsvbRef}, options:=TestOptions.DebugDll).ToModuleInstance() Dim module2 = CreateCompilationWithMscorlib40({source2}, {MsvbRef}, options:=TestOptions.DebugDll).ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({module1, module2, MscorlibRef.ToModuleInstance(), MsvbRef.ToModuleInstance()}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "N1", "N2.N3", "N5.N6") End Sub <Fact> Public Sub ImportStrings_NoMethods() Dim comp = CreateCompilationWithMscorlib40({""}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) WithRuntimeInstance(comp, {MscorlibRef, MsvbRef}, Sub(runtime) ' Since there are no methods in the assembly, there is no import custom debug info, so we ' have no way to find the root namespace. Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub) End Sub <Fact> Public Sub ImportStrings_IgnoreAssemblyWithoutPdb() Dim source1 = " Namespace N1 Module M End Module End Namespace " Dim source2 = " Namespace N2 Module M End Module End Namespace " Dim comp1 = CreateCompilationWithMscorlib40({source1}, {MsvbRef}, options:=TestOptions.ReleaseDll) Dim module1 = comp1.ToModuleInstance(debugFormat:=Nothing) Dim comp2 = CreateCompilationWithMscorlib40({source2}, {MsvbRef}, options:=TestOptions.DebugDll) Dim module2 = comp2.ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({ module1, module2, MscorlibRef.ToModuleInstance(), MsvbRef.ToModuleInstance()}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "N2") End Sub <Fact> Public Sub FalseModule_Nested() ' NOTE: VB only allows top-level module types. Dim ilSource = " .assembly extern Microsoft.VisualBasic { } .class public auto ansi N1.Outer extends [mscorlib]System.Object { .class auto ansi nested public sealed Inner extends [mscorlib]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Inner .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class N1.Outer " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef, MsvbRef}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub FalseModule_Generic() ' NOTE: VB only allows non-generic module types. Dim ilSource = " .assembly extern Microsoft.VisualBasic { } .class public auto ansi sealed N1.M`1<T> extends [mscorlib]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} } // end of class M " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef, MsvbRef}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub FalseModule_Interface() ' NOTE: VB only allows non-interface module types. Dim ilSource = " .assembly extern Microsoft.VisualBasic { } .class interface private abstract auto ansi I { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} } // end of class I " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef, MsvbRef}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub ImportSymbols() Dim source1 = " Namespace N1 Module M Sub M() ' Need a method to record the root namespace. End Sub End Module End Namespace Namespace N2 Module M End Module End Namespace " Dim source2 = " Namespace N1 ' Also imported for source1 Module M2 Sub M() ' Need a method to record the root namespace. End Sub End Module End Namespace Namespace N3 Module M End Module End Namespace " Dim dteeComp = CreateCompilationWithMscorlib40({s_dteeEntryPointSource}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName()) Dim dteeModuleInstance = dteeComp.ToModuleInstance() Dim comp1 = CreateCompilationWithMscorlib40({source1}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) Dim compModuleInstance1 = comp1.ToModuleInstance() Dim comp2 = CreateCompilationWithMscorlib40({source2}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) Dim compModuleInstance2 = comp2.ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({ dteeModuleInstance, compModuleInstance1, compModuleInstance2, MscorlibRef.ToModuleInstance(), MsvbRef.ToModuleInstance()}) Dim lazyAssemblyReaders = MakeLazyAssemblyReaders(runtimeInstance) Dim evalContext = CreateMethodContext(runtimeInstance, s_dteeEntryPointName, lazyAssemblyReaders:=lazyAssemblyReaders) Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing ImportsDebugInfoTests.GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("", rootNamespace.Name) Assert.Equal("", currentNamespace.Name) Assert.Null(aliases) Assert.Null(xmlNamespaces) AssertEx.SetEqual(typesAndNamespaces.Select(Function(tn) tn.NamespaceOrType.ToTestDisplayString()), "root", "root.N1", "root.N2", "root.N3") End Sub Private Shared Function MakeLazyAssemblyReaders(runtimeInstance As RuntimeInstance) As Lazy(Of ImmutableArray(Of AssemblyReaders)) Return New Lazy(Of ImmutableArray(Of AssemblyReaders))( Function() MakeAssemblyReaders(runtimeInstance), LazyThreadSafetyMode.None) End Function Private Shared Function MakeAssemblyReaders(runtimeInstance As RuntimeInstance) As ImmutableArray(Of AssemblyReaders) Return ImmutableArray.CreateRange(runtimeInstance.Modules. Where(Function(instance) instance.SymReader IsNot Nothing). Select(Function(instance) New AssemblyReaders(instance.GetMetadataReader(), instance.SymReader))) End Function Private Shared Sub CheckDteeMethodDebugInfo(methodDebugInfo As MethodDebugInfo(Of TypeSymbol, LocalSymbol), ParamArray namespaceNames As String()) Assert.Equal("", methodDebugInfo.DefaultNamespaceName) Dim importRecordGroups = methodDebugInfo.ImportRecordGroups Assert.Equal(2, importRecordGroups.Length) Dim fileLevelImportRecords As ImmutableArray(Of ImportRecord) = importRecordGroups(0) Dim projectLevelImportRecords As ImmutableArray(Of ImportRecord) = importRecordGroups(1) Assert.Empty(fileLevelImportRecords) AssertEx.All(projectLevelImportRecords, Function(record) record.TargetAssemblyAlias Is Nothing) AssertEx.All(projectLevelImportRecords, Function(record) record.TargetKind = ImportTargetKind.Namespace) AssertEx.All(projectLevelImportRecords, Function(record) record.Alias Is Nothing) AssertEx.SetEqual(projectLevelImportRecords.Select(Function(record) record.TargetString), namespaceNames) 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.IO Imports System.Threading Imports Microsoft.CodeAnalysis.Debugging Imports Microsoft.CodeAnalysis.ExpressionEvaluator Imports Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests Imports Microsoft.CodeAnalysis.Test.Utilities Imports Microsoft.CodeAnalysis.VisualBasic.Symbols Imports Microsoft.CodeAnalysis.VisualBasic.UnitTests Imports Roslyn.Test.PdbUtilities Imports Roslyn.Test.Utilities Imports Xunit Namespace Microsoft.CodeAnalysis.VisualBasic.ExpressionEvaluator.UnitTests Public Class DteeTests Inherits ExpressionCompilerTestBase Private Const s_dteeEntryPointSource = " Imports System.Collections Class HostProc Sub BreakForDebugger() End Sub End Class " Private Const s_dteeEntryPointName = "HostProc.BreakForDebugger" <Fact> Public Sub IsDteeEntryPoint() Const source = " Class HostProc Sub BreakForDebugger() End Sub End Class Class AppDomain Sub ExecuteAssembly() End Sub End Class " Dim comp = CreateCompilationWithMscorlib40({source}) Dim [global] = comp.GlobalNamespace Dim m1 = [global].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [global].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.True(EvaluationContext.IsDteeEntryPoint(m1)) Assert.True(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub IsDteeEntryPoint_Namespace() Const source = " Namespace N Class HostProc Sub BreakForDebugger() End Sub End Class Class AppDomain Sub ExecuteAssembly() End Sub End Class End Namespace " Dim comp = CreateCompilationWithMscorlib40({source}) Dim [namespace] = comp.GlobalNamespace.GetMember(Of NamespaceSymbol)("N") Dim m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.True(EvaluationContext.IsDteeEntryPoint(m1)) Assert.True(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub IsDteeEntryPoint_CaseSensitive() Const source = " Namespace N1 Class HostProc Sub breakfordebugger() End Sub End Class Class AppDomain Sub executeassembly() End Sub End Class End Namespace Namespace N2 Class hostproc Sub BreakForDebugger() End Sub End Class Class appdomain Sub ExecuteAssembly() End Sub End Class End Namespace " Dim comp = CreateCompilationWithMscorlib40({source}) Dim [global] = comp.GlobalNamespace Dim [namespace] = [global].GetMember(Of NamespaceSymbol)("N1") Dim m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") Dim m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.False(EvaluationContext.IsDteeEntryPoint(m1)) Assert.False(EvaluationContext.IsDteeEntryPoint(m2)) [namespace] = [global].GetMember(Of NamespaceSymbol)("N2") m1 = [namespace].GetMember(Of NamedTypeSymbol)("HostProc").GetMember(Of MethodSymbol)("BreakForDebugger") m2 = [namespace].GetMember(Of NamedTypeSymbol)("AppDomain").GetMember(Of MethodSymbol)("ExecuteAssembly") Assert.False(EvaluationContext.IsDteeEntryPoint(m1)) Assert.False(EvaluationContext.IsDteeEntryPoint(m2)) End Sub <Fact> Public Sub DteeEntryPointImportsIgnored() Dim comp = CreateCompilationWithMscorlib40({s_dteeEntryPointSource}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName()) WithRuntimeInstance(comp, {MscorlibRef}, Sub(runtime) Dim lazyAssemblyReaders = MakeLazyAssemblyReaders(runtime) Dim evalContext = CreateMethodContext(runtime, s_dteeEntryPointName, lazyAssemblyReaders:=lazyAssemblyReaders) Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing ImportsDebugInfoTests.GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("", rootNamespace.Name) Assert.Equal("", currentNamespace.Name) Assert.True(typesAndNamespaces.IsDefault) Assert.Null(aliases) Assert.Null(xmlNamespaces) End Sub) End Sub <Fact> Public Sub ImportStrings_DefaultNamespaces() Dim source1 = " Class C1 Sub M() ' Need a method to which we can attach import custom debug info. End Sub End Class " Dim source2 = " Class C2 Sub M() ' Need a method to which we can attach import custom debug info. End Sub End Class " Dim module1 = CreateCompilationWithMscorlib40({source1}, options:=TestOptions.DebugDll.WithRootNamespace("root1")).ToModuleInstance() Dim module2 = CreateCompilationWithMscorlib40({source2}, options:=TestOptions.DebugDll.WithRootNamespace("root2")).ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({module1, module2, MscorlibRef.ToModuleInstance()}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "root1", "root2") End Sub <Fact> Public Sub ImportStrings_ModuleNamespaces() Dim source1 = " Namespace N1 Module M End Module End Namespace Namespace N2 Namespace N3 Module M End Module End Namespace End Namespace Namespace N4 Class C End Class End Namespace " Dim source2 = " Namespace N1 ' Also imported for source1 Module M2 End Module End Namespace Namespace N5 Namespace N6 Module M End Module End Namespace End Namespace Namespace N7 Class C End Class End Namespace " Dim module1 = CreateCompilationWithMscorlib40({source1}, {MsvbRef}, options:=TestOptions.DebugDll).ToModuleInstance() Dim module2 = CreateCompilationWithMscorlib40({source2}, {MsvbRef}, options:=TestOptions.DebugDll).ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({module1, module2, MscorlibRef.ToModuleInstance(), MsvbRef.ToModuleInstance()}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "N1", "N2.N3", "N5.N6") End Sub <Fact> Public Sub ImportStrings_NoMethods() Dim comp = CreateCompilationWithMscorlib40({""}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) WithRuntimeInstance(comp, {MscorlibRef, MsvbRef}, Sub(runtime) ' Since there are no methods in the assembly, there is no import custom debug info, so we ' have no way to find the root namespace. Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub) End Sub <Fact> Public Sub ImportStrings_IgnoreAssemblyWithoutPdb() Dim source1 = " Namespace N1 Module M End Module End Namespace " Dim source2 = " Namespace N2 Module M End Module End Namespace " Dim comp1 = CreateCompilationWithMscorlib40({source1}, {MsvbRef}, options:=TestOptions.ReleaseDll) Dim module1 = comp1.ToModuleInstance(debugFormat:=Nothing) Dim comp2 = CreateCompilationWithMscorlib40({source2}, {MsvbRef}, options:=TestOptions.DebugDll) Dim module2 = comp2.ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({ module1, module2, MscorlibRef.ToModuleInstance(), MsvbRef.ToModuleInstance()}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtimeInstance)) CheckDteeMethodDebugInfo(methodDebugInfo, "N2") End Sub <Fact> Public Sub FalseModule_Nested() ' NOTE: VB only allows top-level module types. Dim ilSource = " .assembly extern Microsoft.VisualBasic { } .class public auto ansi N1.Outer extends [mscorlib]System.Object { .class auto ansi nested public sealed Inner extends [mscorlib]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class Inner .method public specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } // end of class N1.Outer " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef, MsvbRef}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub FalseModule_Generic() ' NOTE: VB only allows non-generic module types. Dim ilSource = " .assembly extern Microsoft.VisualBasic { } .class public auto ansi sealed N1.M`1<T> extends [mscorlib]System.Object { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} } // end of class M " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef, MsvbRef}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub FalseModule_Interface() ' NOTE: VB only allows non-interface module types. Dim ilSource = " .assembly extern Microsoft.VisualBasic { } .class interface private abstract auto ansi I { .custom instance void [Microsoft.VisualBasic]Microsoft.VisualBasic.CompilerServices.StandardModuleAttribute::.ctor() = {} } // end of class I " Dim ilModule = ExpressionCompilerTestHelpers.GetModuleInstanceForIL(ilSource) Dim runtime = CreateRuntimeInstance(ilModule, {MscorlibRef, MsvbRef}) Dim methodDebugInfo = EvaluationContext.SynthesizeMethodDebugInfoForDtee(MakeAssemblyReaders(runtime)) CheckDteeMethodDebugInfo(methodDebugInfo) End Sub <Fact> Public Sub ImportSymbols() Dim source1 = " Namespace N1 Module M Sub M() ' Need a method to record the root namespace. End Sub End Module End Namespace Namespace N2 Module M End Module End Namespace " Dim source2 = " Namespace N1 ' Also imported for source1 Module M2 Sub M() ' Need a method to record the root namespace. End Sub End Module End Namespace Namespace N3 Module M End Module End Namespace " Dim dteeComp = CreateCompilationWithMscorlib40({s_dteeEntryPointSource}, options:=TestOptions.DebugDll, assemblyName:=GetUniqueName()) Dim dteeModuleInstance = dteeComp.ToModuleInstance() Dim comp1 = CreateCompilationWithMscorlib40({source1}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) Dim compModuleInstance1 = comp1.ToModuleInstance() Dim comp2 = CreateCompilationWithMscorlib40({source2}, {MsvbRef}, options:=TestOptions.DebugDll.WithRootNamespace("root"), assemblyName:=GetUniqueName()) Dim compModuleInstance2 = comp2.ToModuleInstance() Dim runtimeInstance = CreateRuntimeInstance({ dteeModuleInstance, compModuleInstance1, compModuleInstance2, MscorlibRef.ToModuleInstance(), MsvbRef.ToModuleInstance()}) Dim lazyAssemblyReaders = MakeLazyAssemblyReaders(runtimeInstance) Dim evalContext = CreateMethodContext(runtimeInstance, s_dteeEntryPointName, lazyAssemblyReaders:=lazyAssemblyReaders) Dim compContext = evalContext.CreateCompilationContext(withSyntax:=True) Dim rootNamespace As NamespaceSymbol = Nothing Dim currentNamespace As NamespaceSymbol = Nothing Dim typesAndNamespaces As ImmutableArray(Of NamespaceOrTypeAndImportsClausePosition) = Nothing Dim aliases As Dictionary(Of String, AliasAndImportsClausePosition) = Nothing Dim xmlNamespaces As Dictionary(Of String, XmlNamespaceAndImportsClausePosition) = Nothing ImportsDebugInfoTests.GetImports(compContext, rootNamespace, currentNamespace, typesAndNamespaces, aliases, xmlNamespaces) Assert.Equal("", rootNamespace.Name) Assert.Equal("", currentNamespace.Name) Assert.Null(aliases) Assert.Null(xmlNamespaces) AssertEx.SetEqual(typesAndNamespaces.Select(Function(tn) tn.NamespaceOrType.ToTestDisplayString()), "root", "root.N1", "root.N2", "root.N3") End Sub Private Shared Function MakeLazyAssemblyReaders(runtimeInstance As RuntimeInstance) As Lazy(Of ImmutableArray(Of AssemblyReaders)) Return New Lazy(Of ImmutableArray(Of AssemblyReaders))( Function() MakeAssemblyReaders(runtimeInstance), LazyThreadSafetyMode.None) End Function Private Shared Function MakeAssemblyReaders(runtimeInstance As RuntimeInstance) As ImmutableArray(Of AssemblyReaders) Return ImmutableArray.CreateRange(runtimeInstance.Modules. Where(Function(instance) instance.SymReader IsNot Nothing). Select(Function(instance) New AssemblyReaders(instance.GetMetadataReader(), instance.SymReader))) End Function Private Shared Sub CheckDteeMethodDebugInfo(methodDebugInfo As MethodDebugInfo(Of TypeSymbol, LocalSymbol), ParamArray namespaceNames As String()) Assert.Equal("", methodDebugInfo.DefaultNamespaceName) Dim importRecordGroups = methodDebugInfo.ImportRecordGroups Assert.Equal(2, importRecordGroups.Length) Dim fileLevelImportRecords As ImmutableArray(Of ImportRecord) = importRecordGroups(0) Dim projectLevelImportRecords As ImmutableArray(Of ImportRecord) = importRecordGroups(1) Assert.Empty(fileLevelImportRecords) AssertEx.All(projectLevelImportRecords, Function(record) record.TargetAssemblyAlias Is Nothing) AssertEx.All(projectLevelImportRecords, Function(record) record.TargetKind = ImportTargetKind.Namespace) AssertEx.All(projectLevelImportRecords, Function(record) record.Alias Is Nothing) AssertEx.SetEqual(projectLevelImportRecords.Select(Function(record) record.TargetString), namespaceNames) End Sub End Class End Namespace
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Features/CSharp/Portable/Completion/KeywordRecommenders/DoubleKeywordRecommender.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class DoubleKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public DoubleKeywordRecommender() : base(SyntaxKind.DoubleKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_Double; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.CSharp.Completion.KeywordRecommenders { internal class DoubleKeywordRecommender : AbstractSpecialTypePreselectingKeywordRecommender { public DoubleKeywordRecommender() : base(SyntaxKind.DoubleKeyword) { } protected override bool IsValidContext(int position, CSharpSyntaxContext context, CancellationToken cancellationToken) { var syntaxTree = context.SyntaxTree; return context.IsAnyExpressionContext || context.IsDefiniteCastTypeContext || context.IsStatementContext || context.IsGlobalStatementContext || context.IsObjectCreationTypeContext || (context.IsGenericTypeArgumentContext && !context.TargetToken.Parent.HasAncestor<XmlCrefAttributeSyntax>()) || context.IsFunctionPointerTypeArgumentContext || context.IsIsOrAsTypeContext || context.IsLocalVariableDeclarationContext || context.IsFixedVariableDeclarationContext || context.IsParameterTypeContext || context.IsPossibleLambdaOrAnonymousMethodParameterTypeContext || context.IsLocalFunctionDeclarationContext || context.IsImplicitOrExplicitOperatorTypeContext || context.IsPrimaryFunctionExpressionContext || context.IsCrefContext || syntaxTree.IsAfterKeyword(position, SyntaxKind.ConstKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.RefKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.ReadOnlyKeyword, cancellationToken) || syntaxTree.IsAfterKeyword(position, SyntaxKind.StackAllocKeyword, cancellationToken) || context.IsDelegateReturnTypeContext || syntaxTree.IsGlobalMemberDeclarationContext(position, SyntaxKindSet.AllGlobalMemberModifiers, cancellationToken) || context.IsPossibleTupleContext || context.IsMemberDeclarationContext( validModifiers: SyntaxKindSet.AllMemberModifiers, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructRecordTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken); } protected override SpecialType SpecialType => SpecialType.System_Double; } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/Compilers/Core/Portable/Compilation/SemanticModelProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace Microsoft.CodeAnalysis { /// <summary> /// Provides semantic models for syntax trees in a compilation. /// This provider can be attached to a compilation, see <see cref="Compilation.SemanticModelProvider"/>. /// </summary> internal abstract class SemanticModelProvider { /// <summary> /// Gets a <see cref="SemanticModel"/> for the given <paramref name="tree"/> that belongs to the given <paramref name="compilation"/>. /// </summary> public abstract SemanticModel GetSemanticModel(SyntaxTree tree, Compilation compilation, bool ignoreAccessibility = 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. namespace Microsoft.CodeAnalysis { /// <summary> /// Provides semantic models for syntax trees in a compilation. /// This provider can be attached to a compilation, see <see cref="Compilation.SemanticModelProvider"/>. /// </summary> internal abstract class SemanticModelProvider { /// <summary> /// Gets a <see cref="SemanticModel"/> for the given <paramref name="tree"/> that belongs to the given <paramref name="compilation"/>. /// </summary> public abstract SemanticModel GetSemanticModel(SyntaxTree tree, Compilation compilation, bool ignoreAccessibility = false); } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/EditorFeatures/VisualBasicTest/Recommendations/Expressions/WithKeywordRecommenderTests.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions Public Class WithKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInClassDeclarationTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterFromTest() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = New Goo From |</ClassDeclaration>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterWith1Test() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = New With |</ClassDeclaration>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterWith2Test() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = New Goo With |</ClassDeclaration>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterDimEqualsNewTest() VerifyRecommendationsContain(<MethodBody>Dim x = New |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterDimEqualsNewTypeNameTest() VerifyRecommendationsContain(<MethodBody>Dim x = New Goo |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterDimEqualsNewTypeNameAndParensTest() VerifyRecommendationsContain(<MethodBody>Dim x = New Goo() |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterDimAsNewTest() VerifyRecommendationsContain(<MethodBody>Dim x As New |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterDimAsNewTypeNameTest() VerifyRecommendationsContain(<MethodBody>Dim x As New Goo |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterDimAsNewTypeNameAndParensTest() VerifyRecommendationsContain(<MethodBody>Dim x As New Goo() |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterAssignmentNewTest() VerifyRecommendationsContain(<MethodBody>x = New |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterAssignmentNewTypeNameTest() VerifyRecommendationsContain(<MethodBody>x = New Goo |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterAssignmentNewTypeNameAndParensTest() VerifyRecommendationsContain(<MethodBody>x = New Goo() |</MethodBody>, "With") End Sub <WorkItem(543291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543291")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoWithAfterDotTest() Dim code = <File> Class C Sub M() Dim c As New C.| End Sub End Class </File> VerifyRecommendationsMissing(code, "With") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <ClassDeclaration>Dim x = New Goo |</ClassDeclaration>, "With") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <ClassDeclaration>Dim x = New Goo _ |</ClassDeclaration>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <ClassDeclaration>Dim x = New Goo _ ' Test |</ClassDeclaration>, "With") End Sub End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.Recommendations.Expressions Public Class WithKeywordRecommenderTests <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneInClassDeclarationTest() VerifyRecommendationsMissing(<ClassDeclaration>|</ClassDeclaration>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterFromTest() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = New Goo From |</ClassDeclaration>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterWith1Test() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = New With |</ClassDeclaration>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoneAfterWith2Test() VerifyRecommendationsMissing(<ClassDeclaration>Dim x = New Goo With |</ClassDeclaration>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterDimEqualsNewTest() VerifyRecommendationsContain(<MethodBody>Dim x = New |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterDimEqualsNewTypeNameTest() VerifyRecommendationsContain(<MethodBody>Dim x = New Goo |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterDimEqualsNewTypeNameAndParensTest() VerifyRecommendationsContain(<MethodBody>Dim x = New Goo() |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterDimAsNewTest() VerifyRecommendationsContain(<MethodBody>Dim x As New |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterDimAsNewTypeNameTest() VerifyRecommendationsContain(<MethodBody>Dim x As New Goo |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterDimAsNewTypeNameAndParensTest() VerifyRecommendationsContain(<MethodBody>Dim x As New Goo() |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterAssignmentNewTest() VerifyRecommendationsContain(<MethodBody>x = New |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterAssignmentNewTypeNameTest() VerifyRecommendationsContain(<MethodBody>x = New Goo |</MethodBody>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub WithAfterAssignmentNewTypeNameAndParensTest() VerifyRecommendationsContain(<MethodBody>x = New Goo() |</MethodBody>, "With") End Sub <WorkItem(543291, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543291")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NoWithAfterDotTest() Dim code = <File> Class C Sub M() Dim c As New C.| End Sub End Class </File> VerifyRecommendationsMissing(code, "With") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub NotAfterEolTest() VerifyRecommendationsMissing( <ClassDeclaration>Dim x = New Goo |</ClassDeclaration>, "With") End Sub <WorkItem(530953, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530953")> <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTest() VerifyRecommendationsContain( <ClassDeclaration>Dim x = New Goo _ |</ClassDeclaration>, "With") End Sub <Fact, Trait(Traits.Feature, Traits.Features.KeywordRecommending)> Public Sub AfterExplicitLineContinuationTestCommentsAfterLineContinuation() VerifyRecommendationsContain( <ClassDeclaration>Dim x = New Goo _ ' Test |</ClassDeclaration>, "With") End Sub End Class End Namespace
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./src/ExpressionEvaluator/Core/Source/ResultProvider/Formatter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable CA1825 // Avoid zero-length array allocations. using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { /// <summary> /// Computes string representations of <see cref="DkmClrValue"/> instances. /// </summary> internal abstract partial class Formatter : IDkmClrFormatter, IDkmClrFormatter2, IDkmClrFullNameProvider { private readonly string _defaultFormat; private readonly string _nullString; private readonly string _thisString; private string _hostValueNotFoundString => Resources.HostValueNotFound; internal Formatter(string defaultFormat, string nullString, string thisString) { _defaultFormat = defaultFormat; _nullString = nullString; _thisString = thisString; } string IDkmClrFormatter.GetValueString(DkmClrValue value, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers) { var useQuotes = (inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoQuotes) == 0; var options = useQuotes ? ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters : ObjectDisplayOptions.None; return GetValueString(value, inspectionContext, options, GetValueFlags.IncludeObjectId); } string IDkmClrFormatter.GetTypeName(DkmInspectionContext inspectionContext, DkmClrType type, DkmClrCustomTypeInfo typeInfo, ReadOnlyCollection<string> formatSpecifiers) { bool unused; return GetTypeName(new TypeAndCustomInfo(type, typeInfo), escapeKeywordIdentifiers: false, sawInvalidIdentifier: out unused); } bool IDkmClrFormatter.HasUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext) { return HasUnderlyingString(value, inspectionContext); } string IDkmClrFormatter.GetUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext) { return GetUnderlyingString(value, inspectionContext); } string IDkmClrFormatter2.GetValueString(DkmClrValue value, DkmClrCustomTypeInfo customTypeInfo, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers) { return value.GetValueString(inspectionContext, formatSpecifiers); } string IDkmClrFormatter2.GetEditableValueString(DkmClrValue value, DkmInspectionContext inspectionContext, DkmClrCustomTypeInfo customTypeInfo) { return GetEditableValue(value, inspectionContext, customTypeInfo); } string IDkmClrFullNameProvider.GetClrTypeName(DkmInspectionContext inspectionContext, DkmClrType clrType, DkmClrCustomTypeInfo customTypeInfo) { Debug.Assert(inspectionContext != null); bool sawInvalidIdentifier; var name = GetTypeName(new TypeAndCustomInfo(clrType, customTypeInfo), escapeKeywordIdentifiers: true, sawInvalidIdentifier: out sawInvalidIdentifier); return sawInvalidIdentifier ? null : name; } string IDkmClrFullNameProvider.GetClrArrayIndexExpression(DkmInspectionContext inspectionContext, string[] indices) { return GetArrayIndexExpression(indices); } string IDkmClrFullNameProvider.GetClrCastExpression(DkmInspectionContext inspectionContext, string argument, DkmClrType type, DkmClrCustomTypeInfo customTypeInfo, DkmClrCastExpressionOptions castExpressionOptions) { bool sawInvalidIdentifier; var name = GetTypeName(new TypeAndCustomInfo(type, customTypeInfo), escapeKeywordIdentifiers: true, sawInvalidIdentifier: out sawInvalidIdentifier); if (sawInvalidIdentifier) { return null; } return GetCastExpression(argument, name, castExpressionOptions); } string IDkmClrFullNameProvider.GetClrObjectCreationExpression(DkmInspectionContext inspectionContext, DkmClrType type, DkmClrCustomTypeInfo customTypeInfo, string[] arguments) { bool sawInvalidIdentifier; var name = GetTypeName(new TypeAndCustomInfo(type, customTypeInfo), escapeKeywordIdentifiers: true, sawInvalidIdentifier: out sawInvalidIdentifier); if (sawInvalidIdentifier) { return null; } return GetObjectCreationExpression(name, arguments); } string IDkmClrFullNameProvider.GetClrValidIdentifier(DkmInspectionContext inspectionContext, string identifier) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; bool sawInvalidIdentifier; AppendIdentifierEscapingPotentialKeywords(builder, identifier, out sawInvalidIdentifier); var result = sawInvalidIdentifier ? null : builder.ToString(); pooledBuilder.Free(); return result; } string IDkmClrFullNameProvider.GetClrExpressionAndFormatSpecifiers(DkmInspectionContext inspectionContext, string expression, out ReadOnlyCollection<string> formatSpecifiers) { return TrimAndGetFormatSpecifiers(expression, out formatSpecifiers); } bool IDkmClrFullNameProvider.ClrExpressionMayRequireParentheses(DkmInspectionContext inspectionContext, string expression) { return NeedsParentheses(expression); } string IDkmClrFullNameProvider.GetClrMemberName( DkmInspectionContext inspectionContext, string parentFullName, DkmClrType declaringType, DkmClrCustomTypeInfo declaringTypeInfo, string memberName, bool memberAccessRequiresExplicitCast, bool memberIsStatic) { string qualifier; if (memberIsStatic) { bool sawInvalidIdentifier; qualifier = GetTypeName(new TypeAndCustomInfo(declaringType, declaringTypeInfo), escapeKeywordIdentifiers: true, sawInvalidIdentifier: out sawInvalidIdentifier); if (sawInvalidIdentifier) { return null; // FullName wouldn't be parseable. } } else if (memberAccessRequiresExplicitCast) { bool sawInvalidIdentifier; var typeName = GetTypeName(new TypeAndCustomInfo(declaringType, declaringTypeInfo), escapeKeywordIdentifiers: true, sawInvalidIdentifier: out sawInvalidIdentifier); if (sawInvalidIdentifier) { return null; // FullName wouldn't be parseable. } qualifier = GetCastExpression(parentFullName, typeName, DkmClrCastExpressionOptions.ParenthesizeEntireExpression); } else { qualifier = parentFullName; } return $"{qualifier}.{memberName}"; } string IDkmClrFullNameProvider.GetClrExpressionForNull(DkmInspectionContext inspectionContext) { return _nullString; } string IDkmClrFullNameProvider.GetClrExpressionForThis(DkmInspectionContext inspectionContext) { return _thisString; } // CONSIDER: If the number or complexity of the "language-specific syntax helpers" grows (or if // we make this a public API, it would be good to consider abstracting them into a separate object // that can be passed to the ResultProvider on construction (a "LanguageSyntax" service of sorts). // It seems more natural to ask these questions of the ResultProvider, but adding such a component // for these few methods seemed a bit overly elaborate given the current internal usage. #region Language-specific syntax helpers internal abstract bool IsValidIdentifier(string name); internal abstract bool IsIdentifierPartCharacter(char c); internal abstract bool IsPredefinedType(Type type); internal abstract bool IsWhitespace(char c); // Note: We could be less conservative (e.g. "new C()"). private bool NeedsParentheses(string expr) { int parens = 0; for (int i = 0; i < expr.Length; i++) { var ch = expr[i]; switch (ch) { case '(': // Cast, "(A)b", requires parentheses. if ((parens == 0) && FollowsCloseParen(expr, i)) { return true; } parens++; break; case '[': parens++; break; case ')': case ']': parens--; break; case '.': break; default: if (parens == 0) { if (this.IsIdentifierPartCharacter(ch)) { // Cast, "(A)b", requires parentheses. if (FollowsCloseParen(expr, i)) { return true; } } else { return true; } } break; } } return false; } private static bool FollowsCloseParen(string expr, int index) { return (index > 0) && (expr[index - 1] == ')'); } internal abstract string TrimAndGetFormatSpecifiers(string expression, out ReadOnlyCollection<string> formatSpecifiers); internal static readonly ReadOnlyCollection<string> NoFormatSpecifiers = new ReadOnlyCollection<string>(new string[0]); internal static ReadOnlyCollection<string> AddFormatSpecifier(ReadOnlyCollection<string> formatSpecifiers, string formatSpecifier) { if (formatSpecifiers.Contains(formatSpecifier)) { return formatSpecifiers; } var builder = ArrayBuilder<string>.GetInstance(); builder.AddRange(formatSpecifiers); builder.Add(formatSpecifier); return builder.ToImmutableAndFree(); } protected string RemoveLeadingAndTrailingContent(string expression, int start, int length, Predicate<char> leading, Predicate<char> trailing) { int oldLength = expression.Length; for (; start < oldLength && leading(expression[start]); start++) { } for (; length > start && trailing(expression[length - 1]); length--) { } if ((start > 0) || (length < oldLength)) { return expression.Substring(start, length - start); } return expression; } protected string RemoveLeadingAndTrailingWhitespace(string expression) { return RemoveLeadingAndTrailingContent(expression, 0, expression.Length, IsWhitespace, IsWhitespace); } protected string RemoveFormatSpecifiers(string expression, out ReadOnlyCollection<string> formatSpecifiers) { var builder = ArrayBuilder<string>.GetInstance(); int oldLength = expression.Length; int newLength = oldLength; for (var i = oldLength - 1; i >= 0; i--) { var ch = expression[i]; if (ch == ',') { builder.Add(RemoveLeadingAndTrailingContent(expression, i + 1, newLength, IsWhitespace, IsWhitespace)); newLength = i; } else if (!IsIdentifierPartCharacter(ch) && !IsWhitespace(ch)) { break; } } if (builder.Count == 0) { formatSpecifiers = NoFormatSpecifiers; } else { var specifiers = builder.ToArray(); Array.Reverse(specifiers); formatSpecifiers = new ReadOnlyCollection<string>(specifiers); } builder.Free(); Debug.Assert((formatSpecifiers.Count == 0) == (newLength == oldLength)); if (newLength < oldLength) { return expression.Substring(0, newLength); } return expression; } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable #pragma warning disable CA1825 // Avoid zero-length array allocations. using System; using System.Collections.ObjectModel; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.ComponentInterfaces; using Microsoft.VisualStudio.Debugger.Evaluation; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.ExpressionEvaluator { /// <summary> /// Computes string representations of <see cref="DkmClrValue"/> instances. /// </summary> internal abstract partial class Formatter : IDkmClrFormatter, IDkmClrFormatter2, IDkmClrFullNameProvider { private readonly string _defaultFormat; private readonly string _nullString; private readonly string _thisString; private string _hostValueNotFoundString => Resources.HostValueNotFound; internal Formatter(string defaultFormat, string nullString, string thisString) { _defaultFormat = defaultFormat; _nullString = nullString; _thisString = thisString; } string IDkmClrFormatter.GetValueString(DkmClrValue value, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers) { var useQuotes = (inspectionContext.EvaluationFlags & DkmEvaluationFlags.NoQuotes) == 0; var options = useQuotes ? ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters : ObjectDisplayOptions.None; return GetValueString(value, inspectionContext, options, GetValueFlags.IncludeObjectId); } string IDkmClrFormatter.GetTypeName(DkmInspectionContext inspectionContext, DkmClrType type, DkmClrCustomTypeInfo typeInfo, ReadOnlyCollection<string> formatSpecifiers) { bool unused; return GetTypeName(new TypeAndCustomInfo(type, typeInfo), escapeKeywordIdentifiers: false, sawInvalidIdentifier: out unused); } bool IDkmClrFormatter.HasUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext) { return HasUnderlyingString(value, inspectionContext); } string IDkmClrFormatter.GetUnderlyingString(DkmClrValue value, DkmInspectionContext inspectionContext) { return GetUnderlyingString(value, inspectionContext); } string IDkmClrFormatter2.GetValueString(DkmClrValue value, DkmClrCustomTypeInfo customTypeInfo, DkmInspectionContext inspectionContext, ReadOnlyCollection<string> formatSpecifiers) { return value.GetValueString(inspectionContext, formatSpecifiers); } string IDkmClrFormatter2.GetEditableValueString(DkmClrValue value, DkmInspectionContext inspectionContext, DkmClrCustomTypeInfo customTypeInfo) { return GetEditableValue(value, inspectionContext, customTypeInfo); } string IDkmClrFullNameProvider.GetClrTypeName(DkmInspectionContext inspectionContext, DkmClrType clrType, DkmClrCustomTypeInfo customTypeInfo) { Debug.Assert(inspectionContext != null); bool sawInvalidIdentifier; var name = GetTypeName(new TypeAndCustomInfo(clrType, customTypeInfo), escapeKeywordIdentifiers: true, sawInvalidIdentifier: out sawInvalidIdentifier); return sawInvalidIdentifier ? null : name; } string IDkmClrFullNameProvider.GetClrArrayIndexExpression(DkmInspectionContext inspectionContext, string[] indices) { return GetArrayIndexExpression(indices); } string IDkmClrFullNameProvider.GetClrCastExpression(DkmInspectionContext inspectionContext, string argument, DkmClrType type, DkmClrCustomTypeInfo customTypeInfo, DkmClrCastExpressionOptions castExpressionOptions) { bool sawInvalidIdentifier; var name = GetTypeName(new TypeAndCustomInfo(type, customTypeInfo), escapeKeywordIdentifiers: true, sawInvalidIdentifier: out sawInvalidIdentifier); if (sawInvalidIdentifier) { return null; } return GetCastExpression(argument, name, castExpressionOptions); } string IDkmClrFullNameProvider.GetClrObjectCreationExpression(DkmInspectionContext inspectionContext, DkmClrType type, DkmClrCustomTypeInfo customTypeInfo, string[] arguments) { bool sawInvalidIdentifier; var name = GetTypeName(new TypeAndCustomInfo(type, customTypeInfo), escapeKeywordIdentifiers: true, sawInvalidIdentifier: out sawInvalidIdentifier); if (sawInvalidIdentifier) { return null; } return GetObjectCreationExpression(name, arguments); } string IDkmClrFullNameProvider.GetClrValidIdentifier(DkmInspectionContext inspectionContext, string identifier) { var pooledBuilder = PooledStringBuilder.GetInstance(); var builder = pooledBuilder.Builder; bool sawInvalidIdentifier; AppendIdentifierEscapingPotentialKeywords(builder, identifier, out sawInvalidIdentifier); var result = sawInvalidIdentifier ? null : builder.ToString(); pooledBuilder.Free(); return result; } string IDkmClrFullNameProvider.GetClrExpressionAndFormatSpecifiers(DkmInspectionContext inspectionContext, string expression, out ReadOnlyCollection<string> formatSpecifiers) { return TrimAndGetFormatSpecifiers(expression, out formatSpecifiers); } bool IDkmClrFullNameProvider.ClrExpressionMayRequireParentheses(DkmInspectionContext inspectionContext, string expression) { return NeedsParentheses(expression); } string IDkmClrFullNameProvider.GetClrMemberName( DkmInspectionContext inspectionContext, string parentFullName, DkmClrType declaringType, DkmClrCustomTypeInfo declaringTypeInfo, string memberName, bool memberAccessRequiresExplicitCast, bool memberIsStatic) { string qualifier; if (memberIsStatic) { bool sawInvalidIdentifier; qualifier = GetTypeName(new TypeAndCustomInfo(declaringType, declaringTypeInfo), escapeKeywordIdentifiers: true, sawInvalidIdentifier: out sawInvalidIdentifier); if (sawInvalidIdentifier) { return null; // FullName wouldn't be parseable. } } else if (memberAccessRequiresExplicitCast) { bool sawInvalidIdentifier; var typeName = GetTypeName(new TypeAndCustomInfo(declaringType, declaringTypeInfo), escapeKeywordIdentifiers: true, sawInvalidIdentifier: out sawInvalidIdentifier); if (sawInvalidIdentifier) { return null; // FullName wouldn't be parseable. } qualifier = GetCastExpression(parentFullName, typeName, DkmClrCastExpressionOptions.ParenthesizeEntireExpression); } else { qualifier = parentFullName; } return $"{qualifier}.{memberName}"; } string IDkmClrFullNameProvider.GetClrExpressionForNull(DkmInspectionContext inspectionContext) { return _nullString; } string IDkmClrFullNameProvider.GetClrExpressionForThis(DkmInspectionContext inspectionContext) { return _thisString; } // CONSIDER: If the number or complexity of the "language-specific syntax helpers" grows (or if // we make this a public API, it would be good to consider abstracting them into a separate object // that can be passed to the ResultProvider on construction (a "LanguageSyntax" service of sorts). // It seems more natural to ask these questions of the ResultProvider, but adding such a component // for these few methods seemed a bit overly elaborate given the current internal usage. #region Language-specific syntax helpers internal abstract bool IsValidIdentifier(string name); internal abstract bool IsIdentifierPartCharacter(char c); internal abstract bool IsPredefinedType(Type type); internal abstract bool IsWhitespace(char c); // Note: We could be less conservative (e.g. "new C()"). private bool NeedsParentheses(string expr) { int parens = 0; for (int i = 0; i < expr.Length; i++) { var ch = expr[i]; switch (ch) { case '(': // Cast, "(A)b", requires parentheses. if ((parens == 0) && FollowsCloseParen(expr, i)) { return true; } parens++; break; case '[': parens++; break; case ')': case ']': parens--; break; case '.': break; default: if (parens == 0) { if (this.IsIdentifierPartCharacter(ch)) { // Cast, "(A)b", requires parentheses. if (FollowsCloseParen(expr, i)) { return true; } } else { return true; } } break; } } return false; } private static bool FollowsCloseParen(string expr, int index) { return (index > 0) && (expr[index - 1] == ')'); } internal abstract string TrimAndGetFormatSpecifiers(string expression, out ReadOnlyCollection<string> formatSpecifiers); internal static readonly ReadOnlyCollection<string> NoFormatSpecifiers = new ReadOnlyCollection<string>(new string[0]); internal static ReadOnlyCollection<string> AddFormatSpecifier(ReadOnlyCollection<string> formatSpecifiers, string formatSpecifier) { if (formatSpecifiers.Contains(formatSpecifier)) { return formatSpecifiers; } var builder = ArrayBuilder<string>.GetInstance(); builder.AddRange(formatSpecifiers); builder.Add(formatSpecifier); return builder.ToImmutableAndFree(); } protected string RemoveLeadingAndTrailingContent(string expression, int start, int length, Predicate<char> leading, Predicate<char> trailing) { int oldLength = expression.Length; for (; start < oldLength && leading(expression[start]); start++) { } for (; length > start && trailing(expression[length - 1]); length--) { } if ((start > 0) || (length < oldLength)) { return expression.Substring(start, length - start); } return expression; } protected string RemoveLeadingAndTrailingWhitespace(string expression) { return RemoveLeadingAndTrailingContent(expression, 0, expression.Length, IsWhitespace, IsWhitespace); } protected string RemoveFormatSpecifiers(string expression, out ReadOnlyCollection<string> formatSpecifiers) { var builder = ArrayBuilder<string>.GetInstance(); int oldLength = expression.Length; int newLength = oldLength; for (var i = oldLength - 1; i >= 0; i--) { var ch = expression[i]; if (ch == ',') { builder.Add(RemoveLeadingAndTrailingContent(expression, i + 1, newLength, IsWhitespace, IsWhitespace)); newLength = i; } else if (!IsIdentifierPartCharacter(ch) && !IsWhitespace(ch)) { break; } } if (builder.Count == 0) { formatSpecifiers = NoFormatSpecifiers; } else { var specifiers = builder.ToArray(); Array.Reverse(specifiers); formatSpecifiers = new ReadOnlyCollection<string>(specifiers); } builder.Free(); Debug.Assert((formatSpecifiers.Count == 0) == (newLength == oldLength)); if (newLength < oldLength) { return expression.Substring(0, newLength); } return expression; } #endregion } }
-1
dotnet/roslyn
56,027
Fix shadow copy loader in framework
Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
RikkiGibson
2021-08-31T15:35:06Z
2021-08-31T20:44:03Z
8efaf83aac58c6b6d21a1e1c4cea2ddd60a8ccd5
d471af61946b3709c65f63f9bfd9e331f5cde422
Fix shadow copy loader in framework. Fixes https://dev.azure.com/devdiv/DevDiv/_workitems/edit/1389790 Added a test which actually performs a deletion and manually verified the scenario in the linked issue.
./eng/common/native/install-cmake.sh
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" . $scriptroot/common-library.sh base_uri= install_path= version= clean=false force=false download_retries=5 retry_wait_time_seconds=30 while (($# > 0)); do lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" case $lowerI in --baseuri) base_uri=$2 shift 2 ;; --installpath) install_path=$2 shift 2 ;; --version) version=$2 shift 2 ;; --clean) clean=true shift 1 ;; --force) force=true shift 1 ;; --downloadretries) download_retries=$2 shift 2 ;; --retrywaittimeseconds) retry_wait_time_seconds=$2 shift 2 ;; --help) echo "Common settings:" echo " --baseuri <value> Base file directory or Url wrom which to acquire tool archives" echo " --installpath <value> Base directory to install native tool to" echo " --clean Don't install the tool, just clean up the current install of the tool" echo " --force Force install of tools even if they previously exist" echo " --help Print help and exit" echo "" echo "Advanced settings:" echo " --downloadretries Total number of retry attempts" echo " --retrywaittimeseconds Wait time between retry attempts in seconds" echo "" exit 0 ;; esac done tool_name="cmake" tool_os=$(GetCurrentOS) tool_folder="$(echo $tool_os | tr "[:upper:]" "[:lower:]")" tool_arch="x86_64" tool_name_moniker="$tool_name-$version-$tool_os-$tool_arch" tool_install_directory="$install_path/$tool_name/$version" tool_file_path="$tool_install_directory/$tool_name_moniker/bin/$tool_name" shim_path="$install_path/$tool_name.sh" uri="${base_uri}/$tool_folder/$tool_name/$tool_name_moniker.tar.gz" # Clean up tool and installers if [[ $clean = true ]]; then echo "Cleaning $tool_install_directory" if [[ -d $tool_install_directory ]]; then rm -rf $tool_install_directory fi echo "Cleaning $shim_path" if [[ -f $shim_path ]]; then rm -rf $shim_path fi tool_temp_path=$(GetTempPathFileName $uri) echo "Cleaning $tool_temp_path" if [[ -f $tool_temp_path ]]; then rm -rf $tool_temp_path fi exit 0 fi # Install tool if [[ -f $tool_file_path ]] && [[ $force = false ]]; then echo "$tool_name ($version) already exists, skipping install" exit 0 fi DownloadAndExtract $uri $tool_install_directory $force $download_retries $retry_wait_time_seconds if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Installation failed' exit 1 fi # Generate Shim # Always rewrite shims so that we are referencing the expected version NewScriptShim $shim_path $tool_file_path true if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Shim generation failed' exit 1 fi exit 0
#!/usr/bin/env bash source="${BASH_SOURCE[0]}" scriptroot="$( cd -P "$( dirname "$source" )" && pwd )" . $scriptroot/common-library.sh base_uri= install_path= version= clean=false force=false download_retries=5 retry_wait_time_seconds=30 while (($# > 0)); do lowerI="$(echo $1 | tr "[:upper:]" "[:lower:]")" case $lowerI in --baseuri) base_uri=$2 shift 2 ;; --installpath) install_path=$2 shift 2 ;; --version) version=$2 shift 2 ;; --clean) clean=true shift 1 ;; --force) force=true shift 1 ;; --downloadretries) download_retries=$2 shift 2 ;; --retrywaittimeseconds) retry_wait_time_seconds=$2 shift 2 ;; --help) echo "Common settings:" echo " --baseuri <value> Base file directory or Url wrom which to acquire tool archives" echo " --installpath <value> Base directory to install native tool to" echo " --clean Don't install the tool, just clean up the current install of the tool" echo " --force Force install of tools even if they previously exist" echo " --help Print help and exit" echo "" echo "Advanced settings:" echo " --downloadretries Total number of retry attempts" echo " --retrywaittimeseconds Wait time between retry attempts in seconds" echo "" exit 0 ;; esac done tool_name="cmake" tool_os=$(GetCurrentOS) tool_folder="$(echo $tool_os | tr "[:upper:]" "[:lower:]")" tool_arch="x86_64" tool_name_moniker="$tool_name-$version-$tool_os-$tool_arch" tool_install_directory="$install_path/$tool_name/$version" tool_file_path="$tool_install_directory/$tool_name_moniker/bin/$tool_name" shim_path="$install_path/$tool_name.sh" uri="${base_uri}/$tool_folder/$tool_name/$tool_name_moniker.tar.gz" # Clean up tool and installers if [[ $clean = true ]]; then echo "Cleaning $tool_install_directory" if [[ -d $tool_install_directory ]]; then rm -rf $tool_install_directory fi echo "Cleaning $shim_path" if [[ -f $shim_path ]]; then rm -rf $shim_path fi tool_temp_path=$(GetTempPathFileName $uri) echo "Cleaning $tool_temp_path" if [[ -f $tool_temp_path ]]; then rm -rf $tool_temp_path fi exit 0 fi # Install tool if [[ -f $tool_file_path ]] && [[ $force = false ]]; then echo "$tool_name ($version) already exists, skipping install" exit 0 fi DownloadAndExtract $uri $tool_install_directory $force $download_retries $retry_wait_time_seconds if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Installation failed' exit 1 fi # Generate Shim # Always rewrite shims so that we are referencing the expected version NewScriptShim $shim_path $tool_file_path true if [[ $? != 0 ]]; then Write-PipelineTelemetryError -category 'NativeToolsBootstrap' 'Shim generation failed' exit 1 fi exit 0
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/CSharp/Portable/Binder/Semantics/OverloadResolution/MethodTypeInference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; /* SPEC: Type inference occurs as part of the compile-time processing of a method invocation and takes place before the overload resolution step of the invocation. When a particular method group is specified in a method invocation, and no type arguments are specified as part of the method invocation, type inference is applied to each generic method in the method group. If type inference succeeds, then the inferred type arguments are used to determine the types of formal parameters for subsequent overload resolution. If overload resolution chooses a generic method as the one to invoke then the inferred type arguments are used as the actual type arguments for the invocation. If type inference for a particular method fails, that method does not participate in overload resolution. The failure of type inference, in and of itself, does not cause a compile-time error. However, it often leads to a compile-time error when overload resolution then fails to find any applicable methods. If the supplied number of arguments is different than the number of parameters in the method, then inference immediately fails. Otherwise, assume that the generic method has the following signature: Tr M<X1...Xn>(T1 x1 ... Tm xm) With a method call of the form M(E1...Em) the task of type inference is to find unique type arguments S1...Sn for each of the type parameters X1...Xn so that the call M<S1...Sn>(E1...Em)becomes valid. During the process of inference each type parameter Xi is either fixed to a particular type Si or unfixed with an associated set of bounds. Each of the bounds is some type T. Each bound is classified as an upper bound, lower bound or exact bound. Initially each type variable Xi is unfixed with an empty set of bounds. */ // This file contains the implementation for method type inference on calls (with // arguments, and method type inference on conversion of method groups to delegate // types (which will not have arguments.) namespace Microsoft.CodeAnalysis.CSharp { internal static class PooledDictionaryIgnoringNullableModifiersForReferenceTypes { private static readonly ObjectPool<PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>> s_poolInstance = PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>.CreatePool(Symbols.SymbolEqualityComparer.IgnoringNullable); internal static PooledDictionary<NamedTypeSymbol, NamedTypeSymbol> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } // Method type inference can fail, but we still might have some best guesses. internal struct MethodTypeInferenceResult { public readonly ImmutableArray<TypeWithAnnotations> InferredTypeArguments; public readonly bool Success; public MethodTypeInferenceResult( bool success, ImmutableArray<TypeWithAnnotations> inferredTypeArguments) { this.Success = success; this.InferredTypeArguments = inferredTypeArguments; } } internal sealed class MethodTypeInferrer { internal abstract class Extensions { internal static readonly Extensions Default = new DefaultExtensions(); internal abstract TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr); internal abstract TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method); private sealed class DefaultExtensions : Extensions { internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType()); } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { return method.ReturnTypeWithAnnotations; } } } private enum InferenceResult { InferenceFailed, MadeProgress, NoProgress, Success } private enum Dependency { Unknown = 0x00, NotDependent = 0x01, DependsMask = 0x10, Direct = 0x11, Indirect = 0x12 } private readonly CSharpCompilation _compilation; private readonly ConversionsBase _conversions; private readonly ImmutableArray<TypeParameterSymbol> _methodTypeParameters; private readonly NamedTypeSymbol _constructedContainingTypeOfMethod; private readonly ImmutableArray<TypeWithAnnotations> _formalParameterTypes; private readonly ImmutableArray<RefKind> _formalParameterRefKinds; private readonly ImmutableArray<BoundExpression> _arguments; private readonly Extensions _extensions; private readonly TypeWithAnnotations[] _fixedResults; private readonly HashSet<TypeWithAnnotations>[] _exactBounds; private readonly HashSet<TypeWithAnnotations>[] _upperBounds; private readonly HashSet<TypeWithAnnotations>[] _lowerBounds; private Dependency[,] _dependencies; // Initialized lazily private bool _dependenciesDirty; /// <summary> /// For error recovery, we allow a mismatch between the number of arguments and parameters /// during type inference. This sometimes enables inferring the type for a lambda parameter. /// </summary> private int NumberArgumentsToProcess => System.Math.Min(_arguments.Length, _formalParameterTypes.Length); public static MethodTypeInferenceResult Infer( Binder binder, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, // We are attempting to build a map from method type parameters // to inferred type arguments. NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, // We have some unusual requirements for the types that flow into the inference engine. // Consider the following inference problems: // // Scenario one: // // class C<T> // { // delegate Y FT<X, Y>(T t, X x); // static void M<U, V>(U u, FT<U, V> f); // ... // C<double>.M(123, (t,x)=>t+x); // // From the first argument we infer that U is int. How now must we make an inference on // the second argument? The *declared* type of the formal is C<T>.FT<U,V>. The // actual type at the time of inference is known to be C<double>.FT<int, something> // where "something" is to be determined by inferring the return type of the // lambda by determine the type of "double + int". // // Therefore when we do type inference, if a formal parameter type is a generic delegate // then *its* formal parameter types must be the formal parameter types of the // *constructed* generic delegate C<double>.FT<...>, not C<T>.FT<...>. // // One would therefore suppose that we'd expect the formal parameter types to here // be passed in with the types constructed with the information known from the // call site, not the declared types. // // Contrast that with this scenario: // // Scenario Two: // // interface I<T> // { // void M<U>(T t, U u); // } // ... // static void Goo<V>(V v, I<V> iv) // { // iv.M(v, ""); // } // // Obviously inference should succeed here; it should infer that U is string. // // But consider what happens during the inference process on the first argument. // The first thing we will do is say "what's the type of the argument? V. What's // the type of the corresponding formal parameter? The first formal parameter of // I<V>.M<whatever> is of type V. The inference engine will then say "V is a // method type parameter, and therefore we have an inference from V to V". // But *V* is not one of the method type parameters being inferred; the only // method type parameter being inferred here is *U*. // // This is perhaps some evidence that the formal parameters passed in should be // the formal parameters of the *declared* method; in this case, (T, U), not // the formal parameters of the *constructed* method, (V, U). // // However, one might make the argument that no, we could just add a check // to ensure that if we see a method type parameter as a formal parameter type, // then we only perform the inference if the method type parameter is a type // parameter of the method for which inference is being performed. // // Unfortunately, that does not work either: // // Scenario three: // // class C<T> // { // static void M<U>(T t, U u) // { // ... // C<U>.M(u, 123); // ... // } // } // // The *original* formal parameter types are (T, U); the *constructed* formal parameter types // are (U, U), but *those are logically two different U's*. The first U is from the outer caller; // the second U is the U of the recursive call. // // That is, suppose someone called C<string>.M<double>(string, double). The recursive call should be to // C<double>.M<int>(double, int). We should absolutely not make an inference on the first argument // from U to U just because C<U>.M<something>'s first formal parameter is of type U. If we did then // inference would fail, because we'd end up with two bounds on 'U' -- 'U' and 'int'. We only want // the latter bound. // // What these three scenarios show is that for a "normal" inference we need to have the // formal parameters of the *original* method definition, but when making an inference from a lambda // to a delegate, we need to have the *constructed* method signature in order that the formal // parameters *of the delegate* be correct. // // How to solve this problem? // // We solve it by passing in the formal parameters in their *original* form, but also getting // the *fully constructed* type that the method call is on. When constructing the fixed // delegate type for inference from a lambda, we do the appropriate type substitution on // the delegate. ImmutableArray<RefKind> formalParameterRefKinds, // Optional; assume all value if missing. ImmutableArray<BoundExpression> arguments,// Required; in scenarios like method group conversions where there are // no arguments per se we cons up some fake arguments. ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, Extensions extensions = null) { Debug.Assert(!methodTypeParameters.IsDefault); Debug.Assert(methodTypeParameters.Length > 0); Debug.Assert(!formalParameterTypes.IsDefault); Debug.Assert(formalParameterRefKinds.IsDefault || formalParameterRefKinds.Length == formalParameterTypes.Length); Debug.Assert(!arguments.IsDefault); // Early out: if the method has no formal parameters then we know that inference will fail. if (formalParameterTypes.Length == 0) { return new MethodTypeInferenceResult(false, default(ImmutableArray<TypeWithAnnotations>)); // UNDONE: OPTIMIZATION: We could check to see whether there is a type // UNDONE: parameter which is never used in any formal parameter; if // UNDONE: so then we know ahead of time that inference will fail. } var inferrer = new MethodTypeInferrer( binder.Compilation, conversions, methodTypeParameters, constructedContainingTypeOfMethod, formalParameterTypes, formalParameterRefKinds, arguments, extensions); return inferrer.InferTypeArgs(binder, ref useSiteInfo); } //////////////////////////////////////////////////////////////////////////////// // // Fixed, unfixed and bounded type parameters // // SPEC: During the process of inference each type parameter is either fixed to // SPEC: a particular type or unfixed with an associated set of bounds. Each of // SPEC: the bounds is of some type T. Initially each type parameter is unfixed // SPEC: with an empty set of bounds. private MethodTypeInferrer( CSharpCompilation compilation, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, ImmutableArray<RefKind> formalParameterRefKinds, ImmutableArray<BoundExpression> arguments, Extensions extensions) { _compilation = compilation; _conversions = conversions; _methodTypeParameters = methodTypeParameters; _constructedContainingTypeOfMethod = constructedContainingTypeOfMethod; _formalParameterTypes = formalParameterTypes; _formalParameterRefKinds = formalParameterRefKinds; _arguments = arguments; _extensions = extensions ?? Extensions.Default; _fixedResults = new TypeWithAnnotations[methodTypeParameters.Length]; _exactBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _upperBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _lowerBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _dependencies = null; _dependenciesDirty = false; } #if DEBUG internal string Dump() { var sb = new System.Text.StringBuilder(); sb.AppendLine("Method type inference internal state"); sb.AppendFormat("Inferring method type parameters <{0}>\n", string.Join(", ", _methodTypeParameters)); sb.Append("Formal parameter types ("); for (int i = 0; i < _formalParameterTypes.Length; ++i) { if (i != 0) { sb.Append(", "); } sb.Append(GetRefKind(i).ToParameterPrefix()); sb.Append(_formalParameterTypes[i]); } sb.Append("\n"); sb.AppendFormat("Argument types ({0})\n", string.Join(", ", from a in _arguments select a.Type)); if (_dependencies == null) { sb.AppendLine("Dependencies are not yet calculated"); } else { sb.AppendFormat("Dependencies are {0}\n", _dependenciesDirty ? "out of date" : "up to date"); sb.AppendLine("dependency matrix (Not dependent / Direct / Indirect / Unknown):"); for (int i = 0; i < _methodTypeParameters.Length; ++i) { for (int j = 0; j < _methodTypeParameters.Length; ++j) { switch (_dependencies[i, j]) { case Dependency.NotDependent: sb.Append("N"); break; case Dependency.Direct: sb.Append("D"); break; case Dependency.Indirect: sb.Append("I"); break; case Dependency.Unknown: sb.Append("U"); break; } } sb.AppendLine(); } } for (int i = 0; i < _methodTypeParameters.Length; ++i) { sb.AppendFormat("Method type parameter {0}: ", _methodTypeParameters[i].Name); var fixedType = _fixedResults[i]; if (!fixedType.HasType) { sb.Append("UNFIXED "); } else { sb.AppendFormat("FIXED to {0} ", fixedType); } sb.AppendFormat("upper bounds: ({0}) ", (_upperBounds[i] == null) ? "" : string.Join(", ", _upperBounds[i])); sb.AppendFormat("lower bounds: ({0}) ", (_lowerBounds[i] == null) ? "" : string.Join(", ", _lowerBounds[i])); sb.AppendFormat("exact bounds: ({0}) ", (_exactBounds[i] == null) ? "" : string.Join(", ", _exactBounds[i])); sb.AppendLine(); } return sb.ToString(); } #endif private RefKind GetRefKind(int index) { Debug.Assert(0 <= index && index < _formalParameterTypes.Length); return _formalParameterRefKinds.IsDefault ? RefKind.None : _formalParameterRefKinds[index]; } private ImmutableArray<TypeWithAnnotations> GetResults() { // Anything we didn't infer a type for, give the error type. // Note: the error type will have the same name as the name // of the type parameter we were trying to infer. This will give a // nice user experience where by we will show something like // the following: // // user types: customers.Select( // we show : IE<TResult> IE<Customer>.Select<Customer,TResult>(Func<Customer,TResult> selector) // // Initially we thought we'd just show ?. i.e.: // // IE<?> IE<Customer>.Select<Customer,?>(Func<Customer,?> selector) // // This is nice and concise. However, it falls down if there are multiple // type params that we have left. for (int i = 0; i < _methodTypeParameters.Length; i++) { if (_fixedResults[i].HasType) { if (!_fixedResults[i].Type.IsErrorType()) { continue; } var errorTypeName = _fixedResults[i].Type.Name; if (errorTypeName != null) { continue; } } _fixedResults[i] = TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(_constructedContainingTypeOfMethod, _methodTypeParameters[i].Name, 0, null, false)); } return _fixedResults.AsImmutable(); } private bool ValidIndex(int index) { return 0 <= index && index < _methodTypeParameters.Length; } private bool IsUnfixed(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return !_fixedResults[methodTypeParameterIndex].HasType; } private bool IsUnfixedTypeParameter(TypeWithAnnotations type) { Debug.Assert(type.HasType); if (type.TypeKind != TypeKind.TypeParameter) return false; TypeParameterSymbol typeParameter = (TypeParameterSymbol)type.Type; int ordinal = typeParameter.Ordinal; return ValidIndex(ordinal) && TypeSymbol.Equals(typeParameter, _methodTypeParameters[ordinal], TypeCompareKind.ConsiderEverything2) && IsUnfixed(ordinal); } private bool AllFixed() { for (int methodTypeParameterIndex = 0; methodTypeParameterIndex < _methodTypeParameters.Length; ++methodTypeParameterIndex) { if (IsUnfixed(methodTypeParameterIndex)) { return false; } } return true; } private void AddBound(TypeWithAnnotations addedBound, HashSet<TypeWithAnnotations>[] collectedBounds, TypeWithAnnotations methodTypeParameterWithAnnotations) { Debug.Assert(IsUnfixedTypeParameter(methodTypeParameterWithAnnotations)); var methodTypeParameter = (TypeParameterSymbol)methodTypeParameterWithAnnotations.Type; int methodTypeParameterIndex = methodTypeParameter.Ordinal; if (collectedBounds[methodTypeParameterIndex] == null) { collectedBounds[methodTypeParameterIndex] = new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); } collectedBounds[methodTypeParameterIndex].Add(addedBound); } private bool HasBound(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return _lowerBounds[methodTypeParameterIndex] != null || _upperBounds[methodTypeParameterIndex] != null || _exactBounds[methodTypeParameterIndex] != null; } private TypeSymbol GetFixedDelegateOrFunctionPointer(TypeSymbol delegateOrFunctionPointerType) { Debug.Assert((object)delegateOrFunctionPointerType != null); Debug.Assert(delegateOrFunctionPointerType.IsDelegateType() || delegateOrFunctionPointerType is FunctionPointerTypeSymbol); // We have a delegate where the input types use no unfixed parameters. Create // a substitution context; we can substitute unfixed parameters for themselves // since they don't actually occur in the inputs. (They may occur in the outputs, // or there may be input parameters fixed to _unfixed_ method type variables. // Both of those scenarios are legal.) var fixedArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(_methodTypeParameters.Length); for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { fixedArguments.Add(IsUnfixed(iParam) ? TypeWithAnnotations.Create(_methodTypeParameters[iParam]) : _fixedResults[iParam]); } TypeMap typeMap = new TypeMap(_constructedContainingTypeOfMethod, _methodTypeParameters, fixedArguments.ToImmutableAndFree()); return typeMap.SubstituteType(delegateOrFunctionPointerType).Type; } //////////////////////////////////////////////////////////////////////////////// // // Phases // private MethodTypeInferenceResult InferTypeArgs(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Type inference takes place in phases. Each phase will try to infer type // SPEC: arguments for more type parameters based on the findings of the previous // SPEC: phase. The first phase makes some initial inferences of bounds, whereas // SPEC: the second phase fixes type parameters to specific types and infers further // SPEC: bounds. The second phase may have to be repeated a number of times. InferTypeArgsFirstPhase(ref useSiteInfo); bool success = InferTypeArgsSecondPhase(binder, ref useSiteInfo); return new MethodTypeInferenceResult(success, GetResults()); } //////////////////////////////////////////////////////////////////////////////// // // The first phase // private void InferTypeArgsFirstPhase(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(!_arguments.IsDefault); // We expect that we have been handed a list of arguments and a list of the // formal parameter types they correspond to; all the details about named and // optional parameters have already been dealt with. // SPEC: For each of the method arguments Ei: for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { BoundExpression argument = _arguments[arg]; TypeWithAnnotations target = _formalParameterTypes[arg]; ExactOrBoundsKind kind = GetRefKind(arg).IsManagedReference() || target.Type.IsPointerType() ? ExactOrBoundsKind.Exact : ExactOrBoundsKind.LowerBound; MakeExplicitParameterTypeInferences(argument, target, kind, ref useSiteInfo); } } private void MakeExplicitParameterTypeInferences(BoundExpression argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If Ei is an anonymous function, an explicit type parameter // SPEC: inference is made from Ei to Ti. // (We cannot make an output type inference from a method group // at this time because we have no fixed types yet to use for // overload resolution.) // SPEC: * Otherwise, if Ei has a type U then a lower-bound inference // SPEC: or exact inference is made from U to Ti. // SPEC: * Otherwise, no inference is made for this argument if (argument.Kind == BoundKind.UnboundLambda && target.Type.GetDelegateType() is { }) { ExplicitParameterTypeInference(argument, target, ref useSiteInfo); } else if (argument.Kind != BoundKind.TupleLiteral || !MakeExplicitParameterTypeInferences((BoundTupleLiteral)argument, target, kind, ref useSiteInfo)) { // Either the argument is not a tuple literal, or we were unable to do the inference from its elements, let's try to infer from argument type if (IsReallyAType(argument.GetTypeOrFunctionType())) { ExactOrBoundsInference(kind, _extensions.GetTypeWithAnnotations(argument), target, ref useSiteInfo); } } } private bool MakeExplicitParameterTypeInferences(BoundTupleLiteral argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // try match up element-wise to the destination tuple (or underlying type) // Example: // if "(a: 1, b: "qq")" is passed as (T, U) arg // then T becomes int and U becomes string if (target.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return false; } var destination = (NamedTypeSymbol)target.Type; var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { // target is not a tuple of appropriate shape return false; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); // NOTE: we are losing tuple element names when recursing into argument expressions. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple literal is used to infer a single type param for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeExplicitParameterTypeInferences(sourceArgument, destType, kind, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // The second phase // private bool InferTypeArgsSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second phase proceeds as follows: // SPEC: * If no unfixed type parameters exist then type inference succeeds. // SPEC: * Otherwise, if there exists one or more arguments Ei with corresponding // SPEC: parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. // SPEC: * Whether or not the previous step actually made an inference, we must // SPEC: now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then type // SPEC: inference fails. // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. // SPEC: * Otherwise, we are unable to make progress and there are unfixed parameters. // SPEC: Type inference fails. // SPEC: * If type inference neither succeeds nor fails then the second phase is // SPEC: repeated until type inference succeeds or fails. (Since each repetition of // SPEC: the second phase either succeeds, fails or fixes an unfixed type parameter, // SPEC: the algorithm must terminate with no more repetitions than the number // SPEC: of type parameters. InitializeDependencies(); while (true) { var res = DoSecondPhase(binder, ref useSiteInfo); Debug.Assert(res != InferenceResult.NoProgress); if (res == InferenceResult.InferenceFailed) { return false; } if (res == InferenceResult.Success) { return true; } // Otherwise, we made some progress last time; do it again. } } private InferenceResult DoSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If no unfixed type parameters exist then type inference succeeds. if (AllFixed()) { return InferenceResult.Success; } // SPEC: * Otherwise, if there exists one or more arguments Ei with // SPEC: corresponding parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. MakeOutputTypeInferences(binder, ref useSiteInfo); // SPEC: * Whether or not the previous step actually made an inference, we // SPEC: must now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. InferenceResult res; res = FixNondependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. res = FixDependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, we are unable to make progress and there are // SPEC: unfixed parameters. Type inference fails. return InferenceResult.InferenceFailed; } private void MakeOutputTypeInferences(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Otherwise, for all arguments Ei with corresponding parameter type Ti // SPEC: where the output types contain unfixed type parameters but the input // SPEC: types do not, an output type inference is made from Ei to Ti. for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { var formalType = _formalParameterTypes[arg]; var argument = _arguments[arg]; MakeOutputTypeInferences(binder, argument, formalType, ref useSiteInfo); } } private void MakeOutputTypeInferences(Binder binder, BoundExpression argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (argument.Kind == BoundKind.TupleLiteral && (object)argument.Type == null) { MakeOutputTypeInferences(binder, (BoundTupleLiteral)argument, formalType, ref useSiteInfo); } else { if (HasUnfixedParamInOutputType(argument, formalType.Type) && !HasUnfixedParamInInputType(argument, formalType.Type)) { //UNDONE: if (argument->isTYPEORNAMESPACEERROR() && argumentType->IsErrorType()) //UNDONE: { //UNDONE: argumentType = GetTypeManager().GetErrorSym(); //UNDONE: } OutputTypeInference(binder, argument, formalType, ref useSiteInfo); } } } private void MakeOutputTypeInferences(Binder binder, BoundTupleLiteral argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (formalType.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return; } var destination = (NamedTypeSymbol)formalType.Type; Debug.Assert((object)argument.Type == null, "should not need to dig into elements if tuple has natural type"); var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { return; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeOutputTypeInferences(binder, sourceArgument, destType, ref useSiteInfo); } } private InferenceResult FixNondependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. return FixParameters((inferrer, index) => !inferrer.DependsOnAny(index), ref useSiteInfo); } private InferenceResult FixDependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * All unfixed type parameters Xi are fixed for which all of the following hold: // SPEC: * There is at least one type parameter Xj that depends on Xi. // SPEC: * Xi has a non-empty set of bounds. return FixParameters((inferrer, index) => inferrer.AnyDependsOn(index), ref useSiteInfo); } private InferenceResult FixParameters( Func<MethodTypeInferrer, int, bool> predicate, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Dependency is only defined for unfixed parameters. Therefore, fixing // a parameter may cause all of its dependencies to become no longer // dependent on anything. We need to first determine which parameters need to be // fixed, and then fix them all at once. var needsFixing = new bool[_methodTypeParameters.Length]; var result = InferenceResult.NoProgress; for (int param = 0; param < _methodTypeParameters.Length; param++) { if (IsUnfixed(param) && HasBound(param) && predicate(this, param)) { needsFixing[param] = true; result = InferenceResult.MadeProgress; } } for (int param = 0; param < _methodTypeParameters.Length; param++) { // Fix as much as you can, even if there are errors. That will // help with intellisense. if (needsFixing[param]) { if (!Fix(param, ref useSiteInfo)) { result = InferenceResult.InferenceFailed; } } } return result; } //////////////////////////////////////////////////////////////////////////////// // // Input types // private static bool DoesInputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then all the parameter types of T are // SPEC: input types of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; // No input types. } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; // No input types. } var parameters = delegateOrFunctionPointerType.DelegateOrFunctionPointerParameters(); if (parameters.IsDefaultOrEmpty) { return false; } foreach (var parameter in parameters) { if (parameter.Type.ContainsTypeParameter(typeParameter)) { return true; } } return false; } private bool HasUnfixedParamInInputType(BoundExpression pSource, TypeSymbol pDest) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesInputTypeContain(pSource, pDest, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output types // private static bool DoesOutputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then the return type of T is an output type // SPEC: of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; } MethodSymbol method = delegateOrFunctionPointerType switch { NamedTypeSymbol n => n.DelegateInvokeMethod, FunctionPointerTypeSymbol f => f.Signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType) }; if ((object)method == null || method.HasUseSiteError) { return false; } var returnType = method.ReturnType; if ((object)returnType == null) { return false; } return returnType.ContainsTypeParameter(typeParameter); } private bool HasUnfixedParamInOutputType(BoundExpression argument, TypeSymbol formalParameterType) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Dependence // private bool DependsDirectlyOn(int iParam, int jParam) { Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // SPEC: An unfixed type parameter Xi depends directly on an unfixed type // SPEC: parameter Xj if for some argument Ek with type Tk, Xj occurs // SPEC: in an input type of Ek and Xi occurs in an output type of Ek // SPEC: with type Tk. // We compute and record the Depends Directly On relationship once, in // InitializeDependencies, below. // At this point, everything should be unfixed. Debug.Assert(IsUnfixed(iParam)); Debug.Assert(IsUnfixed(jParam)); for (int iArg = 0, length = this.NumberArgumentsToProcess; iArg < length; iArg++) { var formalParameterType = _formalParameterTypes[iArg].Type; var argument = _arguments[iArg]; if (DoesInputTypeContain(argument, formalParameterType, _methodTypeParameters[jParam]) && DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } return false; } private void InitializeDependencies() { // We track dependencies by a two-d square array that gives the known // relationship between every pair of type parameters. The relationship // is one of: // // * Unknown relationship // * known to be not dependent // * known to depend directly // * known to depend indirectly // // Since dependency is only defined on unfixed type parameters, fixing a type // parameter causes all dependencies involving that parameter to go to // the "known to be not dependent" state. Since dependency is a transitive property, // this means that doing so may require recalculating the indirect dependencies // from the now possibly smaller set of dependencies. // // Therefore, when we detect that the dependency state has possibly changed // due to fixing, we change all "depends indirectly" back into "unknown" and // recalculate from the remaining "depends directly". // // This algorithm thereby yields an extremely bad (but extremely unlikely) worst // case for asymptotic performance. Suppose there are n type parameters. // "DependsTransitivelyOn" below costs O(n) because it must potentially check // all n type parameters to see if there is any k such that Xj => Xk => Xi. // "DeduceDependencies" calls "DependsTransitivelyOn" for each "Unknown" // pair, and there could be O(n^2) such pairs, so DependsTransitivelyOn is // worst-case O(n^3). And we could have to recalculate the dependency graph // after each type parameter is fixed in turn, so that would be O(n) calls to // DependsTransitivelyOn, giving this algorithm a worst case of O(n^4). // // Of course, in reality, n is going to almost always be on the order of // "smaller than 5", and there will not be O(n^2) dependency relationships // between type parameters; it is far more likely that the transitivity chains // will be very short and not branch or loop at all. This is much more likely to // be an O(n^2) algorithm in practice. Debug.Assert(_dependencies == null); _dependencies = new Dependency[_methodTypeParameters.Length, _methodTypeParameters.Length]; int iParam; int jParam; Debug.Assert(0 == (int)Dependency.Unknown); for (iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsDirectlyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Direct; } } } DeduceAllDependencies(); } private bool DependsOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); // SPEC: Xj depends on Xi if Xj depends directly on Xi, or if Xi depends // SPEC: directly on Xk and Xk depends on Xj. Thus "depends on" is the // SPEC: transitive but not reflexive closure of "depends directly on". Debug.Assert(0 <= iParam && iParam < _methodTypeParameters.Length); Debug.Assert(0 <= jParam && jParam < _methodTypeParameters.Length); if (_dependenciesDirty) { SetIndirectsToUnknown(); DeduceAllDependencies(); } return 0 != ((_dependencies[iParam, jParam]) & Dependency.DependsMask); } private bool DependsTransitivelyOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // Can we find Xk such that Xi depends on Xk and Xk depends on Xj? // If so, then Xi depends indirectly on Xj. (Note that there is // a minor optimization here -- the spec comment above notes that // we want Xi to depend DIRECTLY on Xk, and Xk to depend directly // or indirectly on Xj. But if we already know that Xi depends // directly OR indirectly on Xk and Xk depends on Xj, then that's // good enough.) for (int kParam = 0; kParam < _methodTypeParameters.Length; ++kParam) { if (((_dependencies[iParam, kParam]) & Dependency.DependsMask) != 0 && ((_dependencies[kParam, jParam]) & Dependency.DependsMask) != 0) { return true; } } return false; } private void DeduceAllDependencies() { bool madeProgress; do { madeProgress = DeduceDependencies(); } while (madeProgress); SetUnknownsToNotDependent(); _dependenciesDirty = false; } private bool DeduceDependencies() { Debug.Assert(_dependencies != null); bool madeProgress = false; for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { if (DependsTransitivelyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Indirect; madeProgress = true; } } } } return madeProgress; } private void SetUnknownsToNotDependent() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { _dependencies[iParam, jParam] = Dependency.NotDependent; } } } } private void SetIndirectsToUnknown() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Indirect) { _dependencies[iParam, jParam] = Dependency.Unknown; } } } } //////////////////////////////////////////////////////////////////////////////// // A fixed parameter never depends on anything, nor is depended upon by anything. private void UpdateDependenciesAfterFix(int iParam) { Debug.Assert(ValidIndex(iParam)); if (_dependencies == null) { return; } for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { _dependencies[iParam, jParam] = Dependency.NotDependent; _dependencies[jParam, iParam] = Dependency.NotDependent; } _dependenciesDirty = true; } private bool DependsOnAny(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(iParam, jParam)) { return true; } } return false; } private bool AnyDependsOn(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(jParam, iParam)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output type inferences // //////////////////////////////////////////////////////////////////////////////// private void OutputTypeInference(Binder binder, BoundExpression expression, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expression != null); Debug.Assert(target.HasType); // SPEC: An output type inference is made from an expression E to a type T // SPEC: in the following way: // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. if (InferredReturnTypeInference(expression, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (MethodGroupReturnTypeInference(binder, expression, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is an expression with type U then a lower-bound // SPEC: inference is made from U to T. var sourceType = _extensions.GetTypeWithAnnotations(expression); if (sourceType.HasType) { LowerBoundInference(sourceType, target, ref useSiteInfo); } // SPEC: * Otherwise, no inferences are made. } private bool InferredReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return false; } // cannot be hit, because an invalid delegate does not have an unfixed return type // this will be checked earlier. Debug.Assert((object)delegateType.DelegateInvokeMethod != null && !delegateType.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for valid delegate types."); var returnType = delegateType.DelegateInvokeMethod.ReturnTypeWithAnnotations; if (!returnType.HasType || returnType.SpecialType == SpecialType.System_Void) { return false; } var inferredReturnType = InferReturnType(source, delegateType, ref useSiteInfo); if (!inferredReturnType.HasType) { return false; } LowerBoundInference(inferredReturnType, returnType, ref useSiteInfo); return true; } private bool MethodGroupReturnTypeInference(Binder binder, BoundExpression source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (source.Kind is not (BoundKind.MethodGroup or BoundKind.UnconvertedAddressOfOperator)) { return false; } var delegateOrFunctionPointerType = target.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } if (delegateOrFunctionPointerType.IsFunctionPointer() != (source.Kind == BoundKind.UnconvertedAddressOfOperator)) { return false; } // this part of the code is only called if the targetType has an unfixed type argument in the output // type, which is not the case for invalid delegate invoke methods. var (method, isFunctionPointerResolution) = delegateOrFunctionPointerType switch { NamedTypeSymbol n => (n.DelegateInvokeMethod, false), FunctionPointerTypeSymbol f => (f.Signature, true), _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType), }; Debug.Assert(method is { HasUseSiteError: false }, "This method should only be called for valid delegate or function pointer types"); TypeWithAnnotations sourceReturnType = method.ReturnTypeWithAnnotations; if (!sourceReturnType.HasType || sourceReturnType.SpecialType == SpecialType.System_Void) { return false; } // At this point we are in the second phase; we know that all the input types are fixed. var fixedParameters = GetFixedDelegateOrFunctionPointer(delegateOrFunctionPointerType).DelegateOrFunctionPointerParameters(); if (fixedParameters.IsDefault) { return false; } CallingConventionInfo callingConventionInfo = isFunctionPointerResolution ? new CallingConventionInfo(method.CallingConvention, ((FunctionPointerMethodSymbol)method).GetCallingConventionModifiers()) : default; BoundMethodGroup originalMethodGroup = source as BoundMethodGroup ?? ((BoundUnconvertedAddressOfOperator)source).Operand; var returnType = MethodGroupReturnType(binder, originalMethodGroup, fixedParameters, method.RefKind, isFunctionPointerResolution, ref useSiteInfo, in callingConventionInfo); if (returnType.IsDefault || returnType.IsVoidType()) { return false; } LowerBoundInference(returnType, sourceReturnType, ref useSiteInfo); return true; } private TypeWithAnnotations MethodGroupReturnType( Binder binder, BoundMethodGroup source, ImmutableArray<ParameterSymbol> delegateParameters, RefKind delegateRefKind, bool isFunctionPointerResolution, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, in CallingConventionInfo callingConventionInfo) { var analyzedArguments = AnalyzedArguments.GetInstance(); Conversions.GetDelegateOrFunctionPointerArguments(source.Syntax, analyzedArguments, delegateParameters, binder.Compilation); var resolution = binder.ResolveMethodGroup(source, analyzedArguments, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: true, returnRefKind: delegateRefKind, // Since we are trying to infer the return type, it is not an input to resolving the method group returnType: null, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: in callingConventionInfo); TypeWithAnnotations type = default; // The resolution could be empty (e.g. if there are no methods in the BoundMethodGroup). if (!resolution.IsEmpty) { var result = resolution.OverloadResolutionResult; if (result.Succeeded) { type = _extensions.GetMethodGroupResultType(source, result.BestResult.Member); } } analyzedArguments.Free(); resolution.Free(); return type; } //////////////////////////////////////////////////////////////////////////////// // // Explicit parameter type inferences // private void ExplicitParameterTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: An explicit type parameter type inference is made from an expression // SPEC: E to a type T in the following way. // SPEC: If E is an explicitly typed anonymous function with parameter types // SPEC: U1...Uk and T is a delegate type or expression tree type with // SPEC: parameter types V1...Vk then for each Ui an exact inference is made // SPEC: from Ui to the corresponding Vi. if (source.Kind != BoundKind.UnboundLambda) { return; } UnboundLambda anonymousFunction = (UnboundLambda)source; if (!anonymousFunction.HasExplicitlyTypedParameterList) { return; } var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return; } var delegateParameters = delegateType.DelegateParameters(); if (delegateParameters.IsDefault) { return; } int size = delegateParameters.Length; if (anonymousFunction.ParameterCount < size) { size = anonymousFunction.ParameterCount; } // SPEC ISSUE: What should we do if there is an out/ref mismatch between an // SPEC ISSUE: anonymous function parameter and a delegate parameter? // SPEC ISSUE: The result will not be applicable no matter what, but should // SPEC ISSUE: we make any inferences? This is going to be an error // SPEC ISSUE: ultimately, but it might make a difference for intellisense or // SPEC ISSUE: other analysis. for (int i = 0; i < size; ++i) { ExactInference(anonymousFunction.ParameterTypeWithAnnotations(i), delegateParameters[i].TypeWithAnnotations, ref useSiteInfo); } } //////////////////////////////////////////////////////////////////////////////// // // Exact inferences // private void ExactInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An exact inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if U is the type U1? and V is the type V1? then an // SPEC: exact inference is made from U to V. if (ExactNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: exact bounds for Xi. if (ExactTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (ExactArrayInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. if (ExactConstructedInference(source, target, ref useSiteInfo)) { return; } // This can be valid via (where T : unmanaged) constraints if (ExactPointerInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise no inferences are made. } private bool ExactTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _exactBounds, target); return true; } return false; } private bool ExactArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (!source.Type.IsArray() || !target.Type.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source.Type; var arrayTarget = (ArrayTypeSymbol)target.Type; if (!arraySource.HasSameShapeAs(arrayTarget)) { return false; } ExactInference(arraySource.ElementTypeWithAnnotations, arrayTarget.ElementTypeWithAnnotations, ref useSiteInfo); return true; } private enum ExactOrBoundsKind { Exact, LowerBound, UpperBound, } private void ExactOrBoundsInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (kind) { case ExactOrBoundsKind.Exact: ExactInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.LowerBound: LowerBoundInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.UpperBound: UpperBoundInference(source, target, ref useSiteInfo); break; } } private bool ExactOrBoundsNullableInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); if (source.IsNullableType() && target.IsNullableType()) { ExactOrBoundsInference(kind, ((NamedTypeSymbol)source.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ((NamedTypeSymbol)target.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ref useSiteInfo); return true; } if (isNullableOnly(source) && isNullableOnly(target)) { ExactOrBoundsInference(kind, source.AsNotNullableReferenceType(), target.AsNotNullableReferenceType(), ref useSiteInfo); return true; } return false; // True if the type is nullable. static bool isNullableOnly(TypeWithAnnotations type) => type.NullableAnnotation.IsAnnotated(); } private bool ExactNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.Exact, source, target, ref useSiteInfo); } private bool LowerBoundTupleInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // NOTE: we are losing tuple element names when unwrapping tuple types to underlying types. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple type used to infer a single type param ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> targetTypes; if (!source.Type.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !target.Type.TryGetElementTypesWithAnnotationsIfTupleType(out targetTypes) || sourceTypes.Length != targetTypes.Length) { return false; } for (int i = 0; i < sourceTypes.Length; i++) { LowerBoundInference(sourceTypes[i], targetTypes[i], ref useSiteInfo); } return true; } private bool ExactConstructedInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. var namedSource = source.Type as NamedTypeSymbol; if ((object)namedSource == null) { return false; } var namedTarget = target.Type as NamedTypeSymbol; if ((object)namedTarget == null) { return false; } if (!TypeSymbol.Equals(namedSource.OriginalDefinition, namedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } ExactTypeArgumentInference(namedSource, namedTarget, ref useSiteInfo); return true; } private bool ExactPointerInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source.TypeKind == TypeKind.Pointer && target.TypeKind == TypeKind.Pointer) { ExactInference(((PointerTypeSymbol)source.Type).PointedAtTypeWithAnnotations, ((PointerTypeSymbol)target.Type).PointedAtTypeWithAnnotations, ref useSiteInfo); return true; } else if (source.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int sourceParameterCount } sourceSignature } && target.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int targetParameterCount } targetSignature } && sourceParameterCount == targetParameterCount) { if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } for (int i = 0; i < sourceParameterCount; i++) { ExactInference(sourceSignature.ParameterTypesWithAnnotations[i], targetSignature.ParameterTypesWithAnnotations[i], ref useSiteInfo); } ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); return true; } return false; } private static bool FunctionPointerCallingConventionsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { if (sourceSignature.CallingConvention != targetSignature.CallingConvention) { return false; } return (sourceSignature.GetCallingConventionModifiers(), targetSignature.GetCallingConventionModifiers()) switch { (null, null) => true, ({ } sourceModifiers, { } targetModifiers) when sourceModifiers.SetEquals(targetModifiers) => true, _ => false }; } private static bool FunctionPointerRefKindsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { return sourceSignature.RefKind == targetSignature.RefKind && (sourceSignature.ParameterRefKinds.IsDefault, targetSignature.ParameterRefKinds.IsDefault) switch { (true, false) or (false, true) => false, (true, true) => true, _ => sourceSignature.ParameterRefKinds.SequenceEqual(targetSignature.ParameterRefKinds) }; } private void ExactTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(sourceTypeArguments.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { ExactInference(sourceTypeArguments[arg], targetTypeArguments[arg], ref useSiteInfo); } sourceTypeArguments.Free(); targetTypeArguments.Free(); } //////////////////////////////////////////////////////////////////////////////// // // Lower-bound inferences // private void LowerBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: A lower-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. // SPEC ERROR: The spec should say "lower" here; we can safely make a lower-bound // SPEC ERROR: inference to nullable even though it is a generic struct. That is, // SPEC ERROR: if we have M<T>(T?, T) called with (char?, int) then we can infer // SPEC ERROR: lower bounds of char and int, and choose int. If we make an exact // SPEC ERROR: inference of char then type inference fails. if (LowerBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: lower bounds for Xi. if (LowerBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (LowerBoundArrayInference(source.Type, target.Type, ref useSiteInfo)) { return; } // UNDONE: At this point we could also do an inference from non-nullable U // UNDONE: to nullable V. // UNDONE: // UNDONE: We tried implementing lower bound nullable inference as follows: // UNDONE: // UNDONE: * Otherwise, if V is nullable type V1? and U is a non-nullable // UNDONE: struct type then an exact inference is made from U to V1. // UNDONE: // UNDONE: However, this causes an unfortunate interaction with what // UNDONE: looks like a bug in our implementation of section 15.2 of // UNDONE: the specification. Namely, it appears that the code which // UNDONE: checks whether a given method is compatible with // UNDONE: a delegate type assumes that if method type inference succeeds, // UNDONE: then the inferred types are compatible with the delegate types. // UNDONE: This is not necessarily so; the inferred types could be compatible // UNDONE: via a conversion other than reference or identity. // UNDONE: // UNDONE: We should take an action item to investigate this problem. // UNDONE: Until then, we will turn off the proposed lower bound nullable // UNDONE: inference. // if (LowerBoundNullableInference(pSource, pDest)) // { // return; // } if (LowerBoundTupleInference(source, target, ref useSiteInfo)) { return; } // SPEC: Otherwise... many cases for constructed generic types. if (LowerBoundConstructedInference(source.Type, target.Type, ref useSiteInfo)) { return; } if (LowerBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool LowerBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _lowerBounds, target); return true; } return false; } private static TypeWithAnnotations GetMatchingElementType(ArrayTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // It might be an array of same rank. if (target.IsArray()) { var arrayTarget = (ArrayTypeSymbol)target; if (!arrayTarget.HasSameShapeAs(source)) { return default; } return arrayTarget.ElementTypeWithAnnotations; } // Or it might be IEnum<T> and source is rank one. if (!source.IsSZArray) { return default; } // Arrays are specified as being convertible to IEnumerable<T>, ICollection<T> and // IList<T>; we also honor their convertibility to IReadOnlyCollection<T> and // IReadOnlyList<T>, and make inferences accordingly. if (!target.IsPossibleArrayGenericInterface()) { return default; } return ((NamedTypeSymbol)target).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); } private bool LowerBoundArrayInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!source.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source; var elementSource = arraySource.ElementTypeWithAnnotations; var elementTarget = GetMatchingElementType(arraySource, target, ref useSiteInfo); if (!elementTarget.HasType) { return false; } if (elementSource.Type.IsReferenceType) { LowerBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool LowerBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.LowerBound, source, target, ref useSiteInfo); } private bool LowerBoundConstructedInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget == null) { return false; } if (constructedTarget.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed class or struct type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a constructed interface or delegate type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, constructedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedSource.IsInterface || constructedSource.IsDelegateType()) { LowerBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> then an exact ... // SPEC: * ... and U is a type parameter with effective base class ... // SPEC: * ... and U is a type parameter with an effective base class which inherits ... if (LowerBoundClassInference(source, constructedTarget, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if V is an interface type C<V1...Vk> and U is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an exact ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... if (LowerBoundInterfaceInference(source, constructedTarget, ref useSiteInfo)) { return true; } return false; } private bool LowerBoundClassInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (target.TypeKind != TypeKind.Class) { return false; } // Spec: 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with effective base class C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with an effective base class which inherits directly or indirectly from // SPEC: C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. NamedTypeSymbol sourceBase = null; if (source.TypeKind == TypeKind.Class) { sourceBase = source.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } else if (source.TypeKind == TypeKind.TypeParameter) { sourceBase = ((TypeParameterSymbol)source).EffectiveBaseClass(ref useSiteInfo); } while ((object)sourceBase != null) { if (TypeSymbol.Equals(sourceBase.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(sourceBase, target, ref useSiteInfo); return true; } sourceBase = sourceBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool LowerBoundInterfaceInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!target.IsInterface) { return false; } // Spec 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V [target] is an interface type C<V1...Vk> and U [source] is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an // SPEC: exact, upper-bound, or lower-bound inference ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... ImmutableArray<NamedTypeSymbol> allInterfaces; switch (source.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: allInterfaces = source.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); break; case TypeKind.TypeParameter: var typeParameter = (TypeParameterSymbol)source; allInterfaces = typeParameter.EffectiveBaseClass(ref useSiteInfo). AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo). Concat(typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); break; default: return false; } // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.In); NamedTypeSymbol matchingInterface = GetInterfaceInferenceBound(allInterfaces, target); if ((object)matchingInterface == null) { return false; } LowerBoundTypeArgumentInference(matchingInterface, target, ref useSiteInfo); return true; } internal static ImmutableArray<NamedTypeSymbol> ModuloReferenceTypeNullabilityDifferences(ImmutableArray<NamedTypeSymbol> interfaces, VarianceKind variance) { var dictionary = PooledDictionaryIgnoringNullableModifiersForReferenceTypes.GetInstance(); foreach (var @interface in interfaces) { if (dictionary.TryGetValue(@interface, out var found)) { var merged = (NamedTypeSymbol)found.MergeEquivalentTypes(@interface, variance); dictionary[@interface] = merged; } else { dictionary.Add(@interface, @interface); } } var result = dictionary.Count != interfaces.Length ? dictionary.Values.ToImmutableArray() : interfaces; dictionary.Free(); return result; } private void LowerBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then a lower bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then an upper bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool LowerBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { UpperBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { LowerBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Upper-bound inferences // private void UpperBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An upper-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. if (UpperBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: upper bounds for Xi. if (UpperBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (UpperBoundArrayInference(source, target, ref useSiteInfo)) { return; } Debug.Assert(source.Type.IsReferenceType || source.Type.IsFunctionPointer()); // NOTE: spec would ask us to do the following checks, but since the value types // are trivially handled as exact inference in the callers, we do not have to. //if (ExactTupleInference(source, target, ref useSiteInfo)) //{ // return; //} // SPEC: * Otherwise... cases for constructed types if (UpperBoundConstructedInference(source, target, ref useSiteInfo)) { return; } if (UpperBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool UpperBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of upper bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _upperBounds, target); return true; } return false; } private bool UpperBoundArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!target.Type.IsArray()) { return false; } var arrayTarget = (ArrayTypeSymbol)target.Type; var elementTarget = arrayTarget.ElementTypeWithAnnotations; var elementSource = GetMatchingElementType(arrayTarget, source.Type, ref useSiteInfo); if (!elementSource.HasType) { return false; } if (elementSource.Type.IsReferenceType) { UpperBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool UpperBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.UpperBound, source, target, ref useSiteInfo); } private bool UpperBoundConstructedInference(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations targetWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceWithAnnotations.HasType); Debug.Assert(targetWithAnnotations.HasType); var source = sourceWithAnnotations.Type; var target = targetWithAnnotations.Type; var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource == null) { return false; } if (constructedSource.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is // SPEC: C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedTarget.IsInterface || constructedTarget.IsDelegateType()) { UpperBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact ... if (UpperBoundClassInference(constructedSource, target, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if U is an interface type C<U1...Uk> and V is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... if (UpperBoundInterfaceInference(constructedSource, target, ref useSiteInfo)) { return true; } return false; } private bool UpperBoundClassInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (source.TypeKind != TypeKind.Class || target.TypeKind != TypeKind.Class) { return false; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact // SPEC: inference is made from each Ui to the corresponding Vi. var targetBase = target.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)targetBase != null) { if (TypeSymbol.Equals(targetBase.OriginalDefinition, source.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(source, targetBase, ref useSiteInfo); return true; } targetBase = targetBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool UpperBoundInterfaceInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!source.IsInterface) { return false; } // SPEC: * Otherwise, if U [source] is an interface type C<U1...Uk> and V [target] is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... switch (target.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: break; default: return false; } ImmutableArray<NamedTypeSymbol> allInterfaces = target.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.Out); NamedTypeSymbol bestInterface = GetInterfaceInferenceBound(allInterfaces, source); if ((object)bestInterface == null) { return false; } UpperBoundTypeArgumentInference(source, bestInterface, ref useSiteInfo); return true; } private void UpperBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then an upper-bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then a lower-bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool UpperBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { LowerBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { UpperBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // Fixing // private bool Fix(int iParam, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(IsUnfixed(iParam)); var typeParameter = _methodTypeParameters[iParam]; var exact = _exactBounds[iParam]; var lower = _lowerBounds[iParam]; var upper = _upperBounds[iParam]; var best = Fix(_compilation, _conversions, typeParameter, exact, lower, upper, ref useSiteInfo); if (!best.HasType) { return false; } #if DEBUG if (_conversions.IncludeNullability) { // If the first attempt succeeded, the result should be the same as // the second attempt, although perhaps with different nullability. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var withoutNullability = Fix(_compilation, _conversions.WithNullability(false), typeParameter, exact, lower, upper, ref discardedUseSiteInfo); // https://github.com/dotnet/roslyn/issues/27961 Results may differ by tuple names or dynamic. // See NullableReferenceTypesTests.TypeInference_TupleNameDifferences_01 for example. Debug.Assert(best.Type.Equals(withoutNullability.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); } #endif _fixedResults[iParam] = best; UpdateDependenciesAfterFix(iParam); return true; } private static TypeWithAnnotations Fix( CSharpCompilation compilation, ConversionsBase conversions, TypeParameterSymbol typeParameter, HashSet<TypeWithAnnotations>? exact, HashSet<TypeWithAnnotations>? lower, HashSet<TypeWithAnnotations>? upper, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // UNDONE: This method makes a lot of garbage. // SPEC: An unfixed type parameter with a set of bounds is fixed as follows: // SPEC: * The set of candidate types starts out as the set of all types in // SPEC: the bounds. // SPEC: * We then examine each bound in turn. For each exact bound U of Xi, // SPEC: all types which are not identical to U are removed from the candidate set. // Optimization: if we have two or more exact bounds, fixing is impossible. var candidates = new Dictionary<TypeWithAnnotations, TypeWithAnnotations>(EqualsIgnoringDynamicTupleNamesAndNullabilityComparer.Instance); Debug.Assert(!containsFunctionTypes(exact)); Debug.Assert(!containsFunctionTypes(upper)); // Function types are dropped if there are any non-function types. if (containsFunctionTypes(lower) && (containsNonFunctionTypes(lower) || containsNonFunctionTypes(exact) || containsNonFunctionTypes(upper))) { lower = removeFunctionTypes(lower); } // Optimization: if we have one exact bound then we need not add any // inexact bounds; we're just going to remove them anyway. if (exact == null) { if (lower != null) { // Lower bounds represent co-variance. AddAllCandidates(candidates, lower, VarianceKind.Out, conversions); } if (upper != null) { // Lower bounds represent contra-variance. AddAllCandidates(candidates, upper, VarianceKind.In, conversions); } } else { // Exact bounds represent invariance. AddAllCandidates(candidates, exact, VarianceKind.None, conversions); if (candidates.Count >= 2) { return default; } } if (candidates.Count == 0) { return default; } // Don't mutate the collection as we're iterating it. var initialCandidates = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllCandidates(candidates, initialCandidates); // SPEC: For each lower bound U of Xi all types to which there is not an // SPEC: implicit conversion from U are removed from the candidate set. if (lower != null) { MergeOrRemoveCandidates(candidates, lower, initialCandidates, conversions, VarianceKind.Out, ref useSiteInfo); } // SPEC: For each upper bound U of Xi all types from which there is not an // SPEC: implicit conversion to U are removed from the candidate set. if (upper != null) { MergeOrRemoveCandidates(candidates, upper, initialCandidates, conversions, VarianceKind.In, ref useSiteInfo); } initialCandidates.Clear(); GetAllCandidates(candidates, initialCandidates); // SPEC: * If among the remaining candidate types there is a unique type V to // SPEC: which there is an implicit conversion from all the other candidate // SPEC: types, then the parameter is fixed to V. TypeWithAnnotations best = default; foreach (var candidate in initialCandidates) { foreach (var candidate2 in initialCandidates) { if (!candidate.Equals(candidate2, TypeCompareKind.ConsiderEverything) && !ImplicitConversionExists(candidate2, candidate, ref useSiteInfo, conversions.WithNullability(false))) { goto OuterBreak; } } if (!best.HasType) { best = candidate; } else { Debug.Assert(!best.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // best candidate is not unique best = default; break; } OuterBreak: ; } initialCandidates.Free(); if (isFunctionType(best, out var functionType)) { // Realize the type as TDelegate, or Expression<TDelegate> if the type parameter // is constrained to System.Linq.Expressions.Expression. var resultType = functionType.GetInternalDelegateType(); if (hasExpressionTypeConstraint(typeParameter)) { var expressionOfTType = compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T); resultType = expressionOfTType.Construct(resultType); } best = TypeWithAnnotations.Create(resultType, best.NullableAnnotation); } return best; static bool containsFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => isFunctionType(t, out _)) == true; } static bool containsNonFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => !isFunctionType(t, out _)) == true; } static bool isFunctionType(TypeWithAnnotations type, [NotNullWhen(true)] out FunctionTypeSymbol? functionType) { functionType = type.Type as FunctionTypeSymbol; return functionType is not null; } static bool hasExpressionTypeConstraint(TypeParameterSymbol typeParameter) { var constraintTypes = typeParameter.ConstraintTypesNoUseSiteDiagnostics; return constraintTypes.Any(t => isExpressionType(t.Type)); } static bool isExpressionType(TypeSymbol? type) { while (type is { }) { if (type.IsGenericOrNonGenericExpressionType(out _)) { return true; } type = type.BaseTypeNoUseSiteDiagnostics; } return false; } static HashSet<TypeWithAnnotations>? removeFunctionTypes(HashSet<TypeWithAnnotations> types) { HashSet<TypeWithAnnotations>? updated = null; foreach (var type in types) { if (!isFunctionType(type, out _)) { updated ??= new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); updated.Add(type); } } return updated; } } private static bool ImplicitConversionExists(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations destinationWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionsBase conversions) { var source = sourceWithAnnotations.Type; var destination = destinationWithAnnotations.Type; // SPEC VIOLATION: For the purpose of algorithm in Fix method, dynamic type is not considered convertible to any other type, including object. if (source.IsDynamic() && !destination.IsDynamic()) { return false; } if (!conversions.HasTopLevelNullabilityImplicitConversion(sourceWithAnnotations, destinationWithAnnotations)) { return false; } return conversions.ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo).Exists; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Inferred return type // private TypeWithAnnotations InferReturnType(BoundExpression source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)target != null); Debug.Assert(target.IsDelegateType()); Debug.Assert((object)target.DelegateInvokeMethod != null && !target.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for legal delegate types."); Debug.Assert(!target.DelegateInvokeMethod.ReturnsVoid); // We should not be computing the inferred return type unless we are converting // to a delegate type where all the input types are fixed. Debug.Assert(!HasUnfixedParamInInputType(source, target)); // Spec 7.5.2.12: Inferred return type: // The inferred return type of an anonymous function F is used during // type inference and overload resolution. The inferred return type // can only be determined for an anonymous function where all parameter // types are known, either because they are explicitly given, provided // through an anonymous function conversion, or inferred during type // inference on an enclosing generic method invocation. // The inferred return type is determined as follows: // * If the body of F is an expression (that has a type) then the // inferred return type of F is the type of that expression. // * If the body of F is a block and the set of expressions in the // blocks return statements has a best common type T then the // inferred return type of F is T. // * Otherwise, a return type cannot be inferred for F. if (source.Kind != BoundKind.UnboundLambda) { return default; } var anonymousFunction = (UnboundLambda)source; if (anonymousFunction.HasSignature) { // Optimization: // We know that the anonymous function has a parameter list. If it does not // have the same arity as the delegate, then it cannot possibly be applicable. // Rather than have type inference fail, we will simply not make a return // type inference and have type inference continue on. Either inference // will fail, or we will infer a nonapplicable method. Either way, there // is no change to the semantics of overload resolution. var originalDelegateParameters = target.DelegateParameters(); if (originalDelegateParameters.IsDefault) { return default; } if (originalDelegateParameters.Length != anonymousFunction.ParameterCount) { return default; } } var fixedDelegate = (NamedTypeSymbol)GetFixedDelegateOrFunctionPointer(target); var fixedDelegateParameters = fixedDelegate.DelegateParameters(); // Optimization: // Similarly, if we have an entirely fixed delegate and an explicitly typed // anonymous function, then the parameter types had better be identical. // If not, applicability will eventually fail, so there is no semantic // difference caused by failing to make a return type inference. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < anonymousFunction.ParameterCount; ++p) { if (!anonymousFunction.ParameterType(p).Equals(fixedDelegateParameters[p].Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return default; } } } // Future optimization: We could return default if the delegate has out or ref parameters // and the anonymous function is an implicitly typed lambda. It will not be applicable. // We have an entirely fixed delegate parameter list, which is of the same arity as // the anonymous function parameter list, and possibly exactly the same types if // the anonymous function is explicitly typed. Make an inference from the // delegate parameters to the return type. return anonymousFunction.InferReturnType(_conversions, fixedDelegate, ref useSiteInfo); } /// <summary> /// Return the interface with an original definition matches /// the original definition of the target. If the are no matches, /// or multiple matches, the return value is null. /// </summary> private static NamedTypeSymbol GetInterfaceInferenceBound(ImmutableArray<NamedTypeSymbol> interfaces, NamedTypeSymbol target) { Debug.Assert(target.IsInterface); NamedTypeSymbol matchingInterface = null; foreach (var currentInterface in interfaces) { if (TypeSymbol.Equals(currentInterface.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { if ((object)matchingInterface == null) { matchingInterface = currentInterface; } else if (!TypeSymbol.Equals(matchingInterface, currentInterface, TypeCompareKind.ConsiderEverything)) { // Not unique. Bail out. return null; } } } return matchingInterface; } //////////////////////////////////////////////////////////////////////////////// // // Helper methods // //////////////////////////////////////////////////////////////////////////////// // // In error recovery and reporting scenarios we sometimes end up in a situation // like this: // // x.Goo( y=> // // and the question is, "is Goo a valid extension method of x?" If Goo is // generic, then Goo will be something like: // // static Blah Goo<T>(this Bar<T> bar, Func<T, T> f){ ... } // // What we would like to know is: given _only_ the expression x, can we infer // what T is in Bar<T> ? If we can, then for error recovery and reporting // we can provisionally consider Goo to be an extension method of x. If we // cannot deduce this just from x then we should consider Goo to not be an // extension method of x, at least until we have more information. // // Clearly it is pointless to run multiple phases public static ImmutableArray<TypeWithAnnotations> InferTypeArgumentsFromFirstArgument( CSharpCompilation compilation, ConversionsBase conversions, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)method != null); Debug.Assert(method.Arity > 0); Debug.Assert(!arguments.IsDefault); // We need at least one formal parameter type and at least one argument. if ((method.ParameterCount < 1) || (arguments.Length < 1)) { return default(ImmutableArray<TypeWithAnnotations>); } Debug.Assert(!method.GetParameterType(0).IsDynamic()); var constructedFromMethod = method.ConstructedFrom; var inferrer = new MethodTypeInferrer( compilation, conversions, constructedFromMethod.TypeParameters, constructedFromMethod.ContainingType, constructedFromMethod.GetParameterTypes(), constructedFromMethod.ParameterRefKinds, arguments, extensions: null); if (!inferrer.InferTypeArgumentsFromFirstArgument(ref useSiteInfo)) { return default(ImmutableArray<TypeWithAnnotations>); } return inferrer.GetInferredTypeArguments(); } //////////////////////////////////////////////////////////////////////////////// private bool InferTypeArgumentsFromFirstArgument(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(_formalParameterTypes.Length >= 1); Debug.Assert(!_arguments.IsDefault); Debug.Assert(_arguments.Length >= 1); var dest = _formalParameterTypes[0]; var argument = _arguments[0]; TypeSymbol source = argument.Type; // Rule out lambdas, nulls, and so on. if (!IsReallyAType(source)) { return false; } LowerBoundInference(_extensions.GetTypeWithAnnotations(argument), dest, ref useSiteInfo); // Now check to see that every type parameter used by the first // formal parameter type was successfully inferred. for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { TypeParameterSymbol pParam = _methodTypeParameters[iParam]; if (!dest.Type.ContainsTypeParameter(pParam)) { continue; } Debug.Assert(IsUnfixed(iParam)); if (!HasBound(iParam) || !Fix(iParam, ref useSiteInfo)) { return false; } } return true; } #nullable enable /// <summary> /// Return the inferred type arguments using null /// for any type arguments that were not inferred. /// </summary> private ImmutableArray<TypeWithAnnotations> GetInferredTypeArguments() { return _fixedResults.AsImmutable(); } private static bool IsReallyAType(TypeSymbol? type) { return type is { } && !type.IsErrorType() && !type.IsVoidType(); } private static void GetAllCandidates(Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, ArrayBuilder<TypeWithAnnotations> builder) { builder.AddRange(candidates.Values); } private static void AddAllCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, VarianceKind variance, ConversionsBase conversions) { foreach (var candidate in bounds) { var type = candidate; if (!conversions.IncludeNullability) { // https://github.com/dotnet/roslyn/issues/30534: Should preserve // distinct "not computed" state from initial binding. type = type.SetUnknownNullabilityForReferenceTypes(); } AddOrMergeCandidate(candidates, type, variance, conversions); } } private static void AddOrMergeCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { Debug.Assert(conversions.IncludeNullability || newCandidate.SetUnknownNullabilityForReferenceTypes().Equals(newCandidate, TypeCompareKind.ConsiderEverything)); if (candidates.TryGetValue(newCandidate, out TypeWithAnnotations oldCandidate)) { MergeAndReplaceIfStillCandidate(candidates, oldCandidate, newCandidate, variance, conversions); } else { candidates.Add(newCandidate, newCandidate); } } private static void MergeOrRemoveCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, ArrayBuilder<TypeWithAnnotations> initialCandidates, ConversionsBase conversions, VarianceKind variance, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(variance == VarianceKind.In || variance == VarianceKind.Out); // SPEC: For each lower (upper) bound U of Xi all types to which there is not an // SPEC: implicit conversion from (to) U are removed from the candidate set. var comparison = conversions.IncludeNullability ? TypeCompareKind.ConsiderEverything : TypeCompareKind.IgnoreNullableModifiersForReferenceTypes; foreach (var bound in bounds) { foreach (var candidate in initialCandidates) { if (bound.Equals(candidate, comparison)) { continue; } TypeWithAnnotations source; TypeWithAnnotations destination; if (variance == VarianceKind.Out) { source = bound; destination = candidate; } else { source = candidate; destination = bound; } if (!ImplicitConversionExists(source, destination, ref useSiteInfo, conversions.WithNullability(false))) { candidates.Remove(candidate); if (conversions.IncludeNullability && candidates.TryGetValue(bound, out var oldBound)) { // merge the nullability from candidate into bound var oldAnnotation = oldBound.NullableAnnotation; var newAnnotation = oldAnnotation.MergeNullableAnnotation(candidate.NullableAnnotation, variance); if (oldAnnotation != newAnnotation) { var newBound = TypeWithAnnotations.Create(oldBound.Type, newAnnotation); candidates[bound] = newBound; } } } else if (bound.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // SPEC: 4.7 The Dynamic Type // Type inference (7.5.2) will prefer dynamic over object if both are candidates. // // This rule doesn't have to be implemented explicitly due to special handling of // conversions from dynamic in ImplicitConversionExists helper. // MergeAndReplaceIfStillCandidate(candidates, candidate, bound, variance, conversions); } } } } private static void MergeAndReplaceIfStillCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations oldCandidate, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { // We make an exception when new candidate is dynamic, for backwards compatibility if (newCandidate.Type.IsDynamic()) { return; } if (candidates.TryGetValue(oldCandidate, out TypeWithAnnotations latest)) { // Note: we're ignoring the variance used merging previous candidates into `latest`. // If that variance is different than `variance`, we might infer the wrong nullability, but in that case, // we assume we'll report a warning when converting the arguments to the inferred parameter types. // (For instance, with F<T>(T x, T y, IIn<T> z) and interface IIn<in T> and interface IIOut<out T>, the // call F(IOut<object?>, IOut<object!>, IIn<IOut<object!>>) should find a nullability mismatch. Instead, // we'll merge the lower bounds IOut<object?> with IOut<object!> (using VarianceKind.Out) to produce // IOut<object?>, then merge that result with upper bound IOut<object!> (using VarianceKind.In) // to produce IOut<object?>. But then conversion of argument IIn<IOut<object!>> to parameter // IIn<IOut<object?>> will generate a warning at that point.) TypeWithAnnotations merged = latest.MergeEquivalentTypes(newCandidate, variance); candidates[oldCandidate] = merged; } } /// <summary> /// This is a comparer that ignores differences in dynamic-ness and tuple names. /// But it has a special case for top-level object vs. dynamic for purpose of method type inference. /// </summary> private sealed class EqualsIgnoringDynamicTupleNamesAndNullabilityComparer : EqualityComparer<TypeWithAnnotations> { internal static readonly EqualsIgnoringDynamicTupleNamesAndNullabilityComparer Instance = new EqualsIgnoringDynamicTupleNamesAndNullabilityComparer(); public override int GetHashCode(TypeWithAnnotations obj) { return obj.Type.GetHashCode(); } public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y) { // We do a equality test ignoring dynamic and tuple names differences, // but dynamic and object are not considered equal for backwards compatibility. if (x.Type.IsDynamic() ^ y.Type.IsDynamic()) { return false; } return x.Equals(y, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Diagnostics.CodeAnalysis; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; using Roslyn.Utilities; /* SPEC: Type inference occurs as part of the compile-time processing of a method invocation and takes place before the overload resolution step of the invocation. When a particular method group is specified in a method invocation, and no type arguments are specified as part of the method invocation, type inference is applied to each generic method in the method group. If type inference succeeds, then the inferred type arguments are used to determine the types of formal parameters for subsequent overload resolution. If overload resolution chooses a generic method as the one to invoke then the inferred type arguments are used as the actual type arguments for the invocation. If type inference for a particular method fails, that method does not participate in overload resolution. The failure of type inference, in and of itself, does not cause a compile-time error. However, it often leads to a compile-time error when overload resolution then fails to find any applicable methods. If the supplied number of arguments is different than the number of parameters in the method, then inference immediately fails. Otherwise, assume that the generic method has the following signature: Tr M<X1...Xn>(T1 x1 ... Tm xm) With a method call of the form M(E1...Em) the task of type inference is to find unique type arguments S1...Sn for each of the type parameters X1...Xn so that the call M<S1...Sn>(E1...Em)becomes valid. During the process of inference each type parameter Xi is either fixed to a particular type Si or unfixed with an associated set of bounds. Each of the bounds is some type T. Each bound is classified as an upper bound, lower bound or exact bound. Initially each type variable Xi is unfixed with an empty set of bounds. */ // This file contains the implementation for method type inference on calls (with // arguments, and method type inference on conversion of method groups to delegate // types (which will not have arguments.) namespace Microsoft.CodeAnalysis.CSharp { internal static class PooledDictionaryIgnoringNullableModifiersForReferenceTypes { private static readonly ObjectPool<PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>> s_poolInstance = PooledDictionary<NamedTypeSymbol, NamedTypeSymbol>.CreatePool(Symbols.SymbolEqualityComparer.IgnoringNullable); internal static PooledDictionary<NamedTypeSymbol, NamedTypeSymbol> GetInstance() { var instance = s_poolInstance.Allocate(); Debug.Assert(instance.Count == 0); return instance; } } // Method type inference can fail, but we still might have some best guesses. internal struct MethodTypeInferenceResult { public readonly ImmutableArray<TypeWithAnnotations> InferredTypeArguments; public readonly bool Success; public MethodTypeInferenceResult( bool success, ImmutableArray<TypeWithAnnotations> inferredTypeArguments) { this.Success = success; this.InferredTypeArguments = inferredTypeArguments; } } internal sealed class MethodTypeInferrer { internal abstract class Extensions { internal static readonly Extensions Default = new DefaultExtensions(); internal abstract TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr); internal abstract TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method); private sealed class DefaultExtensions : Extensions { internal override TypeWithAnnotations GetTypeWithAnnotations(BoundExpression expr) { return TypeWithAnnotations.Create(expr.GetTypeOrFunctionType()); } internal override TypeWithAnnotations GetMethodGroupResultType(BoundMethodGroup group, MethodSymbol method) { return method.ReturnTypeWithAnnotations; } } } private enum InferenceResult { InferenceFailed, MadeProgress, NoProgress, Success } private enum Dependency { Unknown = 0x00, NotDependent = 0x01, DependsMask = 0x10, Direct = 0x11, Indirect = 0x12 } private readonly CSharpCompilation _compilation; private readonly ConversionsBase _conversions; private readonly ImmutableArray<TypeParameterSymbol> _methodTypeParameters; private readonly NamedTypeSymbol _constructedContainingTypeOfMethod; private readonly ImmutableArray<TypeWithAnnotations> _formalParameterTypes; private readonly ImmutableArray<RefKind> _formalParameterRefKinds; private readonly ImmutableArray<BoundExpression> _arguments; private readonly Extensions _extensions; private readonly TypeWithAnnotations[] _fixedResults; private readonly HashSet<TypeWithAnnotations>[] _exactBounds; private readonly HashSet<TypeWithAnnotations>[] _upperBounds; private readonly HashSet<TypeWithAnnotations>[] _lowerBounds; // https://github.com/dotnet/csharplang/blob/main/proposals/csharp-9.0/nullable-reference-types-specification.md#fixing // If the resulting candidate is a reference type and *all* of the exact bounds or *any* of // the lower bounds are nullable reference types, `null` or `default`, then `?` is added to // the resulting candidate, making it a nullable reference type. // // This set of bounds effectively tracks whether a typeless null expression (i.e. null // literal) was used as an argument to a parameter whose type is one of this method's type // parameters. Because such expressions only occur as by-value inputs, we only need to track // the lower bounds, not the exact or upper bounds. private readonly NullableAnnotation[] _nullableAnnotationLowerBounds; private Dependency[,] _dependencies; // Initialized lazily private bool _dependenciesDirty; /// <summary> /// For error recovery, we allow a mismatch between the number of arguments and parameters /// during type inference. This sometimes enables inferring the type for a lambda parameter. /// </summary> private int NumberArgumentsToProcess => System.Math.Min(_arguments.Length, _formalParameterTypes.Length); public static MethodTypeInferenceResult Infer( Binder binder, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, // We are attempting to build a map from method type parameters // to inferred type arguments. NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, // We have some unusual requirements for the types that flow into the inference engine. // Consider the following inference problems: // // Scenario one: // // class C<T> // { // delegate Y FT<X, Y>(T t, X x); // static void M<U, V>(U u, FT<U, V> f); // ... // C<double>.M(123, (t,x)=>t+x); // // From the first argument we infer that U is int. How now must we make an inference on // the second argument? The *declared* type of the formal is C<T>.FT<U,V>. The // actual type at the time of inference is known to be C<double>.FT<int, something> // where "something" is to be determined by inferring the return type of the // lambda by determine the type of "double + int". // // Therefore when we do type inference, if a formal parameter type is a generic delegate // then *its* formal parameter types must be the formal parameter types of the // *constructed* generic delegate C<double>.FT<...>, not C<T>.FT<...>. // // One would therefore suppose that we'd expect the formal parameter types to here // be passed in with the types constructed with the information known from the // call site, not the declared types. // // Contrast that with this scenario: // // Scenario Two: // // interface I<T> // { // void M<U>(T t, U u); // } // ... // static void Goo<V>(V v, I<V> iv) // { // iv.M(v, ""); // } // // Obviously inference should succeed here; it should infer that U is string. // // But consider what happens during the inference process on the first argument. // The first thing we will do is say "what's the type of the argument? V. What's // the type of the corresponding formal parameter? The first formal parameter of // I<V>.M<whatever> is of type V. The inference engine will then say "V is a // method type parameter, and therefore we have an inference from V to V". // But *V* is not one of the method type parameters being inferred; the only // method type parameter being inferred here is *U*. // // This is perhaps some evidence that the formal parameters passed in should be // the formal parameters of the *declared* method; in this case, (T, U), not // the formal parameters of the *constructed* method, (V, U). // // However, one might make the argument that no, we could just add a check // to ensure that if we see a method type parameter as a formal parameter type, // then we only perform the inference if the method type parameter is a type // parameter of the method for which inference is being performed. // // Unfortunately, that does not work either: // // Scenario three: // // class C<T> // { // static void M<U>(T t, U u) // { // ... // C<U>.M(u, 123); // ... // } // } // // The *original* formal parameter types are (T, U); the *constructed* formal parameter types // are (U, U), but *those are logically two different U's*. The first U is from the outer caller; // the second U is the U of the recursive call. // // That is, suppose someone called C<string>.M<double>(string, double). The recursive call should be to // C<double>.M<int>(double, int). We should absolutely not make an inference on the first argument // from U to U just because C<U>.M<something>'s first formal parameter is of type U. If we did then // inference would fail, because we'd end up with two bounds on 'U' -- 'U' and 'int'. We only want // the latter bound. // // What these three scenarios show is that for a "normal" inference we need to have the // formal parameters of the *original* method definition, but when making an inference from a lambda // to a delegate, we need to have the *constructed* method signature in order that the formal // parameters *of the delegate* be correct. // // How to solve this problem? // // We solve it by passing in the formal parameters in their *original* form, but also getting // the *fully constructed* type that the method call is on. When constructing the fixed // delegate type for inference from a lambda, we do the appropriate type substitution on // the delegate. ImmutableArray<RefKind> formalParameterRefKinds, // Optional; assume all value if missing. ImmutableArray<BoundExpression> arguments,// Required; in scenarios like method group conversions where there are // no arguments per se we cons up some fake arguments. ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, Extensions extensions = null) { Debug.Assert(!methodTypeParameters.IsDefault); Debug.Assert(methodTypeParameters.Length > 0); Debug.Assert(!formalParameterTypes.IsDefault); Debug.Assert(formalParameterRefKinds.IsDefault || formalParameterRefKinds.Length == formalParameterTypes.Length); Debug.Assert(!arguments.IsDefault); // Early out: if the method has no formal parameters then we know that inference will fail. if (formalParameterTypes.Length == 0) { return new MethodTypeInferenceResult(false, default(ImmutableArray<TypeWithAnnotations>)); // UNDONE: OPTIMIZATION: We could check to see whether there is a type // UNDONE: parameter which is never used in any formal parameter; if // UNDONE: so then we know ahead of time that inference will fail. } var inferrer = new MethodTypeInferrer( binder.Compilation, conversions, methodTypeParameters, constructedContainingTypeOfMethod, formalParameterTypes, formalParameterRefKinds, arguments, extensions); return inferrer.InferTypeArgs(binder, ref useSiteInfo); } //////////////////////////////////////////////////////////////////////////////// // // Fixed, unfixed and bounded type parameters // // SPEC: During the process of inference each type parameter is either fixed to // SPEC: a particular type or unfixed with an associated set of bounds. Each of // SPEC: the bounds is of some type T. Initially each type parameter is unfixed // SPEC: with an empty set of bounds. private MethodTypeInferrer( CSharpCompilation compilation, ConversionsBase conversions, ImmutableArray<TypeParameterSymbol> methodTypeParameters, NamedTypeSymbol constructedContainingTypeOfMethod, ImmutableArray<TypeWithAnnotations> formalParameterTypes, ImmutableArray<RefKind> formalParameterRefKinds, ImmutableArray<BoundExpression> arguments, Extensions extensions) { _compilation = compilation; _conversions = conversions; _methodTypeParameters = methodTypeParameters; _constructedContainingTypeOfMethod = constructedContainingTypeOfMethod; _formalParameterTypes = formalParameterTypes; _formalParameterRefKinds = formalParameterRefKinds; _arguments = arguments; _extensions = extensions ?? Extensions.Default; _fixedResults = new TypeWithAnnotations[methodTypeParameters.Length]; _exactBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _upperBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _lowerBounds = new HashSet<TypeWithAnnotations>[methodTypeParameters.Length]; _nullableAnnotationLowerBounds = new NullableAnnotation[methodTypeParameters.Length]; Debug.Assert(_nullableAnnotationLowerBounds.All(annotation => annotation.IsNotAnnotated())); _dependencies = null; _dependenciesDirty = false; } #if DEBUG internal string Dump() { var sb = new System.Text.StringBuilder(); sb.AppendLine("Method type inference internal state"); sb.AppendFormat("Inferring method type parameters <{0}>\n", string.Join(", ", _methodTypeParameters)); sb.Append("Formal parameter types ("); for (int i = 0; i < _formalParameterTypes.Length; ++i) { if (i != 0) { sb.Append(", "); } sb.Append(GetRefKind(i).ToParameterPrefix()); sb.Append(_formalParameterTypes[i]); } sb.Append("\n"); sb.AppendFormat("Argument types ({0})\n", string.Join(", ", from a in _arguments select a.Type)); if (_dependencies == null) { sb.AppendLine("Dependencies are not yet calculated"); } else { sb.AppendFormat("Dependencies are {0}\n", _dependenciesDirty ? "out of date" : "up to date"); sb.AppendLine("dependency matrix (Not dependent / Direct / Indirect / Unknown):"); for (int i = 0; i < _methodTypeParameters.Length; ++i) { for (int j = 0; j < _methodTypeParameters.Length; ++j) { switch (_dependencies[i, j]) { case Dependency.NotDependent: sb.Append("N"); break; case Dependency.Direct: sb.Append("D"); break; case Dependency.Indirect: sb.Append("I"); break; case Dependency.Unknown: sb.Append("U"); break; } } sb.AppendLine(); } } for (int i = 0; i < _methodTypeParameters.Length; ++i) { sb.AppendFormat("Method type parameter {0}: ", _methodTypeParameters[i].Name); var fixedType = _fixedResults[i]; if (!fixedType.HasType) { sb.Append("UNFIXED "); } else { sb.AppendFormat("FIXED to {0} ", fixedType); } sb.AppendFormat("upper bounds: ({0}) ", (_upperBounds[i] == null) ? "" : string.Join(", ", _upperBounds[i])); sb.AppendFormat("lower bounds: ({0}) ", (_lowerBounds[i] == null) ? "" : string.Join(", ", _lowerBounds[i])); sb.AppendFormat("exact bounds: ({0}) ", (_exactBounds[i] == null) ? "" : string.Join(", ", _exactBounds[i])); sb.AppendLine(); } return sb.ToString(); } #endif private RefKind GetRefKind(int index) { Debug.Assert(0 <= index && index < _formalParameterTypes.Length); return _formalParameterRefKinds.IsDefault ? RefKind.None : _formalParameterRefKinds[index]; } private ImmutableArray<TypeWithAnnotations> GetResults() { // Anything we didn't infer a type for, give the error type. // Note: the error type will have the same name as the name // of the type parameter we were trying to infer. This will give a // nice user experience where by we will show something like // the following: // // user types: customers.Select( // we show : IE<TResult> IE<Customer>.Select<Customer,TResult>(Func<Customer,TResult> selector) // // Initially we thought we'd just show ?. i.e.: // // IE<?> IE<Customer>.Select<Customer,?>(Func<Customer,?> selector) // // This is nice and concise. However, it falls down if there are multiple // type params that we have left. for (int i = 0; i < _methodTypeParameters.Length; i++) { if (_fixedResults[i].HasType) { if (!_fixedResults[i].Type.IsErrorType()) { if (_conversions.IncludeNullability && _nullableAnnotationLowerBounds[i].IsAnnotated()) { _fixedResults[i] = _fixedResults[i].AsAnnotated(); } continue; } var errorTypeName = _fixedResults[i].Type.Name; if (errorTypeName != null) { continue; } } _fixedResults[i] = TypeWithAnnotations.Create(new ExtendedErrorTypeSymbol(_constructedContainingTypeOfMethod, _methodTypeParameters[i].Name, 0, null, false)); } return _fixedResults.AsImmutable(); } private bool ValidIndex(int index) { return 0 <= index && index < _methodTypeParameters.Length; } private bool IsUnfixed(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return !_fixedResults[methodTypeParameterIndex].HasType; } private bool IsUnfixedTypeParameter(TypeWithAnnotations type) { Debug.Assert(type.HasType); if (type.TypeKind != TypeKind.TypeParameter) return false; TypeParameterSymbol typeParameter = (TypeParameterSymbol)type.Type; int ordinal = typeParameter.Ordinal; return ValidIndex(ordinal) && TypeSymbol.Equals(typeParameter, _methodTypeParameters[ordinal], TypeCompareKind.ConsiderEverything2) && IsUnfixed(ordinal); } private bool AllFixed() { for (int methodTypeParameterIndex = 0; methodTypeParameterIndex < _methodTypeParameters.Length; ++methodTypeParameterIndex) { if (IsUnfixed(methodTypeParameterIndex)) { return false; } } return true; } private void AddBound(TypeWithAnnotations addedBound, HashSet<TypeWithAnnotations>[] collectedBounds, TypeWithAnnotations methodTypeParameterWithAnnotations) { Debug.Assert(IsUnfixedTypeParameter(methodTypeParameterWithAnnotations)); var methodTypeParameter = (TypeParameterSymbol)methodTypeParameterWithAnnotations.Type; int methodTypeParameterIndex = methodTypeParameter.Ordinal; if (collectedBounds[methodTypeParameterIndex] == null) { collectedBounds[methodTypeParameterIndex] = new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); } collectedBounds[methodTypeParameterIndex].Add(addedBound); } private bool HasBound(int methodTypeParameterIndex) { Debug.Assert(ValidIndex(methodTypeParameterIndex)); return _lowerBounds[methodTypeParameterIndex] != null || _upperBounds[methodTypeParameterIndex] != null || _exactBounds[methodTypeParameterIndex] != null; } private TypeSymbol GetFixedDelegateOrFunctionPointer(TypeSymbol delegateOrFunctionPointerType) { Debug.Assert((object)delegateOrFunctionPointerType != null); Debug.Assert(delegateOrFunctionPointerType.IsDelegateType() || delegateOrFunctionPointerType is FunctionPointerTypeSymbol); // We have a delegate where the input types use no unfixed parameters. Create // a substitution context; we can substitute unfixed parameters for themselves // since they don't actually occur in the inputs. (They may occur in the outputs, // or there may be input parameters fixed to _unfixed_ method type variables. // Both of those scenarios are legal.) var fixedArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(_methodTypeParameters.Length); for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { fixedArguments.Add(IsUnfixed(iParam) ? TypeWithAnnotations.Create(_methodTypeParameters[iParam]) : _fixedResults[iParam]); } TypeMap typeMap = new TypeMap(_constructedContainingTypeOfMethod, _methodTypeParameters, fixedArguments.ToImmutableAndFree()); return typeMap.SubstituteType(delegateOrFunctionPointerType).Type; } //////////////////////////////////////////////////////////////////////////////// // // Phases // private MethodTypeInferenceResult InferTypeArgs(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Type inference takes place in phases. Each phase will try to infer type // SPEC: arguments for more type parameters based on the findings of the previous // SPEC: phase. The first phase makes some initial inferences of bounds, whereas // SPEC: the second phase fixes type parameters to specific types and infers further // SPEC: bounds. The second phase may have to be repeated a number of times. InferTypeArgsFirstPhase(ref useSiteInfo); bool success = InferTypeArgsSecondPhase(binder, ref useSiteInfo); return new MethodTypeInferenceResult(success, GetResults()); } //////////////////////////////////////////////////////////////////////////////// // // The first phase // private void InferTypeArgsFirstPhase(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(!_arguments.IsDefault); // We expect that we have been handed a list of arguments and a list of the // formal parameter types they correspond to; all the details about named and // optional parameters have already been dealt with. // SPEC: For each of the method arguments Ei: for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { BoundExpression argument = _arguments[arg]; TypeWithAnnotations target = _formalParameterTypes[arg]; ExactOrBoundsKind kind = GetRefKind(arg).IsManagedReference() || target.Type.IsPointerType() ? ExactOrBoundsKind.Exact : ExactOrBoundsKind.LowerBound; MakeExplicitParameterTypeInferences(argument, target, kind, ref useSiteInfo); } } private void MakeExplicitParameterTypeInferences(BoundExpression argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If Ei is an anonymous function, an explicit type parameter // SPEC: inference is made from Ei to Ti. // (We cannot make an output type inference from a method group // at this time because we have no fixed types yet to use for // overload resolution.) // SPEC: * Otherwise, if Ei has a type U then a lower-bound inference // SPEC: or exact inference is made from U to Ti. // SPEC: * Otherwise, no inference is made for this argument if (argument.Kind == BoundKind.UnboundLambda && target.Type.GetDelegateType() is { }) { ExplicitParameterTypeInference(argument, target, ref useSiteInfo); } else if (argument.Kind != BoundKind.TupleLiteral || !MakeExplicitParameterTypeInferences((BoundTupleLiteral)argument, target, kind, ref useSiteInfo)) { // Either the argument is not a tuple literal, or we were unable to do the inference from its elements, let's try to infer from argument type if (IsReallyAType(argument.GetTypeOrFunctionType())) { ExactOrBoundsInference(kind, _extensions.GetTypeWithAnnotations(argument), target, ref useSiteInfo); } else if (IsUnfixedTypeParameter(target) && kind is ExactOrBoundsKind.LowerBound) { var ordinal = ((TypeParameterSymbol)target.Type).Ordinal; var typeWithAnnotations = _extensions.GetTypeWithAnnotations(argument); _nullableAnnotationLowerBounds[ordinal] = _nullableAnnotationLowerBounds[ordinal].Join(typeWithAnnotations.NullableAnnotation); } } } private bool MakeExplicitParameterTypeInferences(BoundTupleLiteral argument, TypeWithAnnotations target, ExactOrBoundsKind kind, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // try match up element-wise to the destination tuple (or underlying type) // Example: // if "(a: 1, b: "qq")" is passed as (T, U) arg // then T becomes int and U becomes string if (target.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return false; } var destination = (NamedTypeSymbol)target.Type; var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { // target is not a tuple of appropriate shape return false; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); // NOTE: we are losing tuple element names when recursing into argument expressions. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple literal is used to infer a single type param for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeExplicitParameterTypeInferences(sourceArgument, destType, kind, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // The second phase // private bool InferTypeArgsSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The second phase proceeds as follows: // SPEC: * If no unfixed type parameters exist then type inference succeeds. // SPEC: * Otherwise, if there exists one or more arguments Ei with corresponding // SPEC: parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. // SPEC: * Whether or not the previous step actually made an inference, we must // SPEC: now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then type // SPEC: inference fails. // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. // SPEC: * Otherwise, we are unable to make progress and there are unfixed parameters. // SPEC: Type inference fails. // SPEC: * If type inference neither succeeds nor fails then the second phase is // SPEC: repeated until type inference succeeds or fails. (Since each repetition of // SPEC: the second phase either succeeds, fails or fixes an unfixed type parameter, // SPEC: the algorithm must terminate with no more repetitions than the number // SPEC: of type parameters. InitializeDependencies(); while (true) { var res = DoSecondPhase(binder, ref useSiteInfo); Debug.Assert(res != InferenceResult.NoProgress); if (res == InferenceResult.InferenceFailed) { return false; } if (res == InferenceResult.Success) { return true; } // Otherwise, we made some progress last time; do it again. } } private InferenceResult DoSecondPhase(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * If no unfixed type parameters exist then type inference succeeds. if (AllFixed()) { return InferenceResult.Success; } // SPEC: * Otherwise, if there exists one or more arguments Ei with // SPEC: corresponding parameter type Ti such that: // SPEC: o the output type of Ei with type Ti contains at least one unfixed // SPEC: type parameter Xj, and // SPEC: o none of the input types of Ei with type Ti contains any unfixed // SPEC: type parameter Xj, // SPEC: then an output type inference is made from all such Ei to Ti. MakeOutputTypeInferences(binder, ref useSiteInfo); // SPEC: * Whether or not the previous step actually made an inference, we // SPEC: must now fix at least one type parameter, as follows: // SPEC: * If there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. InferenceResult res; res = FixNondependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o there is at least one type parameter Xj that depends on Xi // SPEC: then each such Xi is fixed. If any fixing operation fails then // SPEC: type inference fails. res = FixDependentParameters(ref useSiteInfo); if (res != InferenceResult.NoProgress) { return res; } // SPEC: * Otherwise, we are unable to make progress and there are // SPEC: unfixed parameters. Type inference fails. return InferenceResult.InferenceFailed; } private void MakeOutputTypeInferences(Binder binder, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: Otherwise, for all arguments Ei with corresponding parameter type Ti // SPEC: where the output types contain unfixed type parameters but the input // SPEC: types do not, an output type inference is made from Ei to Ti. for (int arg = 0, length = this.NumberArgumentsToProcess; arg < length; arg++) { var formalType = _formalParameterTypes[arg]; var argument = _arguments[arg]; MakeOutputTypeInferences(binder, argument, formalType, ref useSiteInfo); } } private void MakeOutputTypeInferences(Binder binder, BoundExpression argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (argument.Kind == BoundKind.TupleLiteral && (object)argument.Type == null) { MakeOutputTypeInferences(binder, (BoundTupleLiteral)argument, formalType, ref useSiteInfo); } else { if (HasUnfixedParamInOutputType(argument, formalType.Type) && !HasUnfixedParamInInputType(argument, formalType.Type)) { //UNDONE: if (argument->isTYPEORNAMESPACEERROR() && argumentType->IsErrorType()) //UNDONE: { //UNDONE: argumentType = GetTypeManager().GetErrorSym(); //UNDONE: } OutputTypeInference(binder, argument, formalType, ref useSiteInfo); } } } private void MakeOutputTypeInferences(Binder binder, BoundTupleLiteral argument, TypeWithAnnotations formalType, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (formalType.Type.Kind != SymbolKind.NamedType) { // tuples can only match to tuples or tuple underlying types. return; } var destination = (NamedTypeSymbol)formalType.Type; Debug.Assert((object)argument.Type == null, "should not need to dig into elements if tuple has natural type"); var sourceArguments = argument.Arguments; // check if the type is actually compatible type for a tuple of given cardinality if (!destination.IsTupleTypeOfCardinality(sourceArguments.Length)) { return; } var destTypes = destination.TupleElementTypesWithAnnotations; Debug.Assert(sourceArguments.Length == destTypes.Length); for (int i = 0; i < sourceArguments.Length; i++) { var sourceArgument = sourceArguments[i]; var destType = destTypes[i]; MakeOutputTypeInferences(binder, sourceArgument, destType, ref useSiteInfo); } } private InferenceResult FixNondependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * Otherwise, if there exists one or more type parameters Xi such that // SPEC: o Xi is unfixed, and // SPEC: o Xi has a non-empty set of bounds, and // SPEC: o Xi does not depend on any Xj // SPEC: then each such Xi is fixed. return FixParameters((inferrer, index) => !inferrer.DependsOnAny(index), ref useSiteInfo); } private InferenceResult FixDependentParameters(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: * All unfixed type parameters Xi are fixed for which all of the following hold: // SPEC: * There is at least one type parameter Xj that depends on Xi. // SPEC: * Xi has a non-empty set of bounds. return FixParameters((inferrer, index) => inferrer.AnyDependsOn(index), ref useSiteInfo); } private InferenceResult FixParameters( Func<MethodTypeInferrer, int, bool> predicate, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // Dependency is only defined for unfixed parameters. Therefore, fixing // a parameter may cause all of its dependencies to become no longer // dependent on anything. We need to first determine which parameters need to be // fixed, and then fix them all at once. var needsFixing = new bool[_methodTypeParameters.Length]; var result = InferenceResult.NoProgress; for (int param = 0; param < _methodTypeParameters.Length; param++) { if (IsUnfixed(param) && HasBound(param) && predicate(this, param)) { needsFixing[param] = true; result = InferenceResult.MadeProgress; } } for (int param = 0; param < _methodTypeParameters.Length; param++) { // Fix as much as you can, even if there are errors. That will // help with intellisense. if (needsFixing[param]) { if (!Fix(param, ref useSiteInfo)) { result = InferenceResult.InferenceFailed; } } } return result; } //////////////////////////////////////////////////////////////////////////////// // // Input types // private static bool DoesInputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then all the parameter types of T are // SPEC: input types of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; // No input types. } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; // No input types. } var parameters = delegateOrFunctionPointerType.DelegateOrFunctionPointerParameters(); if (parameters.IsDefaultOrEmpty) { return false; } foreach (var parameter in parameters) { if (parameter.Type.ContainsTypeParameter(typeParameter)) { return true; } } return false; } private bool HasUnfixedParamInInputType(BoundExpression pSource, TypeSymbol pDest) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesInputTypeContain(pSource, pDest, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output types // private static bool DoesOutputTypeContain(BoundExpression argument, TypeSymbol formalParameterType, TypeParameterSymbol typeParameter) { // SPEC: If E is a method group or an anonymous function and T is a delegate // SPEC: type or expression tree type then the return type of T is an output type // SPEC: of E with type T. var delegateOrFunctionPointerType = formalParameterType.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } var isFunctionPointer = delegateOrFunctionPointerType.IsFunctionPointer(); if ((isFunctionPointer && argument.Kind != BoundKind.UnconvertedAddressOfOperator) || (!isFunctionPointer && argument.Kind is not (BoundKind.UnboundLambda or BoundKind.MethodGroup))) { return false; } MethodSymbol method = delegateOrFunctionPointerType switch { NamedTypeSymbol n => n.DelegateInvokeMethod, FunctionPointerTypeSymbol f => f.Signature, _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType) }; if ((object)method == null || method.HasUseSiteError) { return false; } var returnType = method.ReturnType; if ((object)returnType == null) { return false; } return returnType.ContainsTypeParameter(typeParameter); } private bool HasUnfixedParamInOutputType(BoundExpression argument, TypeSymbol formalParameterType) { for (int iParam = 0; iParam < _methodTypeParameters.Length; iParam++) { if (IsUnfixed(iParam)) { if (DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Dependence // private bool DependsDirectlyOn(int iParam, int jParam) { Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // SPEC: An unfixed type parameter Xi depends directly on an unfixed type // SPEC: parameter Xj if for some argument Ek with type Tk, Xj occurs // SPEC: in an input type of Ek and Xi occurs in an output type of Ek // SPEC: with type Tk. // We compute and record the Depends Directly On relationship once, in // InitializeDependencies, below. // At this point, everything should be unfixed. Debug.Assert(IsUnfixed(iParam)); Debug.Assert(IsUnfixed(jParam)); for (int iArg = 0, length = this.NumberArgumentsToProcess; iArg < length; iArg++) { var formalParameterType = _formalParameterTypes[iArg].Type; var argument = _arguments[iArg]; if (DoesInputTypeContain(argument, formalParameterType, _methodTypeParameters[jParam]) && DoesOutputTypeContain(argument, formalParameterType, _methodTypeParameters[iParam])) { return true; } } return false; } private void InitializeDependencies() { // We track dependencies by a two-d square array that gives the known // relationship between every pair of type parameters. The relationship // is one of: // // * Unknown relationship // * known to be not dependent // * known to depend directly // * known to depend indirectly // // Since dependency is only defined on unfixed type parameters, fixing a type // parameter causes all dependencies involving that parameter to go to // the "known to be not dependent" state. Since dependency is a transitive property, // this means that doing so may require recalculating the indirect dependencies // from the now possibly smaller set of dependencies. // // Therefore, when we detect that the dependency state has possibly changed // due to fixing, we change all "depends indirectly" back into "unknown" and // recalculate from the remaining "depends directly". // // This algorithm thereby yields an extremely bad (but extremely unlikely) worst // case for asymptotic performance. Suppose there are n type parameters. // "DependsTransitivelyOn" below costs O(n) because it must potentially check // all n type parameters to see if there is any k such that Xj => Xk => Xi. // "DeduceDependencies" calls "DependsTransitivelyOn" for each "Unknown" // pair, and there could be O(n^2) such pairs, so DependsTransitivelyOn is // worst-case O(n^3). And we could have to recalculate the dependency graph // after each type parameter is fixed in turn, so that would be O(n) calls to // DependsTransitivelyOn, giving this algorithm a worst case of O(n^4). // // Of course, in reality, n is going to almost always be on the order of // "smaller than 5", and there will not be O(n^2) dependency relationships // between type parameters; it is far more likely that the transitivity chains // will be very short and not branch or loop at all. This is much more likely to // be an O(n^2) algorithm in practice. Debug.Assert(_dependencies == null); _dependencies = new Dependency[_methodTypeParameters.Length, _methodTypeParameters.Length]; int iParam; int jParam; Debug.Assert(0 == (int)Dependency.Unknown); for (iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsDirectlyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Direct; } } } DeduceAllDependencies(); } private bool DependsOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); // SPEC: Xj depends on Xi if Xj depends directly on Xi, or if Xi depends // SPEC: directly on Xk and Xk depends on Xj. Thus "depends on" is the // SPEC: transitive but not reflexive closure of "depends directly on". Debug.Assert(0 <= iParam && iParam < _methodTypeParameters.Length); Debug.Assert(0 <= jParam && jParam < _methodTypeParameters.Length); if (_dependenciesDirty) { SetIndirectsToUnknown(); DeduceAllDependencies(); } return 0 != ((_dependencies[iParam, jParam]) & Dependency.DependsMask); } private bool DependsTransitivelyOn(int iParam, int jParam) { Debug.Assert(_dependencies != null); Debug.Assert(ValidIndex(iParam)); Debug.Assert(ValidIndex(jParam)); // Can we find Xk such that Xi depends on Xk and Xk depends on Xj? // If so, then Xi depends indirectly on Xj. (Note that there is // a minor optimization here -- the spec comment above notes that // we want Xi to depend DIRECTLY on Xk, and Xk to depend directly // or indirectly on Xj. But if we already know that Xi depends // directly OR indirectly on Xk and Xk depends on Xj, then that's // good enough.) for (int kParam = 0; kParam < _methodTypeParameters.Length; ++kParam) { if (((_dependencies[iParam, kParam]) & Dependency.DependsMask) != 0 && ((_dependencies[kParam, jParam]) & Dependency.DependsMask) != 0) { return true; } } return false; } private void DeduceAllDependencies() { bool madeProgress; do { madeProgress = DeduceDependencies(); } while (madeProgress); SetUnknownsToNotDependent(); _dependenciesDirty = false; } private bool DeduceDependencies() { Debug.Assert(_dependencies != null); bool madeProgress = false; for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { if (DependsTransitivelyOn(iParam, jParam)) { _dependencies[iParam, jParam] = Dependency.Indirect; madeProgress = true; } } } } return madeProgress; } private void SetUnknownsToNotDependent() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Unknown) { _dependencies[iParam, jParam] = Dependency.NotDependent; } } } } private void SetIndirectsToUnknown() { Debug.Assert(_dependencies != null); for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (_dependencies[iParam, jParam] == Dependency.Indirect) { _dependencies[iParam, jParam] = Dependency.Unknown; } } } } //////////////////////////////////////////////////////////////////////////////// // A fixed parameter never depends on anything, nor is depended upon by anything. private void UpdateDependenciesAfterFix(int iParam) { Debug.Assert(ValidIndex(iParam)); if (_dependencies == null) { return; } for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { _dependencies[iParam, jParam] = Dependency.NotDependent; _dependencies[jParam, iParam] = Dependency.NotDependent; } _dependenciesDirty = true; } private bool DependsOnAny(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(iParam, jParam)) { return true; } } return false; } private bool AnyDependsOn(int iParam) { Debug.Assert(ValidIndex(iParam)); for (int jParam = 0; jParam < _methodTypeParameters.Length; ++jParam) { if (DependsOn(jParam, iParam)) { return true; } } return false; } //////////////////////////////////////////////////////////////////////////////// // // Output type inferences // //////////////////////////////////////////////////////////////////////////////// private void OutputTypeInference(Binder binder, BoundExpression expression, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(expression != null); Debug.Assert(target.HasType); // SPEC: An output type inference is made from an expression E to a type T // SPEC: in the following way: // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. if (InferredReturnTypeInference(expression, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (MethodGroupReturnTypeInference(binder, expression, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if E is an expression with type U then a lower-bound // SPEC: inference is made from U to T. var sourceType = _extensions.GetTypeWithAnnotations(expression); if (sourceType.HasType) { LowerBoundInference(sourceType, target, ref useSiteInfo); } // SPEC: * Otherwise, no inferences are made. } private bool InferredReturnTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: * If E is an anonymous function with inferred return type U and // SPEC: T is a delegate type or expression tree with return type Tb // SPEC: then a lower bound inference is made from U to Tb. var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return false; } // cannot be hit, because an invalid delegate does not have an unfixed return type // this will be checked earlier. Debug.Assert((object)delegateType.DelegateInvokeMethod != null && !delegateType.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for valid delegate types."); var returnType = delegateType.DelegateInvokeMethod.ReturnTypeWithAnnotations; if (!returnType.HasType || returnType.SpecialType == SpecialType.System_Void) { return false; } var inferredReturnType = InferReturnType(source, delegateType, ref useSiteInfo); if (!inferredReturnType.HasType) { return false; } LowerBoundInference(inferredReturnType, returnType, ref useSiteInfo); return true; } private bool MethodGroupReturnTypeInference(Binder binder, BoundExpression source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if E is a method group and T is a delegate type or // SPEC: expression tree type with parameter types T1...Tk and return // SPEC: type Tb and overload resolution of E with the types T1...Tk // SPEC: yields a single method with return type U then a lower-bound // SPEC: inference is made from U to Tb. if (source.Kind is not (BoundKind.MethodGroup or BoundKind.UnconvertedAddressOfOperator)) { return false; } var delegateOrFunctionPointerType = target.GetDelegateOrFunctionPointerType(); if ((object)delegateOrFunctionPointerType == null) { return false; } if (delegateOrFunctionPointerType.IsFunctionPointer() != (source.Kind == BoundKind.UnconvertedAddressOfOperator)) { return false; } // this part of the code is only called if the targetType has an unfixed type argument in the output // type, which is not the case for invalid delegate invoke methods. var (method, isFunctionPointerResolution) = delegateOrFunctionPointerType switch { NamedTypeSymbol n => (n.DelegateInvokeMethod, false), FunctionPointerTypeSymbol f => (f.Signature, true), _ => throw ExceptionUtilities.UnexpectedValue(delegateOrFunctionPointerType), }; Debug.Assert(method is { HasUseSiteError: false }, "This method should only be called for valid delegate or function pointer types"); TypeWithAnnotations sourceReturnType = method.ReturnTypeWithAnnotations; if (!sourceReturnType.HasType || sourceReturnType.SpecialType == SpecialType.System_Void) { return false; } // At this point we are in the second phase; we know that all the input types are fixed. var fixedParameters = GetFixedDelegateOrFunctionPointer(delegateOrFunctionPointerType).DelegateOrFunctionPointerParameters(); if (fixedParameters.IsDefault) { return false; } CallingConventionInfo callingConventionInfo = isFunctionPointerResolution ? new CallingConventionInfo(method.CallingConvention, ((FunctionPointerMethodSymbol)method).GetCallingConventionModifiers()) : default; BoundMethodGroup originalMethodGroup = source as BoundMethodGroup ?? ((BoundUnconvertedAddressOfOperator)source).Operand; var returnType = MethodGroupReturnType(binder, originalMethodGroup, fixedParameters, method.RefKind, isFunctionPointerResolution, ref useSiteInfo, in callingConventionInfo); if (returnType.IsDefault || returnType.IsVoidType()) { return false; } LowerBoundInference(returnType, sourceReturnType, ref useSiteInfo); return true; } private TypeWithAnnotations MethodGroupReturnType( Binder binder, BoundMethodGroup source, ImmutableArray<ParameterSymbol> delegateParameters, RefKind delegateRefKind, bool isFunctionPointerResolution, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, in CallingConventionInfo callingConventionInfo) { var analyzedArguments = AnalyzedArguments.GetInstance(); Conversions.GetDelegateOrFunctionPointerArguments(source.Syntax, analyzedArguments, delegateParameters, binder.Compilation); var resolution = binder.ResolveMethodGroup(source, analyzedArguments, useSiteInfo: ref useSiteInfo, isMethodGroupConversion: true, returnRefKind: delegateRefKind, // Since we are trying to infer the return type, it is not an input to resolving the method group returnType: null, isFunctionPointerResolution: isFunctionPointerResolution, callingConventionInfo: in callingConventionInfo); TypeWithAnnotations type = default; // The resolution could be empty (e.g. if there are no methods in the BoundMethodGroup). if (!resolution.IsEmpty) { var result = resolution.OverloadResolutionResult; if (result.Succeeded) { type = _extensions.GetMethodGroupResultType(source, result.BestResult.Member); } } analyzedArguments.Free(); resolution.Free(); return type; } //////////////////////////////////////////////////////////////////////////////// // // Explicit parameter type inferences // private void ExplicitParameterTypeInference(BoundExpression source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source != null); Debug.Assert(target.HasType); // SPEC: An explicit type parameter type inference is made from an expression // SPEC: E to a type T in the following way. // SPEC: If E is an explicitly typed anonymous function with parameter types // SPEC: U1...Uk and T is a delegate type or expression tree type with // SPEC: parameter types V1...Vk then for each Ui an exact inference is made // SPEC: from Ui to the corresponding Vi. if (source.Kind != BoundKind.UnboundLambda) { return; } UnboundLambda anonymousFunction = (UnboundLambda)source; if (!anonymousFunction.HasExplicitlyTypedParameterList) { return; } var delegateType = target.Type.GetDelegateType(); if ((object)delegateType == null) { return; } var delegateParameters = delegateType.DelegateParameters(); if (delegateParameters.IsDefault) { return; } int size = delegateParameters.Length; if (anonymousFunction.ParameterCount < size) { size = anonymousFunction.ParameterCount; } // SPEC ISSUE: What should we do if there is an out/ref mismatch between an // SPEC ISSUE: anonymous function parameter and a delegate parameter? // SPEC ISSUE: The result will not be applicable no matter what, but should // SPEC ISSUE: we make any inferences? This is going to be an error // SPEC ISSUE: ultimately, but it might make a difference for intellisense or // SPEC ISSUE: other analysis. for (int i = 0; i < size; ++i) { ExactInference(anonymousFunction.ParameterTypeWithAnnotations(i), delegateParameters[i].TypeWithAnnotations, ref useSiteInfo); } } //////////////////////////////////////////////////////////////////////////////// // // Exact inferences // private void ExactInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An exact inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if U is the type U1? and V is the type V1? then an // SPEC: exact inference is made from U to V. if (ExactNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: exact bounds for Xi. if (ExactTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (ExactArrayInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. if (ExactConstructedInference(source, target, ref useSiteInfo)) { return; } // This can be valid via (where T : unmanaged) constraints if (ExactPointerInference(source, target, ref useSiteInfo)) { return; } // SPEC: * Otherwise no inferences are made. } private bool ExactTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _exactBounds, target); return true; } return false; } private bool ExactArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if U is an array type UE[...] and V is an array type VE[...] // SPEC: of the same rank then an exact inference from UE to VE is made. if (!source.Type.IsArray() || !target.Type.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source.Type; var arrayTarget = (ArrayTypeSymbol)target.Type; if (!arraySource.HasSameShapeAs(arrayTarget)) { return false; } ExactInference(arraySource.ElementTypeWithAnnotations, arrayTarget.ElementTypeWithAnnotations, ref useSiteInfo); return true; } private enum ExactOrBoundsKind { Exact, LowerBound, UpperBound, } private void ExactOrBoundsInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { switch (kind) { case ExactOrBoundsKind.Exact: ExactInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.LowerBound: LowerBoundInference(source, target, ref useSiteInfo); break; case ExactOrBoundsKind.UpperBound: UpperBoundInference(source, target, ref useSiteInfo); break; } } private bool ExactOrBoundsNullableInference(ExactOrBoundsKind kind, TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); if (source.IsNullableType() && target.IsNullableType()) { ExactOrBoundsInference(kind, ((NamedTypeSymbol)source.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ((NamedTypeSymbol)target.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0], ref useSiteInfo); return true; } if (isNullableOnly(source) && isNullableOnly(target)) { ExactOrBoundsInference(kind, source.AsNotNullableReferenceType(), target.AsNotNullableReferenceType(), ref useSiteInfo); return true; } return false; // True if the type is nullable. static bool isNullableOnly(TypeWithAnnotations type) => type.NullableAnnotation.IsAnnotated(); } private bool ExactNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.Exact, source, target, ref useSiteInfo); } private bool LowerBoundTupleInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // NOTE: we are losing tuple element names when unwrapping tuple types to underlying types. // that is ok, because we are inferring type parameters used in the matching elements, // This is not the situation where entire tuple type used to infer a single type param ImmutableArray<TypeWithAnnotations> sourceTypes; ImmutableArray<TypeWithAnnotations> targetTypes; if (!source.Type.TryGetElementTypesWithAnnotationsIfTupleType(out sourceTypes) || !target.Type.TryGetElementTypesWithAnnotationsIfTupleType(out targetTypes) || sourceTypes.Length != targetTypes.Length) { return false; } for (int i = 0; i < sourceTypes.Length; i++) { LowerBoundInference(sourceTypes[i], targetTypes[i], ref useSiteInfo); } return true; } private bool ExactConstructedInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is a constructed // SPEC: type C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. var namedSource = source.Type as NamedTypeSymbol; if ((object)namedSource == null) { return false; } var namedTarget = target.Type as NamedTypeSymbol; if ((object)namedTarget == null) { return false; } if (!TypeSymbol.Equals(namedSource.OriginalDefinition, namedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { return false; } ExactTypeArgumentInference(namedSource, namedTarget, ref useSiteInfo); return true; } private bool ExactPointerInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source.TypeKind == TypeKind.Pointer && target.TypeKind == TypeKind.Pointer) { ExactInference(((PointerTypeSymbol)source.Type).PointedAtTypeWithAnnotations, ((PointerTypeSymbol)target.Type).PointedAtTypeWithAnnotations, ref useSiteInfo); return true; } else if (source.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int sourceParameterCount } sourceSignature } && target.Type is FunctionPointerTypeSymbol { Signature: { ParameterCount: int targetParameterCount } targetSignature } && sourceParameterCount == targetParameterCount) { if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } for (int i = 0; i < sourceParameterCount; i++) { ExactInference(sourceSignature.ParameterTypesWithAnnotations[i], targetSignature.ParameterTypesWithAnnotations[i], ref useSiteInfo); } ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); return true; } return false; } private static bool FunctionPointerCallingConventionsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { if (sourceSignature.CallingConvention != targetSignature.CallingConvention) { return false; } return (sourceSignature.GetCallingConventionModifiers(), targetSignature.GetCallingConventionModifiers()) switch { (null, null) => true, ({ } sourceModifiers, { } targetModifiers) when sourceModifiers.SetEquals(targetModifiers) => true, _ => false }; } private static bool FunctionPointerRefKindsEqual(FunctionPointerMethodSymbol sourceSignature, FunctionPointerMethodSymbol targetSignature) { return sourceSignature.RefKind == targetSignature.RefKind && (sourceSignature.ParameterRefKinds.IsDefault, targetSignature.ParameterRefKinds.IsDefault) switch { (true, false) or (false, true) => false, (true, true) => true, _ => sourceSignature.ParameterRefKinds.SequenceEqual(targetSignature.ParameterRefKinds) }; } private void ExactTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(sourceTypeArguments.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { ExactInference(sourceTypeArguments[arg], targetTypeArguments[arg], ref useSiteInfo); } sourceTypeArguments.Free(); targetTypeArguments.Free(); } //////////////////////////////////////////////////////////////////////////////// // // Lower-bound inferences // private void LowerBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: A lower-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. // SPEC ERROR: The spec should say "lower" here; we can safely make a lower-bound // SPEC ERROR: inference to nullable even though it is a generic struct. That is, // SPEC ERROR: if we have M<T>(T?, T) called with (char?, int) then we can infer // SPEC ERROR: lower bounds of char and int, and choose int. If we make an exact // SPEC ERROR: inference of char then type inference fails. if (LowerBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: lower bounds for Xi. if (LowerBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (LowerBoundArrayInference(source.Type, target.Type, ref useSiteInfo)) { return; } // UNDONE: At this point we could also do an inference from non-nullable U // UNDONE: to nullable V. // UNDONE: // UNDONE: We tried implementing lower bound nullable inference as follows: // UNDONE: // UNDONE: * Otherwise, if V is nullable type V1? and U is a non-nullable // UNDONE: struct type then an exact inference is made from U to V1. // UNDONE: // UNDONE: However, this causes an unfortunate interaction with what // UNDONE: looks like a bug in our implementation of section 15.2 of // UNDONE: the specification. Namely, it appears that the code which // UNDONE: checks whether a given method is compatible with // UNDONE: a delegate type assumes that if method type inference succeeds, // UNDONE: then the inferred types are compatible with the delegate types. // UNDONE: This is not necessarily so; the inferred types could be compatible // UNDONE: via a conversion other than reference or identity. // UNDONE: // UNDONE: We should take an action item to investigate this problem. // UNDONE: Until then, we will turn off the proposed lower bound nullable // UNDONE: inference. // if (LowerBoundNullableInference(pSource, pDest)) // { // return; // } if (LowerBoundTupleInference(source, target, ref useSiteInfo)) { return; } // SPEC: Otherwise... many cases for constructed generic types. if (LowerBoundConstructedInference(source.Type, target.Type, ref useSiteInfo)) { return; } if (LowerBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool LowerBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _lowerBounds, target); return true; } return false; } private static TypeWithAnnotations GetMatchingElementType(ArrayTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // It might be an array of same rank. if (target.IsArray()) { var arrayTarget = (ArrayTypeSymbol)target; if (!arrayTarget.HasSameShapeAs(source)) { return default; } return arrayTarget.ElementTypeWithAnnotations; } // Or it might be IEnum<T> and source is rank one. if (!source.IsSZArray) { return default; } // Arrays are specified as being convertible to IEnumerable<T>, ICollection<T> and // IList<T>; we also honor their convertibility to IReadOnlyCollection<T> and // IReadOnlyList<T>, and make inferences accordingly. if (!target.IsPossibleArrayGenericInterface()) { return default; } return ((NamedTypeSymbol)target).TypeArgumentWithDefinitionUseSiteDiagnostics(0, ref useSiteInfo); } private bool LowerBoundArrayInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); // SPEC: * Otherwise, if U is an array type Ue[...] and V is either an array // SPEC: type Ve[...] of the same rank, or if U is a one-dimensional array // SPEC: type Ue[] and V is one of IEnumerable<Ve>, ICollection<Ve> or // SPEC: IList<Ve> then // SPEC: * if Ue is known to be a reference type then a lower-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!source.IsArray()) { return false; } var arraySource = (ArrayTypeSymbol)source; var elementSource = arraySource.ElementTypeWithAnnotations; var elementTarget = GetMatchingElementType(arraySource, target, ref useSiteInfo); if (!elementTarget.HasType) { return false; } if (elementSource.Type.IsReferenceType) { LowerBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool LowerBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.LowerBound, source, target, ref useSiteInfo); } private bool LowerBoundConstructedInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget == null) { return false; } if (constructedTarget.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed class or struct type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference // SPEC: is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a constructed interface or delegate type C<V1...Vk> // SPEC: and U is C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, constructedTarget.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedSource.IsInterface || constructedSource.IsDelegateType()) { LowerBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> then an exact ... // SPEC: * ... and U is a type parameter with effective base class ... // SPEC: * ... and U is a type parameter with an effective base class which inherits ... if (LowerBoundClassInference(source, constructedTarget, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if V is an interface type C<V1...Vk> and U is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an exact ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... if (LowerBoundInterfaceInference(source, constructedTarget, ref useSiteInfo)) { return true; } return false; } private bool LowerBoundClassInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (target.TypeKind != TypeKind.Class) { return false; } // Spec: 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a class type which // SPEC: inherits directly or indirectly from C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with effective base class C<U1...Uk> // SPEC: then an exact inference is made from each Ui to the corresponding Vi. // SPEC: * Otherwise, if V is a class type C<V1...Vk> and U is a type parameter // SPEC: with an effective base class which inherits directly or indirectly from // SPEC: C<U1...Uk> then an exact inference is made // SPEC: from each Ui to the corresponding Vi. NamedTypeSymbol sourceBase = null; if (source.TypeKind == TypeKind.Class) { sourceBase = source.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } else if (source.TypeKind == TypeKind.TypeParameter) { sourceBase = ((TypeParameterSymbol)source).EffectiveBaseClass(ref useSiteInfo); } while ((object)sourceBase != null) { if (TypeSymbol.Equals(sourceBase.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(sourceBase, target, ref useSiteInfo); return true; } sourceBase = sourceBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool LowerBoundInterfaceInference(TypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!target.IsInterface) { return false; } // Spec 7.5.2.9 Lower-bound interfaces // SPEC: * Otherwise, if V [target] is an interface type C<V1...Vk> and U [source] is a class type // SPEC: or struct type and there is a unique set U1...Uk such that U directly // SPEC: or indirectly implements C<U1...Uk> then an // SPEC: exact, upper-bound, or lower-bound inference ... // SPEC: * ... and U is an interface type ... // SPEC: * ... and U is a type parameter ... ImmutableArray<NamedTypeSymbol> allInterfaces; switch (source.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: allInterfaces = source.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); break; case TypeKind.TypeParameter: var typeParameter = (TypeParameterSymbol)source; allInterfaces = typeParameter.EffectiveBaseClass(ref useSiteInfo). AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo). Concat(typeParameter.AllEffectiveInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo)); break; default: return false; } // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.In); NamedTypeSymbol matchingInterface = GetInterfaceInferenceBound(allInterfaces, target); if ((object)matchingInterface == null) { return false; } LowerBoundTypeArgumentInference(matchingInterface, target, ref useSiteInfo); return true; } internal static ImmutableArray<NamedTypeSymbol> ModuloReferenceTypeNullabilityDifferences(ImmutableArray<NamedTypeSymbol> interfaces, VarianceKind variance) { var dictionary = PooledDictionaryIgnoringNullableModifiersForReferenceTypes.GetInstance(); foreach (var @interface in interfaces) { if (dictionary.TryGetValue(@interface, out var found)) { var merged = (NamedTypeSymbol)found.MergeEquivalentTypes(@interface, variance); dictionary[@interface] = merged; } else { dictionary.Add(@interface, @interface); } } var result = dictionary.Count != interfaces.Length ? dictionary.Values.ToImmutableArray() : interfaces; dictionary.Free(); return result; } private void LowerBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then a lower bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then an upper bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool LowerBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { UpperBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { LowerBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Upper-bound inferences // private void UpperBoundInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: An upper-bound inference from a type U to a type V is made as follows: // SPEC: * Otherwise, if V is nullable type V1? and U is nullable type U1? // SPEC: then an exact inference is made from U1 to V1. if (UpperBoundNullableInference(source, target, ref useSiteInfo)) { return; } // SPEC: * If V is one of the unfixed Xi then U is added to the set of // SPEC: upper bounds for Xi. if (UpperBoundTypeParameterInference(source, target)) { return; } // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (UpperBoundArrayInference(source, target, ref useSiteInfo)) { return; } Debug.Assert(source.Type.IsReferenceType || source.Type.IsFunctionPointer()); // NOTE: spec would ask us to do the following checks, but since the value types // are trivially handled as exact inference in the callers, we do not have to. //if (ExactTupleInference(source, target, ref useSiteInfo)) //{ // return; //} // SPEC: * Otherwise... cases for constructed types if (UpperBoundConstructedInference(source, target, ref useSiteInfo)) { return; } if (UpperBoundFunctionPointerTypeInference(source.Type, target.Type, ref useSiteInfo)) { return; } // SPEC: * Otherwise, no inferences are made. } private bool UpperBoundTypeParameterInference(TypeWithAnnotations source, TypeWithAnnotations target) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * If V is one of the unfixed Xi then U is added to the set of upper bounds // SPEC: for Xi. if (IsUnfixedTypeParameter(target)) { AddBound(source, _upperBounds, target); return true; } return false; } private bool UpperBoundArrayInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(source.HasType); Debug.Assert(target.HasType); // SPEC: * Otherwise, if V is an array type Ve[...] and U is an array // SPEC: type Ue[...] of the same rank, or if V is a one-dimensional array // SPEC: type Ve[] and U is one of IEnumerable<Ue>, ICollection<Ue> or // SPEC: IList<Ue> then // SPEC: * if Ue is known to be a reference type then an upper-bound inference // SPEC: from Ue to Ve is made. // SPEC: * otherwise an exact inference from Ue to Ve is made. if (!target.Type.IsArray()) { return false; } var arrayTarget = (ArrayTypeSymbol)target.Type; var elementTarget = arrayTarget.ElementTypeWithAnnotations; var elementSource = GetMatchingElementType(arrayTarget, source.Type, ref useSiteInfo); if (!elementSource.HasType) { return false; } if (elementSource.Type.IsReferenceType) { UpperBoundInference(elementSource, elementTarget, ref useSiteInfo); } else { ExactInference(elementSource, elementTarget, ref useSiteInfo); } return true; } private bool UpperBoundNullableInference(TypeWithAnnotations source, TypeWithAnnotations target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { return ExactOrBoundsNullableInference(ExactOrBoundsKind.UpperBound, source, target, ref useSiteInfo); } private bool UpperBoundConstructedInference(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations targetWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(sourceWithAnnotations.HasType); Debug.Assert(targetWithAnnotations.HasType); var source = sourceWithAnnotations.Type; var target = targetWithAnnotations.Type; var constructedSource = source as NamedTypeSymbol; if ((object)constructedSource == null) { return false; } if (constructedSource.AllTypeArgumentCount() == 0) { return false; } // SPEC: * Otherwise, if V is a constructed type C<V1...Vk> and U is // SPEC: C<U1...Uk> then an exact inference, // SPEC: lower bound inference or upper bound inference // SPEC: is made from each Ui to the corresponding Vi. var constructedTarget = target as NamedTypeSymbol; if ((object)constructedTarget != null && TypeSymbol.Equals(constructedSource.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { if (constructedTarget.IsInterface || constructedTarget.IsDelegateType()) { UpperBoundTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } else { ExactTypeArgumentInference(constructedSource, constructedTarget, ref useSiteInfo); } return true; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact ... if (UpperBoundClassInference(constructedSource, target, ref useSiteInfo)) { return true; } // SPEC: * Otherwise, if U is an interface type C<U1...Uk> and V is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... if (UpperBoundInterfaceInference(constructedSource, target, ref useSiteInfo)) { return true; } return false; } private bool UpperBoundClassInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (source.TypeKind != TypeKind.Class || target.TypeKind != TypeKind.Class) { return false; } // SPEC: * Otherwise, if U is a class type C<U1...Uk> and V is a class type which // SPEC: inherits directly or indirectly from C<V1...Vk> then an exact // SPEC: inference is made from each Ui to the corresponding Vi. var targetBase = target.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); while ((object)targetBase != null) { if (TypeSymbol.Equals(targetBase.OriginalDefinition, source.OriginalDefinition, TypeCompareKind.ConsiderEverything2)) { ExactTypeArgumentInference(source, targetBase, ref useSiteInfo); return true; } targetBase = targetBase.BaseTypeWithDefinitionUseSiteDiagnostics(ref useSiteInfo); } return false; } private bool UpperBoundInterfaceInference(NamedTypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)source != null); Debug.Assert((object)target != null); if (!source.IsInterface) { return false; } // SPEC: * Otherwise, if U [source] is an interface type C<U1...Uk> and V [target] is a class type // SPEC: or struct type and there is a unique set V1...Vk such that V directly // SPEC: or indirectly implements C<V1...Vk> then an exact ... // SPEC: * ... and U is an interface type ... switch (target.TypeKind) { case TypeKind.Struct: case TypeKind.Class: case TypeKind.Interface: break; default: return false; } ImmutableArray<NamedTypeSymbol> allInterfaces = target.AllInterfacesWithDefinitionUseSiteDiagnostics(ref useSiteInfo); // duplicates with only nullability differences can be merged (to avoid an error in type inference) allInterfaces = ModuloReferenceTypeNullabilityDifferences(allInterfaces, VarianceKind.Out); NamedTypeSymbol bestInterface = GetInterfaceInferenceBound(allInterfaces, source); if ((object)bestInterface == null) { return false; } UpperBoundTypeArgumentInference(source, bestInterface, ref useSiteInfo); return true; } private void UpperBoundTypeArgumentInference(NamedTypeSymbol source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // SPEC: The choice of inference for the i-th type argument is made // SPEC: based on the declaration of the i-th type parameter of C, as // SPEC: follows: // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as covariant then an upper-bound inference is made. // SPEC: * if Ui is known to be of reference type and the i-th type parameter // SPEC: was declared as contravariant then a lower-bound inference is made. // SPEC: * otherwise, an exact inference is made. Debug.Assert((object)source != null); Debug.Assert((object)target != null); Debug.Assert(TypeSymbol.Equals(source.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything2)); var typeParameters = ArrayBuilder<TypeParameterSymbol>.GetInstance(); var sourceTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); var targetTypeArguments = ArrayBuilder<TypeWithAnnotations>.GetInstance(); source.OriginalDefinition.GetAllTypeParameters(typeParameters); source.GetAllTypeArguments(sourceTypeArguments, ref useSiteInfo); target.GetAllTypeArguments(targetTypeArguments, ref useSiteInfo); Debug.Assert(typeParameters.Count == sourceTypeArguments.Count); Debug.Assert(typeParameters.Count == targetTypeArguments.Count); for (int arg = 0; arg < sourceTypeArguments.Count; ++arg) { var typeParameter = typeParameters[arg]; var sourceTypeArgument = sourceTypeArguments[arg]; var targetTypeArgument = targetTypeArguments[arg]; if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.Out) { UpperBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else if (sourceTypeArgument.Type.IsReferenceType && typeParameter.Variance == VarianceKind.In) { LowerBoundInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } else { ExactInference(sourceTypeArgument, targetTypeArgument, ref useSiteInfo); } } typeParameters.Free(); sourceTypeArguments.Free(); targetTypeArguments.Free(); } #nullable enable private bool UpperBoundFunctionPointerTypeInference(TypeSymbol source, TypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { if (source is not FunctionPointerTypeSymbol { Signature: { } sourceSignature } || target is not FunctionPointerTypeSymbol { Signature: { } targetSignature }) { return false; } if (sourceSignature.ParameterCount != targetSignature.ParameterCount) { return false; } if (!FunctionPointerRefKindsEqual(sourceSignature, targetSignature) || !FunctionPointerCallingConventionsEqual(sourceSignature, targetSignature)) { return false; } // Reference parameters are treated as "input" variance by default, and reference return types are treated as out variance by default. // If they have a ref kind or are not reference types, then they are treated as invariant. for (int i = 0; i < sourceSignature.ParameterCount; i++) { var sourceParam = sourceSignature.Parameters[i]; var targetParam = targetSignature.Parameters[i]; if ((sourceParam.Type.IsReferenceType || sourceParam.Type.IsFunctionPointer()) && sourceParam.RefKind == RefKind.None) { LowerBoundInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceParam.TypeWithAnnotations, targetParam.TypeWithAnnotations, ref useSiteInfo); } } if ((sourceSignature.ReturnType.IsReferenceType || sourceSignature.ReturnType.IsFunctionPointer()) && sourceSignature.RefKind == RefKind.None) { UpperBoundInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } else { ExactInference(sourceSignature.ReturnTypeWithAnnotations, targetSignature.ReturnTypeWithAnnotations, ref useSiteInfo); } return true; } //////////////////////////////////////////////////////////////////////////////// // // Fixing // private bool Fix(int iParam, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(IsUnfixed(iParam)); var typeParameter = _methodTypeParameters[iParam]; var exact = _exactBounds[iParam]; var lower = _lowerBounds[iParam]; var upper = _upperBounds[iParam]; var best = Fix(_compilation, _conversions, typeParameter, exact, lower, upper, ref useSiteInfo); if (!best.HasType) { return false; } #if DEBUG if (_conversions.IncludeNullability) { // If the first attempt succeeded, the result should be the same as // the second attempt, although perhaps with different nullability. var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var withoutNullability = Fix(_compilation, _conversions.WithNullability(false), typeParameter, exact, lower, upper, ref discardedUseSiteInfo); // https://github.com/dotnet/roslyn/issues/27961 Results may differ by tuple names or dynamic. // See NullableReferenceTypesTests.TypeInference_TupleNameDifferences_01 for example. Debug.Assert(best.Type.Equals(withoutNullability.Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); } #endif _fixedResults[iParam] = best; UpdateDependenciesAfterFix(iParam); return true; } private static TypeWithAnnotations Fix( CSharpCompilation compilation, ConversionsBase conversions, TypeParameterSymbol typeParameter, HashSet<TypeWithAnnotations>? exact, HashSet<TypeWithAnnotations>? lower, HashSet<TypeWithAnnotations>? upper, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { // UNDONE: This method makes a lot of garbage. // SPEC: An unfixed type parameter with a set of bounds is fixed as follows: // SPEC: * The set of candidate types starts out as the set of all types in // SPEC: the bounds. // SPEC: * We then examine each bound in turn. For each exact bound U of Xi, // SPEC: all types which are not identical to U are removed from the candidate set. // Optimization: if we have two or more exact bounds, fixing is impossible. var candidates = new Dictionary<TypeWithAnnotations, TypeWithAnnotations>(EqualsIgnoringDynamicTupleNamesAndNullabilityComparer.Instance); Debug.Assert(!containsFunctionTypes(exact)); Debug.Assert(!containsFunctionTypes(upper)); // Function types are dropped if there are any non-function types. if (containsFunctionTypes(lower) && (containsNonFunctionTypes(lower) || containsNonFunctionTypes(exact) || containsNonFunctionTypes(upper))) { lower = removeFunctionTypes(lower); } // Optimization: if we have one exact bound then we need not add any // inexact bounds; we're just going to remove them anyway. if (exact == null) { if (lower != null) { // Lower bounds represent co-variance. AddAllCandidates(candidates, lower, VarianceKind.Out, conversions); } if (upper != null) { // Upper bounds represent contra-variance. AddAllCandidates(candidates, upper, VarianceKind.In, conversions); } } else { // Exact bounds represent invariance. AddAllCandidates(candidates, exact, VarianceKind.None, conversions); if (candidates.Count >= 2) { return default; } } if (candidates.Count == 0) { return default; } // Don't mutate the collection as we're iterating it. var initialCandidates = ArrayBuilder<TypeWithAnnotations>.GetInstance(); GetAllCandidates(candidates, initialCandidates); // SPEC: For each lower bound U of Xi all types to which there is not an // SPEC: implicit conversion from U are removed from the candidate set. if (lower != null) { MergeOrRemoveCandidates(candidates, lower, initialCandidates, conversions, VarianceKind.Out, ref useSiteInfo); } // SPEC: For each upper bound U of Xi all types from which there is not an // SPEC: implicit conversion to U are removed from the candidate set. if (upper != null) { MergeOrRemoveCandidates(candidates, upper, initialCandidates, conversions, VarianceKind.In, ref useSiteInfo); } initialCandidates.Clear(); GetAllCandidates(candidates, initialCandidates); // SPEC: * If among the remaining candidate types there is a unique type V to // SPEC: which there is an implicit conversion from all the other candidate // SPEC: types, then the parameter is fixed to V. TypeWithAnnotations best = default; foreach (var candidate in initialCandidates) { foreach (var candidate2 in initialCandidates) { if (!candidate.Equals(candidate2, TypeCompareKind.ConsiderEverything) && !ImplicitConversionExists(candidate2, candidate, ref useSiteInfo, conversions.WithNullability(false))) { goto OuterBreak; } } if (!best.HasType) { best = candidate; } else { Debug.Assert(!best.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)); // best candidate is not unique best = default; break; } OuterBreak: ; } initialCandidates.Free(); if (isFunctionType(best, out var functionType)) { // Realize the type as TDelegate, or Expression<TDelegate> if the type parameter // is constrained to System.Linq.Expressions.Expression. var resultType = functionType.GetInternalDelegateType(); if (hasExpressionTypeConstraint(typeParameter)) { var expressionOfTType = compilation.GetWellKnownType(WellKnownType.System_Linq_Expressions_Expression_T); resultType = expressionOfTType.Construct(resultType); } best = TypeWithAnnotations.Create(resultType, best.NullableAnnotation); } return best; static bool containsFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => isFunctionType(t, out _)) == true; } static bool containsNonFunctionTypes([NotNullWhen(true)] HashSet<TypeWithAnnotations>? types) { return types?.Any(t => !isFunctionType(t, out _)) == true; } static bool isFunctionType(TypeWithAnnotations type, [NotNullWhen(true)] out FunctionTypeSymbol? functionType) { functionType = type.Type as FunctionTypeSymbol; return functionType is not null; } static bool hasExpressionTypeConstraint(TypeParameterSymbol typeParameter) { var constraintTypes = typeParameter.ConstraintTypesNoUseSiteDiagnostics; return constraintTypes.Any(t => isExpressionType(t.Type)); } static bool isExpressionType(TypeSymbol? type) { while (type is { }) { if (type.IsGenericOrNonGenericExpressionType(out _)) { return true; } type = type.BaseTypeNoUseSiteDiagnostics; } return false; } static HashSet<TypeWithAnnotations>? removeFunctionTypes(HashSet<TypeWithAnnotations> types) { HashSet<TypeWithAnnotations>? updated = null; foreach (var type in types) { if (!isFunctionType(type, out _)) { updated ??= new HashSet<TypeWithAnnotations>(TypeWithAnnotations.EqualsComparer.ConsiderEverythingComparer); updated.Add(type); } } return updated; } } private static bool ImplicitConversionExists(TypeWithAnnotations sourceWithAnnotations, TypeWithAnnotations destinationWithAnnotations, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo, ConversionsBase conversions) { var source = sourceWithAnnotations.Type; var destination = destinationWithAnnotations.Type; // SPEC VIOLATION: For the purpose of algorithm in Fix method, dynamic type is not considered convertible to any other type, including object. if (source.IsDynamic() && !destination.IsDynamic()) { return false; } if (!conversions.HasTopLevelNullabilityImplicitConversion(sourceWithAnnotations, destinationWithAnnotations)) { return false; } return conversions.ClassifyImplicitConversionFromType(source, destination, ref useSiteInfo).Exists; } #nullable disable //////////////////////////////////////////////////////////////////////////////// // // Inferred return type // private TypeWithAnnotations InferReturnType(BoundExpression source, NamedTypeSymbol target, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)target != null); Debug.Assert(target.IsDelegateType()); Debug.Assert((object)target.DelegateInvokeMethod != null && !target.DelegateInvokeMethod.HasUseSiteError, "This method should only be called for legal delegate types."); Debug.Assert(!target.DelegateInvokeMethod.ReturnsVoid); // We should not be computing the inferred return type unless we are converting // to a delegate type where all the input types are fixed. Debug.Assert(!HasUnfixedParamInInputType(source, target)); // Spec 7.5.2.12: Inferred return type: // The inferred return type of an anonymous function F is used during // type inference and overload resolution. The inferred return type // can only be determined for an anonymous function where all parameter // types are known, either because they are explicitly given, provided // through an anonymous function conversion, or inferred during type // inference on an enclosing generic method invocation. // The inferred return type is determined as follows: // * If the body of F is an expression (that has a type) then the // inferred return type of F is the type of that expression. // * If the body of F is a block and the set of expressions in the // blocks return statements has a best common type T then the // inferred return type of F is T. // * Otherwise, a return type cannot be inferred for F. if (source.Kind != BoundKind.UnboundLambda) { return default; } var anonymousFunction = (UnboundLambda)source; if (anonymousFunction.HasSignature) { // Optimization: // We know that the anonymous function has a parameter list. If it does not // have the same arity as the delegate, then it cannot possibly be applicable. // Rather than have type inference fail, we will simply not make a return // type inference and have type inference continue on. Either inference // will fail, or we will infer a nonapplicable method. Either way, there // is no change to the semantics of overload resolution. var originalDelegateParameters = target.DelegateParameters(); if (originalDelegateParameters.IsDefault) { return default; } if (originalDelegateParameters.Length != anonymousFunction.ParameterCount) { return default; } } var fixedDelegate = (NamedTypeSymbol)GetFixedDelegateOrFunctionPointer(target); var fixedDelegateParameters = fixedDelegate.DelegateParameters(); // Optimization: // Similarly, if we have an entirely fixed delegate and an explicitly typed // anonymous function, then the parameter types had better be identical. // If not, applicability will eventually fail, so there is no semantic // difference caused by failing to make a return type inference. if (anonymousFunction.HasExplicitlyTypedParameterList) { for (int p = 0; p < anonymousFunction.ParameterCount; ++p) { if (!anonymousFunction.ParameterType(p).Equals(fixedDelegateParameters[p].Type, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { return default; } } } // Future optimization: We could return default if the delegate has out or ref parameters // and the anonymous function is an implicitly typed lambda. It will not be applicable. // We have an entirely fixed delegate parameter list, which is of the same arity as // the anonymous function parameter list, and possibly exactly the same types if // the anonymous function is explicitly typed. Make an inference from the // delegate parameters to the return type. return anonymousFunction.InferReturnType(_conversions, fixedDelegate, ref useSiteInfo); } /// <summary> /// Return the interface with an original definition matches /// the original definition of the target. If the are no matches, /// or multiple matches, the return value is null. /// </summary> private static NamedTypeSymbol GetInterfaceInferenceBound(ImmutableArray<NamedTypeSymbol> interfaces, NamedTypeSymbol target) { Debug.Assert(target.IsInterface); NamedTypeSymbol matchingInterface = null; foreach (var currentInterface in interfaces) { if (TypeSymbol.Equals(currentInterface.OriginalDefinition, target.OriginalDefinition, TypeCompareKind.ConsiderEverything)) { if ((object)matchingInterface == null) { matchingInterface = currentInterface; } else if (!TypeSymbol.Equals(matchingInterface, currentInterface, TypeCompareKind.ConsiderEverything)) { // Not unique. Bail out. return null; } } } return matchingInterface; } //////////////////////////////////////////////////////////////////////////////// // // Helper methods // //////////////////////////////////////////////////////////////////////////////// // // In error recovery and reporting scenarios we sometimes end up in a situation // like this: // // x.Goo( y=> // // and the question is, "is Goo a valid extension method of x?" If Goo is // generic, then Goo will be something like: // // static Blah Goo<T>(this Bar<T> bar, Func<T, T> f){ ... } // // What we would like to know is: given _only_ the expression x, can we infer // what T is in Bar<T> ? If we can, then for error recovery and reporting // we can provisionally consider Goo to be an extension method of x. If we // cannot deduce this just from x then we should consider Goo to not be an // extension method of x, at least until we have more information. // // Clearly it is pointless to run multiple phases public static ImmutableArray<TypeWithAnnotations> InferTypeArgumentsFromFirstArgument( CSharpCompilation compilation, ConversionsBase conversions, MethodSymbol method, ImmutableArray<BoundExpression> arguments, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert((object)method != null); Debug.Assert(method.Arity > 0); Debug.Assert(!arguments.IsDefault); // We need at least one formal parameter type and at least one argument. if ((method.ParameterCount < 1) || (arguments.Length < 1)) { return default(ImmutableArray<TypeWithAnnotations>); } Debug.Assert(!method.GetParameterType(0).IsDynamic()); var constructedFromMethod = method.ConstructedFrom; var inferrer = new MethodTypeInferrer( compilation, conversions, constructedFromMethod.TypeParameters, constructedFromMethod.ContainingType, constructedFromMethod.GetParameterTypes(), constructedFromMethod.ParameterRefKinds, arguments, extensions: null); if (!inferrer.InferTypeArgumentsFromFirstArgument(ref useSiteInfo)) { return default(ImmutableArray<TypeWithAnnotations>); } return inferrer.GetInferredTypeArguments(); } //////////////////////////////////////////////////////////////////////////////// private bool InferTypeArgumentsFromFirstArgument(ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(!_formalParameterTypes.IsDefault); Debug.Assert(_formalParameterTypes.Length >= 1); Debug.Assert(!_arguments.IsDefault); Debug.Assert(_arguments.Length >= 1); var dest = _formalParameterTypes[0]; var argument = _arguments[0]; TypeSymbol source = argument.Type; // Rule out lambdas, nulls, and so on. if (!IsReallyAType(source)) { return false; } LowerBoundInference(_extensions.GetTypeWithAnnotations(argument), dest, ref useSiteInfo); // Now check to see that every type parameter used by the first // formal parameter type was successfully inferred. for (int iParam = 0; iParam < _methodTypeParameters.Length; ++iParam) { TypeParameterSymbol pParam = _methodTypeParameters[iParam]; if (!dest.Type.ContainsTypeParameter(pParam)) { continue; } Debug.Assert(IsUnfixed(iParam)); if (!HasBound(iParam) || !Fix(iParam, ref useSiteInfo)) { return false; } } return true; } #nullable enable /// <summary> /// Return the inferred type arguments using null /// for any type arguments that were not inferred. /// </summary> private ImmutableArray<TypeWithAnnotations> GetInferredTypeArguments() { return _fixedResults.AsImmutable(); } private static bool IsReallyAType(TypeSymbol? type) { return type is { } && !type.IsErrorType() && !type.IsVoidType(); } private static void GetAllCandidates(Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, ArrayBuilder<TypeWithAnnotations> builder) { builder.AddRange(candidates.Values); } private static void AddAllCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, VarianceKind variance, ConversionsBase conversions) { foreach (var candidate in bounds) { var type = candidate; if (!conversions.IncludeNullability) { // https://github.com/dotnet/roslyn/issues/30534: Should preserve // distinct "not computed" state from initial binding. type = type.SetUnknownNullabilityForReferenceTypes(); } AddOrMergeCandidate(candidates, type, variance, conversions); } } private static void AddOrMergeCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { Debug.Assert(conversions.IncludeNullability || newCandidate.SetUnknownNullabilityForReferenceTypes().Equals(newCandidate, TypeCompareKind.ConsiderEverything)); if (candidates.TryGetValue(newCandidate, out TypeWithAnnotations oldCandidate)) { MergeAndReplaceIfStillCandidate(candidates, oldCandidate, newCandidate, variance, conversions); } else { candidates.Add(newCandidate, newCandidate); } } private static void MergeOrRemoveCandidates( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, HashSet<TypeWithAnnotations> bounds, ArrayBuilder<TypeWithAnnotations> initialCandidates, ConversionsBase conversions, VarianceKind variance, ref CompoundUseSiteInfo<AssemblySymbol> useSiteInfo) { Debug.Assert(variance == VarianceKind.In || variance == VarianceKind.Out); // SPEC: For each lower (upper) bound U of Xi all types to which there is not an // SPEC: implicit conversion from (to) U are removed from the candidate set. var comparison = conversions.IncludeNullability ? TypeCompareKind.ConsiderEverything : TypeCompareKind.IgnoreNullableModifiersForReferenceTypes; foreach (var bound in bounds) { foreach (var candidate in initialCandidates) { if (bound.Equals(candidate, comparison)) { continue; } TypeWithAnnotations source; TypeWithAnnotations destination; if (variance == VarianceKind.Out) { source = bound; destination = candidate; } else { source = candidate; destination = bound; } if (!ImplicitConversionExists(source, destination, ref useSiteInfo, conversions.WithNullability(false))) { candidates.Remove(candidate); if (conversions.IncludeNullability && candidates.TryGetValue(bound, out var oldBound)) { // merge the nullability from candidate into bound var oldAnnotation = oldBound.NullableAnnotation; var newAnnotation = oldAnnotation.MergeNullableAnnotation(candidate.NullableAnnotation, variance); if (oldAnnotation != newAnnotation) { var newBound = TypeWithAnnotations.Create(oldBound.Type, newAnnotation); candidates[bound] = newBound; } } } else if (bound.Equals(candidate, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes)) { // SPEC: 4.7 The Dynamic Type // Type inference (7.5.2) will prefer dynamic over object if both are candidates. // // This rule doesn't have to be implemented explicitly due to special handling of // conversions from dynamic in ImplicitConversionExists helper. // MergeAndReplaceIfStillCandidate(candidates, candidate, bound, variance, conversions); } } } } private static void MergeAndReplaceIfStillCandidate( Dictionary<TypeWithAnnotations, TypeWithAnnotations> candidates, TypeWithAnnotations oldCandidate, TypeWithAnnotations newCandidate, VarianceKind variance, ConversionsBase conversions) { // We make an exception when new candidate is dynamic, for backwards compatibility if (newCandidate.Type.IsDynamic()) { return; } if (candidates.TryGetValue(oldCandidate, out TypeWithAnnotations latest)) { // Note: we're ignoring the variance used merging previous candidates into `latest`. // If that variance is different than `variance`, we might infer the wrong nullability, but in that case, // we assume we'll report a warning when converting the arguments to the inferred parameter types. // (For instance, with F<T>(T x, T y, IIn<T> z) and interface IIn<in T> and interface IIOut<out T>, the // call F(IOut<object?>, IOut<object!>, IIn<IOut<object!>>) should find a nullability mismatch. Instead, // we'll merge the lower bounds IOut<object?> with IOut<object!> (using VarianceKind.Out) to produce // IOut<object?>, then merge that result with upper bound IOut<object!> (using VarianceKind.In) // to produce IOut<object?>. But then conversion of argument IIn<IOut<object!>> to parameter // IIn<IOut<object?>> will generate a warning at that point.) TypeWithAnnotations merged = latest.MergeEquivalentTypes(newCandidate, variance); candidates[oldCandidate] = merged; } } /// <summary> /// This is a comparer that ignores differences in dynamic-ness and tuple names. /// But it has a special case for top-level object vs. dynamic for purpose of method type inference. /// </summary> private sealed class EqualsIgnoringDynamicTupleNamesAndNullabilityComparer : EqualityComparer<TypeWithAnnotations> { internal static readonly EqualsIgnoringDynamicTupleNamesAndNullabilityComparer Instance = new EqualsIgnoringDynamicTupleNamesAndNullabilityComparer(); public override int GetHashCode(TypeWithAnnotations obj) { return obj.Type.GetHashCode(); } public override bool Equals(TypeWithAnnotations x, TypeWithAnnotations y) { // We do a equality test ignoring dynamic and tuple names differences, // but dynamic and object are not considered equal for backwards compatibility. if (x.Type.IsDynamic() ^ y.Type.IsDynamic()) { return false; } return x.Equals(y, TypeCompareKind.IgnoreDynamicAndTupleNames | TypeCompareKind.IgnoreNullableModifiersForReferenceTypes); } } } }
1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./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.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.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> /// 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; /// <summary> /// State of awaitable expressions, for substitution in placeholders within GetAwaiter calls. /// </summary> private PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>? _awaitablePlaceholdersOpt; /// <summary> /// Variables instances for each lambda or local function defined within the analyzed region. /// </summary> private PooledDictionary<MethodSymbol, Variables>? _nestedFunctionVariables; private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>>? _conditionalInfoForConversionOpt; /// <summary> /// Map from a target-typed conditional expression (such as a target-typed conditional or switch) to the nullable state on each branch. This /// is then used by VisitConversion to properly set the state before each branch when visiting a conversion applied to such a construct. These /// states will be the state after visiting the underlying arm value, but before visiting the conversion on top of the arm value. /// </summary> private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>> ConditionalInfoForConversion => _conditionalInfoForConversionOpt ??= PooledDictionary<BoundExpression, ImmutableArray<(LocalState, TypeWithState, bool)>>.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; #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); } /// <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 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() { _nestedFunctionVariables?.Free(); _awaitablePlaceholdersOpt?.Free(); _methodGroupReceiverMapOpt?.Free(); _placeholderLocalsOpt?.Free(); _variables.Free(); Debug.Assert(_conditionalInfoForConversionOpt is null or { Count: 0 }); _conditionalInfoForConversionOpt?.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, 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); _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 { }; } 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.NullableAnalysisData is { 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); } 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); enforceNotNull(null, this.State); foreach (var pendingReturn in pendingReturns) { enforceMemberNotNull(syntaxOpt: pendingReturn.Branch.Syntax, pendingReturn.State); if (pendingReturn.Branch is BoundReturnStatement returnStatement) { enforceNotNull(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; } 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'? { Diagnostics.Add(ErrorCode.WRN_UninitializedNonNullableField, exitLocation ?? symbol.Locations.FirstOrNone(), symbol.Kind.Localize(), symbol.Name); } } 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()) { if (needsDefaultInitialStateForMembers()) { foreach (var member in method.ContainingType.GetMembersUnordered()) { 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); } } bool needsDefaultInitialStateForMembers() { if (_hasInitialState) { return false; } // 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 (!method.HasThisConstructorInitializer(out _) && (!method.ContainingType.IsValueType || method.IsStatic)) { return true; } return method.IncludeFieldInitializersInBody(); } } 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; } } } 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 } }) { enforceParameterNotNullWhen(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; enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } } } 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"); } } void enforceNotNull(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()) { // Parameter '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_ParameterDisallowsNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), parameter.Name); } else { EnforceNotNullIfNotNull(syntaxOpt, state, this.MethodParameters, parameter.NotNullIfParameterNotNull, parameterState, parameter); } } } void enforceParameterNotNullWhen(SyntaxNode syntax, ImmutableArray<ParameterSymbol> parameters, bool sense, LocalState stateWhen) { if (!stateWhen.Reachable) { return; } foreach (var parameter in parameters) { reportParameterIfBadConditionalState(syntax, parameter, sense, stateWhen); } } 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; } 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 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) { // DoesNotReturn is only supported in member methods if (CurrentSymbol is MethodSymbol { ContainingSymbol: TypeSymbol _ } 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, 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, out _, requiresAnalysis: false); } finalNullableState = null; return; } Analyze(compilation, method, node, diagnostics, useConstructorExitWarnings, initialNullableState, getFinalNullableState, out finalNullableState); } private static void Analyze( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, 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, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState, finalNullableState: out finalNullableState, requiresAnalysis); } /// <summary> /// Gets the "after initializers state" which should be used at the beginning of nullable analysis /// of certain constructors. Only used for semantic model and debug verification. /// </summary> internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, Symbol? symbol) { if (symbol is MethodSymbol method && method.IncludeFieldInitializersInBody() && method.ContainingType is SourceMemberContainerTypeSymbol containingType) { var unusedDiagnostics = DiagnosticBag.GetInstance(); Binder.ProcessedFieldInitializers initializers = default; Binder.BindFieldInitializers(compilation, null, method.IsStatic ? containingType.StaticInitializers : containingType.InstanceInitializers, BindingDiagnosticBag.Discarded, ref initializers); NullableWalker.AnalyzeIfNeeded( compilation, method, InitializerRewriter.RewriteConstructor(initializers.BoundInitializers, method), unusedDiagnostics, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, out var afterInitializersState); unusedDiagnostics.Free(); return afterInitializersState; } return 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), 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, 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(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), 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, 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, 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, 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), 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.NullableAnalysisData?.Data is { } 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!.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.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. (value.WasCompilerGenerated && assignmentKind == AssignmentKind.Argument) || !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); // 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 = delegateOrMethod.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.CurrentSymbol; this.CurrentSymbol = lambdaOrFunctionSymbol; var oldDelegateInvokeMethod = _delegateInvokeMethod; _delegateInvokeMethod = delegateInvokeMethod; var oldUseDelegateInvokeParameterTypes = _useDelegateInvokeParameterTypes; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; var oldUseDelegateInvokeReturnType = _useDelegateInvokeReturnType; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; var oldReturnTypes = _returnTypesOpt; _returnTypesOpt = null; 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); RestorePending(oldPending2); // process any forward branches within the lambda body ImmutableArray<PendingBranch> pendingReturns = RemoveReturns(); RestorePending(oldPending); } finally { _snapshotBuilderOpt?.ExitWalker(this.SaveSharedState(), previousSlot); } _variables = _variables.Container!; this.State = oldState; _returnTypesOpt = oldReturnTypes; _useDelegateInvokeReturnType = oldUseDelegateInvokeReturnType; _useDelegateInvokeParameterTypes = oldUseDelegateInvokeParameterTypes; _delegateInvokeMethod = oldDelegateInvokeMethod; this.CurrentSymbol = 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 = withExpr.CloneMethod?.ReturnTypeWithAnnotations ?? 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(containingSymbol: null, resultSlot, withExpr.InitializerExpression, FlowAnalysisAnnotations.None); // 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); } 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). bool canIgnoreAnyType(TypeSymbol type) { return type.VisitType((t, unused1, unused2) => canIgnoreType(t), (object?)null) is object; } bool canIgnoreType(TypeSymbol type) { return type.IsErrorType() || type.IsDynamic() || type.HasUseSiteError || (type.IsAnonymousType && canIgnoreAnonymousType((NamedTypeSymbol)type)); } bool canIgnoreAnonymousType(NamedTypeSymbol type) { return AnonymousTypeManager.GetAnonymousTypePropertyTypesWithAnnotations(type).Any(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) { 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) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArguments(node, arguments, node.ArgumentRefKindsOpt, node.Constructor, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, invokedAsExtensionMethod: false).results; VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); 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 VisitObjectOrDynamicObjectCreation( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> argumentResults, BoundExpression? initializerOpt) { Debug.Assert(node.Kind == BoundKind.ObjectCreationExpression || node.Kind == BoundKind.DynamicObjectCreationExpression || node.Kind == BoundKind.NewT); var argumentTypes = argumentResults.SelectAsArray(ar => ar.RValueType); int slot = -1; var type = node.Type; var resultState = NullableFlowState.NotNull; if (type is object) { slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { var boundObjectCreationExpression = node as BoundObjectCreationExpression; var constructor = boundObjectCreationExpression?.Constructor; bool isDefaultValueTypeConstructor = constructor?.IsDefaultValueTypeConstructor(requireZeroInit: true) == 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!.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; } } if (initializerOpt != null) { VisitObjectCreationInitializer(containingSymbol: null, slot, initializerOpt, leftAnnotations: FlowAnalysisAnnotations.None); } SetResultType(node, TypeWithState.Create(type, resultState)); } private void VisitObjectCreationInitializer(Symbol? containingSymbol, int containingSlot, BoundExpression node, FlowAnalysisAnnotations leftAnnotations) { TakeIncrementalSnapshot(node); switch (node) { case BoundObjectInitializerExpression objectInitializer: checkImplicitReceiver(objectInitializer); foreach (var initializer in objectInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.AssignmentOperator: VisitObjectElementInitializer(containingSlot, (BoundAssignmentOperator)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(objectInitializer.Placeholder); break; case BoundCollectionInitializerExpression collectionInitializer: checkImplicitReceiver(collectionInitializer); foreach (var initializer in collectionInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.CollectionElementInitializer: VisitCollectionElementInitializer((BoundCollectionElementInitializer)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(collectionInitializer.Placeholder); break; default: Debug.Assert(containingSymbol is object); if (containingSymbol is object) { var type = ApplyLValueAnnotations(containingSymbol.GetTypeOrReturnType(), leftAnnotations); TypeWithState resultType = VisitOptionalImplicitConversion(node, type, useLegacyWarnings: false, trackMembers: true, AssignmentKind.Assignment); TrackNullableStateForAssignment(node, type, containingSlot, resultType, MakeSlot(node)); } break; } void checkImplicitReceiver(BoundObjectInitializerExpressionBase node) { if (containingSlot >= 0 && !node.Initializers.IsEmpty) { if (!node.Type.IsValueType && State[containingSlot].MayBeNull()) { if (containingSymbol is null) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, node.Syntax); } else { ReportDiagnostic(ErrorCode.WRN_NullReferenceInitializer, node.Syntax, containingSymbol); } } } } } private void VisitObjectElementInitializer(int containingSlot, BoundAssignmentOperator node) { TakeIncrementalSnapshot(node); var left = node.Left; switch (left.Kind) { case BoundKind.ObjectInitializerMember: { var objectInitializer = (BoundObjectInitializerMember)left; TakeIncrementalSnapshot(left); var symbol = objectInitializer.MemberSymbol; if (!objectInitializer.Arguments.IsDefaultOrEmpty) { VisitArguments(objectInitializer, objectInitializer.Arguments, objectInitializer.ArgumentRefKindsOpt, (PropertySymbol?)symbol, objectInitializer.ArgsToParamsOpt, objectInitializer.DefaultArguments, objectInitializer.Expanded); } if (symbol is object) { int slot = (containingSlot < 0 || !IsSlotMember(containingSlot, symbol)) ? -1 : GetOrCreateSlot(symbol, containingSlot); VisitObjectCreationInitializer(symbol, slot, node.Right, GetLValueAnnotations(node.Left)); // https://github.com/dotnet/roslyn/issues/35040: Should likely be setting _resultType in VisitObjectCreationInitializer // and using that value instead of reconstructing here } var result = new VisitResult(objectInitializer.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull); SetAnalyzedNullability(objectInitializer, result); SetAnalyzedNullability(node, result); } break; default: Visit(node); break; } } private new void VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { // Note: we analyze even omitted calls (var reinferredMethod, _, _) = VisitArguments(node, node.Arguments, refKindsOpt: default, node.AddMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod); 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); } 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(m => m.Kind == SymbolKind.Field)) { return true; } // If there are properties, the type is not empty. if (members.Any(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; } 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. bool isInferred = node.Syntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression; var arrayType = (ArrayTypeSymbol)node.Type; var elementType = arrayType.ElementTypeWithAnnotations; if (!isInferred) { foreach (var expr in expressions) { _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment); } } else { var expressionsNoConversions = ArrayBuilder<BoundExpression>.GetInstance(n); var conversions = ArrayBuilder<Conversion>.GetInstance(n); var resultTypes = 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 resultType = VisitRvalueWithState(expressionNoConversion); resultTypes.Add(resultType); placeholderBuilder.Add(CreatePlaceholderIfNecessary(expressionNoConversion, resultType.ToTypeWithAnnotations(compilation))); } var placeholders = placeholderBuilder.ToImmutableAndFree(); TypeSymbol? bestType = null; if (!node.HasErrors) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bestType = BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo); } 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); resultTypes[i] = VisitConversion(expression, expressionNoConversion, conversions[i], inferredType, resultTypes[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(resultTypes); 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: resultTypes[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(); resultTypes.Free(); arrayType = arrayType.WithElementType(inferredType); } expressions.Free(); SetResultType(node, TypeWithState.Create(arrayType, NullableFlowState.NotNull)); return null; } /// <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, TypeWithAnnotations)> returns, Binder binder, BoundNode node, Conversions conversions) { var walker = new NullableWalker(binder.Compilation, symbol: null, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, conversions: conversions, variables: 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); TypeWithAnnotations inferredType; if (bestType is { }) { // Note: so long as we have a best type, we can proceed. var bestTypeWithObliviousAnnotation = TypeWithAnnotations.Create(bestType); ConversionsBase conversionsWithoutNullability = walker._conversions.WithNullability(false); for (int i = 0; i < n; i++) { BoundExpression placeholder = placeholders[i]; Conversion conversion = conversionsWithoutNullability.ClassifyConversionFromExpression(placeholder, bestType, 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) ?? getTypeIfContainingType(methodContainer, rightUnderlyingType.Type); if (asMemberOfType is object) { 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; visitOperandConversion(binary.Left, leftOperand, leftConversion, parameters[0], leftUnderlyingType); visitOperandConversion(binary.Right, rightOperand, rightConversion, parameters[1], rightUnderlyingType); SetUpdatedSymbol(binary, binary.Method!, method); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType) { TypeWithAnnotations targetTypeWithNullability = parameter.TypeWithAnnotations; if (isLifted && targetTypeWithNullability.Type.IsNonNullableValueType()) { targetTypeWithNullability = TypeWithAnnotations.Create(MakeNullableOf(targetTypeWithNullability)); } _ = VisitConversion( expr as BoundConversion, operand, conversion, targetTypeWithNullability, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument, parameter); } } 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); // 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)); TypeSymbol? getTypeIfContainingType(TypeSymbol baseType, TypeSymbol? derivedType) { if (derivedType is null) { return null; } derivedType = derivedType.StrippedType(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyBuiltInConversion(derivedType, baseType, 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; }; } 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 BoundBinaryOperator? PushBinaryOperatorInterpolatedStringChildren(BoundBinaryOperator node, ArrayBuilder<BoundInterpolatedString> stack) { var result = base.PushBinaryOperatorInterpolatedStringChildren(node, stack); SetNotNullResult(node); return result; } /// <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.Kind == BoundKind.AwaitableValuePlaceholder) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue((BoundAwaitableValuePlaceholder)expression, out var value)) { expression = value.AwaitableExpression; } else { 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) is { Exists: true } conversion) { Debug.Assert(!conversion.IsUserDefined); return (rightType, NullableFlowState.NotNull); } conversion = GenerateConversionForConditionalOperator(node.RightOperand, rightType, leftType, reportMismatch: true); 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); 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(); NullableFlowState resultState; if (!wasTargetTyped) { if (resultType is null) { // 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); resultState = default; } else { var resultTypeWithAnnotations = TypeWithAnnotations.Create(resultType); 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); } } else { resultState = consequenceRValue.State.Join(alternativeRValue.State); ConditionalInfoForConversion.Add(node, ImmutableArray.Create( (consequenceState, consequenceRValue, consequenceEndReachable), (alternativeState, alternativeRValue, alternativeEndReachable))); } SetResultType(node, TypeWithState.Create(resultType, resultState)); return null; (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) { Debug.Assert(!arguments.IsDefault); bool shouldReturnNotNull = false; (ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions) = RemoveArgumentConversions(arguments, refKindsOpt); // Visit the arguments and collect results ImmutableArray<VisitArgumentResult> results = VisitArgumentsEvaluate(node.Syntax, argumentsNoConversions, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded); // 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(p => !p.NotNullIfParameterNotNull.IsEmpty); var notNullParametersBuilder = parameterHasNotNullIfNotNull ? ArrayBuilder<ParameterSymbol>.GetInstance() : null; if (!node.HasErrors && !parametersOpt.IsDefault) { // Visit conversions, inbound assignments including pre-conditions ImmutableHashSet<string>? returnNotNullIfParameterNotNull = IsAnalyzingAttribute ? null : method?.ReturnNotNullIfParameterNotNull; for (int i = 0; i < results.Length; i++) { (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, bool isExpandedParamsArgument) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { continue; } var argumentNoConversion = argumentsNoConversions[i]; var argument = i < arguments.Length ? arguments[i] : argumentsNoConversions[i]; // we disable nullable warnings on default arguments var previousDisableDiagnostics = _disableDiagnostics; _disableDiagnostics |= defaultArguments[i]; VisitArgumentConversionAndInboundAssignmentsAndPreConditions( GetConversionIfApplicable(argument, argumentNoConversion), argumentNoConversion, conversions.IsDefault || i >= conversions.Length ? Conversion.Identity : conversions[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], invokedAsExtensionMethod && i == 0); _disableDiagnostics = previousDisableDiagnostics; if (results[i].RValueType.IsNotNull || isExpandedParamsArgument) { notNullParametersBuilder?.Add(parameter); if (returnNotNullIfParameterNotNull?.Contains(parameter.Name) == true) { shouldReturnNotNull = true; } } } } else { // Normally we delay visiting the lambda until we can visit it along with its conversion. // Since we can't visit its conversion here, or it doesn't have one, we dig back in and // visit the lambda here to ensure all nodes have nullability info for public API for (int i = 0; i < results.Length; i++) { if (argumentsNoConversions[i] is BoundLambda lambda) { VisitLambda(lambda, delegateTypeOpt: null, results[i].StateForLambda); } } } 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); } 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 (!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( SyntaxNode syntax, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { Debug.Assert(!IsConditionalState); int n = arguments.Length; if (n == 0 && parametersOpt.IsDefaultOrEmpty) { return ImmutableArray<VisitArgumentResult>.Empty; } var visitedParameters = PooledHashSet<ParameterSymbol?>.GetInstance(); var resultsBuilder = ArrayBuilder<VisitArgumentResult>.GetInstance(n); var previousDisableDiagnostics = _disableDiagnostics; for (int i = 0; i < n; i++) { var (parameter, _, parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); // we disable nullable warnings on default arguments _disableDiagnostics = defaultArguments[i] || previousDisableDiagnostics; resultsBuilder.Add(VisitArgumentEvaluate(arguments[i], GetRefKind(refKindsOpt, i), parameterAnnotations)); visitedParameters.Add(parameter); } _disableDiagnostics = previousDisableDiagnostics; SetInvalidResult(); visitedParameters.Free(); return resultsBuilder.ToImmutableAndFree(); } 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, 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); 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); // 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); } 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); } } break; case RefKind.Out: 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, parameterType, 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; } void learnFromPostConditions(BoundExpression argument, TypeWithAnnotations parameterType, 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?.IsNull != false) ? NullableAnnotation.NotAnnotated : NullableAnnotation.Annotated; case BoundKind.ExpressionWithNullability: return ((BoundExpressionWithNullability)expr).NullableAnnotation; case BoundKind.MethodGroup: case BoundKind.UnboundLambda: case BoundKind.UnconvertedObjectCreationExpression: 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 } or BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) { // 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) { var conversion = GenerateConversion(_conversions, sourceExpression, sourceType, destinationType, fromExplicitCast: false, extensionMethodThisArgument: false); 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) { 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, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromExpression(sourceExpression, destinationType, ref discardedUseSiteInfo)) : (fromExplicitCast ? conversions.ClassifyConversionFromType(sourceType, destinationType, 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); } (BoundExpression operand, Conversion conversion) = RemoveConversion(expr, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(expr, operand); var operandType = VisitRvalueWithState(operand); // 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; } 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, UnboundLambda unboundLambda) { if (!unboundLambda.HasExplicitlyTypedParameterList) { return; } var invoke = delegateType?.DelegateInvokeMethod; if (invoke is null) { return; } Debug.Assert(delegateType is object); if (unboundLambda.HasExplicitReturnType(out _, out var returnType) && IsNullabilityMismatch(invoke.ReturnTypeWithAnnotations, returnType, requireIdentity: true)) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, location, unboundLambda.MessageID.Localize(), delegateType); } int count = Math.Min(invoke.ParameterCount, unboundLambda.ParameterCount); for (int i = 0; i < count; i++) { var invokeParameter = invoke.Parameters[i]; // 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>'. // https://github.com/dotnet/roslyn/issues/35564: Consider relaxing and allow implicit conversions of nullability. // (Compare with method group conversions which pass `requireIdentity: false`.) if (IsNullabilityMismatch(invokeParameter.TypeWithAnnotations, unboundLambda.ParameterTypeWithAnnotations(i), requireIdentity: true)) { // Should the warning be reported using location of specific lambda parameter? ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, location, unboundLambda.ParameterName(i), unboundLambda.MessageID.Localize(), delegateType); } } } private bool IsNullabilityMismatch(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { if (!HasTopLevelNullabilityConversion(source, destination, requireIdentity)) { return true; } if (requireIdentity) { return IsNullabilityMismatch(source, destination); } var sourceType = source.Type; var destinationType = destination.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return !_conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo).Exists; } private bool HasTopLevelNullabilityConversion(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { return requireIdentity ? _conversions.HasTopLevelNullabilityIdentityConversion(source, destination) : _conversions.HasTopLevelNullabilityImplicitConversion(source, destination); } /// <summary> /// Gets the conversion node for passing to <see cref="VisitConversion(BoundConversion, BoundExpression, Conversion, TypeWithAnnotations, TypeWithState, bool, bool, bool, AssignmentKind, ParameterSymbol, bool, bool, bool, Optional{LocalState}, bool, Location)"/>, /// 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) { Debug.Assert(!trackMembers || !IsConditionalState); Debug.Assert(conversionOperand != 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.UnboundLambda); } 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: // https://github.com/dotnet/roslyn/issues/54583 Handle resultState = NullableFlowState.NotNull; break; case ConversionKind.ObjectCreation: case ConversionKind.SwitchExpression: case ConversionKind.ConditionalExpression: resultState = visitNestedTargetTypedConstructs(); TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); 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); 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); 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); 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 (operandType.Type?.IsErrorType() != true && !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; } NullableFlowState visitNestedTargetTypedConstructs() { switch (conversionOperand) { case BoundConditionalOperator { WasTargetTyped: true } conditional: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(conditional)); var info = ConditionalInfoForConversion[conditional]; Debug.Assert(info.Length == 2); var consequence = conditional.Consequence; (BoundExpression consequenceOperand, Conversion consequenceConversion) = RemoveConversion(consequence, includeExplicitConversions: false); var consequenceRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(consequence, consequenceOperand, consequenceConversion, targetTypeWithNullability, info[0].ResultType, info[0].State, info[0].EndReachable); var alternative = conditional.Alternative; (BoundExpression alternativeOperand, Conversion alternativeConversion) = RemoveConversion(alternative, includeExplicitConversions: false); var alternativeRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(alternative, alternativeOperand, alternativeConversion, targetTypeWithNullability, info[1].ResultType, info[1].State, info[1].EndReachable); ConditionalInfoForConversion.Remove(conditional); return consequenceRValue.State.Join(alternativeRValue.State); } case BoundConvertedSwitchExpression { WasTargetTyped: true } @switch: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(@switch)); var info = ConditionalInfoForConversion[@switch]; Debug.Assert(info.Length == @switch.SwitchArms.Length); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(info.Length); for (int i = 0; i < info.Length; i++) { var (state, armResultType, isReachable) = info[i]; var arm = @switch.SwitchArms[i].Value; var (operand, conversion) = RemoveConversion(arm, includeExplicitConversions: false); resultTypes.Add(ConvertConditionalOperandOrSwitchExpressionArmResult(arm, operand, conversion, targetTypeWithNullability, armResultType, state, isReachable)); } var resultState = BestTypeInferrer.GetNullableState(resultTypes); resultTypes.Free(); ConditionalInfoForConversion.Remove(@switch); return resultState; } case BoundObjectCreationExpression { WasTargetTyped: true }: case BoundUnconvertedObjectCreationExpression: return NullableFlowState.NotNull; case BoundUnconvertedConditionalOperator: case BoundUnconvertedSwitchExpression: return operandType.State; default: throw ExceptionUtilities.UnexpectedValue(conversionOperand.Kind); } } } 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); 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(null, 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); } var delegateType = (NamedTypeSymbol)node.Type; switch (node.Argument) { case BoundMethodGroup group: { VisitMethodGroup(group); var method = node.MethodOpt; if (method is object) { method = CheckMethodGroupReceiverNullability(group, delegateType.DelegateInvokeMethod.Parameters, method, node.IsExtensionMethod); if (!group.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(group.Syntax.Location, delegateType, delegateType.DelegateInvokeMethod, method, node.IsExtensionMethod); } } SetAnalyzedNullability(group, default); } break; case BoundLambda lambda: { VisitLambda(lambda, delegateType); SetNotNullResult(lambda); if (!lambda.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(lambda.Symbol.DiagnosticLocation, delegateType, lambda.UnboundLambda); } } break; case BoundExpression arg when arg.Type is { TypeKind: TypeKind.Delegate } argType: { var argTypeWithAnnotations = TypeWithAnnotations.Create(argType, NullableAnnotation.NotAnnotated); var argState = VisitRvalueWithState(arg); ReportNullableAssignmentIfNecessary(arg, argTypeWithAnnotations, argState, useLegacyWarnings: false); if (!arg.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(arg.Syntax.Location, delegateType, delegateType.DelegateInvokeMethod, argType.DelegateInvokeMethod(), invokedAsExtensionMethod: false); } // Delegate creation will throw an exception if the argument is null LearnFromNonNullTest(arg, ref State); } break; default: VisitRvalue(node.Argument); break; } SetNotNullResult(node); return null; } 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); } 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) { // 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), BoundObjectInitializerMember { MemberSymbol: PropertySymbol prop } => prop.GetFlowAnalysisAnnotations(), BoundObjectInitializerMember { MemberSymbol: FieldSymbol field } => getFieldAnnotations(field), BoundParameter { ParameterSymbol: ParameterSymbol parameter } => ToInwardAnnotations(GetParameterAnnotations(parameter) & ~FlowAnalysisAnnotations.NotNull), // NotNull is enforced upon method exit _ => FlowAnalysisAnnotations.None }; return annotations & (FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull); static FlowAnalysisAnnotations getFieldAnnotations(FieldSymbol field) { return field.AssociatedSymbol is PropertySymbol property ? property.GetFlowAnalysisAnnotations() : field.FlowAnalysisAnnotations; } } 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.UnderlyingConversions, right); } } 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 = deconstructMethod.OriginalDefinition.AsMember((NamedTypeSymbol)rightResult.Type); } } 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 underlyingConversion = conversion.UnderlyingConversions[i]; 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), 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<Conversion> conversions, BoundExpression right) { int n = variables.Count; var rightParts = GetDeconstructionRightParts(right); Debug.Assert(rightParts.Length == n); for (int i = 0; i < n; i++) { var variable = variables[i]; var underlyingConversion = conversions[i]; 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); } 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) { 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); } } break; } 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.IsUserDefined && node.OperandConversion.Method?.ParameterCount == 1) { targetTypeOfOperandConversion = node.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, node.OperandConversion, 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, node.ResultConversion, 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, node.LeftConversion, 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, node.FinalConversion, 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? VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { BoundExpression receiver = node.Receiver; var receiverType = VisitRvalueWithState(receiver).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(receiver); VisitRvalue(node.Argument); var patternSymbol = node.PatternSymbol; if (receiverType is object) { patternSymbol = AsMemberOfType(receiverType, patternSymbol); } SetLvalueResultType(node, patternSymbol.GetTypeOrReturnType()); SetUpdatedSymbol(node, node.PatternSymbol, patternSymbol); 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.ConsiderEverything2)); 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); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(moveNextAsyncMethod), moveNextAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(moveNextPlaceholder, (moveNextPlaceholder, result)); Visit(awaitMoveNextInfo); _awaitablePlaceholdersOpt.Remove(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); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(disposeAsyncMethod), disposeAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(disposalPlaceholder, (disposalPlaceholder, result)); addedPlaceholder = true; } Visit(awaitDisposalInfo); if (addedPlaceholder) { _awaitablePlaceholdersOpt!.Remove(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 = node.ElementConversion.Kind == ConversionKind.UnsetConversionKind ? _conversions.ClassifyImplicitConversionFromType(sourceType.Type, destinationType.Type, ref discardedUseSiteInfo) : node.ElementConversion; 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); EnsureAwaitablePlaceholdersInitialized(); _awaitablePlaceholdersOpt.Add(placeholder, (node.Expression, _visitResult)); Visit(awaitableInfo); _awaitablePlaceholdersOpt.Remove(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 (node.Conversion.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.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); 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? 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.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); 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) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArgumentsEvaluate(node.Syntax, arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); 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) { var result = base.VisitNoPiaObjectCreationExpression(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNewT(BoundNewT node) { VisitObjectOrDynamicObjectCreation(node, ImmutableArray<BoundExpression>.Empty, ImmutableArray<VisitArgumentResult>.Empty, node.InitializerExpressionOpt); 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? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { var result = base.VisitStackAllocArrayCreation(node); Debug.Assert(node.Type is null || node.Type.IsErrorType() || node.Type.IsRefLikeType); SetNotNullResult(node); return result; } 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.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); 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), 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; } // https://github.com/dotnet/roslyn/issues/54583 // Better handle the constructor propagation //public override BoundNode? VisitInterpolatedString(BoundInterpolatedString node) //{ //} 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; } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { var result = base.VisitConvertedStackAllocExpression(node); SetNotNullResult(node); return result; } 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); 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) { SetNotNullResult(node); return null; } public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { SetNotNullResult(node); return null; } [MemberNotNull(nameof(_awaitablePlaceholdersOpt))] private void EnsureAwaitablePlaceholdersInitialized() { _awaitablePlaceholdersOpt ??= PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>.GetInstance(); } public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue(node, out var value)) { var result = value.Result; SetResult(node, result.RValueType, result.LValueType); } else { SetNotNullResult(node); } return null; } 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.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.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> /// 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; /// <summary> /// State of awaitable expressions, for substitution in placeholders within GetAwaiter calls. /// </summary> private PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>? _awaitablePlaceholdersOpt; /// <summary> /// Variables instances for each lambda or local function defined within the analyzed region. /// </summary> private PooledDictionary<MethodSymbol, Variables>? _nestedFunctionVariables; private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>>? _conditionalInfoForConversionOpt; /// <summary> /// Map from a target-typed conditional expression (such as a target-typed conditional or switch) to the nullable state on each branch. This /// is then used by VisitConversion to properly set the state before each branch when visiting a conversion applied to such a construct. These /// states will be the state after visiting the underlying arm value, but before visiting the conversion on top of the arm value. /// </summary> private PooledDictionary<BoundExpression, ImmutableArray<(LocalState State, TypeWithState ResultType, bool EndReachable)>> ConditionalInfoForConversion => _conditionalInfoForConversionOpt ??= PooledDictionary<BoundExpression, ImmutableArray<(LocalState, TypeWithState, bool)>>.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; #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); } /// <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 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() { _nestedFunctionVariables?.Free(); _awaitablePlaceholdersOpt?.Free(); _methodGroupReceiverMapOpt?.Free(); _placeholderLocalsOpt?.Free(); _variables.Free(); Debug.Assert(_conditionalInfoForConversionOpt is null or { Count: 0 }); _conditionalInfoForConversionOpt?.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, 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); _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 { }; } 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.NullableAnalysisData is { 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); } 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); enforceNotNull(null, this.State); foreach (var pendingReturn in pendingReturns) { enforceMemberNotNull(syntaxOpt: pendingReturn.Branch.Syntax, pendingReturn.State); if (pendingReturn.Branch is BoundReturnStatement returnStatement) { enforceNotNull(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; } 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'? { Diagnostics.Add(ErrorCode.WRN_UninitializedNonNullableField, exitLocation ?? symbol.Locations.FirstOrNone(), symbol.Kind.Localize(), symbol.Name); } } 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()) { if (needsDefaultInitialStateForMembers()) { foreach (var member in method.ContainingType.GetMembersUnordered()) { 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); } } bool needsDefaultInitialStateForMembers() { if (_hasInitialState) { return false; } // 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 (!method.HasThisConstructorInitializer(out _) && (!method.ContainingType.IsValueType || method.IsStatic)) { return true; } return method.IncludeFieldInitializersInBody(); } } 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; } } } 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 } }) { enforceParameterNotNullWhen(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; enforceParameterNotNullWhen(returnStatement.Syntax, parameters, sense: value, stateWhen: pendingReturn.State); return; } } } 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"); } } void enforceNotNull(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()) { // Parameter '{name}' must have a non-null value when exiting. Diagnostics.Add(ErrorCode.WRN_ParameterDisallowsNull, syntaxOpt?.GetLocation() ?? methodMainNode.Syntax.GetLastToken().GetLocation(), parameter.Name); } else { EnforceNotNullIfNotNull(syntaxOpt, state, this.MethodParameters, parameter.NotNullIfParameterNotNull, parameterState, parameter); } } } void enforceParameterNotNullWhen(SyntaxNode syntax, ImmutableArray<ParameterSymbol> parameters, bool sense, LocalState stateWhen) { if (!stateWhen.Reachable) { return; } foreach (var parameter in parameters) { reportParameterIfBadConditionalState(syntax, parameter, sense, stateWhen); } } 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; } 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 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) { // DoesNotReturn is only supported in member methods if (CurrentSymbol is MethodSymbol { ContainingSymbol: TypeSymbol _ } 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, 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, out _, requiresAnalysis: false); } finalNullableState = null; return; } Analyze(compilation, method, node, diagnostics, useConstructorExitWarnings, initialNullableState, getFinalNullableState, out finalNullableState); } private static void Analyze( CSharpCompilation compilation, MethodSymbol method, BoundNode node, DiagnosticBag diagnostics, bool useConstructorExitWarnings, VariableState? initialNullableState, bool getFinalNullableState, 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, analyzedNullabilityMapOpt: null, snapshotBuilderOpt: null, returnTypesOpt: null, getFinalNullableState, finalNullableState: out finalNullableState, requiresAnalysis); } /// <summary> /// Gets the "after initializers state" which should be used at the beginning of nullable analysis /// of certain constructors. Only used for semantic model and debug verification. /// </summary> internal static VariableState? GetAfterInitializersState(CSharpCompilation compilation, Symbol? symbol) { if (symbol is MethodSymbol method && method.IncludeFieldInitializersInBody() && method.ContainingType is SourceMemberContainerTypeSymbol containingType) { var unusedDiagnostics = DiagnosticBag.GetInstance(); Binder.ProcessedFieldInitializers initializers = default; Binder.BindFieldInitializers(compilation, null, method.IsStatic ? containingType.StaticInitializers : containingType.InstanceInitializers, BindingDiagnosticBag.Discarded, ref initializers); NullableWalker.AnalyzeIfNeeded( compilation, method, InitializerRewriter.RewriteConstructor(initializers.BoundInitializers, method), unusedDiagnostics, useConstructorExitWarnings: false, initialNullableState: null, getFinalNullableState: true, out var afterInitializersState); unusedDiagnostics.Free(); return afterInitializersState; } return 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), 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, 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(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), 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, 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, 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, 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), 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.NullableAnalysisData?.Data is { } 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!.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.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. (value.WasCompilerGenerated && assignmentKind == AssignmentKind.Argument) || !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); // 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 = delegateOrMethod.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.CurrentSymbol; this.CurrentSymbol = lambdaOrFunctionSymbol; var oldDelegateInvokeMethod = _delegateInvokeMethod; _delegateInvokeMethod = delegateInvokeMethod; var oldUseDelegateInvokeParameterTypes = _useDelegateInvokeParameterTypes; _useDelegateInvokeParameterTypes = useDelegateInvokeParameterTypes; var oldUseDelegateInvokeReturnType = _useDelegateInvokeReturnType; _useDelegateInvokeReturnType = useDelegateInvokeReturnType; var oldReturnTypes = _returnTypesOpt; _returnTypesOpt = null; 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); RestorePending(oldPending2); // process any forward branches within the lambda body ImmutableArray<PendingBranch> pendingReturns = RemoveReturns(); RestorePending(oldPending); } finally { _snapshotBuilderOpt?.ExitWalker(this.SaveSharedState(), previousSlot); } _variables = _variables.Container!; this.State = oldState; _returnTypesOpt = oldReturnTypes; _useDelegateInvokeReturnType = oldUseDelegateInvokeReturnType; _useDelegateInvokeParameterTypes = oldUseDelegateInvokeParameterTypes; _delegateInvokeMethod = oldDelegateInvokeMethod; this.CurrentSymbol = 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 = withExpr.CloneMethod?.ReturnTypeWithAnnotations ?? 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(containingSymbol: null, resultSlot, withExpr.InitializerExpression, FlowAnalysisAnnotations.None); // 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); } 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). bool canIgnoreAnyType(TypeSymbol type) { return type.VisitType((t, unused1, unused2) => canIgnoreType(t), (object?)null) is object; } bool canIgnoreType(TypeSymbol type) { return type.IsErrorType() || type.IsDynamic() || type.HasUseSiteError || (type.IsAnonymousType && canIgnoreAnonymousType((NamedTypeSymbol)type)); } bool canIgnoreAnonymousType(NamedTypeSymbol type) { return AnonymousTypeManager.GetAnonymousTypePropertyTypesWithAnnotations(type).Any(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) { 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) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArguments(node, arguments, node.ArgumentRefKindsOpt, node.Constructor, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, invokedAsExtensionMethod: false).results; VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); 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 VisitObjectOrDynamicObjectCreation( BoundExpression node, ImmutableArray<BoundExpression> arguments, ImmutableArray<VisitArgumentResult> argumentResults, BoundExpression? initializerOpt) { Debug.Assert(node.Kind == BoundKind.ObjectCreationExpression || node.Kind == BoundKind.DynamicObjectCreationExpression || node.Kind == BoundKind.NewT); var argumentTypes = argumentResults.SelectAsArray(ar => ar.RValueType); int slot = -1; var type = node.Type; var resultState = NullableFlowState.NotNull; if (type is object) { slot = GetOrCreatePlaceholderSlot(node); if (slot > 0) { var boundObjectCreationExpression = node as BoundObjectCreationExpression; var constructor = boundObjectCreationExpression?.Constructor; bool isDefaultValueTypeConstructor = constructor?.IsDefaultValueTypeConstructor(requireZeroInit: true) == 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!.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; } } if (initializerOpt != null) { VisitObjectCreationInitializer(containingSymbol: null, slot, initializerOpt, leftAnnotations: FlowAnalysisAnnotations.None); } SetResultType(node, TypeWithState.Create(type, resultState)); } private void VisitObjectCreationInitializer(Symbol? containingSymbol, int containingSlot, BoundExpression node, FlowAnalysisAnnotations leftAnnotations) { TakeIncrementalSnapshot(node); switch (node) { case BoundObjectInitializerExpression objectInitializer: checkImplicitReceiver(objectInitializer); foreach (var initializer in objectInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.AssignmentOperator: VisitObjectElementInitializer(containingSlot, (BoundAssignmentOperator)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(objectInitializer.Placeholder); break; case BoundCollectionInitializerExpression collectionInitializer: checkImplicitReceiver(collectionInitializer); foreach (var initializer in collectionInitializer.Initializers) { switch (initializer.Kind) { case BoundKind.CollectionElementInitializer: VisitCollectionElementInitializer((BoundCollectionElementInitializer)initializer); break; default: VisitRvalue(initializer); break; } } SetNotNullResult(collectionInitializer.Placeholder); break; default: Debug.Assert(containingSymbol is object); if (containingSymbol is object) { var type = ApplyLValueAnnotations(containingSymbol.GetTypeOrReturnType(), leftAnnotations); TypeWithState resultType = VisitOptionalImplicitConversion(node, type, useLegacyWarnings: false, trackMembers: true, AssignmentKind.Assignment); TrackNullableStateForAssignment(node, type, containingSlot, resultType, MakeSlot(node)); } break; } void checkImplicitReceiver(BoundObjectInitializerExpressionBase node) { if (containingSlot >= 0 && !node.Initializers.IsEmpty) { if (!node.Type.IsValueType && State[containingSlot].MayBeNull()) { if (containingSymbol is null) { ReportDiagnostic(ErrorCode.WRN_NullReferenceReceiver, node.Syntax); } else { ReportDiagnostic(ErrorCode.WRN_NullReferenceInitializer, node.Syntax, containingSymbol); } } } } } private void VisitObjectElementInitializer(int containingSlot, BoundAssignmentOperator node) { TakeIncrementalSnapshot(node); var left = node.Left; switch (left.Kind) { case BoundKind.ObjectInitializerMember: { var objectInitializer = (BoundObjectInitializerMember)left; TakeIncrementalSnapshot(left); var symbol = objectInitializer.MemberSymbol; if (!objectInitializer.Arguments.IsDefaultOrEmpty) { VisitArguments(objectInitializer, objectInitializer.Arguments, objectInitializer.ArgumentRefKindsOpt, (PropertySymbol?)symbol, objectInitializer.ArgsToParamsOpt, objectInitializer.DefaultArguments, objectInitializer.Expanded); } if (symbol is object) { int slot = (containingSlot < 0 || !IsSlotMember(containingSlot, symbol)) ? -1 : GetOrCreateSlot(symbol, containingSlot); VisitObjectCreationInitializer(symbol, slot, node.Right, GetLValueAnnotations(node.Left)); // https://github.com/dotnet/roslyn/issues/35040: Should likely be setting _resultType in VisitObjectCreationInitializer // and using that value instead of reconstructing here } var result = new VisitResult(objectInitializer.Type, NullableAnnotation.NotAnnotated, NullableFlowState.NotNull); SetAnalyzedNullability(objectInitializer, result); SetAnalyzedNullability(node, result); } break; default: Visit(node); break; } } private new void VisitCollectionElementInitializer(BoundCollectionElementInitializer node) { // Note: we analyze even omitted calls (var reinferredMethod, _, _) = VisitArguments(node, node.Arguments, refKindsOpt: default, node.AddMethod, node.ArgsToParamsOpt, node.DefaultArguments, node.Expanded, node.InvokedAsExtensionMethod); 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); } 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(m => m.Kind == SymbolKind.Field)) { return true; } // If there are properties, the type is not empty. if (members.Any(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; } 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. bool isInferred = node.Syntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression; var arrayType = (ArrayTypeSymbol)node.Type; var elementType = arrayType.ElementTypeWithAnnotations; if (!isInferred) { foreach (var expr in expressions) { _ = VisitOptionalImplicitConversion(expr, elementType, useLegacyWarnings: false, trackMembers: false, AssignmentKind.Assignment); } } else { var expressionsNoConversions = ArrayBuilder<BoundExpression>.GetInstance(n); var conversions = ArrayBuilder<Conversion>.GetInstance(n); var resultTypes = 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 resultType = VisitRvalueWithState(expressionNoConversion); resultTypes.Add(resultType); placeholderBuilder.Add(CreatePlaceholderIfNecessary(expressionNoConversion, resultType.ToTypeWithAnnotations(compilation))); } var placeholders = placeholderBuilder.ToImmutableAndFree(); TypeSymbol? bestType = null; if (!node.HasErrors) { var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; bestType = BestTypeInferrer.InferBestType(placeholders, _conversions, ref discardedUseSiteInfo); } 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); resultTypes[i] = VisitConversion(expression, expressionNoConversion, conversions[i], inferredType, resultTypes[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(resultTypes); 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: resultTypes[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(); resultTypes.Free(); arrayType = arrayType.WithElementType(inferredType); } expressions.Free(); SetResultType(node, TypeWithState.Create(arrayType, NullableFlowState.NotNull)); return null; } /// <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, TypeWithAnnotations)> returns, Binder binder, BoundNode node, Conversions conversions) { var walker = new NullableWalker(binder.Compilation, symbol: null, useConstructorExitWarnings: false, useDelegateInvokeParameterTypes: false, useDelegateInvokeReturnType: false, delegateInvokeMethodOpt: null, node, binder, conversions: conversions, variables: 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); TypeWithAnnotations inferredType; if (bestType is { }) { // Note: so long as we have a best type, we can proceed. var bestTypeWithObliviousAnnotation = TypeWithAnnotations.Create(bestType); ConversionsBase conversionsWithoutNullability = walker._conversions.WithNullability(false); for (int i = 0; i < n; i++) { BoundExpression placeholder = placeholders[i]; Conversion conversion = conversionsWithoutNullability.ClassifyConversionFromExpression(placeholder, bestType, 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) ?? getTypeIfContainingType(methodContainer, rightUnderlyingType.Type); if (asMemberOfType is object) { 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; visitOperandConversion(binary.Left, leftOperand, leftConversion, parameters[0], leftUnderlyingType); visitOperandConversion(binary.Right, rightOperand, rightConversion, parameters[1], rightUnderlyingType); SetUpdatedSymbol(binary, binary.Method!, method); void visitOperandConversion( BoundExpression expr, BoundExpression operand, Conversion conversion, ParameterSymbol parameter, TypeWithState operandType) { TypeWithAnnotations targetTypeWithNullability = parameter.TypeWithAnnotations; if (isLifted && targetTypeWithNullability.Type.IsNonNullableValueType()) { targetTypeWithNullability = TypeWithAnnotations.Create(MakeNullableOf(targetTypeWithNullability)); } _ = VisitConversion( expr as BoundConversion, operand, conversion, targetTypeWithNullability, operandType, checkConversion: true, fromExplicitCast: false, useLegacyWarnings: false, AssignmentKind.Argument, parameter); } } 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); // 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)); TypeSymbol? getTypeIfContainingType(TypeSymbol baseType, TypeSymbol? derivedType) { if (derivedType is null) { return null; } derivedType = derivedType.StrippedType(); var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; var conversion = _conversions.ClassifyBuiltInConversion(derivedType, baseType, 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; }; } 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 BoundBinaryOperator? PushBinaryOperatorInterpolatedStringChildren(BoundBinaryOperator node, ArrayBuilder<BoundInterpolatedString> stack) { var result = base.PushBinaryOperatorInterpolatedStringChildren(node, stack); SetNotNullResult(node); return result; } /// <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.Kind == BoundKind.AwaitableValuePlaceholder) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue((BoundAwaitableValuePlaceholder)expression, out var value)) { expression = value.AwaitableExpression; } else { 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) is { Exists: true } conversion) { Debug.Assert(!conversion.IsUserDefined); return (rightType, NullableFlowState.NotNull); } conversion = GenerateConversionForConditionalOperator(node.RightOperand, rightType, leftType, reportMismatch: true); 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); 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(); NullableFlowState resultState; if (!wasTargetTyped) { if (resultType is null) { // 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); resultState = default; } else { var resultTypeWithAnnotations = TypeWithAnnotations.Create(resultType); 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); } } else { resultState = consequenceRValue.State.Join(alternativeRValue.State); ConditionalInfoForConversion.Add(node, ImmutableArray.Create( (consequenceState, consequenceRValue, consequenceEndReachable), (alternativeState, alternativeRValue, alternativeEndReachable))); } SetResultType(node, TypeWithState.Create(resultType, resultState)); return null; (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) { Debug.Assert(!arguments.IsDefault); bool shouldReturnNotNull = false; (ImmutableArray<BoundExpression> argumentsNoConversions, ImmutableArray<Conversion> conversions) = RemoveArgumentConversions(arguments, refKindsOpt); // Visit the arguments and collect results ImmutableArray<VisitArgumentResult> results = VisitArgumentsEvaluate(node.Syntax, argumentsNoConversions, refKindsOpt, parametersOpt, argsToParamsOpt, defaultArguments, expanded); // 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(p => !p.NotNullIfParameterNotNull.IsEmpty); var notNullParametersBuilder = parameterHasNotNullIfNotNull ? ArrayBuilder<ParameterSymbol>.GetInstance() : null; if (!node.HasErrors && !parametersOpt.IsDefault) { // Visit conversions, inbound assignments including pre-conditions ImmutableHashSet<string>? returnNotNullIfParameterNotNull = IsAnalyzingAttribute ? null : method?.ReturnNotNullIfParameterNotNull; for (int i = 0; i < results.Length; i++) { (ParameterSymbol? parameter, TypeWithAnnotations parameterType, FlowAnalysisAnnotations parameterAnnotations, bool isExpandedParamsArgument) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); if (parameter is null) { continue; } var argumentNoConversion = argumentsNoConversions[i]; var argument = i < arguments.Length ? arguments[i] : argumentsNoConversions[i]; // we disable nullable warnings on default arguments var previousDisableDiagnostics = _disableDiagnostics; _disableDiagnostics |= defaultArguments[i]; VisitArgumentConversionAndInboundAssignmentsAndPreConditions( GetConversionIfApplicable(argument, argumentNoConversion), argumentNoConversion, conversions.IsDefault || i >= conversions.Length ? Conversion.Identity : conversions[i], GetRefKind(refKindsOpt, i), parameter, parameterType, parameterAnnotations, results[i], invokedAsExtensionMethod && i == 0); _disableDiagnostics = previousDisableDiagnostics; if (results[i].RValueType.IsNotNull || isExpandedParamsArgument) { notNullParametersBuilder?.Add(parameter); if (returnNotNullIfParameterNotNull?.Contains(parameter.Name) == true) { shouldReturnNotNull = true; } } } } else { // Normally we delay visiting the lambda until we can visit it along with its conversion. // Since we can't visit its conversion here, or it doesn't have one, we dig back in and // visit the lambda here to ensure all nodes have nullability info for public API for (int i = 0; i < results.Length; i++) { if (argumentsNoConversions[i] is BoundLambda lambda) { VisitLambda(lambda, delegateTypeOpt: null, results[i].StateForLambda); } } } 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); } 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 (!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( SyntaxNode syntax, ImmutableArray<BoundExpression> arguments, ImmutableArray<RefKind> refKindsOpt, ImmutableArray<ParameterSymbol> parametersOpt, ImmutableArray<int> argsToParamsOpt, BitVector defaultArguments, bool expanded) { Debug.Assert(!IsConditionalState); int n = arguments.Length; if (n == 0 && parametersOpt.IsDefaultOrEmpty) { return ImmutableArray<VisitArgumentResult>.Empty; } var visitedParameters = PooledHashSet<ParameterSymbol?>.GetInstance(); var resultsBuilder = ArrayBuilder<VisitArgumentResult>.GetInstance(n); var previousDisableDiagnostics = _disableDiagnostics; for (int i = 0; i < n; i++) { var (parameter, _, parameterAnnotations, _) = GetCorrespondingParameter(i, parametersOpt, argsToParamsOpt, expanded); // we disable nullable warnings on default arguments _disableDiagnostics = defaultArguments[i] || previousDisableDiagnostics; resultsBuilder.Add(VisitArgumentEvaluate(arguments[i], GetRefKind(refKindsOpt, i), parameterAnnotations)); visitedParameters.Add(parameter); } _disableDiagnostics = previousDisableDiagnostics; SetInvalidResult(); visitedParameters.Free(); return resultsBuilder.ToImmutableAndFree(); } 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, 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); 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); // 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); } 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); } } break; case RefKind.Out: 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, parameterType, 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; } void learnFromPostConditions(BoundExpression argument, TypeWithAnnotations parameterType, 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: 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 } or BoundConditionalOperator { WasTargetTyped: true } or BoundConvertedSwitchExpression { WasTargetTyped: true }) { // 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) { var conversion = GenerateConversion(_conversions, sourceExpression, sourceType, destinationType, fromExplicitCast: false, extensionMethodThisArgument: false); 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) { 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, ref discardedUseSiteInfo, forCast: true) : conversions.ClassifyImplicitConversionFromExpression(sourceExpression, destinationType, ref discardedUseSiteInfo)) : (fromExplicitCast ? conversions.ClassifyConversionFromType(sourceType, destinationType, 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); } (BoundExpression operand, Conversion conversion) = RemoveConversion(expr, includeExplicitConversions: false); SnapshotWalkerThroughConversionGroup(expr, operand); var operandType = VisitRvalueWithState(operand); // 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; } 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, UnboundLambda unboundLambda) { if (!unboundLambda.HasExplicitlyTypedParameterList) { return; } var invoke = delegateType?.DelegateInvokeMethod; if (invoke is null) { return; } Debug.Assert(delegateType is object); if (unboundLambda.HasExplicitReturnType(out _, out var returnType) && IsNullabilityMismatch(invoke.ReturnTypeWithAnnotations, returnType, requireIdentity: true)) { ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, location, unboundLambda.MessageID.Localize(), delegateType); } int count = Math.Min(invoke.ParameterCount, unboundLambda.ParameterCount); for (int i = 0; i < count; i++) { var invokeParameter = invoke.Parameters[i]; // 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>'. // https://github.com/dotnet/roslyn/issues/35564: Consider relaxing and allow implicit conversions of nullability. // (Compare with method group conversions which pass `requireIdentity: false`.) if (IsNullabilityMismatch(invokeParameter.TypeWithAnnotations, unboundLambda.ParameterTypeWithAnnotations(i), requireIdentity: true)) { // Should the warning be reported using location of specific lambda parameter? ReportDiagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, location, unboundLambda.ParameterName(i), unboundLambda.MessageID.Localize(), delegateType); } } } private bool IsNullabilityMismatch(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { if (!HasTopLevelNullabilityConversion(source, destination, requireIdentity)) { return true; } if (requireIdentity) { return IsNullabilityMismatch(source, destination); } var sourceType = source.Type; var destinationType = destination.Type; var discardedUseSiteInfo = CompoundUseSiteInfo<AssemblySymbol>.Discarded; return !_conversions.ClassifyImplicitConversionFromType(sourceType, destinationType, ref discardedUseSiteInfo).Exists; } private bool HasTopLevelNullabilityConversion(TypeWithAnnotations source, TypeWithAnnotations destination, bool requireIdentity) { return requireIdentity ? _conversions.HasTopLevelNullabilityIdentityConversion(source, destination) : _conversions.HasTopLevelNullabilityImplicitConversion(source, destination); } /// <summary> /// Gets the conversion node for passing to <see cref="VisitConversion(BoundConversion, BoundExpression, Conversion, TypeWithAnnotations, TypeWithState, bool, bool, bool, AssignmentKind, ParameterSymbol, bool, bool, bool, Optional{LocalState}, bool, Location)"/>, /// 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) { Debug.Assert(!trackMembers || !IsConditionalState); Debug.Assert(conversionOperand != 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.UnboundLambda); } 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: // https://github.com/dotnet/roslyn/issues/54583 Handle resultState = NullableFlowState.NotNull; break; case ConversionKind.ObjectCreation: case ConversionKind.SwitchExpression: case ConversionKind.ConditionalExpression: resultState = visitNestedTargetTypedConstructs(); TrackAnalyzedNullabilityThroughConversionGroup(targetTypeWithNullability.ToTypeWithState(), conversionOpt, conversionOperand); 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); 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); 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); 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 (operandType.Type?.IsErrorType() != true && !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; } NullableFlowState visitNestedTargetTypedConstructs() { switch (conversionOperand) { case BoundConditionalOperator { WasTargetTyped: true } conditional: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(conditional)); var info = ConditionalInfoForConversion[conditional]; Debug.Assert(info.Length == 2); var consequence = conditional.Consequence; (BoundExpression consequenceOperand, Conversion consequenceConversion) = RemoveConversion(consequence, includeExplicitConversions: false); var consequenceRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(consequence, consequenceOperand, consequenceConversion, targetTypeWithNullability, info[0].ResultType, info[0].State, info[0].EndReachable); var alternative = conditional.Alternative; (BoundExpression alternativeOperand, Conversion alternativeConversion) = RemoveConversion(alternative, includeExplicitConversions: false); var alternativeRValue = ConvertConditionalOperandOrSwitchExpressionArmResult(alternative, alternativeOperand, alternativeConversion, targetTypeWithNullability, info[1].ResultType, info[1].State, info[1].EndReachable); ConditionalInfoForConversion.Remove(conditional); return consequenceRValue.State.Join(alternativeRValue.State); } case BoundConvertedSwitchExpression { WasTargetTyped: true } @switch: { Debug.Assert(ConditionalInfoForConversion.ContainsKey(@switch)); var info = ConditionalInfoForConversion[@switch]; Debug.Assert(info.Length == @switch.SwitchArms.Length); var resultTypes = ArrayBuilder<TypeWithState>.GetInstance(info.Length); for (int i = 0; i < info.Length; i++) { var (state, armResultType, isReachable) = info[i]; var arm = @switch.SwitchArms[i].Value; var (operand, conversion) = RemoveConversion(arm, includeExplicitConversions: false); resultTypes.Add(ConvertConditionalOperandOrSwitchExpressionArmResult(arm, operand, conversion, targetTypeWithNullability, armResultType, state, isReachable)); } var resultState = BestTypeInferrer.GetNullableState(resultTypes); resultTypes.Free(); ConditionalInfoForConversion.Remove(@switch); return resultState; } case BoundObjectCreationExpression { WasTargetTyped: true }: case BoundUnconvertedObjectCreationExpression: return NullableFlowState.NotNull; case BoundUnconvertedConditionalOperator: case BoundUnconvertedSwitchExpression: return operandType.State; default: throw ExceptionUtilities.UnexpectedValue(conversionOperand.Kind); } } } 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); 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(null, 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); } var delegateType = (NamedTypeSymbol)node.Type; switch (node.Argument) { case BoundMethodGroup group: { VisitMethodGroup(group); var method = node.MethodOpt; if (method is object) { method = CheckMethodGroupReceiverNullability(group, delegateType.DelegateInvokeMethod.Parameters, method, node.IsExtensionMethod); if (!group.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(group.Syntax.Location, delegateType, delegateType.DelegateInvokeMethod, method, node.IsExtensionMethod); } } SetAnalyzedNullability(group, default); } break; case BoundLambda lambda: { VisitLambda(lambda, delegateType); SetNotNullResult(lambda); if (!lambda.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(lambda.Symbol.DiagnosticLocation, delegateType, lambda.UnboundLambda); } } break; case BoundExpression arg when arg.Type is { TypeKind: TypeKind.Delegate } argType: { var argTypeWithAnnotations = TypeWithAnnotations.Create(argType, NullableAnnotation.NotAnnotated); var argState = VisitRvalueWithState(arg); ReportNullableAssignmentIfNecessary(arg, argTypeWithAnnotations, argState, useLegacyWarnings: false); if (!arg.IsSuppressed) { ReportNullabilityMismatchWithTargetDelegate(arg.Syntax.Location, delegateType, delegateType.DelegateInvokeMethod, argType.DelegateInvokeMethod(), invokedAsExtensionMethod: false); } // Delegate creation will throw an exception if the argument is null LearnFromNonNullTest(arg, ref State); } break; default: VisitRvalue(node.Argument); break; } SetNotNullResult(node); return null; } 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); } 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) { // 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), BoundObjectInitializerMember { MemberSymbol: PropertySymbol prop } => prop.GetFlowAnalysisAnnotations(), BoundObjectInitializerMember { MemberSymbol: FieldSymbol field } => getFieldAnnotations(field), BoundParameter { ParameterSymbol: ParameterSymbol parameter } => ToInwardAnnotations(GetParameterAnnotations(parameter) & ~FlowAnalysisAnnotations.NotNull), // NotNull is enforced upon method exit _ => FlowAnalysisAnnotations.None }; return annotations & (FlowAnalysisAnnotations.DisallowNull | FlowAnalysisAnnotations.AllowNull); static FlowAnalysisAnnotations getFieldAnnotations(FieldSymbol field) { return field.AssociatedSymbol is PropertySymbol property ? property.GetFlowAnalysisAnnotations() : field.FlowAnalysisAnnotations; } } 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.UnderlyingConversions, right); } } 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 = deconstructMethod.OriginalDefinition.AsMember((NamedTypeSymbol)rightResult.Type); } } 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 underlyingConversion = conversion.UnderlyingConversions[i]; 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), 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<Conversion> conversions, BoundExpression right) { int n = variables.Count; var rightParts = GetDeconstructionRightParts(right); Debug.Assert(rightParts.Length == n); for (int i = 0; i < n; i++) { var variable = variables[i]; var underlyingConversion = conversions[i]; 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); } 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) { 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); } } break; } 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.IsUserDefined && node.OperandConversion.Method?.ParameterCount == 1) { targetTypeOfOperandConversion = node.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, node.OperandConversion, 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, node.ResultConversion, 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, node.LeftConversion, 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, node.FinalConversion, 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? VisitIndexOrRangePatternIndexerAccess(BoundIndexOrRangePatternIndexerAccess node) { BoundExpression receiver = node.Receiver; var receiverType = VisitRvalueWithState(receiver).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(receiver); VisitRvalue(node.Argument); var patternSymbol = node.PatternSymbol; if (receiverType is object) { patternSymbol = AsMemberOfType(receiverType, patternSymbol); } SetLvalueResultType(node, patternSymbol.GetTypeOrReturnType()); SetUpdatedSymbol(node, node.PatternSymbol, patternSymbol); 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.ConsiderEverything2)); 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); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(moveNextAsyncMethod), moveNextAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(moveNextPlaceholder, (moveNextPlaceholder, result)); Visit(awaitMoveNextInfo); _awaitablePlaceholdersOpt.Remove(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); EnsureAwaitablePlaceholdersInitialized(); var result = new VisitResult(GetReturnTypeWithState(disposeAsyncMethod), disposeAsyncMethod.ReturnTypeWithAnnotations); _awaitablePlaceholdersOpt.Add(disposalPlaceholder, (disposalPlaceholder, result)); addedPlaceholder = true; } Visit(awaitDisposalInfo); if (addedPlaceholder) { _awaitablePlaceholdersOpt!.Remove(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 = node.ElementConversion.Kind == ConversionKind.UnsetConversionKind ? _conversions.ClassifyImplicitConversionFromType(sourceType.Type, destinationType.Type, ref discardedUseSiteInfo) : node.ElementConversion; 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); EnsureAwaitablePlaceholdersInitialized(); _awaitablePlaceholdersOpt.Add(placeholder, (node.Expression, _visitResult)); Visit(awaitableInfo); _awaitablePlaceholdersOpt.Remove(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 (node.Conversion.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.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); 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? 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.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); 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) { Debug.Assert(!IsConditionalState); var arguments = node.Arguments; var argumentResults = VisitArgumentsEvaluate(node.Syntax, arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); VisitObjectOrDynamicObjectCreation(node, arguments, argumentResults, node.InitializerExpressionOpt); 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) { var result = base.VisitNoPiaObjectCreationExpression(node); SetResultType(node, TypeWithState.Create(node.Type, NullableFlowState.NotNull)); return result; } public override BoundNode? VisitNewT(BoundNewT node) { VisitObjectOrDynamicObjectCreation(node, ImmutableArray<BoundExpression>.Empty, ImmutableArray<VisitArgumentResult>.Empty, node.InitializerExpressionOpt); 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? VisitStackAllocArrayCreation(BoundStackAllocArrayCreation node) { var result = base.VisitStackAllocArrayCreation(node); Debug.Assert(node.Type is null || node.Type.IsErrorType() || node.Type.IsRefLikeType); SetNotNullResult(node); return result; } 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.Syntax, node.Arguments, node.ArgumentRefKindsOpt, parametersOpt: default, argsToParamsOpt: default, defaultArguments: default, expanded: false); 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), 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; } // https://github.com/dotnet/roslyn/issues/54583 // Better handle the constructor propagation //public override BoundNode? VisitInterpolatedString(BoundInterpolatedString node) //{ //} 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; } public override BoundNode? VisitInterpolatedStringHandlerPlaceholder(BoundInterpolatedStringHandlerPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitInterpolatedStringArgumentPlaceholder(BoundInterpolatedStringArgumentPlaceholder node) { SetNotNullResult(node); return null; } public override BoundNode? VisitConvertedStackAllocExpression(BoundConvertedStackAllocExpression node) { var result = base.VisitConvertedStackAllocExpression(node); SetNotNullResult(node); return result; } 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); 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) { SetNotNullResult(node); return null; } public override BoundNode? VisitObjectOrCollectionValuePlaceholder(BoundObjectOrCollectionValuePlaceholder node) { SetNotNullResult(node); return null; } [MemberNotNull(nameof(_awaitablePlaceholdersOpt))] private void EnsureAwaitablePlaceholdersInitialized() { _awaitablePlaceholdersOpt ??= PooledDictionary<BoundAwaitableValuePlaceholder, (BoundExpression AwaitableExpression, VisitResult Result)>.GetInstance(); } public override BoundNode? VisitAwaitableValuePlaceholder(BoundAwaitableValuePlaceholder node) { if (_awaitablePlaceholdersOpt != null && _awaitablePlaceholdersOpt.TryGetValue(node, out var value)) { var result = value.Result; SetResult(node, result.RValueType, result.LValueType); } else { SetNotNullResult(node); } return null; } 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
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/CSharp/Test/Semantic/Semantics/NullableReferenceTypesTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CSharp.Symbols.FlowAnalysisAnnotations; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { [CompilerTrait(CompilerFeature.NullableReferenceTypes)] public class NullableReferenceTypesTests : CSharpTestBase { private const string Tuple2NonNullable = @" namespace System { #nullable enable // struct with two values public struct ValueTuple<T1, T2> where T1 : notnull where T2 : notnull { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return """"; } } }"; private const string TupleRestNonNullable = @" namespace System { #nullable enable public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; Rest = rest; } public override string ToString() { return base.ToString(); } } }"; private CSharpCompilation CreateNullableCompilation(CSharpTestSource source, IEnumerable<MetadataReference> references = null, CSharpParseOptions parseOptions = null) { return CreateCompilation(source, options: WithNullableEnable(), references: references, parseOptions: parseOptions); } private static bool IsNullableAnalysisEnabled(CSharpCompilation compilation, string methodName) { var method = compilation.GetMember<MethodSymbol>(methodName); return method.IsNullableAnalysisEnabled(); } [Fact] public void DefaultLiteralInConditional() { var comp = CreateNullableCompilation(@" class C { public void M<T>(bool condition, T t) { t = default; _ = condition ? t : default; _ = condition ? default : t; } }"); comp.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // t = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(6, 13)); } [Fact, WorkItem(46461, "https://github.com/dotnet/roslyn/issues/46461")] public void DefaultLiteralInConditional_02() { var comp = CreateNullableCompilation(@" using System; public class C { public void M() { M1(true, b => b ? """" : default); M1<bool, string?>(true, b => b ? """" : default); M1<bool, string>(true, b => b ? """" : default); // 1 M1(true, b => b ? """" : null); M1<bool, string?>(true, b => b ? """" : null); M1<bool, string>(true, b => b ? """" : null); // 2 } public void M1<T,U>(T t, Func<T, U> fn) { fn(t); } }"); comp.VerifyDiagnostics( // (10,37): warning CS8603: Possible null reference return. // M1<bool, string>(true, b => b ? "" : default); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, @"b ? """" : default", isSuppressed: false).WithLocation(10, 37), // (14,37): warning CS8603: Possible null reference return. // M1<bool, string>(true, b => b ? "" : null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, @"b ? """" : null", isSuppressed: false).WithLocation(14, 37)); } [Fact, WorkItem(33982, "https://github.com/dotnet/roslyn/issues/33982")] public void AssigningNullToRefLocalIsSafetyWarning() { var comp = CreateCompilation(@" class C { void M(ref string s1, ref string s2) { s1 = null; // 1 s1.ToString(); // 2 ref string s3 = ref s2; s3 = null; // 3 s3.ToString(); // 4 ref string s4 = ref s2; s4 ??= null; // 5 s4.ToString(); // 6 ref string s5 = ref s2; M2(out s5); // 7 s5.ToString(); // 8 } void M2(out string? x) => throw null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // s1 = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 14), // (7,9): warning CS8602: Possible dereference of a null reference. // s1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(7, 9), // (10,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // s3 = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 14), // (11,9): warning CS8602: Possible dereference of a null reference. // s3.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(11, 9), // (14,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // s4 ??= null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 16), // (15,9): warning CS8602: Possible dereference of a null reference. // s4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(15, 9), // (18,16): warning CS8601: Possible null reference assignment. // M2(out s5); // 7 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s5").WithLocation(18, 16), // (19,9): warning CS8602: Possible dereference of a null reference. // s5.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(19, 9) ); } [Fact, WorkItem(33365, "https://github.com/dotnet/roslyn/issues/33365")] public void AssigningNullToConditionalRefLocal() { var comp = CreateCompilation(@" class C { void M(ref string s1, ref string s2, bool b) { (b ? ref s1 : ref s1) = null; // 1 s1.ToString(); ref string s3 = ref s2; (b ? ref s3 : ref s3) = null; // 2 s3.ToString(); ref string s4 = ref s2; (b ? ref s4 : ref s4) ??= null; // 3 s4.ToString(); ref string s5 = ref s2; M2(out (b ? ref s5 : ref s5)); // 4 s5.ToString(); } void M2(out string? x) => throw null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,33): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref s1 : ref s1) = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 33), // (10,33): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref s3 : ref s3) = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 33), // (14,35): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref s4 : ref s4) ??= null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 35), // (18,17): warning CS8601: Possible null reference assignment. // M2(out (b ? ref s5 : ref s5)); // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "b ? ref s5 : ref s5").WithLocation(18, 17) ); } [Fact, WorkItem(33365, "https://github.com/dotnet/roslyn/issues/33365")] public void AssigningNullToConditionalRefLocal_NullableLocals() { var comp = CreateCompilation(@" class C { void M(ref string? s1, ref string? s2, bool b) { (b ? ref s1 : ref s1) = null; s1.ToString(); // 1 ref string? s3 = ref s2; (b ? ref s3 : ref s3) = null; s3.ToString(); // 2 ref string? s4 = ref s2; (b ? ref s4 : ref s4) ??= null; s4.ToString(); // 3 ref string? s5 = ref s2; M2(out (b ? ref s5 : ref s5)); s5.ToString(); // 4 } void M2(out string? x) => throw null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Possible dereference of a null reference. // s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(7, 9), // (11,9): warning CS8602: Possible dereference of a null reference. // s3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(11, 9), // (15,9): warning CS8602: Possible dereference of a null reference. // s4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(15, 9), // (19,9): warning CS8602: Possible dereference of a null reference. // s5.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(19, 9) ); } [Fact, WorkItem(33365, "https://github.com/dotnet/roslyn/issues/33365")] public void AssigningNullToConditionalRefLocal_NullableLocals_NonNullValues() { var comp = CreateCompilation(@" class C { void M(ref string? s1, ref string? s2, bool b) { (b ? ref s1 : ref s1) = """"; s1.ToString(); // 1 ref string? s3 = ref s2; (b ? ref s3 : ref s3) = """"; s3.ToString(); // 2 ref string? s4 = ref s2; (b ? ref s4 : ref s4) ??= """"; s4.ToString(); // 3 ref string? s5 = ref s2; M2(out (b ? ref s5 : ref s5)); s5.ToString(); // 4 } void M2(out string x) => throw null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Possible dereference of a null reference. // s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(7, 9), // (11,9): warning CS8602: Possible dereference of a null reference. // s3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(11, 9), // (15,9): warning CS8602: Possible dereference of a null reference. // s4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(15, 9), // (19,9): warning CS8602: Possible dereference of a null reference. // s5.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(19, 9) ); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver() { var comp = CreateCompilation(@" public class B { public B? f2; public B? f3; } public class C { public B? f; static void Main() { new C() { f = { f2 = null, f3 = null }}; // 1 } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,23): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C.f'. // new C() { f = { f2 = null, f3 = null }}; // 1 Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ f2 = null, f3 = null }").WithArguments("C.f").WithLocation(12, 23)); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_Generic() { var comp = CreateCompilation(@" public interface IB { object? f2 { get; set; } object? f3 { get; set; } } public struct StructB : IB { public object? f2 { get; set; } public object? f3 { get; set; } } public class ClassB : IB { public object? f2 { get; set; } public object? f3 { get; set; } } public class C<T> where T : IB? { public T f = default!; static void Main() { new C<T>() { f = { f2 = null, f3 = null }}; // 1 new C<ClassB>() { f = { f2 = null, f3 = null }}; new C<ClassB?>() { f = { f2 = null, f3 = null }}; // 2 new C<StructB>() { f = { f2 = null, f3 = null }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (25,26): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C<T>.f'. // new C<T>() { f = { f2 = null, f3 = null }}; // 1 Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ f2 = null, f3 = null }").WithArguments("C<T>.f").WithLocation(25, 26), // (27,32): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C<ClassB?>.f'. // new C<ClassB?>() { f = { f2 = null, f3 = null }}; // 2 Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ f2 = null, f3 = null }").WithArguments("C<ClassB?>.f").WithLocation(27, 32)); } [Fact, WorkItem(38060, "https://github.com/dotnet/roslyn/issues/38060")] public void CheckImplicitObjectInitializerReceiver_EmptyInitializers() { var comp = CreateCompilation(@" public class B { } public class C { public B? f; static void Main() { new C() { f = { }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_CollectionInitializer() { var comp = CreateCompilation(@" using System.Collections; public class B : IEnumerable { public void Add(object o) { } public IEnumerator GetEnumerator() => null!; } public class C { public B? f; static void Main() { new C() { f = { new object(), new object() }}; // 1 } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,23): warning CS8670: Object or collection initializer implicitly dereferences nullable member 'C.f'. // new C() { f = { new object(), new object() }}; // 1 Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ new object(), new object() }").WithArguments("C.f").WithLocation(15, 23)); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_CollectionInitializer_Generic() { var comp = CreateCompilation(@" using System.Collections; public interface IAddable : IEnumerable { void Add(object o); } public class ClassAddable : IAddable { public void Add(object o) { } public IEnumerator GetEnumerator() => null!; } public struct StructAddable : IAddable { public void Add(object o) { } public IEnumerator GetEnumerator() => null!; } public class C<T> where T : IAddable? { public T f = default!; static void Main() { new C<T>() { f = { new object(), new object() }}; // 1 new C<ClassAddable>() { f = { new object(), new object() }}; new C<ClassAddable?>() { f = { new object(), new object() }}; // 2 new C<StructAddable>() { f = { new object(), new object() }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (27,26): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C<T>.f'. // new C<T>() { f = { new object(), new object() }}; // 1 Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ new object(), new object() }").WithArguments("C<T>.f").WithLocation(27, 26), // (29,38): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C<ClassAddable?>.f'. // new C<ClassAddable?>() { f = { new object(), new object() }}; // 2 Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ new object(), new object() }").WithArguments("C<ClassAddable?>.f").WithLocation(29, 38)); } [Fact, WorkItem(38060, "https://github.com/dotnet/roslyn/issues/38060")] public void CheckImplicitObjectInitializerReceiver_EmptyCollectionInitializer() { var comp = CreateCompilation(@" public class B { void Add(object o) { } } public class C { public B? f; static void Main() { new C() { f = { }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_ReceiverNotNullable() { var comp = CreateCompilation(@" public class B { public B? f2; } public class C { public B f; static void Main() { new C() { f = { f2 = null }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8618: Non-nullable field 'f' is uninitialized. Consider declaring the field as nullable. // public B f; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "f").WithArguments("field", "f").WithLocation(8, 14) ); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_ReceiverOblivious() { var comp = CreateCompilation(@" public class B { public B? f2; } public class C { #nullable disable public B f; #nullable enable static void Main() { new C() { f = { f2 = null }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_ReceiverNullableIndexer() { var comp = CreateCompilation(@" public class B { public B? f2; } public class C { static void Main() { new C() { [0] = { f2 = null }}; } public B? this[int i] { get => throw null!; set => throw null!; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,25): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C.this[int]'. // new C() { [0] = { f2 = null }}; Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ f2 = null }").WithArguments("C.this[int]").WithLocation(10, 25)); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_Nested() { var comp = CreateCompilation(@" public class B { public B? f2; } public class C { public C? fc; public B? fb; static void Main() { new C() { fc = { fb = { f2 = null} }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,24): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C.fc'. // new C() { fc = { fb = { f2 = null} }}; Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ fb = { f2 = null} }").WithArguments("C.fc").WithLocation(12, 24), // (12,31): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C.fb'. // new C() { fc = { fb = { f2 = null} }}; Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ f2 = null}").WithArguments("C.fb").WithLocation(12, 31)); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_Index() { var comp = CreateCompilation(@" public class B { public B? this[int i] { get => throw null!; set => throw null!; } } public class C { public B? f; static void Main() { new C() { f = { [0] = null }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,23): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C.f'. // new C() { f = { [0] = null }}; Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ [0] = null }").WithArguments("C.f").WithLocation(11, 23)); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitCollectionInitializerReceiver() { var comp = CreateCompilation(@" public class B : System.Collections.Generic.IEnumerable<int> { public void Add(int i) { } System.Collections.Generic.IEnumerator<int> System.Collections.Generic.IEnumerable<int>.GetEnumerator() => throw null!; System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => throw null!; } public class C { public B? f; static void Main() { new C() { f = { 1 }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,23): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C.f'. // new C() { f = { 1 }}; Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ 1 }").WithArguments("C.f").WithLocation(13, 23)); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_ReturnType() { var comp = CreateCompilation(@" using System.Collections.Generic; class C { static void M(object? o, object o2) { L(o)[0].ToString(); // 1 foreach (var x in L(o)) { x.ToString(); // 2 } L(o2)[0].ToString(); } static List<T> L<T>(T t) => null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // L(o)[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "L(o)[0]").WithLocation(7, 9), // (10,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 13)); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_ReturnType_Inferred() { var comp = CreateCompilation(@" public class C<T> { public T Field = default!; public C<T> this[T index] { get => throw null!; set => throw null!; } } public class Main { static void M(object? o, object o2) { if (o is null) return; L(o)[0].Field.ToString(); o2 = null; L(o2)[0].Field.ToString(); // 1 } static C<U> L<U>(U u) => null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // o2 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 14), // (15,9): warning CS8602: Dereference of a possibly null reference. // L(o2)[0].Field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "L(o2)[0].Field").WithLocation(15, 9) ); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_ReturnType_NestedNullability_Inferred() { var comp = CreateCompilation(@" public class C<T> { public T this[int index] { get => throw null!; set => throw null!; } } public class Program { static void M(object? x) { var y = L(new[] { x }); y[0][0].ToString(); // warning if (x == null) return; var z = L(new[] { x }); z[0][0].ToString(); // ok } static C<U> L<U>(U u) => null!; } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // y[0][0].ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y[0][0]").WithLocation(11, 9) ); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_SetterArguments() { var comp = CreateCompilation(@" public class C<T> { public int this[T index] { get => throw null!; set => throw null!; } } class Program { static void M(object? o, object o2) { L(o)[o] = 1; L(o)[o2] = 2; L(o2)[o] = 3; // warn L(o2)[o2] = 4; } static C<U> L<U>(U u) => null!; } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,15): warning CS8604: Possible null reference argument for parameter 'index' in 'int C<object>.this[object index]'. // L(o2)[o] = 3; // warn Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("index", "int C<object>.this[object index]").WithLocation(13, 15) ); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_SetterArguments_Inferred() { var comp = CreateCompilation(@" public class C<T> { public int this[T index] { get => throw null!; set => throw null!; } } class Program { static void M(object? o, object o2, object? input, object input2) { if (o is null) return; L(o)[input] = 1; // 1 L(o)[input2] = 2; o2 = null; L(o2)[input] = 3; L(o2)[input2] = 4; } static C<U> L<U>(U u) => null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,14): warning CS8604: Possible null reference argument for parameter 'index' in 'int C<object>.this[object index]'. // L(o)[input] = 1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "input").WithArguments("index", "int C<object>.this[object index]").WithLocation(11, 14), // (14,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // o2 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 14) ); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_GetterArguments() { var comp = CreateCompilation(@" public class C<T> { public int this[T index] { get => throw null!; set => throw null!; } } class Program { static void M(object? o, object o2) { _ = L(o)[o]; _ = L(o)[o2]; _ = L(o2)[o]; // warn _ = L(o2)[o2]; } static C<U> L<U>(U u) => null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,19): warning CS8604: Possible null reference argument for parameter 'index' in 'int C<object>.this[object index]'. // _ = L(o2)[o]; // warn Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("index", "int C<object>.this[object index]").WithLocation(13, 19) ); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_SetterArguments_NestedNullability() { var comp = CreateCompilation(@" public class C<T> { public int this[C<T> index] { get => throw null!; set => throw null!; } } class Program { static void M(object? o, object o2) { L(o)[L(o)] = 1; L(o)[L(o2)] = 2; // 1 L(o2)[L(o)] = 3; // 2 L(o2)[L(o2)] = 4; } static C<U> L<U>(U u) => null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,14): warning CS8620: Argument of type 'C<object>' cannot be used for parameter 'index' of type 'C<object?>' in 'int C<object?>.this[C<object?> index]' due to differences in the nullability of reference types. // L(o)[L(o2)] = 2; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "L(o2)").WithArguments("C<object>", "C<object?>", "index", "int C<object?>.this[C<object?> index]").WithLocation(11, 14), // (13,15): warning CS8620: Argument of type 'C<object?>' cannot be used for parameter 'index' of type 'C<object>' in 'int C<object>.this[C<object> index]' due to differences in the nullability of reference types. // L(o2)[L(o)] = 3; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "L(o)").WithArguments("C<object?>", "C<object>", "index", "int C<object>.this[C<object> index]").WithLocation(13, 15) ); } [Fact, WorkItem(33289, "https://github.com/dotnet/roslyn/issues/33289")] public void ConditionalReceiver() { var comp = CreateCompilation(@" public class Container<T> { public T Field = default!; } class C { static void M(string? s) { var x = Create(s); _ = x /*T:Container<string?>?*/; x?.Field.ToString(); // 1 } public static Container<U>? Create<U>(U u) => new Container<U>(); }", options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (13,11): warning CS8602: Dereference of a possibly null reference. // x?.Field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, ".Field").WithLocation(13, 11) ); } [Fact, WorkItem(28792, "https://github.com/dotnet/roslyn/issues/28792")] public void ConditionalReceiver_Verify28792() { var comp = CreateNullableCompilation(@" class C { void M<T>(T t) => t?.ToString(); }"); comp.VerifyDiagnostics(); } [Fact, WorkItem(33289, "https://github.com/dotnet/roslyn/issues/33289")] public void ConditionalReceiver_Chained() { var comp = CreateCompilation(@" public class Container<T> { public T Field = default!; } class C { static void M(string? s) { var x = Create(s); if (x is null) return; _ = x /*T:Container<string?>!*/; x?.Field.ToString(); // 1 x = Create(s); if (x is null) return; x.Field?.ToString(); } public static Container<U>? Create<U>(U u) => new Container<U>(); }", options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (14,11): warning CS8602: Dereference of a possibly null reference. // x?.Field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, ".Field").WithLocation(14, 11) ); } [Fact, WorkItem(33289, "https://github.com/dotnet/roslyn/issues/33289")] public void ConditionalReceiver_Chained_Inversed() { var comp = CreateCompilation(@" public class Container<T> { public T Field = default!; } class C { static void M(string s) { var x = Create(s); _ = x /*T:Container<string!>?*/; x?.Field.ToString(); x = Create(s); x.Field?.ToString(); // 1 } public static Container<U>? Create<U>(U u) => new Container<U>(); }", options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (16,9): warning CS8602: Dereference of a possibly null reference. // x.Field?.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 9) ); } [Fact, WorkItem(33289, "https://github.com/dotnet/roslyn/issues/33289")] public void ConditionalReceiver_Nested() { var comp = CreateCompilation(@" public class Container<T> { public T Field = default!; } class C { static void M(string? s1, string s2) { var x = Create(s1); var y = Create(s2); x?.Field /*1*/ .Extension(y?.Field.ToString()); } public static Container<U>? Create<U>(U u) => new Container<U>(); } public static class Extensions { public static void Extension(this string s, object? o) => throw null!; }", options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (13,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Extensions.Extension(string s, object? o)'. // x?.Field /*1*/ Diagnostic(ErrorCode.WRN_NullReferenceArgument, ".Field").WithArguments("s", "void Extensions.Extension(string s, object? o)").WithLocation(13, 11) ); } [Fact, WorkItem(33289, "https://github.com/dotnet/roslyn/issues/33289")] public void ConditionalReceiver_MiscTypes() { var comp = CreateCompilation(@" public class Container<T> { public T M() => default!; } class C { static void M<T>(int i, Missing m, string s, T t) { Create(i)?.M().ToString(); Create(m)?.M().ToString(); Create(s)?.M().ToString(); Create(t)?.M().ToString(); // 1 } public static Container<U>? Create<U>(U u) => new Container<U>(); }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,29): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // static void M<T>(int i, Missing m, string s, T t) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(8, 29), // (13,19): warning CS8602: Dereference of a possibly null reference. // Create(t)?.M().ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, ".M()").WithLocation(13, 19) ); } [Fact, WorkItem(26810, "https://github.com/dotnet/roslyn/issues/26810")] public void LockStatement() { var comp = CreateCompilation(@" class C { void F(object? maybeNull, object nonNull, Missing? annotatedMissing, Missing unannotatedMissing) { lock (maybeNull) { } lock (nonNull) { } lock (annotatedMissing) { } lock (unannotatedMissing) { } } #nullable disable void F(object oblivious, Missing obliviousMissing) #nullable enable { lock (oblivious) { } lock (obliviousMissing) { } } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,47): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // void F(object? maybeNull, object nonNull, Missing? annotatedMissing, Missing unannotatedMissing) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(4, 47), // (4,74): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // void F(object? maybeNull, object nonNull, Missing? annotatedMissing, Missing unannotatedMissing) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(4, 74), // (6,15): warning CS8602: Dereference of a possibly null reference. // lock (maybeNull) { } Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "maybeNull").WithLocation(6, 15), // (8,15): error CS0185: 'Missing?' is not a reference type as required by the lock statement // lock (annotatedMissing) { } Diagnostic(ErrorCode.ERR_LockNeedsReference, "annotatedMissing").WithArguments("Missing?").WithLocation(8, 15), // (12,30): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // void F(object oblivious, Missing obliviousMissing) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(12, 30) ); } [Fact, WorkItem(33537, "https://github.com/dotnet/roslyn/issues/33537")] public void SuppressOnNullLiteralInAs() { var comp = CreateCompilation(@" class C { public static void Main() { var x = null! as object; } }"); comp.VerifyDiagnostics(); } [Fact, WorkItem(26654, "https://github.com/dotnet/roslyn/issues/26654")] [WorkItem(27522, "https://github.com/dotnet/roslyn/issues/27522")] public void SuppressNullableWarning_DeclarationExpression() { var source = @" public class C { public void M(out string? x) => throw null!; public void M2() { M(out string y!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // We don't allow suppressions on out-variable-declarations at this point (LDM 2/13/2019) comp.VerifyDiagnostics( // (7,23): error CS1003: Syntax error, ',' expected // M(out string y!); Diagnostic(ErrorCode.ERR_SyntaxError, "!").WithArguments(",", "!").WithLocation(7, 23), // (7,24): error CS1525: Invalid expression term ')' // M(out string y!); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(7, 24) ); } [Fact, WorkItem(26654, "https://github.com/dotnet/roslyn/issues/26654")] public void SuppressNullableWarning_LocalDeclarationAndAssignmentTarget() { var source = @" public class C { public void M2() { object y! = null; object y2; y2! = null; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // We don't allow suppressions in those positions at this point (LDM 2/13/2019) comp.VerifyDiagnostics( // (6,16): warning CS0168: The variable 'y' is declared but never used // object y! = null; Diagnostic(ErrorCode.WRN_UnreferencedVar, "y").WithArguments("y").WithLocation(6, 16), // (6,17): error CS1002: ; expected // object y! = null; Diagnostic(ErrorCode.ERR_SemicolonExpected, "!").WithLocation(6, 17), // (6,19): error CS1525: Invalid expression term '=' // object y! = null; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(6, 19), // (7,16): warning CS0219: The variable 'y2' is assigned but its value is never used // object y2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y2").WithArguments("y2").WithLocation(7, 16), // (8,9): error CS8598: The suppression operator is not allowed in this context // y2! = null; Diagnostic(ErrorCode.ERR_IllegalSuppression, "y2").WithLocation(8, 9), // (8,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // y2! = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 15) ); } [Fact] [WorkItem(788968, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/788968")] public void MissingMethodOnTupleLiteral() { var source = @" #nullable enable class C { void M() { (0, (string?)null).Missing(); _ = (0, (string?)null).Missing; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,28): error CS1061: '(int, string)' does not contain a definition for 'Missing' and no accessible extension method 'Missing' accepting a first argument of type '(int, string)' could be found (are you missing a using directive or an assembly reference?) // (0, (string?)null).Missing(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Missing").WithArguments("(int, string)", "Missing").WithLocation(7, 28), // (8,32): error CS1061: '(int, string)' does not contain a definition for 'Missing' and no accessible extension method 'Missing' accepting a first argument of type '(int, string)' could be found (are you missing a using directive or an assembly reference?) // _ = (0, (string?)null).Missing; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Missing").WithArguments("(int, string)", "Missing").WithLocation(8, 32) ); } [Fact, WorkItem(41520, "https://github.com/dotnet/roslyn/issues/41520")] public void WarnInsideTupleLiteral() { var source = @" class C { (int, int) M(string? s) { return (s.Length, 1); } } "; var compilation = CreateNullableCompilation(source); compilation.VerifyDiagnostics( // (6,17): warning CS8602: Dereference of a possibly null reference. // return (s.Length, 1); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 17) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void SuppressNullableWarning_RefSpanReturn() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class C { ref Span<byte> M(bool b) { Span<byte> x = stackalloc byte[10]; ref Span<byte> y = ref x!; if (b) return ref y; // 1 else return ref y!; // 2 } ref Span<string> M2(ref Span<string?> x, bool b) { if (b) return ref x; // 3 else return ref x!; } }", options: WithNullable(TestOptions.ReleaseDll, NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (10,24): error CS8157: Cannot return 'y' by reference because it was initialized to a value that cannot be returned by reference // return ref y; // 1 Diagnostic(ErrorCode.ERR_RefReturnNonreturnableLocal, "y").WithArguments("y").WithLocation(10, 24), // (12,24): error CS8157: Cannot return 'y' by reference because it was initialized to a value that cannot be returned by reference // return ref y!; // 2 Diagnostic(ErrorCode.ERR_RefReturnNonreturnableLocal, "y").WithArguments("y").WithLocation(12, 24), // (17,24): warning CS8619: Nullability of reference types in value of type 'Span<string?>' doesn't match target type 'Span<string>'. // return ref x; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("System.Span<string?>", "System.Span<string>").WithLocation(17, 24) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void SuppressNullableWarning_RefReassignment() { var comp = CreateCompilation(@" class C { void M() { ref string x = ref NullableRef(); // 1 ref string x2 = ref x; // 2 ref string x3 = ref x!; ref string y = ref NullableRef()!; ref string y2 = ref y; ref string y3 = ref y!; } ref string? NullableRef() => throw null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,28): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // ref string x = ref NullableRef(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "NullableRef()").WithArguments("string?", "string").WithLocation(6, 28), // (7,29): warning CS8601: Possible null reference assignment. // ref string x2 = ref x; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(7, 29) ); } [Fact] public void SuppressNullableWarning_This() { var comp = CreateCompilation(@" class C { void M() { this!.M(); } }", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void SuppressNullableWarning_UnaryOperator() { var comp = CreateCompilation(@" class C { void M(C? y) { y++; y!++; y--; } public static C operator++(C x) => throw null!; public static C operator--(C? x) => throw null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8604: Possible null reference argument for parameter 'x' in 'C C.operator ++(C x)'. // y++; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "C C.operator ++(C x)").WithLocation(6, 9) ); } [Fact, WorkItem(30151, "https://github.com/dotnet/roslyn/issues/30151")] public void SuppressNullableWarning_WholeArrayInitializer() { var comp = CreateCompilationWithMscorlibAndSpan(@" class C { unsafe void M() { string[] s = new[] { null, string.Empty }; // expecting a warning string[] s2 = (new[] { null, string.Empty })!; int* s3 = (stackalloc[] { 1 })!; System.Span<string> s4 = (stackalloc[] { null, string.Empty })!; } }", options: TestOptions.UnsafeDebugDll); // Missing warning // Need to confirm whether this suppression should be allowed or be effective // If so, we need to verify the semantic model // Tracked by https://github.com/dotnet/roslyn/issues/30151 comp.VerifyDiagnostics( // (8,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'int*' is not possible. // int* s3 = (stackalloc[] { 1 })!; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1 }").WithArguments("int", "int*").WithLocation(8, 20), // (9,35): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // System.Span<string> s4 = (stackalloc[] { null, string.Empty })!; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { null, string.Empty }").WithArguments("string").WithLocation(9, 35)); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_NullCoalescingAssignment() { var comp = CreateCompilation(@" class C { void M(int? i, int i2, dynamic d) { i! ??= i2; // 1 i ??= i2!; i! ??= d; // 2 i ??= d!; } void M(string? s, string s2, dynamic d) { s! ??= s2; // 3 s ??= s2!; s! ??= d; // 4 s ??= d!; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): error CS8598: The suppression operator is not allowed in this context // i! ??= i2; // 1 Diagnostic(ErrorCode.ERR_IllegalSuppression, "i").WithLocation(6, 9), // (8,9): error CS8598: The suppression operator is not allowed in this context // i! ??= d; // 2 Diagnostic(ErrorCode.ERR_IllegalSuppression, "i").WithLocation(8, 9), // (13,9): error CS8598: The suppression operator is not allowed in this context // s! ??= s2; // 3 Diagnostic(ErrorCode.ERR_IllegalSuppression, "s").WithLocation(13, 9), // (15,9): error CS8598: The suppression operator is not allowed in this context // s! ??= d; // 4 Diagnostic(ErrorCode.ERR_IllegalSuppression, "s").WithLocation(15, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_ExpressionTree() { var comp = CreateCompilation(@" using System; using System.Linq.Expressions; class C { void M() { string x = null; Expression<Func<string>> e = () => x!; Expression<Func<string>> e2 = (() => x)!; Expression<Func<Func<string>>> e3 = () => M2!; } string M2() => throw null!; }"); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_QueryReceiver() { string source = @" using System; namespace NS { } static class C { static void Main() { _ = from x in null! select x; _ = from x in default! select x; _ = from x in (y => y)! select x; _ = from x in NS! select x; _ = from x in Main! select x; } static object Select(this object x, Func<int, int> y) { return null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,29): error CS0186: Use of null is not valid in this context // _ = from x in null! select x; Diagnostic(ErrorCode.ERR_NullNotValid, "select x").WithLocation(8, 29), // (9,23): error CS8716: There is no target type for the default literal. // _ = from x in default! select x; Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(9, 23), // (10,33): error CS1936: Could not find an implementation of the query pattern for source type 'anonymous method'. 'Select' not found. // _ = from x in (y => y)! select x; Diagnostic(ErrorCode.ERR_QueryNoProvider, "select x").WithArguments("anonymous method", "Select").WithLocation(10, 33), // (11,23): error CS8598: The suppression operator is not allowed in this context // _ = from x in NS! select x; Diagnostic(ErrorCode.ERR_IllegalSuppression, "NS").WithLocation(11, 23), // (11,23): error CS0119: 'NS' is a namespace, which is not valid in the given context // _ = from x in NS! select x; Diagnostic(ErrorCode.ERR_BadSKunknown, "NS").WithArguments("NS", "namespace").WithLocation(11, 23), // (12,23): error CS0119: 'C.Main()' is a method, which is not valid in the given context // _ = from x in Main! select x; Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("C.Main()", "method").WithLocation(12, 23) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Query() { string source = @" using System.Linq; class C { static void M(System.Collections.Generic.IEnumerable<int> c) { var q = (from x in c select x)!; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_EventInCompoundAssignment() { var comp = CreateCompilation(@" class C { public event System.Action E; void M() { E! += () => {}; E(); } }"); comp.VerifyDiagnostics( // (7,9): error CS8598: The suppression operator is not allowed in this context // E! += () => {}; Diagnostic(ErrorCode.ERR_IllegalSuppression, "E").WithLocation(7, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void OperationsInNonDeclaringType() { var text = @" class C { public event System.Action E; } class D { void Method(ref System.Action a, C c) { c.E! = a; //CS0070 c.E! += a; a = c.E!; //CS0070 Method(ref c.E!, c); //CS0070 c.E!.Invoke(); //CS0070 bool b1 = c.E! is System.Action; //CS0070 c.E!++; //CS0070 c.E! |= true; //CS0070 } } "; CreateCompilation(text).VerifyDiagnostics( // (11,11): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // c.E! = a; //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(11, 11), // (12,9): error CS8598: The suppression operator is not allowed in this context // c.E! += a; Diagnostic(ErrorCode.ERR_IllegalSuppression, "c.E").WithLocation(12, 9), // (13,15): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // a = c.E!; //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(13, 15), // (14,22): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // Method(ref c.E!, c); //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(14, 22), // (15,11): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // c.E!.Invoke(); //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(15, 11), // (16,21): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // bool b1 = c.E! is System.Action; //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(16, 21), // (17,11): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // c.E!++; //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(17, 11), // (18,9): error CS8598: The suppression operator is not allowed in this context // c.E! |= true; //CS0070 Diagnostic(ErrorCode.ERR_IllegalSuppression, "c.E").WithLocation(18, 9), // (18,11): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // c.E! |= true; //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(18, 11) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Fixed() { var text = @" public class MyClass { int field = 0; unsafe public void Main() { int i = 45; fixed (int *j = &(i!)) { } fixed (int *k = &(this!.field)) { } int[] a = new int[] {1,2,3}; fixed (int *b = a!) { fixed (int *c = b!) { } } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int *j = &(i!)) { } Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&(i!)").WithLocation(8, 25), // (8,27): error CS8598: The suppression operator is not allowed in this context // fixed (int *j = &(i!)) { } Diagnostic(ErrorCode.ERR_IllegalSuppression, "i").WithLocation(8, 27), // (14,29): error CS8385: The given expression cannot be used in a fixed statement // fixed (int *c = b!) { } Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "b").WithLocation(14, 29) ); } [Fact, WorkItem(31748, "https://github.com/dotnet/roslyn/issues/31748")] public void NullableRangeIndexer() { var text = @" #nullable enable class Program { void M(int[] x, string m) { var y = x[1..3]; var z = m[1..3]; } }" + TestSources.GetSubArray; CreateCompilationWithIndexAndRange(text).VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MemberAccess() { var comp = CreateCompilation(@" namespace NS { public static class C { public static void M() { _ = null!.field; // 1 _ = default!.field; // 2 _ = NS!.C.field; // 3 _ = NS.C!.field; // 4 _ = nameof(C!.M); // 5 _ = nameof(C.M!); // 6 _ = nameof(missing!); // 7 } } public class Base { public virtual void M() { } } public class D : Base { public override void M() { _ = this!.ToString(); // 8 _ = base!.ToString(); // 9 } } }"); // Like cast, suppressions are allowed on `this`, but not on `base` comp.VerifyDiagnostics( // (8,17): error CS0023: Operator '.' cannot be applied to operand of type '<null>' // _ = null!.field; // 1 Diagnostic(ErrorCode.ERR_BadUnaryOp, "null!.field").WithArguments(".", "<null>").WithLocation(8, 17), // (9,17): error CS8716: There is no target type for the default literal. // _ = default!.field; // 2 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(9, 17), // (10,17): error CS8598: The suppression operator is not allowed in this context // _ = NS!.C.field; // 3 Diagnostic(ErrorCode.ERR_IllegalSuppression, "NS").WithLocation(10, 17), // (10,23): error CS0117: 'C' does not contain a definition for 'field' // _ = NS!.C.field; // 3 Diagnostic(ErrorCode.ERR_NoSuchMember, "field").WithArguments("NS.C", "field").WithLocation(10, 23), // (11,17): error CS8598: The suppression operator is not allowed in this context // _ = NS.C!.field; // 4 Diagnostic(ErrorCode.ERR_IllegalSuppression, "NS.C").WithLocation(11, 17), // (11,23): error CS0117: 'C' does not contain a definition for 'field' // _ = NS.C!.field; // 4 Diagnostic(ErrorCode.ERR_NoSuchMember, "field").WithArguments("NS.C", "field").WithLocation(11, 23), // (12,24): error CS8598: The suppression operator is not allowed in this context // _ = nameof(C!.M); // 5 Diagnostic(ErrorCode.ERR_IllegalSuppression, "C").WithLocation(12, 24), // (12,24): error CS8082: Sub-expression cannot be used in an argument to nameof. // _ = nameof(C!.M); // 5 Diagnostic(ErrorCode.ERR_SubexpressionNotInNameof, "C!").WithLocation(12, 24), // (13,24): error CS8081: Expression does not have a name. // _ = nameof(C.M!); // 6 Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M!").WithLocation(13, 24), // (14,24): error CS0103: The name 'missing' does not exist in the current context // _ = nameof(missing!); // 7 Diagnostic(ErrorCode.ERR_NameNotInContext, "missing").WithArguments("missing").WithLocation(14, 24), // (23,17): error CS0175: Use of keyword 'base' is not valid in this context // _ = base!.ToString(); // 9 Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(23, 17) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SymbolInfoForMethodGroup03() { var source = @" public class A { public static void M(A a) { _ = nameof(a.Extension!); } } public static class X1 { public static string Extension(this A a) { return null; } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (6,20): error CS8081: Expression does not have a name. // _ = nameof(a.Extension!); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "a.Extension!").WithLocation(6, 20) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_StringInterpolation() { var source = @" public class C { public static void Main() { M(""world"", null); } public static void M(string x, string? y) { System.IFormattable z = $""hello ""!; System.IFormattable z2 = $""{x} {y} {y!}""!; System.Console.Write(z); System.Console.Write(z2); } }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello world"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First(); Assert.Equal(@"$""hello ""!", suppression.ToString()); VerifyTypeInfo(model, suppression, "System.String", "System.IFormattable"); var interpolated = suppression.Operand; Assert.Equal(@"$""hello """, interpolated.ToString()); VerifyTypeInfo(model, interpolated, "System.String", "System.IFormattable"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_StringInterpolation_ExplicitCast() { var source = @" public class C { public static void Main() { M(""world"", null); } public static void M(string x, string? y) { var z = (System.IFormattable)($""hello ""!); var z2 = (System.IFormattable)($""{x} {y} {y!}""!); System.Console.Write(z); System.Console.Write(z2); } }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello world"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First(); Assert.Equal(@"$""hello ""!", suppression.ToString()); VerifyTypeInfo(model, suppression, "System.String", "System.String"); var interpolated = suppression.Operand; Assert.Equal(@"$""hello """, interpolated.ToString()); VerifyTypeInfo(model, interpolated, "System.String", "System.String"); } private static void VerifyTypeInfo(SemanticModel model, ExpressionSyntax expression, string expectedType, string expectedConvertedType) { var type = model.GetTypeInfoAndVerifyIOperation(expression); if (expectedType is null) { Assert.Null(type.Type); } else { var actualType = type.Type.ToTestDisplayString(); Assert.True(expectedType == actualType, $"Unexpected TypeInfo.Type '{actualType}'"); } if (expectedConvertedType is null) { Assert.Null(type.ConvertedType); } else { var actualConvertedType = type.ConvertedType.ToTestDisplayString(); Assert.True(expectedConvertedType == actualConvertedType, $"Unexpected TypeInfo.ConvertedType '{actualConvertedType}'"); } } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Default() { var source = @"class C { static void M() { string s = default!; s.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().Single(); VerifyTypeInfo(model, suppression, "System.String", "System.String"); var literal = suppression.Operand; VerifyTypeInfo(model, literal, "System.String", "System.String"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Constant() { var source = @"class C { static void M() { const int i = 3!; _ = i; const string s = null!; _ = s; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppressions = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().ToArray(); Assert.Equal(3, model.GetConstantValue(suppressions[0]).Value); Assert.Null(model.GetConstantValue(suppressions[1]).Value); } [Fact] public void SuppressNullableWarning_GetTypeInfo() { var source = @"class C<T> { void M(string s, string? s2, C<string> c, C<string?> c2) { _ = s!; _ = s2!; _ = c!; _ = c2!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppressions = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().ToArray(); var s = model.GetTypeInfoAndVerifyIOperation(suppressions[0]); Assert.Equal("System.String", s.Type.ToTestDisplayString()); Assert.Equal("System.String", s.ConvertedType.ToTestDisplayString()); Assert.Equal("System.String s", model.GetSymbolInfo(suppressions[0]).Symbol.ToTestDisplayString()); var s2 = model.GetTypeInfoAndVerifyIOperation(suppressions[1]); Assert.Equal("System.String", s2.Type.ToTestDisplayString()); Assert.Equal("System.String", s2.ConvertedType.ToTestDisplayString()); Assert.Equal("System.String? s2", model.GetSymbolInfo(suppressions[1]).Symbol.ToTestDisplayString()); var c = model.GetTypeInfoAndVerifyIOperation(suppressions[2]); Assert.Equal("C<System.String>", c.Type.ToTestDisplayString()); Assert.Equal("C<System.String>", c.ConvertedType.ToTestDisplayString()); Assert.Equal("C<System.String> c", model.GetSymbolInfo(suppressions[2]).Symbol.ToTestDisplayString()); var c2 = model.GetTypeInfoAndVerifyIOperation(suppressions[3]); Assert.Equal("C<System.String?>", c2.Type.ToTestDisplayString()); Assert.Equal("C<System.String?>", c2.ConvertedType.ToTestDisplayString()); Assert.Equal("C<System.String?> c2", model.GetSymbolInfo(suppressions[3]).Symbol.ToTestDisplayString()); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MethodGroupInNameof() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void M<T>() { _ = nameof(C.M<T>!); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,24): error CS0119: 'T' is a type, which is not valid in the given context // _ = nameof(C.M<T>!); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 24), // (6,27): error CS1525: Invalid expression term ')' // _ = nameof(C.M<T>!); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 27) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MethodGroup() { var source = @"class C { delegate string Copier(string s); static void Main() { Copier c = M2; Copier c2 = M2!; } static string? M2(string? s) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (6,20): warning CS8621: Nullability of reference types in return type of 'string? C.M2(string? s)' doesn't match the target delegate 'C.Copier'. // Copier c = M2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M2").WithArguments("string? C.M2(string? s)", "C.Copier").WithLocation(6, 20) ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First(); Assert.Equal("M2!", suppression.ToString()); VerifyTypeInfo(model, suppression, null, "C.Copier"); var methodGroup = suppression.Operand; VerifyTypeInfo(model, methodGroup, null, "C.Copier"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void InvalidUseOfMethodGroup() { var source = @"class A { internal object E() { return null; } private object F() { return null; } static void M(A a) { object o; a.E! += a.E!; // 1 if (a.E! != null) // 2 { M(a.E!); // 3 a.E!.ToString(); // 4 a.P!.ToString(); // 5 o = !(a.E!); // 6 o = a.E! ?? a.F!; // 7 } a.F! += a.F!; // 8 if (a.F! != null) // 9 { M(a.F!); // 10 a.F!.ToString(); // 11 o = !(a.F!); // 12 o = (o != null) ? a.E! : a.F!; // 13 } } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (8,9): error CS1656: Cannot assign to 'E' because it is a 'method group' // a.E! += a.E!; // 1 Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "a.E").WithArguments("E", "method group").WithLocation(8, 9), // (9,13): error CS0019: Operator '!=' cannot be applied to operands of type 'method group' and '<null>' // if (a.E! != null) // 2 Diagnostic(ErrorCode.ERR_BadBinaryOps, "a.E! != null").WithArguments("!=", "method group", "<null>").WithLocation(9, 13), // (11,15): error CS1503: Argument 1: cannot convert from 'method group' to 'A' // M(a.E!); // 3 Diagnostic(ErrorCode.ERR_BadArgType, "a.E").WithArguments("1", "method group", "A").WithLocation(11, 15), // (12,15): error CS0119: 'A.E()' is a method, which is not valid in the given context // a.E!.ToString(); // 4 Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("A.E()", "method").WithLocation(12, 15), // (13,15): error CS1061: 'A' does not contain a definition for 'P' and no accessible extension method 'P' accepting a first argument of type 'A' could be found (are you missing a using directive or an assembly reference?) // a.P!.ToString(); // 5 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("A", "P").WithLocation(13, 15), // (14,17): error CS0023: Operator '!' cannot be applied to operand of type 'method group' // o = !(a.E!); // 6 Diagnostic(ErrorCode.ERR_BadUnaryOp, "!(a.E!)").WithArguments("!", "method group").WithLocation(14, 17), // (15,17): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // o = a.E! ?? a.F!; // 7 Diagnostic(ErrorCode.ERR_BadBinaryOps, "a.E! ?? a.F!").WithArguments("??", "method group", "method group").WithLocation(15, 17), // (17,9): error CS1656: Cannot assign to 'F' because it is a 'method group' // a.F! += a.F!; // 8 Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "a.F").WithArguments("F", "method group").WithLocation(17, 9), // (18,13): error CS0019: Operator '!=' cannot be applied to operands of type 'method group' and '<null>' // if (a.F! != null) // 9 Diagnostic(ErrorCode.ERR_BadBinaryOps, "a.F! != null").WithArguments("!=", "method group", "<null>").WithLocation(18, 13), // (20,15): error CS1503: Argument 1: cannot convert from 'method group' to 'A' // M(a.F!); // 10 Diagnostic(ErrorCode.ERR_BadArgType, "a.F").WithArguments("1", "method group", "A").WithLocation(20, 15), // (21,15): error CS0119: 'A.F()' is a method, which is not valid in the given context // a.F!.ToString(); // 11 Diagnostic(ErrorCode.ERR_BadSKunknown, "F").WithArguments("A.F()", "method").WithLocation(21, 15), // (22,17): error CS0023: Operator '!' cannot be applied to operand of type 'method group' // o = !(a.F!); // 12 Diagnostic(ErrorCode.ERR_BadUnaryOp, "!(a.F!)").WithArguments("!", "method group").WithLocation(22, 17), // (23,33): error CS0428: Cannot convert method group 'E' to non-delegate type 'object'. Did you intend to invoke the method? // o = (o != null) ? a.E! : a.F!; // 13 Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "E").WithArguments("E", "object").WithLocation(23, 33), // (23,40): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // o = (o != null) ? a.E! : a.F!; // 13 Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(23, 40) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_AccessPropertyWithoutArguments() { string source1 = @" Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IB Property Value(Optional index As Object = Nothing) As Object End Interface "; var reference = BasicCompilationUtils.CompileToMetadata(source1); string source2 = @" class CIB : IB { public dynamic get_Value(object index = null) { return ""Test""; } public void set_Value(object index = null, object Value = null) { } } class Test { static void Main() { IB x = new CIB(); System.Console.WriteLine(x.Value!.Length); } } "; var compilation2 = CreateCompilation(source2, new[] { reference.WithEmbedInteropTypes(true), CSharpRef }, options: TestOptions.ReleaseExe); CompileAndVerify(compilation2, expectedOutput: @"4"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_CollectionInitializerProperty() { var source = @" public class C { public string P { get; set; } = null!; void M() { _ = new C() { P! = null }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,21): error CS1922: Cannot initialize type 'C' with a collection initializer because it does not implement 'System.Collections.IEnumerable' // _ = new C() { P! = null }; Diagnostic(ErrorCode.ERR_CollectionInitRequiresIEnumerable, "{ P! = null }").WithArguments("C").WithLocation(7, 21), // (7,23): error CS0747: Invalid initializer member declarator // _ = new C() { P! = null }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "P! = null").WithLocation(7, 23), // (7,23): error CS8598: The suppression operator is not allowed in this context // _ = new C() { P! = null }; Diagnostic(ErrorCode.ERR_IllegalSuppression, "P").WithLocation(7, 23), // (7,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // _ = new C() { P! = null }; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 28) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_InInvocation() { var source = @" public class C { public System.Action? field = null; void M() { this.M!(); nameof!(M); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): error CS8598: The suppression operator is not allowed in this context // this.M!(); Diagnostic(ErrorCode.ERR_IllegalSuppression, "this.M").WithLocation(7, 9), // (8,9): error CS0103: The name 'nameof' does not exist in the current context // nameof!(M); Diagnostic(ErrorCode.ERR_NameNotInContext, "nameof").WithArguments("nameof").WithLocation(8, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_InInvocation2() { var source = @" public class C { public System.Action? field = null; void M() { this!.field!(); } }"; var comp = CreateCompilationWithCSharp(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); CompileAndVerify(comp); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_InInvocationAndDynamic() { var source = @" public class C { void M() { dynamic? d = new object(); d.M!(); // 1 int z = d.y.z; d = null; d!.M(); d = null; int y = d.y; // 2 d = null; d.M!(); // 3 d += null; d += null!; } }"; // What warnings should we produce on dynamic? // Should `!` be allowed on members/invocations on dynamic? // See https://github.com/dotnet/roslyn/issues/32364 var comp = CreateCompilationWithCSharp(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): error CS8598: The suppression operator is not allowed in this context // d.M!(); // 1 Diagnostic(ErrorCode.ERR_IllegalSuppression, "d.M").WithLocation(7, 9), // (14,17): warning CS8602: Dereference of a possibly null reference. // int y = d.y; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d").WithLocation(14, 17), // (17,9): error CS8598: The suppression operator is not allowed in this context // d.M!(); // 3 Diagnostic(ErrorCode.ERR_IllegalSuppression, "d.M").WithLocation(17, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // d.M!(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d").WithLocation(17, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Stackalloc() { var comp = CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { System.Span<int> a3 = stackalloc[] { 1, 2, 3 }!; var x3 = true ? stackalloc[] { 1, 2, 3 }! : a3; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MethodGroup2() { var source = @"class C { delegate string? Copier(string? s); static void Main() { Copier c = M2; Copier c2 = M2!; } static string M2(string s) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (6,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'string C.M2(string s)' doesn't match the target delegate 'C.Copier'. // Copier c = M2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M2").WithArguments("s", "string C.M2(string s)", "C.Copier").WithLocation(6, 20) ); CompileAndVerify(comp); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Lambda() { var source = @"class C { delegate string Copier(string s); static void Main() { Copier c = (string? x) => { return null; }!; Copier c2 = (string? x) => { return null; }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (6,44): warning CS8603: Possible null reference return. // Copier c = (string? x) => { return null; }!; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 44), // (7,21): warning CS8622: Nullability of reference types in type of parameter 'x' of 'lambda expression' doesn't match the target delegate 'C.Copier'. // Copier c2 = (string? x) => { return null; }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(string? x) => { return null; }").WithArguments("x", "lambda expression", "C.Copier").WithLocation(7, 21), // (7,45): warning CS8603: Possible null reference return. // Copier c2 = (string? x) => { return null; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(7, 45) ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().Single(); Assert.Equal("(string? x) => { return null; }!", suppression.ToString()); VerifyTypeInfo(model, suppression, null, "C.Copier"); var lambda = suppression.Operand; Assert.Equal("(string? x) => { return null; }", lambda.ToString()); VerifyTypeInfo(model, lambda, null, "C.Copier"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Lambda_ExplicitCast() { var source = @"class C { delegate string Copier(string s); static void M() { var c = (Copier)((string? x) => { return null; }!); var c2 = (Copier)((string? x) => { return null; }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,50): warning CS8603: Possible null reference return. // var c = (Copier)((string? x) => { return null; }!); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 50), // (7,18): warning CS8622: Nullability of reference types in type of parameter 'x' of 'lambda expression' doesn't match the target delegate 'C.Copier'. // var c2 = (Copier)((string? x) => { return null; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(Copier)((string? x) => { return null; })").WithArguments("x", "lambda expression", "C.Copier").WithLocation(7, 18), // (7,51): warning CS8603: Possible null reference return. // var c2 = (Copier)((string? x) => { return null; }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(7, 51) ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().Single(); Assert.Equal("(string? x) => { return null; }!", suppression.ToString()); VerifyTypeInfo(model, suppression, null, "C.Copier"); var lambda = suppression.Operand; Assert.Equal("(string? x) => { return null; }", lambda.ToString()); VerifyTypeInfo(model, lambda, null, "C.Copier"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Lambda2() { var source = @"class C { delegate string? Copier(string? s); static void Main() { Copier c = (string x) => { return string.Empty; }!; Copier c2 = (string x) => { return string.Empty; }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (7,21): warning CS8622: Nullability of reference types in type of parameter 'x' of 'lambda expression' doesn't match the target delegate 'C.Copier'. // Copier c2 = (string x) => { return string.Empty; }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(string x) => { return string.Empty; }").WithArguments("x", "lambda expression", "C.Copier").WithLocation(7, 21) ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().Single(); Assert.Equal("(string x) => { return string.Empty; }!", suppression.ToString()); VerifyTypeInfo(model, suppression, null, "C.Copier"); var lambda = suppression.Operand; Assert.Equal("(string x) => { return string.Empty; }", lambda.ToString()); VerifyTypeInfo(model, lambda, null, "C.Copier"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Lambda2_ExplicitCast() { var source = @"class C { delegate string? Copier(string? s); static void Main() { var c = (Copier)((string x) => { return string.Empty; }!); var c2 = (Copier)((string x) => { return string.Empty; }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (7,18): warning CS8622: Nullability of reference types in type of parameter 'x' of 'lambda expression' doesn't match the target delegate 'C.Copier'. // var c2 = (Copier)((string x) => { return string.Empty; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(Copier)((string x) => { return string.Empty; })").WithArguments("x", "lambda expression", "C.Copier").WithLocation(7, 18) ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().Single(); Assert.Equal("(string x) => { return string.Empty; }!", suppression.ToString()); VerifyTypeInfo(model, suppression, null, "C.Copier"); var lambda = suppression.Operand; Assert.Equal("(string x) => { return string.Empty; }", lambda.ToString()); VerifyTypeInfo(model, lambda, null, "C.Copier"); } [Fact, WorkItem(32697, "https://github.com/dotnet/roslyn/issues/32697")] public void SuppressNullableWarning_LambdaInOverloadResolution() { var source = @"class C { static void Main(string? x) { var s = M(() => { return x; }); s /*T:string?*/ .ToString(); // 1 var s2 = M(() => { return x; }!); // suppressed s2 /*T:string?*/ .ToString(); // 2 var s3 = M(M2); s3 /*T:string?*/ .ToString(); // 3 var s4 = M(M2!); // suppressed s4 /*T:string?*/ .ToString(); // 4 } static T M<T>(System.Func<T> x) => throw null!; static string? M2() => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s /*T:string?*/ .ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // s2 /*T:string?*/ .ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(9, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // s3 /*T:string?*/ .ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(12, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // s4 /*T:string?*/ .ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(15, 9)); CompileAndVerify(comp); } [Fact, WorkItem(32698, "https://github.com/dotnet/roslyn/issues/32698")] public void SuppressNullableWarning_DelegateCreation() { var source = @"class C { static void Main() { _ = new System.Func<string, string>((string? x) => { return null; }!); _ = new System.Func<string?, string?>((string x) => { return string.Empty; }!); _ = new System.Func<string, string>(M1!); _ = new System.Func<string?, string?>(M2!); // without suppression _ = new System.Func<string, string>((string? x) => { return null; }); // 1 _ = new System.Func<string?, string?>((string x) => { return string.Empty; }); // 2 _ = new System.Func<string, string>(M1); // 3 _ = new System.Func<string?, string?>(M2); // 4 } static string? M1(string? x) => throw null!; static string M2(string x) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (5,69): warning CS8603: Possible null reference return. // _ = new System.Func<string, string>((string? x) => { return null; }!); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(5, 69), // (11,57): warning CS8622: Nullability of reference types in type of parameter 'x' of 'lambda expression' doesn't match the target delegate 'Func<string, string>'. // _ = new System.Func<string, string>((string? x) => { return null; }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("x", "lambda expression", "System.Func<string, string>").WithLocation(11, 57), // (11,69): warning CS8603: Possible null reference return. // _ = new System.Func<string, string>((string? x) => { return null; }); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(11, 69), // (12,58): warning CS8622: Nullability of reference types in type of parameter 'x' of 'lambda expression' doesn't match the target delegate 'Func<string?, string?>'. // _ = new System.Func<string?, string?>((string x) => { return string.Empty; }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("x", "lambda expression", "System.Func<string?, string?>").WithLocation(12, 58), // (13,45): warning CS8621: Nullability of reference types in return type of 'string? C.M1(string? x)' doesn't match the target delegate 'Func<string, string>'. // _ = new System.Func<string, string>(M1); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M1").WithArguments("string? C.M1(string? x)", "System.Func<string, string>").WithLocation(13, 45), // (14,47): warning CS8622: Nullability of reference types in type of parameter 'x' of 'string C.M2(string x)' doesn't match the target delegate 'Func<string?, string?>'. // _ = new System.Func<string?, string?>(M2); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M2").WithArguments("x", "string C.M2(string x)", "System.Func<string?, string?>").WithLocation(14, 47)); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First(); Assert.Equal(@"(string? x) => { return null; }!", suppression.ToString()); VerifyTypeInfo(model, suppression, null, "System.Func<System.String, System.String>"); VerifyTypeInfo(model, suppression.Operand, null, "System.Func<System.String, System.String>"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MethodGroupInOverloadResolution_NoReceiver() { var source = @"using System; using System.Collections.Generic; class A { class B { void F() { IEnumerable<string?> c = null!; c.S(G); c.S(G!); IEnumerable<string> c2 = null!; c2.S(G); c2.S(G2); } } object G(string s) => throw null!; object G2(string? s) => throw null!; } static class E { internal static IEnumerable<U> S<T, U>(this IEnumerable<T> c, Func<T, U> f) { throw new NotImplementedException(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,17): error CS0120: An object reference is required for the non-static field, method, or property 'A.G(string)' // c.S(G); Diagnostic(ErrorCode.ERR_ObjectRequired, "G").WithArguments("A.G(string)").WithLocation(10, 17), // (11,17): error CS0120: An object reference is required for the non-static field, method, or property 'A.G(string)' // c.S(G!); Diagnostic(ErrorCode.ERR_ObjectRequired, "G").WithArguments("A.G(string)").WithLocation(11, 17), // (14,18): error CS0120: An object reference is required for the non-static field, method, or property 'A.G(string)' // c2.S(G); Diagnostic(ErrorCode.ERR_ObjectRequired, "G").WithArguments("A.G(string)").WithLocation(14, 18), // (15,18): error CS0120: An object reference is required for the non-static field, method, or property 'A.G2(string?)' // c2.S(G2); Diagnostic(ErrorCode.ERR_ObjectRequired, "G2").WithArguments("A.G2(string?)").WithLocation(15, 18) ); } [Fact] [WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] [WorkItem(33635, "https://github.com/dotnet/roslyn/issues/33635")] public void SuppressNullableWarning_MethodGroupInOverloadResolution() { var source = @"using System; using System.Collections.Generic; class A { void M() { IEnumerable<string?> c = null!; c.S(G)/*T:System.Collections.Generic.IEnumerable<object!>!*/; // 1 c.S(G!)/*T:System.Collections.Generic.IEnumerable<object!>!*/; IEnumerable<string> c2 = null!; c2.S(G)/*T:System.Collections.Generic.IEnumerable<object!>!*/; c2.S(G2)/*T:System.Collections.Generic.IEnumerable<object!>!*/; } static object G(string s) => throw null!; static object G2(string? s) => throw null!; } static class E { internal static IEnumerable<U> S<T, U>(this IEnumerable<T> c, Func<T, U> f) { throw new NotImplementedException(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8622: Nullability of reference types in type of parameter 's' of 'object A.G(string s)' doesn't match the target delegate 'Func<string?, object>'. // c.S(G)/*T:IEnumerable<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "G").WithArguments("s", "object A.G(string s)", "System.Func<string?, object>").WithLocation(8, 13) ); comp.VerifyTypes(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void ErrorInLambdaArgumentList() { var source = @" class Program { public Program(string x) : this((() => x)!) { } }"; CreateCompilation(source).VerifyDiagnostics( // (4,38): error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type // public Program(string x) : this((() => x)!) { } Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => x").WithArguments("lambda expression", "string").WithLocation(4, 38) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void CS1113ERR_ValueTypeExtDelegate01() { var source = @"class C { public void M() { } } interface I { void M(); } enum E { } struct S { public void M() { } } static class SC { static void Test(C c, I i, E e, S s, double d) { System.Action cm = c.M!; // OK -- instance method System.Action cm1 = c.M1!; // OK -- extension method on ref type System.Action im = i.M!; // OK -- instance method System.Action im2 = i.M2!; // OK -- extension method on ref type System.Action em3 = e.M3!; // BAD -- extension method on value type System.Action sm = s.M!; // OK -- instance method System.Action sm4 = s.M4!; // BAD -- extension method on value type System.Action dm5 = d.M5!; // BAD -- extension method on value type } static void M1(this C c) { } static void M2(this I i) { } static void M3(this E e) { } static void M4(this S s) { } static void M5(this double d) { } }"; CreateCompilationWithMscorlib40(source, references: new[] { TestMetadata.Net40.SystemCore }).VerifyDiagnostics( // (24,29): error CS1113: Extension methods 'SC.M3(E)' defined on value type 'E' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "e.M3").WithArguments("SC.M3(E)", "E").WithLocation(24, 29), // (26,29): error CS1113: Extension methods 'SC.M4(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M4").WithArguments("SC.M4(S)", "S").WithLocation(26, 29), // (27,29): error CS1113: Extension methods 'SC.M5(double)' defined on value type 'double' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "d.M5").WithArguments("SC.M5(double)", "double").WithLocation(27, 29)); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void BugCodePlex_30_01() { string source1 = @" using System; class C { static void Main() { Goo(() => { return () => 0; ; }!); Goo(() => { return () => 0; }!); } static void Goo(Func<Func<short>> x) { Console.Write(1); } static void Goo(Func<Func<int>> x) { Console.Write(2); } } "; CompileAndVerify(source1, expectedOutput: @"22"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_AddressOfWithLambdaOrMethodGroup() { var source = @" unsafe class C { static void M() { _ = &(() => {}!); _ = &(M!); } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,15): error CS0211: Cannot take the address of the given expression // _ = &(() => {}!); Diagnostic(ErrorCode.ERR_InvalidAddrOp, "() => {}").WithLocation(6, 15), // (7,9): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = &(M!); Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(7, 9), // (7,15): error CS8598: The suppression operator is not allowed in this context // _ = &(M!); Diagnostic(ErrorCode.ERR_IllegalSuppression, "M").WithLocation(7, 15) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void SuppressNullableWarning_AddressOf() { var source = @" unsafe class C<T> { static void M(C<string> x) { C<string?>* y1 = &x; C<string?>* y2 = &x!; } }"; var comp = CreateCompilation(source, options: WithNullable(TestOptions.UnsafeReleaseDll, NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (6,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C<string?>') // C<string?>* y1 = &x; Diagnostic(ErrorCode.ERR_ManagedAddr, "C<string?>*").WithArguments("C<string?>").WithLocation(6, 9), // (6,26): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C<string>') // C<string?>* y1 = &x; Diagnostic(ErrorCode.ERR_ManagedAddr, "&x").WithArguments("C<string>").WithLocation(6, 26), // (6,26): warning CS8619: Nullability of reference types in value of type 'C<string>*' doesn't match target type 'C<string?>*'. // C<string?>* y1 = &x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "&x").WithArguments("C<string>*", "C<string?>*").WithLocation(6, 26), // (7,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C<string?>') // C<string?>* y2 = &x!; Diagnostic(ErrorCode.ERR_ManagedAddr, "C<string?>*").WithArguments("C<string?>").WithLocation(7, 9), // (7,26): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C<string>') // C<string?>* y2 = &x!; Diagnostic(ErrorCode.ERR_ManagedAddr, "&x!").WithArguments("C<string>").WithLocation(7, 26), // (7,26): warning CS8619: Nullability of reference types in value of type 'C<string>*' doesn't match target type 'C<string?>*'. // C<string?>* y2 = &x!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "&x!").WithArguments("C<string>*", "C<string?>*").WithLocation(7, 26), // (7,27): error CS8598: The suppression operator is not allowed in this context // C<string?>* y2 = &x!; Diagnostic(ErrorCode.ERR_IllegalSuppression, "x").WithLocation(7, 27) ); } [Fact] public void SuppressNullableWarning_Invocation() { var source = @" class C { void M() { _ = nameof!(M); _ = typeof!(C); this.M!(); dynamic d = null!; d.M2!(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): error CS0103: The name 'nameof' does not exist in the current context // _ = nameof!(M); Diagnostic(ErrorCode.ERR_NameNotInContext, "nameof").WithArguments("nameof").WithLocation(6, 13), // (7,19): error CS1003: Syntax error, '(' expected // _ = typeof!(C); Diagnostic(ErrorCode.ERR_SyntaxError, "!").WithArguments("(", "!").WithLocation(7, 19), // (7,19): error CS1031: Type expected // _ = typeof!(C); Diagnostic(ErrorCode.ERR_TypeExpected, "!").WithLocation(7, 19), // (7,19): error CS1026: ) expected // _ = typeof!(C); Diagnostic(ErrorCode.ERR_CloseParenExpected, "!").WithLocation(7, 19), // (7,21): error CS0119: 'C' is a type, which is not valid in the given context // _ = typeof!(C); Diagnostic(ErrorCode.ERR_BadSKunknown, "C").WithArguments("C", "type").WithLocation(7, 21), // (8,9): error CS8598: The suppression operator is not allowed in this context // this.M!(); Diagnostic(ErrorCode.ERR_IllegalSuppression, "this.M").WithLocation(8, 9), // (10,9): error CS8598: The suppression operator is not allowed in this context // d.M2!(); Diagnostic(ErrorCode.ERR_IllegalSuppression, "d.M2").WithLocation(10, 9) ); } [Fact, WorkItem(31584, "https://github.com/dotnet/roslyn/issues/31584")] public void Verify31584() { var comp = CreateCompilation(@" using System; using System.Linq; class C { void M<T>(Func<T, bool>? predicate) { var items = Enumerable.Empty<T>(); if (predicate != null) items = items.Where(x => predicate(x)); } }", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(32463, "https://github.com/dotnet/roslyn/issues/32463")] public void Verify32463() { var comp = CreateCompilation(@" using System.Linq; class C { public void F(string? param) { if (param != null) _ = new[] { 0 }.Select(_ => param.Length); string? local = """"; if (local != null) _ = new[] { 0 }.Select(_ => local.Length); } }", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(32701, "https://github.com/dotnet/roslyn/issues/32701")] public void Verify32701() { var source = @" class C { static void M<T>(ref T t, dynamic? d) { t = d; // 1 } static void M2<T>(T t, dynamic? d) { t = d; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,13): warning CS8601: Possible null reference assignment. // t = d; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "d").WithLocation(6, 13)); comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8601: Possible null reference assignment. // t = d; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "d").WithLocation(6, 13), // (10,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // t = d; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "d").WithLocation(10, 13)); source = @" class C { static void M<T>(ref T? t, dynamic? d) { t = d; } static void M2<T>(T? t, dynamic? d) { t = d; } }"; comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(26696, "https://github.com/dotnet/roslyn/issues/26696")] public void Verify26696() { var source = @" interface I { object this[int i] { get; } } class C<T> : I { T this[int i] => throw null!; object I.this[int i] => this[i]!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefReturn() { var source = @" struct S<T> { ref S<string?> M(ref S<string> x) { return ref x; // 1 } ref S<string?> M2(ref S<string> x) { return ref x!; } } class C<T> { ref C<string>? M3(ref C<string> x) { return ref x; // 2 } ref C<string> M4(ref C<string>? x) { return ref x; // 3 } ref C<string>? M5(ref C<string> x) { return ref x!; } ref C<string> M6(ref C<string>? x) { return ref x!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,20): warning CS8619: Nullability of reference types in value of type 'S<string>' doesn't match target type 'S<string?>'. // return ref x; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("S<string>", "S<string?>").WithLocation(6, 20), // (17,20): warning CS8619: Nullability of reference types in value of type 'C<string>' doesn't match target type 'C<string>?'. // return ref x; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<string>", "C<string>?").WithLocation(17, 20), // (21,20): warning CS8619: Nullability of reference types in value of type 'C<string>?' doesn't match target type 'C<string>'. // return ref x; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<string>?", "C<string>").WithLocation(21, 20) ); } [Fact, WorkItem(33982, "https://github.com/dotnet/roslyn/issues/33982")] public void RefReturn_Lambda() { var comp = CreateCompilation(@" delegate ref V D<T, U, V>(ref T t, ref U u); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static V F<T, U, V>(D<T, U, V> d) => throw null!; void M(bool b) { F((ref object? x, ref object y) => { if (b) return ref x; return ref y; }); // 1 F((ref object? x, ref object y) => { if (b) return ref y; return ref x; }); // 2 F((ref I<object?> x, ref I<object> y) => { if (b) return ref x; return ref y; }); // 3 F((ref I<object?> x, ref I<object> y) => { if (b) return ref y; return ref x; }); // 4 F((ref IOut<object?> x, ref IOut<object> y) => { if (b) return ref x; return ref y; }); // 5 F((ref IOut<object?> x, ref IOut<object> y) => { if (b) return ref y; return ref x; }); // 6 F((ref IIn<object?> x, ref IIn<object> y) => { if (b) return ref x; return ref y; }); // 7 F((ref IIn<object?> x, ref IIn<object> y) => { if (b) return ref y; return ref x; }); // 8 } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,47): warning CS8619: Nullability of reference types in value of type 'object' doesn't match target type 'object?'. // { if (b) return ref x; return ref y; }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("object", "object?").WithLocation(12, 47), // (14,33): warning CS8619: Nullability of reference types in value of type 'object' doesn't match target type 'object?'. // { if (b) return ref y; return ref x; }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("object", "object?").WithLocation(14, 33), // (17,33): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // { if (b) return ref x; return ref y; }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object?>", "I<object>").WithLocation(17, 33), // (19,47): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // { if (b) return ref y; return ref x; }); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object?>", "I<object>").WithLocation(19, 47), // (22,47): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'IOut<object?>'. // { if (b) return ref x; return ref y; }); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("IOut<object>", "IOut<object?>").WithLocation(22, 47), // (24,33): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'IOut<object?>'. // { if (b) return ref y; return ref x; }); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("IOut<object>", "IOut<object?>").WithLocation(24, 33), // (27,33): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'IIn<object>'. // { if (b) return ref x; return ref y; }); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object?>", "IIn<object>").WithLocation(27, 33), // (29,47): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'IIn<object>'. // { if (b) return ref y; return ref x; }); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object?>", "IIn<object>").WithLocation(29, 47) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefReturn_State() { var source = @" class C { ref C M1(ref C? w) { return ref w; // 1 } ref C? M2(ref C w) { return ref w; // 2 } ref C M3(ref C w) { return ref w; } ref C? M4(ref C? w) { return ref w; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,20): warning CS8619: Nullability of reference types in value of type 'C?' doesn't match target type 'C'. // return ref w; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("C?", "C").WithLocation(6, 20), // (10,20): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'C?'. // return ref w; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("C", "C?").WithLocation(10, 20) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefAssignment() { var source = @" class C { void M1(C? x) { ref C y = ref x; // 1 y.ToString(); // 2 } void M2(C x) { ref C? y = ref x; // 3 y.ToString(); } void M3(C? x, C nonNull) { x = nonNull; ref C y = ref x; // 4 y.ToString(); y = null; // 5 } void M4(C x, C? nullable) { x = nullable; // 6 ref C? y = ref x; // 7 y.ToString(); // 8 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,23): warning CS8619: Nullability of reference types in value of type 'C?' doesn't match target type 'C'. // ref C y = ref x; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C?", "C").WithLocation(6, 23), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9), // (11,24): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'C?'. // ref C? y = ref x; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C", "C?").WithLocation(11, 24), // (17,23): warning CS8619: Nullability of reference types in value of type 'C?' doesn't match target type 'C'. // ref C y = ref x; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C?", "C").WithLocation(17, 23), // (19,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // y = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 13), // (23,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = nullable; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "nullable").WithLocation(23, 13), // (24,24): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'C?'. // ref C? y = ref x; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C", "C?").WithLocation(24, 24), // (25,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(25, 9) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefAssignment_WithSuppression() { var source = @" class C { void M1(C? x) { ref C y = ref x!; y.ToString(); } void M2(C x) { ref C? y = ref x!; y.ToString(); } void M3(C? x, C nonNull) { x = nonNull; ref C y = ref x!; y.ToString(); } void M4(C x, C? nullable) { x = nullable; // 1 ref C? y = ref x!; y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (22,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = nullable; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "nullable").WithLocation(22, 13) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefAssignment_Nested() { var source = @" struct S<T> { void M(ref S<string> x) { S<string?> y = default; ref S<string> y2 = ref y; // 1 y2 = ref y; // 2 y2 = ref y!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,32): warning CS8619: Nullability of reference types in value of type 'S<string?>' doesn't match target type 'S<string>'. // ref S<string> y2 = ref y; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("S<string?>", "S<string>").WithLocation(7, 32), // (8,18): warning CS8619: Nullability of reference types in value of type 'S<string?>' doesn't match target type 'S<string>'. // y2 = ref y; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("S<string?>", "S<string>").WithLocation(8, 18) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefAssignment_Foreach() { verify(variableType: "string?", itemType: "string", // (6,18): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // foreach (ref string? item in collection) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ref string?").WithArguments("string", "string?").WithLocation(6, 18)); verify("string", "string?", // (6,18): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // foreach (ref string item in collection) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ref string").WithArguments("string?", "string").WithLocation(6, 18), // (8,13): warning CS8602: Dereference of a possibly null reference. // item.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(8, 13)); verify("string", "string"); verify("string?", "string?", // (8,13): warning CS8602: Dereference of a possibly null reference. // item.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(8, 13)); verify("C<string?>", "C<string>", // (6,18): warning CS8619: Nullability of reference types in value of type 'C<string>' doesn't match target type 'C<string?>'. // foreach (ref C<string?> item in collection) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ref C<string?>").WithArguments("C<string>", "C<string?>").WithLocation(6, 18)); verify("C<string>", "C<string?>", // (6,18): warning CS8619: Nullability of reference types in value of type 'C<string?>' doesn't match target type 'C<string>'. // foreach (ref C<string> item in collection) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ref C<string>").WithArguments("C<string?>", "C<string>").WithLocation(6, 18)); verify("C<object?>", "C<dynamic>?", // (6,18): warning CS8619: Nullability of reference types in value of type 'C<dynamic>?' doesn't match target type 'C<object?>'. // foreach (ref C<object?> item in collection) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ref C<object?>").WithArguments("C<dynamic>?", "C<object?>").WithLocation(6, 18), // (8,13): warning CS8602: Dereference of a possibly null reference. // item.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(8, 13)); verify("C<object>", "C<dynamic>"); verify("var", "string"); verify("var", "string?", // (8,13): warning CS8602: Dereference of a possibly null reference. // item.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(8, 13)); verify("T", "T", // (8,13): warning CS8602: Dereference of a possibly null reference. // item.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(8, 13)); void verify(string variableType, string itemType, params DiagnosticDescription[] expected) { var source = @" class C<T> { void M(RefEnumerable collection) { foreach (ref VARTYPE item in collection) { item.ToString(); } } class RefEnumerable { public StructEnum GetEnumerator() => throw null!; public struct StructEnum { public ref ITEMTYPE Current => throw null!; public bool MoveNext() => throw null!; } } }"; var comp = CreateCompilation(source.Replace("VARTYPE", variableType).Replace("ITEMTYPE", itemType), options: WithNullableEnable()); comp.VerifyDiagnostics(expected); } } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefAssignment_Foreach_Nested() { verify(fieldType: "string?", // (9,13): warning CS8602: Dereference of a possibly null reference. // item.Field.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item.Field").WithLocation(9, 13)); verify(fieldType: "string", // (4,19): warning CS8618: Non-nullable field 'Field' is uninitialized. Consider declaring the field as nullable. // public string Field; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Field").WithArguments("field", "Field").WithLocation(4, 19)); void verify(string fieldType, params DiagnosticDescription[] expected) { var source = @" class C { public FIELDTYPE Field; void M(RefEnumerable collection) { foreach (ref C item in collection) { item.Field.ToString(); } } class RefEnumerable { public StructEnum GetEnumerator() => throw null!; public struct StructEnum { public ref C Current => throw null!; public bool MoveNext() => throw null!; } } }"; var comp = CreateCompilation(source.Replace("FIELDTYPE", fieldType), options: WithNullableEnable()); comp.VerifyDiagnostics(expected); } } [Fact] public void RefAssignment_Inferred() { var source = @" class C { void M1(C x) { ref var y = ref x; y = null; x.ToString(); y.ToString(); // 1 } void M2(C? x) { ref var y = ref x; y = null; x.ToString(); // 2 y.ToString(); // 3 } void M3(C? x) { ref var y = ref x; x.ToString(); // 4 y.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(17, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(23, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(24, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void TestLambdaWithError19() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { Ma(string.Empty, ((x, y) => x.ToString())!); Mb(string.Empty, ((x, y) => x.ToString())!); Mc(string.Empty, ((x, y) => x.ToString())!); } static void Ma<T>(T t, Expression<Action<T, T, int>> action) { } static void Mb<T>(T t, Expression<Action<T, T, int>> action) { } static void Mb<T>(T t, Action<T, T, int> action) { } static void Mc<T>(T t, Expression<Action<T, T, int>> action) { } static void Mc() { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfoAndVerifyIOperation(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_DelegateComparison() { var source = @" class C { static void M() { System.Func<int> x = null; _ = x == (() => 1)!; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'Func<int>' and 'lambda expression' // _ = x == (() => 1)!; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x == (() => 1)!").WithArguments("==", "System.Func<int>", "lambda expression").WithLocation(7, 13) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_ArgList() { var source = @" class C { static void M() { _ = __arglist!; M(__arglist(__arglist()!)); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0190: The __arglist construct is valid only within a variable argument method // _ = __arglist!; Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist").WithLocation(6, 13), // (7,21): error CS0226: An __arglist expression may only appear inside of a call or new expression // M(__arglist(__arglist()!)); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist()").WithLocation(7, 21) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void BadInvocationInLambda() { var src = @" using System; using System.Linq.Expressions; class C { Expression<Action<dynamic>> e = x => new object[](x); Expression<Action<dynamic>> e2 = x => new object[](x)!; }"; // Suppressed expression cannot be used as a statement var comp = CreateCompilationWithMscorlib40AndSystemCore(src); comp.VerifyDiagnostics( // (7,52): error CS1586: Array creation must have array size or array initializer // Expression<Action<dynamic>> e = x => new object[](x); Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(7, 52), // (8,43): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // Expression<Action<dynamic>> e2 = x => new object[](x)!; Diagnostic(ErrorCode.ERR_IllegalStatement, "new object[](x)!").WithLocation(8, 43), // (8,53): error CS1586: Array creation must have array size or array initializer // Expression<Action<dynamic>> e2 = x => new object[](x)!; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(8, 53) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_AsStatement() { var src = @" class C { void M2(string x) { x!; M2(x)!; } string M(string x) { x!; M(x)!; throw null!; } }"; // Suppressed expression cannot be used as a statement var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,9): error CS8598: The suppression operator is not allowed in this context // x!; Diagnostic(ErrorCode.ERR_IllegalSuppression, "x").WithLocation(6, 9), // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x!; Diagnostic(ErrorCode.ERR_IllegalStatement, "x!").WithLocation(6, 9), // (7,9): error CS8598: The suppression operator is not allowed in this context // M2(x)!; Diagnostic(ErrorCode.ERR_IllegalSuppression, "M2(x)").WithLocation(7, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // M2(x)!; Diagnostic(ErrorCode.ERR_IllegalStatement, "M2(x)!").WithLocation(7, 9), // (11,9): error CS8598: The suppression operator is not allowed in this context // x!; Diagnostic(ErrorCode.ERR_IllegalSuppression, "x").WithLocation(11, 9), // (11,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x!; Diagnostic(ErrorCode.ERR_IllegalStatement, "x!").WithLocation(11, 9), // (12,9): error CS8598: The suppression operator is not allowed in this context // M(x)!; Diagnostic(ErrorCode.ERR_IllegalSuppression, "M(x)").WithLocation(12, 9), // (12,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // M(x)!; Diagnostic(ErrorCode.ERR_IllegalStatement, "M(x)!").WithLocation(12, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_VoidInvocation() { var src = @" class C { void M() { _ = M()!; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = M()!; Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void CS0023ERR_BadUnaryOp_lambdaExpression() { var text = @" class X { static void Main() { System.Func<int, int> f = (arg => { arg = 2; return arg; } !).ToString(); var x = (delegate { } !).ToString(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,35): error CS0023: Operator '.' cannot be applied to operand of type 'lambda expression' // System.Func<int, int> f = (arg => { arg = 2; return arg; } !).ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(arg => { arg = 2; return arg; } !).ToString").WithArguments(".", "lambda expression").WithLocation(6, 35), // (8,17): error CS0023: Operator '.' cannot be applied to operand of type 'anonymous method' // var x = (delegate { } !).ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(delegate { } !).ToString").WithArguments(".", "anonymous method").WithLocation(8, 17) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void ConditionalMemberAccess001() { var text = @" class Program { static void Main(string[] args) { var x4 = (()=> { return 1; } !) ?.ToString(); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (6,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression' // var x4 = (()=> { return 1; } !) ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(()=> { return 1; } !) ?.ToString()").WithArguments("?", "lambda expression").WithLocation(6, 18), // (6,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression' // var x4 = (()=> { return 1; } !) ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(()=> { return 1; } !) ?.ToString()").WithArguments("?", "lambda expression").WithLocation(6, 18) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void DynamicCollectionInitializer_Errors() { string source = @" using System; unsafe class C { public dynamic X; public static int* ptr = null; static void M() { var c = new C { X = { M!, ptr!, () => {}!, default(TypedReference)!, M()!, __arglist } }; } } "; // Should `!` be disallowed on arguments to dynamic? // See https://github.com/dotnet/roslyn/issues/32364 CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (15,17): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? // M!, Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, "M").WithLocation(15, 17), // (16,17): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. // ptr!, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "ptr").WithArguments("int*").WithLocation(16, 17), // (17,17): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // () => {}!, Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "() => {}").WithLocation(17, 17), // (18,17): error CS1978: Cannot use an expression of type 'TypedReference' as an argument to a dynamically dispatched operation. // default(TypedReference)!, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "default(TypedReference)").WithArguments("System.TypedReference").WithLocation(18, 17), // (19,17): error CS1978: Cannot use an expression of type 'void' as an argument to a dynamically dispatched operation. // M()!, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "M()").WithArguments("void").WithLocation(19, 17), // (20,17): error CS0190: The __arglist construct is valid only within a variable argument method // __arglist Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist").WithLocation(20, 17), // (20,17): error CS1978: Cannot use an expression of type 'RuntimeArgumentHandle' as an argument to a dynamically dispatched operation. // __arglist Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(20, 17) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void TestNullCoalesceWithMethodGroup() { var source = @" using System; class Program { static void Main() { Action a = Main! ?? Main; Action a2 = Main ?? Main!; } } "; CreateCompilation(source).VerifyDiagnostics( // (8,20): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // Action a = Main! ?? Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main! ?? Main").WithArguments("??", "method group", "method group").WithLocation(8, 20), // (9,21): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // Action a2 = Main ?? Main!; Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main ?? Main!").WithArguments("??", "method group", "method group").WithLocation(9, 21) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_IsAsOperatorWithBadSuppressedExpression() { var source = @" class C { void M() { _ = (() => {}!) is null; // 1 _ = (M!) is null; // 2 _ = (null, null)! is object; // 3 _ = null! is object; // 4 _ = default! is object; // 5 _ = (() => {}!) as object; // 6 _ = (M!) as object; // 7 _ = (null, null)! as object; // 8 _ = null! as object; // ok _ = default! as string; // 10 } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // _ = (() => {}!) is null; // 1 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(() => {}!) is null").WithLocation(6, 13), // (7,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // _ = (M!) is null; // 2 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(M!) is null").WithLocation(7, 13), // (8,13): error CS0023: Operator 'is' cannot be applied to operand of type '(<null>, <null>)' // _ = (null, null)! is object; // 3 Diagnostic(ErrorCode.ERR_BadUnaryOp, "(null, null)! is object").WithArguments("is", "(<null>, <null>)").WithLocation(8, 13), // (9,13): warning CS0184: The given expression is never of the provided ('object') type // _ = null! is object; // 4 Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null! is object").WithArguments("object").WithLocation(9, 13), // (10,13): error CS8716: There is no target type for the default literal. // _ = default! is object; // 5 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(10, 13), // (12,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // _ = (() => {}!) as object; // 6 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(() => {}!) as object").WithLocation(12, 13), // (13,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // _ = (M!) as object; // 7 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(M!) as object").WithLocation(13, 13), // (14,13): error CS8307: The first operand of an 'as' operator may not be a tuple literal without a natural type. // _ = (null, null)! as object; // 8 Diagnostic(ErrorCode.ERR_TypelessTupleInAs, "(null, null)! as object").WithLocation(14, 13), // (16,13): error CS8716: There is no target type for the default literal. // _ = default! as string; // 10 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(16, 13) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void ImplicitDelegateCreationWithIncompleteLambda() { var source = @" using System; class C { public void F() { Action<int> x = (i => i.)! } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,33): error CS1001: Identifier expected // Action<int> x = (i => i.)! Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(7, 33), // (7,35): error CS1002: ; expected // Action<int> x = (i => i.)! Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 35), // (7,31): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // Action<int> x = (i => i.)! Diagnostic(ErrorCode.ERR_IllegalStatement, "i.").WithLocation(7, 31) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lambda = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single(); var param = lambda.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single(); var symbol1 = model.GetDeclaredSymbol(param); Assert.Equal("System.Int32 i", symbol1.ToTestDisplayString()); var id = lambda.DescendantNodes().First(n => n.IsKind(SyntaxKind.IdentifierName)); var symbol2 = model.GetSymbolInfo(id).Symbol; Assert.Equal("System.Int32 i", symbol2.ToTestDisplayString()); Assert.Same(symbol1, symbol2); } [Fact, WorkItem(32179, "https://github.com/dotnet/roslyn/issues/32179")] public void SuppressNullableWarning_DefaultStruct() { var source = @"public struct S { public string field; } public class C { public S field; void M() { S s = default; // assigns null to S.field _ = s; _ = new C(); // assigns null to C.S.field } }"; // We should probably warn for such scenarios (either in the definition of S, or in the usage of S) // Tracked by https://github.com/dotnet/roslyn/issues/32179 var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_ThrowNull() { var source = @"class C { void M() { throw null!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_ThrowExpression() { var source = @"class C { void M() { (throw null!)!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (throw null!)!; Diagnostic(ErrorCode.ERR_IllegalStatement, "(throw null!)!").WithLocation(5, 9), // (5,10): error CS8115: A throw expression is not allowed in this context. // (throw null!)!; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(5, 10) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_IsNull() { var source = @"class C { bool M(object o) { return o is null!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,21): error CS8598: The suppression operator is not allowed in this context // return o is null!; Diagnostic(ErrorCode.ERR_IllegalSuppression, "null!").WithLocation(5, 21)); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MiscNull() { var source = @" using System.Linq.Expressions; class C { void M<T>(object o, int? i) { _ = null is object; // 1 _ = null! is object; // 2 int i2 = null!; // 3 var i3 = (int)null!; // 4 T t = null!; // 5 var t2 = (T)null!; // 6 _ = null == null!; _ = (null!, null) == (null, null!); (null)++; // 9 (null!)++; // 10 _ = !null; // 11 _ = !(null!); // 12 Expression<System.Func<object>> testExpr = () => null! ?? ""hello""; // 13 _ = o == null; _ = o == null!; // 14 _ = null ?? o; _ = null! ?? o; _ = i == null; _ = i == null!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS0184: The given expression is never of the provided ('object') type // _ = null is object; // 1 Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null is object").WithArguments("object").WithLocation(7, 13), // (8,13): warning CS0184: The given expression is never of the provided ('object') type // _ = null! is object; // 2 Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null! is object").WithArguments("object").WithLocation(8, 13), // (10,18): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // int i2 = null!; // 3 Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(10, 18), // (11,18): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // var i3 = (int)null!; // 4 Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(int)null!").WithArguments("int").WithLocation(11, 18), // (12,15): error CS0403: Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead. // T t = null!; // 5 Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T").WithLocation(12, 15), // (13,18): error CS0037: Cannot convert null to 'T' because it is a non-nullable value type // var t2 = (T)null!; // 6 Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T)null!").WithArguments("T").WithLocation(13, 18), // (16,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer // (null)++; // 9 Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "null").WithLocation(16, 10), // (17,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer // (null!)++; // 10 Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "null").WithLocation(17, 10), // (18,13): error CS8310: Operator '!' cannot be applied to operand '<null>' // _ = !null; // 11 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "!null").WithArguments("!", "<null>").WithLocation(18, 13), // (19,13): error CS8310: Operator '!' cannot be applied to operand '<null>' // _ = !(null!); // 12 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "!(null!)").WithArguments("!", "<null>").WithLocation(19, 13), // (20,58): error CS0845: An expression tree lambda may not contain a coalescing operator with a null or default literal left-hand side // Expression<System.Func<object>> testExpr = () => null! ?? "hello"; // 13 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, "null").WithLocation(20, 58) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MiscDefault() { var source = @"class C { void M(dynamic d, int? i) { d.M(null!, default!, null, default); // 1 _ = default == default!; // 2 _ = default! == default!; // 3 _ = 1 + default!; // 4 _ = default ?? d; // 5 _ = default! ?? d; // 6 _ = i ?? default; _ = i ?? default!; } void M2(object o) { _ = o == default; _ = o == default!; } }"; // Should `!` be disallowed on arguments to dynamic (line // 1) ? // See https://github.com/dotnet/roslyn/issues/32364 var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): error CS8716: There is no target type for the default literal. // d.M(null!, default!, null, default); // 1 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(5, 20), // (5,36): error CS8716: There is no target type for the default literal. // d.M(null!, default!, null, default); // 1 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(5, 36), // (6,13): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // _ = default == default!; // 2 Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "default == default!").WithArguments("==", "default", "default").WithLocation(6, 13), // (7,13): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // _ = default! == default!; // 3 Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "default! == default!").WithArguments("==", "default", "default").WithLocation(7, 13), // (8,13): error CS8310: Operator '+' cannot be applied to operand 'default' // _ = 1 + default!; // 4 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 + default!").WithArguments("+", "default").WithLocation(8, 13), // (9,13): error CS8716: There is no target type for the default literal. // _ = default ?? d; // 5 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(9, 13), // (10,13): error CS8716: There is no target type for the default literal. // _ = default! ?? d; // 6 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(10, 13) ); } [Fact, WorkItem(32879, "https://github.com/dotnet/roslyn/issues/32879")] public void ThrowExpressionInNullCoalescingOperator() { var source = @" class C { string Field = string.Empty; void M(C? c) { _ = c ?? throw new System.ArgumentNullException(nameof(c)); c.ToString(); } void M2(C? c) { _ = c?.Field ?? throw new System.ArgumentNullException(nameof(c)); c.ToString(); c.Field.ToString(); } void M3(C? c) { _ = c ?? throw new System.ArgumentNullException(c.ToString()); // 1 } void M4(string? s) { _ = s ?? s.ToString(); // 2 s.ToString(); } void M5(string s) { _ = s ?? s.ToString(); // 3 } #nullable disable void M6(string s) { #nullable enable _ = s ?? s.ToString(); // 4 } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (18,57): warning CS8602: Dereference of a possibly null reference. // _ = c ?? throw new System.ArgumentNullException(c.ToString()); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(18, 57), // (22,18): warning CS8602: Dereference of a possibly null reference. // _ = s ?? s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(22, 18), // (27,18): warning CS8602: Dereference of a possibly null reference. // _ = s ?? s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(27, 18), // (33,18): warning CS8602: Dereference of a possibly null reference. // _ = s ?? s.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(33, 18)); } [Fact, WorkItem(32877, "https://github.com/dotnet/roslyn/issues/32877")] public void CheckReceiverOfThrow() { var source = @" class C { void M(System.Exception? e, C? c) { _ = c ?? throw e; // 1 _ = c ?? throw null; // 2 throw null; // 3 } void M2(System.Exception? e, bool b) { if (b) throw e; // 4 else throw e!; } void M3() { throw this; // 5 } public static implicit operator System.Exception?(C c) => throw null!; void M4<TException>(TException? e) where TException : System.Exception { throw e; // 6 } void M5<TException>(TException e) where TException : System.Exception? { throw e; // 7 } void M6<TException>(TException? e) where TException : Interface { throw e; // 8 } void M7<TException>(TException e) where TException : Interface? { throw e; // 9 } void M8<TException>(TException e) where TException : Interface { throw e; // 10 } void M9<T>(T e) { throw e; // 11 } void M10() { try { } catch { throw; } } interface Interface { } }"; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (6,24): warning CS8597: Thrown value may be null. // _ = c ?? throw e; // 1 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "e").WithLocation(6, 24), // (7,24): warning CS8597: Thrown value may be null. // _ = c ?? throw null; // 2 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "null").WithLocation(7, 24), // (8,15): warning CS8597: Thrown value may be null. // throw null; // 3 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "null").WithLocation(8, 15), // (13,19): warning CS8597: Thrown value may be null. // throw e; // 4 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "e").WithLocation(13, 19), // (19,15): warning CS8597: Thrown value may be null. // throw this; // 5 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "this").WithLocation(19, 15), // (24,15): warning CS8597: Thrown value may be null. // throw e; // 6 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "e").WithLocation(24, 15), // (28,15): warning CS8597: Thrown value may be null. // throw e; // 7 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "e").WithLocation(28, 15), // (30,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void M6<TException>(TException? e) where TException : Interface Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "TException?").WithArguments("9.0").WithLocation(30, 25), // (32,15): error CS0029: Cannot implicitly convert type 'TException' to 'System.Exception' // throw e; // 8 Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("TException", "System.Exception").WithLocation(32, 15), // (36,15): error CS0029: Cannot implicitly convert type 'TException' to 'System.Exception' // throw e; // 9 Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("TException", "System.Exception").WithLocation(36, 15), // (40,15): error CS0029: Cannot implicitly convert type 'TException' to 'System.Exception' // throw e; // 10 Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("TException", "System.Exception").WithLocation(40, 15), // (44,15): error CS0029: Cannot implicitly convert type 'T' to 'System.Exception' // throw e; // 11 Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("T", "System.Exception").WithLocation(44, 15) ); } [Fact, WorkItem(32877, "https://github.com/dotnet/roslyn/issues/32877")] public void CatchClause() { var source = @" class C { void M() { try { } catch (System.Exception? e) { throw e; } } void M2() { try { } catch (System.Exception? e) { throw; } } void M3() { try { } catch (System.Exception? e) { e = null; throw e; // 1 } } void M4() { try { } catch (System.Exception e) { e = null; // 2 throw e; // 3 } } void M5() { try { } catch (System.Exception e) { e = null; // 4 throw; // this rethrows the original exception, not an NRE } } }"; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,34): warning CS0168: The variable 'e' is declared but never used // catch (System.Exception? e) { throw; } Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(12, 34), // (20,19): error CS8597: Thrown value may be null. // throw e; // 1 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "e").WithLocation(20, 19), // (28,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // e = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(28, 17), // (29,19): error CS8597: Thrown value may be null. // throw e; // 3 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "e").WithLocation(29, 19), // (35,33): warning CS0168: The variable 'e' is declared but never used // catch (System.Exception e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(35, 33), // (37,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // e = null; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(37, 17) ); } [Fact] public void Test0() { var source = @" class C { static void Main() { string? x = null; } } "; var c = CreateCompilation(source, parseOptions: TestOptions.Regular7); c.VerifyDiagnostics( // (6,15): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // string? x = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(6, 15), // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used // string? x = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 17) ); var c2 = CreateCompilation(source, parseOptions: TestOptions.Regular8); c2.VerifyDiagnostics( // (6,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? x = null; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 15), // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used // string? x = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 17) ); } [Fact] public void SpeakableInference_MethodTypeInference() { var source = @"class Program { void M<T>(T t) { if (t == null) throw null!; t.ToString(); var t2 = Copy(t); t2.ToString(); // warn } static T Copy<T>(T t) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(8, 9) ); } [Fact] public void SpeakableInference_MethodTypeInference_WithTuple() { var source = @"class Program { void M<T>(T t) { if (t == null) throw null!; var tuple = (t, t); tuple.Item1.ToString(); tuple.Item2.ToString(); var tuple2 = Copy(tuple); tuple2.Item1.ToString(); // warn tuple2.Item2.ToString(); // warn var tuple3 = Copy<T, T>(tuple); tuple3.Item1.ToString(); // warn tuple3.Item2.ToString(); // warn } static (T, U) Copy<T, U>((T, U) t) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // tuple2.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "tuple2.Item1").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // tuple2.Item2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "tuple2.Item2").WithLocation(12, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // tuple3.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "tuple3.Item1").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // tuple3.Item2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "tuple3.Item2").WithLocation(16, 9) ); } [Fact] public void SpeakableInference_MethodTypeInference_WithNull() { var source = @"class Program { void M<T>(T t) where T : class? { if (t == null) throw null!; t.ToString(); var t2 = Copy(t, null); t2.ToString(); // warn } static T Copy<T, U>(T t, U t) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,18): error CS0411: The type arguments for method 'Program.Copy<T, U>(T, U)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var t2 = Copy(t, null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Copy").WithArguments("Program.Copy<T, U>(T, U)").WithLocation(7, 18), // (10,32): error CS0100: The parameter name 't' is a duplicate // static T Copy<T, U>(T t, U t) => throw null!; Diagnostic(ErrorCode.ERR_DuplicateParamName, "t").WithArguments("t").WithLocation(10, 32) ); } [Fact] public void SpeakableInference_MethodTypeInference_NullAssigned() { var source = @"class Program { void M<T>(T t) where T : class { t = null; var t2 = Copy(t); t2 /*T:T?*/ .ToString(); // warn } static T Copy<T>(T t) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (5,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // t = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // t2 /*T:T?*/ .ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(7, 9) ); } [Fact] public void SpeakableInference_MethodTypeInference_NullableValueType() { var source = @"class Program { void M(int? t) { if (t == null) throw null!; t.Value.ToString(); var t2 = Copy(t); t2.Value.ToString(); // warn } void M2<T>(T? t) where T : struct { if (t == null) throw null!; t.Value.ToString(); var t2 = Copy(t); t2.Value.ToString(); // warn } static T Copy<T>(T t) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8629: Nullable value type may be null. // t2.Value.ToString(); // warn Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(8, 9), // (15,9): warning CS8629: Nullable value type may be null. // t2.Value.ToString(); // warn Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(15, 9) ); } [Fact] public void SpeakableInference_ArrayTypeInference() { var source = @"class Program { void M<T>(T t) { if (t == null) throw null!; t.ToString(); var t2 = new[] { t }; t2[0].ToString(); // warn } }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t2[0].ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2[0]").WithLocation(8, 9) ); } [Fact] public void SpeakableInference_ArrayTypeInference_WithTuple() { var source = @"class Program { void M<T>(T t) { if (t == null) throw null!; var a = new[] { (t, t) }; a[0].Item1.ToString(); a[0].Item2.ToString(); var b = new (T, T)[] { (t, t) }; b[0].Item1.ToString(); b[0].Item2.ToString(); } }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // a[0].Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a[0].Item1").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // a[0].Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a[0].Item2").WithLocation(8, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // b[0].Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0].Item1").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // b[0].Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0].Item2").WithLocation(12, 9) ); } [Fact] public void SpeakableInference_ArrayTypeInference_WithNull() { var source = @"class Program { void M<T>(T t) where T : class? { if (t == null) throw null!; t.ToString(); var t2 = new[] { t, null }; t2[0].ToString(); // 1 } }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t2[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2[0]").WithLocation(8, 9) ); } [Fact, WorkItem(30941, "https://github.com/dotnet/roslyn/issues/30941")] public void Verify30941() { var source = @" class Outer : Base { void M1(Base? x1) { Outer y = x1; } } class Base { } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,19): error CS0266: Cannot implicitly convert type 'Base' to 'Outer'. An explicit conversion exists (are you missing a cast?) // Outer y = x1; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x1").WithArguments("Base", "Outer").WithLocation(6, 19), // (6,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer y = x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(6, 19) ); } [Fact, WorkItem(31958, "https://github.com/dotnet/roslyn/issues/31958")] public void Verify31958() { var source = @" class C { string? M1(string s) { var d = (D)M1; // 1 d(null).ToString(); return null; } string M2(string s) { var d = (D)M2; // 2 d(null).ToString(); return s; } delegate string D(string? s); } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,17): warning CS8621: Nullability of reference types in return type of 'string? C.M1(string s)' doesn't match the target delegate 'C.D' (possibly because of nullability attributes). // var d = (D)M1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "(D)M1").WithArguments("string? C.M1(string s)", "C.D").WithLocation(6, 17), // (14,17): warning CS8622: Nullability of reference types in type of parameter 's' of 'string C.M2(string s)' doesn't match the target delegate 'C.D' (possibly because of nullability attributes). // var d = (D)M2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(D)M2").WithArguments("s", "string C.M2(string s)", "C.D").WithLocation(14, 17) ); } [Fact, WorkItem(28377, "https://github.com/dotnet/roslyn/issues/28377")] public void Verify28377() { var source = @" class C { void M() { object x; x! = null; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS0219: The variable 'x' is assigned but its value is never used // object x; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 16), // (7,9): error CS8598: The suppression operator is not allowed in this context // x! = null; Diagnostic(ErrorCode.ERR_IllegalSuppression, "x").WithLocation(7, 9), // (7,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x! = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 14) ); } [Fact, WorkItem(31295, "https://github.com/dotnet/roslyn/issues/31295")] public void Verify31295() { var source = @" class C { void M() { for (var x = 0; ; x!++) { } } }"; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact, WorkItem(26654, "https://github.com/dotnet/roslyn/issues/26654")] public void Verify26654() { var source = @" public class C { public void M(out string? x) => throw null!; public void M2() { string y; M(out y!); } }"; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact, WorkItem(33782, "https://github.com/dotnet/roslyn/issues/33782")] public void AnnotationInXmlDoc_TwoDeclarations() { var source = @" /// <summary /> public class C { void M<T>(T? t) where T : struct { } void M<T>(T t) where T : class { } /// <summary> /// See <see cref=""M{T}(T?)""/> /// </summary> void M2() { } /// <summary> /// See <see cref=""M{T}(T)""/> /// </summary> void M3() { } }"; // In cref, `T?` always binds to `Nullable<T>` var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, options: WithNullableEnable()); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var firstCref = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<NameMemberCrefSyntax>().First(); var firstCrefSymbol = model.GetSymbolInfo(firstCref).Symbol; Assert.Equal("void C.M<T>(T? t)", firstCrefSymbol.ToTestDisplayString()); var lastCref = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<NameMemberCrefSyntax>().Last(); var lastCrefSymbol = model.GetSymbolInfo(lastCref).Symbol; Assert.Equal("void C.M<T>(T t)", lastCrefSymbol.ToTestDisplayString()); } [Fact, WorkItem(33782, "https://github.com/dotnet/roslyn/issues/33782")] public void AnnotationInXmlDoc_DeclaredAsNonNullableReferenceType() { var source = @" /// <summary /> public class C { void M<T>(T t) where T : class { } /// <summary> /// <see cref=""M{T}(T?)""/> warn 1 /// </summary> void M2() { } /// <summary> /// <see cref=""M{T}(T)""/> /// </summary> void M3() { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,20): warning CS1574: XML comment has cref attribute 'M{T}(T?)' that could not be resolved // /// <see cref="M{T}(T?)"/> warn 1 Diagnostic(ErrorCode.WRN_BadXMLRef, "M{T}(T?)").WithArguments("M{T}(T?)").WithLocation(8, 20)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var lastCref = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<NameMemberCrefSyntax>().Last(); var lastCrefSymbol = model.GetSymbolInfo(lastCref).Symbol; Assert.Equal("void C.M<T>(T t)", lastCrefSymbol.ToTestDisplayString()); } [Fact, WorkItem(33782, "https://github.com/dotnet/roslyn/issues/33782")] public void AnnotationInXmlDoc_DeclaredAsNullableReferenceType() { var source = @" /// <summary /> public class C { void M<T>(T? t) where T : class { } /// <summary> /// <see cref=""M{T}(T?)""/> warn 1 /// </summary> void M2() { } /// <summary> /// <see cref=""M{T}(T)""/> /// </summary> void M3() { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,20): warning CS1574: XML comment has cref attribute 'M{T}(T?)' that could not be resolved // /// <see cref="M{T}(T?)"/> warn 1 Diagnostic(ErrorCode.WRN_BadXMLRef, "M{T}(T?)").WithArguments("M{T}(T?)").WithLocation(8, 20)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var lastCref = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<NameMemberCrefSyntax>().Last(); var lastCrefSymbol = model.GetSymbolInfo(lastCref).Symbol; Assert.Equal("void C.M<T>(T? t)", lastCrefSymbol.ToTestDisplayString()); } [Fact, WorkItem(30955, "https://github.com/dotnet/roslyn/issues/30955")] public void ArrayTypeInference_Verify30955() { var source = @" class Outer { void M0(object x0, object? y0) { var a = new[] { x0, 1 }; a[0] = y0; var b = new[] { x0, x0 }; b[0] = y0; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8601: Possible null reference assignment. // a[0] = y0; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y0").WithLocation(7, 16), // (9,16): warning CS8601: Possible null reference assignment. // b[0] = y0; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y0").WithLocation(9, 16) ); } [Fact, WorkItem(30598, "https://github.com/dotnet/roslyn/issues/30598")] public void Verify30598() { var source = @" class Program { static object F(object[]? x) { return x[ // warning: possibly null x.Length - 1]; // no warning } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8602: Dereference of a possibly null reference. // return x[ // warning: possibly null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 16) ); } [Fact, WorkItem(30925, "https://github.com/dotnet/roslyn/issues/30925")] public void Verify30925() { var source = @" class Outer { void M1<T>(T x1, object? y1) where T : class? { x1 = (T)y1; } void M2<T>(T x2, object? y2) where T : class? { x2 = y2; } void M3(string x3, object? y3) { x3 = (string)y3; } void M4(string x4, object? y4) { x4 = y4; } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (11,14): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // x2 = y2; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y2").WithArguments("object", "T").WithLocation(11, 14), // (16,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = (string)y3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)y3").WithLocation(16, 14), // (21,14): error CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?) // x4 = y4; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y4").WithArguments("object", "string").WithLocation(21, 14), // (21,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = y4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y4").WithLocation(21, 14)); } [Fact] public void SpeakableInference_ArrayTypeInference_NullableValueType() { var source = @"class Program { void M(int? t) { if (t == null) throw null!; t.Value.ToString(); var t2 = new[] { t }; t2[0].Value.ToString(); // warn } void M2<T>(T? t) where T : struct { if (t == null) throw null!; t.Value.ToString(); var t2 = new[] { t }; t2[0].Value.ToString(); // warn } }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8629: Nullable value type may be null. // t2[0].Value.ToString(); // warn Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2[0]").WithLocation(8, 9), // (15,9): warning CS8629: Nullable value type may be null. // t2[0].Value.ToString(); // warn Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2[0]").WithLocation(15, 9) ); } [Fact] public void SpeakableInference_ArrayTypeInference_ConversionWithNullableOutput_WithNestedMismatch() { var source = @"class A<T> { public static implicit operator C<T>?(A<T> a) => throw null!; } class B<T> : A<T> { } class C<T> { void M(B<string> x, C<string?> y) { var a = new[] { x, y }; a[0].ToString(); var b = new[] { y, x }; b[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,25): warning CS8619: Nullability of reference types in value of type 'C<string>' doesn't match target type 'C<string?>'. // var a = new[] { x, y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<string>", "C<string?>").WithLocation(12, 25), // (13,9): warning CS8602: Dereference of a possibly null reference. // a[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a[0]").WithLocation(13, 9), // (15,28): warning CS8619: Nullability of reference types in value of type 'C<string>' doesn't match target type 'C<string?>'. // var b = new[] { y, x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<string>", "C<string?>").WithLocation(15, 28), // (16,9): warning CS8602: Dereference of a possibly null reference. // b[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0]").WithLocation(16, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference() { var source = @"class Program { void M<T>(T t) { var x1 = F(() => { if (t == null) throw null!; bool b = true; if (b) return t; return t; }); x1.ToString(); var x2 = F<T>(() => { if (t == null) throw null!; bool b = true; if (b) return t; return t; }); x2.ToString(); } T F<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(12, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(21, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference2() { var source = @"class Program { void M<T>(T t, T t2) { var x1 = F(() => { if (t == null) throw null!; bool b = true; if (b) return t; return t2; }); x1.ToString(); var x2 = F<T>(() => { if (t == null) throw null!; bool b = true; if (b) return t; return t2; }); x2.ToString(); } T F<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(12, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(21, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_WithSingleReturn() { var source = @"class Program { void M<T>() { var x1 = Copy(() => """"); x1.ToString(); } void M2<T>(T t) { if (t == null) throw null!; var x1 = Copy(() => t); x1.ToString(); // 1 } T Copy<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(12, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_WithTuple() { var source = @"class Program { void M<T>(T t) { var x1 = Copy(() => { if (t == null) throw null!; bool b = true; if (b) return (t, t); return (t, t); }); x1.Item1.ToString(); x1.Item2.ToString(); } T Copy<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x1.Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1.Item1").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // x1.Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1.Item2").WithLocation(13, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_ConversionWithNullableOutput() { var source = @"class A { public static implicit operator C?(A a) => new C(); } class B : A { } class C { void M(B x, C y) { var x1 = F(() => { bool b = true; if (b) return x; return y; }); x1.ToString(); var x2 = F(() => { bool b = true; if (b) return y; return x; }); x2.ToString(); } T F<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(18, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(26, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_ConversionWithNullableOutput2() { var source = @"class A<T> { public static implicit operator C<T>?(A<T> a) => throw null!; } class B<T> : A<T> { } class C<T> { void M(B<string?> x, C<string?> y) { var x1 = F(() => { bool b = true; if (b) return x; return y; }); x1.ToString(); var x2 = F(() => { bool b = true; if (b) return y; return x; }); x2.ToString(); } U F<U>(System.Func<U> f) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(18, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(26, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_ConversionWithNullableOutput_WithNestedMismatch() { var source = @"class A<T> { public static implicit operator C<T>?(A<T> a) => throw null!; } class B<T> : A<T> { } class C<T> { void M(B<string> x, C<string?> y) { var x1 = F(() => { bool b = true; if (b) return x; return y; }); x1.ToString(); var x2 = F(() => { bool b = true; if (b) return y; return x; }); x2.ToString(); } U F<U>(System.Func<U> f) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,27): warning CS8619: Nullability of reference types in value of type 'C<string>' doesn't match target type 'C<string?>'. // if (b) return x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<string>", "C<string?>").WithLocation(15, 27), // (18,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(18, 9), // (24,20): warning CS8619: Nullability of reference types in value of type 'C<string>' doesn't match target type 'C<string?>'. // return x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<string>", "C<string?>").WithLocation(24, 20), // (26,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(26, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_ConversionWithNullableInput() { var source = @"class A { public static implicit operator C(A? a) => null; // warn } class B : A { } class C { void M(B? x, C y) { var x1 = F(() => { bool b = true; if (b) return x; return y; }); x1.ToString(); var x2 = F(() => { bool b = true; if (b) return y; return x; }); x2.ToString(); } T F<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,48): warning CS8603: Possible null reference return. // public static implicit operator C(A? a) => null; // warn Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(3, 48) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_WithNullabilityMismatch() { var source = @" class C<T> { void M(C<object>? x, C<object?> y) { var x1 = F(() => { bool b = true; if (b) return x; return y; }); _ = x1 /*T:C<object!>?*/; x1.ToString(); var x2 = F(() => { bool b = true; if (b) return y; return x; }); _ = x2 /*T:C<object!>?*/; x2.ToString(); } U F<U>(System.Func<U> f) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (10,20): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // return y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(10, 20), // (13,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(13, 9), // (18,27): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // if (b) return y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(18, 27), // (22,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(22, 9) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] [WorkItem(32006, "https://github.com/dotnet/roslyn/issues/32006")] public void SpeakableInference_LambdaReturnTypeInference_NonNullableTypelessOuptut() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @" class C { void M(C? c) { var x1 = F(() => { bool b = true; if (b) return (c, c); return (null, null); }); x1.ToString(); x1.Item1.ToString(); } T F<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // x1.Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1.Item1").WithLocation(13, 9) ); } [Fact] public void SpeakableInference_VarInference() { var source = @"class Program { void M<T>(T t) { if (t == null) throw null!; var t2 = t; t2.ToString(); } }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); var syntaxTree = comp.SyntaxTrees[0]; var declaration = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(syntaxTree); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("T? t2", local.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); Assert.Equal("T?", local.Type.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void Directive_Qualifiers() { var source = @"#nullable #nullable enable #nullable disable #nullable restore #nullable safeonly #nullable yes "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (1,10): error CS8637: Expected 'enable', 'disable', or 'restore' // #nullable Diagnostic(ErrorCode.ERR_NullableDirectiveQualifierExpected, "").WithLocation(1, 10), // (5,11): error CS8637: Expected 'enable', 'disable', or 'restore' // #nullable safeonly Diagnostic(ErrorCode.ERR_NullableDirectiveQualifierExpected, "safeonly").WithLocation(5, 11), // (6,11): error CS8637: Expected 'enable', 'disable', or 'restore' // #nullable yes Diagnostic(ErrorCode.ERR_NullableDirectiveQualifierExpected, "yes").WithLocation(6, 11) ); comp.VerifyTypes(); } [Fact] public void Directive_NullableDefault() { var source = @"#pragma warning disable 0649, 8618 class A<T, U> { } class B { static A<object, string?> F1; static void G1() { object o1; o1 = F1/*T:A<object, string?>!*/; o1 = F2/*T:A<object, string?>!*/; o1 = F3/*T:A<object!, string?>!*/; } #nullable disable static A<object, string?> F2; static void G2() { object o2; o2 = F1/*T:A<object, string?>!*/; o2 = F2/*T:A<object, string?>!*/; o2 = F3/*T:A<object!, string?>!*/; } #nullable enable static A<object, string?> F3; static void G3() { object o3; o3 = F1/*T:A<object, string?>!*/; o3 = F2/*T:A<object, string?>!*/; o3 = F3/*T:A<object!, string?>!*/; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (5,28): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static A<object, string?> F1; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 28), // (14,28): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static A<object, string?> F2; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 28)); comp.VerifyTypes(); } [Fact] public void Directive_NullableFalse() { var source = @"#pragma warning disable 0649, 8618 class A<T, U> { } class B { static A<object, string?> F1; static void G1() { object o1; o1 = F1/*T:A<object, string?>!*/; o1 = F2/*T:A<object, string?>!*/; o1 = F3/*T:A<object!, string?>!*/; } #nullable disable static A<object, string?> F2; static void G2() { object o2; o2 = F1/*T:A<object, string?>!*/; o2 = F2/*T:A<object, string?>!*/; o2 = F3/*T:A<object!, string?>!*/; } #nullable enable static A<object, string?> F3; static void G3() { object o3; o3 = F1/*T:A<object, string?>!*/; o3 = F2/*T:A<object, string?>!*/; o3 = F3/*T:A<object!, string?>!*/; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Disable)); comp.VerifyDiagnostics( // (5,28): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static A<object, string?> F1; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 28), // (14,28): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static A<object, string?> F2; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 28)); comp.VerifyTypes(); } [Fact] public void Directive_NullableTrue() { var source = @"#pragma warning disable 0649, 8618 class A<T, U> { } class B { static A<object, string?> F1; static void G1() { object o1; o1 = F1/*T:A<object!, string?>!*/; o1 = F2/*T:A<object, string?>!*/; o1 = F3/*T:A<object!, string?>!*/; } #nullable disable static A<object, string?> F2; static void G2() { object o2; o2 = F1/*T:A<object!, string?>!*/; o2 = F2/*T:A<object, string?>!*/; o2 = F3/*T:A<object!, string?>!*/; } #nullable enable static A<object, string?> F3; static void G3() { object o3; o3 = F1/*T:A<object!, string?>!*/; o3 = F2/*T:A<object, string?>!*/; o3 = F3/*T:A<object!, string?>!*/; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (14,28): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static A<object, string?> F2; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 28)); comp.VerifyTypes(); } [Fact] public void Directive_PartialClasses() { var source0 = @"class Base<T> { } class Program { #nullable enable static void F(Base<object?> b) { } static void Main() { F(new C1()); F(new C2()); F(new C3()); F(new C4()); F(new C5()); F(new C6()); F(new C7()); F(new C8()); F(new C9()); } }"; var source1 = @"#pragma warning disable 8632 partial class C1 : Base<object> { } partial class C2 { } partial class C3 : Base<object> { } #nullable disable partial class C4 { } partial class C5 : Base<object> { } partial class C6 { } #nullable enable partial class C7 : Base<object> { } partial class C8 { } partial class C9 : Base<object> { } "; var source2 = @"#pragma warning disable 8632 partial class C1 { } partial class C4 : Base<object> { } partial class C7 { } #nullable disable partial class C2 : Base<object> { } partial class C5 { } partial class C8 : Base<object> { } #nullable enable partial class C3 { } partial class C6 : Base<object> { } partial class C9 { } "; // -nullable (default): var comp = CreateCompilation(new[] { source0, source1, source2 }, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (15,11): warning CS8620: Nullability of reference types in argument of type 'C6' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C6()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C6()").WithArguments("C6", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(15, 11), // (16,11): warning CS8620: Nullability of reference types in argument of type 'C7' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C7()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C7()").WithArguments("C7", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(16, 11), // (18,11): warning CS8620: Nullability of reference types in argument of type 'C9' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C9()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C9()").WithArguments("C9", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(18, 11)); // -nullable-: comp = CreateCompilation(new[] { source0, source1, source2 }, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Disable)); comp.VerifyDiagnostics( // (15,11): warning CS8620: Nullability of reference types in argument of type 'C6' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C6()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C6()").WithArguments("C6", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(15, 11), // (16,11): warning CS8620: Nullability of reference types in argument of type 'C7' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C7()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C7()").WithArguments("C7", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(16, 11), // (18,11): warning CS8620: Nullability of reference types in argument of type 'C9' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C9()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C9()").WithArguments("C9", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(18, 11)); // -nullable+: comp = CreateCompilation(new[] { source0, source1, source2 }, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (10,11): warning CS8620: Nullability of reference types in argument of type 'C1' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C1()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C1()").WithArguments("C1", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(10, 11), // (12,11): warning CS8620: Nullability of reference types in argument of type 'C3' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C3()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C3()").WithArguments("C3", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(12, 11), // (13,11): warning CS8620: Nullability of reference types in argument of type 'C4' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C4()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C4()").WithArguments("C4", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(13, 11), // (15,11): warning CS8620: Nullability of reference types in argument of type 'C6' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C6()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C6()").WithArguments("C6", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(15, 11), // (16,11): warning CS8620: Nullability of reference types in argument of type 'C7' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C7()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C7()").WithArguments("C7", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(16, 11), // (18,11): warning CS8620: Nullability of reference types in argument of type 'C9' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C9()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C9()").WithArguments("C9", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(18, 11)); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void Directive_EnableAndDisable_01() { var source = @"#nullable enable class Program { static void F(object x) { object? y = null; F(y); // warning } #nullable disable static void G() { F(null); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void Program.F(object x)'. // F(y); // warning Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void Program.F(object x)").WithLocation(7, 11)); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void Directive_EnableAndDisable_02() { var source = @"class Program { #nullable disable static void G() { F(null); } #nullable enable static void F(object x) { object? y = null; F(y); // warning } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void Program.F(object x)'. // F(y); // warning Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void Program.F(object x)").WithLocation(12, 11)); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void Directive_EnableAndDisable_03() { var source = @"class Program { static void F(object x) { object? y = null; F(y); // warning } #nullable disable static void G() { F(null); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void Program.F(object x)'. // F(y); // warning Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void Program.F(object x)").WithLocation(6, 11)); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void Directive_EnableAndDisable_04() { var source = @"class Program { static void G() { F(null); } #nullable enable static void F(object x) { object? y = null; F(y); // warning } }"; var comp = CreateCompilation(source, options: WithNullableDisable()); comp.VerifyDiagnostics( // (11,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void Program.F(object x)'. // F(y); // warning Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void Program.F(object x)").WithLocation(11, 11)); } [Fact] public void Directive_GloballyEnabled_GeneratedCode_DisabledByDefault() { var source = @" // <autogenerated /> class Program { static void F(object x) { x = null; // no warning, generated file } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("#nullable enable warnings")] [InlineData("#nullable disable")] public void Directive_GloballyEnabled_GeneratedCode_Annotations_Disabled(string nullableDirective) { var source = $@" // <autogenerated /> {nullableDirective} class Program {{ static void F(string? s) {{ }} }}"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (6,25): error CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable enable' directive in source. // static void F(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode, "?").WithLocation(6, 25)); } [Theory] [InlineData("#nullable enable")] [InlineData("#nullable enable annotations")] public void Directive_GloballyEnabled_GeneratedCode_Annotations_Enabled(string nullableDirective) { var source = $@" // <autogenerated /> {nullableDirective} class Program {{ static void F(string? s) {{ }} }}"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics(); } [Fact] public void Directive_GloballyEnabled_GeneratedCode_Enabled() { var source = @" // <autogenerated /> #nullable enable class Program { static void F(object x) { x = null; // warning } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 13) ); } [Fact] public void Directive_GloballyEnabled_GeneratedCode_RestoreToProjectDefault() { var source = @" // <autogenerated /> partial class Program { #nullable restore static void F(object x) { x = null; // warning, restored to project default } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 13) ); } [Fact] public void Directive_GloballyEnabled_GeneratedCode_WarningsAreDisabledByDefault() { var source = @" // <autogenerated /> partial class Program { static void G(object x) { x = null; // no warning F = null; // no warning #nullable enable warnings x = null; // no warning - declared out of nullable context F = null; // warning - declared in a nullable context } #nullable enable static object F = new object(); }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (12,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // warning - declared in a nullable context Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 13) ); } [Fact] public void Directive_GloballyEnabled_GeneratedCode_PartialClasses() { var source1 = @" // <autogenerated /> partial class Program { static void G(object x) { x = null; // no warning F = null; // no warning } }"; var source2 = @" partial class Program { static object F = new object(); static void H() { F = null; // warning } }"; var comp = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (8,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // warning Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 13) ); } [Fact] public void Directive_GloballyEnabled_GeneratedCode_PartialClasses2() { var source1 = @" // <autogenerated /> partial class Program { #nullable enable warnings static void G(object x) { x = null; // no warning F = null; // warning } }"; var source2 = @" partial class Program { static object F = new object(); static void H() { F = null; // warning } }"; var comp = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (8,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // warning Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 13), // (9,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // warning Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 13) ); } [Fact] [WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")] public void GeneratedSyntaxTrees_Nullable() { #pragma warning disable CS0618 // This test is intentionally calling the obsolete method to assert it's isGeneratedCode input is now ignored var source1 = CSharpSyntaxTree.ParseText(@" partial class Program { static void G(object x) { x = null; // no warning F = null; // no warning } }", options: null, path: "", encoding: null, diagnosticOptions: null, isGeneratedCode: true, cancellationToken: default); Assert.False(((CSharpSyntaxTree)source1).IsGeneratedCode(null, cancellationToken: default)); var source2 = CSharpSyntaxTree.ParseText(@" partial class Program { static object F = new object(); static void H(object x) { x = null; // warning 1 F = null; // warning 2 } }", options: null, path: "", encoding: null, diagnosticOptions: null, isGeneratedCode: false, cancellationToken: default); Assert.False(((CSharpSyntaxTree)source2).IsGeneratedCode(null, cancellationToken: default)); var source3 = CSharpSyntaxTree.ParseText( @" partial class Program { static void I(object x) { x = null; // warning 3 F = null; // warning 4 } }", options: null, path: "", encoding: null, diagnosticOptions: null, isGeneratedCode: null /* use heuristic */, cancellationToken: default); Assert.False(((CSharpSyntaxTree)source3).IsGeneratedCode(null, cancellationToken: default)); var source4 = SyntaxFactory.ParseSyntaxTree(@" partial class Program { static void J(object x) { x = null; // no warning F = null; // no warning } }", options: null, path: "", encoding: null, diagnosticOptions: null, isGeneratedCode: true, cancellationToken: default); Assert.False(((CSharpSyntaxTree)source4).IsGeneratedCode(null, cancellationToken: default)); #pragma warning restore CS0618 var syntaxOptions = new TestSyntaxTreeOptionsProvider( (source1, GeneratedKind.MarkedGenerated), (source2, GeneratedKind.NotGenerated), (source3, GeneratedKind.Unknown), (source4, GeneratedKind.MarkedGenerated) ); var comp = CreateCompilation(new[] { source1, source2, source3, source4 }, options: TestOptions.DebugDll .WithNullableContextOptions(NullableContextOptions.Enable) .WithSyntaxTreeOptionsProvider(syntaxOptions)); comp.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // warning 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (7,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // warning 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 13), // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // warning 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 13), // (9,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // warning 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 13) ); } [WorkItem(30862, "https://github.com/dotnet/roslyn/issues/30862")] [Fact] public void DirectiveDisableWarningEnable() { var source = @"#nullable enable class Program { static void F(object x) { } #nullable disable static void F1(object? y, object? z) { F(y); #pragma warning restore 8604 F(z); // 1 } static void F2(object? w) { F(w); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static void F1(object? y, object? z) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 26), // (8,37): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static void F1(object? y, object? z) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 37), // (14,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static void F2(object? w) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 26)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void PragmaNullable_NoEffect() { var source = @" #pragma warning disable nullable class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_Enable_01() { var source = @" #nullable enable annotations class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_Enable_02() { var source = @" #nullable enable #nullable disable warnings class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_Enable_03() { var source = @" #nullable enable #nullable restore warnings class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_Enable_04() { var source = @" class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullable(NullableContextOptions.Annotations)); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_Enable_05() { var source = @" #nullable enable #nullable restore warnings class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableDisable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_Enable_06() { var source = @" #nullable disable #nullable restore warnings class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void M(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 25), // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_NonFlowAnalysisWarning_01() { var source = @" #nullable enable annotations public partial class C { partial void M(string? s); } public partial class C { partial void M(string s) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_NonFlowAnalysisWarning_02() { var source = @" using System.Collections.Generic; #nullable enable annotations class Base { internal virtual void M(List<string> list) { } } class Derived : Base { internal override void M(List<string?> list) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_NonFlowAnalysisWarning_03() { var source = @" using System.Collections.Generic; class Base { internal virtual void M(List<string> list) { } } #nullable enable annotations class Derived : Base { internal override void M(List<string?> list) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_NonFlowAnalysisWarning_04() { var source = @" #nullable enable annotations public interface I { void M(string? s); } public class C : I { public void M(string s) => throw null!; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_NonFlowAnalysisWarning_05() { var source = @" #nullable enable annotations public interface I { string M(); } public class C : I { public string? M() => throw null!; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Enable_NonFlowAnalysisWarning_01() { var source = @" #nullable enable public partial class C { partial void M(string? s); } public partial class C { partial void M(string s) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): warning CS8611: Nullability of reference types in type of parameter 's' doesn't match partial method declaration. // partial void M(string s) { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M").WithArguments("s").WithLocation(10, 18)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Enable_NonFlowAnalysisWarning_02() { var source = @" using System.Collections.Generic; #nullable enable class Base { internal virtual void M(List<string> list) { } } class Derived : Base { internal override void M(List<string?> list) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,28): warning CS8610: Nullability of reference types in type of parameter 'list' doesn't match overridden member. // internal override void M(List<string?> list) { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("list").WithLocation(11, 28)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Enable_NonFlowAnalysisWarning_03() { var source = @" using System.Collections.Generic; class Base { internal virtual void M(List<string> list) { } } #nullable enable class Derived : Base { // No warning because the base method's parameter type is oblivious internal override void M(List<string?> list) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Enable_NonFlowAnalysisWarning_04() { var source = @" #nullable enable public interface I { void M(string? s); } public class C : I { public void M(string s) => throw null!; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,17): warning CS8767: Nullability of reference types in type of parameter 's' of 'void C.M(string s)' doesn't match implicitly implemented member 'void I.M(string? s)' (possibly because of nullability attributes). // public void M(string s) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M").WithArguments("s", "void C.M(string s)", "void I.M(string? s)").WithLocation(10, 17) ); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Enable_NonFlowAnalysisWarning_05() { var source = @" #nullable enable public interface I { string M(); } public class C : I { public string? M() => throw null!; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,20): warning CS8766: Nullability of reference types in return type of 'string? C.M()' doesn't match implicitly implemented member 'string I.M()' (possibly because of nullability attributes). // public string? M() => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M").WithArguments("string? C.M()", "string I.M()").WithLocation(10, 20) ); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Warnings_Enable_01() { var source = @" #nullable enable warnings class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void M(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 25), // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Warnings_Enable_02() { var source = @" #nullable enable #nullable disable annotations class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void M(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 25), // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Warnings_Enable_03() { var source = @" #nullable enable #nullable restore annotations class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void M(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 25), // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Warnings_Enable_04() { var source = @" class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullable(NullableContextOptions.Warnings)); comp.VerifyDiagnostics( // (4,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void M(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 25), // (6,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Warnings_Enable_05() { var source = @" #nullable enable #nullable restore annotations class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableDisable()); comp.VerifyDiagnostics( // (6,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void M(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 25), // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Warnings_Enable_06() { var source = @" #nullable disable #nullable restore annotations class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(35730, "https://github.com/dotnet/roslyn/issues/35730")] public void Directive_ProjectNoWarn() { var source = @" #nullable enable class Program { void M1(string? s) { _ = s.ToString(); } } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13)); var id = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullReferenceReceiver); var comp2 = CreateCompilation(source, options: TestOptions.DebugDll.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress)); comp2.VerifyDiagnostics(); } [Fact, WorkItem(31740, "https://github.com/dotnet/roslyn/issues/31740")] public void Attribute_ArrayWithDifferentNullability() { var source = @" public class MyAttribute : System.Attribute { public MyAttribute(string[] x) { } } #nullable enable [My(new string[] { ""hello"" })] class C { } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); } [Fact, WorkItem(31740, "https://github.com/dotnet/roslyn/issues/31740")] public void Attribute_ArrayWithDifferentNullability2() { var source = @" public class MyAttribute : System.Attribute { public MyAttribute(string[] x) { } } #nullable enable [My(new string[] { null })] class C { } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (7,20): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [My(new string[] { null })] Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 20) ); } [Fact, WorkItem(31740, "https://github.com/dotnet/roslyn/issues/31740")] public void Attribute_ArrayWithDifferentNullability_DynamicAndTupleNames() { var source = @" public class MyAttribute : System.Attribute { public MyAttribute((string alice, string)[] x, dynamic[] y, object[] z) { } } #nullable enable [My(new (string, string bob)[] { }, new object[] { }, new dynamic[] { })] class C { } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (7,2): error CS0181: Attribute constructor parameter 'x' has type '(string alice, string)[]', which is not a valid attribute parameter type // [My(new (string, string bob)[] { }, new object[] { }, new dynamic[] { })] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("x", "(string alice, string)[]").WithLocation(7, 2), // (7,2): error CS0181: Attribute constructor parameter 'y' has type 'dynamic[]', which is not a valid attribute parameter type // [My(new (string, string bob)[] { }, new object[] { }, new dynamic[] { })] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("y", "dynamic[]").WithLocation(7, 2) ); } [Fact, WorkItem(31740, "https://github.com/dotnet/roslyn/issues/31740")] public void Attribute_ArrayWithDifferentNullability_Dynamic() { var source = @" public class MyAttribute : System.Attribute { public MyAttribute(dynamic[] y) { } } #nullable enable [My(new object[] { })] class C { } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (7,2): error CS0181: Attribute constructor parameter 'y' has type 'dynamic[]', which is not a valid attribute parameter type // [My(new object[] { })] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("y", "dynamic[]").WithLocation(7, 2) ); } [Fact, WorkItem(36974, "https://github.com/dotnet/roslyn/issues/36974")] public void Attribute_Params() { var source = @" using System; [My(new object[] { new string[] { ""a"" } })] public class C { } #nullable enable public class MyAttribute : Attribute { public MyAttribute(params object[] o) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); var c = comp.GetTypeByMetadataName("C"); var attribute = c.GetAttributes().Single(); Assert.Equal(@"{{""a""}}", attribute.CommonConstructorArguments.Single().ToCSharpString()); } [Fact, WorkItem(36974, "https://github.com/dotnet/roslyn/issues/36974")] public void Attribute_Params_Disabled() { var source = @" using System; [My(new object[] { new string[] { ""a"" } })] public class C { } #nullable disable public class MyAttribute : Attribute { public MyAttribute(params object[] o) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); var c = comp.GetTypeByMetadataName("C"); var attribute = c.GetAttributes().Single(); Assert.Equal(@"{{""a""}}", attribute.CommonConstructorArguments.Single().ToCSharpString()); } [Fact, WorkItem(37155, "https://github.com/dotnet/roslyn/issues/37155")] public void Attribute_Params_DifferentNullability() { var source = @" using System; #nullable enable [My(new object?[] { null })] public class C { } public class MyAttribute : Attribute { public MyAttribute(params object[] o) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (5,5): warning CS8620: Argument of type 'object?[]' cannot be used for parameter 'o' of type 'object[]' in 'MyAttribute.MyAttribute(params object[] o)' due to differences in the nullability of reference types. // [My(new object?[] { null })] Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new object?[] { null }").WithArguments("object?[]", "object[]", "o", "MyAttribute.MyAttribute(params object[] o)").WithLocation(5, 5) ); } [Fact, WorkItem(37155, "https://github.com/dotnet/roslyn/issues/37155")] public void Attribute_DifferentNullability() { var source = @" using System; #nullable enable [My(new object?[] { null })] public class C { } public class MyAttribute : Attribute { public MyAttribute(object[] o) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (5,5): warning CS8620: Argument of type 'object?[]' cannot be used for parameter 'o' of type 'object[]' in 'MyAttribute.MyAttribute(object[] o)' due to differences in the nullability of reference types. // [My(new object?[] { null })] Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new object?[] { null }").WithArguments("object?[]", "object[]", "o", "MyAttribute.MyAttribute(object[] o)").WithLocation(5, 5) ); } [Fact, WorkItem(36974, "https://github.com/dotnet/roslyn/issues/36974")] public void Attribute_Params_TupleNames() { var source = @" using System; [My(new (int a, int b)[] { (1, 2) })] public class C { } public class MyAttribute : Attribute { public MyAttribute(params (int c, int)[] o) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (4,2): error CS0181: Attribute constructor parameter 'o' has type '(int c, int)[]', which is not a valid attribute parameter type // [My(new (int a, int b)[] { (1, 2) })] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("o", "(int c, int)[]").WithLocation(4, 2) ); } [Fact, WorkItem(36974, "https://github.com/dotnet/roslyn/issues/36974")] public void Attribute_Params_Dynamic() { var source = @" using System; [My(new object[] { 1 })] public class C { } public class MyAttribute : Attribute { public MyAttribute(params dynamic[] o) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (4,2): error CS0181: Attribute constructor parameter 'o' has type 'dynamic[]', which is not a valid attribute parameter type // [My(new object[] { 1 })] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("o", "dynamic[]").WithLocation(4, 2) ); } [Fact] public void AttributeArgument_Constructor_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s) { } } [MyAttribute(null)] //1 class C { } [MyAttribute(""str"")] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 14) ); } [Fact] public void AttributeArgument_Constructor_NullLiteral_Suppressed() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s) { } } [MyAttribute(null!)] class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void AttributeArgument_Constructor_NullLiteral_CSharp7_3() { var source = @" class MyAttribute : System.Attribute { public MyAttribute(string s) { } } [MyAttribute(null)] class C { } [MyAttribute(""str"")] class D { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(); } [Fact] public void AttributeArgument_Constructor_NullLiteral_WithDefaultArgument() { var source = @"#nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s, string s2 = ""str"") { } } [MyAttribute(null)] //1 class C { } [MyAttribute(null, null)] // 2, 3 class D { } [MyAttribute(null, ""str"")] // 4 class E { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 14), // (10,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, null)] // 2, 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 14), // (10,20): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, null)] // 2, 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 20), // (13,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, "str")] // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 14) ); } [Fact] public void AttributeArgument_Constructor_NullLiteral_WithNullDefaultArgument() { var source = @"#nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s, string s2 = null) { } // 1 } [MyAttribute(""str"")] class C { } [MyAttribute(""str"", null)] // 2 class D { } [MyAttribute(""str"", ""str"")] class E { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,46): warning CS8625: Cannot convert null literal to non-nullable reference type. // public MyAttribute(string s, string s2 = null) { } // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 46), // (10,21): warning CS8625: Cannot convert null literal to non-nullable reference type. // [MyAttribute("str", null)] // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 21) ); } [Fact] public void AttributeArgument_Constructor_NullLiteral_WithNamedArguments() { var source = @"#nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s, string s2 = ""str"", string? s3 = ""str"") { } } [MyAttribute(""str"", s2: null, s3: null)] //1 class C { } [MyAttribute(s3: null, s2: null, s: ""str"")] // 2 class D { } [MyAttribute(s3: null, s2: ""str"", s: ""str"")] class E { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,25): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute("str", s2: null, s3: null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 25), // (10,28): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(s3: null, s2: null, s: "str")] // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 28) ); } [Fact] public void AttributeArgument_Constructor_NullLiteral_DisabledEnabled() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s, string s2) { } } [MyAttribute(null, //1 #nullable disable null #nullable enable )] class C { } [MyAttribute( #nullable disable null, #nullable enable null //2 )] class D { } [MyAttribute(null, //3 s2: #nullable disable null #nullable enable )] class E { } [MyAttribute( #nullable disable null, s2: #nullable enable null //4 )] class F { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 14), // (19,1): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // null //2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 1), // (23,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, //3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(23, 14), // (36,1): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // null //4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(36, 1) ); } [Fact] public void AttributeArgument_Constructor_NullLiteral_WarningDisabledEnabled() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s, string s2) { } } #nullable disable #nullable enable warnings [MyAttribute(null, //1 #nullable disable warnings null #nullable enable warnings )] class C { } [MyAttribute( #nullable disable warnings null, #nullable enable warnings null //2 )] class D { } [MyAttribute(null, //3 s2: #nullable disable warnings null #nullable enable warnings )] class E { } [MyAttribute( #nullable disable warnings null, s2: #nullable enable warnings null //4 )] class F { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 14), // (21,1): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // null //2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 1), // (25,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, //3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(25, 14), // (38,1): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // null //4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(38, 1) ); } [Fact] public void AttributeArgument_Constructor_Array_LiteralNull() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string[] s) { } } [MyAttribute(null)] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 14) ); } [Fact] public void AttributeArgument_Constructor_Array_LiteralNull_Suppressed() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string[] s) { } } [MyAttribute(null!)] class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void AttributeArgument_Constructor_Array_ArrayOfNullable() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string[] s) { } } [MyAttribute(new string?[]{ null })] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,14): warning CS8620: Argument of type 'string?[]' cannot be used as an input of type 'string[]' for parameter 's' in 'MyAttribute.MyAttribute(string[] s)' due to differences in the nullability of reference types. // [MyAttribute(new string?[]{ null })] //1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new string?[]{ null }").WithArguments("string?[]", "string[]", "s", "MyAttribute.MyAttribute(string[] s)").WithLocation(8, 14) ); } [Fact] public void AttributeArgument_Constructor_Array_ArrayOfNullable_Suppressed() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string[] s) { } } [MyAttribute(new string?[]{ null }!)] class C { } [MyAttribute(new string[]{ null! })] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void AttributeArgument_Constructor_Array_ArrayOfNullable_ImplicitType() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string[] s) { } } [MyAttribute(new []{ ""str"", null })] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,14): warning CS8620: Argument of type 'string?[]' cannot be used as an input of type 'string[]' for parameter 's' in 'MyAttribute.MyAttribute(string[] s)' due to differences in the nullability of reference types. // [MyAttribute(new []{ "str", null })] //1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, @"new []{ ""str"", null }").WithArguments("string?[]", "string[]", "s", "MyAttribute.MyAttribute(string[] s)").WithLocation(8, 14) ); } [Fact] public void AttributeArgument_Constructor_Array_NullValueInInitializer() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string[] s) { } } [MyAttribute(new string[]{ ""str"", null, ""str"" })] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,35): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(new string[]{ "str", null, "str" })] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 35) ); } [Fact] public void AttributeArgument_Constructor_Array_NullValueInNestedInitializer() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(object[] s) { } } [MyAttribute(new object[] { new string[] { ""str"", null }, //1 new string[] { null }, //2 new string?[] { null } })] class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,27): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // new string[] { "str", null }, //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 27), // (11,20): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // new string[] { null }, //2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 20) ); } [Fact] public void AttributeArgument_Constructor_ParamsArrayOfNullable_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(params object?[] s) { } } [MyAttribute(null)] //1 class C { } [MyAttribute(null, null)] class D { } [MyAttribute((object?)null)] class E { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 14) ); } [Fact] public void AttributeArgument_Constructor_ParamsArray_NullItem() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s1, params object[] s) { } } [MyAttribute(""str"", null, ""str"", ""str"")] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,21): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute("str", null, "str", "str")] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 21) ); } [Fact] public void AttributeArgument_PropertyAssignment_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute() { } public string MyValue { get; set; } = ""str""; } [MyAttribute(MyValue = null)] //1 class C { } [MyAttribute(MyValue = ""str"")] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,24): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(MyValue = null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 24) ); } [Fact] public void AttributeArgument_PropertyAssignment_Array_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute() { } public string[] PropertyArray { get; set; } = new string[] { }; public string[]? NullablePropertyArray { get; set; } = null; } [MyAttribute(PropertyArray = null)] //1 class C { } [MyAttribute(NullablePropertyArray = null)] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,30): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(PropertyArray = null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 30) ); } [Fact] public void AttributeArgument_PropertyAssignment_Array_ArrayOfNullable() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute() { } public string[] PropertyArray { get; set; } = new string[] { ""str"" }; public string[]? PropertyNullableArray { get; set; } = new string[] { ""str"" }; } [MyAttribute(PropertyArray = new string?[]{ null })] //1 class C { } [MyAttribute(PropertyNullableArray = null)] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,30): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'. // [MyAttribute(PropertyArray = new string?[]{ null })] //1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new string?[]{ null }").WithArguments("string?[]", "string[]").WithLocation(12, 30) ); } [Fact] public void AttributeArgument_FieldAssignment_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute() { } public string myValue = ""str""; } [MyAttribute(myValue = null)] //1 class C { } [MyAttribute(myValue = ""str"")] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,24): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(myValue = null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 24) ); } [Fact] public void AttributeArgument_FieldAssignment_Array_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute() { } public string[] fieldArray = new string[] { }; public string[]? nullableFieldArray = null; } [MyAttribute(fieldArray = null)] //1 class C { } [MyAttribute(nullableFieldArray = null)] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,27): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(fieldArray = null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 27) ); } [Fact] public void AttributeArgument_FieldAssignment_Array_ArrayOfNullable() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute() { } public string[] fieldArray = new string[] { }; public string?[] fieldArrayOfNullable = new string?[] { }; } [MyAttribute(fieldArray = new string?[]{ null })] //1 class C { } [MyAttribute(fieldArrayOfNullable = new string?[]{ null })] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,27): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'. // [MyAttribute(fieldArray = new string?[]{ null })] //1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new string?[]{ null }").WithArguments("string?[]", "string[]").WithLocation(12, 27) ); } [Fact] public void AttributeArgument_NoMatchingConstructor_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { } [MyAttribute(null)] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,2): error CS1729: 'MyAttribute' does not contain a constructor that takes 1 arguments // [MyAttribute(null)] //1 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "MyAttribute(null)").WithArguments("MyAttribute", "1").WithLocation(7, 2) ); } [Fact] public void AttributeArgument_NoMatchingConstructor_Array_NullValueInInitializer() { var source = @" #nullable enable class MyAttribute : System.Attribute { } [MyAttribute(new string[] { null })] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,2): error CS1729: 'MyAttribute' does not contain a constructor that takes 1 arguments // [MyAttribute(new string[] { null })] //1 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "MyAttribute(new string[] { null })").WithArguments("MyAttribute", "1").WithLocation(7, 2), // (7,29): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(new string[] { null })] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 29) ); } [Fact] public void AttributeArgument_NoMatchingConstructor_PropertyAssignment_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public string[] PropertyArray { get; set; } = new string[] { ""str"" }; public string[]? PropertyNullableArray { get; set; } = new string[] { ""str"" }; } [MyAttribute( // 1 new string[] { null }, // 2 PropertyArray = null, // 3 PropertyNullableArray = new string[] { null } // 4 )] class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,2): error CS1729: 'MyAttribute' does not contain a constructor that takes 1 arguments // [MyAttribute( // 1 Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"MyAttribute( // 1 new string[] { null }, // 2 PropertyArray = null, // 3 PropertyNullableArray = new string[] { null } // 4 )").WithArguments("MyAttribute", "1").WithLocation(10, 2), // (11,20): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // new string[] { null }, // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 20), // (12,21): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // PropertyArray = null, // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 21), // (13,44): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // PropertyNullableArray = new string[] { null } // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 44) ); } [Fact] public void AttributeArgument_NoMatchingConstructor_FieldAssignment_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public string[] fieldArray = new string[] { }; public string?[] fieldArrayOfNullable = new string?[] { }; } [MyAttribute( // 1 new string[] { null }, // 2 fieldArray = null, // 3 fieldArrayOfNullable = new string[] { null } // 4 )] class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,2): error CS1729: 'MyAttribute' does not contain a constructor that takes 1 arguments // [MyAttribute( // 1 Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"MyAttribute( // 1 new string[] { null }, // 2 fieldArray = null, // 3 fieldArrayOfNullable = new string[] { null } // 4 )").WithArguments("MyAttribute", "1").WithLocation(10, 2), // (11,20): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // new string[] { null }, // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 20), // (12,18): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // fieldArray = null, // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 18), // (13,43): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // fieldArrayOfNullable = new string[] { null } // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 43) ); } [Fact] public void AttributeArgument_ComplexAssignment() { var source = @" #nullable enable [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)] class MyAttribute : System.Attribute { public MyAttribute(string s, string s2 = ""str"", string s3 = ""str"") { } public string[] fieldArray = new string[] { }; public string?[] fieldArrayOfNullable = new string[] { }; public string[]? nullableFieldArray = null; public string[] PropertyArray { get; set; } = new string[] { }; public string?[] PropertyArrayOfNullable { get; set; } = new string[] { }; public string[]? NullablePropertyArray { get; set; } = null; } [MyAttribute(""s1"")] [MyAttribute(""s1"", s3: ""s3"", fieldArray = new string[]{})] [MyAttribute(""s1"", s2: ""s2"", fieldArray = new string[]{}, PropertyArray = new string[]{})] [MyAttribute(""s1"", fieldArrayOfNullable = new string?[]{ null }, NullablePropertyArray = null)] [MyAttribute(null)] // 1 [MyAttribute(""s1"", s3: null, fieldArray = new string[]{})] // 2 [MyAttribute(""s1"", s2: ""s2"", fieldArray = new string?[]{ null }, PropertyArray = new string[]{})] // 3 [MyAttribute(""s1"", PropertyArrayOfNullable = null)] // 4 [MyAttribute(""s1"", NullablePropertyArray = new string?[]{ null })] // 5 [MyAttribute(""s1"", fieldArrayOfNullable = null)] // 6 [MyAttribute(""s1"", nullableFieldArray = new string[]{ null })] // 7 [MyAttribute(null, //8 s2: null, //9 fieldArrayOfNullable = null, //10 NullablePropertyArray = new string?[]{ null })] // 11 [MyAttribute(null, // 12 #nullable disable s2: null, #nullable enable fieldArrayOfNullable = null, //13 #nullable disable warnings NullablePropertyArray = new string?[]{ null }, #nullable enable warnings nullableFieldArray = new string?[]{ null })] //14 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (26,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null)] // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(26, 14), // (27,24): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute("s1", s3: null, fieldArray = new string[]{})] // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(27, 24), // (28,43): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'. // [MyAttribute("s1", s2: "s2", fieldArray = new string?[]{ null }, PropertyArray = new string[]{})] // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new string?[]{ null }").WithArguments("string?[]", "string[]").WithLocation(28, 43), // (29,46): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute("s1", PropertyArrayOfNullable = null)] // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(29, 46), // (30,44): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'. // [MyAttribute("s1", NullablePropertyArray = new string?[]{ null })] // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new string?[]{ null }").WithArguments("string?[]", "string[]").WithLocation(30, 44), // (31,43): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute("s1", fieldArrayOfNullable = null)] // 6 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(31, 43), // (32,55): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute("s1", nullableFieldArray = new string[]{ null })] // 7 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(32, 55), // (33,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, //8 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(33, 14), // (34,17): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // s2: null, //9 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(34, 17), // (35,36): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // fieldArrayOfNullable = null, //10 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(35, 36), // (36,37): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'. // NullablePropertyArray = new string?[]{ null })] // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new string?[]{ null }").WithArguments("string?[]", "string[]").WithLocation(36, 37), // (37,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, // 12 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(37, 14), // (41,36): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // fieldArrayOfNullable = null, //13 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(41, 36), // (45,34): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'. // nullableFieldArray = new string?[]{ null })] //14 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new string?[]{ null }").WithArguments("string?[]", "string[]").WithLocation(45, 34) ); } [Fact, WorkItem(40136, "https://github.com/dotnet/roslyn/issues/40136")] public void SelfReferencingAttribute() { var source = @" using System; [AttributeUsage(AttributeTargets.All)] [ExplicitCrossPackageInternal(ExplicitCrossPackageInternalAttribute.s)] internal sealed class ExplicitCrossPackageInternalAttribute : Attribute { internal const string s = """"; [ExplicitCrossPackageInternal(s)] internal ExplicitCrossPackageInternalAttribute([ExplicitCrossPackageInternal(s)] string prop) { } [return: ExplicitCrossPackageInternal(s)] [ExplicitCrossPackageInternal(s)] internal void Method() { } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void NullableAndConditionalOperators() { var source = @"class Program { static void F1(object x) { _ = x is string? 1 : 2; _ = x is string? ? 1 : 2; // error 1: is a nullable reference type _ = x is string ? ? 1 : 2; // error 2: is a nullable reference type _ = x as string?? x; _ = x as string ? ?? x; // error 3: as a nullable reference type } static void F2(object y) { _ = y is object[]? 1 : 2; _ = y is object[]? ? 1 : 2; // error 4 _ = y is object[] ? ? 1 : 2; // error 5 _ = y as object[]?? y; _ = y as object[] ? ?? y; // error 6 } static void F3<T>(object z) { _ = z is T[][]? 1 : 2; _ = z is T[]?[] ? 1 : 2; _ = z is T[] ? [] ? 1 : 2; _ = z as T[][]?? z; _ = z as T[] ? [] ?? z; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (6,18): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead. // _ = x is string? ? 1 : 2; // error 1: is a nullable reference type Diagnostic(ErrorCode.ERR_IsNullableType, "string?").WithArguments("string").WithLocation(6, 18), // (6,24): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = x is string? ? 1 : 2; // error 1: is a nullable reference type Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(6, 24), // (7,18): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead. // _ = x is string ? ? 1 : 2; // error 2: is a nullable reference type Diagnostic(ErrorCode.ERR_IsNullableType, "string ?").WithArguments("string").WithLocation(7, 18), // (7,25): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = x is string ? ? 1 : 2; // error 2: is a nullable reference type Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(7, 25), // (9,18): error CS8651: It is not legal to use nullable reference type 'string?' in an as expression; use the underlying type 'string' instead. // _ = x as string ? ?? x; // error 3: as a nullable reference type Diagnostic(ErrorCode.ERR_AsNullableType, "string ?").WithArguments("string").WithLocation(9, 18), // (9,25): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = x as string ? ?? x; // error 3: as a nullable reference type Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(9, 25), // (14,18): error CS8650: It is not legal to use nullable reference type 'object[]?' in an is-type expression; use the underlying type 'object[]' instead. // _ = y is object[]? ? 1 : 2; // error 4 Diagnostic(ErrorCode.ERR_IsNullableType, "object[]?").WithArguments("object[]").WithLocation(14, 18), // (14,26): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = y is object[]? ? 1 : 2; // error 4 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(14, 26), // (15,18): error CS8650: It is not legal to use nullable reference type 'object[]?' in an is-type expression; use the underlying type 'object[]' instead. // _ = y is object[] ? ? 1 : 2; // error 5 Diagnostic(ErrorCode.ERR_IsNullableType, "object[] ?").WithArguments("object[]").WithLocation(15, 18), // (15,27): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = y is object[] ? ? 1 : 2; // error 5 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(15, 27), // (17,18): error CS8651: It is not legal to use nullable reference type 'object[]?' in an as expression; use the underlying type 'object[]' instead. // _ = y as object[] ? ?? y; // error 6 Diagnostic(ErrorCode.ERR_AsNullableType, "object[] ?").WithArguments("object[]").WithLocation(17, 18), // (17,27): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = y as object[] ? ?? y; // error 6 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(17, 27), // (22,21): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = z is T[]?[] ? 1 : 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(22, 21), // (23,22): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = z is T[] ? [] ? 1 : 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(23, 22), // (25,22): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = z as T[] ? [] ?? z; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(25, 22) ); comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead. // _ = x is string? ? 1 : 2; // error 1: is a nullable reference type Diagnostic(ErrorCode.ERR_IsNullableType, "string?").WithArguments("string").WithLocation(6, 18), // (7,18): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead. // _ = x is string ? ? 1 : 2; // error 2: is a nullable reference type Diagnostic(ErrorCode.ERR_IsNullableType, "string ?").WithArguments("string").WithLocation(7, 18), // (9,18): error CS8651: It is not legal to use nullable reference type 'string?' in an as expression; use the underlying type 'string' instead. // _ = x as string ? ?? x; // error 3: as a nullable reference type Diagnostic(ErrorCode.ERR_AsNullableType, "string ?").WithArguments("string").WithLocation(9, 18), // (14,18): error CS8650: It is not legal to use nullable reference type 'object[]?' in an is-type expression; use the underlying type 'object[]' instead. // _ = y is object[]? ? 1 : 2; // error 4 Diagnostic(ErrorCode.ERR_IsNullableType, "object[]?").WithArguments("object[]").WithLocation(14, 18), // (15,18): error CS8650: It is not legal to use nullable reference type 'object[]?' in an is-type expression; use the underlying type 'object[]' instead. // _ = y is object[] ? ? 1 : 2; // error 5 Diagnostic(ErrorCode.ERR_IsNullableType, "object[] ?").WithArguments("object[]").WithLocation(15, 18), // (17,18): error CS8651: It is not legal to use nullable reference type 'object[]?' in an as expression; use the underlying type 'object[]' instead. // _ = y as object[] ? ?? y; // error 6 Diagnostic(ErrorCode.ERR_AsNullableType, "object[] ?").WithArguments("object[]").WithLocation(17, 18) ); } [Fact, WorkItem(29318, "https://github.com/dotnet/roslyn/issues/29318")] public void IsOperatorOnNonNullExpression() { var source = @" class C { void M(object o) { if (o is string) { o.ToString(); } else { o.ToString(); } } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); c.VerifyDiagnostics(); } [Fact, WorkItem(29318, "https://github.com/dotnet/roslyn/issues/29318")] public void IsOperatorOnMaybeNullExpression() { var source = @" class C { static void Main(object? o) { if (o is string) { o.ToString(); } else { o.ToString(); // 1 } } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(12, 13) ); } [Fact, WorkItem(29318, "https://github.com/dotnet/roslyn/issues/29318")] public void IsOperatorOnUnconstrainedType() { var source = @" class C { static void M<T>(T t) { if (t is string) { t.ToString(); } else { t.ToString(); // 1 } } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(12, 13) ); } [Fact] public void IsOperator_AffectsNullConditionalOperator() { var source = @" class C { public object? field = null; static void M(C? c) { if (c?.field is string) { c.ToString(); c.field.ToString(); } else { c.ToString(); // 1 } } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(14, 13) ); } [Fact] public void OmittedCall() { var source = @" partial class C { void M(string? x) { OmittedMethod(x); } partial void OmittedMethod(string x); } "; var c = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,23): warning CS8604: Possible null reference argument for parameter 'x' in 'void C.OmittedMethod(string x)'. // OmittedMethod(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "void C.OmittedMethod(string x)").WithLocation(6, 23) ); } [Fact] public void OmittedInitializerCall() { var source = @" using System.Collections; partial class Collection : IEnumerable { void M(string? x) { _ = new Collection() { x }; } IEnumerator IEnumerable.GetEnumerator() => throw null!; partial void Add(string x); } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,32): warning CS8604: Possible null reference argument for parameter 'x' in 'void Collection.Add(string x)'. // _ = new Collection() { x }; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "void Collection.Add(string x)").WithLocation(7, 32) ); } [Fact] public void UpdateArrayRankSpecifier() { var source = @" class C { static void Main() { object[]? x = null; } } "; var tree = Parse(source); var specifier = tree.GetRoot().DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single(); Assert.Equal("[]", specifier.ToString()); var newSpecifier = specifier.Update( specifier.OpenBracketToken, SyntaxFactory.SeparatedList<ExpressionSyntax>( new[] { SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(3)) }), specifier.CloseBracketToken); Assert.Equal("[3]", newSpecifier.ToString()); } [Fact] public void TestUnaryNegation() { // This test verifies that we no longer crash hitting an assertion var source = @" public class C<T> { C(C<object> c) => throw null!; void M(bool b) { _ = new C<object>(!b); } public static implicit operator C<T>(T x) => throw null!; } "; var c = CreateCompilation(source, parseOptions: TestOptions.Regular8); c.VerifyDiagnostics(); } [Fact] public void UnconstrainedAndErrorNullableFields() { var source = @" public class C<T> { public T? field; public Unknown? field2; } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // public Unknown? field2; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(5, 12), // (4,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public T? field; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 12)); } [Fact] public void NoNullableAnalysisWithoutNonNullTypes() { var source = @" class C { void M(string z) { z = null; z.ToString(); } } #nullable enable class C2 { void M(string z) { z = null; // 1 z.ToString(); // 2 } } "; var expected = new[] { // (15,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // z = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(15, 13), // (16,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(16, 9) }; var c = CreateCompilation(new[] { source }); c.VerifyDiagnostics(expected); c = CreateCompilation(source, parseOptions: TestOptions.Regular8); c.VerifyDiagnostics(expected); expected = new[] { // (10,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(10, 2) }; var c2 = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); c2.VerifyDiagnostics(expected); } [Fact] public void NonNullTypesOnPartialSymbol() { var source = @" #nullable enable partial class C { #nullable disable partial void M(); } #nullable enable partial class C { #nullable disable partial void M() { } } "; var c = CreateCompilation(new[] { source }); c.VerifyDiagnostics( ); } [Fact] public void SuppressionAsLValue() { var source = @" class C { void M(string? x) { ref string y = ref x; ref string y2 = ref x; (y2! = ref y) = ref y; } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,28): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // ref string y = ref x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("string?", "string").WithLocation(6, 28), // (7,29): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // ref string y2 = ref x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("string?", "string").WithLocation(7, 29), // (8,10): error CS8598: The suppression operator is not allowed in this context // (y2! = ref y) = ref y; Diagnostic(ErrorCode.ERR_IllegalSuppression, "y2").WithLocation(8, 10), // (8,20): warning CS8601: Possible null reference assignment. // (y2! = ref y) = ref y; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(8, 20), // (8,29): warning CS8601: Possible null reference assignment. // (y2! = ref y) = ref y; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(8, 29) ); } [Fact] [WorkItem(31732, "https://github.com/dotnet/roslyn/issues/31732")] public void SuppressionOnUnconstrainedTypeParameter() { var source = @" class C { void M<T>(T t) { t!.ToString(); t.ToString(); } } "; var c = CreateCompilation(new[] { source }); c.VerifyDiagnostics(); c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(31732, "https://github.com/dotnet/roslyn/issues/31732")] public void SuppressionOnNullableValueType() { var source = @" class C { void M(int? i) { i!.Value.ToString(); i.Value.ToString(); } } "; var c = CreateCompilation(new[] { source }); c.VerifyDiagnostics(); c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(31732, "https://github.com/dotnet/roslyn/issues/31732")] public void SuppressionOnNullableValueType_AppliedOnField() { var source = @" public struct S { public string? field; } class C { void M(S? s) { s.Value.field!.ToString(); } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,9): warning CS8629: Nullable value type may be null. // s.Value.field!.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s").WithLocation(10, 9) ); } [Fact] [WorkItem(31732, "https://github.com/dotnet/roslyn/issues/31732")] public void SuppressionOnNullableReferenceType_AppliedOnField() { var source = @" public class C { public string? field; void M(C? c) { c.field!.ToString(); } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // c.field!.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(7, 9) ); } [Fact] [WorkItem(31732, "https://github.com/dotnet/roslyn/issues/31732")] public void SuppressionOnNullableReferenceType_AppliedOnField2() { var source = @" public class C { public string? field; void M1(C? c) { c?.field!.ToString(); c.ToString(); // 1 } void M2(C? c) { c!?.field!.ToString(); c.ToString(); // 2 } void M3(C? c) { _ = c?.field!.ToString()!; c.ToString(); // 3 } void M4(C? c) { (c?.field!.ToString()!).ToString(); c.ToString(); // no warning because 'c' was part of a call receiver in previous line } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c", isSuppressed: false).WithLocation(8, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c", isSuppressed: false).WithLocation(14, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c", isSuppressed: false).WithLocation(20, 9)); } [Fact] [WorkItem(43659, "https://github.com/dotnet/roslyn/issues/43659")] public void SuppressionOnNullableReferenceType_AppliedOnField3() { var source = @" public class C { public string[]? F1; public System.Func<object>? F2; static void M1(C? c) { c?.F1![0].ToString(); c.ToString(); // 1 } static void M2(C? c) { c?.F2!().ToString(); c.ToString(); // 2 } } "; var c = CreateNullableCompilation(source); c.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c", isSuppressed: false).WithLocation(9, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c", isSuppressed: false).WithLocation(14, 9)); } [Fact] [WorkItem(31732, "https://github.com/dotnet/roslyn/issues/31732")] public void SuppressionOnArgument() { var source = @" class C { void M(string? s) { NonNull(s!); s.ToString(); // warn } void NonNull(string s) => throw null!; } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void SuppressionWithoutNonNullTypes() { var source = @" [System.Obsolete("""", true!)] // 1, 2 class C { string x = null!; // 3, 4 static void Main(string z = null!) // 5 { string y = null!; // 6, 7 } } "; var c = CreateCompilation(source); c.VerifyEmitDiagnostics( // (8,16): warning CS0219: The variable 'y' is assigned but its value is never used // string y = null!; // 6, 7 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(8, 16), // (5,12): warning CS0414: The field 'C.x' is assigned but its value is never used // string x = null!; // 3, 4 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x").WithLocation(5, 12) ); } [Fact, WorkItem(26812, "https://github.com/dotnet/roslyn/issues/26812")] public void DoubleAssignment() { CSharpCompilation c = CreateCompilation(new[] { @" using static System.Console; class C { static void Main() { string? x; x = x = """"; WriteLine(x.Length); string? y; x = y = """"; WriteLine(x.Length); WriteLine(y.Length); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact, WorkItem(26746, "https://github.com/dotnet/roslyn/issues/26746")] public void TernaryWithConversionFromExpression() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void M() { uint a = 0; uint x = true ? a : 1; uint y = true ? 1 : a; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact, WorkItem(26746, "https://github.com/dotnet/roslyn/issues/26746")] public void TernaryWithImplicitUsedDefinedConversion_ConstantTrue() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void M() { C c = new C(); C x = true ? c : 1; C y = true ? 1 : c; } public static implicit operator C?(int i) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // C y = true ? 1 : c; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "true ? 1 : c").WithLocation(8, 15) ); } [Fact, WorkItem(26746, "https://github.com/dotnet/roslyn/issues/26746")] public void TernaryWithImplicitUsedDefinedConversion_ConstantFalse() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void M() { C c = new C(); C x = false ? c : 1; C y = false ? 1 : c; } public static implicit operator C?(int i) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // C x = false ? c : 1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "false ? c : 1").WithLocation(7, 15) ); } [Fact, WorkItem(26746, "https://github.com/dotnet/roslyn/issues/26746")] public void TernaryWithImplicitUsedDefinedConversion_NotConstant() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void M(bool b) { C c = new C(); C x = b ? c : 1; C y = b ? 1 : c; } public static implicit operator C?(int i) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // C x = b ? c : 1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b ? c : 1").WithLocation(7, 15), // (8,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // C y = b ? 1 : c; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b ? 1 : c").WithLocation(8, 15) ); } [Fact, WorkItem(26746, "https://github.com/dotnet/roslyn/issues/26746")] public void TernaryWithImplicitUsedDefinedConversion2() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void M() { C c = null!; int x = true ? c : 1; int y = true ? 1 : c; C? c2 = null; int x2 = true ? c2 : 1; int y2 = true ? 1 : c2; } public static implicit operator int(C i) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,25): warning CS8604: Possible null reference argument for parameter 'i' in 'C.implicit operator int(C i)'. // int x2 = true ? c2 : 1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c2").WithArguments("i", "C.implicit operator int(C i)").WithLocation(11, 25) ); } [Fact] public void AnnotationWithoutNonNullTypes() { var source = @" class C<T> where T : class { static string? field = M2(out string? x1); // warn 1 and 2 static string? P // warn 3 { get { string? x2 = null; // warn 4 return x2; } } static string? MethodWithLocalFunction() // warn 5 { string? x3 = local(null); // warn 6 return x3; string? local(C<string?>? x) // warn 7, 8 and 9 { string? x4 = null; // warn 10 return x4; } } static string? Lambda() // warn 11 { System.Func<string?, string?> x5 = (string? x) => // warn 12, 13 and 14 { string? x6 = null; // warn 15 return x6; }; return x5(null); } static string M2(out string? x4) => throw null!; // warn 16 static string M3(C<string?> x, C<string> y) => throw null!; // warn 17 delegate string? MyDelegate(C<string?> x); // warn 18 and 19 event MyDelegate? Event; // warn 20 void M4() { Event(new C<string?>()); } // warn 21 class D<T2> where T2 : T? { } // warn 22 class D2 : C<string?> { } // warn 23 public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 class D3 { D3(C<T?> x) => throw null!; // warn 26 } public string? this[C<string?> x] { get => throw null!; } // warn 27 and 28 } "; var expectedDiagnostics = new[] { // (36,21): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // event MyDelegate? Event; // warn 20 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(36, 21), // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string? P // warn 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18), // (13,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string? MethodWithLocalFunction() // warn 5 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 18), // (24,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string? Lambda() // warn 11 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(24, 18), // (33,32): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string M2(out string? x4) => throw null!; // warn 16 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(33, 32), // (34,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string M3(C<string?> x, C<string> y) => throw null!; // warn 17 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(34, 30), // (40,47): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(40, 47), // (40,46): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(40, 46), // (40,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(40, 22), // (40,21): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(40, 21), // (45,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public string? this[C<string?> x] { get => throw null!; } // warn 27 and 28 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(45, 33), // (45,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public string? this[C<string?> x] { get => throw null!; } // warn 27 and 28 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(45, 18), // (43,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // D3(C<T?> x) => throw null!; // warn 26 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(43, 15), // (43,14): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // D3(C<T?> x) => throw null!; // warn 26 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(43, 14), // (35,20): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // delegate string? MyDelegate(C<string?> x); // warn 18 and 19 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(35, 20), // (35,41): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // delegate string? MyDelegate(C<string?> x); // warn 18 and 19 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(35, 41), // (38,29): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // class D<T2> where T2 : T? { } // warn 22 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(38, 29), // (38,28): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class D<T2> where T2 : T? { } // warn 22 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(38, 28), // (39,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // class D2 : C<string?> { } // warn 23 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(39, 24), // (4,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string? field = M2(out string? x1); // warn 1 and 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 18), // (4,41): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string? field = M2(out string? x1); // warn 1 and 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 41), // (9,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? x2 = null; // warn 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 19), // (15,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? x3 = local(null); // warn 6 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(15, 15), // (20,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? x4 = null; // warn 10 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(20, 19), // (18,31): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? local(C<string?>? x) // warn 7, 8 and 9 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 31), // (18,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? local(C<string?>? x) // warn 7, 8 and 9 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 33), // (18,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? local(C<string?>? x) // warn 7, 8 and 9 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 15), // (26,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // System.Func<string?, string?> x5 = (string? x) => // warn 12, 13 and 14 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(26, 27), // (26,36): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // System.Func<string?, string?> x5 = (string? x) => // warn 12, 13 and 14 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(26, 36), // (26,51): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // System.Func<string?, string?> x5 = (string? x) => // warn 12, 13 and 14 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(26, 51), // (28,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? x6 = null; // warn 15 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(28, 19), // (37,35): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M4() { Event(new C<string?>()); } // warn 21 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(37, 35) }; var c = CreateCompilation(source, parseOptions: TestOptions.Regular8); c.VerifyDiagnostics(expectedDiagnostics); var c2 = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); c2.VerifyDiagnostics( // (18,25): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // string? local(C<string?>? x) // warn 7, 8 and 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("C<T>", "T", "string?").WithLocation(18, 25), // (34,33): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // static string M3(C<string?> x, C<string> y) => throw null!; // warn 17 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "x").WithArguments("C<T>", "T", "string?").WithLocation(34, 33), // (35,35): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // delegate string? MyDelegate(C<string?> x); // warn 18 and 19 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("C<T>", "T", "string?").WithLocation(35, 35), // (37,17): warning CS8602: Dereference of a possibly null reference. // void M4() { Event(new C<string?>()); } // warn 21 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Event").WithLocation(37, 17), // (37,29): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // void M4() { Event(new C<string?>()); } // warn 21 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("C<T>", "T", "string?").WithLocation(37, 29), // (39,11): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // class D2 : C<string?> { } // warn 23 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "D2").WithArguments("C<T>", "T", "string?").WithLocation(39, 11), // (40,34): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "+").WithArguments("C<T>", "T", "T?").WithLocation(40, 34), // (40,50): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "y").WithArguments("C<T>", "T", "T?").WithLocation(40, 50), // (43,18): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // D3(C<T?> x) => throw null!; // warn 26 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "x").WithArguments("C<T>", "T", "T?").WithLocation(43, 18), // (45,36): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // public string? this[C<string?> x] { get => throw null!; } // warn 27 and 28 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "x").WithArguments("C<T>", "T", "string?").WithLocation(45, 36) ); var c3 = CreateCompilation(new[] { source }, options: WithNullableDisable(), parseOptions: TestOptions.Regular8); c3.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void AnnotationWithoutNonNullTypes_GenericType() { var source = @" public class C<T> where T : class { public T? M(T? x1) // warn 1 and 2 { T? y1 = x1; // warn 3 return y1; } } public class E<T> where T : struct { public T? M(T? x2) { T? y2 = x2; return y2; } } "; CSharpCompilation c = CreateCompilation(source, parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (4,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public T? M(T? x1) // warn 1 and 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 18), // (4,17): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public T? M(T? x1) // warn 1 and 2 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 17), // (4,13): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public T? M(T? x1) // warn 1 and 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 13), // (4,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public T? M(T? x1) // warn 1 and 2 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 12), // (6,10): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? y1 = x1; // warn 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 10), // (6,9): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? y1 = x1; // warn 3 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(6, 9) ); var client = @" class Client { void M(C<string> c) { c.M("""").ToString(); } } "; var comp2 = CreateCompilation(new[] { client }, options: WithNullableEnable(), references: new[] { c.ToMetadataReference() }); comp2.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // c.M("").ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"c.M("""")").WithLocation(6, 9) ); c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics(); comp2 = CreateCompilation(new[] { client }, options: WithNullableEnable(), references: new[] { c.EmitToImageReference() }); comp2.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // c.M("").ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"c.M("""")").WithLocation(6, 9) ); comp2 = CreateCompilation(new[] { client }, options: WithNullableEnable(), references: new[] { c.ToMetadataReference() }); comp2.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // c.M("").ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"c.M("""")").WithLocation(6, 9) ); } [Fact] public void AnnotationWithoutNonNullTypes_AttributeArgument() { var source = @"class AAttribute : System.Attribute { internal AAttribute(object o) { } } class B<T> { } [A(typeof(object?))] // 1 class C1 { } [A(typeof(int?))] class C2 { } [A(typeof(B<object?>))] // 2 class C3 { } [A(typeof(B<int?>))] class C4 { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,4): error CS8639: The typeof operator cannot be used on a nullable reference type // [A(typeof(object?))] // 1 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(object?)").WithLocation(6, 4), // (6,17): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // [A(typeof(object?))] // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 17), // (10,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // [A(typeof(B<object?>))] // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 19)); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,4): error CS8639: The typeof operator cannot be used on a nullable reference type // [A(typeof(object?))] // 1 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(object?)").WithLocation(6, 4)); } [Fact] public void Nullable_False_InCSharp7() { var comp = CreateCompilation("", options: WithNullableDisable(), parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); } [Fact] public void NullableOption() { var comp = CreateCompilation("", options: WithNullable(NullableContextOptions.Enable), parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.3", "8.0").WithLocation(1, 1) ); comp = CreateCompilation("", options: WithNullable(NullableContextOptions.Warnings), parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // error CS8630: Invalid 'NullableContextOptions' value: 'Warnings' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Warnings", "7.3", "8.0").WithLocation(1, 1) ); comp = CreateCompilation("", options: WithNullable(NullableContextOptions.Disable), parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(); comp = CreateCompilation("", options: WithNullable(NullableContextOptions.Enable), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation("", options: WithNullable(NullableContextOptions.Warnings), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation("", options: WithNullable(NullableContextOptions.Disable), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(new string[] { }, options: WithNullable(NullableContextOptions.Enable), parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(); comp = CreateCompilation(new string[] { }, options: WithNullable(NullableContextOptions.Enable), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(new string[] { }, options: WithNullable(NullableContextOptions.Warnings), parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(); comp = CreateCompilation(new string[] { }, options: WithNullable(NullableContextOptions.Warnings), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(new string[] { }, options: WithNullable(NullableContextOptions.Disable), parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(); comp = CreateCompilation(new string[] { }, options: WithNullable(NullableContextOptions.Disable), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void NullableAttribute_NotRequiredCSharp7_01() { var source = @"using System.Threading.Tasks; class C { static async Task<string> F() { return await Task.FromResult(default(string)); } }"; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Regular7); comp.VerifyEmitDiagnostics(); } [Fact] public void NullableAttribute_NotRequiredCSharp7_02() { var source = @"using System; using System.Threading.Tasks; class C { static async Task F<T>(Func<Task> f) { await G(async () => { await f(); return default(object); }); } static async Task<TResult> G<TResult>(Func<Task<TResult>> f) { throw new NotImplementedException(); } }"; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Regular7); comp.VerifyEmitDiagnostics( // (13,32): 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<TResult> G<TResult>(Func<Task<TResult>> f) Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "G").WithLocation(13, 32)); } [Fact, WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26618")] public void SuppressionOnNullConvertedToConstrainedTypeParameterType() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public T M<T>() where T : C { return null!; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void MissingInt() { var source0 = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Enum { } public class Attribute { } }"; var comp0 = CreateEmptyCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"enum E { A } class C { int F() => (int)E.A; }"; var comp = CreateEmptyCompilation( source, references: new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (1,6): error CS0518: Predefined type 'System.Int32' is not defined or imported // enum E { A } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "E").WithArguments("System.Int32").WithLocation(1, 6), // (4,5): error CS0518: Predefined type 'System.Int32' is not defined or imported // int F() => (int)E.A; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(4, 5), // (4,17): error CS0518: Predefined type 'System.Int32' is not defined or imported // int F() => (int)E.A; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(4, 17)); } [Fact] public void MissingNullable() { var source = @" namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Enum { } public class Attribute { } }"; var source2 = @" class C<T> where T : struct { void M() { T? local = null; _ = local; } } "; var comp = CreateEmptyCompilation(new[] { source, source2 }); comp.VerifyDiagnostics( // (6,9): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // T? local = null; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T?").WithArguments("System.Nullable`1").WithLocation(6, 9) ); var source3 = @" class C<T> where T : struct { void M(T? nullable) { } } "; var comp2 = CreateEmptyCompilation(new[] { source, source3 }); comp2.VerifyDiagnostics( // (4,12): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // void M(T? nullable) { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T?").WithArguments("System.Nullable`1").WithLocation(4, 12) ); var source4 = @" class C<T> where T : struct { void M<U>() where U : T? { } } "; var comp3 = CreateEmptyCompilation(new[] { source, source4 }); comp3.VerifyDiagnostics( // (4,27): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // void M<U>() where U : T? { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T?").WithArguments("System.Nullable`1").WithLocation(4, 27), // (4,12): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // void M<U>() where U : T? { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "U").WithArguments("System.Nullable`1").WithLocation(4, 12) ); } [Fact] public void UnannotatedAssemblies_01() { var source0 = @"public class A { public static void F(string s) { } }"; var source1 = @"class B { static void Main() { A.F(string.Empty); A.F(null); } }"; TypeWithAnnotations getParameterType(CSharpCompilation c) => c.GetMember<MethodSymbol>("A.F").Parameters[0].TypeWithAnnotations; // 7.0 library var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var compRefs0 = new MetadataReference[] { new CSharpCompilationReference(comp0) }; var metadataRefs0 = new[] { comp0.EmitToImageReference() }; Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp0).NullableAnnotation); // ... used in 7.0. var comp1 = CreateCompilation(source1, references: compRefs0, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(source1, references: metadataRefs0, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); // ... used in 8.0. comp1 = CreateCompilation(source1, references: compRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(source1, references: metadataRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); // 8.0 library comp0 = CreateCompilation(source0); comp0.VerifyDiagnostics(); compRefs0 = new MetadataReference[] { new CSharpCompilationReference(comp0) }; metadataRefs0 = new[] { comp0.EmitToImageReference() }; Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp0).NullableAnnotation); // ... used in 7.0. comp1 = CreateCompilation(source1, references: compRefs0, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(source1, references: metadataRefs0, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); // ... used in 8.0. comp1 = CreateCompilation(source1, references: compRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(source1, references: metadataRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: compRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: metadataRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); // 8.0 library comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); comp0.VerifyDiagnostics(); compRefs0 = new MetadataReference[] { new CSharpCompilationReference(comp0) }; metadataRefs0 = new[] { comp0.EmitToImageReference() }; Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp0).NullableAnnotation); // ... used in 7.0. comp1 = CreateCompilation(source1, references: compRefs0, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(source1, references: metadataRefs0, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp1).NullableAnnotation); // ... used in 8.0. comp1 = CreateCompilation(source1, references: compRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(source1, references: metadataRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: compRefs0); comp1.VerifyDiagnostics( // (6,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // A.F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 13)); Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: metadataRefs0); comp1.VerifyDiagnostics( // (6,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // A.F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 13)); Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp1).NullableAnnotation); } [Fact] public void UnannotatedAssemblies_02() { var source0 = @"#pragma warning disable 67 public delegate void D(); public class C { public object F; public event D E; public object P => null; public object this[object o] => null; public object M(object o) => null; }"; var source1 = @"class P { static void F(C c) { object o; o = c.F; c.E += null; o = c.P; o = c[null]; o = c.M(null); } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); void verify(CSharpCompilation c) { c.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, c.GetMember<FieldSymbol>("C.F").TypeWithAnnotations.NullableAnnotation); Assert.Equal(NullableAnnotation.Oblivious, c.GetMember<EventSymbol>("C.E").TypeWithAnnotations.NullableAnnotation); Assert.Equal(NullableAnnotation.Oblivious, c.GetMember<PropertySymbol>("C.P").TypeWithAnnotations.NullableAnnotation); var indexer = c.GetMember<PropertySymbol>("C.this[]"); Assert.Equal(NullableAnnotation.Oblivious, indexer.TypeWithAnnotations.NullableAnnotation); Assert.Equal(NullableAnnotation.Oblivious, indexer.Parameters[0].TypeWithAnnotations.NullableAnnotation); var method = c.GetMember<MethodSymbol>("C.M"); Assert.Equal(NullableAnnotation.Oblivious, method.ReturnTypeWithAnnotations.NullableAnnotation); Assert.Equal(NullableAnnotation.Oblivious, method.Parameters[0].TypeWithAnnotations.NullableAnnotation); } var comp1A = CreateCompilation(source1, references: new MetadataReference[] { new CSharpCompilationReference(comp0) }); verify(comp1A); var comp1B = CreateCompilation(source1, references: new[] { comp0.EmitToImageReference() }); verify(comp1B); } [Fact] public void UnannotatedAssemblies_03() { var source0 = @"#pragma warning disable 67 public class C { public (object, object) F; public (object, object) P => (null, null); public (object, object) M((object, object) o) => o; }"; var source1 = @"class P { static void F(C c) { (object, object) t; t = c.F; t = c.P; t = c.M((null, null)); } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); void verifyTuple(TypeWithAnnotations type) { var tuple = (NamedTypeSymbol)type.Type; Assert.Equal(NullableAnnotation.Oblivious, tuple.TupleElements[0].TypeWithAnnotations.NullableAnnotation); Assert.Equal(NullableAnnotation.Oblivious, tuple.TupleElements[1].TypeWithAnnotations.NullableAnnotation); } void verify(CSharpCompilation c) { c.VerifyDiagnostics(); verifyTuple(c.GetMember<FieldSymbol>("C.F").TypeWithAnnotations); verifyTuple(c.GetMember<PropertySymbol>("C.P").TypeWithAnnotations); var method = c.GetMember<MethodSymbol>("C.M"); verifyTuple(method.ReturnTypeWithAnnotations); verifyTuple(method.Parameters[0].TypeWithAnnotations); } var comp1A = CreateCompilation(source1, references: new[] { new CSharpCompilationReference(comp0) }); verify(comp1A); var comp1B = CreateCompilation(source1, references: new[] { comp0.EmitToImageReference() }); verify(comp1B); } [Fact] public void UnannotatedAssemblies_04() { var source = @"class A { } class B : A { } interface I<T> where T : A { } abstract class C<T> where T : A { internal abstract void M<U>() where U : T; } class D : C<B>, I<B> { internal override void M<T>() { } }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var derivedType = comp.GetMember<NamedTypeSymbol>("D"); var baseType = derivedType.BaseTypeNoUseSiteDiagnostics; var constraintType = baseType.TypeParameters.Single().ConstraintTypesNoUseSiteDiagnostics.Single(); Assert.Equal(NullableAnnotation.Oblivious, constraintType.NullableAnnotation); var interfaceType = derivedType.Interfaces().Single(); constraintType = interfaceType.TypeParameters.Single().ConstraintTypesNoUseSiteDiagnostics.Single(); Assert.Equal(NullableAnnotation.Oblivious, constraintType.NullableAnnotation); var method = baseType.GetMember<MethodSymbol>("M"); constraintType = method.TypeParameters.Single().ConstraintTypesNoUseSiteDiagnostics.Single(); Assert.Equal(NullableAnnotation.Oblivious, constraintType.NullableAnnotation); } [Fact] public void UnannotatedAssemblies_05() { var source = @"interface I<T> { I<object[]> F(I<T> t); } class C : I<string> { I<object[]> I<string>.F(I<string> s) => null; }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("C"); var interfaceType = type.Interfaces().Single(); var typeArg = interfaceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); Assert.Equal(NullableAnnotation.Oblivious, typeArg.NullableAnnotation); var method = type.GetMember<MethodSymbol>("I<System.String>.F"); Assert.Equal(NullableAnnotation.Oblivious, method.ReturnTypeWithAnnotations.NullableAnnotation); typeArg = ((NamedTypeSymbol)method.ReturnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); Assert.Equal(NullableAnnotation.Oblivious, typeArg.NullableAnnotation); var parameter = method.Parameters.Single(); Assert.Equal(NullableAnnotation.Oblivious, parameter.TypeWithAnnotations.NullableAnnotation); typeArg = ((NamedTypeSymbol)parameter.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); Assert.Equal(NullableAnnotation.Oblivious, typeArg.NullableAnnotation); } [Fact] public void UnannotatedAssemblies_06() { var source0 = @"public class C<T> { public T F; } public class C { public static C<T> Create<T>(T t) => new C<T>(); }"; var source1 = @"class P { static void F(object x, object? y) { object z; z = C.Create(x).F; z = C.Create(y).F; } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { comp0.EmitToImageReference() }); comp1.VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // z = C.Create(y).F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "C.Create(y).F").WithLocation(7, 13)); } [Fact] public void UnannotatedAssemblies_07() { var source0 = @"public interface I { object F(object o); }"; var source1 = @"class A1 : I { object I.F(object? o) => new object(); } class A2 : I { object? I.F(object o) => o; } class B1 : I { public object F(object? o) => new object(); } class B2 : I { public object? F(object o) => o; } class C1 { public object F(object? o) => new object(); } class C2 { public object? F(object o) => o; } class D1 : C1, I { } class D2 : C2, I { } class P { static void F(object? x, A1 a1, A2 a2) { object y; y = ((I)a1).F(x); y = ((I)a2).F(x); } static void F(object? x, B1 b1, B2 b2) { object y; y = b1.F(x); y = b2.F(x); y = ((I)b1).F(x); y = ((I)b2).F(x); } static void F(object? x, D1 d1, D2 d2) { object y; y = d1.F(x); y = d2.F(x); y = ((I)d1).F(x); y = ((I)d2).F(x); } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new MetadataReference[] { new CSharpCompilationReference(comp0) }); comp1.VerifyDiagnostics( // (43,18): warning CS8604: Possible null reference argument for parameter 'o' in 'object? B2.F(object o)'. // y = b2.F(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("o", "object? B2.F(object o)").WithLocation(43, 18), // (43,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = b2.F(x); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b2.F(x)").WithLocation(43, 13), // (51,18): warning CS8604: Possible null reference argument for parameter 'o' in 'object? C2.F(object o)'. // y = d2.F(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("o", "object? C2.F(object o)").WithLocation(51, 18), // (51,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = d2.F(x); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "d2.F(x)").WithLocation(51, 13)); comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { comp0.EmitToImageReference() }); comp1.VerifyDiagnostics( // (43,18): warning CS8604: Possible null reference argument for parameter 'o' in 'object? B2.F(object o)'. // y = b2.F(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("o", "object? B2.F(object o)").WithLocation(43, 18), // (43,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = b2.F(x); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b2.F(x)").WithLocation(43, 13), // (51,18): warning CS8604: Possible null reference argument for parameter 'o' in 'object? C2.F(object o)'. // y = d2.F(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("o", "object? C2.F(object o)").WithLocation(51, 18), // (51,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = d2.F(x); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "d2.F(x)").WithLocation(51, 13)); } [Fact] public void UnannotatedAssemblies_08() { var source0 = @"public interface I { object? F(object? o); object G(object o); }"; var source1 = @"public class A : I { object I.F(object o) => null; object I.G(object o) => null; } public class B : I { public object F(object o) => null; public object G(object o) => null; } public class C { public object F(object o) => null; public object G(object o) => null; } public class D : C { }"; var source2 = @"class P { static void F(object o, A a) { ((I)a).F(o).ToString(); ((I)a).G(null).ToString(); } static void F(object o, B b) { b.F(o).ToString(); b.G(null).ToString(); ((I)b).F(o).ToString(); ((I)b).G(null).ToString(); } static void F(object o, D d) { d.F(o).ToString(); d.G(null).ToString(); ((I)d).F(o).ToString(); ((I)d).G(null).ToString(); } }"; var comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var comp1 = CreateCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var comp2A = CreateCompilation(source2, references: new[] { ref0, ref1 }, parseOptions: TestOptions.Regular7); comp2A.VerifyDiagnostics(); var comp2B = CreateCompilation(source2, references: new[] { ref0, ref1 }); comp2B.VerifyDiagnostics(); var comp2C = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { ref0, ref1 }); comp2C.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // ((I)a).F(o).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((I)a).F(o)").WithLocation(5, 9), // (6,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((I)a).G(null).ToString(); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 18), // (12,9): warning CS8602: Dereference of a possibly null reference. // ((I)b).F(o).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((I)b).F(o)").WithLocation(12, 9), // (13,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((I)b).G(null).ToString(); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 18), // (19,9): warning CS8602: Dereference of a possibly null reference. // ((I)d).F(o).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((I)d).F(o)").WithLocation(19, 9), // (20,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((I)d).G(null).ToString(); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 18)); var comp2D = CreateCompilation(new[] { source2 }, options: WithNullableDisable(), references: new[] { ref0, ref1 }); comp2D.VerifyDiagnostics(); } [Fact] public void UnannotatedAssemblies_09() { var source0 = @"public abstract class A { public abstract object? F(object x, object? y); }"; var source1 = @"public abstract class B : A { public abstract override object F(object x, object y); public abstract object G(object x, object y); }"; var source2 = @"class C1 : B { public override object F(object x, object y) => x; public override object G(object x, object y) => x; } class C2 : B { public override object? F(object? x, object? y) => x; public override object? G(object? x, object? y) => x; } class P { static void F(bool b, object? x, object y, C1 c) { if (b) c.F(x, y).ToString(); if (b) c.G(x, y).ToString(); ((B)c).F(x, y).ToString(); ((B)c).G(x, y).ToString(); ((A)c).F(x, y).ToString(); } static void F(object? x, object y, C2 c) { c.F(x, y).ToString(); c.G(x, y).ToString(); ((B)c).F(x, y).ToString(); ((B)c).G(x, y).ToString(); ((A)c).F(x, y).ToString(); } }"; var comp0 = CreateCompilation(source0); comp0.VerifyDiagnostics( // (3,47): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public abstract object? F(object x, object? y); Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 47), // (3,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public abstract object? F(object x, object? y); Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 27) ); var ref0 = comp0.EmitToImageReference(); var comp1 = CreateCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var comp2 = CreateCompilation(source2, references: new[] { ref0, ref1 }); comp2.VerifyDiagnostics( // (9,37): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override object? G(object? x, object? y) => x; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 37), // (9,48): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override object? G(object? x, object? y) => x; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 48), // (9,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override object? G(object? x, object? y) => x; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 27), // (21,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F(object? x, object y, C2 c) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 25), // (13,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F(bool b, object? x, object y, C1 c) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 33), // (8,37): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override object? F(object? x, object? y) => x; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 37), // (8,48): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override object? F(object? x, object? y) => x; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 48), // (8,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override object? F(object? x, object? y) => x; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 27) ); comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); comp0.VerifyDiagnostics(); ref0 = comp0.EmitToImageReference(); comp1 = CreateCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); ref1 = comp1.EmitToImageReference(); comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { ref0, ref1 }); comp2.VerifyDiagnostics( // (15,20): warning CS8604: Possible null reference argument for parameter 'x' in 'object C1.F(object x, object y)'. // if (b) c.F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "object C1.F(object x, object y)").WithLocation(15, 20), // (16,20): warning CS8604: Possible null reference argument for parameter 'x' in 'object C1.G(object x, object y)'. // if (b) c.G(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "object C1.G(object x, object y)").WithLocation(16, 20), // (19,18): warning CS8604: Possible null reference argument for parameter 'x' in 'object? A.F(object x, object? y)'. // ((A)c).F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "object? A.F(object x, object? y)").WithLocation(19, 18), // (19,9): warning CS8602: Dereference of a possibly null reference. // ((A)c).F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((A)c).F(x, y)").WithLocation(19, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // c.F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F(x, y)").WithLocation(23, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // c.G(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.G(x, y)").WithLocation(24, 9), // (27,18): warning CS8604: Possible null reference argument for parameter 'x' in 'object? A.F(object x, object? y)'. // ((A)c).F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "object? A.F(object x, object? y)").WithLocation(27, 18), // (27,9): warning CS8602: Dereference of a possibly null reference. // ((A)c).F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((A)c).F(x, y)").WithLocation(27, 9)); } [Fact] public void UnannotatedAssemblies_10() { var source0 = @"public abstract class A<T> { public T F; } public sealed class B : A<object> { }"; var source1 = @"class C { static void Main() { B b = new B(); b.F = null; } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var comp1 = CreateCompilation(source1, references: new MetadataReference[] { new CSharpCompilationReference(comp0) }); comp1.VerifyDiagnostics(); comp1 = CreateCompilation(source1, references: new[] { comp0.EmitToImageReference() }); comp1.VerifyDiagnostics(); } [Fact] public void Embedded_WithObsolete() { string source = @" namespace Microsoft.CodeAnalysis { [Embedded] [System.Obsolete(""obsolete"")] class EmbeddedAttribute : System.Attribute { public EmbeddedAttribute() { } } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); Assert.False(comp.GetMember("Microsoft.CodeAnalysis.EmbeddedAttribute").IsImplicitlyDeclared); } [Fact] public void NonNullTypes_Cycle5() { string source = @" namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] class SomeAttribute : Attribute { public SomeAttribute() { } public int Property { get; set; } } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NonNullTypes_Cycle12() { string source = @" [System.Flags] enum E { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NonNullTypes_Cycle13() { string source = @" interface I { } [System.Obsolete(nameof(I2))] interface I2 : I { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NonNullTypes_Cycle15() { string lib_cs = "public class Base { }"; var lib = CreateCompilation(lib_cs, assemblyName: "lib"); string lib2_cs = "public class C : Base { }"; var lib2 = CreateCompilation(lib2_cs, references: new[] { lib.EmitToImageReference() }, assemblyName: "lib2"); string source_cs = @" [D] class DAttribute : C { } "; var comp = CreateCompilation(source_cs, references: new[] { lib2.EmitToImageReference() }); comp.VerifyDiagnostics( // (3,20): error CS0012: The type 'Base' is defined in an assembly that is not referenced. You must add a reference to assembly 'lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class DAttribute : C { } Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Base", "lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(3, 20), // (2,2): error CS0012: The type 'Base' is defined in an assembly that is not referenced. You must add a reference to assembly 'lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // [D] Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("Base", "lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 2), // (2,2): error CS0012: The type 'Base' is defined in an assembly that is not referenced. You must add a reference to assembly 'lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // [D] Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("Base", "lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 2) ); } [Fact] public void NonNullTypes_Cycle16() { string source = @" using System; [AttributeUsage(AttributeTargets.Property)] class AttributeWithProperty : System.ComponentModel.DisplayNameAttribute { public override string DisplayName { get => throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NonNullTypes_OnFields() { var obliviousLib = @" public class Oblivious { public static string s; } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); var lib = @" #nullable enable #pragma warning disable 8618 public class External { public static string s; public static string? ns; #nullable disable public static string fs; #nullable disable public static string? fns; } "; var libComp = CreateCompilation(new[] { lib }, options: WithNullableEnable()); libComp.VerifyDiagnostics( // (13,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static string? fns; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 25) ); var source = @" #nullable disable public class OuterA { #nullable enable public class A { public static string s; public static string? ns; } } // NonNullTypes(true) by default public class B { public static string s; public static string? ns; } #nullable disable public class C { #nullable enable public static string s; #nullable enable public static string? ns; } #nullable disable public class OuterD { public class D { #nullable enable public static string s; #nullable enable public static string? ns; } } public class Oblivious2 { #nullable disable public static string s; #nullable disable public static string? ns; } #nullable enable class E { public void M() { Oblivious.s /*T:string!*/ = null; External.s /*T:string!*/ = null; // warn 1 External.ns /*T:string?*/ = null; External.fs /*T:string!*/ = null; External.fns /*T:string?*/ = null; OuterA.A.s /*T:string!*/ = null; // warn 2 OuterA.A.ns /*T:string?*/ = null; B.s /*T:string!*/ = null; // warn 3 B.ns /*T:string?*/ = null; C.s /*T:string!*/ = null; // warn 4 C.ns /*T:string?*/ = null; OuterD.D.s /*T:string!*/ = null; // warn 5 OuterD.D.ns /*T:string?*/ = null; Oblivious2.s /*T:string!*/ = null; Oblivious2.ns /*T:string?*/ = null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference(), libComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (10,30): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(10, 30), // (18,26): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(18, 26), // (26,26): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(26, 26), // (38,30): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(38, 30), // (49,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static string? ns; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(49, 25), // (58,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // External.s /*T:string!*/ = null; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(58, 36), // (64,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterA.A.s /*T:string!*/ = null; // warn 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(64, 36), // (67,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // B.s /*T:string!*/ = null; // warn 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(67, 29), // (70,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // C.s /*T:string!*/ = null; // warn 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(70, 29), // (73,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterD.D.s /*T:string!*/ = null; // warn 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(73, 36) ); } [Fact] public void SuppressedNullConvertedToUnconstrainedT() { var source = @" public class List2<T> { public T Item { get; set; } = null!; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (2,55): error CS0403: Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead. // public class List2<T> { public T Item { get; set; } = null!; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T").WithLocation(2, 55) ); } [Fact] public void NonNullTypes_OnFields_Nested() { var obliviousLib = @" public class List1<T> { public T Item { get; set; } = default(T); } public class Oblivious { public static List1<string> s; } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); var lib = @" #pragma warning disable 8618 using System.Diagnostics.CodeAnalysis; public class List2<T> { public T Item { get; set; } = default!; } public class External { public static List2<string> s; public static List2<string?> ns; #nullable disable public static List2<string> fs; #nullable disable public static List2<string?> fns; } "; var libComp = CreateCompilation(new[] { lib }, options: WithNullableEnable()); var source = @" public class List3<T> { public T Item { get; set; } = default!; } #nullable disable public class OuterA { #nullable enable public class A { public static List3<string> s; public static List3<string?> ns; } } // NonNullTypes(true) by default public class B { public static List3<string> s; public static List3<string?> ns; } #nullable disable public class OuterD { public class D { #nullable enable public static List3<string> s; #nullable enable public static List3<string?> ns; } } #nullable disable public class Oblivious2 { public static List3<string> s; public static List3<string?> ns; } #nullable enable class E { public void M() { Oblivious.s.Item /*T:string!*/ = null; External.s.Item /*T:string!*/ = null; // warn 1 External.ns.Item /*T:string?*/ = null; External.fs.Item /*T:string!*/ = null; External.fns.Item /*T:string?*/ = null; OuterA.A.s.Item /*T:string!*/ = null; // warn 2 OuterA.A.ns.Item /*T:string?*/ = null; B.s.Item /*T:string!*/ = null; // warn 3 B.ns.Item /*T:string?*/ = null; OuterD.D.s.Item /*T:string!*/ = null; // warn 4 OuterD.D.ns.Item /*T:string?*/ = null; Oblivious2.s.Item /*T:string!*/ = null; Oblivious2.ns.Item /*T:string?*/ = null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference(), libComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (11,37): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static List3<string> s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(11, 37), // (12,38): warning CS8618: Non-nullable field 'ns' is uninitialized. Consider declaring the field as nullable. // public static List3<string?> ns; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "ns").WithArguments("field", "ns").WithLocation(12, 38), // (19,33): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static List3<string> s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(19, 33), // (20,34): warning CS8618: Non-nullable field 'ns' is uninitialized. Consider declaring the field as nullable. // public static List3<string?> ns; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "ns").WithArguments("field", "ns").WithLocation(20, 34), // (29,37): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static List3<string> s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(29, 37), // (31,38): warning CS8618: Non-nullable field 'ns' is uninitialized. Consider declaring the field as nullable. // public static List3<string?> ns; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "ns").WithArguments("field", "ns").WithLocation(31, 38), // (39,31): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public static List3<string?> ns; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(39, 31), // (48,41): warning CS8625: Cannot convert null literal to non-nullable reference type. // External.s.Item /*T:string!*/ = null; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(48, 41), // (54,41): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterA.A.s.Item /*T:string!*/ = null; // warn 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(54, 41), // (57,34): warning CS8625: Cannot convert null literal to non-nullable reference type. // B.s.Item /*T:string!*/ = null; // warn 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(57, 34), // (60,41): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterD.D.s.Item /*T:string!*/ = null; // warn 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(60, 41)); } [Fact] public void NonNullTypes_OnFields_Tuples() { var obliviousLib = @" public class Oblivious { public static (string s, string s2) t; } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); var lib = @" public class External { public static (string s, string? ns) t; } "; var libComp = CreateCompilation(new[] { lib }, options: WithNullableEnable()); var source = @" #nullable disable public class OuterA { #nullable enable public class A { public static (string s, string? ns) t; } } // NonNullTypes(true) by default public class B { public static (string s, string? ns) t; } #nullable disable public class OuterD { public class D { #nullable enable public static (string s, string? ns) t; } } #nullable disable public class Oblivious2 { public static (string s, string? ns) t; } #nullable enable class E { public void M() { Oblivious.t.s /*T:string!*/ = null; External.t.s /*T:string!*/ = null; // warn 1 External.t.ns /*T:string?*/ = null; OuterA.A.t.s /*T:string!*/ = null; // warn 2 OuterA.A.t.ns /*T:string?*/ = null; B.t.s /*T:string!*/ = null; // warn 3 B.t.ns /*T:string?*/ = null; OuterD.D.t.s /*T:string!*/ = null; // warn 4 OuterD.D.t.ns /*T:string?*/ = null; Oblivious2.t.s /*T:string!*/ = null; Oblivious2.t.ns /*T:string?*/ = null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference(), libComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (33,36): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static (string s, string? ns) t; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(33, 36), // (42,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // External.t.s /*T:string!*/ = null; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(42, 38), // (45,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterA.A.t.s /*T:string!*/ = null; // warn 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(45, 38), // (48,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // B.t.s /*T:string!*/ = null; // warn 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(48, 31), // (51,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterD.D.t.s /*T:string!*/ = null; // warn 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(51, 38) ); } [Fact] public void NonNullTypes_OnFields_Arrays() { var obliviousLib = @" public class Oblivious { public static string[] s; } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); var lib = @" #pragma warning disable 8618 public class External { public static string[] s; public static string?[] ns; } "; var libComp = CreateCompilation(new[] { lib }, options: WithNullableEnable()); var source = @" #nullable disable public class OuterA { #nullable enable public class A { public static string[] s; public static string?[] ns; } } // NonNullTypes(true) by default public class B { public static string[] s; public static string?[] ns; } #nullable disable public class OuterD { public class D { #nullable enable public static string[] s; #nullable enable public static string?[] ns; } } #nullable disable public class Oblivious2 { public static string[] s; public static string?[] ns; } #nullable enable class E { public void M() { Oblivious.s[0] /*T:string!*/ = null; External.s[0] /*T:string!*/ = null; // warn 1 External.ns[0] /*T:string?*/ = null; OuterA.A.s[0] /*T:string!*/ = null; // warn 2 OuterA.A.ns[0] /*T:string?*/ = null; B.s[0] /*T:string!*/ = null; // warn 3 B.ns[0] /*T:string?*/ = null; OuterD.D.s[0] /*T:string!*/ = null; // warn 4 OuterD.D.ns[0] /*T:string?*/ = null; Oblivious2.s[0] /*T:string!*/ = null; Oblivious2.ns[0] /*T:string?*/ = null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference(), libComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (10,32): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string[] s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(10, 32), // (11,33): warning CS8618: Non-nullable field 'ns' is uninitialized. Consider declaring the field as nullable. // public static string?[] ns; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "ns").WithArguments("field", "ns").WithLocation(11, 33), // (18,28): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string[] s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(18, 28), // (19,29): warning CS8618: Non-nullable field 'ns' is uninitialized. Consider declaring the field as nullable. // public static string?[] ns; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "ns").WithArguments("field", "ns").WithLocation(19, 29), // (28,32): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string[] s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(28, 32), // (30,33): warning CS8618: Non-nullable field 'ns' is uninitialized. Consider declaring the field as nullable. // public static string?[] ns; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "ns").WithArguments("field", "ns").WithLocation(30, 33), // (38,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static string?[] ns; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(38, 25), // (47,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // External.s[0] /*T:string!*/ = null; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(47, 39), // (50,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterA.A.s[0] /*T:string!*/ = null; // warn 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(50, 39), // (53,32): warning CS8625: Cannot convert null literal to non-nullable reference type. // B.s[0] /*T:string!*/ = null; // warn 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(53, 32), // (56,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterD.D.s[0] /*T:string!*/ = null; // warn 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(56, 39) ); } [Fact] public void NonNullTypes_OnProperties() { var obliviousLib = @" public class Oblivious { public static string s { get; set; } } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); obliviousComp.VerifyDiagnostics(); var lib = @" #pragma warning disable 8618 public class External { public static string s { get; set; } public static string? ns { get; set; } } "; var libComp = CreateCompilation(new[] { lib }, options: WithNullableEnable()); var source = @" #nullable disable public class OuterA { public class A { #nullable enable public static string s { get; set; } #nullable enable public static string? ns { get; set; } } } // NonNullTypes(true) by default public class B { public static string s { get; set; } public static string? ns { get; set; } } #nullable disable public class OuterD { #nullable enable public class D { public static string s { get; set; } public static string? ns { get; set; } } } public class Oblivious2 { #nullable disable public static string s { get; set; } #nullable disable public static string? ns { get; set; } } #nullable enable class E { public void M() { Oblivious.s /*T:string!*/ = null; External.s /*T:string!*/ = null; // warn 1 External.ns /*T:string?*/ = null; OuterA.A.s /*T:string!*/ = null; // warn 2 OuterA.A.ns /*T:string?*/ = null; B.s /*T:string!*/ = null; // warn 3 B.ns /*T:string?*/ = null; OuterD.D.s /*T:string!*/ = null; // warn 4 OuterD.D.ns /*T:string?*/ = null; Oblivious2.s /*T:string!*/ = null; Oblivious2.ns /*T:string?*/ = null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference(), libComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (10,30): warning CS8618: Non-nullable property 's' is uninitialized. Consider declaring the property as nullable. // public static string s { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("property", "s").WithLocation(10, 30), // (19,26): warning CS8618: Non-nullable property 's' is uninitialized. Consider declaring the property as nullable. // public static string s { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("property", "s").WithLocation(19, 26), // (29,30): warning CS8618: Non-nullable property 's' is uninitialized. Consider declaring the property as nullable. // public static string s { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("property", "s").WithLocation(29, 30), // (39,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public static string? ns { get; set; } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(39, 25), // (48,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // External.s /*T:string!*/ = null; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(48, 36), // (51,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterA.A.s /*T:string!*/ = null; // warn 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(51, 36), // (54,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // B.s /*T:string!*/ = null; // warn 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(54, 29), // (57,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterD.D.s /*T:string!*/ = null; // warn 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(57, 36) ); } [Fact] public void NonNullTypes_OnMethods() { var obliviousLib = @" public class Oblivious { public static string Method(string s) => throw null; } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); var lib = @" public class External { public static string Method(string s) => throw null!; public static string? NMethod(string? ns) => throw null!; } "; var libComp = CreateCompilation(new[] { lib }, options: WithNullableEnable()); var source = @" #nullable disable public class OuterA { #nullable enable public class A { public static string Method(string s) => throw null!; public static string? NMethod(string? ns) => throw null!; } } // NonNullTypes(true) by default public class B { public static string Method(string s) => throw null!; public static string? NMethod(string? ns) => throw null!; } #nullable disable public class OuterD { public class D { #nullable enable public static string Method(string s) => throw null!; #nullable enable public static string? NMethod(string? ns) => throw null!; } } #nullable disable public class Oblivious2 { public static string Method(string s) => throw null!; public static string? NMethod(string? ns) => throw null!; } #nullable enable class E { public void M() { Oblivious.Method(null) /*T:string!*/; External.Method(null) /*T:string!*/; // warn 1 External.NMethod(null) /*T:string?*/; OuterA.A.Method(null) /*T:string!*/; // warn 2 OuterA.A.NMethod(null) /*T:string?*/; B.Method(null) /*T:string!*/; // warn 3 B.NMethod(null) /*T:string?*/; OuterD.D.Method(null) /*T:string!*/; // warn 4 OuterD.D.NMethod(null) /*T:string?*/; Oblivious2.Method(null) /*T:string!*/; Oblivious2.NMethod(null) /*T:string?*/; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference(), libComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (38,41): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static string? NMethod(string? ns) => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(38, 41), // (38,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static string? NMethod(string? ns) => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(38, 25), // (47,25): warning CS8625: Cannot convert null literal to non-nullable reference type. // External.Method(null) /*T:string!*/; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(47, 25), // (50,25): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterA.A.Method(null) /*T:string!*/; // warn 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(50, 25), // (53,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // B.Method(null) /*T:string!*/; // warn 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(53, 18), // (56,25): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterD.D.Method(null) /*T:string!*/; // warn 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(56, 25) ); } [Fact] public void NonNullTypes_OnModule() { var obliviousLib = @"#nullable disable public class Oblivious { } "; var obliviousComp = CreateCompilation(new[] { obliviousLib }); obliviousComp.VerifyDiagnostics(); var compilation = CreateCompilation("", options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference() }); compilation.VerifyDiagnostics(); } [Fact] public void NonNullTypes_ValueTypeArgument() { var source = @"#nullable disable class A<T> { } class B { A<byte> P { get; } }"; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); } [WorkItem(28324, "https://github.com/dotnet/roslyn/issues/28324")] [Fact] public void NonNullTypes_GenericOverriddenMethod_ValueType() { var source = @"#nullable disable class C<T> { } abstract class A { internal abstract C<T> F<T>() where T : struct; } class B : A { internal override C<T> F<T>() => throw null!; }"; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); var method = comp.GetMember<MethodSymbol>("A.F"); var typeArg = ((NamedTypeSymbol)method.ReturnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; Assert.True(typeArg.Type.IsValueType); Assert.Equal(NullableAnnotation.Oblivious, typeArg.NullableAnnotation); method = comp.GetMember<MethodSymbol>("B.F"); typeArg = ((NamedTypeSymbol)method.ReturnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; Assert.True(typeArg.Type.IsValueType); Assert.Equal(NullableAnnotation.Oblivious, typeArg.NullableAnnotation); // https://github.com/dotnet/roslyn/issues/29843: Test all combinations of base and derived // including explicit Nullable<T>. } // BoundExpression.Type for Task.FromResult(_f[0]) is Task<T!> // but the inferred type is Task<T~>. [Fact] public void CompareUnannotatedAndNonNullableTypeParameter() { var source = @"#pragma warning disable 0649 using System.Threading.Tasks; class C<T> { T[] _f; Task<T> F() => Task.FromResult(_f[0]); }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8618: Non-nullable field '_f' is uninitialized. Consider declaring the field as nullable. // T[] _f; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "_f").WithArguments("field", "_f").WithLocation(5, 9) ); } [Fact] public void CircularConstraints() { var source = @"class A<T> where T : B<T>.I { internal interface I { } } class B<T> : A<T> where T : A<T>.I { }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular7, skipUsesIsNullable: true); comp.VerifyDiagnostics( // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.0", "8.0").WithLocation(1, 1) ); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(27686, "https://github.com/dotnet/roslyn/issues/27686")] public void AssignObliviousIntoLocals() { var obliviousLib = @" public class Oblivious { public static string f; } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); var source = @" class C { void M() { string s = Oblivious.f; s /*T:string!*/ .ToString(); string ns = Oblivious.f; ns /*T:string!*/ .ToString(); } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics(); } [Fact] public void NonNullTypesTrue_Foreach() { var source = @" class C { #nullable enable public void M2() { foreach (string s in Collection()) { s /*T:string!*/ .ToString(); } foreach (string? ns in NCollection()) { ns /*T:string?*/ .ToString(); // 1 } foreach (var s1 in Collection()) { s1 /*T:string!*/ .ToString(); } foreach (var ns1 in NCollection()) { ns1 /*T:string?*/ .ToString(); // 2 } foreach (string s in FalseCollection()) { s /*T:string!*/ .ToString(); } foreach (string? ns in FalseNCollection()) { ns /*T:string?*/ .ToString(); // 3 } foreach (var s1 in FalseCollection()) { s1 /*T:string!*/ .ToString(); } foreach (var ns1 in FalseNCollection()) { ns1 /*T:string?*/ .ToString(); // 4 } } #nullable enable string[] Collection() => throw null!; #nullable enable string?[] NCollection() => throw null!; #nullable disable string[] FalseCollection() => throw null!; #nullable disable string?[] FalseNCollection() => throw null!; // 5 } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (60,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string?[] FalseNCollection() => throw null!; // 5 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(60, 11), // (16,13): warning CS8602: Dereference of a possibly null reference. // ns /*T:string?*/ .ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns").WithLocation(16, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // ns1 /*T:string?*/ .ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns1").WithLocation(26, 13), // (36,13): warning CS8602: Dereference of a possibly null reference. // ns /*T:string?*/ .ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns").WithLocation(36, 13), // (46,13): warning CS8602: Dereference of a possibly null reference. // ns1 /*T:string?*/ .ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns1").WithLocation(46, 13) ); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypesFalse_Foreach() { var source = @" class C { #nullable disable public void M2() { foreach (string s in Collection()) { s /*T:string!*/ .ToString(); } foreach (string? ns in NCollection()) // 1 { ns /*T:string?*/ .ToString(); } foreach (var s1 in Collection()) { s1 /*T:string!*/ .ToString(); } foreach (var ns1 in NCollection()) { ns1 /*T:string?*/ .ToString(); } foreach (string s in FalseCollection()) { s /*T:string!*/ .ToString(); } foreach (string? ns in FalseNCollection()) // 2 { ns /*T:string?*/ .ToString(); } foreach (var s1 in FalseCollection()) { s1 /*T:string!*/ .ToString(); } foreach (var ns1 in FalseNCollection()) { ns1 /*T:string?*/ .ToString(); } } #nullable enable string[] Collection() => throw null!; #nullable enable string?[] NCollection() => throw null!; #nullable disable string[] FalseCollection() => throw null!; #nullable disable string?[] FalseNCollection() => throw null!; // 3 } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (60,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string?[] FalseNCollection() => throw null!; // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(60, 11), // (14,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // foreach (string? ns in NCollection()) // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 24), // (34,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // foreach (string? ns in FalseNCollection()) // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(34, 24) ); } [Fact] public void NonNullTypesTrue_OutVars() { var source = @" class C { #nullable enable public void M() { Out(out string s2); s2 /*T:string!*/ .ToString(); s2 = null; // 1 NOut(out string? ns2); ns2 /*T:string?*/ .ToString(); // 2 ns2 = null; FalseOut(out string s3); s3 /*T:string!*/ .ToString(); s3 = null; // 3 FalseNOut(out string? ns3); ns3 /*T:string?*/ .ToString(); // 4 ns3 = null; Out(out var s4); s4 /*T:string!*/ .ToString(); s4 = null; NOut(out var ns4); ns4 /*T:string?*/ .ToString(); // 5 ns4 = null; FalseOut(out var s5); s5 /*T:string!*/ .ToString(); s5 = null; FalseNOut(out var ns5); ns5 /*T:string?*/ .ToString(); // 6 ns5 = null; } #nullable enable void Out(out string s) => throw null!; #nullable enable void NOut(out string? ns) => throw null!; #nullable disable void FalseOut(out string s) => throw null!; #nullable disable void FalseNOut(out string? ns) => throw null!; // 7 } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (52,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void FalseNOut(out string? ns) => throw null!; // 7 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(52, 30), // (11,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // s2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 14), // (14,9): warning CS8602: Dereference of a possibly null reference. // ns2 /*T:string?*/ .ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns2").WithLocation(14, 9), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // s3 = null; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 14), // (22,9): warning CS8602: Dereference of a possibly null reference. // ns3 /*T:string?*/ .ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns3").WithLocation(22, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // ns4 /*T:string?*/ .ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns4").WithLocation(30, 9), // (38,9): warning CS8602: Dereference of a possibly null reference. // ns5 /*T:string?*/ .ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns5").WithLocation(38, 9) ); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypesFalse_OutVars() { var source = @" class C { #nullable disable public void M() { Out(out string s2); s2 /*T:string!*/ .ToString(); s2 = null; NOut(out string? ns2); // 1 ns2 /*T:string?*/ .ToString(); // 2 ns2 = null; FalseOut(out string s3); s3 /*T:string!*/ .ToString(); s3 = null; FalseNOut(out string? ns3); // 3 ns3 /*T:string?*/ .ToString(); // 4 ns3 = null; Out(out var s4); s4 /*T:string!*/ .ToString(); s4 = null; // 5 NOut(out var ns4); ns4 /*T:string?*/ .ToString(); // 6 ns4 = null; FalseOut(out var s5); s5 /*T:string!*/ .ToString(); s5 = null; FalseNOut(out var ns5); ns5 /*T:string?*/ .ToString(); // 7 ns5 = null; } #nullable enable void Out(out string s) => throw null!; #nullable enable void NOut(out string? ns) => throw null!; #nullable disable void FalseOut(out string s) => throw null!; #nullable disable void FalseNOut(out string? ns) => throw null!; // 8 } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (52,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void FalseNOut(out string? ns) => throw null!; // 8 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(52, 30), // (13,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // NOut(out string? ns2); // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 24), // (21,29): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // FalseNOut(out string? ns3); // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 29) ); } [Fact] public void NonNullTypesTrue_LocalDeclarations() { var source = @" #nullable enable public class C : Base { public void M() { string s2 = Method(); s2 /*T:string!*/ .ToString(); s2 = null; // warn 1 string? ns2 = NMethod(); ns2 /*T:string?*/ .ToString(); // warn 2 ns2 = null; string s3 = FalseMethod(); s3 /*T:string!*/ .ToString(); s3 = null; // warn 3 string? ns3 = FalseNMethod(); ns3 /*T:string?*/ .ToString(); // warn 4 ns3 = null; var s4 = Method(); s4 /*T:string!*/ .ToString(); s4 = null; var ns4 = NMethod(); ns4 /*T:string?*/ .ToString(); // warn 5 ns4 = null; var s5 = FalseMethod(); s5 /*T:string!*/ .ToString(); s5 = null; var ns5 = FalseNMethod(); ns5 /*T:string?*/ .ToString(); // warn 6 ns5 = null; } } public class Base { #nullable enable public string Method() => throw null!; #nullable enable public string? NMethod() => throw null!; #nullable disable public string FalseMethod() => throw null!; #nullable disable public string? FalseNMethod() => throw null!; // warn 7 } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (54,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public string? FalseNMethod() => throw null!; // warn 7 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(54, 18), // (11,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // s2 = null; // warn 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 14), // (14,9): warning CS8602: Dereference of a possibly null reference. // ns2 /*T:string?*/ .ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns2").WithLocation(14, 9), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // s3 = null; // warn 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 14), // (22,9): warning CS8602: Dereference of a possibly null reference. // ns3 /*T:string?*/ .ToString(); // warn 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns3").WithLocation(22, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // ns4 /*T:string?*/ .ToString(); // warn 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns4").WithLocation(30, 9), // (38,9): warning CS8602: Dereference of a possibly null reference. // ns5 /*T:string?*/ .ToString(); // warn 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns5").WithLocation(38, 9) ); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypesFalse_LocalDeclarations() { var source = @" #nullable disable public class C : Base { public void M() { string s2 = Method(); s2 /*T:string!*/ .ToString(); s2 = null; string? ns2 = NMethod(); // 1 ns2 /*T:string?*/ .ToString(); ns2 = null; string s3 = FalseMethod(); s3 /*T:string!*/ .ToString(); s3 = null; string? ns3 = FalseNMethod(); // 2 ns3 /*T:string?*/ .ToString(); ns3 = null; var s4 = Method(); s4 /*T:string!*/ .ToString(); s4 = null; var ns4 = NMethod(); ns4 /*T:string?*/ .ToString(); ns4 = null; var s5 = FalseMethod(); s5 /*T:string!*/ .ToString(); s5 = null; var ns5 = FalseNMethod(); ns5 /*T:string?*/ .ToString(); ns5 = null; } } public class Base { #nullable enable public string Method() => throw null!; #nullable enable public string? NMethod() => throw null!; #nullable disable public string FalseMethod() => throw null!; #nullable disable public string? FalseNMethod() => throw null!; // 3 } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (54,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public string? FalseNMethod() => throw null!; // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(54, 18), // (13,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? ns2 = NMethod(); // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 15), // (21,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? ns3 = FalseNMethod(); // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 15) ); } [Fact] public void NonNullTypes_Constraint() { var source = @" public class S { } #nullable enable public struct C<T> where T : S { public void M(T t) { t.ToString(); t = null; // warn } } #nullable disable public struct D<T> where T : S { public void M(T t) { t.ToString(); t = null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (11,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // t = null; // warn Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 13) ); } [Fact] public void NonNullTypes_Delegate() { var source = @" #nullable enable public delegate string[] MyDelegate(string[] x); #nullable disable public delegate string[] MyFalseDelegate(string[] x); #nullable enable public delegate string[]? MyNullableDelegate(string[]? x); class C { void M() { MyDelegate x1 = Method; MyDelegate x2 = FalseMethod; MyDelegate x4 = NullableReturnMethod; // warn 1 MyDelegate x5 = NullableParameterMethod; MyFalseDelegate y1 = Method; MyFalseDelegate y2 = FalseMethod; MyFalseDelegate y4 = NullableReturnMethod; MyFalseDelegate y5 = NullableParameterMethod; MyNullableDelegate z1 = Method; // warn 2 MyNullableDelegate z2 = FalseMethod; MyNullableDelegate z4 = NullableReturnMethod; // warn 3 MyNullableDelegate z5 = NullableParameterMethod; } #nullable enable public string[] Method(string[] x) => throw null!; #nullable disable public string[] FalseMethod(string[] x) => throw null!; #nullable enable public string[]? NullableReturnMethod(string[] x) => throw null!; public string[] NullableParameterMethod(string[]? x) => throw null!; } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (18,25): warning CS8621: Nullability of reference types in return type of 'string[]? C.NullableReturnMethod(string[] x)' doesn't match the target delegate 'MyDelegate'. // MyDelegate x4 = NullableReturnMethod; // warn 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "NullableReturnMethod").WithArguments("string[]? C.NullableReturnMethod(string[] x)", "MyDelegate").WithLocation(18, 25), // (24,33): warning CS8622: Nullability of reference types in type of parameter 'x' of 'string[] C.Method(string[] x)' doesn't match the target delegate 'MyNullableDelegate'. // MyNullableDelegate z1 = Method; // warn 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Method").WithArguments("x", "string[] C.Method(string[] x)", "MyNullableDelegate").WithLocation(24, 33), // (26,33): warning CS8622: Nullability of reference types in type of parameter 'x' of 'string[]? C.NullableReturnMethod(string[] x)' doesn't match the target delegate 'MyNullableDelegate'. // MyNullableDelegate z4 = NullableReturnMethod; // warn 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "NullableReturnMethod").WithArguments("x", "string[]? C.NullableReturnMethod(string[] x)", "MyNullableDelegate").WithLocation(26, 33) ); } [Fact] public void NonNullTypes_Constructor() { var source = @" public class C { #nullable enable public C(string[] x) => throw null!; } public class D { #nullable disable public D(string[] x) => throw null!; } #nullable enable public class E { public string[] field = null!; #nullable disable public string[] obliviousField; #nullable enable public string[]? nullableField; void M() { new C(field); new C(obliviousField); new C(nullableField); // warn new D(field); new D(obliviousField); new D(nullableField); } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (27,15): warning CS8604: Possible null reference argument for parameter 'x' in 'C.C(string[] x)'. // new C(nullableField); // warn Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nullableField").WithArguments("x", "C.C(string[] x)").WithLocation(27, 15) ); } [Fact] public void NonNullTypes_Constraint_Nested() { var source = @" public class S { } public class List<T> { public T Item { get; set; } = default!; } #nullable enable public struct C<T, NT> where T : List<S> where NT : List<S?> { public void M(T t, NT nt) { t.Item /*T:S!*/ .ToString(); t.Item = null; // warn 1 nt.Item /*T:S?*/ .ToString(); // warn 2 nt.Item = null; } } #nullable disable public struct D<T, NT> where T : List<S> where NT : List<S?> // warn 3 { public void M(T t, NT nt) { t.Item /*T:S!*/ .ToString(); t.Item = null; nt.Item /*T:S?*/ .ToString(); nt.Item = null; } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (14,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // t.Item = null; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 18), // (15,9): warning CS8602: Dereference of a possibly null reference. // nt.Item /*T:S?*/ .ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "nt.Item").WithLocation(15, 9), // (23,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // where NT : List<S?> // warn 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(23, 22)); } [Fact] public void IsAnnotated_01() { var source = @"using System; class C1 { string F1() => throw null!; string? F2() => throw null!; int F3() => throw null!; int? F4() => throw null!; Nullable<int> F5() => throw null!; } #nullable disable class C2 { string F1() => throw null!; string? F2() => throw null!; int F3() => throw null!; int? F4() => throw null!; Nullable<int> F5() => throw null!; } #nullable enable class C3 { string F1() => throw null!; string? F2() => throw null!; int F3() => throw null!; int? F4() => throw null!; Nullable<int> F5() => throw null!; }"; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (6,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? F2() => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 11), // (15,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? F2() => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(15, 11) ); verify("C1.F1", "System.String", NullableAnnotation.Oblivious); verify("C1.F2", "System.String?", NullableAnnotation.Annotated); verify("C1.F3", "System.Int32", NullableAnnotation.Oblivious); verify("C1.F4", "System.Int32?", NullableAnnotation.Annotated); verify("C1.F5", "System.Int32?", NullableAnnotation.Annotated); verify("C2.F1", "System.String", NullableAnnotation.Oblivious); verify("C2.F2", "System.String?", NullableAnnotation.Annotated); verify("C2.F3", "System.Int32", NullableAnnotation.Oblivious); verify("C2.F4", "System.Int32?", NullableAnnotation.Annotated); verify("C2.F5", "System.Int32?", NullableAnnotation.Annotated); verify("C3.F1", "System.String!", NullableAnnotation.NotAnnotated); verify("C3.F2", "System.String?", NullableAnnotation.Annotated); verify("C3.F3", "System.Int32", NullableAnnotation.NotAnnotated); verify("C3.F4", "System.Int32?", NullableAnnotation.Annotated); verify("C3.F5", "System.Int32?", NullableAnnotation.Annotated); // https://github.com/dotnet/roslyn/issues/29845: Test nested nullability. void verify(string methodName, string displayName, NullableAnnotation nullableAnnotation) { var method = comp.GetMember<MethodSymbol>(methodName); var type = method.ReturnTypeWithAnnotations; Assert.Equal(displayName, type.ToTestDisplayString(true)); Assert.Equal(nullableAnnotation, type.NullableAnnotation); } } [Fact] public void IsAnnotated_02() { var source = @"using System; class C1 { T F1<T>() => throw null!; T? F2<T>() => throw null!; T F3<T>() where T : class => throw null!; T? F4<T>() where T : class => throw null!; T F5<T>() where T : struct => throw null!; T? F6<T>() where T : struct => throw null!; Nullable<T> F7<T>() where T : struct => throw null!; } #nullable disable class C2 { T F1<T>() => throw null!; T? F2<T>() => throw null!; T F3<T>() where T : class => throw null!; T? F4<T>() where T : class => throw null!; T F5<T>() where T : struct => throw null!; T? F6<T>() where T : struct => throw null!; Nullable<T> F7<T>() where T : struct => throw null!; } #nullable enable class C3 { T F1<T>() => throw null!; T? F2<T>() => throw null!; T F3<T>() where T : class => throw null!; T? F4<T>() where T : class => throw null!; T F5<T>() where T : struct => throw null!; T? F6<T>() where T : struct => throw null!; Nullable<T> F7<T>() where T : struct => throw null!; }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (28,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? F2<T>() => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(28, 5), // (17,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? F2<T>() => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 6), // (17,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? F2<T>() => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(17, 5), // (6,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? F2<T>() => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 6), // (6,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? F2<T>() => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(6, 5), // (19,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? F4<T>() where T : class => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(19, 6), // (19,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? F4<T>() where T : class => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(19, 5), // (8,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? F4<T>() where T : class => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 6), // (8,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? F4<T>() where T : class => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 5) ); verify("C1.F1", "T", NullableAnnotation.Oblivious); verify("C1.F2", "T?", NullableAnnotation.Annotated); verify("C1.F3", "T", NullableAnnotation.Oblivious); verify("C1.F4", "T?", NullableAnnotation.Annotated); verify("C1.F5", "T", NullableAnnotation.Oblivious); verify("C1.F6", "T?", NullableAnnotation.Annotated); verify("C1.F7", "T?", NullableAnnotation.Annotated); verify("C2.F1", "T", NullableAnnotation.Oblivious); verify("C2.F2", "T?", NullableAnnotation.Annotated); verify("C2.F3", "T", NullableAnnotation.Oblivious); verify("C2.F4", "T?", NullableAnnotation.Annotated); verify("C2.F5", "T", NullableAnnotation.Oblivious); verify("C2.F6", "T?", NullableAnnotation.Annotated); verify("C2.F7", "T?", NullableAnnotation.Annotated); verify("C3.F1", "T", NullableAnnotation.NotAnnotated); verify("C3.F2", "T?", NullableAnnotation.Annotated); verify("C3.F3", "T!", NullableAnnotation.NotAnnotated); verify("C3.F4", "T?", NullableAnnotation.Annotated); verify("C3.F5", "T", NullableAnnotation.NotAnnotated); verify("C3.F6", "T?", NullableAnnotation.Annotated); verify("C3.F7", "T?", NullableAnnotation.Annotated); // https://github.com/dotnet/roslyn/issues/29845: Test nested nullability. // https://github.com/dotnet/roslyn/issues/29845: Test all combinations of overrides. void verify(string methodName, string displayName, NullableAnnotation nullableAnnotation) { var method = comp.GetMember<MethodSymbol>(methodName); var type = method.ReturnTypeWithAnnotations; Assert.Equal(displayName, type.ToTestDisplayString(true)); Assert.Equal(nullableAnnotation, type.NullableAnnotation); } } [Fact] public void InheritedValueConstraintForNullable1_01() { var source = @" class A { public virtual T? Goo<T>() where T : struct { return null; } } class B : A { public override T? Goo<T>() { return null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); //var a = compilation.GetTypeByMetadataName("A"); //var aGoo = a.GetMember<MethodSymbol>("Goo"); //Assert.Equal("T? A.Goo<T>()", aGoo.ToTestDisplayString()); //var b = compilation.GetTypeByMetadataName("B"); //var bGoo = b.GetMember<MethodSymbol>("Goo"); //Assert.Equal("T? A.Goo<T>()", bGoo.OverriddenMethod.ToTestDisplayString()); compilation.VerifyDiagnostics(); } [Fact] public void InheritedValueConstraintForNullable1_02() { var source = @" class A { public virtual void Goo<T>(T? x) where T : struct { } } class B : A { public override void Goo<T>(T? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); } [Fact] public void InheritedValueConstraintForNullable1_03() { var source = @" class A { public virtual System.Nullable<T> Goo<T>() where T : struct { return null; } } class B : A { public override T? Goo<T>() { return null; } } "; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void InheritedValueConstraintForNullable1_04() { var source = @" class A { public virtual void Goo<T>(System.Nullable<T> x) where T : struct { } } class B : A { public override void Goo<T>(T? x) { } } "; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void InheritedValueConstraintForNullable1_05() { var source = @" class A { public virtual T? Goo<T>() where T : struct { return null; } } class B : A { public override System.Nullable<T> Goo<T>() { return null; } } "; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void InheritedValueConstraintForNullable1_06() { var source = @" class A { public virtual void M1<T>(T? x) where T : struct { } } class B : A { public override void M1<T>(System.Nullable<T> x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.True(m1.Parameters[0].Type.IsValueType); Assert.True(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); } [Fact] public void Overriding_03() { var source = @" class A { public virtual void M1<T>(T? x) where T : class { } public virtual T? M2<T>() where T : class { return null; } } class B : A { public override void M1<T>(T? x) { } public override T? M2<T>() { return null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (16,26): error CS0115: 'B.M1<T>(T?)': no suitable method found to override // public override void M1<T>(T? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("B.M1<T>(T?)").WithLocation(16, 26), // (16,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(T? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(16, 35), // (20,24): error CS0508: 'B.M2<T>()': return type must be 'T' to match overridden member 'A.M2<T>()' // public override T? M2<T>() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("B.M2<T>()", "A.M2<T>()", "T").WithLocation(20, 24), // (20,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? M2<T>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M2").WithArguments("System.Nullable<T>", "T", "T").WithLocation(20, 24)); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.False(m1.Parameters[0].Type.IsReferenceType); Assert.Null(m1.OverriddenMethod); var m2 = b.GetMember<MethodSymbol>("M2"); Assert.True(m2.ReturnType.IsNullableType()); Assert.False(m2.ReturnType.IsReferenceType); Assert.False(m2.OverriddenMethod.ReturnType.IsNullableType()); } [Fact] [WorkItem(29846, "https://github.com/dotnet/roslyn/issues/29846")] public void Overriding_04() { var source = @" class A { public virtual void M1<T>(T? x) where T : struct { } public virtual void M1<T>(T x) { } public virtual void M2<T>(T? x) where T : struct { } public virtual void M2<T>(T x) { } public virtual void M3<T>(T x) { } public virtual void M3<T>(T? x) where T : struct { } } class B : A { public override void M1<T>(T? x) { } public override void M2<T>(T x) { } public override void M3<T>(T? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.True(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); var m2 = b.GetMember<MethodSymbol>("M2"); Assert.False(m2.Parameters[0].Type.IsNullableType()); Assert.False(m2.OverriddenMethod.Parameters[0].Type.IsNullableType()); var m3 = b.GetMember<MethodSymbol>("M3"); Assert.True(m3.Parameters[0].Type.IsNullableType()); Assert.True(m3.OverriddenMethod.Parameters[0].Type.IsNullableType()); } [Fact] [WorkItem(29847, "https://github.com/dotnet/roslyn/issues/29847")] public void Overriding_05() { var source = @" class A { public virtual void M1<T>(T? x) where T : struct { } public virtual void M1<T>(T? x) where T : class { } } class B : A { public override void M1<T>(T? x) { } } class C { public virtual void M2<T>(T? x) where T : class { } public virtual void M2<T>(T? x) where T : struct { } } class D : C { public override void M2<T>(T? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.True(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); var d = compilation.GetTypeByMetadataName("D"); var m2 = d.GetMember<MethodSymbol>("M2"); Assert.True(m2.Parameters[0].Type.IsNullableType()); Assert.True(m2.OverriddenMethod.Parameters[0].Type.IsNullableType()); } [Fact] public void Overriding_06() { var source = @" class A { public virtual void M1<T>(System.Nullable<T> x) where T : struct { } public virtual void M2<T>(T? x) where T : struct { } public virtual void M3<T>(C<T?> x) where T : struct { } public virtual void M4<T>(C<System.Nullable<T>> x) where T : struct { } public virtual void M5<T>(C<T?> x) where T : class { } } class B : A { public override void M1<T>(T? x) { } public override void M2<T>(T? x) { } public override void M3<T>(C<T?> x) { } public override void M4<T>(C<T?> x) { } public override void M5<T>(C<T?> x) { } } class C<T> {} "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (43,26): error CS0115: 'B.M5<T>(C<T?>)': no suitable method found to override // public override void M5<T>(C<T?> x) where T : class Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M5").WithArguments("B.M5<T>(C<T?>)").WithLocation(43, 26), // (43,38): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M5<T>(C<T?> x) where T : class Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(43, 38)); var b = compilation.GetTypeByMetadataName("B"); var m3 = b.GetMember<MethodSymbol>("M3"); var m4 = b.GetMember<MethodSymbol>("M4"); var m5 = b.GetMember<MethodSymbol>("M5"); Assert.True(((NamedTypeSymbol)m3.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m3.OverriddenMethod.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m4.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m4.OverriddenMethod.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m5.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.Null(m5.OverriddenMethod); } [Fact] public void Overriding_07() { var source = @" class A { public void M1<T>(T x) { } } class B : A { public void M1<T>(T? x) where T : struct { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.True(m1.Parameters[0].Type.StrippedType().IsValueType); Assert.Null(m1.OverriddenMethod); } [Fact] public void Overriding_08() { var source = @" class A { public void M1<T>(T x) { } } class B : A { public override void M1<T>(T? x) where T : struct { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (11,26): error CS0115: 'B.M1<T>(T?)': no suitable method found to override // public override void M1<T>(T? x) where T : struct Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("B.M1<T>(T?)").WithLocation(11, 26), // (11,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(T? x) where T : struct Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 35) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.False(m1.Parameters[0].Type.StrippedType().IsValueType); Assert.False(m1.Parameters[0].Type.StrippedType().IsReferenceType); Assert.Null(m1.OverriddenMethod); } [Fact] public void Overriding_09() { var source = @" class A { public void M1<T>(T x) { } public void M2<T>(T? x) { } public void M3<T>(T? x) where T : class { } public void M4<T>(T? x) where T : struct { } } class B : A { public override void M1<T>(T? x) { } public override void M2<T>(T? x) { } public override void M3<T>(T? x) { } public override void M4<T>(T? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (8,23): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void M2<T>(T? x) Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 23), // (27,26): error CS0115: 'B.M2<T>(T?)': no suitable method found to override // public override void M2<T>(T? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M2").WithArguments("B.M2<T>(T?)").WithLocation(27, 26), // (31,26): error CS0115: 'B.M3<T>(T?)': no suitable method found to override // public override void M3<T>(T? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("B.M3<T>(T?)").WithLocation(31, 26), // (35,26): error CS0506: 'B.M4<T>(T?)': cannot override inherited member 'A.M4<T>(T?)' because it is not marked virtual, abstract, or override // public override void M4<T>(T? x) Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M4").WithArguments("B.M4<T>(T?)", "A.M4<T>(T?)").WithLocation(35, 26), // (23,26): error CS0115: 'B.M1<T>(T?)': no suitable method found to override // public override void M1<T>(T? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("B.M1<T>(T?)").WithLocation(23, 26), // (27,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M2<T>(T? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(27, 35), // (31,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M3<T>(T? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(31, 35), // (35,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M4<T>(T? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(35, 35), // (23,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(T? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(23, 35) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); var m2 = b.GetMember<MethodSymbol>("M2"); var m3 = b.GetMember<MethodSymbol>("M3"); var m4 = b.GetMember<MethodSymbol>("M4"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.True(m2.Parameters[0].Type.IsNullableType()); Assert.True(m3.Parameters[0].Type.IsNullableType()); Assert.True(m4.Parameters[0].Type.IsNullableType()); Assert.Null(m1.OverriddenMethod); Assert.Null(m2.OverriddenMethod); Assert.Null(m3.OverriddenMethod); Assert.Null(m4.OverriddenMethod); } [Fact] public void Overriding_10() { var source = @" class A { public virtual void M1<T>(System.Nullable<T> x) where T : class { } } class B : A { public override void M1<T>(T? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (4,50): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public virtual void M1<T>(System.Nullable<T> x) where T : class Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(4, 50), // (11,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(T? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 35) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.NotNull(m1.OverriddenMethod); } [Fact] public void Overriding_11() { var source = @" class A { public virtual C<System.Nullable<T>> M1<T>() where T : class { throw new System.NotImplementedException(); } } class B : A { public override C<T?> M1<T>() { throw new System.NotImplementedException(); } } class C<T> {} "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (4,42): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public virtual C<System.Nullable<T>> M1<T>() where T : class Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M1").WithArguments("System.Nullable<T>", "T", "T").WithLocation(4, 42), // (12,27): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override C<T?> M1<T>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M1").WithArguments("System.Nullable<T>", "T", "T").WithLocation(12, 27) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(((NamedTypeSymbol)m1.ReturnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m1.OverriddenMethod.ReturnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); } [Fact] public void Overriding_12() { var source = @" class A { public virtual string M1() { throw new System.NotImplementedException(); } public virtual string? M2() { throw new System.NotImplementedException(); } public virtual string? M3() { throw new System.NotImplementedException(); } public virtual System.Nullable<string> M4() { throw new System.NotImplementedException(); } public System.Nullable<string> M5() { throw new System.NotImplementedException(); } } class B : A { public override string? M1() { throw new System.NotImplementedException(); } public override string? M2() { throw new System.NotImplementedException(); } public override string M3() { throw new System.NotImplementedException(); } public override string? M4() { throw new System.NotImplementedException(); } public override string? M5() { throw new System.NotImplementedException(); } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (47,29): error CS0508: 'B.M4()': return type must be 'string?' to match overridden member 'A.M4()' // public override string? M4() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M4").WithArguments("B.M4()", "A.M4()", "string?").WithLocation(47, 29), // (52,29): error CS0506: 'B.M5()': cannot override inherited member 'A.M5()' because it is not marked virtual, abstract, or override // public override string? M5() Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M5").WithArguments("B.M5()", "A.M5()").WithLocation(52, 29), // (32,29): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override string? M1() Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M1").WithLocation(32, 29), // (19,44): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public virtual System.Nullable<string> M4() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M4").WithArguments("System.Nullable<T>", "T", "string").WithLocation(19, 44), // (24,36): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public System.Nullable<string> M5() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M5").WithArguments("System.Nullable<T>", "T", "string").WithLocation(24, 36) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.False(m1.ReturnType.IsNullableType()); Assert.False(m1.OverriddenMethod.ReturnType.IsNullableType()); var m4 = b.GetMember<MethodSymbol>("M4"); Assert.False(m4.ReturnType.IsNullableType()); Assert.True(m4.OverriddenMethod.ReturnType.IsNullableType()); var m5 = b.GetMember<MethodSymbol>("M4"); Assert.False(m5.ReturnType.IsNullableType()); } [Fact] public void Overriding_13() { var source = @" class A { public virtual void M1(string x) { } public virtual void M2(string? x) { } public virtual void M3(string? x) { } public virtual void M4(System.Nullable<string> x) { } public void M5(System.Nullable<string> x) { } } class B : A { public override void M1(string? x) { } public override void M2(string? x) { } public override void M3(string x) { } public override void M4(string? x) { } public override void M5(string? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (16,52): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public virtual void M4(System.Nullable<string> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "string").WithLocation(16, 52), // (20,44): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public void M5(System.Nullable<string> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "string").WithLocation(20, 44), // (35,26): warning CS8765: Type of parameter 'x' doesn't match overridden member because of nullability attributes. // public override void M3(string x) Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("x").WithLocation(35, 26), // (39,26): error CS0115: 'B.M4(string?)': no suitable method found to override // public override void M4(string? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M4").WithArguments("B.M4(string?)").WithLocation(39, 26), // (43,26): error CS0115: 'B.M5(string?)': no suitable method found to override // public override void M5(string? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M5").WithArguments("B.M5(string?)").WithLocation(43, 26) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.False(m1.Parameters[0].Type.IsNullableType()); Assert.Equal(NullableAnnotation.Annotated, m1.Parameters[0].TypeWithAnnotations.NullableAnnotation); Assert.True(m1.Parameters[0].Type.IsReferenceType); Assert.False(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); var m4 = b.GetMember<MethodSymbol>("M4"); Assert.False(m4.Parameters[0].Type.IsNullableType()); Assert.Null(m4.OverriddenMethod); var m5 = b.GetMember<MethodSymbol>("M4"); Assert.False(m5.Parameters[0].Type.IsNullableType()); } [Fact] public void Overriding_14() { var source = @" class A { public virtual int M1() { throw new System.NotImplementedException(); } public virtual int? M2() { throw new System.NotImplementedException(); } public virtual int? M3() { throw new System.NotImplementedException(); } public virtual System.Nullable<int> M4() { throw new System.NotImplementedException(); } public System.Nullable<int> M5() { throw new System.NotImplementedException(); } } class B : A { public override int? M1() { throw new System.NotImplementedException(); } public override int? M2() { throw new System.NotImplementedException(); } public override int M3() { throw new System.NotImplementedException(); } public override int? M4() { throw new System.NotImplementedException(); } public override int? M5() { throw new System.NotImplementedException(); } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (42,25): error CS0508: 'B.M3()': return type must be 'int?' to match overridden member 'A.M3()' // public override int M3() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M3").WithArguments("B.M3()", "A.M3()", "int?").WithLocation(42, 25), // (52,26): error CS0506: 'B.M5()': cannot override inherited member 'A.M5()' because it is not marked virtual, abstract, or override // public override int? M5() Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M5").WithArguments("B.M5()", "A.M5()").WithLocation(52, 26), // (32,26): error CS0508: 'B.M1()': return type must be 'int' to match overridden member 'A.M1()' // public override int? M1() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M1").WithArguments("B.M1()", "A.M1()", "int").WithLocation(32, 26) ); var b = compilation.GetTypeByMetadataName("B"); Assert.True(b.GetMember<MethodSymbol>("M1").ReturnType.IsNullableType()); Assert.True(b.GetMember<MethodSymbol>("M2").ReturnType.IsNullableType()); Assert.False(b.GetMember<MethodSymbol>("M3").ReturnType.IsNullableType()); Assert.True(b.GetMember<MethodSymbol>("M4").ReturnType.IsNullableType()); Assert.True(b.GetMember<MethodSymbol>("M5").ReturnType.IsNullableType()); } [Fact] public void Overriding_15() { var source = @" class A { public virtual void M1(int x) { } public virtual void M2(int? x) { } public virtual void M3(int? x) { } public virtual void M4(System.Nullable<int> x) { } public void M5(System.Nullable<int> x) { } } class B : A { public override void M1(int? x) { } public override void M2(int? x) { } public override void M3(int x) { } public override void M4(int? x) { } public override void M5(int? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (35,26): error CS0115: 'B.M3(int)': no suitable method found to override // public override void M3(int x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("B.M3(int)").WithLocation(35, 26), // (43,26): error CS0506: 'B.M5(int?)': cannot override inherited member 'A.M5(int?)' because it is not marked virtual, abstract, or override // public override void M5(int? x) Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M5").WithArguments("B.M5(int?)", "A.M5(int?)").WithLocation(43, 26), // (27,26): error CS0115: 'B.M1(int?)': no suitable method found to override // public override void M1(int? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("B.M1(int?)").WithLocation(27, 26) ); var b = compilation.GetTypeByMetadataName("B"); Assert.True(b.GetMember<MethodSymbol>("M1").Parameters[0].Type.IsNullableType()); Assert.True(b.GetMember<MethodSymbol>("M2").Parameters[0].Type.IsNullableType()); Assert.False(b.GetMember<MethodSymbol>("M3").Parameters[0].Type.IsNullableType()); Assert.True(b.GetMember<MethodSymbol>("M4").Parameters[0].Type.IsNullableType()); Assert.True(b.GetMember<MethodSymbol>("M5").Parameters[0].Type.IsNullableType()); } [Fact] public void Overriding_16() { var source = @" class C { public static void Main() { } } abstract class A { public abstract event System.Action<string> E1; public abstract event System.Action<string>? E2; public abstract event System.Action<string?>? E3; } class B1 : A { public override event System.Action<string?> E1 {add {} remove{}} public override event System.Action<string> E2 {add {} remove{}} public override event System.Action<string?>? E3 {add {} remove{}} } class B2 : A { public override event System.Action<string?> E1; // 2 public override event System.Action<string> E2; // 2 public override event System.Action<string?>? E3; // 2 void Dummy() { var e1 = E1; var e2 = E2; var e3 = E3; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (18,50): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event System.Action<string?> E1 {add {} remove{}} Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E1").WithLocation(18, 50), // (19,49): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event System.Action<string> E2 {add {} remove{}} Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E2").WithLocation(19, 49), // (25,50): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event System.Action<string?> E1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E1").WithLocation(25, 50), // (25,50): warning CS8618: Non-nullable event 'E1' is uninitialized. Consider declaring the event as nullable. // public override event System.Action<string?> E1; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(25, 50), // (26,49): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event System.Action<string> E2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E2").WithLocation(26, 49), // (26,49): warning CS8618: Non-nullable event 'E2' is uninitialized. Consider declaring the event as nullable. // public override event System.Action<string> E2; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E2").WithArguments("event", "E2").WithLocation(26, 49) ); foreach (string typeName in new[] { "B1", "B2" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (string memberName in new[] { "E1", "E2" }) { var member = type.GetMember<EventSymbol>(memberName); Assert.False(member.TypeWithAnnotations.Equals(member.OverriddenEvent.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } var e3 = type.GetMember<EventSymbol>("E3"); Assert.True(e3.TypeWithAnnotations.Equals(e3.OverriddenEvent.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "A", "B1", "B2" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var ev in type.GetMembers().OfType<EventSymbol>()) { Assert.True(ev.TypeWithAnnotations.Equals(ev.AddMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(ev.TypeWithAnnotations.Equals(ev.RemoveMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] [WorkItem(29851, "https://github.com/dotnet/roslyn/issues/29851")] public void Overriding_Methods() { var source = @" public abstract class A { #nullable disable public abstract System.Action<string> Oblivious1(System.Action<string> x); #nullable enable public abstract System.Action<string> Oblivious2(System.Action<string> x); public abstract System.Action<string> M3(System.Action<string> x); public abstract System.Action<string> M4(System.Action<string> x); public abstract System.Action<string>? M5(System.Action<string>? x); } public class B1 : A { public override System.Action<string?> Oblivious1(System.Action<string?> x) => throw null!; public override System.Action<string?> Oblivious2(System.Action<string?> x) => throw null!; // warn 3 and 4 // https://github.com/dotnet/roslyn/issues/29851: Should not warn public override System.Action<string?> M3(System.Action<string?> x) => throw null!; // warn 5 and 6 public override System.Action<string?> M4(System.Action<string?> x) => throw null!; // warn 7 and 8 public override System.Action<string?> M5(System.Action<string?> x) => throw null!; // warn 9 and 10 } public class B2 : A { public override System.Action<string> Oblivious1(System.Action<string> x) => throw null!; public override System.Action<string> Oblivious2(System.Action<string> x) => throw null!; #nullable disable public override System.Action<string> M3(System.Action<string> x) => throw null!; #nullable enable public override System.Action<string> M4(System.Action<string> x) => throw null!; #nullable disable public override System.Action<string> M5(System.Action<string> x) => throw null!; } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (18,44): warning CS8610: Nullability of reference types in type of parameter 'x' doesn't match overridden member. // public override System.Action<string?> Oblivious2(System.Action<string?> x) => throw null!; // warn 3 and 4 // https://github.com/dotnet/roslyn/issues/29851: Should not warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "Oblivious2").WithArguments("x").WithLocation(18, 44), // (19,44): warning CS8610: Nullability of reference types in type of parameter 'x' doesn't match overridden member. // public override System.Action<string?> M3(System.Action<string?> x) => throw null!; // warn 5 and 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("x").WithLocation(19, 44), // (20,44): warning CS8610: Nullability of reference types in type of parameter 'x' doesn't match overridden member. // public override System.Action<string?> M4(System.Action<string?> x) => throw null!; // warn 7 and 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M4").WithArguments("x").WithLocation(20, 44), // (21,44): warning CS8610: Nullability of reference types in type of parameter 'x' doesn't match overridden member. // public override System.Action<string?> M5(System.Action<string?> x) => throw null!; // warn 9 and 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M5").WithArguments("x").WithLocation(21, 44) ); var b1 = compilation.GetTypeByMetadataName("B1"); verifyMethodMatchesOverridden(expectMatch: false, b1, "Oblivious1"); verifyMethodMatchesOverridden(expectMatch: false, b1, "Oblivious2"); verifyMethodMatchesOverridden(expectMatch: false, b1, "M3"); verifyMethodMatchesOverridden(expectMatch: false, b1, "M4"); verifyMethodMatchesOverridden(expectMatch: false, b1, "M5"); var b2 = compilation.GetTypeByMetadataName("B2"); verifyMethodMatchesOverridden(expectMatch: false, b2, "Oblivious1"); // https://github.com/dotnet/roslyn/issues/29851: They should match verifyMethodMatchesOverridden(expectMatch: true, b2, "Oblivious2"); // https://github.com/dotnet/roslyn/issues/29851: They should not match verifyMethodMatchesOverridden(expectMatch: false, b2, "M3"); verifyMethodMatchesOverridden(expectMatch: true, b2, "M4"); // https://github.com/dotnet/roslyn/issues/29851: They should not match verifyMethodMatchesOverridden(expectMatch: false, b2, "M5"); void verifyMethodMatchesOverridden(bool expectMatch, NamedTypeSymbol type, string methodName) { var member = type.GetMember<MethodSymbol>(methodName); Assert.Equal(expectMatch, member.ReturnTypeWithAnnotations.Equals(member.OverriddenMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.Equal(expectMatch, member.Parameters.Single().TypeWithAnnotations.Equals(member.OverriddenMethod.Parameters.Single().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } [Fact] public void Overriding_Properties_WithNullableTypeArgument() { var source = @" #nullable enable public class List<T> { } public class Base<T> { public virtual List<T?> P { get; set; } = default; } public class Class<T> : Base<T> { #nullable disable public override List<T?> P { get; set; } = default; } "; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public virtual List<T?> P { get; set; } = default; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 25), // (7,47): warning CS8625: Cannot convert null literal to non-nullable reference type. // public virtual List<T?> P { get; set; } = default; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(7, 47), // (12,26): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public override List<T?> P { get; set; } = default; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(12, 26), // (12,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override List<T?> P { get; set; } = default; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(12, 27) ); } [Fact] public void Overriding_Properties_WithNullableTypeArgument_WithClassConstraint() { var source = @" #nullable enable public class List<T> { } public class Base<T> where T : class { public virtual List<T?> P { get; set; } = default; } public class Class<T> : Base<T> where T : class { #nullable disable public override List<T?> P { get; set; } = default; } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (7,47): warning CS8625: Cannot convert null literal to non-nullable reference type. // public virtual List<T?> P { get; set; } = default; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(7, 47), // (12,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override List<T?> P { get; set; } = default; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(12, 27) ); } [Fact] public void Overriding_Properties_WithNullableTypeArgument_WithStructConstraint() { var source = @" public class List<T> { } public class Base<T> where T : struct { public virtual List<T?> P { get; set; } = default; } public class Class<T> : Base<T> where T : struct { #nullable disable public override List<T?> P { get; set; } = default; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,47): warning CS8625: Cannot convert null literal to non-nullable reference type. // public virtual List<T?> P { get; set; } = default; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(6, 47)); } [Fact] public void Overriding_Indexer() { var source = @" public class List<T> { } public class Base { public virtual List<string[]> this[List<string[]> x] { get => throw null!; set => throw null!; } } public class Class : Base { #nullable disable public override List<string[]> this[List<string[]> x] { get => throw null!; set => throw null!; } } public class Class2 : Base { #nullable enable public override List<string[]> this[List<string[]> x] { get => throw null!; set => throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Overriding_Indexer2() { var source = @" #nullable enable public class List<T> { } public class Oblivious { #nullable disable public virtual List<string[]> this[List<string[]> x] { get => throw null!; set => throw null!; } } #nullable enable public class Class : Oblivious { public override List<string[]> this[List<string[]> x] { get => throw null!; set => throw null!; } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); } [Fact] public void Overriding_21() { var source = @" class C { public static void Main() { } } abstract class A { public abstract event System.Action<string> E1; public abstract event System.Action<string>? E2; } class B1 : A { #nullable disable annotations public override event System.Action<string?> E1 {add {} remove{}} // 1 #nullable disable annotations public override event System.Action<string> E2 {add {} remove{}} } #nullable enable class B2 : A { #nullable disable annotations public override event System.Action<string?> E1; // 3 #nullable disable annotations public override event System.Action<string> E2; #nullable enable void Dummy() { var e1 = E1; var e2 = E2; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (19,47): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override event System.Action<string?> E1 {add {} remove{}} // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(19, 47), // (19,50): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event System.Action<string?> E1 {add {} remove{}} // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E1").WithLocation(19, 50), // (27,47): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override event System.Action<string?> E1; // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(27, 47), // (27,50): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event System.Action<string?> E1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E1").WithLocation(27, 50) ); } [Fact] public void Implementing_01() { var source = @" class C { public static void Main() { } } interface IA { event System.Action<string> E1; event System.Action<string>? E2; event System.Action<string?>? E3; } class B1 : IA { public event System.Action<string?> E1 {add {} remove{}} public event System.Action<string> E2 {add {} remove{}} public event System.Action<string?>? E3 {add {} remove{}} } class B2 : IA { public event System.Action<string?> E1; // 2 public event System.Action<string> E2; // 2 public event System.Action<string?>? E3; // 2 void Dummy() { var e1 = E1; var e2 = E2; var e3 = E3; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (26,40): warning CS8612: Nullability of reference types in type of 'event Action<string> B2.E2' doesn't match implicitly implemented member 'event Action<string>? IA.E2'. // public event System.Action<string> E2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "E2").WithArguments("event Action<string> B2.E2", "event Action<string>? IA.E2").WithLocation(26, 40), // (25,41): warning CS8612: Nullability of reference types in type of 'event Action<string?> B2.E1' doesn't match implicitly implemented member 'event Action<string> IA.E1'. // public event System.Action<string?> E1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "E1").WithArguments("event Action<string?> B2.E1", "event Action<string> IA.E1").WithLocation(25, 41), // (19,40): warning CS8612: Nullability of reference types in type of 'event Action<string> B1.E2' doesn't match implicitly implemented member 'event Action<string>? IA.E2'. // public event System.Action<string> E2 {add {} remove{}} Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "E2").WithArguments("event Action<string> B1.E2", "event Action<string>? IA.E2").WithLocation(19, 40), // (18,41): warning CS8612: Nullability of reference types in type of 'event Action<string?> B1.E1' doesn't match implicitly implemented member 'event Action<string> IA.E1'. // public event System.Action<string?> E1 {add {} remove{}} Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "E1").WithArguments("event Action<string?> B1.E1", "event Action<string> IA.E1").WithLocation(18, 41), // (25,41): warning CS8618: Non-nullable event 'E1' is uninitialized. Consider declaring the event as nullable. // public event System.Action<string?> E1; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(25, 41), // (26,40): warning CS8618: Non-nullable event 'E2' is uninitialized. Consider declaring the event as nullable. // public event System.Action<string> E2; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E2").WithArguments("event", "E2").WithLocation(26, 40) ); var ia = compilation.GetTypeByMetadataName("IA"); foreach (string memberName in new[] { "E1", "E2" }) { var member = ia.GetMember<EventSymbol>(memberName); foreach (string typeName in new[] { "B1", "B2" }) { var type = compilation.GetTypeByMetadataName(typeName); var impl = (EventSymbol)type.FindImplementationForInterfaceMember(member); Assert.False(impl.TypeWithAnnotations.Equals(member.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } var e3 = ia.GetMember<EventSymbol>("E3"); foreach (string typeName in new[] { "B1", "B2" }) { var type = compilation.GetTypeByMetadataName(typeName); var impl = (EventSymbol)type.FindImplementationForInterfaceMember(e3); Assert.True(impl.TypeWithAnnotations.Equals(e3.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA", "B1", "B2" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var ev in type.GetMembers().OfType<EventSymbol>()) { Assert.True(ev.TypeWithAnnotations.Equals(ev.AddMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(ev.TypeWithAnnotations.Equals(ev.RemoveMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Implementing_02() { var source = @" class C { public static void Main() { } } interface IA { event System.Action<string> E1; event System.Action<string>? E2; event System.Action<string?>? E3; } class B1 : IA { event System.Action<string?> IA.E1 {add {} remove{}} event System.Action<string> IA.E2 {add {} remove{}} event System.Action<string?>? IA.E3 {add {} remove{}} } interface IB { //event System.Action<string> E1; //event System.Action<string>? E2; event System.Action<string?>? E3; } class B2 : IB { //event System.Action<string?> IB.E1; // 2 //event System.Action<string> IB.E2; // 2 event System.Action<string?>? IB.E3; // 2 } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (34,38): error CS0071: An explicit interface implementation of an event must use event accessor syntax // event System.Action<string?>? IB.E3; // 2 Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "E3").WithLocation(34, 38), // (30,12): error CS0535: 'B2' does not implement interface member 'IB.E3.remove' // class B2 : IB Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IB").WithArguments("B2", "IB.E3.remove").WithLocation(30, 12), // (30,12): error CS0535: 'B2' does not implement interface member 'IB.E3.add' // class B2 : IB Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IB").WithArguments("B2", "IB.E3.add").WithLocation(30, 12), // (19,36): warning CS8615: Nullability of reference types in type doesn't match implemented member 'event Action<string>? IA.E2'. // event System.Action<string> IA.E2 {add {} remove{}} Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, "E2").WithArguments("event Action<string>? IA.E2").WithLocation(19, 36), // (18,37): warning CS8615: Nullability of reference types in type doesn't match implemented member 'event Action<string> IA.E1'. // event System.Action<string?> IA.E1 {add {} remove{}} Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, "E1").WithArguments("event Action<string> IA.E1").WithLocation(18, 37) ); var ia = compilation.GetTypeByMetadataName("IA"); var b1 = compilation.GetTypeByMetadataName("B1"); foreach (string memberName in new[] { "E1", "E2" }) { var member = ia.GetMember<EventSymbol>(memberName); var impl = (EventSymbol)b1.FindImplementationForInterfaceMember(member); Assert.False(impl.TypeWithAnnotations.Equals(member.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } var e3 = ia.GetMember<EventSymbol>("E3"); { var impl = (EventSymbol)b1.FindImplementationForInterfaceMember(e3); Assert.True(impl.TypeWithAnnotations.Equals(e3.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA", "B1" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var ev in type.GetMembers().OfType<EventSymbol>()) { Assert.True(ev.TypeWithAnnotations.Equals(ev.AddMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(ev.TypeWithAnnotations.Equals(ev.RemoveMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Overriding_17() { var source = @"#pragma warning disable 8618 class C { public static void Main() { } } abstract class A1 { public abstract string?[] P1 {get; set;} public abstract string[] P2 {get; set;} public abstract string?[] this[int x] {get; set;} public abstract string[] this[short x] {get; set;} } abstract class A2 { public abstract string?[]? P3 {get; set;} public abstract string?[]? this[long x] {get; set;} } class B1 : A1 { public override string[] P1 {get; set;} public override string[]? P2 {get; set;} public override string[] this[int x] // 1 { get {throw new System.NotImplementedException();} set {} } public override string[]? this[short x] // 2 { get {throw new System.NotImplementedException();} set {} } } class B2 : A2 { public override string?[]? P3 {get; set;} public override string?[]? this[long x] // 3 { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (27,39): warning CS8610: Nullability of reference types in type of parameter 'value' doesn't match overridden member. // public override string[] P1 {get; set;} Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(27, 39), // (28,35): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override string[]? P2 {get; set;} Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(28, 35), // (33,9): warning CS8610: Nullability of reference types in type of parameter 'value' doesn't match overridden member. // set {} Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(33, 9), // (38,9): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // get {throw new System.NotImplementedException();} Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(38, 9) ); foreach (var member in compilation.GetTypeByMetadataName("B1").GetMembers().OfType<PropertySymbol>()) { Assert.False(member.TypeWithAnnotations.Equals(member.OverriddenProperty.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (var member in compilation.GetTypeByMetadataName("B2").GetMembers().OfType<PropertySymbol>()) { Assert.True(member.TypeWithAnnotations.Equals(member.OverriddenProperty.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "A1", "B1", "A2", "B2" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var property in type.GetMembers().OfType<PropertySymbol>()) { Assert.True(property.TypeWithAnnotations.Equals(property.GetMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(property.TypeWithAnnotations.Equals(property.SetMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Overriding_22() { var source = @"#pragma warning disable 8618 class C { public static void Main() { } } abstract class A1 { public abstract string?[] P1 {get; set;} // 1 public abstract string[] P2 {get; set;} public abstract string?[] this[int x] {get; set;} // 2 public abstract string[] this[short x] {get; set;} } class B1 : A1 { #nullable disable public override string[] P1 {get; set;} #nullable disable public override string[]? P2 {get; set;} // 3 #nullable disable public override string[] this[int x] { get {throw new System.NotImplementedException();} set {} } #nullable disable public override string[]? this[short x] // 4 { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }); compilation.VerifyDiagnostics( // (14,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public abstract string?[] this[int x] {get; set;} // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 27), // (11,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public abstract string?[] P1 {get; set;} // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 27), // (23,29): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override string[]? P2 {get; set;} // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(23, 29), // (33,29): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override string[]? this[short x] // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(33, 29) ); } [Fact] public void Implementing_03() { var source = @"#pragma warning disable 8618 class C { public static void Main() { } } interface IA { string?[] P1 {get; set;} string[] P2 {get; set;} string?[] this[int x] {get; set;} string[] this[short x] {get; set;} } interface IA2 { string?[]? P3 {get; set;} string?[]? this[long x] {get; set;} } class B : IA, IA2 { public string[] P1 {get; set;} public string[]? P2 {get; set;} public string?[]? P3 {get; set;} public string[] this[int x] { get {throw new System.NotImplementedException();} set {} // 1 } public string[]? this[short x] { get {throw new System.NotImplementedException();} // 2 set {} } public string?[]? this[long x] { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (23,26): warning CS8766: Nullability of reference types in return type of 'string[]? B.P2.get' doesn't match implicitly implemented member 'string[] IA.P2.get' (possibly because of nullability attributes). // public string[]? P2 {get; set;} Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("string[]? B.P2.get", "string[] IA.P2.get").WithLocation(23, 26), // (29,9): warning CS8614: Nullability of reference types in type of parameter 'value' of 'void B.this[int x].set' doesn't match implicitly implemented member 'void IA.this[int x].set'. // set {} // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void B.this[int x].set", "void IA.this[int x].set").WithLocation(29, 9), // (34,9): warning CS8766: Nullability of reference types in return type of 'string[]? B.this[short x].get' doesn't match implicitly implemented member 'string[] IA.this[short x].get' (possibly because of nullability attributes). // get {throw new System.NotImplementedException();} // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("string[]? B.this[short x].get", "string[] IA.this[short x].get").WithLocation(34, 9), // (22,30): warning CS8614: Nullability of reference types in type of parameter 'value' of 'void B.P1.set' doesn't match implicitly implemented member 'void IA.P1.set'. // public string[] P1 {get; set;} Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void B.P1.set", "void IA.P1.set").WithLocation(22, 30) ); var b = compilation.GetTypeByMetadataName("B"); foreach (var member in compilation.GetTypeByMetadataName("IA").GetMembers().OfType<PropertySymbol>()) { var impl = (PropertySymbol)b.FindImplementationForInterfaceMember(member); Assert.False(impl.TypeWithAnnotations.Equals(member.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (var member in compilation.GetTypeByMetadataName("IA2").GetMembers().OfType<PropertySymbol>()) { var impl = (PropertySymbol)b.FindImplementationForInterfaceMember(member); Assert.True(impl.TypeWithAnnotations.Equals(member.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA", "IA2", "B" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var property in type.GetMembers().OfType<PropertySymbol>()) { Assert.True(property.TypeWithAnnotations.Equals(property.GetMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(property.TypeWithAnnotations.Equals(property.SetMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Implementing_04() { var source = @"#pragma warning disable 8618 class C { public static void Main() { } } interface IA { string?[] P1 {get; set;} string[] P2 {get; set;} string?[] this[int x] {get; set;} string[] this[short x] {get; set;} } interface IA2 { string?[]? P3 {get; set;} string?[]? this[long x] {get; set;} } class B : IA, IA2 { string[] IA.P1 {get; set;} string[]? IA.P2 {get; set;} string?[]? IA2.P3 {get; set;} string[] IA.this[int x] { get {throw new System.NotImplementedException();} set {} // 1 } string[]? IA.this[short x] { get {throw new System.NotImplementedException();} // 2 set {} } string?[]? IA2.this[long x] { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (22,26): warning CS8617: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void IA.P1.set'. // string[] IA.P1 {get; set;} Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void IA.P1.set").WithLocation(22, 26), // (23,22): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'string[] IA.P2.get' (possibly because of nullability attributes). // string[]? IA.P2 {get; set;} Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("string[] IA.P2.get").WithLocation(23, 22), // (29,9): warning CS8617: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void IA.this[int x].set'. // set {} // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void IA.this[int x].set").WithLocation(29, 9), // (34,9): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'string[] IA.this[short x].get' (possibly because of nullability attributes). // get {throw new System.NotImplementedException();} // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("string[] IA.this[short x].get").WithLocation(34, 9) ); var b = compilation.GetTypeByMetadataName("B"); foreach (var member in compilation.GetTypeByMetadataName("IA").GetMembers().OfType<PropertySymbol>()) { var impl = (PropertySymbol)b.FindImplementationForInterfaceMember(member); Assert.False(impl.TypeWithAnnotations.Equals(member.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (var member in compilation.GetTypeByMetadataName("IA2").GetMembers().OfType<PropertySymbol>()) { var impl = (PropertySymbol)b.FindImplementationForInterfaceMember(member); Assert.True(impl.TypeWithAnnotations.Equals(member.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA", "IA2", "B" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var property in type.GetMembers().OfType<PropertySymbol>()) { Assert.True(property.TypeWithAnnotations.Equals(property.GetMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(property.TypeWithAnnotations.Equals(property.SetMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Overriding_18() { var source = @" class C { public static void Main() { } } abstract class A { public abstract string[] M1(); public abstract T[] M2<T>() where T : class; public abstract T?[]? M3<T>() where T : class; } class B : A { public override string?[] M1() { return new string?[] {}; } public override S?[] M2<S>() { return new S?[] {}; } public override S?[]? M3<S>() { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (23,26): error CS0508: 'B.M2<S>()': return type must be 'S[]' to match overridden member 'A.M2<T>()' // public override S?[] M2<S>() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("B.M2<S>()", "A.M2<T>()", "S[]").WithLocation(23, 26), // (28,27): error CS0508: 'B.M3<S>()': return type must be 'S?[]' to match overridden member 'A.M3<T>()' // public override S?[]? M3<S>() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M3").WithArguments("B.M3<S>()", "A.M3<T>()", "S?[]").WithLocation(28, 27), // (18,31): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override string?[] M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M1").WithLocation(18, 31), // (23,26): error CS0453: The type 'S' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override S?[] M2<S>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M2").WithArguments("System.Nullable<T>", "T", "S").WithLocation(23, 26), // (28,27): error CS0453: The type 'S' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override S?[]? M3<S>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M3").WithArguments("System.Nullable<T>", "T", "S").WithLocation(28, 27)); var b = compilation.GetTypeByMetadataName("B"); foreach (string memberName in new[] { "M1", "M2", "M3" }) { var member = b.GetMember<MethodSymbol>(memberName); Assert.False(member.ReturnTypeWithAnnotations.Equals(member.OverriddenMethod.ConstructIfGeneric(member.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))).ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } [Fact] [WorkItem(28684, "https://github.com/dotnet/roslyn/issues/28684")] public void Overriding_23() { var source = @" class C { public static void Main() { } } abstract class A { public abstract string[] M1(); public abstract T[] M2<T>() where T : class; } class B : A { #nullable disable annotations public override string?[] M1() { return new string?[] {}; } #nullable disable annotations public override S?[] M2<S>() { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (24,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override S?[] M2<S>() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(24, 22), // (18,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override string?[] M1() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 27), // (24,26): error CS0508: 'B.M2<S>()': return type must be 'S[]' to match overridden member 'A.M2<T>()' // public override S?[] M2<S>() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("B.M2<S>()", "A.M2<T>()", "S[]").WithLocation(24, 26), // (18,31): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override string?[] M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M1").WithLocation(18, 31), // (24,26): error CS0453: The type 'S' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override S?[] M2<S>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M2").WithArguments("System.Nullable<T>", "T", "S").WithLocation(24, 26), // (20,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // return new string?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(20, 26), // (26,21): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // return new S?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(26, 21) ); } [Fact] public void Implementing_05() { var source = @" class C { public static void Main() { } } interface IA { string[] M1(); T[] M2<T>() where T : class; T?[]? M3<T>() where T : class; } class B : IA { public string?[] M1() { return new string?[] {}; } public S?[] M2<S>() where S : class { return new S?[] {}; } public S?[]? M3<S>() where S : class { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (23,17): warning CS8613: Nullability of reference types in return type of 'S?[] B.M2<S>()' doesn't match implicitly implemented member 'T[] IA.M2<T>()'. // public S?[] M2<S>() where S : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "M2").WithArguments("S?[] B.M2<S>()", "T[] IA.M2<T>()").WithLocation(23, 17), // (18,22): warning CS8613: Nullability of reference types in return type of 'string?[] B.M1()' doesn't match implicitly implemented member 'string[] IA.M1()'. // public string?[] M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "M1").WithArguments("string?[] B.M1()", "string[] IA.M1()").WithLocation(18, 22) ); var ia = compilation.GetTypeByMetadataName("IA"); var b = compilation.GetTypeByMetadataName("B"); foreach (var memberName in new[] { "M1", "M2" }) { var member = ia.GetMember<MethodSymbol>(memberName); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.False(implementing.ReturnTypeWithAnnotations.Equals(implemented.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var member = ia.GetMember<MethodSymbol>("M3"); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.True(implementing.ReturnTypeWithAnnotations.Equals(implemented.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } [Fact] public void Implementing_06() { var source = @" class C { public static void Main() { } } interface IA { string[] M1(); T[] M2<T>() where T : class; T?[]? M3<T>() where T : class; } class B : IA { string?[] IA.M1() { return new string?[] {}; } S?[] IA.M2<S>() { return new S?[] {}; } S?[]? IA.M3<S>() { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (23,13): error CS0539: 'B.M2<S>()' in explicit interface declaration is not found among members of the interface that can be implemented // S?[] IA.M2<S>() Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M2").WithArguments("B.M2<S>()").WithLocation(23, 13), // (28,14): error CS0539: 'B.M3<S>()' in explicit interface declaration is not found among members of the interface that can be implemented // S?[]? IA.M3<S>() Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M3").WithArguments("B.M3<S>()").WithLocation(28, 14), // (18,18): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'string[] IA.M1()'. // string?[] IA.M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M1").WithArguments("string[] IA.M1()").WithLocation(18, 18), // (16,11): error CS0535: 'B' does not implement interface member 'IA.M3<T>()' // class B : IA Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IA").WithArguments("B", "IA.M3<T>()").WithLocation(16, 11), // (16,11): error CS0535: 'B' does not implement interface member 'IA.M2<T>()' // class B : IA Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IA").WithArguments("B", "IA.M2<T>()").WithLocation(16, 11), // (23,13): error CS0453: The type 'S' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // S?[] IA.M2<S>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M2").WithArguments("System.Nullable<T>", "T", "S").WithLocation(23, 13), // (28,14): error CS0453: The type 'S' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // S?[]? IA.M3<S>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M3").WithArguments("System.Nullable<T>", "T", "S").WithLocation(28, 14), // (25,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // return new S?[] {}; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "S?").WithArguments("9.0").WithLocation(25, 20), // (30,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // return new S?[] {}; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "S?").WithArguments("9.0").WithLocation(30, 20) ); var ia = compilation.GetTypeByMetadataName("IA"); var b = compilation.GetTypeByMetadataName("B"); var member = ia.GetMember<MethodSymbol>("M1"); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.False(implementing.ReturnTypeWithAnnotations.Equals(implemented.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); member = ia.GetMember<MethodSymbol>("M2"); Assert.Null(b.FindImplementationForInterfaceMember(member)); member = ia.GetMember<MethodSymbol>("M3"); Assert.Null(b.FindImplementationForInterfaceMember(member)); } [Fact] public void ImplementingNonNullWithNullable_01() { var source = @" interface IA { string[] M1(); T[] M2<T>() where T : class; } class B : IA { #nullable disable annotations string?[] IA.M1() { return new string?[] {}; } #nullable disable annotations S?[] IA.M2<S>() { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (17,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // S?[] IA.M2<S>() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 6), // (17,13): error CS0539: 'B.M2<S>()' in explicit interface declaration is not found among members of the interface that can be implemented // S?[] IA.M2<S>() Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M2").WithArguments("B.M2<S>()").WithLocation(17, 13), // (11,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string?[] IA.M1() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 11), // (11,18): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'string[] IA.M1()'. // string?[] IA.M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M1").WithArguments("string[] IA.M1()").WithLocation(11, 18), // (8,11): error CS0535: 'B' does not implement interface member 'IA.M2<T>()' // class B : IA Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IA").WithArguments("B", "IA.M2<T>()").WithLocation(8, 11), // (17,13): error CS0453: The type 'S' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // S?[] IA.M2<S>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M2").WithArguments("System.Nullable<T>", "T", "S").WithLocation(17, 13), // (13,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // return new string?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 26), // (19,21): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // return new S?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(19, 21), // (19,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // return new S?[] {}; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "S?").WithArguments("9.0").WithLocation(19, 20) ); } [Fact] [WorkItem(28684, "https://github.com/dotnet/roslyn/issues/28684")] public void ImplementingNonNullWithNullable_02() { var source = @" interface IA { string[] M1(); T[] M2<T>() where T : class; } class B : IA { #nullable disable annotations string?[] IA.M1() { return new string?[] {}; } #nullable disable annotations S?[] IA.M2<S>() where S : class { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Skip(1).Single(); AssertEx.Equal("S?[]", model.GetTypeInfo(returnStatement.Expression).Type.ToTestDisplayString()); compilation.VerifyDiagnostics( // (17,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // S?[] IA.M2<S>() where S : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 6), // (17,13): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'T[] IA.M2<T>()'. // S?[] IA.M2<S>() where S : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M2").WithArguments("T[] IA.M2<T>()").WithLocation(17, 13), // (11,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string?[] IA.M1() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 11), // (11,18): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'string[] IA.M1()'. // string?[] IA.M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M1").WithArguments("string[] IA.M1()").WithLocation(11, 18), // (13,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // return new string?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 26), // (19,21): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // return new S?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(19, 21) ); } [Fact] public void ImplementingNullableWithNonNull_ReturnType() { var source = @" interface IA { #nullable disable string?[] M1(); #nullable disable T?[] M2<T>() where T : class; } #nullable enable class B : IA { string[] IA.M1() => throw null!; S[] IA.M2<S>() => throw null!; } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (7,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T?[] M2<T>() where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 6), // (7,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T?[] M2<T>() where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 5), // (5,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string?[] M1(); Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 11) ); } [Fact] public void ImplementingNullableWithNonNull_Parameter() { var source = @" interface IA { #nullable disable void M1(string?[] x); #nullable disable void M2<T>(T?[] x) where T : class; } #nullable enable class B : IA { void IA.M1(string[] x) => throw null!; void IA.M2<S>(S[] x) => throw null!; } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (5,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M1(string?[] x); Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 19), // (7,16): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void M2<T>(T?[] x) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 16), // (7,17): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M2<T>(T?[] x) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 17), // (12,13): warning CS8617: Nullability of reference types in type of parameter 'x' doesn't match implemented member 'void IA.M1(string?[] x)'. // void IA.M1(string[] x) => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "M1").WithArguments("x", "void IA.M1(string?[] x)").WithLocation(12, 13), // (13,13): warning CS8617: Nullability of reference types in type of parameter 'x' doesn't match implemented member 'void IA.M2<T>(T?[] x)'. // void IA.M2<S>(S[] x) Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "M2").WithArguments("x", "void IA.M2<T>(T?[] x)").WithLocation(13, 13) ); } [Fact] public void ImplementingObliviousWithNonNull() { var source = @" interface IA { #nullable disable string[] M1(); #nullable disable T[] M2<T>() where T : class; } #nullable enable class B : IA { string[] IA.M1() => throw null!; S[] IA.M2<S>() => throw null!; } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); } [Fact] public void Overriding_19() { var source = @" class C { public static void Main() { } } abstract class A { public abstract void M1(string[] x); public abstract void M2<T>(T[] x) where T : class; public abstract void M3<T>(T?[]? x) where T : class; } class B : A { public override void M1(string?[] x) { } public override void M2<T>(T?[] x) { } public override void M3<T>(T?[]? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (22,26): error CS0115: 'B.M2<T>(T?[])': no suitable method found to override // public override void M2<T>(T?[] x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M2").WithArguments("B.M2<T>(T?[])").WithLocation(22, 26), // (26,26): error CS0115: 'B.M3<T>(T?[]?)': no suitable method found to override // public override void M3<T>(T?[]? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("B.M3<T>(T?[]?)").WithLocation(26, 26), // (16,7): error CS0534: 'B' does not implement inherited abstract member 'A.M3<T>(T?[]?)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.M3<T>(T?[]?)").WithLocation(16, 7), // (16,7): error CS0534: 'B' does not implement inherited abstract member 'A.M2<T>(T[])' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.M2<T>(T[])").WithLocation(16, 7), // (22,37): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M2<T>(T?[] x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(22, 37), // (26,38): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M3<T>(T?[]? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(26, 38) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.False(m1.Parameters[0].TypeWithAnnotations.Equals(m1.OverriddenMethod.ConstructIfGeneric(m1.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))).Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); var m2 = b.GetMember<MethodSymbol>("M2"); Assert.Null(m2.OverriddenMethod); var m3 = b.GetMember<MethodSymbol>("M3"); Assert.Null(m3.OverriddenMethod); } [Fact] [WorkItem(28684, "https://github.com/dotnet/roslyn/issues/28684")] public void Overriding_24() { var source = @" #nullable enable abstract class A { public abstract void M1(string[] x); public abstract void M2<T>(T[] x) where T : class; } class B : A { #nullable disable public override void M1(string?[] x) { } #nullable disable public override void M2<T>(T?[] x) { } } "; var compilation = CreateCompilation(new[] { source }); compilation.VerifyDiagnostics( // (18,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override void M2<T>(T?[] x) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 33), // (13,35): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override void M1(string?[] x) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 35), // (18,26): error CS0115: 'B.M2<T>(T?[])': no suitable method found to override // public override void M2<T>(T?[] x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M2").WithArguments("B.M2<T>(T?[])").WithLocation(18, 26), // (10,7): error CS0534: 'B' does not implement inherited abstract member 'A.M2<T>(T[])' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.M2<T>(T[])").WithLocation(10, 7), // (18,37): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M2<T>(T?[] x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(18, 37) ); } [Fact] public void Overriding_25() { var ilSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly '<<GeneratedFileName>>' { } .module '<<GeneratedFileName>>.dll' .class public auto ansi beforefieldinit C`2<T,S> extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C`2::.ctor } // end of class C`2 .class public abstract auto ansi beforefieldinit A extends [mscorlib]System.Object { .method public hidebysig newslot abstract virtual instance class C`2<string modopt([mscorlib]System.Runtime.CompilerServices.IsConst),string> M1() cil managed { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 01 02 01 00 00 ) } // end of method A::M1 .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method A::.ctor } // end of class A .class public auto ansi beforefieldinit System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 86 6B 00 00 01 00 54 02 0D 41 6C 6C 6F 77 // ...k....T..Allow 4D 75 6C 74 69 70 6C 65 00 ) // Multiple. .method public hidebysig specialname rtspecialname instance void .ctor(uint8 transformFlag) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method NullableAttribute::.ctor .method public hidebysig specialname rtspecialname instance void .ctor(uint8[] transformFlags) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method NullableAttribute::.ctor } // end of class System.Runtime.CompilerServices.NullableAttribute "; var source = @" class C { public static void Main() { } } class B : A { public override C<string, string?> M1() { return new C<string, string?>(); } } "; var compilation = CreateCompilation(new[] { source }, new[] { CompileIL(ilSource, prependDefaultHeader: false) }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); var m1 = compilation.GetTypeByMetadataName("B").GetMember<MethodSymbol>("M1"); Assert.Equal("C<System.String? modopt(System.Runtime.CompilerServices.IsConst), System.String>", m1.OverriddenMethod.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Equal("C<System.String modopt(System.Runtime.CompilerServices.IsConst), System.String?>", m1.ReturnTypeWithAnnotations.ToTestDisplayString()); compilation.VerifyDiagnostics( // (11,40): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override C<string, string?> M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M1").WithLocation(11, 40) ); } [Fact] public void Overriding_26() { var source = @" class A { public virtual void M1<T>(T? x) where T : class { } public virtual T? M2<T>() where T : class { return null; } } class B : A { public override void M1<T>(T? x) where T : class { } public override T? M2<T>() where T : class { return null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.False(m1.Parameters[0].Type.IsNullableType()); Assert.Equal(NullableAnnotation.Annotated, m1.Parameters[0].TypeWithAnnotations.NullableAnnotation); Assert.True(m1.Parameters[0].Type.IsReferenceType); Assert.False(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); var m2 = b.GetMember<MethodSymbol>("M2"); Assert.False(m2.ReturnType.IsNullableType()); Assert.Equal(NullableAnnotation.Annotated, m2.ReturnTypeWithAnnotations.NullableAnnotation); Assert.True(m2.ReturnType.IsReferenceType); Assert.False(m2.OverriddenMethod.ReturnType.IsNullableType()); } [Fact] public void Overriding_27() { var source = @" class A { public virtual void M1<T>(System.Nullable<T> x) where T : struct { } public virtual void M2<T>(T? x) where T : struct { } public virtual void M3<T>(C<T?> x) where T : struct { } public virtual void M4<T>(C<System.Nullable<T>> x) where T : struct { } public virtual void M5<T>(C<T?> x) where T : class { } } class B : A { public override void M1<T>(T? x) { } public override void M2<T>(T? x) { } public override void M3<T>(C<T?> x) { } public override void M4<T>(C<T?> x) { } public override void M5<T>(C<T?> x) where T : class { } } class C<T> {} "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m3 = b.GetMember<MethodSymbol>("M3"); var m4 = b.GetMember<MethodSymbol>("M4"); var m5 = b.GetMember<MethodSymbol>("M5"); Assert.True(((NamedTypeSymbol)m3.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m3.OverriddenMethod.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m4.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m4.OverriddenMethod.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.False(((NamedTypeSymbol)m5.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.False(((NamedTypeSymbol)m5.OverriddenMethod.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); } [Fact] public void Overriding_28() { var source = @" class C { public static void Main() { } } abstract class A { public abstract string[] M1(); public abstract T[] M2<T>() where T : class; public abstract T?[]? M3<T>() where T : class; } class B : A { public override string?[] M1() { return new string?[] {}; } public override S?[] M2<S>() where S : class { return new S?[] {}; } public override S?[]? M3<S>() where S : class { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (23,26): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override S?[] M2<S>() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(23, 26), // (18,31): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override string?[] M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M1").WithLocation(18, 31) ); var b = compilation.GetTypeByMetadataName("B"); foreach (string memberName in new[] { "M1", "M2" }) { var member = b.GetMember<MethodSymbol>(memberName); Assert.False(member.ReturnTypeWithAnnotations.Equals(member.OverriddenMethod.ConstructIfGeneric(member.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))).ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } var m3 = b.GetMember<MethodSymbol>("M3"); Assert.True(m3.ReturnTypeWithAnnotations.Equals(m3.OverriddenMethod.ConstructIfGeneric(m3.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))).ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } [Fact] [WorkItem(28684, "https://github.com/dotnet/roslyn/issues/28684")] public void Overriding_29() { var source = @" class C { public static void Main() { } } abstract class A { public abstract string[] M1(); public abstract T[] M2<T>() where T : class; } class B : A { #nullable disable annotations public override string?[] M1() { return new string?[] {}; } #nullable disable annotations public override S?[] M2<S>() where S : class { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (18,31): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override string?[] M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M1").WithLocation(18, 31), // (24,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override S?[] M2<S>() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(24, 22), // (24,26): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override S?[] M2<S>() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(24, 26), // (18,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override string?[] M1() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 27), // (20,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // return new string?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(20, 26), // (26,21): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // return new S?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(26, 21) ); } [Fact] public void Overriding_30() { var source = @" class C { public static void Main() { } } abstract class A { public abstract void M1(string[] x); public abstract void M2<T>(T[] x) where T : class; public abstract void M3<T>(T?[]? x) where T : class; } class B : A { public override void M1(string?[] x) { } public override void M2<T>(T?[] x) where T : class { } public override void M3<T>(T?[]? x) where T : class { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( ); var b = compilation.GetTypeByMetadataName("B"); foreach (string memberName in new[] { "M1", "M2" }) { var member = b.GetMember<MethodSymbol>(memberName); Assert.False(member.Parameters[0].TypeWithAnnotations.Equals(member.OverriddenMethod.ConstructIfGeneric(member.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))).Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } var m3 = b.GetMember<MethodSymbol>("M3"); Assert.True(m3.Parameters[0].TypeWithAnnotations.Equals(m3.OverriddenMethod.ConstructIfGeneric(m3.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))).Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } [Fact] [WorkItem(28684, "https://github.com/dotnet/roslyn/issues/28684")] public void Overriding_31() { var source = @" #nullable enable abstract class A { public abstract void M1(string[] x); public abstract void M2<T>(T[] x) where T : class; } class B : A { #nullable disable public override void M1(string?[] x) { } #nullable disable public override void M2<T>(T?[] x) where T : class { } } "; var compilation = CreateCompilation(new[] { source }); compilation.VerifyDiagnostics( // (18,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override void M2<T>(T?[] x) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 33), // (13,35): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override void M1(string?[] x) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 35) ); } [Fact] [WorkItem(29847, "https://github.com/dotnet/roslyn/issues/29847")] public void Overriding_32() { var source = @" class A { public virtual void M1<T>(T? x) where T : struct { } public virtual void M1<T>(T? x) where T : class { } } class B : A { public override void M1<T>(T? x) where T : class { } } class C { public virtual void M2<T>(T? x) where T : class { } public virtual void M2<T>(T? x) where T : struct { } } class D : C { public override void M2<T>(T? x) where T : class { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.False(m1.Parameters[0].Type.IsNullableType()); Assert.False(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); var d = compilation.GetTypeByMetadataName("D"); var m2 = d.GetMember<MethodSymbol>("M2"); Assert.False(m2.Parameters[0].Type.IsNullableType()); Assert.False(m2.OverriddenMethod.Parameters[0].Type.IsNullableType()); } [Fact] [WorkItem(29847, "https://github.com/dotnet/roslyn/issues/29847")] public void Overriding_33() { var source = @" class A { public virtual void M1<T>(T? x) where T : struct { } public virtual void M1<T>(T? x) where T : class { } } class B : A { public override void M1<T>(T? x) where T : struct { } } class C { public virtual void M2<T>(T? x) where T : class { } public virtual void M2<T>(T? x) where T : struct { } } class D : C { public override void M2<T>(T? x) where T : struct { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.True(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); var d = compilation.GetTypeByMetadataName("D"); var m2 = d.GetMember<MethodSymbol>("M2"); Assert.True(m2.Parameters[0].Type.IsNullableType()); Assert.True(m2.OverriddenMethod.Parameters[0].Type.IsNullableType()); } [Fact] [WorkItem(33276, "https://github.com/dotnet/roslyn/issues/33276")] public void Overriding_34() { var source1 = @" public class MyEntity { } public abstract class BaseController<T> where T : MyEntity { public abstract void SomeMethod<R>(R? lite) where R : MyEntity; } "; var source2 = @" class DerivedController<T> : BaseController<T> where T : MyEntity { Table<T> table = null!; public override void SomeMethod<R>(R? lite) where R : class { table.OtherMethod(lite); } } class Table<T> where T : MyEntity { public void OtherMethod<R>(R? lite) where R : MyEntity { lite?.ToString(); } } "; var compilation1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { reference }); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2); } } [Fact] [WorkItem(31676, "https://github.com/dotnet/roslyn/issues/31676")] public void Overriding_35() { var source1 = @" using System; namespace Microsoft.EntityFrameworkCore.TestUtilities { public abstract class QueryAsserterBase { public abstract void AssertQueryScalar<TItem1, TResult>( Func<IQueryable<TItem1>, IQueryable<Nullable<TResult>>> actualQuery) where TResult : struct; } } public interface IQueryable<out T> { } "; var source2 = @" using System; namespace Microsoft.EntityFrameworkCore.TestUtilities { public class QueryAsserter<TContext> : QueryAsserterBase { public override void AssertQueryScalar<TItem1, TResult>( Func<IQueryable<TItem1>, IQueryable<TResult?>> actualQuery) { } } } "; foreach (var options1 in new[] { WithNullableEnable(), WithNullableDisable() }) { var compilation1 = CreateCompilation(new[] { source1 }, options: options1); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var options2 in new[] { WithNullableEnable(), WithNullableDisable() }) { var compilation2 = CreateCompilation(new[] { source2 }, options: options2, references: new[] { reference }); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2); } } var compilation3 = CreateCompilation(new[] { source1, source2 }, options: options1); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3); var compilation4 = CreateCompilation(new[] { source2, source1 }, options: options1); compilation4.VerifyDiagnostics(); CompileAndVerify(compilation4); } } [Fact] [WorkItem(38403, "https://github.com/dotnet/roslyn/issues/38403")] public void Overriding_36() { var source = @" #nullable enable using System; using System.Collections.Generic; using System.Text; public abstract class QueryAsserterBase { public abstract void AssertQueryScalar<TItem1, TResult>( Func<IQueryable<TItem1>, IQueryable<Nullable<TResult>>> actualQuery) where TResult : struct; } public class QueryAsserter<TContext> : QueryAsserterBase { public override void AssertQueryScalar<TItem1, TResult>( Func<IQueryable<TItem1>, IQueryable<TResult?>> actualQuery) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (4,1): hidden CS8019: Unnecessary using directive. // using System.Collections.Generic; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;").WithLocation(4, 1), // (5,1): hidden CS8019: Unnecessary using directive. // using System.Text; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Text;").WithLocation(5, 1), // (10,14): error CS0246: The type or namespace name 'IQueryable<>' could not be found (are you missing a using directive or an assembly reference?) // Func<IQueryable<TItem1>, IQueryable<Nullable<TResult>>> actualQuery) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IQueryable<TItem1>").WithArguments("IQueryable<>").WithLocation(10, 14), // (10,34): error CS0246: The type or namespace name 'IQueryable<>' could not be found (are you missing a using directive or an assembly reference?) // Func<IQueryable<TItem1>, IQueryable<Nullable<TResult>>> actualQuery) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IQueryable<Nullable<TResult>>").WithArguments("IQueryable<>").WithLocation(10, 34), // (17,14): error CS0246: The type or namespace name 'IQueryable<>' could not be found (are you missing a using directive or an assembly reference?) // Func<IQueryable<TItem1>, IQueryable<TResult?>> actualQuery) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IQueryable<TItem1>").WithArguments("IQueryable<>").WithLocation(17, 14), // (17,34): error CS0246: The type or namespace name 'IQueryable<>' could not be found (are you missing a using directive or an assembly reference?) // Func<IQueryable<TItem1>, IQueryable<TResult?>> actualQuery) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IQueryable<TResult?>").WithArguments("IQueryable<>").WithLocation(17, 34) ); } [Fact] [WorkItem(38403, "https://github.com/dotnet/roslyn/issues/38403")] public void Overriding_37() { var source = @" #nullable enable using System; using System.Collections.Generic; using System.Text; using System.Linq; public abstract class QueryAsserterBase { public abstract void AssertQueryScalar<TItem1, TResult>( Func<IQueryable<TItem1>, IQueryable<Nullable<TResult>>> actualQuery) where TResult : struct; } public class QueryAsserter<TContext> : QueryAsserterBase { public override void AssertQueryScalar<TItem1, TResult>( Func<IQueryable<TItem1>, IQueryable<TResult?>> actualQuery) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); CompileAndVerify(comp); } [Fact] public void Override_NullabilityCovariance_01() { var src = @" using System; interface I<out T> {} class A { public virtual object? M() => null; public virtual (object?, object?) M2() => throw null!; public virtual I<object?> M3() => throw null!; public virtual ref object? M4() => throw null!; public virtual ref readonly object? M5() => throw null!; public virtual Func<object>? P1 { get; set; } = null!; public virtual Func<object?> P2 { get; set; } = null!; public virtual object? P3 => null!; public virtual event Func<object>? E1 { add {} remove {} } public virtual event Func<object?> E2 { add {} remove {} } } class B : A { public override object M() => null!; public override (object, object) M2() => throw null!; public override I<object> M3() => throw null!; public override ref object M4() => throw null!; // warn public override ref readonly object M5() => throw null!; public override Func<object> P1 { get; set; } = null!; // warn public override Func<object> P2 { get; set; } = null!; // warn public override object P3 => null!; // ok public override event Func<object> E1 { add {} remove {} } // warn public override event Func<object> E2 { add {} remove {} } // warn } class C : B { public override object? M() => null; // warn public override (object?, object?) M2() => throw null!; // warn public override I<object?> M3() => throw null!; // warn public override ref object? M4() => throw null!; // warn public override ref readonly object? M5() => throw null!; // warn public override Func<object>? P1 { get; set; } = null!; // warn public override Func<object?> P2 { get; set; } = null!; // warn public override object? P3 => null!; // warn public override event Func<object>? E1 { add {} remove {} } // ok public override event Func<object?> E2 { add {} remove {} } // ok } class D : C { public override object M() => null!; public override (object, object) M2() => throw null!; public override I<object> M3() => throw null!; public override ref object M4() => throw null!; // warn public override ref readonly object M5() => throw null!; public override Func<object> P1 { get; set; } = null!; // warn public override Func<object> P2 { get; set; } = null!; // warn public override object P3 => null!; // ok public override event Func<object> E1 { add {} remove {} } // ok public override event Func<object> E2 { add {} remove {} } // ok } class E : D { public override object? M() => null; // warn public override (object?, object?) M2() => throw null!; // warn public override I<object?> M3() => throw null!; // warn public override ref object? M4() => throw null!; // warn public override ref readonly object? M5() => throw null!; // warn public override Func<object>? P1 { get; set; } = null!; // warn public override Func<object?> P2 { get; set; } = null!; // warn public override object? P3 => null!; // warn public override event Func<object>? E1 { add {} remove {} } // warn public override event Func<object?> E2 { add {} remove {} } // warn }"; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,32): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override ref object M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(23, 32), // (25,44): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // public override Func<object> P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(25, 44), // (26,44): warning CS8610: Nullability of reference types in type of parameter 'value' doesn't match overridden member. // public override Func<object> P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(26, 44), // (28,40): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event Func<object> E1 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E1").WithLocation(28, 40), // (29,40): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event Func<object> E2 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E2").WithLocation(29, 40), // (33,29): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override object? M() => null; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M").WithLocation(33, 29), // (34,40): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override (object?, object?) M2() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(34, 40), // (35,32): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override I<object?> M3() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M3").WithLocation(35, 32), // (36,33): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override ref object? M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(36, 33), // (37,42): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override ref readonly object? M5() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M5").WithLocation(37, 42), // (38,40): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override Func<object>? P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(38, 40), // (39,40): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override Func<object?> P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(39, 40), // (40,35): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override object? P3 => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "null!").WithLocation(40, 35), // (49,32): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override ref object M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(49, 32), // (51,44): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // public override Func<object> P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(51, 44), // (52,44): warning CS8610: Nullability of reference types in type of parameter 'value' doesn't match overridden member. // public override Func<object> P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(52, 44), // (54,40): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event Func<object> E1 { add {} remove {} } // ok Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E1").WithLocation(54, 40), // (55,40): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event Func<object> E2 { add {} remove {} } // ok Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E2").WithLocation(55, 40), // (59,29): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override object? M() => null; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M").WithLocation(59, 29), // (60,40): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override (object?, object?) M2() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(60, 40), // (61,32): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override I<object?> M3() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M3").WithLocation(61, 32), // (62,33): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override ref object? M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(62, 33), // (63,42): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override ref readonly object? M5() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M5").WithLocation(63, 42), // (64,40): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override Func<object>? P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(64, 40), // (65,40): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override Func<object?> P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(65, 40), // (66,35): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override object? P3 => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "null!").WithLocation(66, 35) ); } [Fact] public void Override_NullabilityCovariance_02() { var src = @" using System; class A { public virtual Func<object>? P1 { get; set; } = null!; } class B : A { public override Func<object> P1 { get => null!; } } class C : B { public override Func<object> P1 { get; set; } = null!; // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,44): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // public override Func<object> P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(14, 44) ); } [Fact] public void Override_NullabilityCovariance_03() { var src = @" using System; class B { public virtual Func<object> P1 { get; set; } = null!; } class C : B { public override Func<object>? P1 { set {} } } class D : C { public override Func<object>? P1 { get; set; } = null!; // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,40): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override Func<object>? P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(14, 40) ); } [Fact] public void Override_NullabilityContravariance_01() { var src = @" interface I<out T> {} class A { public virtual void M(object o) { } public virtual void M2((object, object) t) { } public virtual void M3(I<object> i) { } public virtual void M4(ref object o) { } public virtual void M5(out object o) => throw null!; public virtual void M6(in object o) { } public virtual object this[object o] { get => null!; set { } } public virtual string this[string s] => null!; public virtual string this[int[] a] { set { } } } class B : A { public override void M(object? o) { } public override void M2((object?, object?) t) { } public override void M3(I<object?> i) { } public override void M4(ref object? o) { } // warn public override void M5(out object? o) => throw null!; // warn public override void M6(in object? o) { } public override object? this[object? o] { get => null!; set { } } public override string this[string? s] => null!; public override string this[int[]? a] { set { } } } class C : B { public override void M(object o) { } // warn public override void M2((object, object) t) { } // warn public override void M3(I<object> i) { } // warn public override void M4(ref object o) { } // warn public override void M5(out object o) => throw null!; public override void M6(in object o) { } // warn public override object this[object o] { get => null!; set { } } public override string this[string s] => null!; public override string this[int[] a] { set { } } } class D : C { public override void M(object? o) { } public override void M2((object?, object?) t) { } public override void M3(I<object?> i) { } public override void M4(ref object? o) { } // warn public override void M5(out object? o) => throw null!; // warn public override void M6(in object? o) { } public override object? this[object? o] { get => null!; set { } } public override string this[string? s] => null!; public override string this[int[]? a] { set { } } } class E : D { public override void M(object o) { } // warn public override void M2((object, object) t) { } // warn public override void M3(I<object> i) { } // warn public override void M4(ref object o) { } // warn public override void M5(out object o) => throw null!; public override void M6(in object o) { } // warn public override object this[object o] { get => null!; set { } } public override string this[string s] => null!; public override string this[int[] a] { set { } } }"; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M4(ref object? o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M4").WithArguments("o").WithLocation(20, 26), // (21,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M5(out object? o) => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M5").WithArguments("o").WithLocation(21, 26), // (23,47): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override object? this[object? o] { get => null!; set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(23, 47), // (29,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M(object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("o").WithLocation(29, 26), // (30,26): warning CS8610: Nullability of reference types in type of parameter 't' doesn't match overridden member. // public override void M2((object, object) t) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M2").WithArguments("t").WithLocation(30, 26), // (31,26): warning CS8610: Nullability of reference types in type of parameter 'i' doesn't match overridden member. // public override void M3(I<object> i) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("i").WithLocation(31, 26), // (32,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M4(ref object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M4").WithArguments("o").WithLocation(32, 26), // (34,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M6(in object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M6").WithArguments("o").WithLocation(34, 26), // (35,59): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override object this[object o] { get => null!; set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("o").WithLocation(35, 59), // (35,59): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // public override object this[object o] { get => null!; set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(35, 59), // (36,46): warning CS8765: Type of parameter 's' doesn't match overridden member because of nullability attributes. // public override string this[string s] => null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "null!").WithArguments("s").WithLocation(36, 46), // (37,44): warning CS8765: Type of parameter 'a' doesn't match overridden member because of nullability attributes. // public override string this[int[] a] { set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("a").WithLocation(37, 44), // (44,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M4(ref object? o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M4").WithArguments("o").WithLocation(44, 26), // (45,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M5(out object? o) => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M5").WithArguments("o").WithLocation(45, 26), // (47,47): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override object? this[object? o] { get => null!; set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(47, 47), // (53,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M(object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("o").WithLocation(53, 26), // (54,26): warning CS8610: Nullability of reference types in type of parameter 't' doesn't match overridden member. // public override void M2((object, object) t) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M2").WithArguments("t").WithLocation(54, 26), // (55,26): warning CS8610: Nullability of reference types in type of parameter 'i' doesn't match overridden member. // public override void M3(I<object> i) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("i").WithLocation(55, 26), // (56,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M4(ref object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M4").WithArguments("o").WithLocation(56, 26), // (58,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M6(in object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M6").WithArguments("o").WithLocation(58, 26), // (59,59): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override object this[object o] { get => null!; set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("o").WithLocation(59, 59), // (59,59): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // public override object this[object o] { get => null!; set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(59, 59), // (60,46): warning CS8765: Type of parameter 's' doesn't match overridden member because of nullability attributes. // public override string this[string s] => null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "null!").WithArguments("s").WithLocation(60, 46), // (61,44): warning CS8765: Type of parameter 'a' doesn't match overridden member because of nullability attributes. // public override string this[int[] a] { set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("a").WithLocation(61, 44) ); } [Fact] public void Override_NullabilityContravariance_02() { var src = @" class B { public virtual object? this[object? o] { get => null!; set { } } } class C : B { #nullable disable public override object this[object o] { set { } } #nullable enable } class D : C { public override object this[object? o] { get => null!; } } class E : D { public override object this[object o] { get => null!; set { } } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,45): warning CS8765: Nullability of type of parameter 'o' doesn't match overridden member (possibly because of nullability attributes). // public override object this[object o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "get").WithArguments("o").WithLocation(18, 45) ); } [Fact] public void Override_NullabilityContravariance_03() { var src = @" class B { public virtual object? this[object? o] { get => null!; set { } } } class C : B { public override object this[object? o] { get => null!; } } class D : C { #nullable disable public override object this[object o] { set { } } #nullable enable } class E : D { public override object this[object o] { get => null!; set { } } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,45): warning CS8765: Nullability of type of parameter 'o' doesn't match overridden member (possibly because of nullability attributes). // public override object this[object o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "get").WithArguments("o").WithLocation(18, 45) ); } [Fact] public void OverrideConstraintVariance() { var src = @" using System.Collections.Generic; class A { public virtual List<T>? M<T>(List<T>? t) => null!; } class B : A { public override List<T> M<T>(List<T> t) => null!; } class C : B { public override List<T>? M<T>(List<T>? t) => null!; } class D : C { public override List<T> M<T>(List<T> t) => null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,29): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override List<T> M<T>(List<T> t) => null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("t").WithLocation(9, 29), // (13,30): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override List<T>? M<T>(List<T>? t) => null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M").WithLocation(13, 30), // (17,29): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override List<T> M<T>(List<T> t) => null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("t").WithLocation(17, 29)); } [Fact] public void OverrideVarianceGenericBase() { var comp = CreateCompilation(@" class A<T> { public virtual T M(T t) => default!; } #nullable enable class B : A<object> { public override object? M(object? o) => null!; // warn } class C : A<object?> { public override object M(object o) => null!; // warn } #nullable disable class D : A<object> { #nullable enable public override object? M(object? o) => null!; } class E : A<object> { #nullable disable public override object M(object o) => null!; } #nullable enable class F : A<object?> { #nullable disable public override object M(object o) => null; } "); comp.VerifyDiagnostics( // (9,29): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override object? M(object? o) => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M").WithLocation(9, 29), // (13,28): warning CS8765: Nullability of type of parameter 'o' doesn't match overridden member (possibly because of nullability attributes). // public override object M(object o) => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("o").WithLocation(13, 28)); } [Fact] public void NullableVarianceConsumer() { var comp = CreateCompilation(@" class A { public virtual object? M() => null; } class B : A { public override object M() => null; // warn } class C { void M() { var b = new B(); b.M().ToString(); A a = b; a.M().ToString(); // warn } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,35): warning CS8603: Possible null reference return. // public override object M() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 35), // (17,9): warning CS8602: Dereference of a possibly null reference. // a.M().ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.M()").WithLocation(17, 9)); } [Fact] public void Implement_NullabilityCovariance_Implicit_01() { var src = @" using System; interface I<out T> {} interface A { object? M(); (object?, object?) M2(); I<object?> M3(); ref object? M4(); ref readonly object? M5(); Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } object? P3 {get;} event Func<object>? E1; event Func<object?> E2; } class B : A { public object M() => null!; public (object, object) M2() => throw null!; public I<object> M3() => throw null!; public ref object M4() => throw null!; // warn public ref readonly object M5() => throw null!; public Func<object> P1 { get; set; } = null!; // warn public Func<object> P2 { get; set; } = null!; // warn public object P3 => null!; // ok public event Func<object> E1 { add {} remove {} } // warn public event Func<object> E2 { add {} remove {} } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,23): warning CS8766: Nullability of reference types in return type of 'ref object B.M4()' doesn't match implicitly implemented member 'ref object? A.M4()' (possibly because of nullability attributes). // public ref object M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M4").WithArguments("ref object B.M4()", "ref object? A.M4()").WithLocation(23, 23), // (25,35): warning CS8767: Nullability of reference types in type of parameter 'value' of 'void B.P1.set' doesn't match implicitly implemented member 'void A.P1.set' (possibly because of nullability attributes). // public Func<object> P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void B.P1.set", "void A.P1.set").WithLocation(25, 35), // (26,35): warning CS8614: Nullability of reference types in type of parameter 'value' of 'void B.P2.set' doesn't match implicitly implemented member 'void A.P2.set'. // public Func<object> P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void B.P2.set", "void A.P2.set").WithLocation(26, 35), // (28,31): warning CS8612: Nullability of reference types in type of 'event Func<object> B.E1' doesn't match implicitly implemented member 'event Func<object>? A.E1'. // public event Func<object> E1 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "E1").WithArguments("event Func<object> B.E1", "event Func<object>? A.E1").WithLocation(28, 31), // (29,31): warning CS8612: Nullability of reference types in type of 'event Func<object> B.E2' doesn't match implicitly implemented member 'event Func<object?> A.E2'. // public event Func<object> E2 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "E2").WithArguments("event Func<object> B.E2", "event Func<object?> A.E2").WithLocation(29, 31) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_02() { var src = @" using System; interface I<out T> {} interface B { object M(); (object, object) M2(); I<object> M3(); ref object M4(); ref readonly object M5(); Func<object> P1 { get; set; } Func<object> P2 { get; set; } object P3 { get; } event Func<object> E1; event Func<object> E2; } class C : B { public object? M() => null; // warn public (object?, object?) M2() => throw null!; // warn public I<object?> M3() => throw null!; // warn public ref object? M4() => throw null!; // warn public ref readonly object? M5() => throw null!; // warn public Func<object>? P1 { get; set; } = null!; // warn public Func<object?> P2 { get; set; } = null!; // warn public object? P3 => null!; // warn public event Func<object>? E1 { add {} remove {} } // ok public event Func<object?> E2 { add {} remove {} } // ok } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,20): warning CS8766: Nullability of reference types in return type of 'object? C.M()' doesn't match implicitly implemented member 'object B.M()' (possibly because of nullability attributes). // public object? M() => null; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M").WithArguments("object? C.M()", "object B.M()").WithLocation(20, 20), // (21,31): warning CS8613: Nullability of reference types in return type of '(object?, object?) C.M2()' doesn't match implicitly implemented member '(object, object) B.M2()'. // public (object?, object?) M2() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "M2").WithArguments("(object?, object?) C.M2()", "(object, object) B.M2()").WithLocation(21, 31), // (22,23): warning CS8613: Nullability of reference types in return type of 'I<object?> C.M3()' doesn't match implicitly implemented member 'I<object> B.M3()'. // public I<object?> M3() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "M3").WithArguments("I<object?> C.M3()", "I<object> B.M3()").WithLocation(22, 23), // (23,24): warning CS8766: Nullability of reference types in return type of 'ref object? C.M4()' doesn't match implicitly implemented member 'ref object B.M4()' (possibly because of nullability attributes). // public ref object? M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M4").WithArguments("ref object? C.M4()", "ref object B.M4()").WithLocation(23, 24), // (24,33): warning CS8766: Nullability of reference types in return type of 'ref readonly object? C.M5()' doesn't match implicitly implemented member 'ref readonly object B.M5()' (possibly because of nullability attributes). // public ref readonly object? M5() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M5").WithArguments("ref readonly object? C.M5()", "ref readonly object B.M5()").WithLocation(24, 33), // (25,31): warning CS8766: Nullability of reference types in return type of 'Func<object>? C.P1.get' doesn't match implicitly implemented member 'Func<object> B.P1.get' (possibly because of nullability attributes). // public Func<object>? P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("Func<object>? C.P1.get", "Func<object> B.P1.get").WithLocation(25, 31), // (26,31): warning CS8613: Nullability of reference types in return type of 'Func<object?> C.P2.get' doesn't match implicitly implemented member 'Func<object> B.P2.get'. // public Func<object?> P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("Func<object?> C.P2.get", "Func<object> B.P2.get").WithLocation(26, 31), // (27,26): warning CS8766: Nullability of reference types in return type of 'object? C.P3.get' doesn't match implicitly implemented member 'object B.P3.get' (possibly because of nullability attributes). // public object? P3 => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "null!").WithArguments("object? C.P3.get", "object B.P3.get").WithLocation(27, 26) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_05() { var src = @" using System; interface I<out T> {} interface A { object? M(); (object?, object?) M2(); I<object?> M3(); ref object? M4(); ref readonly object? M5(); Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } object? P3 {get;} event Func<object>? E1; event Func<object?> E2; } class B { public object M() => null!; public (object, object) M2() => throw null!; public I<object> M3() => throw null!; public ref object M4() => throw null!; // warn public ref readonly object M5() => throw null!; public Func<object> P1 { get; set; } = null!; // warn public Func<object> P2 { get; set; } = null!; // warn public object P3 => null!; // ok public event Func<object> E1 { add {} remove {} } // warn public event Func<object> E2 { add {} remove {} } // warn } class C : B, A {} "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (31,14): warning CS8766: Nullability of reference types in return type of 'ref object B.M4()' doesn't match implicitly implemented member 'ref object? A.M4()' (possibly because of nullability attributes). // class C : B, A Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "A").WithArguments("ref object B.M4()", "ref object? A.M4()").WithLocation(31, 14), // (31,14): warning CS8767: Nullability of reference types in type of parameter 'value' of 'void B.P1.set' doesn't match implicitly implemented member 'void A.P1.set' (possibly because of nullability attributes). // class C : B, A Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "A").WithArguments("value", "void B.P1.set", "void A.P1.set").WithLocation(31, 14), // (31,14): warning CS8614: Nullability of reference types in type of parameter 'value' of 'void B.P2.set' doesn't match implicitly implemented member 'void A.P2.set'. // class C : B, A Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "A").WithArguments("value", "void B.P2.set", "void A.P2.set").WithLocation(31, 14), // (31,14): warning CS8612: Nullability of reference types in type of 'event Func<object> B.E1' doesn't match implicitly implemented member 'event Func<object>? A.E1'. // class C : B, A Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "A").WithArguments("event Func<object> B.E1", "event Func<object>? A.E1").WithLocation(31, 14), // (31,14): warning CS8612: Nullability of reference types in type of 'event Func<object> B.E2' doesn't match implicitly implemented member 'event Func<object?> A.E2'. // class C : B, A Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "A").WithArguments("event Func<object> B.E2", "event Func<object?> A.E2").WithLocation(31, 14) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_06() { var src = @" using System; interface A { Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } } class B { public virtual Func<object> P1 { get; set; } = null!; // warn public virtual Func<object> P2 { get; set; } = null!; // warn } class C : B, A { public override Func<object> P1 { get => null!;} public override Func<object> P2 => null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,14): warning CS8614: Nullability of reference types in type of parameter 'value' of 'void B.P2.set' doesn't match implicitly implemented member 'void A.P2.set'. // class C : B, A Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "A").WithArguments("value", "void B.P2.set", "void A.P2.set").WithLocation(14, 14), // (14,14): warning CS8767: Nullability of reference types in type of parameter 'value' of 'void B.P1.set' doesn't match implicitly implemented member 'void A.P1.set' (possibly because of nullability attributes). // class C : B, A Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "A").WithArguments("value", "void B.P1.set", "void A.P1.set").WithLocation(14, 14) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_07() { var src = @" using System; interface A { Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } } class B { public virtual Func<object>? P1 { get; set; } = null!; public virtual Func<object?> P2 { get; set; } = null!; } class C : B, A { public override Func<object> P1 { get => null!;} public override Func<object> P2 => null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_08() { var src = @" using System; interface A { Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } } class B { public virtual Func<object>? P1 { get; set; } = null!; public virtual Func<object?> P2 { get; set; } = null!; } class C : B, A { public override Func<object> P1 { set {} } // warn public override Func<object> P2 { set; } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,39): warning CS8765: Nullability of type of parameter 'value' doesn't match overridden member (possibly because of nullability attributes). // public override Func<object> P1 { set {} } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(15, 39), // (15,39): warning CS8767: Nullability of reference types in type of parameter 'value' of 'void C.P1.set' doesn't match implicitly implemented member 'void A.P1.set' (possibly because of nullability attributes). // public override Func<object> P1 { set {} } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void C.P1.set", "void A.P1.set").WithLocation(15, 39), // (16,39): error CS8051: Auto-implemented properties must have get accessors. // public override Func<object> P2 { set; } // warn Diagnostic(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, "set").WithArguments("C.P2.set").WithLocation(16, 39), // (16,39): warning CS8610: Nullability of reference types in type of parameter 'value' doesn't match overridden member. // public override Func<object> P2 { set; } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(16, 39), // (16,39): warning CS8614: Nullability of reference types in type of parameter 'value' of 'void C.P2.set' doesn't match implicitly implemented member 'void A.P2.set'. // public override Func<object> P2 { set; } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void C.P2.set", "void A.P2.set").WithLocation(16, 39) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_09() { var src = @" using System; interface A { Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } } class B { public virtual Func<object> P1 { get; set; } = null!; public virtual Func<object> P2 { get; set; } = null!; } class C : B, A { public override Func<object>? P1 { set {} } public override Func<object?> P2 { set {} } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_10() { var src = @" using System; interface A { Func<object>? P1 { get => null!; private set {} } Func<object?> P2 { get => null!; private set {} } } class B : A { public Func<object> P1 { get; set; } = null!; public Func<object> P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_11() { var src = @" using System; interface A { Func<object>? P1 { get => null!; private set {} } Func<object?> P2 { get => null!; private set {} } } class B : A { public Func<object> P1 { get; } = null!; public Func<object> P2 { get; } = null!; } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_12() { var src = @" using System; interface A { Func<object>? P1 { get; } Func<object?> P2 { get; } } class B : A { public Func<object> P1 { get; set; } = null!; public Func<object> P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_13() { var src = @" using System; interface A { Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } } class B : A { public Func<object> P1 { get; } = null!; public Func<object> P2 { get; } = null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): error CS0535: 'B' does not implement interface member 'A.P2.set' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.P2.set").WithLocation(9, 11), // (9,11): error CS0535: 'B' does not implement interface member 'A.P1.set' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.P1.set").WithLocation(9, 11) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_14() { var src = @" using System; interface B { Func<object> P1 { get; set; } Func<object> P2 { get; set; } } class C { public virtual Func<object>? P1 { get; set; } = null!; // warn public virtual Func<object?> P2 { get; set; } = null!; // warn } class D : C, B { public override Func<object>? P1 { set {} } public override Func<object?> P2 { set {} } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,14): warning CS8613: Nullability of reference types in return type of 'Func<object?> C.P2.get' doesn't match implicitly implemented member 'Func<object> B.P2.get'. // class D : C, B Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "B").WithArguments("Func<object?> C.P2.get", "Func<object> B.P2.get").WithLocation(14, 14), // (14,14): warning CS8766: Nullability of reference types in return type of 'Func<object>? C.P1.get' doesn't match implicitly implemented member 'Func<object> B.P1.get' (possibly because of nullability attributes). // class D : C, B Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "B").WithArguments("Func<object>? C.P1.get", "Func<object> B.P1.get").WithLocation(14, 14) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_15() { var src = @" using System; interface B { Func<object> P1 { get; set; } Func<object> P2 { get; set; } } class C { public virtual Func<object> P1 { get; set; } = null!; public virtual Func<object> P2 { get; set; } = null!; } class D : C, B { public override Func<object>? P1 { set {} } public override Func<object?> P2 { set {} } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_16() { var src = @" using System; interface B { Func<object> P1 { get; set; } Func<object> P2 { get; set; } } class C { public virtual Func<object> P1 { get; set; } = null!; public virtual Func<object> P2 { get; set; } = null!; } class D : C, B { public override Func<object>? P1 { get; } = null!; // warn public override Func<object?> P2 { get => null!; } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,35): error CS8080: Auto-implemented properties must override all accessors of the overridden property. // public override Func<object>? P1 { get; } = null!; // warn Diagnostic(ErrorCode.ERR_AutoPropertyMustOverrideSet, "P1").WithArguments("D.P1").WithLocation(16, 35), // (16,40): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override Func<object>? P1 { get; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(16, 40), // (16,40): warning CS8766: Nullability of reference types in return type of 'Func<object>? D.P1.get' doesn't match implicitly implemented member 'Func<object> B.P1.get' (possibly because of nullability attributes). // public override Func<object>? P1 { get; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("Func<object>? D.P1.get", "Func<object> B.P1.get").WithLocation(16, 40), // (17,40): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override Func<object?> P2 { get => null!; } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(17, 40), // (17,40): warning CS8613: Nullability of reference types in return type of 'Func<object?> D.P2.get' doesn't match implicitly implemented member 'Func<object> B.P2.get'. // public override Func<object?> P2 { get => null!; } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("Func<object?> D.P2.get", "Func<object> B.P2.get").WithLocation(17, 40) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_17() { var src = @" using System; interface B { Func<object> P1 { get; set; } Func<object> P2 { get; set; } } class C { public virtual Func<object>? P1 { get; set; } = null!; public virtual Func<object?> P2 { get; set; } = null!; } class D : C, B { public override Func<object> P1 { get => null!; } public override Func<object> P2 { get => null!; } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_18() { var src = @" using System; interface B { Func<object> P1 { private get => null!; set{} } Func<object> P2 { private get => null!; set{} } } class C : B { public Func<object>? P1 { get; set; } = null!; public Func<object?> P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_19() { var src = @" using System; interface B { Func<object> P1 { private get => null!; set{} } Func<object> P2 { private get => null!; set{} } } class C : B { public Func<object>? P1 { set{} } public Func<object?> P2 { set{} } } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_20() { var src = @" using System; interface B { Func<object> P1 { set; } Func<object> P2 { set; } } class C : B { public Func<object>? P1 { get; set; } public Func<object?> P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_21() { var src = @" using System; interface B { Func<object> P1 { get; set; } Func<object> P2 { get; set; } } class C : B { public Func<object>? P1 { set {} } public Func<object?> P2 { set {} } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): error CS0535: 'C' does not implement interface member 'B.P1.get' // class C : B Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "B").WithArguments("C", "B.P1.get").WithLocation(9, 11), // (9,11): error CS0535: 'C' does not implement interface member 'B.P2.get' // class C : B Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "B").WithArguments("C", "B.P2.get").WithLocation(9, 11) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_01() { var src = @" using System; interface I<out T> {} interface A { object? M(); (object?, object?) M2(); I<object?> M3(); ref object? M4(); ref readonly object? M5(); Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } object? P3 {get;} event Func<object>? E1; event Func<object?> E2; } class B : A { object A.M() => null!; (object, object) A.M2() => throw null!; I<object> A.M3() => throw null!; ref object A.M4() => throw null!; // warn ref readonly object A.M5() => throw null!; Func<object> A.P1 { get; set; } = null!; // warn Func<object> A.P2 { get; set; } = null!; // warn object A.P3 => null!; // ok event Func<object> A.E1 { add {} remove {} } // warn event Func<object> A.E2 { add {} remove {} } // warn } class C : B, A {} "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,18): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'ref object? A.M4()' (possibly because of nullability attributes). // ref object A.M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M4").WithArguments("ref object? A.M4()").WithLocation(23, 18), // (25,30): warning CS8769: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void A.P1.set' (possibly because of nullability attributes). // Func<object> A.P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void A.P1.set").WithLocation(25, 30), // (26,30): warning CS8617: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void A.P2.set'. // Func<object> A.P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void A.P2.set").WithLocation(26, 30), // (28,26): warning CS8615: Nullability of reference types in type doesn't match implemented member 'event Func<object>? A.E1'. // event Func<object> A.E1 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, "E1").WithArguments("event Func<object>? A.E1").WithLocation(28, 26), // (29,26): warning CS8615: Nullability of reference types in type doesn't match implemented member 'event Func<object?> A.E2'. // event Func<object> A.E2 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, "E2").WithArguments("event Func<object?> A.E2").WithLocation(29, 26) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_02() { var src = @" using System; interface I<out T> {} interface B { object M(); (object, object) M2(); I<object> M3(); ref object M4(); ref readonly object M5(); Func<object> P1 { get; set; } Func<object> P2 { get; set; } object P3 { get; } event Func<object> E1; event Func<object> E2; } class C : B { object? B.M() => null; // warn (object?, object?) B.M2() => throw null!; // warn I<object?> B.M3() => throw null!; // warn ref object? B.M4() => throw null!; // warn ref readonly object? B.M5() => throw null!; // warn Func<object>? B.P1 { get; set; } = null!; // warn Func<object?> B.P2 { get; set; } = null!; // warn object? B.P3 => null!; // warn event Func<object>? B.E1 { add {} remove {} } // ok event Func<object?> B.E2 { add {} remove {} } // ok } class D : C, B {} "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,15): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'object B.M()' (possibly because of nullability attributes). // object? B.M() => null; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M").WithArguments("object B.M()").WithLocation(20, 15), // (21,26): warning CS8616: Nullability of reference types in return type doesn't match implemented member '(object, object) B.M2()'. // (object?, object?) B.M2() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M2").WithArguments("(object, object) B.M2()").WithLocation(21, 26), // (22,18): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'I<object> B.M3()'. // I<object?> B.M3() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M3").WithArguments("I<object> B.M3()").WithLocation(22, 18), // (23,19): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'ref object B.M4()' (possibly because of nullability attributes). // ref object? B.M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M4").WithArguments("ref object B.M4()").WithLocation(23, 19), // (24,28): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'ref readonly object B.M5()' (possibly because of nullability attributes). // ref readonly object? B.M5() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M5").WithArguments("ref readonly object B.M5()").WithLocation(24, 28), // (25,26): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'Func<object> B.P1.get' (possibly because of nullability attributes). // Func<object>? B.P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("Func<object> B.P1.get").WithLocation(25, 26), // (26,26): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'Func<object> B.P2.get'. // Func<object?> B.P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("Func<object> B.P2.get").WithLocation(26, 26), // (27,21): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'object B.P3.get' (possibly because of nullability attributes). // object? B.P3 => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "null!").WithArguments("object B.P3.get").WithLocation(27, 21) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_03() { var src = @" using System; interface I<out T> {} interface A { object? M(); (object?, object?) M2(); I<object?> M3(); ref object? M4(); ref readonly object? M5(); Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } object? P3 {get;} event Func<object>? E1; event Func<object?> E2; } interface B : A { object A.M() => null!; (object, object) A.M2() => throw null!; I<object> A.M3() => throw null!; ref object A.M4() => throw null!; // warn ref readonly object A.M5() => throw null!; Func<object> A.P1 { get => null!; set {} } // warn Func<object> A.P2 { get => null!; set {} } // warn object A.P3 => null!; // ok event Func<object> A.E1 { add {} remove {} } // warn event Func<object> A.E2 { add {} remove {} } // warn } class C : B, A {} interface D : B, A {} "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,18): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'ref object? A.M4()' (possibly because of nullability attributes). // ref object A.M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M4").WithArguments("ref object? A.M4()").WithLocation(23, 18), // (25,39): warning CS8769: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void A.P1.set' (possibly because of nullability attributes). // Func<object> A.P1 { get => null!; set {} } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void A.P1.set").WithLocation(25, 39), // (26,39): warning CS8617: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void A.P2.set'. // Func<object> A.P2 { get => null!; set {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void A.P2.set").WithLocation(26, 39), // (28,26): warning CS8615: Nullability of reference types in type doesn't match implemented member 'event Func<object>? A.E1'. // event Func<object> A.E1 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, "E1").WithArguments("event Func<object>? A.E1").WithLocation(28, 26), // (29,26): warning CS8615: Nullability of reference types in type doesn't match implemented member 'event Func<object?> A.E2'. // event Func<object> A.E2 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, "E2").WithArguments("event Func<object?> A.E2").WithLocation(29, 26) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_04() { var src = @" using System; interface I<out T> {} interface B { object M(); (object, object) M2(); I<object> M3(); ref object M4(); ref readonly object M5(); Func<object> P1 { get; set; } Func<object> P2 { get; set; } object P3 { get; } event Func<object> E1; event Func<object> E2; } interface C : B { object? B.M() => null; // warn (object?, object?) B.M2() => throw null!; // warn I<object?> B.M3() => throw null!; // warn ref object? B.M4() => throw null!; // warn ref readonly object? B.M5() => throw null!; // warn Func<object>? B.P1 { get => null!; set {} } // warn Func<object?> B.P2 { get => null!; set {} } // warn object? B.P3 => null!; // warn event Func<object>? B.E1 { add {} remove {} } // ok event Func<object?> B.E2 { add {} remove {} } // ok } class D : C, B {} interface E : C, B {} "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,15): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'object B.M()' (possibly because of nullability attributes). // object? B.M() => null; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M").WithArguments("object B.M()").WithLocation(20, 15), // (21,26): warning CS8616: Nullability of reference types in return type doesn't match implemented member '(object, object) B.M2()'. // (object?, object?) B.M2() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M2").WithArguments("(object, object) B.M2()").WithLocation(21, 26), // (22,18): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'I<object> B.M3()'. // I<object?> B.M3() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M3").WithArguments("I<object> B.M3()").WithLocation(22, 18), // (23,19): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'ref object B.M4()' (possibly because of nullability attributes). // ref object? B.M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M4").WithArguments("ref object B.M4()").WithLocation(23, 19), // (24,28): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'ref readonly object B.M5()' (possibly because of nullability attributes). // ref readonly object? B.M5() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M5").WithArguments("ref readonly object B.M5()").WithLocation(24, 28), // (25,26): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'Func<object> B.P1.get' (possibly because of nullability attributes). // Func<object>? B.P1 { get => null!; set {} } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("Func<object> B.P1.get").WithLocation(25, 26), // (26,26): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'Func<object> B.P2.get'. // Func<object?> B.P2 { get => null!; set {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("Func<object> B.P2.get").WithLocation(26, 26), // (27,21): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'object B.P3.get' (possibly because of nullability attributes). // object? B.P3 => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "null!").WithArguments("object B.P3.get").WithLocation(27, 21) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_05() { var src = @" using System; interface A { Func<object>? P1 { get => null!; private set {} } Func<object?> P2 { get => null!; private set {} } } class B : A { Func<object> A.P1 { get; set; } = null!; Func<object> A.P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,30): error CS0550: 'B.A.P1.set' adds an accessor not found in interface member 'A.P1' // Func<object> A.P1 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("B.A.P1.set", "A.P1").WithLocation(11, 30), // (12,30): error CS0550: 'B.A.P2.set' adds an accessor not found in interface member 'A.P2' // Func<object> A.P2 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("B.A.P2.set", "A.P2").WithLocation(12, 30) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_06() { var src = @" using System; interface A { Func<object>? P1 { get => null!; private set {} } Func<object?> P2 { get => null!; private set {} } } class B : A { Func<object> A.P1 { get; } = null!; Func<object> A.P2 { get; } = null!; } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Explicit_07() { var src = @" using System; interface A { Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } } class B : A { Func<object> A.P1 { get; } = null!; Func<object> A.P2 { get; } = null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): error CS0535: 'B' does not implement interface member 'A.P2.set' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.P2.set").WithLocation(9, 11), // (9,11): error CS0535: 'B' does not implement interface member 'A.P1.set' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.P1.set").WithLocation(9, 11), // (11,20): error CS0551: Explicit interface implementation 'B.A.P1' is missing accessor 'A.P1.set' // Func<object> A.P1 { get; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P1").WithArguments("B.A.P1", "A.P1.set").WithLocation(11, 20), // (12,20): error CS0551: Explicit interface implementation 'B.A.P2' is missing accessor 'A.P2.set' // Func<object> A.P2 { get; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P2").WithArguments("B.A.P2", "A.P2.set").WithLocation(12, 20) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_08() { var src = @" using System; interface A { Func<object>? P1 { get; } Func<object?> P2 { get; } } class B : A { Func<object> A.P1 { get; set; } = null!; Func<object> A.P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,30): error CS0550: 'B.A.P1.set' adds an accessor not found in interface member 'A.P1' // Func<object> A.P1 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("B.A.P1.set", "A.P1").WithLocation(11, 30), // (12,30): error CS0550: 'B.A.P2.set' adds an accessor not found in interface member 'A.P2' // Func<object> A.P2 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("B.A.P2.set", "A.P2").WithLocation(12, 30) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_09() { var src = @" using System; interface B { Func<object> P1 { private get => null!; set{} } Func<object> P2 { private get => null!; set{} } } class C : B { Func<object>? B.P1 { get; set; } = null!; Func<object?> B.P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,26): error CS0550: 'C.B.P1.get' adds an accessor not found in interface member 'B.P1' // Func<object>? B.P1 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C.B.P1.get", "B.P1").WithLocation(11, 26), // (12,26): error CS0550: 'C.B.P2.get' adds an accessor not found in interface member 'B.P2' // Func<object?> B.P2 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C.B.P2.get", "B.P2").WithLocation(12, 26) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_10() { var src = @" using System; interface B { Func<object> P1 { private get => null!; set{} } Func<object> P2 { private get => null!; set{} } } class C : B { Func<object>? B.P1 { set{} } Func<object?> B.P2 { set{} } } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Explicit_11() { var src = @" using System; interface B { Func<object> P1 { set; } Func<object> P2 { set; } } class C : B { Func<object>? B.P1 { get; set; } Func<object?> B.P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,26): error CS0550: 'C.B.P1.get' adds an accessor not found in interface member 'B.P1' // Func<object>? B.P1 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C.B.P1.get", "B.P1").WithLocation(11, 26), // (12,26): error CS0550: 'C.B.P2.get' adds an accessor not found in interface member 'B.P2' // Func<object?> B.P2 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C.B.P2.get", "B.P2").WithLocation(12, 26) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_12() { var src = @" using System; interface B { Func<object> P1 { get; set; } Func<object> P2 { get; set; } } class C : B { Func<object>? B.P1 { set {} } Func<object?> B.P2 { set {} } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): error CS0535: 'C' does not implement interface member 'B.P1.get' // class C : B Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "B").WithArguments("C", "B.P1.get").WithLocation(9, 11), // (9,11): error CS0535: 'C' does not implement interface member 'B.P2.get' // class C : B Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "B").WithArguments("C", "B.P2.get").WithLocation(9, 11), // (11,21): error CS0551: Explicit interface implementation 'C.B.P1' is missing accessor 'B.P1.get' // Func<object>? B.P1 { set {} } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P1").WithArguments("C.B.P1", "B.P1.get").WithLocation(11, 21), // (12,21): error CS0551: Explicit interface implementation 'C.B.P2' is missing accessor 'B.P2.get' // Func<object?> B.P2 { set {} } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P2").WithArguments("C.B.P2", "B.P2.get").WithLocation(12, 21) ); } [Fact] public void Implement_NullabilityContravariance_Implicit_01() { var src = @" interface I<out T> {} interface A { void M(object o); void M2((object, object) t); void M3(I<object> i); void M4(ref object o); void M5(out object o); void M6(in object o); object this[object o] { get; set; } string this[string s] { get; } string this[int[] a] { set; } } class B : A { public void M(object? o) { } public void M2((object?, object?) t) { } public void M3(I<object?> i) { } public void M4(ref object? o) { } // warn public void M5(out object? o) => throw null!; // warn public void M6(in object? o) { } public object? this[object? o] { get => null!; set { } } // warn public string this[string? s] => null!; public string this[int[]? a] { set { } } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,17): warning CS8767: Nullability of reference types in type of parameter 'o' of 'void B.M4(ref object? o)' doesn't match implicitly implemented member 'void A.M4(ref object o)' (possibly because of nullability attributes). // public void M4(ref object? o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M4").WithArguments("o", "void B.M4(ref object? o)", "void A.M4(ref object o)").WithLocation(20, 17), // (21,17): warning CS8767: Nullability of reference types in type of parameter 'o' of 'void B.M5(out object? o)' doesn't match implicitly implemented member 'void A.M5(out object o)' (possibly because of nullability attributes). // public void M5(out object? o) => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M5").WithArguments("o", "void B.M5(out object? o)", "void A.M5(out object o)").WithLocation(21, 17), // (23,38): warning CS8766: Nullability of reference types in return type of 'object? B.this[object? o].get' doesn't match implicitly implemented member 'object A.this[object o].get' (possibly because of nullability attributes). // public object? this[object? o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("object? B.this[object? o].get", "object A.this[object o].get").WithLocation(23, 38) ); } [Fact] public void Implement_NullabilityContravariance_Implicit_02() { var src = @" interface I<out T> {} interface B { void M(object? o); void M2((object?, object?) t); void M3(I<object?> i); void M4(ref object? o); void M5(out object? o); void M6(in object? o); object? this[object? o] { get; set; } string this[string? s] { get; } string this[int[]? a] { set; } } class C : B { public void M(object o) { } // warn public void M2((object, object) t) { } // warn public void M3(I<object> i) { } // warn public void M4(ref object o) { } // warn public void M5(out object o) => throw null!; public void M6(in object o) { } // warn public object this[object o] { get => null!; set { } } // warn public string this[string s] => null!; // warn public string this[int[] a] { set { } } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,17): warning CS8767: Nullability of reference types in type of parameter 'o' of 'void C.M(object o)' doesn't match implicitly implemented member 'void B.M(object? o)' (possibly because of nullability attributes). // public void M(object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M").WithArguments("o", "void C.M(object o)", "void B.M(object? o)").WithLocation(17, 17), // (18,17): warning CS8614: Nullability of reference types in type of parameter 't' of 'void C.M2((object, object) t)' doesn't match implicitly implemented member 'void B.M2((object?, object?) t)'. // public void M2((object, object) t) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "M2").WithArguments("t", "void C.M2((object, object) t)", "void B.M2((object?, object?) t)").WithLocation(18, 17), // (19,17): warning CS8614: Nullability of reference types in type of parameter 'i' of 'void C.M3(I<object> i)' doesn't match implicitly implemented member 'void B.M3(I<object?> i)'. // public void M3(I<object> i) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "M3").WithArguments("i", "void C.M3(I<object> i)", "void B.M3(I<object?> i)").WithLocation(19, 17), // (20,17): warning CS8767: Nullability of reference types in type of parameter 'o' of 'void C.M4(ref object o)' doesn't match implicitly implemented member 'void B.M4(ref object? o)' (possibly because of nullability attributes). // public void M4(ref object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M4").WithArguments("o", "void C.M4(ref object o)", "void B.M4(ref object? o)").WithLocation(20, 17), // (22,17): warning CS8767: Nullability of reference types in type of parameter 'o' of 'void C.M6(in object o)' doesn't match implicitly implemented member 'void B.M6(in object? o)' (possibly because of nullability attributes). // public void M6(in object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M6").WithArguments("o", "void C.M6(in object o)", "void B.M6(in object? o)").WithLocation(22, 17), // (23,50): warning CS8767: Nullability of reference types in type of parameter 'o' of 'void C.this[object o].set' doesn't match implicitly implemented member 'void B.this[object? o].set' (possibly because of nullability attributes). // public object this[object o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("o", "void C.this[object o].set", "void B.this[object? o].set").WithLocation(23, 50), // (23,50): warning CS8767: Nullability of reference types in type of parameter 'value' of 'void C.this[object o].set' doesn't match implicitly implemented member 'void B.this[object? o].set' (possibly because of nullability attributes). // public object this[object o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void C.this[object o].set", "void B.this[object? o].set").WithLocation(23, 50), // (24,37): warning CS8767: Nullability of reference types in type of parameter 's' of 'string C.this[string s].get' doesn't match implicitly implemented member 'string B.this[string? s].get' (possibly because of nullability attributes). // public string this[string s] => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "null!").WithArguments("s", "string C.this[string s].get", "string B.this[string? s].get").WithLocation(24, 37), // (25,35): warning CS8767: Nullability of reference types in type of parameter 'a' of 'void C.this[int[] a].set' doesn't match implicitly implemented member 'void B.this[int[]? a].set' (possibly because of nullability attributes). // public string this[int[] a] { set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("a", "void C.this[int[] a].set", "void B.this[int[]? a].set").WithLocation(25, 35) ); } [Fact] public void Implement_NullabilityContravariance_Implicit_03() { var src = @" interface B { object? this[object? o] { get; set; } } class C { #nullable disable public virtual object this[object o] { get => null!; set { } } #nullable enable } class D : C, B { public override object this[object o] { get => null!; } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,45): warning CS8767: Nullability of reference types in type of parameter 'o' of 'object D.this[object o].get' doesn't match implicitly implemented member 'object? B.this[object? o].get' (possibly because of nullability attributes). // public override object this[object o] { get => null!; } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "get").WithArguments("o", "object D.this[object o].get", "object? B.this[object? o].get").WithLocation(14, 45) ); } [Fact] public void Implement_NullabilityContravariance_Implicit_04() { var src = @" interface B { object? this[object? o] { get; set; } } class C { public virtual object this[object o] { get => null!; set { } } } class D : C, B { #nullable disable public override object this[object o #nullable enable ] { set {} } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,14): warning CS8767: Nullability of reference types in type of parameter 'o' of 'object C.this[object o].get' doesn't match implicitly implemented member 'object? B.this[object? o].get' (possibly because of nullability attributes). // class D : C, B Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "B").WithArguments("o", "object C.this[object o].get", "object? B.this[object? o].get").WithLocation(10, 14) ); } [Fact] public void Implement_NullabilityContravariance_Explicit_01() { var src = @" interface I<out T> {} interface A { void M(object o); void M2((object, object) t); void M3(I<object> i); void M4(ref object o); void M5(out object o); void M6(in object o); object this[object o] { get; set; } string this[string s] { get; } string this[int[] a] { set; } } class B : A { void A.M(object? o) { } void A.M2((object?, object?) t) { } void A.M3(I<object?> i) { } void A.M4(ref object? o) { } // warn void A.M5(out object? o) => throw null!; // warn void A.M6(in object? o) { } object? A.this[object? o] { get => null!; set { } } // warn string A.this[string? s] => null!; string A.this[int[]? a] { set { } } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,12): warning CS8769: Nullability of reference types in type of parameter 'o' doesn't match implemented member 'void A.M4(ref object o)' (possibly because of nullability attributes). // void A.M4(ref object? o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "M4").WithArguments("o", "void A.M4(ref object o)").WithLocation(20, 12), // (21,12): warning CS8769: Nullability of reference types in type of parameter 'o' doesn't match implemented member 'void A.M5(out object o)' (possibly because of nullability attributes). // void A.M5(out object? o) => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "M5").WithArguments("o", "void A.M5(out object o)").WithLocation(21, 12), // (23,33): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'object A.this[object o].get' (possibly because of nullability attributes). // object? A.this[object? o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("object A.this[object o].get").WithLocation(23, 33) ); } [Fact] public void Implement_NullabilityContravariance_Explicit_02() { var src = @" interface I<out T> {} interface B { void M(object? o); void M2((object?, object?) t); void M3(I<object?> i); void M4(ref object? o); void M5(out object? o); void M6(in object? o); object? this[object? o] { get; set; } string this[string? s] { get; } string this[int[]? a] { set; } } class C : B { void B.M(object o) { } // warn void B.M2((object, object) t) { } // warn void B.M3(I<object> i) { } // warn void B.M4(ref object o) { } // warn void B.M5(out object o) => throw null!; void B.M6(in object o) { } // warn object B.this[object o] { get => null!; set { } } // warn string B.this[string s] => null!; // warn string B.this[int[] a] { set { } } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,12): warning CS8769: Nullability of reference types in type of parameter 'o' doesn't match implemented member 'void B.M(object? o)' (possibly because of nullability attributes). // void B.M(object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "M").WithArguments("o", "void B.M(object? o)").WithLocation(17, 12), // (18,12): warning CS8617: Nullability of reference types in type of parameter 't' doesn't match implemented member 'void B.M2((object?, object?) t)'. // void B.M2((object, object) t) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "M2").WithArguments("t", "void B.M2((object?, object?) t)").WithLocation(18, 12), // (19,12): warning CS8617: Nullability of reference types in type of parameter 'i' doesn't match implemented member 'void B.M3(I<object?> i)'. // void B.M3(I<object> i) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "M3").WithArguments("i", "void B.M3(I<object?> i)").WithLocation(19, 12), // (20,12): warning CS8769: Nullability of reference types in type of parameter 'o' doesn't match implemented member 'void B.M4(ref object? o)' (possibly because of nullability attributes). // void B.M4(ref object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "M4").WithArguments("o", "void B.M4(ref object? o)").WithLocation(20, 12), // (22,12): warning CS8769: Nullability of reference types in type of parameter 'o' doesn't match implemented member 'void B.M6(in object? o)' (possibly because of nullability attributes). // void B.M6(in object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "M6").WithArguments("o", "void B.M6(in object? o)").WithLocation(22, 12), // (23,45): warning CS8769: Nullability of reference types in type of parameter 'o' doesn't match implemented member 'void B.this[object? o].set' (possibly because of nullability attributes). // object B.this[object o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("o", "void B.this[object? o].set").WithLocation(23, 45), // (23,45): warning CS8769: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void B.this[object? o].set' (possibly because of nullability attributes). // object B.this[object o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void B.this[object? o].set").WithLocation(23, 45), // (24,32): warning CS8769: Nullability of reference types in type of parameter 's' doesn't match implemented member 'string B.this[string? s].get' (possibly because of nullability attributes). // string B.this[string s] => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "null!").WithArguments("s", "string B.this[string? s].get").WithLocation(24, 32), // (25,30): warning CS8769: Nullability of reference types in type of parameter 'a' doesn't match implemented member 'void B.this[int[]? a].set' (possibly because of nullability attributes). // string B.this[int[] a] { set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("a", "void B.this[int[]? a].set").WithLocation(25, 30) ); } [Fact] public void Partial_NullabilityContravariance_01() { var src = @" interface I<out T> {} partial class A { partial void M(object o); partial void M2((object, object) t); partial void M3(I<object> i); partial void M4(ref object o); partial void M6(in object o); } partial class A { partial void M(object? o) { } partial void M2((object?, object?) t) { } partial void M3(I<object?> i) { } partial void M4(ref object? o) { } // warn partial void M6(in object? o) { } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,18): warning CS8826: Partial method declarations 'void A.M(object o)' and 'void A.M(object? o)' have signature differences. // partial void M(object? o) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void A.M(object o)", "void A.M(object? o)").WithLocation(13, 18), // (14,18): warning CS8826: Partial method declarations 'void A.M2((object, object) t)' and 'void A.M2((object?, object?) t)' have signature differences. // partial void M2((object?, object?) t) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M2").WithArguments("void A.M2((object, object) t)", "void A.M2((object?, object?) t)").WithLocation(14, 18), // (15,18): warning CS8826: Partial method declarations 'void A.M3(I<object> i)' and 'void A.M3(I<object?> i)' have signature differences. // partial void M3(I<object?> i) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M3").WithArguments("void A.M3(I<object> i)", "void A.M3(I<object?> i)").WithLocation(15, 18), // (16,18): warning CS8611: Nullability of reference types in type of parameter 'o' doesn't match partial method declaration. // partial void M4(ref object? o) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M4").WithArguments("o").WithLocation(16, 18), // (17,18): warning CS8826: Partial method declarations 'void A.M6(in object o)' and 'void A.M6(in object? o)' have signature differences. // partial void M6(in object? o) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M6").WithArguments("void A.M6(in object o)", "void A.M6(in object? o)").WithLocation(17, 18) ); } [Fact] public void Partial_NullabilityContravariance_02() { var src = @" interface I<out T> {} partial class B { partial void M(object? o); partial void M2((object?, object?) t); partial void M3(I<object?> i); partial void M4(ref object? o); partial void M6(in object? o); } partial class B { partial void M(object o) { } // warn partial void M2((object, object) t) { } // warn partial void M3(I<object> i) { } // warn partial void M4(ref object o) { } // warn partial void M6(in object o) { } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,18): warning CS8611: Nullability of reference types in type of parameter 'o' doesn't match partial method declaration. // partial void M(object o) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M").WithArguments("o").WithLocation(13, 18), // (14,18): warning CS8611: Nullability of reference types in type of parameter 't' doesn't match partial method declaration. // partial void M2((object, object) t) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M2").WithArguments("t").WithLocation(14, 18), // (15,18): warning CS8611: Nullability of reference types in type of parameter 'i' doesn't match partial method declaration. // partial void M3(I<object> i) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M3").WithArguments("i").WithLocation(15, 18), // (16,18): warning CS8611: Nullability of reference types in type of parameter 'o' doesn't match partial method declaration. // partial void M4(ref object o) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M4").WithArguments("o").WithLocation(16, 18), // (17,18): warning CS8611: Nullability of reference types in type of parameter 'o' doesn't match partial method declaration. // partial void M6(in object o) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M6").WithArguments("o").WithLocation(17, 18) ); } [Fact] public void Implementing_07() { var source = @" class C { public static void Main() { } } interface IA { void M1(string[] x); void M2<T>(T[] x) where T : class; void M3<T>(T?[]? x) where T : class; } class B : IA { public void M1(string?[] x) { } public void M2<T>(T?[] x) where T : class { } public void M3<T>(T?[]? x) where T : class { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var ia = compilation.GetTypeByMetadataName("IA"); var b = compilation.GetTypeByMetadataName("B"); foreach (var memberName in new[] { "M1", "M2" }) { var member = ia.GetMember<MethodSymbol>(memberName); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.False(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var member = ia.GetMember<MethodSymbol>("M3"); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.True(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } [Fact] public void Implementing_08() { var source = @" class C { public static void Main() { } } interface IA { void M1(string[] x); void M2<T>(T[] x) where T : class; void M3<T>(T?[]? x) where T : class; } class B : IA { void IA.M1(string?[] x) { } void IA.M2<T>(T?[] x) { } void IA.M3<T>(T?[]? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (20,13): error CS0539: 'B.M2<T>(T?[])' in explicit interface declaration is not found among members of the interface that can be implemented // void IA.M2<T>(T?[] x) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M2").WithArguments("B.M2<T>(T?[])").WithLocation(20, 13), // (24,13): error CS0539: 'B.M3<T>(T?[]?)' in explicit interface declaration is not found among members of the interface that can be implemented // void IA.M3<T>(T?[]? x) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M3").WithArguments("B.M3<T>(T?[]?)").WithLocation(24, 13), // (14,11): error CS0535: 'B' does not implement interface member 'IA.M3<T>(T?[]?)' // class B : IA Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IA").WithArguments("B", "IA.M3<T>(T?[]?)").WithLocation(14, 11), // (14,11): error CS0535: 'B' does not implement interface member 'IA.M2<T>(T[])' // class B : IA Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IA").WithArguments("B", "IA.M2<T>(T[])").WithLocation(14, 11), // (20,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void IA.M2<T>(T?[] x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(20, 24), // (24,25): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void IA.M3<T>(T?[]? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(24, 25)); } [Fact] public void Overriding_20() { var source = @" class C { public static void Main() { } } abstract class A1 { public abstract int this[string?[] x] {get; set;} } abstract class A2 { public abstract int this[string[] x] {get; set;} } abstract class A3 { public abstract int this[string?[]? x] {get; set;} } class B1 : A1 { public override int this[string[] x] { get {throw new System.NotImplementedException();} set {} // 1 } } class B2 : A2 { public override int this[string[]? x] { get {throw new System.NotImplementedException();} set {} } } class B3 : A3 { public override int this[string?[]? x] { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (27,9): warning CS8610: Nullability of reference types in type of parameter 'x' doesn't match overridden member. // set {} // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("x").WithLocation(27, 9) ); foreach (string typeName in new[] { "B1", "B2" }) { foreach (var member in compilation.GetTypeByMetadataName(typeName).GetMembers().OfType<PropertySymbol>()) { Assert.False(member.Parameters[0].TypeWithAnnotations.Equals(member.OverriddenProperty.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } foreach (var member in compilation.GetTypeByMetadataName("B3").GetMembers().OfType<PropertySymbol>()) { Assert.True(member.Parameters[0].TypeWithAnnotations.Equals(member.OverriddenProperty.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "A1", "A2", "A3", "B1", "B2", "B3" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var property in type.GetMembers().OfType<PropertySymbol>()) { Assert.True(property.TypeWithAnnotations.Equals(property.GetMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(property.TypeWithAnnotations.Equals(property.SetMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Implementing_09() { var source = @" class C { public static void Main() { } } interface IA1 { int this[string?[] x] {get; set;} } interface IA2 { int this[string[] x] {get; set;} } interface IA3 { int this[string?[]? x] {get; set;} } class B1 : IA1 { public int this[string[] x] { get {throw new System.NotImplementedException();} set {} // 1 } } class B2 : IA2 { public int this[string[]? x] // 2 { get {throw new System.NotImplementedException();} set {} } } class B3 : IA3 { public int this[string?[]? x] // 3 { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (27,9): warning CS8614: Nullability of reference types in type of parameter 'x' of 'void B1.this[string[] x].set' doesn't match implicitly implemented member 'void IA1.this[string?[] x].set'. // set {} // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("x", "void B1.this[string[] x].set", "void IA1.this[string?[] x].set").WithLocation(27, 9) ); foreach (string[] typeName in new[] { new[] { "IA1", "B1" }, new[] { "IA2", "B2" } }) { var implemented = compilation.GetTypeByMetadataName(typeName[0]).GetMembers().OfType<PropertySymbol>().Single(); var implementing = (PropertySymbol)compilation.GetTypeByMetadataName(typeName[1]).FindImplementationForInterfaceMember(implemented); Assert.False(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var implemented = compilation.GetTypeByMetadataName("IA3").GetMembers().OfType<PropertySymbol>().Single(); var implementing = (PropertySymbol)compilation.GetTypeByMetadataName("B3").FindImplementationForInterfaceMember(implemented); Assert.True(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA1", "IA2", "IA3", "B1", "B2", "B3" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var property in type.GetMembers().OfType<PropertySymbol>()) { Assert.True(property.TypeWithAnnotations.Equals(property.GetMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(property.TypeWithAnnotations.Equals(property.SetMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Implementing_10() { var source = @" class C { public static void Main() { } } interface IA1 { int this[string?[] x] {get; set;} } interface IA2 { int this[string[] x] {get; set;} } interface IA3 { int this[string?[]? x] {get; set;} } class B1 : IA1 { int IA1.this[string[] x] { get {throw new System.NotImplementedException();} set {} // 1 } } class B2 : IA2 { int IA2.this[string[]? x] // 2 { get {throw new System.NotImplementedException();} set {} } } class B3 : IA3 { int IA3.this[string?[]? x] // 3 { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (27,9): warning CS8617: Nullability of reference types in type of parameter 'x' doesn't match implemented member 'void IA1.this[string?[] x].set'. // set {} // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("x", "void IA1.this[string?[] x].set").WithLocation(27, 9) ); foreach (string[] typeName in new[] { new[] { "IA1", "B1" }, new[] { "IA2", "B2" } }) { var implemented = compilation.GetTypeByMetadataName(typeName[0]).GetMembers().OfType<PropertySymbol>().Single(); var implementing = (PropertySymbol)compilation.GetTypeByMetadataName(typeName[1]).FindImplementationForInterfaceMember(implemented); Assert.False(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var implemented = compilation.GetTypeByMetadataName("IA3").GetMembers().OfType<PropertySymbol>().Single(); var implementing = (PropertySymbol)compilation.GetTypeByMetadataName("B3").FindImplementationForInterfaceMember(implemented); Assert.True(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA1", "IA2", "IA3", "B1", "B2", "B3" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var property in type.GetMembers().OfType<PropertySymbol>()) { Assert.True(property.TypeWithAnnotations.Equals(property.GetMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(property.TypeWithAnnotations.Equals(property.SetMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Implementing_11() { var source = @" public interface I1<T> { void M(); } public class A {} public interface I2 : I1<A?> { } public interface I3 : I1<A> { } public class C1 : I2, I1<A> { void I1<A?>.M(){} void I1<A>.M(){} } public class C2 : I1<A>, I2 { void I1<A?>.M(){} void I1<A>.M(){} } public class C3 : I1<A>, I1<A?> { void I1<A?>.M(){} void I1<A>.M(){} } public class C4 : I2, I3 { void I1<A?>.M(){} void I1<A>.M(){} } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,14): warning CS8645: 'I1<A>' is already listed in the interface list on type 'C1' with different nullability of reference types. // public class C1 : I2, I1<A> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C1").WithArguments("I1<A>", "C1").WithLocation(11, 14), // (11,14): error CS8646: 'I1<A?>.M()' is explicitly implemented more than once. // public class C1 : I2, I1<A> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<A?>.M()").WithLocation(11, 14), // (11,14): error CS8646: 'I1<A>.M()' is explicitly implemented more than once. // public class C1 : I2, I1<A> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<A>.M()").WithLocation(11, 14), // (17,14): warning CS8645: 'I1<A?>' is already listed in the interface list on type 'C2' with different nullability of reference types. // public class C2 : I1<A>, I2 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C2").WithArguments("I1<A?>", "C2").WithLocation(17, 14), // (17,14): error CS8646: 'I1<A>.M()' is explicitly implemented more than once. // public class C2 : I1<A>, I2 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<A>.M()").WithLocation(17, 14), // (17,14): error CS8646: 'I1<A?>.M()' is explicitly implemented more than once. // public class C2 : I1<A>, I2 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<A?>.M()").WithLocation(17, 14), // (23,14): warning CS8645: 'I1<A?>' is already listed in the interface list on type 'C3' with different nullability of reference types. // public class C3 : I1<A>, I1<A?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C3").WithArguments("I1<A?>", "C3").WithLocation(23, 14), // (23,14): error CS8646: 'I1<A>.M()' is explicitly implemented more than once. // public class C3 : I1<A>, I1<A?> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<A>.M()").WithLocation(23, 14), // (23,14): error CS8646: 'I1<A?>.M()' is explicitly implemented more than once. // public class C3 : I1<A>, I1<A?> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<A?>.M()").WithLocation(23, 14), // (29,14): warning CS8645: 'I1<A>' is already listed in the interface list on type 'C4' with different nullability of reference types. // public class C4 : I2, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C4").WithArguments("I1<A>", "C4").WithLocation(29, 14), // (29,14): error CS8646: 'I1<A?>.M()' is explicitly implemented more than once. // public class C4 : I2, I3 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<A?>.M()").WithLocation(29, 14), // (29,14): error CS8646: 'I1<A>.M()' is explicitly implemented more than once. // public class C4 : I2, I3 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<A>.M()").WithLocation(29, 14) ); var c1 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C1"); var c1Interfaces = c1.Interfaces(); var c1AllInterfaces = c1.AllInterfaces(); Assert.Equal(2, c1Interfaces.Length); Assert.Equal(3, c1AllInterfaces.Length); Assert.Equal("I2", c1Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c1Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2", c1AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c1AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c1AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c1); var c2 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C2"); var c2Interfaces = c2.Interfaces(); var c2AllInterfaces = c2.AllInterfaces(); Assert.Equal(2, c2Interfaces.Length); Assert.Equal(3, c2AllInterfaces.Length); Assert.Equal("I1<A!>", c2Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2", c2Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c2AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2", c2AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c2AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c2); var c3 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C3"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<A!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c3); var c4 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C4"); var c4Interfaces = c4.Interfaces(); var c4AllInterfaces = c4.AllInterfaces(); Assert.Equal(2, c4Interfaces.Length); Assert.Equal(4, c4AllInterfaces.Length); Assert.Equal("I2", c4Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I3", c4Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2", c4AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c4AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I3", c4AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c4AllInterfaces[3].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c4); void assertExplicitInterfaceImplementations(NamedTypeSymbol c) { var members = c.GetMembers("I1<A>.M"); Assert.Equal(2, members.Length); var cMabImplementations = ((MethodSymbol)members[0]).ExplicitInterfaceImplementations; Assert.Equal(1, cMabImplementations.Length); Assert.Equal("void I1<A?>.M()", cMabImplementations[0].ToTestDisplayString(includeNonNullable: true)); var cMcdImplementations = ((MethodSymbol)members[1]).ExplicitInterfaceImplementations; Assert.Equal(1, cMcdImplementations.Length); Assert.Equal("void I1<A!>.M()", cMcdImplementations[0].ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void Implementing_12() { var source = @" public interface I1<T> { void M1(); void M2(); } public class A {} public class C1 : I1<A?> { public void M1() => System.Console.Write(""C1.M1 ""); void I1<A?>.M2() => System.Console.Write(""C1.M2 ""); } public class C2 : C1, I1<A> { new public void M1() => System.Console.Write(""C2.M1 ""); void I1<A>.M2() => System.Console.Write(""C2.M2 ""); static void Main() { var x = (C1)new C2(); var y = (I1<A?>)x; y.M1(); y.M2(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics(); Action<ModuleSymbol> validate = (m) => { bool isMetadata = m is PEModuleSymbol; var c1 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C1"); var c1Interfaces = c1.Interfaces(); var c1AllInterfaces = c1.AllInterfaces(); Assert.Equal(1, c1Interfaces.Length); Assert.Equal(1, c1AllInterfaces.Length); Assert.Equal("I1<A?>", c1Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c1AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); var c2 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C2"); var c2Interfaces = c2.Interfaces(); var c2AllInterfaces = c2.AllInterfaces(); Assert.Equal(1, c2Interfaces.Length); Assert.Equal(2, c2AllInterfaces.Length); Assert.Equal("I1<A!>", c2Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c2AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c2AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("void C2.M1()", c2.FindImplementationForInterfaceMember(((TypeSymbol)c2Interfaces[0]).GetMember("M1")).ToTestDisplayString(includeNonNullable: true)); Assert.Equal("void C2.M1()", c2.FindImplementationForInterfaceMember(((TypeSymbol)c1Interfaces[0]).GetMember("M1")).ToTestDisplayString(includeNonNullable: true)); var m2 = (MethodSymbol)((TypeSymbol)c2).GetMember("I1<A>.M2"); var m2Implementations = m2.ExplicitInterfaceImplementations; Assert.Equal(1, m2Implementations.Length); Assert.Equal(isMetadata ? "void I1<A>.M2()" : "void I1<A!>.M2()", m2Implementations[0].ToTestDisplayString(includeNonNullable: true)); Assert.Same(m2, c2.FindImplementationForInterfaceMember(((TypeSymbol)c2Interfaces[0]).GetMember("M2"))); Assert.Same(m2, c2.FindImplementationForInterfaceMember(((TypeSymbol)c1Interfaces[0]).GetMember("M2"))); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C2.M1 C2.M2"); } [Fact] public void Implementing_13() { var source = @" public interface I1<T> { void M1(); void M2(); } public class A {} public class C1 : I1<A?> { public void M1() => System.Console.Write(""C1.M1 ""); void I1<A?>.M2() => System.Console.Write(""C1.M2 ""); public virtual void M2() {} } public class C2 : C1, I1<A> { static void Main() { var x = (C1)new C2(); var y = (I1<A>)x; y.M1(); y.M2(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (17,23): warning CS8644: 'C2' does not implement interface member 'I1<A>.M2()'. Nullability of reference types in interface implemented by the base type doesn't match. // public class C2 : C1, I1<A> Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I1<A>").WithArguments("C2", "I1<A>.M2()").WithLocation(17, 23) ); Action<ModuleSymbol> validate = (m) => { bool isMetadata = m is PEModuleSymbol; var c1 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C1"); var c1Interfaces = c1.Interfaces(); var c1AllInterfaces = c1.AllInterfaces(); Assert.Equal(1, c1Interfaces.Length); Assert.Equal(1, c1AllInterfaces.Length); Assert.Equal("I1<A?>", c1Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c1AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); var c2 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C2"); var c2Interfaces = c2.Interfaces(); var c2AllInterfaces = c2.AllInterfaces(); Assert.Equal(1, c2Interfaces.Length); Assert.Equal(2, c2AllInterfaces.Length); Assert.Equal("I1<A!>", c2Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c2AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c2AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("void C1.M1()", c2.FindImplementationForInterfaceMember(((TypeSymbol)c2Interfaces[0]).GetMember("M1")).ToTestDisplayString(includeNonNullable: true)); Assert.Equal("void C1.M1()", c2.FindImplementationForInterfaceMember(((TypeSymbol)c1Interfaces[0]).GetMember("M1")).ToTestDisplayString(includeNonNullable: true)); var m2 = (MethodSymbol)((TypeSymbol)c1).GetMember("I1<A>.M2"); var m2Implementations = m2.ExplicitInterfaceImplementations; Assert.Equal(1, m2Implementations.Length); Assert.Equal(isMetadata ? "void I1<A>.M2()" : "void I1<A?>.M2()", m2Implementations[0].ToTestDisplayString(includeNonNullable: true)); Assert.Same(m2, c2.FindImplementationForInterfaceMember(((TypeSymbol)c2Interfaces[0]).GetMember("M2"))); Assert.Same(m2, c2.FindImplementationForInterfaceMember(((TypeSymbol)c1Interfaces[0]).GetMember("M2"))); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C1.M1 C1.M2"); } [Fact] public void Implementing_14() { var source = @" public interface I1<T> { void M1(); } public class A {} public class C1 : I1<A?> { } public class C2 : C1, I1<A> { } public class C3 : C1, I1<A?> { } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,19): error CS0535: 'C1' does not implement interface member 'I1<A?>.M1()' // public class C1 : I1<A?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<A?>").WithArguments("C1", "I1<A?>.M1()").WithLocation(9, 19), // (13,23): warning CS8644: 'C2' does not implement interface member 'I1<A>.M1()'. Nullability of reference types in interface implemented by the base type doesn't match. // public class C2 : C1, I1<A> Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I1<A>").WithArguments("C2", "I1<A>.M1()").WithLocation(13, 23) ); } [Fact] public void Implementing_15() { var source1 = @" public interface I1<T> { void M1(); } public class A {} public class C1 : I1<A?> { } "; var comp1 = CreateCompilation(source1, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (9,19): error CS0535: 'C1' does not implement interface member 'I1<A?>.M1()' // public class C1 : I1<A?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<A?>").WithArguments("C1", "I1<A?>.M1()").WithLocation(9, 19) ); var source2 = @" public class C2 : C1, I1<A> { } public class C3 : C1, I1<A?> { } "; var comp2 = CreateCompilation(source2, references: new[] { comp1.ToMetadataReference() }, options: WithNullableEnable()); comp2.VerifyDiagnostics( // (2,23): warning CS8644: 'C2' does not implement interface member 'I1<A>.M1()'. Nullability of reference types in interface implemented by the base type doesn't match. // public class C2 : C1, I1<A> Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I1<A>").WithArguments("C2", "I1<A>.M1()").WithLocation(2, 23) ); } [Fact] public void Implementing_16() { var source = @" public interface I1<T> { void M(); } public interface I2<I2T> : I1<I2T?> where I2T : class { } public interface I3<I3T> : I1<I3T> where I3T : class { } public class C1<T> : I2<T>, I1<T> where T : class { void I1<T?>.M(){} void I1<T>.M(){} } public class C2<T> : I1<T>, I2<T> where T : class { void I1<T?>.M(){} void I1<T>.M(){} } public class C3<T> : I1<T>, I1<T?> where T : class { void I1<T?>.M(){} void I1<T>.M(){} } public class C4<T> : I2<T>, I3<T> where T : class { void I1<T?>.M(){} void I1<T>.M(){} } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,14): warning CS8645: 'I1<T>' is already listed in the interface list on type 'C1<T>' with different nullability of reference types. // public class C1<T> : I2<T>, I1<T> where T : class Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C1").WithArguments("I1<T>", "C1<T>").WithLocation(10, 14), // (10,14): error CS8646: 'I1<T?>.M()' is explicitly implemented more than once. // public class C1<T> : I2<T>, I1<T> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<T?>.M()").WithLocation(10, 14), // (10,14): error CS8646: 'I1<T>.M()' is explicitly implemented more than once. // public class C1<T> : I2<T>, I1<T> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<T>.M()").WithLocation(10, 14), // (16,14): warning CS8645: 'I1<T?>' is already listed in the interface list on type 'C2<T>' with different nullability of reference types. // public class C2<T> : I1<T>, I2<T> where T : class Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C2").WithArguments("I1<T?>", "C2<T>").WithLocation(16, 14), // (16,14): error CS8646: 'I1<T>.M()' is explicitly implemented more than once. // public class C2<T> : I1<T>, I2<T> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<T>.M()").WithLocation(16, 14), // (16,14): error CS8646: 'I1<T?>.M()' is explicitly implemented more than once. // public class C2<T> : I1<T>, I2<T> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<T?>.M()").WithLocation(16, 14), // (22,14): warning CS8645: 'I1<T?>' is already listed in the interface list on type 'C3<T>' with different nullability of reference types. // public class C3<T> : I1<T>, I1<T?> where T : class Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C3").WithArguments("I1<T?>", "C3<T>").WithLocation(22, 14), // (22,14): error CS8646: 'I1<T>.M()' is explicitly implemented more than once. // public class C3<T> : I1<T>, I1<T?> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<T>.M()").WithLocation(22, 14), // (22,14): error CS8646: 'I1<T?>.M()' is explicitly implemented more than once. // public class C3<T> : I1<T>, I1<T?> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<T?>.M()").WithLocation(22, 14), // (28,14): warning CS8645: 'I1<T>' is already listed in the interface list on type 'C4<T>' with different nullability of reference types. // public class C4<T> : I2<T>, I3<T> where T : class Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C4").WithArguments("I1<T>", "C4<T>").WithLocation(28, 14), // (28,14): error CS8646: 'I1<T?>.M()' is explicitly implemented more than once. // public class C4<T> : I2<T>, I3<T> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<T?>.M()").WithLocation(28, 14), // (28,14): error CS8646: 'I1<T>.M()' is explicitly implemented more than once. // public class C4<T> : I2<T>, I3<T> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<T>.M()").WithLocation(28, 14) ); var c1 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C1`1"); var c1Interfaces = c1.Interfaces(); var c1AllInterfaces = c1.AllInterfaces(); Assert.Equal(2, c1Interfaces.Length); Assert.Equal(3, c1AllInterfaces.Length); Assert.Equal("I2<T!>", c1Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T!>", c1Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2<T!>", c1AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T?>", c1AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T!>", c1AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c1); var c2 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C2`1"); var c2Interfaces = c2.Interfaces(); var c2AllInterfaces = c2.AllInterfaces(); Assert.Equal(2, c2Interfaces.Length); Assert.Equal(3, c2AllInterfaces.Length); Assert.Equal("I1<T!>", c2Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2<T!>", c2Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T!>", c2AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2<T!>", c2AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T?>", c2AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c2); var c3 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C3`1"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<T!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T?>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c3); var c4 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C4`1"); var c4Interfaces = c4.Interfaces(); var c4AllInterfaces = c4.AllInterfaces(); Assert.Equal(2, c4Interfaces.Length); Assert.Equal(4, c4AllInterfaces.Length); Assert.Equal("I2<T!>", c4Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I3<T!>", c4Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2<T!>", c4AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T?>", c4AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I3<T!>", c4AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T!>", c4AllInterfaces[3].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c4); void assertExplicitInterfaceImplementations(NamedTypeSymbol c) { var members = c.GetMembers("I1<T>.M"); Assert.Equal(2, members.Length); var cMabImplementations = ((MethodSymbol)members[0]).ExplicitInterfaceImplementations; Assert.Equal(1, cMabImplementations.Length); Assert.Equal("void I1<T?>.M()", cMabImplementations[0].ToTestDisplayString(includeNonNullable: true)); var cMcdImplementations = ((MethodSymbol)members[1]).ExplicitInterfaceImplementations; Assert.Equal(1, cMcdImplementations.Length); Assert.Equal("void I1<T!>.M()", cMcdImplementations[0].ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void Implementing_17() { var source = @" public interface I1<T> { void M(); } public class C3<T, U> : I1<T>, I1<U?> where T : class where U : class { void I1<U?>.M(){} void I1<T>.M(){} } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,14): error CS0695: 'C3<T, U>' cannot implement both 'I1<T>' and 'I1<U?>' because they may unify for some type parameter substitutions // public class C3<T, U> : I1<T>, I1<U?> where T : class where U : class Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I1<T>", "I1<U?>").WithLocation(7, 14) ); var c3 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C3`2"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<T!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<U?>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<U?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c3); void assertExplicitInterfaceImplementations(NamedTypeSymbol c) { var cMabImplementations = ((MethodSymbol)((TypeSymbol)c).GetMember("I1<T>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMabImplementations.Length); Assert.Equal("void I1<T!>.M()", cMabImplementations[0].ToTestDisplayString(includeNonNullable: true)); var cMcdImplementations = ((MethodSymbol)((TypeSymbol)c).GetMember("I1<U>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMcdImplementations.Length); Assert.Equal("void I1<U?>.M()", cMcdImplementations[0].ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void Implementing_18() { var source = @" public interface I1<T> { void M(); } public class A {} public class C3 : I1<A> { void I1<A?>.M() { System.Console.Write(""C3.M ""); } static void Main() { var x = new C3(); ((I1<A>)x).M(); ((I1<A?>)x).M(); } } public class C4 : I1<A?> { void I1<A?>.M(){} } "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (11,10): warning CS8643: Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type. // void I1<A?>.M() Diagnostic(ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface, "I1<A?>").WithLocation(11, 10) ); Action<ModuleSymbol> validate = (ModuleSymbol m) => { bool isMetadata = m is PEModuleSymbol; var c3 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C3"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); Assert.Equal(1, c3Interfaces.Length); Assert.Equal(1, c3AllInterfaces.Length); Assert.Equal("I1<A!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); var method = (MethodSymbol)((TypeSymbol)c3).GetMember("I1<A>.M"); Assert.Equal("I1<A>.M", method.Name); var mImplementations = method.ExplicitInterfaceImplementations; Assert.Equal(1, mImplementations.Length); Assert.Equal(isMetadata ? "void I1<A>.M()" : "void I1<A?>.M()", mImplementations[0].ToTestDisplayString(includeNonNullable: true)); Assert.Same(method, c3.FindImplementationForInterfaceMember(((TypeSymbol)c3Interfaces[0]).GetMember("M"))); Assert.Same(method, c3.FindImplementationForInterfaceMember(mImplementations[0])); Assert.Same(method, c3.FindImplementationForInterfaceMember(m.GlobalNamespace.GetTypeMember("C4").InterfacesNoUseSiteDiagnostics()[0].GetMember("M"))); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C3.M C3.M"); } [Fact] public void Implementing_19() { var source = @" public interface I1<T> { void M(); } public class A {} public class C3 : I1<A>, I1<A?> { void I1<A?>.M() { System.Console.Write(""C3.M ""); } static void Main() { var x = new C3(); ((I1<A>)x).M(); ((I1<A?>)x).M(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (9,14): warning CS8645: 'I1<A?>' is already listed in the interface list on type 'C3' with different nullability of reference types. // public class C3 : I1<A>, I1<A?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C3").WithArguments("I1<A?>", "C3").WithLocation(9, 14) ); Action<ModuleSymbol> validate = (ModuleSymbol m) => { bool isMetadata = m is PEModuleSymbol; var c3 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C3"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); if (isMetadata) { Assert.Equal(1, c3Interfaces.Length); Assert.Equal(1, c3AllInterfaces.Length); Assert.Equal("I1<A!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); } else { Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<A!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); } var method = (MethodSymbol)((TypeSymbol)c3).GetMember("I1<A>.M"); Assert.Equal("I1<A>.M", method.Name); var mImplementations = method.ExplicitInterfaceImplementations; Assert.Equal(1, mImplementations.Length); Assert.Equal(isMetadata ? "void I1<A>.M()" : "void I1<A?>.M()", mImplementations[0].ToTestDisplayString(includeNonNullable: true)); Assert.Same(method, c3.FindImplementationForInterfaceMember(((TypeSymbol)c3Interfaces[0]).GetMember("M"))); Assert.Same(method, c3.FindImplementationForInterfaceMember(mImplementations[0])); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C3.M C3.M"); } [Fact] public void Implementing_20() { var source = @" public interface I1<T> { void M(); } public class A {} public interface I2 : I1<A?> {} public class C3 : I2, I1<A> { void I1<A?>.M() { System.Console.Write(""C3.M ""); } static void Main() { var x = new C3(); ((I1<A>)x).M(); ((I1<A?>)x).M(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (12,14): warning CS8645: 'I1<A>' is already listed in the interface list on type 'C3' with different nullability of reference types. // public class C3 : I2, I1<A> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C3").WithArguments("I1<A>", "C3").WithLocation(12, 14) ); Action<ModuleSymbol> validate = (ModuleSymbol m) => { bool isMetadata = m is PEModuleSymbol; var c3 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C3"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); if (isMetadata) { Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I2", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); } else { Assert.Equal(2, c3Interfaces.Length); Assert.Equal(3, c3AllInterfaces.Length); Assert.Equal("I2", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); } var method = (MethodSymbol)((TypeSymbol)c3).GetMember("I1<A>.M"); Assert.Equal("I1<A>.M", method.Name); var mImplementations = method.ExplicitInterfaceImplementations; Assert.Equal(1, mImplementations.Length); Assert.Equal(isMetadata ? "void I1<A>.M()" : "void I1<A?>.M()", mImplementations[0].ToTestDisplayString(includeNonNullable: true)); Assert.Same(method, c3.FindImplementationForInterfaceMember(((TypeSymbol)c3Interfaces[1]).GetMember("M"))); Assert.Same(method, c3.FindImplementationForInterfaceMember(mImplementations[0])); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C3.M C3.M"); } [Fact] public void Implementing_21() { var source = @" public interface I1<T> { void M(); } public class A {} public partial class C3 : I1<A> { void I1<A?>.M() { System.Console.Write(""C3.M ""); } static void Main() { var x = new C3(); ((I1<A>)x).M(); ((I1<A?>)x).M(); } } public partial class C3 : I1<A?> {} "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (9,22): warning CS8645: 'I1<A?>' is already listed in the interface list on type 'C3' with different nullability of reference types. // public partial class C3 : I1<A> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C3").WithArguments("I1<A?>", "C3").WithLocation(9, 22) ); Action<ModuleSymbol> validate = (ModuleSymbol m) => { bool isMetadata = m is PEModuleSymbol; var c3 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C3"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); if (isMetadata) { Assert.Equal(1, c3Interfaces.Length); Assert.Equal(1, c3AllInterfaces.Length); Assert.Equal("I1<A!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); } else { Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<A!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); } var method = (MethodSymbol)((TypeSymbol)c3).GetMember("I1<A>.M"); Assert.Equal("I1<A>.M", method.Name); var mImplementations = method.ExplicitInterfaceImplementations; Assert.Equal(1, mImplementations.Length); Assert.Equal(isMetadata ? "void I1<A>.M()" : "void I1<A?>.M()", mImplementations[0].ToTestDisplayString(includeNonNullable: true)); Assert.Same(method, c3.FindImplementationForInterfaceMember(((TypeSymbol)c3Interfaces[0]).GetMember("M"))); Assert.Same(method, c3.FindImplementationForInterfaceMember(mImplementations[0])); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C3.M C3.M"); } [Fact] public void Implementing_23() { var source = @" class C { public static void Main() { } } interface IA { void M1(string[] x); void M2<T>(T[] x) where T : class; void M3<T>(T?[]? x) where T : class; } class B : IA { void IA.M1(string?[] x) { } void IA.M2<T>(T?[] x) where T : class { } void IA.M3<T>(T?[]? x) where T : class { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var ia = compilation.GetTypeByMetadataName("IA"); var b = compilation.GetTypeByMetadataName("B"); foreach (var memberName in new[] { "M1", "M2" }) { var member = ia.GetMember<MethodSymbol>(memberName); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.False(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var member = ia.GetMember<MethodSymbol>("M3"); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.True(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } [Fact] public void Implementing_24() { var source = @" class C { public static void Main() { } } interface IA { string[] M1(); T[] M2<T>() where T : class; T?[]? M3<T>() where T : class; } class B : IA { string?[] IA.M1() { return new string?[] {}; } S?[] IA.M2<S>() where S : class { return new S?[] {}; } S?[]? IA.M3<S>() where S : class { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (23,13): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'T[] IA.M2<T>()'. // S?[] IA.M2<S>() where S : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M2").WithArguments("T[] IA.M2<T>()").WithLocation(23, 13), // (18,18): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'string[] IA.M1()'. // string?[] IA.M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M1").WithArguments("string[] IA.M1()").WithLocation(18, 18) ); var ia = compilation.GetTypeByMetadataName("IA"); var b = compilation.GetTypeByMetadataName("B"); foreach (var memberName in new[] { "M1", "M2" }) { var member = ia.GetMember<MethodSymbol>(memberName); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.False(implementing.ReturnTypeWithAnnotations.Equals(implemented.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var member = ia.GetMember<MethodSymbol>("M3"); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.True(implementing.ReturnTypeWithAnnotations.Equals(implemented.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } [Fact] public void Implementing_25() { var source = @" #nullable enable interface I { void M<T>(T value) where T : class; } class C : I { void I.M<T>(T value) { T? x = value; } } "; var compilation = CreateCompilation(source).VerifyDiagnostics(); var c = compilation.GetTypeByMetadataName("C"); var member = c.GetMember<MethodSymbol>("I.M"); var tp = member.GetMemberTypeParameters()[0]; Assert.True(tp.IsReferenceType); Assert.False(tp.IsNullableType()); } [Fact] public void PartialMethods_01() { var source = @" class C { public static void Main() { } } partial class C1 { partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; } partial class C1 { partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class { } }"; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (16,18): warning CS8611: Nullability of reference types in type of parameter 'y' doesn't match partial method declaration. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M1").WithArguments("y").WithLocation(16, 18), // (16,18): warning CS8611: Nullability of reference types in type of parameter 'z' doesn't match partial method declaration. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M1").WithArguments("z").WithLocation(16, 18) ); var c1 = compilation.GetTypeByMetadataName("C1"); var m1 = c1.GetMember<MethodSymbol>("M1"); var m1Impl = m1.PartialImplementationPart; var m1Def = m1.ConstructIfGeneric(m1Impl.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); for (int i = 0; i < 3; i++) { Assert.False(m1Impl.Parameters[i].TypeWithAnnotations.Equals(m1Def.Parameters[i].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } Assert.True(m1Impl.Parameters[3].TypeWithAnnotations.Equals(m1Def.Parameters[3].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); compilation = CreateCompilation("", references: new[] { compilation.EmitToImageReference() }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); c1 = compilation.GetTypeByMetadataName("C1"); m1 = c1.GetMember<MethodSymbol>("M1"); Assert.Equal("void C1.M1<T>(T! x, T?[]! y, System.Action<T!>! z, System.Action<T?[]?>?[]? u)", m1.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void PartialMethods_02_01() { var source = @" partial class C1 { #nullable disable partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; } partial class C1 { partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class { } }"; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (5,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 30), // (5,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 29), // (5,72): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 72), // (5,71): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 71), // (5,75): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 75), // (5,77): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 77), // (5,80): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 80), // (10,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 25), // (10,24): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(10, 24), // (10,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 33), // (10,53): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 53), // (10,52): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(10, 52), // (10,74): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 74), // (10,73): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(10, 73), // (10,77): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 77), // (10,79): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 79), // (10,82): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 82) ); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void PartialMethods_02_02() { var source = @" partial class C1 { #nullable disable partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; } #nullable enable partial class C1 { partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class { } }"; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (5,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 30), // (5,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 29), // (5,72): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 72), // (5,71): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 71), // (5,75): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 75), // (5,77): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 77), // (5,80): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 80), // (10,18): warning CS8611: Nullability of reference types in type of parameter 'y' doesn't match partial method declaration. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M1").WithArguments("y").WithLocation(10, 18) ); } [Fact] public void PartialMethods_03() { var source = @" class C { public static void Main() { } } partial class C1 { partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; } partial class C1 { #nullable disable partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class { } }"; var compilation = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (11,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 30), // (11,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(11, 29), // (11,72): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 72), // (11,71): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(11, 71), // (11,75): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 75), // (11,77): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 77), // (11,80): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 80), // (17,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 25), // (17,24): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(17, 24), // (17,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 33), // (17,53): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 53), // (17,52): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(17, 52), // (17,74): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 74), // (17,73): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(17, 73), // (17,77): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 77), // (17,79): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 79), // (17,82): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 82) ); } [Fact] public void Overloading_01() { var source = @" class A { void Test1(string? x1) {} void Test1(string x2) {} string Test2(string y1) { return y1; } string? Test2(string y2) { return y2; } } "; CreateCompilation(new[] { source }, options: WithNullableEnable()). VerifyDiagnostics( // (5,10): error CS0111: Type 'A' already defines a member called 'Test1' with the same parameter types // void Test1(string x2) {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Test1").WithArguments("Test1", "A").WithLocation(5, 10), // (8,13): error CS0111: Type 'A' already defines a member called 'Test2' with the same parameter types // string? Test2(string y2) { return y2; } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Test2").WithArguments("Test2", "A").WithLocation(8, 13) ); } [Fact] public void Overloading_02() { var source = @" class A { public void M1<T>(T? x) where T : struct { } public void M1<T>(T? x) where T : class { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); } [Fact] public void Test1() { CSharpCompilation c = CreateCompilation( new[] { @"#pragma warning disable 8618 class C { static void Main() { } void Test1() { string? x1 = null; string? y1 = x1; string z1 = x1; } void Test2() { string? x2 = """"; string z2 = x2; } void Test3() { string? x3; string z3 = x3; } void Test4() { string x4; string z4 = x4; } void Test5() { string? x5 = """"; x5 = null; string? y5; y5 = x5; string z5; z5 = x5; } void Test6() { string? x6 = """"; string z6; z6 = x6; } void Test7() { CL1? x7 = null; CL1 y7 = x7.P1; CL1 z7 = x7?.P1; x7 = new CL1(); CL1 u7 = x7.P1; } void Test8() { CL1? x8 = new CL1(); CL1 y8 = x8.M1(); x8 = null; CL1 u8 = x8.M1(); CL1 z8 = x8?.M1(); } void Test9(CL1? x9, CL1 y9) { CL1 u9; u9 = x9; u9 = y9; x9 = y9; CL1 v9; v9 = x9; y9 = null; } void Test10(CL1 x10) { CL1 u10; u10 = x10.P1; u10 = x10.P2; u10 = x10.M1(); u10 = x10.M2(); CL1? v10; v10 = x10.P2; v10 = x10.M2(); } void Test11(CL1 x11, CL1? y11) { CL1 u11; u11 = x11.F1; u11 = x11.F2; CL1? v11; v11 = x11.F2; x11.F2 = x11.F1; u11 = x11.F2; v11 = y11.F1; } void Test12(CL1 x12) { S1 y12; CL1 u12; u12 = y12.F3; u12 = y12.F4; } void Test13(CL1 x13) { S1 y13; CL1? u13; u13 = y13.F3; u13 = y13.F4; } void Test14(CL1 x14) { S1 y14; y14.F3 = null; y14.F4 = null; y14.F3 = x14; y14.F4 = x14; } void Test15(CL1 x15) { S1 y15; CL1 u15; y15.F3 = null; y15.F4 = null; u15 = y15.F3; u15 = y15.F4; CL1? v15; v15 = y15.F4; y15.F4 = x15; u15 = y15.F4; } void Test16() { S1 y16; CL1 u16; y16 = new S1(); u16 = y16.F3; u16 = y16.F4; } void Test17(CL1 z17) { S1 x17; x17.F4 = z17; S1 y17 = new S1(); CL1 u17; u17 = y17.F4; y17 = x17; CL1 v17; v17 = y17.F4; } void Test18(CL1 z18) { S1 x18; x18.F4 = z18; S1 y18 = x18; CL1 u18; u18 = y18.F4; } void Test19(S1 x19, CL1 z19) { S1 y19; y19.F4 = null; CL1 u19; u19 = y19.F4; x19.F4 = z19; y19 = x19; CL1 v19; v19 = y19.F4; } void Test20(S1 x20, CL1 z20) { S1 y20; y20.F4 = z20; CL1 u20; u20 = y20.F4; y20 = x20; CL1 v20; v20 = y20.F4; } S1 GetS1() { return new S1(); } void Test21(CL1 z21) { S1 y21; y21.F4 = z21; CL1 u21; u21 = y21.F4; y21 = GetS1(); CL1 v21; v21 = y21.F4; } void Test22() { S1 y22; CL1 u22; u22 = y22.F4; y22 = GetS1(); CL1 v22; v22 = y22.F4; } void Test23(CL1 z23) { S2 y23; y23.F5.F4 = z23; CL1 u23; u23 = y23.F5.F4; y23 = GetS2(); CL1 v23; v23 = y23.F5.F4; } S2 GetS2() { return new S2(); } void Test24() { S2 y24; CL1 u24; u24 = y24.F5.F4; // 1 u24 = y24.F5.F4; // 2 y24 = GetS2(); CL1 v24; v24 = y24.F5.F4; } void Test25(CL1 z25) { S2 y25; S2 x25 = GetS2(); x25.F5.F4 = z25; y25 = x25; CL1 v25; v25 = y25.F5.F4; } void Test26(CL1 x26, CL1? y26, CL1 z26) { x26.P1 = y26; x26.P1 = z26; } void Test27(CL1 x27, CL1? y27, CL1 z27) { x27[x27] = y27; x27[x27] = z27; } void Test28(CL1 x28, CL1? y28, CL1 z28) { x28[y28] = z28; } void Test29(CL1 x29, CL1 y29, CL1 z29) { z29 = x29[y29]; z29 = x29[1]; } void Test30(CL1? x30, CL1 y30, CL1 z30) { z30 = x30[y30]; } void Test31(CL1 x31) { x31 = default(CL1); } void Test32(CL1 x32) { var y32 = new CL1() ?? x32; } void Test33(object x33) { var y33 = new { p = (object)null } ?? x33; } } class CL1 { public CL1() { F1 = this; } public CL1 F1; public CL1? F2; public CL1 P1 { get; set; } public CL1? P2 { get; set; } public CL1 M1() { return new CL1(); } public CL1? M2() { return null; } public CL1 this[CL1 x] { get { return x; } set { } } public CL1? this[int x] { get { return null; } set { } } } struct S1 { public CL1 F3; public CL1? F4; } struct S2 { public S1 F5; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string z1 = x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(12, 21), // (24,21): error CS0165: Use of unassigned local variable 'x3' // string z3 = x3; Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(24, 21), // (24,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string z3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(24, 21), // (30,21): error CS0165: Use of unassigned local variable 'x4' // string z4 = x4; Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(30, 21), // (40,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // z5 = x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5").WithLocation(40, 14), // (53,18): warning CS8602: Dereference of a possibly null reference. // CL1 y7 = x7.P1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x7").WithLocation(53, 18), // (54,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z7 = x7?.P1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x7?.P1").WithLocation(54, 18), // (64,18): warning CS8602: Dereference of a possibly null reference. // CL1 u8 = x8.M1(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x8").WithLocation(64, 18), // (65,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z8 = x8?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x8?.M1()").WithLocation(65, 18), // (71,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // u9 = x9; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x9").WithLocation(71, 14), // (76,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y9 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(76, 14), // (83,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u10 = x10.P2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x10.P2").WithLocation(83, 15), // (85,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u10 = x10.M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x10.M2()").WithLocation(85, 15), // (95,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u11 = x11.F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x11.F2").WithLocation(95, 15), // (101,15): warning CS8602: Dereference of a possibly null reference. // v11 = y11.F1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y11").WithLocation(101, 15), // (108,15): error CS0170: Use of possibly unassigned field 'F3' // u12 = y12.F3; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y12.F3").WithArguments("F3").WithLocation(108, 15), // (109,15): error CS0170: Use of possibly unassigned field 'F4' // u12 = y12.F4; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y12.F4").WithArguments("F4").WithLocation(109, 15), // (109,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u12 = y12.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y12.F4").WithLocation(109, 15), // (116,15): error CS0170: Use of possibly unassigned field 'F3' // u13 = y13.F3; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y13.F3").WithArguments("F3").WithLocation(116, 15), // (117,15): error CS0170: Use of possibly unassigned field 'F4' // u13 = y13.F4; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y13.F4").WithArguments("F4").WithLocation(117, 15), // (123,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // y14.F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(123, 18), // (133,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // y15.F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(133, 18), // (135,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u15 = y15.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y15.F3").WithLocation(135, 15), // (136,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u15 = y15.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y15.F4").WithLocation(136, 15), // (149,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u16 = y16.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y16.F3").WithLocation(149, 15), // (150,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u16 = y16.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y16.F4").WithLocation(150, 15), // (161,15): error CS0165: Use of unassigned local variable 'x17' // y17 = x17; Diagnostic(ErrorCode.ERR_UseDefViolation, "x17").WithArguments("x17").WithLocation(161, 15), // (159,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u17 = y17.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y17.F4").WithLocation(159, 15), // (170,18): error CS0165: Use of unassigned local variable 'x18' // S1 y18 = x18; Diagnostic(ErrorCode.ERR_UseDefViolation, "x18").WithArguments("x18").WithLocation(170, 18), // (180,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u19 = y19.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y19.F4").WithLocation(180, 15), // (197,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // v20 = y20.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y20.F4").WithLocation(197, 15), // (213,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // v21 = y21.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y21.F4").WithLocation(213, 15), // (220,15): error CS0170: Use of possibly unassigned field 'F4' // u22 = y22.F4; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y22.F4").WithArguments("F4").WithLocation(220, 15), // (220,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u22 = y22.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y22.F4").WithLocation(220, 15), // (224,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // v22 = y22.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y22.F4").WithLocation(224, 15), // (236,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // v23 = y23.F5.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y23.F5.F4").WithLocation(236, 15), // (248,15): error CS0170: Use of possibly unassigned field 'F4' // u24 = y24.F5.F4; // 1 Diagnostic(ErrorCode.ERR_UseDefViolationField, "y24.F5.F4").WithArguments("F4").WithLocation(248, 15), // (248,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u24 = y24.F5.F4; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y24.F5.F4").WithLocation(248, 15), // (249,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u24 = y24.F5.F4; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y24.F5.F4").WithLocation(249, 15), // (253,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // v24 = y24.F5.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y24.F5.F4").WithLocation(253, 15), // (268,18): warning CS8601: Possible null reference assignment. // x26.P1 = y26; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y26").WithLocation(268, 18), // (274,20): warning CS8601: Possible null reference assignment. // x27[x27] = y27; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y27").WithLocation(274, 20), // (280,13): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1 CL1.this[CL1 x]'. // x28[y28] = z28; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y28").WithArguments("x", "CL1 CL1.this[CL1 x]").WithLocation(280, 13), // (286,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // z29 = x29[1]; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x29[1]").WithLocation(286, 15), // (291,15): warning CS8602: Dereference of a possibly null reference. // z30 = x30[y30]; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x30").WithLocation(291, 15), // (296,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // x31 = default(CL1); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(CL1)").WithLocation(296, 15), // (306,29): warning CS8600: Converting null literal or possible null value to non-nullable type. // var y33 = new { p = (object)null } ?? x33; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)null").WithLocation(306, 29) ); } [Fact] public void PassingParameters_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void M1(CL1 p) {} void Test1(CL1? x1, CL1 y1) { M1(x1); M1(y1); } void Test2() { CL1? x2; M1(x2); } void M2(ref CL1? p) {} void Test3() { CL1 x3; M2(ref x3); } void Test4(CL1 x4) { M2(ref x4); } void M3(out CL1? p) { p = null; } void Test5() { CL1 x5; M3(out x5); } void M4(ref CL1 p) {} void Test6() { CL1? x6 = null; M4(ref x6); } void M5(out CL1 p) { p = new CL1(); } void Test7() { CL1? x7 = null; CL1 u7 = x7; M5(out x7); CL1 v7 = x7; } void M6(CL1 p1, CL1? p2) {} void Test8(CL1? x8, CL1? y8) { M6(p2: x8, p1: y8); } void M7(params CL1[] p1) {} void Test9(CL1 x9, CL1? y9) { M7(x9, y9); } void Test10(CL1? x10, CL1 y10) { M7(x10, y10); } void M8(CL1 p1, params CL1[] p2) {} void Test11(CL1? x11, CL1 y11, CL1? z11) { M8(x11, y11, z11); } void Test12(CL1? x12, CL1 y12) { M8(p2: x12, p1: y12); } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,12): warning CS8604: Possible null reference argument for parameter 'p' in 'void C.M1(CL1 p)'. // M1(x1); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("p", "void C.M1(CL1 p)").WithLocation(12, 12), // (19,12): error CS0165: Use of unassigned local variable 'x2' // M1(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(19, 12), // (19,12): warning CS8604: Possible null reference argument for parameter 'p' in 'void C.M1(CL1 p)'. // M1(x2); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("p", "void C.M1(CL1 p)").WithLocation(19, 12), // (27,16): error CS0165: Use of unassigned local variable 'x3' // M2(ref x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(27, 16), // (27,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // M2(ref x3); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(27, 16), // (32,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // M2(ref x4); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x4").WithLocation(32, 16), // (40,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // M3(out x5); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5").WithLocation(40, 16), // (48,16): warning CS8601: Possible null reference assignment. // M4(ref x6); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x6").WithLocation(48, 16), // (56,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u7 = x7; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x7").WithLocation(56, 18), // (65,24): warning CS8604: Possible null reference argument for parameter 'p1' in 'void C.M6(CL1 p1, CL1? p2)'. // M6(p2: x8, p1: y8); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y8").WithArguments("p1", "void C.M6(CL1 p1, CL1? p2)").WithLocation(65, 24), // (72,16): warning CS8604: Possible null reference argument for parameter 'p1' in 'void C.M7(params CL1[] p1)'. // M7(x9, y9); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y9").WithArguments("p1", "void C.M7(params CL1[] p1)").WithLocation(72, 16), // (77,12): warning CS8604: Possible null reference argument for parameter 'p1' in 'void C.M7(params CL1[] p1)'. // M7(x10, y10); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x10").WithArguments("p1", "void C.M7(params CL1[] p1)").WithLocation(77, 12), // (84,12): warning CS8604: Possible null reference argument for parameter 'p1' in 'void C.M8(CL1 p1, params CL1[] p2)'. // M8(x11, y11, z11); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x11").WithArguments("p1", "void C.M8(CL1 p1, params CL1[] p2)").WithLocation(84, 12), // (84,22): warning CS8604: Possible null reference argument for parameter 'p2' in 'void C.M8(CL1 p1, params CL1[] p2)'. // M8(x11, y11, z11); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "z11").WithArguments("p2", "void C.M8(CL1 p1, params CL1[] p2)").WithLocation(84, 22), // (89,16): warning CS8604: Possible null reference argument for parameter 'p2' in 'void C.M8(CL1 p1, params CL1[] p2)'. // M8(p2: x12, p1: y12); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x12").WithArguments("p2", "void C.M8(CL1 p1, params CL1[] p2)").WithLocation(89, 16) ); } [Fact] public void PassingParameters_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0 x1) { var y1 = new CL0() { [null] = x1 }; } } class CL0 { public CL0 this[CL0 x] { get { return x; } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // var y1 = new CL0() { [null] = x1 }; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 31)); } [Fact] public void PassingParameters_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0 x1) { var y1 = new CL0() { null }; } } class CL0 : System.Collections.IEnumerable { public void Add(CL0 x) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new System.NotImplementedException(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,30): warning CS8625: Cannot convert null literal to non-nullable reference type. // var y1 = new CL0() { null }; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 30)); } [Fact] public void PassingParameters_04() { var source = @"interface I<T> { } class C { static void F(I<object> x, I<object?> y, I<object>? z, I<object?>? w, I<object?>[]? a) { G(x); G(y); // 1 G(x, x, x); // 2, 3 G(x, y, y); G(x, x, y, z, w); // 4, 5, 6, 7 G(y: x, x: y); // 8, 9 G(y: y, x: x); G(x, a); // 10 G(x, new I<object?>[0]); G(x, new[] { x, x }); // 11 G(x, new[] { y, y }); // note that the array type below is reinferred to 'I<object>[]' // due to previous usage of the variables as call arguments. G(x, new[] { x, y, z }); // 12, 13 G(y: new[] { x, x }, x: y); // 14, 15 G(y: new[] { y, y }, x: x); } static void G(I<object> x, params I<object?>[] y) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,11): warning CS8620: Argument of type 'I<object?>' cannot be used for parameter 'x' of type 'I<object>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object?>", "I<object>", "x", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(7, 11), // (8,14): warning CS8620: Argument of type 'I<object>' cannot be used for parameter 'y' of type 'I<object?>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(x, x, x); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(8, 14), // (8,17): warning CS8620: Argument of type 'I<object>' cannot be used for parameter 'y' of type 'I<object?>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(x, x, x); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(8, 17), // (10,14): warning CS8620: Argument of type 'I<object>' cannot be used for parameter 'y' of type 'I<object?>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(x, x, y, z, w); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(10, 14), // (10,20): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.G(I<object> x, params I<object?>[] y)'. // G(x, x, y, z, w); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "z").WithArguments("y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(10, 20), // (10,20): warning CS8620: Argument of type 'I<object>' cannot be used for parameter 'y' of type 'I<object?>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(x, x, y, z, w); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("I<object>", "I<object?>", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(10, 20), // (10,23): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.G(I<object> x, params I<object?>[] y)'. // G(x, x, y, z, w); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "w").WithArguments("y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(10, 23), // (11,14): warning CS8620: Argument of type 'I<object>' cannot be used for parameter 'y' of type 'I<object?>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(y: x, x: y); // 8, 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(11, 14), // (11,20): warning CS8620: Argument of type 'I<object?>' cannot be used for parameter 'x' of type 'I<object>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(y: x, x: y); // 8, 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object?>", "I<object>", "x", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(11, 20), // (13,14): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.G(I<object> x, params I<object?>[] y)'. // G(x, a); // 10 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(13, 14), // (15,14): warning CS8620: Argument of type 'I<object>[]' cannot be used for parameter 'y' of type 'I<object?>[]' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(x, new[] { x, x }); // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new[] { x, x }").WithArguments("I<object>[]", "I<object?>[]", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(15, 14), // (19,14): warning CS8620: Argument of type 'I<object>[]' cannot be used for parameter 'y' of type 'I<object?>[]' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(x, new[] { x, y, z }); // 12, 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new[] { x, y, z }").WithArguments("I<object>[]", "I<object?>[]", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(19, 14), // (19,25): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // G(x, new[] { x, y, z }); // 12, 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(19, 25), // (20,14): warning CS8620: Argument of type 'I<object>[]' cannot be used for parameter 'y' of type 'I<object?>[]' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(y: new[] { x, x }, x: y); // 14, 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new[] { x, x }").WithArguments("I<object>[]", "I<object?>[]", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(20, 14), // (20,33): warning CS8620: Argument of type 'I<object?>' cannot be used for parameter 'x' of type 'I<object>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(y: new[] { x, x }, x: y); // 14, 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object?>", "I<object>", "x", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(20, 33) ); } [Fact] public void PassingParameters_DifferentRefKinds() { var source = @" class C { void M(string xNone, ref string xRef, out string xOut) { xNone = null; xRef = null; xOut = null; } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // xNone = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 17), // (7,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // xRef = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 16), // (8,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // xOut = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 16) ); var source2 = @" class C { void M(in string xIn) { xIn = null; } } "; var c2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable()); c2.VerifyDiagnostics( // (6,9): error CS8331: Cannot assign to variable 'in string' because it is a readonly variable // xIn = null; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField, "xIn").WithArguments("variable", "in string").WithLocation(6, 9)); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void PassingParameters_UnknownMethod() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static int F(object x) { Missing(F(null)); // 1 Missing(F(x = null)); // 2 x.ToString(); Missing(F(x = this)); // 3 x.ToString(); return 0; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,9): error CS0103: The name 'Missing' does not exist in the current context // Missing(F(null)); // 1 Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(6, 9), // (6,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // Missing(F(null)); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 19), // (7,9): error CS0103: The name 'Missing' does not exist in the current context // Missing(F(x = null)); // 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(7, 9), // (7,19): warning CS8604: Possible null reference argument for parameter 'x' in 'int C.F(object x)'. // Missing(F(x = null)); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x = null").WithArguments("x", "int C.F(object x)").WithLocation(7, 19), // (7,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Missing(F(x = null)); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 23), // (10,9): error CS0103: The name 'Missing' does not exist in the current context // Missing(F(x = this)); // 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(10, 9), // (10,23): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // Missing(F(x = this)); // 3 Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this").WithLocation(10, 23) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void PassingParameters_UnknownMethod_UnknownReceiver() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static int F(object x) { bad.Missing(F(null)); // 1 bad.Missing(F(x = null)); // 2 x.ToString(); bad.Missing(F(x = this)); // 3 x.ToString(); return 0; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,9): error CS0103: The name 'bad' does not exist in the current context // bad.Missing(F(null)); // 1 Diagnostic(ErrorCode.ERR_NameNotInContext, "bad").WithArguments("bad").WithLocation(6, 9), // (6,23): warning CS8625: Cannot convert null literal to non-nullable reference type. // bad.Missing(F(null)); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 23), // (7,9): error CS0103: The name 'bad' does not exist in the current context // bad.Missing(F(x = null)); // 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "bad").WithArguments("bad").WithLocation(7, 9), // (7,23): warning CS8604: Possible null reference argument for parameter 'x' in 'int C.F(object x)'. // bad.Missing(F(x = null)); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x = null").WithArguments("x", "int C.F(object x)").WithLocation(7, 23), // (7,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // bad.Missing(F(x = null)); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 27), // (10,9): error CS0103: The name 'bad' does not exist in the current context // bad.Missing(F(x = this)); // 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "bad").WithArguments("bad").WithLocation(10, 9), // (10,27): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // bad.Missing(F(x = this)); // 3 Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this").WithLocation(10, 27) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void PassingParameters_UnknownMethod_AffectingState() { CSharpCompilation c = CreateCompilation(new[] { @" class C { object F(object x) { Missing( F(x = null) /*warn*/, x.ToString(), F(x = this), x.ToString()); return x; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,9): error CS0103: The name 'Missing' does not exist in the current context // Missing( Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(6, 9), // (7,15): warning CS8604: Possible null reference argument for parameter 'x' in 'object C.F(object x)'. // F(x = null) /*warn*/, Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x = null").WithArguments("x", "object C.F(object x)").WithLocation(7, 15), // (7,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(x = null) /*warn*/, Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 19) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void PassingParameters_UnknownMethod_AffectingConditionalState() { CSharpCompilation c = CreateCompilation(new[] { @" class C { int F(object x) { if (G(F(x = null))) { x.ToString(); } else { x.ToString(); } return 0; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,13): error CS0103: The name 'G' does not exist in the current context // if (G(F(x = null))) Diagnostic(ErrorCode.ERR_NameNotInContext, "G").WithArguments("G").WithLocation(6, 13), // (6,17): warning CS8604: Possible null reference argument for parameter 'x' in 'int C.F(object x)'. // if (G(F(x = null))) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x = null").WithArguments("x", "int C.F(object x)").WithLocation(6, 17), // (6,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (G(F(x = null))) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 21) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void PassingParameters_UnknownMethod_AffectingConditionalState2() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void F(object x) { if (Missing(x) && Missing(x = null)) { x.ToString(); // 1 } else { x.ToString(); // 2 } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,13): error CS0103: The name 'Missing' does not exist in the current context // if (Missing(x) && Missing(x = null)) Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(6, 13), // (6,27): error CS0103: The name 'Missing' does not exist in the current context // if (Missing(x) && Missing(x = null)) Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(6, 27), // (6,39): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (Missing(x) && Missing(x = null)) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 39), // (8,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 13) ); } [Fact] public void DuplicateArguments() { var source = @"class C { static void F(object x, object? y) { // Duplicate x G(x: x, x: y); G(x: y, x: x); G(x: x, x: y, y: y); G(x: y, x: x, y: y); G(y: y, x: x, x: y); G(y: y, x: y, x: x); // Duplicate y G(y: x, y: y); G(y: y, y: x); G(x, y: x, y: y); G(x, y: y, y: x); G(y: x, y: y, x: x); G(y: y, y: x, x: x); } static void G(object x, params object?[] y) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,17): error CS1740: Named argument 'x' cannot be specified multiple times // G(x: x, x: y); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(6, 17), // (7,17): error CS1740: Named argument 'x' cannot be specified multiple times // G(x: y, x: x); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(7, 17), // (8,17): error CS1740: Named argument 'x' cannot be specified multiple times // G(x: x, x: y, y: y); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(8, 17), // (9,17): error CS1740: Named argument 'x' cannot be specified multiple times // G(x: y, x: x, y: y); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(9, 17), // (10,23): error CS1740: Named argument 'x' cannot be specified multiple times // G(y: y, x: x, x: y); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(10, 23), // (11,23): error CS1740: Named argument 'x' cannot be specified multiple times // G(y: y, x: y, x: x); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(11, 23), // (13,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.G(object, params object?[])' // G(y: x, y: y); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "G").WithArguments("x", "C.G(object, params object?[])").WithLocation(13, 9), // (14,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.G(object, params object?[])' // G(y: y, y: x); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "G").WithArguments("x", "C.G(object, params object?[])").WithLocation(14, 9), // (15,20): error CS1740: Named argument 'y' cannot be specified multiple times // G(x, y: x, y: y); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "y").WithArguments("y").WithLocation(15, 20), // (16,20): error CS1740: Named argument 'y' cannot be specified multiple times // G(x, y: y, y: x); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "y").WithArguments("y").WithLocation(16, 20), // (17,17): error CS1740: Named argument 'y' cannot be specified multiple times // G(y: x, y: y, x: x); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "y").WithArguments("y").WithLocation(17, 17), // (18,17): error CS1740: Named argument 'y' cannot be specified multiple times // G(y: y, y: x, x: x); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "y").WithArguments("y").WithLocation(18, 17)); } [Fact] public void MissingArguments() { var source = @"class C { static void F(object? x) { G(y: x); } static void G(object? x = null, object y) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,45): error CS1737: Optional parameters must appear after all required parameters // static void G(object? x = null, object y) Diagnostic(ErrorCode.ERR_DefaultValueBeforeRequiredValue, ")").WithLocation(7, 45), // (5,14): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.G(object? x = null, object y)'. // G(y: x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("y", "void C.G(object? x = null, object y)").WithLocation(5, 14)); } [Fact] public void ParamsArgument_NotLast() { var source = @"class C { static void F(object[]? a, object? b) { G(a, b, a); } static void G(params object[] x, params object[] y) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,19): error CS0231: A params parameter must be the last parameter in a formal parameter list // static void G(params object[] x, params object[] y) Diagnostic(ErrorCode.ERR_ParamsLast, "params object[] x").WithLocation(7, 19), // (5,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void C.G(params object[] x, params object[] y)'. // G(a, b, a); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("x", "void C.G(params object[] x, params object[] y)").WithLocation(5, 11), // (5,14): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.G(params object[] x, params object[] y)'. // G(a, b, a); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b").WithArguments("y", "void C.G(params object[] x, params object[] y)").WithLocation(5, 14), // (5,17): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.G(params object[] x, params object[] y)'. // G(a, b, a); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("y", "void C.G(params object[] x, params object[] y)").WithLocation(5, 17)); } [Fact] public void ParamsArgument_NotArray() { var source = @"class C { static void F1(bool b, object x, object? y) { if (b) F2(y); if (b) F2(x, y); if (b) F3(y, x); if (b) F3(x, y, x); } static void F2(params object x) { } static void F3(params object x, params object[] y) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,20): error CS0225: The params parameter must be a single dimensional array // static void F2(params object x) Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(10, 20), // (13,20): error CS0225: The params parameter must be a single dimensional array // static void F3(params object x, params object[] y) Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(13, 20), // (13,20): error CS0231: A params parameter must be the last parameter in a formal parameter list // static void F3(params object x, params object[] y) Diagnostic(ErrorCode.ERR_ParamsLast, "params object x").WithLocation(13, 20), // (6,16): error CS1501: No overload for method 'F2' takes 2 arguments // if (b) F2(x, y); Diagnostic(ErrorCode.ERR_BadArgCount, "F2").WithArguments("F2", "2").WithLocation(6, 16), // (5,19): warning CS8604: Possible null reference argument for parameter 'x' in 'void C.F2(params object x)'. // if (b) F2(y); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void C.F2(params object x)").WithLocation(5, 19), // (7,19): warning CS8604: Possible null reference argument for parameter 'x' in 'void C.F3(params object x, params object[] y)'. // if (b) F3(y, x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void C.F3(params object x, params object[] y)").WithLocation(7, 19), // (8,22): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.F3(params object x, params object[] y)'. // if (b) F3(x, y, x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("y", "void C.F3(params object x, params object[] y)").WithLocation(8, 22)); } [Fact] public void ParamsArgument_BinaryOperator() { var source = @"class C { public static object operator+(C x, params object?[] y) => x; static object F(C x, object[] y) => x + y; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,41): error CS1670: params is not valid in this context // public static object operator+(C x, params object?[] y) => x; Diagnostic(ErrorCode.ERR_IllegalParams, "params").WithLocation(3, 41)); } [Fact] public void RefOutParameters_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(ref CL1 x1, CL1 y1) { y1 = x1; } void Test2(ref CL1? x2, CL1 y2) { y2 = x2; } void Test3(ref CL1? x3, CL1 y3) { x3 = y3; y3 = x3; } void Test4(out CL1 x4, CL1 y4) { y4 = x4; x4 = y4; } void Test5(out CL1? x5, CL1 y5) { y5 = x5; x5 = y5; } void Test6(out CL1? x6, CL1 y6) { x6 = y6; y6 = x6; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y2 = x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(15, 14), // (26,14): error CS0269: Use of unassigned out parameter 'x4' // y4 = x4; Diagnostic(ErrorCode.ERR_UseDefViolationOut, "x4").WithArguments("x4").WithLocation(26, 14), // (32,14): error CS0269: Use of unassigned out parameter 'x5' // y5 = x5; Diagnostic(ErrorCode.ERR_UseDefViolationOut, "x5").WithArguments("x5").WithLocation(32, 14), // (32,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y5 = x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5").WithLocation(32, 14)); } [Fact] public void RefOutParameters_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(ref S1 x1, CL1 y1) { y1 = x1.F1; } void Test2(ref S1 x2, CL1 y2) { y2 = x2.F2; } void Test3(ref S1 x3, CL1 y3) { x3.F2 = y3; y3 = x3.F2; } void Test4(out S1 x4, CL1 y4) { y4 = x4.F1; x4.F1 = y4; x4.F2 = y4; } void Test5(out S1 x5, CL1 y5) { y5 = x5.F2; x5.F1 = y5; x5.F2 = y5; } void Test6(out S1 x6, CL1 y6) { x6.F1 = y6; x6.F2 = y6; y6 = x6.F2; } } class CL1 { } struct S1 { public CL1 F1; public CL1? F2; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y2 = x2.F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2.F2").WithLocation(15, 14), // (26,14): error CS0170: Use of possibly unassigned field 'F1' // y4 = x4.F1; Diagnostic(ErrorCode.ERR_UseDefViolationField, "x4.F1").WithArguments("F1").WithLocation(26, 14), // (33,14): error CS0170: Use of possibly unassigned field 'F2' // y5 = x5.F2; Diagnostic(ErrorCode.ERR_UseDefViolationField, "x5.F2").WithArguments("F2").WithLocation(33, 14), // (33,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y5 = x5.F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5.F2").WithLocation(33, 14), // (34,17): warning CS8601: Possible null reference assignment. // x5.F1 = y5; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y5").WithLocation(34, 17)); } [Fact] public void RefOutParameters_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test3(ref S1 x3, CL1 y3) { S1 z3; z3.F1 = y3; z3.F2 = y3; x3 = z3; y3 = x3.F2; } void Test6(out S1 x6, CL1 y6) { S1 z6; z6.F1 = y6; z6.F2 = y6; x6 = z6; y6 = x6.F2; } } class CL1 { } struct S1 { public CL1 F1; public CL1? F2; } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void RefOutParameters_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void M1(ref CL0<string> x) {} void Test1(CL0<string?> x1) { M1(ref x1); } void M2(out CL0<string?> x) { throw new System.NotImplementedException(); } void Test2(CL0<string> x2) { M2(out x2); } void M3(CL0<string> x) {} void Test3(CL0<string?> x3) { M3(x3); } } class CL0<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,16): warning CS8620: Argument of type 'CL0<string?>' cannot be used as an input of type 'CL0<string>' for parameter 'x' in 'void C.M1(ref CL0<string> x)' due to differences in the nullability of reference types. // M1(ref x1); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1").WithArguments("CL0<string?>", "CL0<string>", "x", "void C.M1(ref CL0<string> x)").WithLocation(12, 16), // (19,16): warning CS8624: Argument of type 'CL0<string>' cannot be used as an output of type 'CL0<string?>' for parameter 'x' in 'void C.M2(out CL0<string?> x)' due to differences in the nullability of reference types. // M2(out x2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "x2").WithArguments("CL0<string>", "CL0<string?>", "x", "void C.M2(out CL0<string?> x)").WithLocation(19, 16), // (26,12): warning CS8620: Argument of type 'CL0<string?>' cannot be used as an input of type 'CL0<string>' for parameter 'x' in 'void C.M3(CL0<string> x)' due to differences in the nullability of reference types. // M3(x3); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x3").WithArguments("CL0<string?>", "CL0<string>", "x", "void C.M3(CL0<string> x)").WithLocation(26, 12)); } [Fact] public void RefOutParameters_05() { var source = @"class C { static void F(object? x, object? y, object? z) { G(out x, ref y, in z); x.ToString(); y.ToString(); z.ToString(); } static void G(out object x, ref object y, in object z) { x = new object(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,22): warning CS8601: Possible null reference assignment. // G(out x, ref y, in z); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(5, 22), // (5,28): warning CS8604: Possible null reference argument for parameter 'z' in 'void C.G(out object x, ref object y, in object z)'. // G(out x, ref y, in z); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "z").WithArguments("z", "void C.G(out object x, ref object y, in object z)").WithLocation(5, 28) ); } [Fact] public void RefOutParameters_06() { var source = @"class C { static void F(object x, object y, object z) { G(out x, ref y, in z); x.ToString(); y.ToString(); z.ToString(); } static void G(out object? x, ref object? y, in object? z) { x = new object(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // G(out x, ref y, in z); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(5, 15), // (5,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // G(out x, ref y, in z); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(5, 22), // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9)); } [Fact] public void TargetingUnannotatedAPIs_01() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public object F1; public object P1 { get; set;} public object this[object x] { get { return null; } set { } } public S1 M1() { return new S1(); } } public struct S1 { public CL0 F1; } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } bool Test1(string? x1, string y1) { return string.Equals(x1, y1); } object Test2(ref object? x2, object? y2) { System.Threading.Interlocked.Exchange(ref x2, y2); return x2 ?? new object(); } object Test3(ref object? x3, object? y3) { return System.Threading.Interlocked.Exchange(ref x3, y3) ?? new object(); } object Test4(System.Delegate x4) { return x4.Target ?? new object(); } object Test5(CL0 x5) { return x5.F1 ?? new object(); } void Test6(CL0 x6, object? y6) { x6.F1 = y6; } void Test7(CL0 x7, object? y7) { x7.P1 = y7; } void Test8(CL0 x8, object? y8, object? z8) { x8[y8] = z8; } object Test9(CL0 x9) { return x9[1] ?? new object(); } object Test10(CL0 x10) { return x10.M1().F1 ?? new object(); } object Test11(CL0 x11, CL0? z11) { S1 y11 = x11.M1(); y11.F1 = z11; return y11.F1; } object Test12(CL0 x12) { S1 y12 = x12.M1(); y12.F1 = x12; return y12.F1 ?? new object(); } void Test13(CL0 x13, object? y13) { y13 = x13.F1; object z13 = y13; z13 = y13 ?? new object(); } void Test14(CL0 x14) { object? y14 = x14.F1; object z14 = y14; z14 = y14 ?? new object(); } void Test15(CL0 x15) { S2 y15; y15.F2 = x15.F1; object z15 = y15.F2; z15 = y15.F2 ?? new object(); } struct Test16 { object? y16 {get;} public Test16(CL0 x16) { y16 = x16.F1; object z16 = y16; z16 = y16 ?? new object(); } } void Test17(CL0 x17) { var y17 = new { F2 = x17.F1 }; object z17 = y17.F2; z17 = y17.F2 ?? new object(); } } public struct S2 { public object? F2; } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( // (63,16): warning CS8603: Possible null reference return. // return y11.F1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y11.F1").WithLocation(63, 16)); } [Fact] public void TargetingUnannotatedAPIs_02() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public static object M1() { return new object(); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } public static object? M2() { return null; } public static object M3() { return new object(); } void Test1() { object? x1 = CL0.M1() ?? M2(); object y1 = x1; object z1 = x1 ?? new object(); } void Test2() { object? x2 = CL0.M1() ?? M3(); object z2 = x2 ?? new object(); } void Test3() { object? x3 = M3() ?? M2(); object z3 = x3 ?? new object(); } void Test4() { object? x4 = CL0.M1() ?? CL0.M1(); object y4 = x4; object z4 = x4 ?? new object(); } void Test5() { object x5 = M2() ?? M2(); } void Test6() { object? x6 = M3() ?? M3(); object z6 = x6 ?? new object(); } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( // (14,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y1 = x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(14, 21), // (39,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x5 = M2() ?? M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M2() ?? M2()").WithLocation(39, 21)); } [Fact] public void TargetingUnannotatedAPIs_03() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public static object M1() { return new object(); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } public static object? M2() { return null; } public static object M3() { return new object(); } void Test1() { object? x1 = M2() ?? CL0.M1(); object y1 = x1; object z1 = x1 ?? new object(); } void Test2() { object? x2 = M3() ?? CL0.M1(); object z2 = x2 ?? new object(); } void Test3() { object? x3 = M2() ?? M3(); object z3 = x3 ?? new object(); } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( ); } [Fact] public void TargetingUnannotatedAPIs_04() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public static object M1() { return new object(); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } public static object? M2() { return null; } public static object M3() { return new object(); } public static bool M4() {return false;} void Test1() { object x1 = M4() ? CL0.M1() : M2(); } void Test2() { object? x2 = M4() ? CL0.M1() : M3(); object y2 = x2; object z2 = x2 ?? new object(); } void Test3() { object x3 = M4() ? M3() : M2(); } void Test4() { object? x4 = M4() ? CL0.M1() : CL0.M1(); object y4 = x4; object z4 = x4 ?? new object(); } void Test5() { object x5 = M4() ? M2() : M2(); } void Test6() { object? x6 = M4() ? M3() : M3(); object z6 = x6 ?? new object(); } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( // (14,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x1 = M4() ? CL0.M1() : M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M4() ? CL0.M1() : M2()").WithLocation(14, 21), // (26,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x3 = M4() ? M3() : M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M4() ? M3() : M2()").WithLocation(26, 22), // (38,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x5 = M4() ? M2() : M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M4() ? M2() : M2()").WithLocation(38, 22) ); } [Fact] public void TargetingUnannotatedAPIs_05() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public static object M1() { return new object(); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } public static object? M2() { return null; } public static object M3() { return new object(); } public static bool M4() {return false;} void Test1() { object x1 = M4() ? M2() : CL0.M1(); } void Test2() { object? x2 = M4() ? M3() : CL0.M1(); object y2 = x2; object z2 = x2 ?? new object(); } void Test3() { object x3 = M4() ? M2() : M3(); } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( // (14,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x1 = M4() ? M2() : CL0.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M4() ? M2() : CL0.M1()").WithLocation(14, 21), // (26,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x3 = M4() ? M2() : M3(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M4() ? M2() : M3()").WithLocation(26, 22) ); } [Fact] public void TargetingUnannotatedAPIs_06() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public static object M1() { return new object(); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } public static object? M2() { return null; } public static object M3() { return new object(); } public static bool M4() {return false;} void Test1() { object? x1; if (M4()) x1 = CL0.M1(); else x1 = M2(); object y1 = x1; } void Test2() { object? x2; if (M4()) x2 = CL0.M1(); else x2 = M3(); object y2 = x2; object z2 = x2 ?? new object(); } void Test3() { object? x3; if (M4()) x3 = M3(); else x3 = M2(); object y3 = x3; } void Test4() { object? x4; if (M4()) x4 = CL0.M1(); else x4 = CL0.M1(); object y4 = x4; object z4 = x4 ?? new object(); } void Test5() { object? x5; if (M4()) x5 = M2(); else x5 = M2(); object y5 = x5; } void Test6() { object? x6; if (M4()) x6 = M3(); else x6 = M3(); object z6 = x6 ?? new object(); } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( // (16,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y1 = x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(16, 21), // (31,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(31, 21), // (46,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y5 = x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5").WithLocation(46, 21) ); } [Fact] public void TargetingUnannotatedAPIs_07() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public static object M1() { return new object(); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } public static object? M2() { return null; } public static object M3() { return new object(); } public static bool M4() {return false;} void Test1() { object? x1; if (M4()) x1 = M2(); else x1 = CL0.M1(); object y1 = x1; } void Test2() { object? x2; if (M4()) x2 = M3(); else x2 = CL0.M1(); object y2 = x2; object z2 = x2 ?? new object(); } void Test3() { object? x3; if (M4()) x3 = M2(); else x3 = M3(); object y3 = x3; } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( // (16,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y1 = x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(16, 21), // (31,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(31, 21) ); } [Fact] public void TargetingUnannotatedAPIs_08() { CSharpCompilation c0 = CreateCompilation(@" public abstract class A1 { public abstract event System.Action E1; public abstract string P2 { get; set; } public abstract string M3(string x); public abstract event System.Action E4; public abstract string this[string x] { get; set; } } public interface IA2 { event System.Action E5; string P6 { get; set; } string M7(string x); event System.Action E8; string this[string x] { get; set; } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class B1 : A1 { static void Main() { } public override string? P2 { get; set; } public override event System.Action? E1; public override string? M3(string? x) { var dummy = E1; throw new System.NotImplementedException(); } public override event System.Action? E4 { add { } remove { } } public override string? this[string? x] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } } class B2 : IA2 { public string? P6 { get; set; } public event System.Action? E5; public event System.Action? E8 { add { } remove { } } public string? M7(string? x) { var dummy = E5; throw new System.NotImplementedException(); } public string? this[string? x] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } } class B3 : IA2 { string? IA2.P6 { get; set; } event System.Action? IA2.E5 { add { } remove { } } event System.Action? IA2.E8 { add { } remove { } } string? IA2.M7(string? x) { throw new System.NotImplementedException(); } string? IA2.this[string? x] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics(); } [Fact] public void ReturningValues_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1 Test1(CL1? x1) { return x1; } CL1? Test2(CL1? x2) { return x2; } CL1? Test3(CL1 x3) { return x3; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,16): warning CS8603: Possible null reference return. // return x1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x1").WithLocation(10, 16) ); } [Fact] public void ReturningValues_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1<string?> Test1(CL1<string> x1) { return x1; } CL1<string> Test2(CL1<string?> x2) { return x2; } } class CL1<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,16): warning CS8619: Nullability of reference types in value of type 'CL1<string>' doesn't match target type 'CL1<string?>'. // return x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("CL1<string>", "CL1<string?>").WithLocation(10, 16), // (15,16): warning CS8619: Nullability of reference types in value of type 'CL1<string?>' doesn't match target type 'CL1<string>'. // return x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("CL1<string?>", "CL1<string>").WithLocation(15, 16) ); } [Fact] public void ReturningValues_BadValue() { CSharpCompilation c = CreateCompilation(new[] { @" class C { string M() { return bad; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,16): error CS0103: The name 'bad' does not exist in the current context // return bad; Diagnostic(ErrorCode.ERR_NameNotInContext, "bad").WithArguments("bad").WithLocation(6, 16) ); } [Fact] public void IdentityConversion_Return_01() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static I<object?> F(I<object> x) => x; static IIn<object?> F(IIn<object> x) => x; static IOut<object?> F(IOut<object> x) => x; static I<object> G(I<object?> x) => x; static IIn<object> G(IIn<object?> x) => x; static IOut<object> G(IOut<object?> x) => x; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,41): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // static I<object?> F(I<object> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object>", "I<object?>").WithLocation(6, 41), // (7,45): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // static IIn<object?> F(IIn<object> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object>", "IIn<object?>").WithLocation(7, 45), // (9,41): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // static I<object> G(I<object?> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object?>", "I<object>").WithLocation(9, 41), // (11,47): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // static IOut<object> G(IOut<object?> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IOut<object?>", "IOut<object>").WithLocation(11, 47)); } [Fact] public void IdentityConversion_Return_02() { var source = @"#pragma warning disable 1998 using System.Threading.Tasks; interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static async Task<I<object?>> F(I<object> x) => x; static async Task<IIn<object?>> F(IIn<object> x) => x; static async Task<IOut<object?>> F(IOut<object> x) => x; static async Task<I<object>> G(I<object?> x) => x; static async Task<IIn<object>> G(IIn<object?> x) => x; static async Task<IOut<object>> G(IOut<object?> x) => x; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,53): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // static async Task<I<object?>> F(I<object> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object>", "I<object?>").WithLocation(8, 53), // (9,57): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // static async Task<IIn<object?>> F(IIn<object> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object>", "IIn<object?>").WithLocation(9, 57), // (11,53): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // static async Task<I<object>> G(I<object?> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object?>", "I<object>").WithLocation(11, 53), // (13,59): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // static async Task<IOut<object>> G(IOut<object?> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IOut<object?>", "IOut<object>").WithLocation(13, 59)); } [Fact] public void MakeMethodKeyForWhereMethod() { // this test verifies that a bad method symbol doesn't crash when generating a key for external annotations CSharpCompilation c = CreateCompilation(new[] { @" class Test { public void SimpleWhere() { int[] numbers = { 1, 2, 3 }; var lowNums = from n in numbers where n < 5 select n; } }" }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,33): error CS1935: Could not find an implementation of the query pattern for source type 'int[]'. 'Where' not found. Are you missing required assembly references or a using directive for 'System.Linq'? // var lowNums = from n in numbers Diagnostic(ErrorCode.ERR_QueryNoProviderStandard, "numbers").WithArguments("int[]", "Where").WithLocation(7, 33) ); } [Fact] public void MemberNotNull_Simple() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { Init(); field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } [MemberNotNull(nameof(field1), nameof(field2))] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_NullValue() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { Init(); field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 } [MemberNotNull(null!, null!)] [MemberNotNull(members: null!)] [MemberNotNull(member: null!)] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_LocalFunction() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { init(); field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 [MemberNotNull(nameof(field1), nameof(field2))] void init() => throw null!; } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); // Note: the local function is not invoked on this or base c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_Interfaces() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public interface I { string Property1 { get; } string? Property2 { get; } string Property3 { get; } string? Property4 { get; } [MemberNotNull(nameof(Property1), nameof(Property2))] // Note: attribute ineffective void Init(); } public class C : I { public string Property1 { get; set; } public string? Property2 { get; set; } public string Property3 { get; set; } public string? Property4 { get; set; } public void M() { Init(); Property1.ToString(); Property2.ToString(); // 1 Property3.ToString(); Property4.ToString(); // 2 } public void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,19): warning CS8618: Non-nullable property 'Property1' is uninitialized. Consider declaring the property as nullable. // public string Property1 { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Property1").WithArguments("property", "Property1").WithLocation(15, 19), // (17,19): warning CS8618: Non-nullable property 'Property3' is uninitialized. Consider declaring the property as nullable. // public string Property3 { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Property3").WithArguments("property", "Property3").WithLocation(17, 19), // (24,9): warning CS8602: Dereference of a possibly null reference. // Property2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Property2").WithLocation(24, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // Property4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Property4").WithLocation(26, 9) ); } [Fact] public void MemberNotNull_Inheritance() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field0), nameof(field1), nameof(field2))] public virtual void Init() => throw null!; } public class Derived : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override void Init() { field5 = """"; field6 = """"; } // 1, 2, 3 Derived() { Init(); field0.ToString(); // 4 field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 5 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 6 } } public class Derived2 : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override void Init() { base.Init(); field5 = """"; field6 = """"; } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (27,5): warning CS8771: Member 'field0' must have a non-null value when exiting. // } // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field0").WithLocation(27, 5), // (27,5): warning CS8771: Member 'field1' must have a non-null value when exiting. // } // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(27, 5), // (27,5): warning CS8771: Member 'field2' must have a non-null value when exiting. // } // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(27, 5), // (32,9): warning CS8602: Dereference of a possibly null reference. // field0.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field0").WithLocation(32, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(36, 9), // (40,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(40, 9) ); } [Fact] public void MemberNotNull_OnInstance() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; [MemberNotNull(nameof(field1), nameof(field2))] public virtual void Init() => throw null!; } public class Derived : Base { public new string? field0; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field0), nameof(field3), nameof(field4))] public override void Init() => throw null!; } public class C { void M(Derived d, Derived d2) { d.field0.ToString(); // 1 d.field1.ToString(); d.field2.ToString(); // 2 d.field3.ToString(); d.field4.ToString(); // 3 d2.Init(); d2.field0.ToString(); d2.field1.ToString(); d2.field2.ToString(); d2.field3.ToString(); d2.field4.ToString(); } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (25,9): warning CS8602: Dereference of a possibly null reference. // d.field0.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field0").WithLocation(25, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // d.field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field2").WithLocation(27, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // d.field4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field4").WithLocation(29, 9) ); } [Fact] public void MemberNotNull_Property_OnInstance() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; [MemberNotNull(nameof(field1), nameof(field2))] public virtual int Init => throw null!; } public class Derived : Base { public new string? field0; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field0), nameof(field3), nameof(field4))] public override int Init => throw null!; } public class C { void M(Derived d, Derived d2) { d.field0.ToString(); // 1 d.field1.ToString(); d.field2.ToString(); // 2 d.field3.ToString(); d.field4.ToString(); // 3 _ = d2.Init; d2.field0.ToString(); d2.field1.ToString(); d2.field2.ToString(); d2.field3.ToString(); d2.field4.ToString(); } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (25,9): warning CS8602: Dereference of a possibly null reference. // d.field0.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field0").WithLocation(25, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // d.field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field2").WithLocation(27, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // d.field4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field4").WithLocation(29, 9) ); } [Fact] public void MemberNotNull_OnMethodWithConditionalAttribute() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1 = null!; public string? field2; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field1), nameof(field2))] public bool Init([NotNullWhen(true)] string p) // NotNullWhen splits the state before we analyze MemberNotNull { field1 = """"; field2 = """"; return false; } C() { if (Init("""")) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 1 } else { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 2 } } } ", MemberNotNullAttributeDefinition, NotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (25,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(25, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(32, 13) ); } [Fact] public void MemberNotNull_Inheritance_PE() { var libComp = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; public string? field2b; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field0))] [MemberNotNull(nameof(field1), nameof(field2))] [MemberNotNull(nameof(field2b))] public virtual void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); var c = CreateNullableCompilation(@" using System.Diagnostics.CodeAnalysis; public class Derived : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override void Init() { field5 = """"; field6 = """"; } // 1, 2, 3, 4 Derived() { Init(); field0.ToString(); // 5 field1.ToString(); field2.ToString(); field2b.ToString(); field3.ToString(); field4.ToString(); // 6 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 7 } } public class Derived2 : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override void Init() { base.Init(); field5 = """"; field6 = """"; } } ", references: new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,5): warning CS8774: Member 'field1' must have a non-null value when exiting. // } // 1, 2, 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(16, 5), // (16,5): warning CS8774: Member 'field2' must have a non-null value when exiting. // } // 1, 2, 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(16, 5), // (16,5): warning CS8774: Member 'field0' must have a non-null value when exiting. // } // 1, 2, 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field0").WithLocation(16, 5), // (16,5): warning CS8774: Member 'field2b' must have a non-null value when exiting. // } // 1, 2, 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2b").WithLocation(16, 5), // (21,9): warning CS8602: Dereference of a possibly null reference. // field0.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field0").WithLocation(21, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(26, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(30, 9) ); } [Fact] public void MemberNotNull_Inheritance_Property() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field0), nameof(field1), nameof(field2))] public virtual int Init { get => throw null!; set => throw null!; } } public class Derived : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override int Init { get { field5 = """"; field6 = """"; return 0; // 1, 2, 3 } set { field5 = """"; field6 = """"; } // 4, 5, 6 } Derived() { _ = Init; field0.ToString(); // 7 field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 8 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 9 } Derived(int unused) { Init = 42; field0.ToString(); // 10 field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 11 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 12 } } public class Derived2 : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override int Init { get { _ = base.Init; field5 = """"; field6 = """"; return 0; } set { base.Init = value; field5 = """"; field6 = """"; } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (29,13): warning CS8774: Member 'field0' must have a non-null value when exiting. // return 0; // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field0").WithLocation(29, 13), // (29,13): warning CS8774: Member 'field1' must have a non-null value when exiting. // return 0; // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field1").WithLocation(29, 13), // (29,13): warning CS8774: Member 'field2' must have a non-null value when exiting. // return 0; // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field2").WithLocation(29, 13), // (35,9): warning CS8774: Member 'field0' must have a non-null value when exiting. // } // 4, 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field0").WithLocation(35, 9), // (35,9): warning CS8774: Member 'field1' must have a non-null value when exiting. // } // 4, 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(35, 9), // (35,9): warning CS8774: Member 'field2' must have a non-null value when exiting. // } // 4, 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(35, 9), // (41,9): warning CS8602: Dereference of a possibly null reference. // field0.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field0").WithLocation(41, 9), // (45,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(45, 9), // (49,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(49, 9), // (55,9): warning CS8602: Dereference of a possibly null reference. // field0.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field0").WithLocation(55, 9), // (59,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(59, 9), // (63,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(63, 9) ); } [Fact] public void MemberNotNull_Inheritance_Property_PE() { var libComp = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field0), nameof(field1), nameof(field2))] public virtual int Init { get => throw null!; set => throw null!; } }", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); var c = CreateNullableCompilation(@" using System.Diagnostics.CodeAnalysis; public class Derived : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override int Init { get { field5 = """"; field6 = """"; return 0; // 1, 2, 3 } set { field5 = """"; field6 = """"; } // 4, 5, 6 } Derived() { _ = Init; field0.ToString(); // 7 field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 8 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 9 } Derived(int unused) { Init = 42; field0.ToString(); // 10 field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 11 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 12 } } ", new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (18,13): warning CS8774: Member 'field0' must have a non-null value when exiting. // return 0; // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field0").WithLocation(18, 13), // (18,13): warning CS8774: Member 'field1' must have a non-null value when exiting. // return 0; // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field1").WithLocation(18, 13), // (18,13): warning CS8774: Member 'field2' must have a non-null value when exiting. // return 0; // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field2").WithLocation(18, 13), // (24,9): warning CS8774: Member 'field0' must have a non-null value when exiting. // } // 4, 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field0").WithLocation(24, 9), // (24,9): warning CS8774: Member 'field1' must have a non-null value when exiting. // } // 4, 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(24, 9), // (24,9): warning CS8774: Member 'field2' must have a non-null value when exiting. // } // 4, 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(24, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // field0.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field0").WithLocation(30, 9), // (34,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(34, 9), // (38,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(38, 9), // (44,9): warning CS8602: Dereference of a possibly null reference. // field0.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field0").WithLocation(44, 9), // (48,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(48, 9), // (52,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(52, 9) ); } [Fact] public void MemberNotNull_Inheritance_SpecifiedOnDerived() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; public string field3 = null!; public string? field4; public virtual void Init() => throw null!; } public class Derived : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field0), nameof(field1), nameof(field2), nameof(field5), nameof(field6))] // 1, 2 public override void Init() => throw null!; Derived() { Init(); field0.ToString(); field1.ToString(); field2.ToString(); // 3 field3.ToString(); field4.ToString(); // 4 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 5 } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (21,6): error CS8776: Member 'field1' cannot be used in this attribute. // [MemberNotNull(nameof(field0), nameof(field1), nameof(field2), nameof(field5), nameof(field6))] // 1, 2 Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNull(nameof(field0), nameof(field1), nameof(field2), nameof(field5), nameof(field6))").WithArguments("field1").WithLocation(21, 6), // (21,6): error CS8776: Member 'field2' cannot be used in this attribute. // [MemberNotNull(nameof(field0), nameof(field1), nameof(field2), nameof(field5), nameof(field6))] // 1, 2 Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNull(nameof(field0), nameof(field1), nameof(field2), nameof(field5), nameof(field6))").WithArguments("field2").WithLocation(21, 6), // (29,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(29, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(31, 9), // (35,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(35, 9) ); } [Fact] public void MemberNotNull_Inheritance_Property_SpecifiedOnDerived_BadMember() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field; public virtual int Init => throw null!; } public class Derived : Base { [MemberNotNull(nameof(field))] public override int Init => 0; } public class Derived2 : Base { [MemberNotNull(nameof(field))] public override int Init { get { field = """"; return 0; } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,6): error CS8776: Member 'field' cannot be used in this attribute. // [MemberNotNull(nameof(field))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNull(nameof(field))").WithArguments("field").WithLocation(10, 6), // (15,6): error CS8776: Member 'field' cannot be used in this attribute. // [MemberNotNull(nameof(field))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNull(nameof(field))").WithArguments("field").WithLocation(15, 6) ); } [Fact] public void MemberNotNull_BadMember() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { [MemberNotNull(nameof(missing))] public int Init => 0; [MemberNotNull(nameof(missing))] public int Init2() => 0; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,27): error CS0103: The name 'missing' does not exist in the current context // [MemberNotNull(nameof(missing))] Diagnostic(ErrorCode.ERR_NameNotInContext, "missing").WithArguments("missing").WithLocation(5, 27), // (8,27): error CS0103: The name 'missing' does not exist in the current context // [MemberNotNull(nameof(missing))] Diagnostic(ErrorCode.ERR_NameNotInContext, "missing").WithArguments("missing").WithLocation(8, 27) ); } [Fact] public void MemberNotNull_BadMember_2() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { [MemberNotNull(nameof(C))] public int Init => 0; [MemberNotNull(nameof(M))] public int Init2() => 0; public void M() { } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,6): warning CS8776: Member 'C' cannot be used in this attribute. // [MemberNotNull(nameof(C))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNull(nameof(C))").WithArguments("C").WithLocation(5, 6), // (8,6): warning CS8776: Member 'M' cannot be used in this attribute. // [MemberNotNull(nameof(M))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNull(nameof(M))").WithArguments("M").WithLocation(8, 6) ); } [Fact] public void MemberNotNull_AppliedInCSharp8() { var libComp = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string? field; [MemberNotNull(nameof(field))] public int Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); var c = CreateNullableCompilation(new[] { @" public class D { void M(C c, C c2) { c.field.ToString(); c2.Init(); c2.field.ToString(); } } " }, references: new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular8); // Note: attribute honored in C# 8 caller c.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(6, 9) ); } [Fact] public void MemberNotNullWhen_Inheritance_SpecifiedOnDerived_BadMember() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field; public string? Property; public virtual bool Init => throw null!; public virtual bool Init2() => throw null!; } public class Derived : Base { [MemberNotNullWhen(true, nameof(field), nameof(Property))] public override bool Init => throw null!; [MemberNotNullWhen(true, nameof(field), nameof(Property))] public override bool Init2() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (12,6): error CS8776: Member 'field' cannot be used in this attribute. // [MemberNotNullWhen(true, nameof(field), nameof(Property))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNullWhen(true, nameof(field), nameof(Property))").WithArguments("field").WithLocation(12, 6), // (12,6): error CS8776: Member 'Property' cannot be used in this attribute. // [MemberNotNullWhen(true, nameof(field), nameof(Property))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNullWhen(true, nameof(field), nameof(Property))").WithArguments("Property").WithLocation(12, 6), // (15,6): error CS8776: Member 'field' cannot be used in this attribute. // [MemberNotNullWhen(true, nameof(field), nameof(Property))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNullWhen(true, nameof(field), nameof(Property))").WithArguments("field").WithLocation(15, 6), // (15,6): error CS8776: Member 'Property' cannot be used in this attribute. // [MemberNotNullWhen(true, nameof(field), nameof(Property))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNullWhen(true, nameof(field), nameof(Property))").WithArguments("Property").WithLocation(15, 6) ); } [Fact] public void MemberNotNull_EnforcementInTryFinally() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public string field5; public string? field6; public C() // 1 { Init(); } [MemberNotNull(nameof(field1), nameof(field2), nameof(field3), nameof(field4))] void Init() { try { bool b = true; if (b) { return; // 2, 3 } else { field3 = """"; field4 = """"; return; } } finally { field1 = """"; field2 = """"; } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (12,12): warning CS8618: Non-nullable field 'field5' is uninitialized. Consider declaring the field as nullable. // public C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field5").WithLocation(12, 12), // (25,17): warning CS8771: Member 'field3' must have a non-null value when exiting. // return; // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return;").WithArguments("field3").WithLocation(25, 17), // (25,17): warning CS8771: Member 'field4' must have a non-null value when exiting. // return; // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return;").WithArguments("field4").WithLocation(25, 17) ); } [Fact] public void MemberNotNull_LangVersion() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public string? field1; [MemberNotNull(nameof(field1))] void Init() => throw null!; [MemberNotNullWhen(true, nameof(field1))] bool Init2() => throw null!; [MemberNotNull(nameof(field1))] bool IsInit { get { throw null!; } } [MemberNotNullWhen(true, nameof(field1))] bool IsInit2 { get { throw null!; } } } "; var c = CreateCompilation(new[] { source, MemberNotNullAttributeDefinition, MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public string? field1; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18), // (6,6): error CS8400: Feature 'MemberNotNull attribute' is not available in C# 8.0. Please use language version 9.0 or greater. // [MemberNotNull(nameof(field1))] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "MemberNotNull(nameof(field1))").WithArguments("MemberNotNull attribute", "9.0").WithLocation(6, 6), // (9,6): error CS8400: Feature 'MemberNotNull attribute' is not available in C# 8.0. Please use language version 9.0 or greater. // [MemberNotNullWhen(true, nameof(field1))] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "MemberNotNullWhen(true, nameof(field1))").WithArguments("MemberNotNull attribute", "9.0").WithLocation(9, 6), // (12,6): error CS8400: Feature 'MemberNotNull attribute' is not available in C# 8.0. Please use language version 9.0 or greater. // [MemberNotNull(nameof(field1))] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "MemberNotNull(nameof(field1))").WithArguments("MemberNotNull attribute", "9.0").WithLocation(12, 6), // (15,6): error CS8400: Feature 'MemberNotNull attribute' is not available in C# 8.0. Please use language version 9.0 or greater. // [MemberNotNullWhen(true, nameof(field1))] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "MemberNotNullWhen(true, nameof(field1))").WithArguments("MemberNotNull attribute", "9.0").WithLocation(15, 6) ); var c2 = CreateCompilation(new[] { source, MemberNotNullAttributeDefinition, MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c2.VerifyDiagnostics( // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public string? field1; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18) ); } [Fact] public void MemberNotNull_BoolReturning() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } else { field1.ToString(); field2.ToString(); field3.ToString(); // 3 field4.ToString(); // 4 } } [MemberNotNull(nameof(field1), nameof(field2))] bool Init() => true; // 5, 6 } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (23,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(23, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13), // (29,20): warning CS8774: Member 'field1' must have a non-null value when exiting. // bool Init() => true; // 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "true").WithArguments("field1").WithLocation(29, 20), // (29,20): warning CS8774: Member 'field2' must have a non-null value when exiting. // bool Init() => true; // 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "true").WithArguments("field2").WithLocation(29, 20) ); } [Fact] public void MemberNotNull_OtherType() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void M() { var d = new D(); d.Init(); d.field1.ToString(); d.field2.ToString(); d.field3.ToString(); d.field4.ToString(); // 1 } } public class D { public string field1; // 2 public string? field2; public string field3; // 3 public string? field4; [MemberNotNull(nameof(field1), nameof(field2))] public void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // d.field4.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field4").WithLocation(12, 9), // (17,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(17, 19), // (19,19): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public string field3; // 3 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(19, 19) ); } [Fact] public void MemberNotNull_OtherType_ExtensionMethod() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void M() { var d = new D(); d.Init(); d.field1.ToString(); d.field2.ToString(); d.field3.ToString(); d.field4.ToString(); } } public class D { public string field1; public string? field2; public string field3; public string? field4; } public static class Extension { [MemberNotNull(nameof(field1), nameof(field2))] public static void Init(this D d) => throw null!; } ", MemberNotNullAttributeDefinition }); c.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // d.field2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field2").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // d.field4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field4").WithLocation(12, 9), // (17,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(17, 19), // (19,19): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public string field3; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(19, 19), // (24,27): error CS0103: The name 'field1' does not exist in the current context // [MemberNotNull(nameof(field1), nameof(field2))] Diagnostic(ErrorCode.ERR_NameNotInContext, "field1").WithArguments("field1").WithLocation(24, 27), // (24,43): error CS0103: The name 'field2' does not exist in the current context // [MemberNotNull(nameof(field1), nameof(field2))] Diagnostic(ErrorCode.ERR_NameNotInContext, "field2").WithArguments("field2").WithLocation(24, 43) ); } [Fact] public void MemberNotNull_Property_Getter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { _ = Count; field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } public C(int unused) { Count = 42; field1.ToString(); // 3 field2.ToString(); // 4 field3.ToString(); // 5 field4.ToString(); // 6 } int Count { [MemberNotNull(nameof(field1), nameof(field2))] get => throw null!; set { } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9), // (22,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(22, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(23, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(25, 9) ); } [Fact] public void MemberNotNull_Property_Setter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { _ = Count; field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 } public C(int unused) { Count = 1; field1.ToString(); field2.ToString(); field3.ToString(); // 5 field4.ToString(); // 6 } int Count { get { field1 = """"; return 0; } [MemberNotNull(nameof(field1), nameof(field2))] set { field2 = """"; } // 7 } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(25, 9), // (39,9): warning CS8774: Member 'field1' must have a non-null value when exiting. // } // 7 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(39, 9) ); } [Fact] public void MemberNotNull_Property_Getter_Static() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public static class C { public static string field1; public static string? field2; public static string field3; public static string? field4; static C() { _ = Count; field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } static int Count { [MemberNotNull(nameof(field1), nameof(field2))] get => throw null!; set { } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_Property_Getter_Static_2() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public static class C { public static string field1; public static string? field2; public static string field3; public static string? field4; static C() { Count = 42; field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 } static int Count { [MemberNotNull(nameof(field1), nameof(field2))] get => throw null!; set { } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_Property_Setter_Static() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public static class C { public static string field1; public static string? field2; public static string field3; public static string? field4; static C() { _ = Count; field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 } static int Count { get => throw null!; [MemberNotNull(nameof(field1), nameof(field2))] set => throw null!; } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_Property_Setter_Static_2() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public static class C { public static string field1; public static string? field2; public static string field3; public static string? field4; static C() { Count = 1; field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } static int Count { get => throw null!; [MemberNotNull(nameof(field1), nameof(field2))] set => throw null!; } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_Branches() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string field2; public string field3; public string field4; public C() { bool b = true; if (b) Init(); else Init2(); } [MemberNotNull(nameof(field1), nameof(field2))] void Init() => throw null!; [MemberNotNull(nameof(field2), nameof(field3))] void Init2() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 12), // (10,12): warning CS8618: Non-nullable field 'field4' is uninitialized. Consider declaring the field as nullable. // public C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field4").WithLocation(10, 12), // (10,12): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field1").WithLocation(10, 12) ); } [Fact] public void MemberNotNull_Static() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static string field1; public static string? field2; public static string field3; public static string? field4; static C() { Init(); field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); } [MemberNotNull(nameof(field1), nameof(field2), nameof(field4))] static void Init() { field2 = """"; } // 2, 3 } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (23,5): warning CS8774: Member 'field1' must have a non-null value when exiting. // } // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(23, 5), // (23,5): warning CS8774: Member 'field4' must have a non-null value when exiting. // } // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field4").WithLocation(23, 5) ); } [Fact] public void MemberNotNull_Multiple() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string field2; public string field3; public string field4; public C() { Init(); } [MemberNotNull(nameof(field1))] [MemberNotNull(nameof(field2), nameof(field3))] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field4' is uninitialized. Consider declaring the field as nullable. // public C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field4").WithLocation(10, 12) ); } [Fact] public void MemberNotNull_Multiple_ParamsConstructor() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string field2; public string field3; public string field4; public C() { Init(); field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); } [MemberNotNull(nameof(field1), nameof(field2))] [MemberNotNull(nameof(field3), nameof(field4))] void Init() { } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (23,5): warning CS8774: Member 'field1' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(23, 5), // (23,5): warning CS8774: Member 'field2' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(23, 5), // (23,5): warning CS8774: Member 'field3' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field3").WithLocation(23, 5), // (23,5): warning CS8774: Member 'field4' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field4").WithLocation(23, 5) ); } [Fact] public void MemberNotNull_Multiple_Property() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string field2; public string field3; public string field4; public C() { _ = Init; } [MemberNotNull(nameof(field1))] [MemberNotNull(nameof(field2), nameof(field3))] int Init { get => 1; set { } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field4' is uninitialized. Consider declaring the field as nullable. // public C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field4").WithLocation(10, 12), // (19,16): warning CS8774: Member 'field1' must have a non-null value when exiting. // get => 1; Diagnostic(ErrorCode.WRN_MemberNotNull, "1").WithArguments("field1").WithLocation(19, 16), // (19,16): warning CS8774: Member 'field2' must have a non-null value when exiting. // get => 1; Diagnostic(ErrorCode.WRN_MemberNotNull, "1").WithArguments("field2").WithLocation(19, 16), // (19,16): warning CS8774: Member 'field3' must have a non-null value when exiting. // get => 1; Diagnostic(ErrorCode.WRN_MemberNotNull, "1").WithArguments("field3").WithLocation(19, 16), // (20,15): warning CS8774: Member 'field1' must have a non-null value when exiting. // set { } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(20, 15), // (20,15): warning CS8774: Member 'field2' must have a non-null value when exiting. // set { } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(20, 15), // (20,15): warning CS8774: Member 'field3' must have a non-null value when exiting. // set { } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field3").WithLocation(20, 15) ); } [Fact] public void MemberNotNull_NotFound() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public C() { Init(); } [MemberNotNull(nameof(field))] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }); c.VerifyDiagnostics( // (10,27): error CS0103: The name 'field' does not exist in the current context // [MemberNotNull(nameof(field))] Diagnostic(ErrorCode.ERR_NameNotInContext, "field").WithArguments("field").WithLocation(10, 27) ); } [Fact] public void MemberNotNull_NotFound_PrivateInBase() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { private string? field; public string? P { get { return field; } set { field = value; } } } public class C : Base { public C() { Init(); } [MemberNotNull(nameof(field))] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }); c.VerifyDiagnostics( // (15,27): error CS0122: 'Base.field' is inaccessible due to its protection level // [MemberNotNull(nameof(field))] Diagnostic(ErrorCode.ERR_BadAccess, "field").WithArguments("Base.field").WithLocation(15, 27) ); } [Fact] public void MemberNotNull_Null() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { [MemberNotNull(members: null)] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // [MemberNotNull(members: null)] Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 29) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() { Init(); } [MemberNotNull(nameof(field1), nameof(field2))] void Init() { } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (16,19): warning CS8771: Member 'field1' must have a non-null value when exiting. // void Init() { } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(16, 19), // (16,19): warning CS8771: Member 'field2' must have a non-null value when exiting. // void Init() { } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(16, 19) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody_AccessedInBody() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() { Init(); } [MemberNotNull(nameof(field1), nameof(field2))] void Init() { field1.ToString(); } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (18,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(18, 9), // (19,5): warning CS8771: Member 'field2' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(19, 5) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody_AccessedInBody_OnlyThisField() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() { Init("""", new C()); } [MemberNotNull(nameof(field1), nameof(field2))] void Init(string field1, C c) { field1.ToString(); c.field1.ToString(); } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (20,5): warning CS8771: Member 'field1' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(20, 5), // (20,5): warning CS8771: Member 'field2' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(20, 5) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody_Throw() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; [MemberNotNull(nameof(field1), nameof(field2))] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19), // (7,19): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public string field3; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 19) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody_BranchWithReturn() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; // 1 public string? field2; public string field3; // 2 public string? field4; [MemberNotNull(nameof(field1), nameof(field2))] void Init() { bool b = true; if (b) { return; // 3, 4 } field2 = """"; } // 5 } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19), // (7,19): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public string field3; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 19), // (16,13): warning CS8771: Member 'field1' must have a non-null value when exiting. // return; // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "return;").WithArguments("field1").WithLocation(16, 13), // (16,13): warning CS8771: Member 'field2' must have a non-null value when exiting. // return; // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "return;").WithArguments("field2").WithLocation(16, 13), // (19,5): warning CS8771: Member 'field1' must have a non-null value when exiting. // } // 5 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(19, 5) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody_BranchWithReturn_WithValue() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; // 1 public string? field2; public string field3; // 2 public string? field4; [MemberNotNull(nameof(field1), nameof(field2))] int Init() { bool b = true; if (b) { return 0; // 3, 4 } field2 = """"; return 0; // 5 } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19), // (7,19): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public string field3; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 19), // (16,13): warning CS8771: Member 'field1' must have a non-null value when exiting. // return 0; // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field1").WithLocation(16, 13), // (16,13): warning CS8771: Member 'field2' must have a non-null value when exiting. // return 0; // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field2").WithLocation(16, 13), // (19,9): warning CS8771: Member 'field1' must have a non-null value when exiting. // return 0; // 5 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field1").WithLocation(19, 9) ); } [Fact] public void MemberNotNull_EnforcedInProperty() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() // 1 { _ = Init; } C(int ignored) // 2 { Init = 42; } [MemberNotNull(nameof(field1), nameof(field2))] int Init { get { return 42; } // 3, 4 set { } // 5, 6 } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (15,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C(int ignored) // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(15, 5), // (23,15): warning CS8774: Member 'field1' must have a non-null value when exiting. // get { return 42; } // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 42;").WithArguments("field1").WithLocation(23, 15), // (23,15): warning CS8774: Member 'field2' must have a non-null value when exiting. // get { return 42; } // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 42;").WithArguments("field2").WithLocation(23, 15), // (24,15): warning CS8774: Member 'field1' must have a non-null value when exiting. // set { } // 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(24, 15), // (24,15): warning CS8774: Member 'field2' must have a non-null value when exiting. // set { } // 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(24, 15) ); } [Fact] public void MemberNotNullWhenTrue_Simple() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } else { throw null!; } } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13) ); } [Fact, WorkItem(47667, "https://github.com/dotnet/roslyn/issues/47667")] public void MemberNotNullWhenTrue_Generic_01() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C<T> { public T field1; public T? field2; public T field3; public T? field4; public C() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } else { throw null!; } } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13) ); } [Fact, WorkItem(47667, "https://github.com/dotnet/roslyn/issues/47667")] public void MemberNotNullWhenTrue_Generic_02() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class GetResult<T> { [MemberNotNullWhen(true, ""Value"")] public bool OK { get; set; } public T? Value { get; init; } } record Manager(int Age); class Archive { readonly Dictionary<string, Manager> Dict = new Dictionary<string, Manager>(); public GetResult<Manager> this[string key] => Dict.TryGetValue(key, out var value) ? new GetResult<Manager> { OK = true, Value = value } : new GetResult<Manager> { OK = false, Value = null }; } public class C { public void M() { Archive archive = new Archive(); var result = archive[""John""]; int age1 = result.OK ? result.Value.Age : result.Value.Age; // 1 } } ", MemberNotNullWhenAttributeDefinition, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (33,15): warning CS8602: Dereference of a possibly null reference. // : result.Value.Age; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result.Value", isSuppressed: false).WithLocation(33, 15) ); } [Fact, WorkItem(47667, "https://github.com/dotnet/roslyn/issues/47667")] public void MemberNotNullWhenFalse_Generic_01() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C<T> where T : new() { [MemberNotNullWhen(false, ""Value"")] public bool IsBad { get; set; } public T? Value { get; set; } } public class Program { public void M(C<object> c) { _ = c.IsBad ? c.Value.ToString() // 1 : c.Value.ToString(); } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,15): warning CS8602: Dereference of a possibly null reference. // ? c.Value.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.Value", isSuppressed: false).WithLocation(16, 15) ); } [Fact, WorkItem(47667, "https://github.com/dotnet/roslyn/issues/47667")] public void MemberNotNull_Generic_01() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C<T> where T : new() { [MemberNotNull(""Value"")] public void Init() { Value = new T(); } public T? Value { get; set; } } public class Program { public void M(bool b, C<object> c) { if (b) c.Value.ToString(); // 1 c.Init(); c.Value.ToString(); } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,16): warning CS8602: Dereference of a possibly null reference. // if (b) c.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.Value", isSuppressed: false).WithLocation(15, 16) ); } [Fact, WorkItem(47667, "https://github.com/dotnet/roslyn/issues/47667")] public void MemberNotNull_Extension_01() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string? _field; } public static class Ext { public static string? _field; [MemberNotNull(""_field"")] public static void AssertFieldNotNull(this C c) { if (_field == null) throw null!; } } class Program { void M1(C c) { c.AssertFieldNotNull(); Ext._field.ToString(); c._field.ToString(); // 1 } void M2(C c) { Ext.AssertFieldNotNull(c); Ext._field.ToString(); c._field.ToString(); // 2 } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (23,9): warning CS8602: Dereference of a possibly null reference. // c._field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c._field", isSuppressed: false).WithLocation(23, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // c._field.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c._field", isSuppressed: false).WithLocation(30, 9) ); } [Fact, WorkItem(47667, "https://github.com/dotnet/roslyn/issues/47667")] public void MemberNotNullWhen_Extension_01() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string? _field; } public static class Ext { public static string? _field; [MemberNotNullWhen(true, ""_field"")] public static bool IsFieldPresent(this C c) { return _field != null; } [MemberNotNullWhen(false, ""_field"")] public static bool IsFieldAbsent(this C c) { return _field == null; } } class Program { void M1(C c) { _ = c.IsFieldPresent() ? Ext._field.ToString() : Ext._field.ToString(); // 1 _ = c.IsFieldPresent() ? c._field.ToString() // 2 : c._field.ToString(); // 3 } void M2(C c) { _ = c.IsFieldAbsent() ? Ext._field.ToString() // 4 : Ext._field.ToString(); _ = c.IsFieldAbsent() ? c._field.ToString() // 5 : c._field.ToString(); // 6 } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (26,15): warning CS8602: Dereference of a possibly null reference. // : Ext._field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Ext._field", isSuppressed: false).WithLocation(26, 15), // (29,15): warning CS8602: Dereference of a possibly null reference. // ? c._field.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c._field", isSuppressed: false).WithLocation(29, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // : c._field.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c._field", isSuppressed: false).WithLocation(30, 15), // (36,15): warning CS8602: Dereference of a possibly null reference. // ? Ext._field.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Ext._field", isSuppressed: false).WithLocation(36, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // ? c._field.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c._field", isSuppressed: false).WithLocation(40, 15), // (41,15): warning CS8602: Dereference of a possibly null reference. // : c._field.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c._field", isSuppressed: false).WithLocation(41, 15) ); } [Fact] public void MemberNotNullWhenTrue_NonConstantBool() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; // 1 [MemberNotNullWhen(true, nameof(field1))] bool Init() { bool b = true; return b; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19) ); } [Fact] public void MemberNotNullWhenTrue_NullValues() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (Init()) { field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 } else { throw null!; } } [MemberNotNullWhen(true, null!, null!)] [MemberNotNullWhen(true, members: null!)] [MemberNotNullWhen(true, member: null!)] bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(14, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(15, 13), // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13) ); } [Fact] public void MemberNotNullWhenTrue_EnforcementInTryFinally() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (!Init()) { throw null!; } } [MemberNotNullWhen(true, nameof(field1), nameof(field2), nameof(field3), nameof(field4))] bool Init() { try { bool b = true; if (b) { field3 = """"; field4 = """"; return true; // 1, 2 } } finally { field1 = """"; field2 = """"; } return false; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics(); } [Fact] public void MemberNotNullWhenTrue_EnforcementInTryFinally_2() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; [MemberNotNullWhen(true, nameof(field1))] bool Init() { try { return true; } finally { field1 = string.Empty; } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19) ); } [Fact] public void MemberNotNullWhenTrue_EnforcementInTryFinally_2_Reversed() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; [MemberNotNullWhen(true, nameof(field1))] bool Init() { try { return false; } finally { field1 = string.Empty; } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19) ); } [Fact] public void MemberNotNullWhenTrue_EnforcementInTryFinally_Reversed() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (!Init()) { throw null!; } } [MemberNotNullWhen(true, nameof(field1), nameof(field2), nameof(field3), nameof(field4))] bool Init() { try { bool b = true; if (b) { field3 = """"; field4 = """"; return false; } } finally { field1 = """"; field2 = """"; } return true; // 1, 2 } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (37,9): warning CS8772: Member 'field3' must have a non-null value when exiting with 'true'. // return true; // 1, 2 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field3", "true").WithLocation(37, 9), // (37,9): warning CS8772: Member 'field4' must have a non-null value when exiting with 'true'. // return true; // 1, 2 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field4", "true").WithLocation(37, 9) ); } [Fact] public void MemberNotNullWhenFalse_EnforcementInTryFinally() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (NotInit()) { throw null!; } } [MemberNotNullWhen(false, nameof(field1), nameof(field2), nameof(field3), nameof(field4))] bool NotInit() { try { bool b = true; if (b) { field3 = """"; field4 = """"; return false; } } finally { field1 = """"; field2 = """"; } return true; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics(); } [Fact] public void MemberNotNullWhenTrue_Inheritance() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string field1; public string? field2; public string field3; public string? field4; public Base() // 1 { if (!Init()) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] public virtual bool Init() => throw null!; } public class Derived : Base { public string field5; public string? field6; public string field7; public string? field8; public Derived() : base() // 2 { if (!Init()) throw null!; } void M() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 3 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 4 } } [MemberNotNullWhen(true, nameof(field6), nameof(field7))] public override bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public Base() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Base").WithArguments("field", "field3").WithLocation(10, 12), // (26,12): warning CS8618: Non-nullable field 'field5' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field5").WithLocation(26, 12), // (39,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(39, 13), // (43,13): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(43, 13) ); } [Fact] public void MemberNotNullWhenTrue_Inheritance_PE() { var libComp = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string field1; public string? field2; public string? field2b; public string field3; public string? field4; public Base() { if (!Init()) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] [MemberNotNullWhen(true, nameof(field2b))] public virtual bool Init() => throw null!; }", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); var c = CreateNullableCompilation(@" using System.Diagnostics.CodeAnalysis; public class Derived : Base { public string field5; public string? field6; public string field7; public string? field8; public Derived() : base() // 1 { if (!Init()) throw null!; } void M() { if (Init()) { field1.ToString(); field2.ToString(); field2b.ToString(); field3.ToString(); field4.ToString(); // 2 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 3 } } [MemberNotNullWhen(true, nameof(field6), nameof(field7))] public override bool Init() => throw null!; } ", references: new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field5' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field5").WithLocation(10, 12), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13), // (28,13): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(28, 13) ); } [Fact] public void MemberNotNullWhenFalse_Inheritance_PE() { var libComp = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string field1; public string? field2; public string field3; public string? field4; public Base() { if (!NotInit()) throw null!; } [MemberNotNullWhen(false, nameof(field1), nameof(field2))] public virtual bool NotInit() => throw null!; }", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); var c = CreateNullableCompilation(@" using System.Diagnostics.CodeAnalysis; public class Derived : Base { public string field5; public string? field6; public string field7; public string? field8; public Derived() : base() // 1 { if (NotInit()) throw null!; } void M() { if (!NotInit()) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 2 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 3 } } [MemberNotNullWhen(false, nameof(field6), nameof(field7))] public override bool NotInit() => throw null!; } ", references: new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field5' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field5").WithLocation(10, 12), // (23,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(23, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(27, 13) ); } [Fact] public void MemberNotNullWhenTrue_Inheritance_Property() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string field1; public string? field2; public string field3; public string? field4; public Base() // 1 { if (!Init) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] public virtual bool Init => throw null!; } public class Derived : Base { public string field5; public string? field6; public string field7; public string? field8; public Derived() : base() // 3 { if (!Init) throw null!; } void M() { if (Init) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 4 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 5 } } [MemberNotNullWhen(true, nameof(field6), nameof(field7))] public override bool Init => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public Base() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Base").WithArguments("field", "field3").WithLocation(10, 12), // (26,12): warning CS8618: Non-nullable field 'field5' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 3 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field5").WithLocation(26, 12), // (39,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(39, 13), // (43,13): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(43, 13) ); } [Fact] public void MemberNotNullWhenTrue_Inheritance_Property_PE() { var libComp = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string field1; public string? field2; public string field3; public string? field4; public Base() { if (!Init) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] public virtual bool Init => throw null!; }", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); var c = CreateNullableCompilation(@" using System.Diagnostics.CodeAnalysis; public class Derived : Base { public string field5; public string? field6; public string field7; public string? field8; public Derived() : base() // 1 { if (!Init) throw null!; } void M() { if (Init) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 2 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 3 } } [MemberNotNullWhen(true, nameof(field6), nameof(field7))] public override bool Init => throw null!; } ", references: new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field5' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field5").WithLocation(10, 12), // (23,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(23, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(27, 13) ); } [Fact] public void MemberNotNullWhenTrue_Inheritance_New() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string field1; public string? field2; public string field3; public string? field4; public Base() // 1, 2 { Init(); } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] public virtual bool Init() => throw null!; } public class Derived : Base { public new string field1; public new string? field2; public new string field3; public new string? field4; public Derived() : base() // 3, 4 { Init(); } void M() { Init(); field1.ToString(); field2.ToString(); // 5 field3.ToString(); field4.ToString(); // 6 } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] public override bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public Base() // 1, 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Base").WithArguments("field", "field3").WithLocation(10, 12), // (10,12): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public Base() // 1, 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Base").WithArguments("field", "field1").WithLocation(10, 12), // (25,12): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 3, 4 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field3").WithLocation(25, 12), // (25,12): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 3, 4 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field1").WithLocation(25, 12), // (34,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(34, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(36, 9) ); } [Fact] public void MemberNotNull_InstanceMethodValidatingStaticFields() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static string field1; // 1 public static string? field2; public static string field3; // 2 public static string? field4; public void M() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 3 } else { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 4 } } [MemberNotNull(nameof(field1), nameof(field2))] bool Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,26): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public static string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 26), // (7,26): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public static string field3; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 26), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13) ); } [Fact] public void MemberNotNullWhenTrue_InstanceMethodValidatingStaticFields() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static string field1; // 1 public static string? field2; public static string field3; // 2 public static string? field4; public void M() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 3 } else { field1.ToString(); field2.ToString(); // 4 field3.ToString(); field4.ToString(); // 5 } } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,26): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public static string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 26), // (7,26): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public static string field3; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 26), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (22,13): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(22, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13) ); } [Fact] public void MemberNotNullWhenTrue_Property() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (IsInit) { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } else { field1.ToString(); // 3 field2.ToString(); // 4 field3.ToString(); // 5 field4.ToString(); // 6 throw null!; } } public C(bool b) { IsInit = b; field1.ToString(); // 7 field2.ToString(); // 8 field3.ToString(); // 9 field4.ToString(); // 10 } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool IsInit { get => throw null!; set => throw null!; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (21,13): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(21, 13), // (22,13): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(22, 13), // (23,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(23, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13), // (32,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(32, 9), // (33,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(33, 9), // (34,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(34, 9), // (35,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(35, 9) ); } [Fact] public void MemberNotNullWhenTrue_Property_AppliedOnGetter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (IsInit) { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } else { field1.ToString(); // 3 field2.ToString(); // 4 field3.ToString(); // 5 field4.ToString(); // 6 throw null!; } } bool IsInit { [MemberNotNullWhen(true, nameof(field1), nameof(field2))] get => throw null!; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (21,13): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(21, 13), // (22,13): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(22, 13), // (23,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(23, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13) ); } [Fact] public void MemberNotNullWhenTrue_Property_AppliedOnSetter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { IsInit = true; field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 } bool IsInit { get { bool b = true; if (b) { field1 = """"; return true; // 5 } field2 = """"; return false; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] set { } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNullWhenTrue_Property_Static() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public static class C { public static string field1; // 1 public static string? field2; public static string field3; // 2 public static string? field4; public static void M() { if (IsInit) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 3 } else { field1.ToString(); field2.ToString(); // 4 field3.ToString(); field4.ToString(); // 5 throw null!; } } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] static bool IsInit => true; // 6, 7 } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,26): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public static string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 26), // (7,26): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public static string field3; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 26), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (22,13): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(22, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13), // (31,12): error CS8772: Member 'field1' must have a non-null value when exiting with 'true'. // => true; // 6, 7 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "true").WithArguments("field1", "true").WithLocation(31, 12), // (31,12): error CS8772: Member 'field2' must have a non-null value when exiting with 'true'. // => true; // 6, 7 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "true").WithArguments("field2", "true").WithLocation(31, 12) ); } [Fact] public void MemberNotNullWhenTrue_Multiple() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } else { throw null!; } } [MemberNotNullWhen(true, nameof(field1)), MemberNotNullWhen(true, nameof(field2))] bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13) ); } [Fact] public void MemberNotNullWhenTrue_Multiple_ParamsConstructor() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); } else { throw null!; } } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] [MemberNotNullWhen(true, nameof(field3), nameof(field4))] bool Init() { return true; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (29,9): warning CS8775: Member 'field1' must have a non-null value when exiting with 'true'. // return true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field1", "true").WithLocation(29, 9), // (29,9): warning CS8775: Member 'field2' must have a non-null value when exiting with 'true'. // return true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field2", "true").WithLocation(29, 9), // (29,9): warning CS8775: Member 'field3' must have a non-null value when exiting with 'true'. // return true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field3", "true").WithLocation(29, 9), // (29,9): warning CS8775: Member 'field4' must have a non-null value when exiting with 'true'. // return true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field4", "true").WithLocation(29, 9) ); } [Fact] public void MemberNotNullWhenTrue_Multiple_Property() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string? field3; public string? field4; public C() { if (Init) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); } else { throw null!; } } [MemberNotNullWhen(true, nameof(field1))] [MemberNotNullWhen(true, nameof(field2), nameof(field3))] bool Init { get => true; set { } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (29,16): warning CS8775: Member 'field1' must have a non-null value when exiting with 'true'. // get => true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "true").WithArguments("field1", "true").WithLocation(29, 16), // (29,16): warning CS8775: Member 'field2' must have a non-null value when exiting with 'true'. // get => true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "true").WithArguments("field2", "true").WithLocation(29, 16), // (29,16): warning CS8775: Member 'field3' must have a non-null value when exiting with 'true'. // get => true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "true").WithArguments("field3", "true").WithLocation(29, 16) ); } [Fact] public void MemberNotNullWhenFalse_Simple() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (NotInit()) { throw null!; } else { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } } [MemberNotNullWhen(false, nameof(field1), nameof(field2))] bool NotInit() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (20,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(20, 13), // (21,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(21, 13) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() // 1 { if (!Init()) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init() { bool b = true; if (b) { return true; // 2, 3 } field2 = """"; return false; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (21,13): error CS8772: Member 'field1' must have a non-null value when exiting with 'true'. // return true; // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field1", "true").WithLocation(21, 13), // (21,13): error CS8772: Member 'field2' must have a non-null value when exiting with 'true'. // return true; // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field2", "true").WithLocation(21, 13) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody_NonConstant() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() // 1 { if (!Init()) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init() { bool b = true; if (b) { return b; } if (b) { return !b; } return M(out _); } bool M([MaybeNullWhen(true)]out string s) => throw null!; } ", MemberNotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody_NonConstant_ButAnalyzable() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string field3; C() { if (!Init()) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field3))] bool Init() { bool b = true; if (b) { return field1 == null; // 1 } if (b) { return field1 != null; } if (b) { return Init(); } return !Init(); // 2, 3 } } ", MemberNotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (19,13): warning CS8775: Member 'field1' must have a non-null value when exiting with 'true'. // return field1 == null; // 1 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return field1 == null;").WithArguments("field1", "true").WithLocation(19, 13), // (29,9): warning CS8775: Member 'field1' must have a non-null value when exiting with 'true'. // return !Init(); // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return !Init();").WithArguments("field1", "true").WithLocation(29, 9), // (29,9): warning CS8775: Member 'field3' must have a non-null value when exiting with 'true'. // return !Init(); // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return !Init();").WithArguments("field3", "true").WithLocation(29, 9) ); } [Fact] public void MemberNotNullWhenFalse_EnforcedInMethodBody_NonConstant_ButAnalyzable() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string field3; C() { if (Init()) throw null!; } [MemberNotNullWhen(false, nameof(field1), nameof(field3))] bool Init() { bool b = true; if (b) { return field1 == null; } if (b) { return field1 != null; // 1 } if (b) { return Init(); } return !Init(); // 2, 3 } bool M([MaybeNullWhen(true)]out string s) => throw null!; } ", MemberNotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (23,13): warning CS8775: Member 'field1' must have a non-null value when exiting with 'false'. // return field1 != null; // 1 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return field1 != null;").WithArguments("field1", "false").WithLocation(23, 13), // (29,9): warning CS8775: Member 'field1' must have a non-null value when exiting with 'false'. // return !Init(); // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return !Init();").WithArguments("field1", "false").WithLocation(29, 9), // (29,9): warning CS8775: Member 'field3' must have a non-null value when exiting with 'false'. // return !Init(); // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return !Init();").WithArguments("field3", "false").WithLocation(29, 9) ); } [Fact] public void MemberNotNullWhenTrue_WithMemberNotNull() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public string field5; public string? field6; C() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); field5.ToString(); // 1 field6.ToString(); // 2 } else { field1.ToString(); field2.ToString(); field3.ToString(); // 3 field4.ToString(); // 4 field5.ToString(); // 5 field6.ToString(); // 6 } } [MemberNotNull(nameof(field1), nameof(field2))] [MemberNotNullWhen(true, nameof(field3), nameof(field4))] bool Init() => throw null!; } ", MemberNotNullAttributeDefinition, MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (20,13): warning CS8602: Dereference of a possibly null reference. // field5.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field5").WithLocation(20, 13), // (21,13): warning CS8602: Dereference of a possibly null reference. // field6.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field6").WithLocation(21, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(27, 13), // (28,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(28, 13), // (29,13): warning CS8602: Dereference of a possibly null reference. // field5.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field5").WithLocation(29, 13), // (30,13): warning CS8602: Dereference of a possibly null reference. // field6.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field6").WithLocation(30, 13) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody_UnreachableExit() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init(bool b) { try { if (b) return true; else return false; } finally { throw null!; } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody_UnreachableExit() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; [MemberNotNull(nameof(field1), nameof(field2))] bool Init(bool b) { try { if (b) return true; else return false; } finally { throw null!; } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19) ); } [Fact, WorkItem(44080, "https://github.com/dotnet/roslyn/issues/44080")] public void MemberNotNullWhenTrue_EnforcedInMethodBody_NonConstantBool() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string? field3; [MemberNotNullWhen(true, nameof(field1), nameof(field2), nameof(field3))] bool Init() { field2 = """"; return NonConstantBool(); } bool NonConstantBool() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody_Property() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() // 1 { if (!IsInit) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool IsInit { get { bool b = true; if (b) { return true; // 2, 3 } field2 = """"; return false; } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (23,17): error CS8772: Member 'field1' must have a non-null value when exiting with 'true'. // return true; // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field1", "true").WithLocation(23, 17), // (23,17): error CS8772: Member 'field2' must have a non-null value when exiting with 'true'. // return true; // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field2", "true").WithLocation(23, 17) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody_Property_NotConstantReturn() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string? field2; [MemberNotNullWhen(true, nameof(field2))] bool IsInit { get { return field2 != null; } } [MemberNotNullWhen(true, nameof(field2))] bool IsInit2 { get { return field2 == null; // 1 } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (21,13): warning CS8775: Member 'field2' must have a non-null value when exiting with 'true'. // return field2 == null; // 1 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return field2 == null;").WithArguments("field2", "true").WithLocation(21, 13) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody_SwitchedBranches() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() // 1 { if (!Init()) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init() { bool b = true; if (b) { return false; } field2 = """"; return true; // 2 } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (24,9): error CS8772: Member 'field1' must have a non-null value when exiting with 'true'. // return true; // 2 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field1", "true").WithLocation(24, 9) ); } [Fact] public void MemberNotNullWhenFalse_EnforcedInMethodBody() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() // 1, 2 { if (!Init()) throw null!; } [MemberNotNullWhen(false, nameof(field1), nameof(field2), nameof(field4))] bool Init() { bool b = true; if (b) { return true; } field2 = """"; return false; // 3, 4 } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() // 1, 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (10,5): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // C() // 1, 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field1").WithLocation(10, 5), // (24,9): error CS8772: Member 'field1' must have a non-null value when exiting with 'false'. // return false; // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return false;").WithArguments("field1", "false").WithLocation(24, 9), // (24,9): error CS8772: Member 'field4' must have a non-null value when exiting with 'false'. // return false; // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return false;").WithArguments("field4", "false").WithLocation(24, 9) ); } [Fact] public void MemberNotNullWhenFalse_VoidReturning() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; // 1 public string? field2; public string field3; // 2 public string? field4; [MemberNotNullWhen(false, nameof(field1), nameof(field2), nameof(field4))] void Init() { bool b = true; if (b) { return; } field2 = """"; return; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19), // (7,19): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public string field3; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 19) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void NullableValueType_RecursivePattern() { var c = CreateCompilation(@" #nullable enable public struct Test { public int M(int? i) { switch (i) { case { HasValue: true }: return i.Value; default: return i.Value; } } } "); c.VerifyDiagnostics( // (10,20): error CS0117: 'int' does not contain a definition for 'HasValue' // case { HasValue: true }: Diagnostic(ErrorCode.ERR_NoSuchMember, "HasValue").WithArguments("int", "HasValue").WithLocation(10, 20), // (13,24): warning CS8629: Nullable value type may be null. // return i.Value; Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(13, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: true }: return Value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_Nested() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } } public class Container { public C? Item; public string M() { switch (this) { case { Item: { IsOk: true } }: return this.Item.Value; case { Item: C item }: return item.Value; // 1 default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (22,24): warning CS8603: Possible null reference return. // return item.Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "item.Value").WithLocation(22, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_Nested_WithDeclaration() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } } public class Container { public C? Item; public string M() { switch (this) { case { Item: { IsOk: true } item }: return item.Value; case { Item: C item }: return item.Value; // 1 default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (22,24): warning CS8603: Possible null reference return. // return item.Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "item.Value").WithLocation(22, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithSecondPattern() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public bool IsIrrelevant { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: false }: return Value; // 1 case { IsOk: true, IsIrrelevant: true }: return Value; default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (17,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(17, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_SplitValueIntoVariable() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: var v }: return Value; // 1 default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (16,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(16, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] [WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void MemberNotNullWhenTrue_TupleInSwitchStatement() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M(object? o) { switch (this, o) { case ({ IsOk: true }, null): return Value; case ({ IsOk: true }, not null): return Value; default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] [WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void MemberNotNullWhenTrue_TupleInSwitchExpression() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M(object? o) { return (this, o) switch { ({ IsOk: true }, null) => M2(Value), ({ IsOk: true }, not null) => M2(Value), _ => throw null!, }; } string M2(string s) => throw null!; } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] [WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void MemberNotNullWhenTrue_TupleInIsExpression() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M(object? o) { if ((this, o) is ({ IsOk: true }, null)) { return Value; } throw null!; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] [WorkItem(50980, "https://github.com/dotnet/roslyn/issues/50980")] public void MemberNotNullWhenTrue_TupleEquality() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M(object? o) { if ((IsOk, o) is (true, null)) { return Value; // incorrect warning } if (IsOk is true) { return Value; } throw null!; } } ", MemberNotNullWhenAttributeDefinition }); // We're not learning from tuple equality... // Tracked by https://github.com/dotnet/roslyn/issues/50980 c.VerifyDiagnostics( // (15,20): warning CS8603: Possible null reference return. // return Value; // incorrect warning Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(15, 20) ); } [Fact, WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void PatternOnTuple_IsExpression() { var src = @" #nullable enable public class C { void M(object? o, object o2) { if ((o, o2) is (not null, null)) { o.ToString(); o2.ToString(); // 1 } } void M2(object? o) { if (o is not null) { o.ToString(); } } void M3(object o2) { if (o2 is null) { o2.ToString(); // 2 } } void M4(object? o, object o2) { if ((true, (o, o2)) is (true, (not null, null))) { o.ToString(); // 3 o2.ToString(); } } } "; // Note: we lose track in M4 because any learnings we make on elements of nested tuples // apply to temps, rather than the original expressions/slots. // This is unfortunate, but doesn't seem much of a priority to address. var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // o2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o2").WithLocation(10, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // o2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o2").WithLocation(26, 13), // (34,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(34, 13) ); } [Fact, WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void PatternOnTuple_IsExpression_ContradictoryTests() { var src = @" #nullable enable public class C { void M(object o) { if ((o, o) is (not null, null)) { o.ToString(); // 1 } } void M2(object? o) { if ((o, o) is (null, not null)) { o.ToString(); } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(9, 13) ); } [Fact, WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void PatternOnTuple_IsExpression_LongTuple() { var src = @" #nullable enable public class C { void M(object? o, object o2) { if ((o2, o2, o2, o2, o2, o2, o2, o) is (null, null, null, null, null, null, null, not null)) { o.ToString(); o2.ToString(); // 1 } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // o2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o2").WithLocation(10, 13) ); } [Fact, WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void PatternOnTuple_IsExpression_LearnFromNonNullTest() { var src = @" #nullable enable public class C { int Value { get; set; } void M(C? c, object? o) { if ((c?.Value, o) is (1, not null)) { c.ToString(); } } void M2(C? c) { if (c?.Value is 1) { c.ToString(); } } void M3(C? c, object? o) { if ((true, (o, o, c?.Value)) is (true, (not null, not null, 1))) { c.ToString(); // 1 } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (27,13): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(27, 13) ); } [Fact, WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void PatternOnTuple_SwitchExpression() { var src = @" #nullable enable public class C { int Test(object o, object o2) => throw null!; void M(object? o, object o2) { _ = (o, o2) switch { (not null, null) => Test(o, o2), // 1 (not null, not null) => Test(o, o2), _ => Test(o, o2), // 2 }; } void M2(object? o, object o2) { _ = (true, (o, o2)) switch { (true, (not null, null)) => Test(o, o2), // 3 (_, (not null, not null)) => Test(o, o2), // 4 _ => Test(o, o2), // 5 }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,41): warning CS8604: Possible null reference argument for parameter 'o2' in 'int C.Test(object o, object o2)'. // (not null, null) => Test(o, o2), // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o2").WithArguments("o2", "int C.Test(object o, object o2)").WithLocation(11, 41), // (13,23): warning CS8604: Possible null reference argument for parameter 'o' in 'int C.Test(object o, object o2)'. // _ => Test(o, o2), // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "int C.Test(object o, object o2)").WithLocation(13, 23), // (21,46): warning CS8604: Possible null reference argument for parameter 'o' in 'int C.Test(object o, object o2)'. // (true, (not null, null)) => Test(o, o2), // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "int C.Test(object o, object o2)").WithLocation(21, 46), // (22,47): warning CS8604: Possible null reference argument for parameter 'o' in 'int C.Test(object o, object o2)'. // (_, (not null, not null)) => Test(o, o2), // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "int C.Test(object o, object o2)").WithLocation(22, 47), // (23,23): warning CS8604: Possible null reference argument for parameter 'o' in 'int C.Test(object o, object o2)'. // _ => Test(o, o2), // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "int C.Test(object o, object o2)").WithLocation(23, 23) ); } [Fact, WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void PatternOnTuple_SwitchStatement() { var src = @" #nullable enable public class C { void Test(object o, object o2) => throw null!; void M(object? o, object o2) { switch (o, o2) { case (not null, null): Test(o, o2); // 1 break; case (not null, not null): Test(o, o2); break; default: Test(o, o2); // 2 break; } } void M2(object? o, object o2) { switch (true, (o, o2)) { case (true, (not null, null)): Test(o, o2); // 3 break; case (_, (not null, not null)): Test(o, o2); // 4 break; default: Test(o, o2); // 5 break; }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,25): warning CS8604: Possible null reference argument for parameter 'o2' in 'void C.Test(object o, object o2)'. // Test(o, o2); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o2").WithArguments("o2", "void C.Test(object o, object o2)").WithLocation(12, 25), // (18,22): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.Test(object o, object o2)'. // Test(o, o2); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.Test(object o, object o2)").WithLocation(18, 22), // (28,22): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.Test(object o, object o2)'. // Test(o, o2); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.Test(object o, object o2)").WithLocation(28, 22), // (31,22): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.Test(object o, object o2)'. // Test(o, o2); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.Test(object o, object o2)").WithLocation(31, 22), // (34,22): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.Test(object o, object o2)'. // Test(o, o2); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.Test(object o, object o2)").WithLocation(34, 22) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_TypeTest() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: bool }: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (16,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(16, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_StateAfterSwitch() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: true }: break; default: throw null!; } return Value; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithBoolPattern() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public bool IsIrrelevant { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: true, IsIrrelevant: true }: return Value; case { IsOk: true, IsIrrelevant: not true }: return Value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (21,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(21, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_OnSetter() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { set { } } public string? Value { get; } public string M() { switch (this) { case { IsOk: true }: // 1 return Value; // 2 default: return Value; // 3 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (15,20): error CS0154: The property or indexer 'C.IsOk' cannot be used in this context because it lacks the get accessor // case { IsOk: true }: // 1 Diagnostic(ErrorCode.ERR_PropertyLacksGet, "IsOk:").WithArguments("C.IsOk").WithLocation(15, 20), // (16,24): warning CS8603: Possible null reference return. // return Value; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(16, 24), // (18,24): warning CS8603: Possible null reference return. // return Value; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_AttributeOnBase() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Base { [MemberNotNullWhen(true, nameof(Value))] public virtual bool IsOk { get; } public string? Value { get; } } public class C : Base { public override bool IsOk { get; } public string M() { switch (this) { case { IsOk: true }: return Value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (22,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(22, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_NotFalse() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: not false }: return Value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenFalse_RecursivePattern() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(false, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: false }: return Value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithNestedDeclaration() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: true, Value: var value }: return value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithNestedDeclaration_ReverseOrder_Struct() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { Value: var value, IsOk: true }: return value; case { Value: var value }: return value; // 1 default: return Value; // 2 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "value").WithLocation(18, 24), // (20,17): warning CS0162: Unreachable code detected // return Value; // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(20, 17) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_Struct() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: true }: return Value; default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); // Analysis of patterns assumes that they are pure, so testing a copy of a struct is // as good as testing the original instance c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithNestedDeclaration_ReverseOrder_Class() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { Value: var value, IsOk: true }: return value; case { Value: var value }: return value; // 1 default: return Value; // not thought as reachable by nullable analysis because `this` is not-null } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithNestedDeclaration_ReverseOrder_Class_OnMaybeNullVariable() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M(Test? t) { switch (t) { case { Value: var value, IsOk: true }: return value; case { Value: var value }: return value; // 1 default: return t.Value; // 2 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "value").WithLocation(18, 24), // (20,24): warning CS8602: Dereference of a possibly null reference. // return t.Value; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(20, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithTopLevelDeclaration() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: true } c: return c.Value; default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithTopLevelDeclaration_WithType() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case C { IsOk: true } c: // note: has type return c.Value; case C c: return c.Value; // 1 default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return c.Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "c.Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_BinaryPatternTest() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public bool IsRandom { get; } public string? Value { get; } public string M() { if (this is { IsOk: true } and { IsRandom: true }) { return Value; } if (this is { IsOk: true } or { IsRandom: true }) { return Value; // 1 } return Value; // 2 } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (21,20): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(21, 20), // (24,16): warning CS8603: Possible null reference return. // return Value; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(24, 16) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_BinaryPatternTest_Struct() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct S { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { if (this is { IsOk: true }) { return Value; } throw null!; } } ", MemberNotNullWhenAttributeDefinition }); // Analysis of patterns assumes that they are pure, so testing a copy of a struct is // as good as testing the original instance c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_IsTrueTest() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { if (IsOk is true) { return Value; } else { return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (19,20): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(19, 20) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_IsNotTrueTest() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { if (IsOk is not true) { return Value; // 1 } else { return Value; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (15,20): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(15, 20) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_IsNotFalseTest() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { if (IsOk is not false) { return Value; } else { return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (19,20): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(19, 20) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_IsTrueTest_OnLocal() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public static string M(Test t) { if (t.IsOk is true) { return t.Value; } else { return t.Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (19,20): warning CS8603: Possible null reference return. // return t.Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t.Value").WithLocation(19, 20) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_IsFalseTest() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { if (IsOk is false) { return Value; // 1 } else { return Value; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (15,20): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(15, 20) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_SwitchStatementOnProperty() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (IsOk) { case true: return Value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_SwitchExpressionOnProperty() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { return IsOk switch { true => Value, _ => throw null!, }; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_SwitchExpressionOnMethod() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk() { throw null!; } public string? Value { get; } public string M() { return IsOk() switch { true => Value, _ => throw null!, }; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_SwitchExpressionOnProperty_WhenFalseBranch() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { return IsOk switch { true => throw null!, _ => Value }; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (13,16): warning CS8603: Possible null reference return. // return IsOk switch { true => throw null!, _ => Value }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "IsOk switch { true => throw null!, _ => Value }").WithLocation(13, 16) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_Ternary() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { return IsOk ? Value : throw null!; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_Ternary_WhenFalseBranch() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { return IsOk ? throw null! : Value; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (13,16): warning CS8603: Possible null reference return. // return IsOk ? throw null! : Value; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "IsOk ? throw null! : Value").WithLocation(13, 16) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNull_RecursivePattern() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNull(nameof(Value))] public int InitCount { get; } public string? Value { get; } public string M() { switch (this) { case { InitCount: var n }: return Value; default: return Value; // 1 } } } ", MemberNotNullAttributeDefinition }); // We honored the unconditional MemberNotNull attributes in the arms where // we know it was evaluated. We recommend that users don't do this. c.VerifyDiagnostics( // (18,17): warning CS0162: Unreachable code detected // return Value; // 1 Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(18, 17) ); } [Fact] public void ConstructorUsesStateFromInitializers() { var source = @" public class Program { public string Prop { get; set; } = ""a""; public Program() { Prop.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source }); comp.VerifyDiagnostics(); } [Fact] public void ConstMembersUseDeclaredNullability_01() { var source = @" public class Program { const string s1 = ""hello""; public static readonly string s2 = s1.ToString(); public Program() { } } "; var comp = CreateNullableCompilation(new[] { source }); comp.VerifyDiagnostics(); } [Fact] public void ConstMembersUseDeclaredNullability_02() { var source = @" public class Program { const string? s1 = ""hello""; public Program() { var x = s1.ToString(); // 1 } } "; // Arguably we could just see through to the constant value and know it's non-null, // but it feels like the user should just fix the type of their 'const' in this scenario. var comp = CreateNullableCompilation(new[] { source }); comp.VerifyDiagnostics( // (8,17): warning CS8602: Dereference of a possibly null reference. // var x = s1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(8, 17)); } [Fact] public void ComputedPropertiesUseDeclaredNullability() { var source = @" public class Program { string Prop1 => ""hello""; string? Prop2 => ""world""; public Program() { Prop1.ToString(); Prop2.ToString(); // 1 } } "; var comp = CreateNullableCompilation(new[] { source }); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // Prop2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Prop2").WithLocation(10, 9)); } [Fact] public void MaybeNullWhenTrue_Simple() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (IsNull(s)) { s.ToString(); // warn } else { s.ToString(); // ok } s.ToString(); // ok } public static bool IsNull([MaybeNullWhen(true)] string s) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void MaybeNullWhenTrue_Indexer() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { _ = this[s] ? s.ToString() // 1 : s.ToString(); } public bool this[[MaybeNullWhen(true)] string s] => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 15) ); } [Fact] public void MaybeNullWhenTrue_OutParameter_MiscTypes() { // Warn on redundant nullability attributes (F3, F4 and F5)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool F1<T>(T t, [MaybeNullWhen(true)]out T t2) => throw null!; static bool F2<T>(T t, [MaybeNullWhen(true)]out T t2) where T : class => throw null!; static bool F3<T>(T t, [MaybeNullWhen(true)]out T? t2) where T : class => throw null!; static bool F4<T>(T t, [MaybeNullWhen(true)]out T t2) where T : struct => throw null!; static bool F5<T>(T? t, [MaybeNullWhen(true)]out T? t2) where T : struct => throw null!; static void M1<T>(T t1) { _ = F1(t1, out var s2) // 0 ? s2.ToString() // 1 : s2.ToString(); // 2 } static void M2<T>(T t2) where T : class { _ = F1(t2, out var s3) ? s3.ToString() // 3 : s3.ToString(); _ = F2(t2, out var s4) ? s4.ToString() // 4 : s4.ToString(); _ = F3(t2, out var s5) ? s5.ToString() // 5 : s5.ToString(); // 6 t2 = null; // 7 _ = F1(t2, out var s6) ? s6.ToString() // 8 : s6.ToString(); // 9 _ = F2(t2, out var s7) // 10 ? s7.ToString() // 11 : s7.ToString(); // 12 _ = F3(t2, out var s8) // 13 ? s8.ToString() // 14 : s8.ToString(); // 15 } static void M3<T>(T? t3) where T : class { _ = F1(t3, out var s9) ? s9.ToString() // 16 : s9.ToString(); // 17 _ = F2(t3, out var s10) // 18 ? s10.ToString() // 19 : s10.ToString(); // 20 _ = F3(t3, out var s11) // 21 ? s11.ToString() // 22 : s11.ToString(); // 23 if (t3 == null) return; _ = F1(t3, out var s12) ? s12.ToString() // 24 : s12.ToString(); _ = F2(t3, out var s13) ? s13.ToString() // 25 : s13.ToString(); _ = F3(t3, out var s14) ? s14.ToString() // 26 : s14.ToString(); // 27 } static void M4<T>(T t4) where T : struct { _ = F1(t4, out var s15) ? s15.ToString() : s15.ToString(); _ = F4(t4, out var s16) ? s16.ToString() : s16.ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1(t5, out var s17) ? s17.Value // 28 : s17.Value; // 29 _ = F5(t5, out var s18) ? s18.Value // 30 : s18.Value; // 31 if (t5 == null) return; _ = F1(t5, out var s19) ? s19.Value // 32 : s19.Value; // 33 _ = F5(t5, out var s20) ? s20.Value // 34 : s20.Value; // 35 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // ? s2.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 15), // (13,15): warning CS8602: Dereference of a possibly null reference. // : s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(13, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? s3.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(18, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // ? s4.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(22, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // ? s5.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(26, 15), // (27,15): warning CS8602: Dereference of a possibly null reference. // : s5.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(27, 15), // (29,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 7 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(29, 14), // (31,15): warning CS8602: Dereference of a possibly null reference. // ? s6.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(31, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // : s6.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(32, 15), // (34,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F2(t2, out var s7) // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(34, 13), // (35,15): warning CS8602: Dereference of a possibly null reference. // ? s7.ToString() // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s7").WithLocation(35, 15), // (36,15): warning CS8602: Dereference of a possibly null reference. // : s7.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s7").WithLocation(36, 15), // (38,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F3(t2, out var s8) // 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(38, 13), // (39,15): warning CS8602: Dereference of a possibly null reference. // ? s8.ToString() // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s8").WithLocation(39, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : s8.ToString(); // 15 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s8").WithLocation(40, 15), // (45,15): warning CS8602: Dereference of a possibly null reference. // ? s9.ToString() // 16 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s9").WithLocation(45, 15), // (46,15): warning CS8602: Dereference of a possibly null reference. // : s9.ToString(); // 17 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s9").WithLocation(46, 15), // (48,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F2(t3, out var s10) // 18 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(48, 13), // (49,15): warning CS8602: Dereference of a possibly null reference. // ? s10.ToString() // 19 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s10").WithLocation(49, 15), // (50,15): warning CS8602: Dereference of a possibly null reference. // : s10.ToString(); // 20 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s10").WithLocation(50, 15), // (52,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F3(t3, out var s11) // 21 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(52, 13), // (53,15): warning CS8602: Dereference of a possibly null reference. // ? s11.ToString() // 22 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s11").WithLocation(53, 15), // (54,15): warning CS8602: Dereference of a possibly null reference. // : s11.ToString(); // 23 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s11").WithLocation(54, 15), // (58,15): warning CS8602: Dereference of a possibly null reference. // ? s12.ToString() // 24 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s12").WithLocation(58, 15), // (62,15): warning CS8602: Dereference of a possibly null reference. // ? s13.ToString() // 25 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s13").WithLocation(62, 15), // (66,15): warning CS8602: Dereference of a possibly null reference. // ? s14.ToString() // 26 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s14").WithLocation(66, 15), // (67,15): warning CS8602: Dereference of a possibly null reference. // : s14.ToString(); // 27 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s14").WithLocation(67, 15), // (82,15): warning CS8629: Nullable value type may be null. // ? s17.Value // 28 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s17").WithLocation(82, 15), // (83,15): warning CS8629: Nullable value type may be null. // : s17.Value; // 29 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s17").WithLocation(83, 15), // (86,15): warning CS8629: Nullable value type may be null. // ? s18.Value // 30 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s18").WithLocation(86, 15), // (87,15): warning CS8629: Nullable value type may be null. // : s18.Value; // 31 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s18").WithLocation(87, 15), // (91,15): warning CS8629: Nullable value type may be null. // ? s19.Value // 32 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s19").WithLocation(91, 15), // (92,15): warning CS8629: Nullable value type may be null. // : s19.Value; // 33 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s19").WithLocation(92, 15), // (95,15): warning CS8629: Nullable value type may be null. // ? s20.Value // 34 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s20").WithLocation(95, 15), // (96,15): warning CS8629: Nullable value type may be null. // : s20.Value; // 35 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s20").WithLocation(96, 15) ); } [Fact] public void MaybeNullWhenTrue_FromMetadata() { var lib = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static bool MaybeNullWhenTrue([MaybeNullWhen(true)] string s) => throw null!; } ", MaybeNullWhenAttributeDefinition }); var c = CreateNullableCompilation(@" public class D { public void Main(string s) { _ = C.MaybeNullWhenTrue(s) ? s.ToString() // 1 : s.ToString(); s.ToString(); } } ", references: new[] { lib.EmitToImageReference() }); c.VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 15) ); } [Fact] public void MaybeNullWhenFalse_FromMetadata() { var lib = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static bool MaybeNullWhenFalse([MaybeNullWhen(false)] string s) => throw null!; } ", MaybeNullWhenAttributeDefinition }); var c = CreateNullableCompilation(@" public class D { public void Main(string s) { _ = C.MaybeNullWhenFalse(s) ? s.ToString() : s.ToString(); // 1 } } ", references: new[] { lib.EmitToImageReference() }); c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 15) ); } [Fact] public void MaybeNullWhenFalse_TryGetValue() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Optional<T> { public void Main(Optional<string> holder) { _ = holder.TryGetValue(out var item) ? item.ToString() : item.ToString(); // 1 item = null; } bool TryGetValue([MaybeNullWhen(false)] out T item) => throw null!; } ", MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // : item.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(9, 15) ); } [Fact] public void MaybeNull_TryGetValue() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Optional<T> { public void Main(Optional<string> holder) { _ = holder.TryGetValue(out var item) ? item.ToString() // 1 : item.ToString(); // 2 item = null; } bool TryGetValue([MaybeNull] out T item) => throw null!; } ", MaybeNullAttributeDefinition }); c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // ? item.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(8, 15), // (9,15): warning CS8602: Dereference of a possibly null reference. // : item.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(9, 15) ); } [Fact, WorkItem(42722, "https://github.com/dotnet/roslyn/issues/42722")] public void MaybeNull_NullableRefParameterAssigningToMaybeNullStringParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void M([MaybeNull] ref string s) { Test(ref s); } void Test(ref string? s) => s = null; } ", MaybeNullAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(42743, "https://github.com/dotnet/roslyn/issues/42743")] public void NotNull_NullableRefParameterAssigningToNotNullParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { static void M([NotNull] out string? s) { s = """"; Ref(ref s); void Ref(ref string? s) => s = null; } } ", NotNullAttributeDefinition }); c.VerifyDiagnostics( // (12,5): warning CS8777: Parameter 's' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("s").WithLocation(12, 5) ); } [Fact, WorkItem(42743, "https://github.com/dotnet/roslyn/issues/42743")] public void MaybeNull_NullableRefParameterAssigningToMaybeNullParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void M([MaybeNull] out string s) { s = null; Out(out s); Ref(ref s); void Out(out string? s) => s = null; void Ref(ref string? s) => s = null; } } ", MaybeNullAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(37014, "https://github.com/dotnet/roslyn/pull/37014")] public void NotNull_CompareExchangeIntoRefNotNullParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; using System.Threading; class C { internal static T InterlockedStore<T>([NotNull] ref T? target, T value) where T : class { return Interlocked.CompareExchange(ref target, value, null) ?? value; } } ", NotNullAttributeDefinition }); c.VerifyDiagnostics(); } [Fact] public void NotNullWhenTrue_FromMetadata() { var lib = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static bool NotNullWhenTrue([NotNullWhen(true)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }); var c = CreateNullableCompilation(@" public class D { public void Main(string? s) { _ = C.NotNullWhenTrue(s) ? s.ToString() : s.ToString(); // 1 } } ", references: new[] { lib.EmitToImageReference() }); c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 15) ); } [Fact] public void NotNullWhenFalse_FromMetadata() { var lib = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static bool NotNullWhenFalse([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }); var c = CreateNullableCompilation(@" public class D { public void Main(string? s) { _ = C.NotNullWhenFalse(s) ? s.ToString() // 1 : s.ToString(); } } ", references: new[] { lib.EmitToImageReference() }); c.VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 15) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(true)] out string? s) { bool b = true; if (b) { s = null; return false; } else { s = """"; return true; } } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNullWhenTrue_EnforceInMethodBody_ConditionalWithThrow() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { static bool M([NotNullWhen(true)] object? o) { return o == null ? true : throw null!; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNullWhenTrue_EnforceInMethodBody_WithMaybeNull_CallingObliviousAPI() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue<T>([MaybeNull] [NotNullWhen(true)] out T t) { return TryGetValue2<T>(out t); } #nullable disable public static bool TryGetValue2<T>(out T t) => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody_Warn() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(true)] out string? s) { bool b = true; if (b) { s = null; return true; // 1 } else { s = """"; return false; } } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,13): error CS8762: Parameter 's' must have a non-null value when exiting with 'true'. // return true; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return true;").WithArguments("s", "true").WithLocation(11, 13) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody_DoNotWarnInLocalFunction() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Reflection; public class C { private static bool TryGetTaskOfTOrValueTaskOfTType(TypeInfo taskTypeInfo, [NotNullWhen(true)] out TypeInfo? taskOfTTypeInfo) { TypeInfo? taskTypeInfoLocal = taskTypeInfo; while (taskTypeInfoLocal != null) { if (IsTaskOfTOrValueTaskOfT(taskTypeInfoLocal)) { taskOfTTypeInfo = taskTypeInfoLocal; return true; } taskTypeInfoLocal = taskTypeInfoLocal.BaseType?.GetTypeInfo(); } taskOfTTypeInfo = null; return false; bool IsTaskOfTOrValueTaskOfT(TypeInfo typeInfo) => typeInfo.IsGenericType && (typeInfo.GetGenericTypeDefinition() == typeof(int)); } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody_InTryFinally() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(true)] out string? s) { try { bool b = true; if (b) { s = """"; return true; } throw null!; } finally { s = null; } } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (13,17): warning CS8762: Parameter 's' must have a non-null value when exiting with 'true'. // return true; Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return true;").WithArguments("s", "true").WithLocation(13, 17) ); } [Fact, WorkItem(42981, "https://github.com/dotnet/roslyn/issues/42981")] public void MaybeNullWhenTrue_EnforceInMethodBody_InTryFinally() { var source = @" using System.Diagnostics.CodeAnalysis; class C { static bool M(bool b, [MaybeNullWhen(true)] out string s) { s = string.Empty; try { if (b) return false; // 1 } finally { s = null; } return true; } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8762: Parameter 's' must have a non-null value when exiting with 'false'. // return false; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return false;").WithArguments("s", "false").WithLocation(11, 15) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody_InTryFinally_Reversed() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(true)] out string? s) { try { bool b = true; if (b) { s = null; return true; } throw null!; } finally { s = """"; } } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenFalse_EnforceInMethodBody_InTryFinally() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(false)] out string? s) { try { bool b = true; if (b) { s = """"; return false; } throw null!; } finally { s = null; } } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (13,17): warning CS8762: Parameter 's' must have a non-null value when exiting with 'false'. // return false; Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return false;").WithArguments("s", "false").WithLocation(13, 17) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody_Warn_NonConstantReturn() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(true)] out string? s) { s = null; return NonConstantBool(); } static bool NonConstantBool() => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922"), WorkItem(44080, "https://github.com/dotnet/roslyn/issues/44080")] public void NotNullWhenFalse_EnforceInMethodBody_Warn_NonConstantReturn() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(false)] out string? s) { s = null; return NonConstantBool(); } static bool NonConstantBool() => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922"), WorkItem(42386, "https://github.com/dotnet/roslyn/issues/42386")] public void NotNull_EnforceInMethodBody_Warn() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNull] out string? s) { s = null; return NonConstantBool(); // 1 } public static bool M([NotNull] string? s) { s = null; return NonConstantBool(); // 2 } public static bool M([NotNull] ref string? s) { s = null; return NonConstantBool(); // 3 } static bool NonConstantBool() => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (8,9): warning CS8777: Parameter 's' must have a non-null value when exiting. // return NonConstantBool(); // 1 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return NonConstantBool();").WithArguments("s").WithLocation(8, 9), // (13,9): warning CS8777: Parameter 's' must have a non-null value when exiting. // return NonConstantBool(); // 2 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return NonConstantBool();").WithArguments("s").WithLocation(13, 9), // (18,9): warning CS8777: Parameter 's' must have a non-null value when exiting. // return NonConstantBool(); // 3 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return NonConstantBool();").WithArguments("s").WithLocation(18, 9) ); } [Fact, WorkItem(42386, "https://github.com/dotnet/roslyn/issues/42386")] public void NotNull_EnforceInMethodBody_Warn_TransientAssignmentOkay() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNull] out string? s) { s = null; s = string.Empty; return NonConstantBool(); } static bool NonConstantBool() => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(42386, "https://github.com/dotnet/roslyn/issues/42386")] public void NotNull_EnforceInMethodBody_Warn_TryCatch() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNull] out string? s) { bool b = true; try { if (b) return true; // 1 else return false; // 2 } finally { s = null; } } // 3 } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (12,17): warning CS8777: Parameter 's' must have a non-null value when exiting. // return true; // 1 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return true;").WithArguments("s").WithLocation(12, 17), // (14,17): warning CS8777: Parameter 's' must have a non-null value when exiting. // return false; // 2 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return false;").WithArguments("s").WithLocation(14, 17), // (20,5): warning CS8777: Parameter 's' must have a non-null value when exiting. // } // 3 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("s").WithLocation(20, 5) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void MaybeNullWhenTrue_EnforceInMethodBody() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([MaybeNullWhen(true)] out string s) { bool b = true; if (b) { s = null; return false; // 1 } else { s = """"; return true; } } public static bool TryGetValue2([MaybeNullWhen(true)] out string s) { bool b = true; if (b) { s = """"; return false; } else { s = null; return true; } } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,13): warning CS8762: Parameter 's' must have a non-null value when exiting with 'false'. // return false; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return false;").WithArguments("s", "false").WithLocation(11, 13) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody_OnConversionToBool() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static implicit operator bool(C? c) => throw null!; public static bool TryGetValue(C? c, [NotNullWhen(true)] out string? s) { s = null; return c; } public static bool TryGetValue2(C c, [NotNullWhen(false)] out string? s) { s = null; return c; } static bool TryGetValue3([MaybeNullWhen(false)]out string s) { s = null; return (bool)true; // 1 } static bool TryGetValue4([MaybeNullWhen(false)]out string s) { s = null; return (bool)false; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (22,9): warning CS8762: Parameter 's' must have a non-null value when exiting with 'true'. // return (bool)true; Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return (bool)true;").WithArguments("s", "true").WithLocation(22, 9) ); } [Fact] public void MaybeNullWhenTrue_OutParameter() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { string s; _ = M(out s) // 1 ? s.ToString() // 2 : s.ToString(); } public static bool M([MaybeNullWhen(true)] out string s) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // _ = M(out s) // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(8, 19), // (9,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 15) ); } [Fact, WorkItem(42735, "https://github.com/dotnet/roslyn/issues/42735")] public void MaybeNullWhenTrue_OutParameter_UnconstrainedT() { var c = CreateNullableCompilation(new[] { @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { public static T M<T>() { GetT<T>(out var t); return t; // 1 } public static T M2<T>() { GetT<T>(out T t); return t; // 2 } public static bool GetT<T>([MaybeNullWhen(true)] out T t) => throw null!; } ", MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (9,16): warning CS8603: Possible null reference return. // return t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(9, 16), // (14,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // GetT<T>(out T t); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T t").WithLocation(14, 21), // (15,16): warning CS8603: Possible null reference return. // return t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(15, 16) ); } [Fact, WorkItem(42735, "https://github.com/dotnet/roslyn/issues/42735")] public void MaybeNullWhenFalse_OutParameter_UnconstrainedT() { var c = CreateNullableCompilation(new[] { @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { public static T M<T>() { GetT<T>(out var t); return t; // 1 } public static T M2<T>() { GetT<T>(out T t); return t; // 2 } public static bool GetT<T>([MaybeNullWhen(false)] out T t) => throw null!; } ", MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (9,16): warning CS8603: Possible null reference return. // return t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(9, 16), // (14,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // GetT<T>(out T t); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T t").WithLocation(14, 21), // (15,16): warning CS8603: Possible null reference return. // return t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(15, 16) ); } [Fact, WorkItem(42735, "https://github.com/dotnet/roslyn/issues/42735")] public void MaybeNull_OutParameter_UnconstrainedT() { var c = CreateNullableCompilation(new[] { @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { public static T M<T>() { GetT<T>(out var t); return t; // 1 } public static T M2<T>() { GetT<T>(out T t); return t; // 2 } public static bool GetT<T>([MaybeNull] out T t) => throw null!; } ", MaybeNullAttributeDefinition }, parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (9,16): warning CS8603: Possible null reference return. // return t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(9, 16), // (15,16): warning CS8603: Possible null reference return. // return t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(15, 16) ); c = CreateNullableCompilation(new[] { @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { public static T? M<T>() { GetT<T>(out var t); return t; } public static T? M2<T>() { GetT<T>(out T? t); return t; } public static bool GetT<T>([MaybeNull] out T t) => throw null!; } ", MaybeNullAttributeDefinition }); c.VerifyDiagnostics(); } [Fact] public void MaybeNull_OutParameter_InConditional() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { string s; _ = M(out s) // 1 ? s.ToString() // 2 : s.ToString(); // 3 } public static bool M([MaybeNull] out string s) => throw null!; } ", MaybeNullAttributeDefinition }, options: WithNullableEnable()); // Warn on misused nullability attributes (M)? https://github.com/dotnet/roslyn/issues/36073 c.VerifyDiagnostics( // (8,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // _ = M(out s) // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(8, 19), // (9,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 15), // (10,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 15) ); } [Fact] public void AllowNull_Parameter_OnPartial() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; partial class C { partial void M1([AllowNull] string s); partial void M1([AllowNull] string s) => throw null!; partial void M2([AllowNull] string s); partial void M2(string s) => throw null!; partial void M3(string s); partial void M3([AllowNull] string s) => throw null!; } ", AllowNullAttributeDefinition }); c.VerifyDiagnostics( // (5,22): error CS0579: Duplicate 'AllowNull' attribute // partial void M1([AllowNull] string s); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "AllowNull").WithArguments("AllowNull").WithLocation(5, 22) ); } [Fact] public void AllowNull_OnInterface() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; interface I { void M1([AllowNull] string s); [return: NotNull] string? M2(); } public class Implicit : I { public void M1(string s) => throw null!; // 1 public string? M2() => throw null!; // 2 } public class Explicit : I { void I.M1(string s) => throw null!; // 3 string? I.M2() => throw null!; // 4 } ", AllowNullAttributeDefinition, NotNullAttributeDefinition }); c.VerifyDiagnostics( // (10,17): warning CS8767: Nullability of reference types in type of parameter 's' of 'void Implicit.M1(string s)' doesn't match implicitly implemented member 'void I.M1(string s)' because of nullability attributes. // public void M1(string s) => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M1").WithArguments("s", "void Implicit.M1(string s)", "void I.M1(string s)").WithLocation(10, 17), // (11,20): warning CS8766: Nullability of reference types in return type of 'string? Implicit.M2()' doesn't match implicitly implemented member 'string? I.M2()' because of nullability attributes. // public string? M2() => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M2").WithArguments("string? Implicit.M2()", "string? I.M2()").WithLocation(11, 20), // (15,12): warning CS8769: Nullability of reference types in type of parameter 's' doesn't match implemented member 'void I.M1(string s)' because of nullability attributes. // void I.M1(string s) => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "M1").WithArguments("s", "void I.M1(string s)").WithLocation(15, 12), // (16,15): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'string? I.M2()' because of nullability attributes. // string? I.M2() => throw null!; // 4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M2").WithArguments("string? I.M2()").WithLocation(16, 15) ); } [Fact] public void MaybeNull_RefParameter_InConditional() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { string s = """"; _ = M(ref s) // 1 ? s.ToString() // 2 : s.ToString(); // 3 } public static bool M([MaybeNull] ref string s) => throw null!; } ", MaybeNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // _ = M(ref s) // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(8, 19), // (9,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 15), // (10,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 15) ); } [Fact] public void MaybeNullWhenTrue_RefParameter() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { string s = """"; _ = M(ref s) // 1 ? s.ToString() // 2 : s.ToString(); } public static bool M([MaybeNullWhen(true)] ref string s) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // _ = M(ref s) // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(8, 19), // (9,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 15) ); } [Fact] public void MaybeNullWhenTrue_OnImplicitConversion() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class A { public static implicit operator C(A a) => throw null!; } public class C { public void Main() { A a = new A(); _ = IsNull(a) ? a.ToString() // 1 : a.ToString(); } public static bool IsNull([MaybeNullWhen(true)] C c) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); // This warning is correct because we should be able to infer that `a` may be null when `(C)a` may be null c.VerifyDiagnostics( // (13,15): warning CS8602: Dereference of a possibly null reference. // ? a.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(13, 15) ); } [Fact] public void MaybeNullWhenTrue_OnImplicitConversion_ToNullable() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class A { public static implicit operator C?(A a) => throw null!; } public class C { public void Main() { A a = new A(); _ = IsNull(a) // 1 ? a.ToString() : a.ToString(); } public static bool IsNull([MaybeNullWhen(true)] C c) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); // Unexpected second warning // We should not blindly strip conversions when learning that a value is null. // In this case, we shouldn't infer that `a` may be null from the fact that `(C)a` may be null in the when-true branch. // Tracked by https://github.com/dotnet/roslyn/issues/36164 c.VerifyDiagnostics( // (12,20): warning CS8604: Possible null reference argument for parameter 'c' in 'bool C.IsNull(C c)'. // _ = IsNull(a) // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("c", "bool C.IsNull(C c)").WithLocation(12, 20), // (13,15): warning CS8602: Dereference of a possibly null reference. // ? a.ToString() Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(13, 15) ); } [Fact] public void MaybeNullWhenTrue_OnExplicitConversion() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class A { public static explicit operator C(A a) => throw null!; } public class C { public void Main() { A a = new A(); _ = IsNull((C)a) ? a.ToString() // 1 : a.ToString(); } public static bool IsNull([MaybeNullWhen(true)] C c) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,15): warning CS8602: Dereference of a possibly null reference. // ? a.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(13, 15) ); } [Fact] public void MaybeNull_OnExplicitConversion() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class A { public static explicit operator C(A? a) => throw null!; } public class C { public void Main() { A a = new A(); _ = IsNull((C)a) ? a.ToString() : a.ToString(); } public static bool IsNull([MaybeNull] C c) => throw null!; } ", MaybeNullAttributeDefinition }, options: WithNullableEnable()); // Both diagnostics are unexpected // We should not blindly strip conversions when learning that a value is null. // In this case, we shouldn't infer that `a` may be null from the fact that `(C)a` may be null. // Tracked by https://github.com/dotnet/roslyn/issues/36164 c.VerifyDiagnostics( // (13,15): warning CS8602: Dereference of a possibly null reference. // ? a.ToString() Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(13, 15), // (14,15): warning CS8602: Dereference of a possibly null reference. // : a.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(14, 15) ); } [Fact] public void MaybeNull_Property() { // Warn on redundant nullability attributes (P3, P5)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [MaybeNull]public TOpen P1 { get; set; } = default!; } public class CClass<TClass> where TClass : class { [MaybeNull]public TClass P2 { get; set; } = null!; [MaybeNull]public TClass? P3 { get; set; } = null; } public class CStruct<TStruct> where TStruct : struct { [MaybeNull]public TStruct P4 { get; set; } [MaybeNull]public TStruct? P5 { get; set; } }"; var lib = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, lib_cs }); lib.VerifyDiagnostics(); var source = @" class C { static void M1<T>(T t1) { new COpen<T>().P1 = t1; new COpen<T>().P1.ToString(); // 0, 1 var xOpen = new COpen<T>(); xOpen.P1 = t1; xOpen.P1.ToString(); // 2, 3 var xOpen2 = new COpen<T>(); if (xOpen2.P1 is object) // 4 { xOpen2.P1.ToString(); } } static void M2<T>(T t2) where T : class { new COpen<T>().P1.ToString(); // 5 new CClass<T>().P2.ToString(); // 6 new CClass<T>().P3.ToString(); // 7 } static void M4<T>(T t4) where T : struct { new COpen<T>().P1.ToString(); new CStruct<T>().P4.ToString(); new COpen<T?>().P1.Value.ToString(); // 8 new CStruct<T>().P5.Value.ToString(); // 9 } }"; var expected = new[] { // (7,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>().P1.ToString(); // 0, 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>().P1").WithLocation(7, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // xOpen.P1.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xOpen.P1").WithLocation(11, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>().P1.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>().P1").WithLocation(21, 9), // (22,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>().P2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>().P2").WithLocation(22, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>().P3.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>().P3").WithLocation(23, 9), // (29,9): warning CS8629: Nullable value type may be null. // new COpen<T?>().P1.Value.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new COpen<T?>().P1").WithLocation(29, 9), // (30,9): warning CS8629: Nullable value type may be null. // new CStruct<T>().P5.Value.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new CStruct<T>().P5").WithLocation(30, 9) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, MaybeNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var copenAttributes = copen.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(copenAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableContextAttribute(1)", "System.Runtime.CompilerServices.NullableAttribute(0)" }, copenAttributes); } var property = copen.GetMembers().OfType<PropertySymbol>().Single(); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" }, propertyAttributes); } else { AssertEx.Empty(propertyAttributes); } var getter = property.GetMethod; var getterAttributes = getter.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(getterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, getterAttributes); } var getterReturnAttributes = getter.GetReturnTypeAttributes().Select(a => a.ToString()); Assert.Equal(FlowAnalysisAnnotations.MaybeNull, getter.ReturnTypeFlowAnalysisAnnotations); if (isSource) { AssertEx.Empty(getterReturnAttributes); } else { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" }, getterReturnAttributes); } var setter = property.SetMethod; var setterAttributes = setter.GetAttributes(); if (isSource) { AssertEx.Empty(setterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, setterAttributes.Select(a => a.ToString())); } Assert.Equal(FlowAnalysisAnnotations.None, setter.ReturnTypeFlowAnalysisAnnotations); var setterReturnAttributes = setter.GetReturnTypeAttributes(); AssertEx.Empty(setterReturnAttributes); } } [Fact] public void MaybeNull_Property_InCompoundAssignment() { var source = @" using System.Diagnostics.CodeAnalysis; class C { [MaybeNull] C Property { get; set; } = null!; public static C operator+(C one, C other) => throw null!; void M(C c) { Property += c; // 1 } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,9): warning CS8604: Possible null reference argument for parameter 'one' in 'C C.operator +(C one, C other)'. // Property += c; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "Property").WithArguments("one", "C C.operator +(C one, C other)").WithLocation(10, 9) ); } [Fact, WorkItem(36073, "https://github.com/dotnet/roslyn/issues/36073")] public void MaybeNull_Property_WithNotNull() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [MaybeNull, NotNull]public TOpen P1 { get; set; } = default!; }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, NotNullAttributeDefinition, source }); comp.VerifyDiagnostics(); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var copenAttributes = copen.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(copenAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableContextAttribute(1)", "System.Runtime.CompilerServices.NullableAttribute(0)" }, copenAttributes); } var property = copen.GetMembers().OfType<PropertySymbol>().Single(); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.MaybeNullAttribute", "System.Diagnostics.CodeAnalysis.NotNullAttribute" }, propertyAttributes); } else { AssertEx.Empty(propertyAttributes); } var getter = property.GetMethod; var getterAttributes = getter.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(getterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, getterAttributes); } var getterReturnAttributes = getter.GetReturnTypeAttributes().Select(a => a.ToString()); Assert.Equal(FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull, getter.ReturnTypeFlowAnalysisAnnotations); if (isSource) { AssertEx.Empty(getterReturnAttributes); } else { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.MaybeNullAttribute", "System.Diagnostics.CodeAnalysis.NotNullAttribute" }, getterReturnAttributes); } } } [Fact] public void MaybeNull_Property_WithExpressionBody() { // Warn on misused nullability attributes (P3, P5)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [MaybeNull]public TOpen P1 => throw null!; } public class CClass<TClass> where TClass : class { [MaybeNull]public TClass P2 => throw null!; [MaybeNull]public TClass? P3 => throw null!; } public class CStruct<TStruct> where TStruct : struct { [MaybeNull]public TStruct P4 => throw null!; [MaybeNull]public TStruct? P5 => throw null!; }"; var lib = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, lib_cs }); lib.VerifyDiagnostics(); var source = @" class C { static void M1<T>(T t1) { new COpen<T>().P1.ToString(); // 0, 1 } static void M2<T>(T t2) where T : class { new COpen<T>().P1.ToString(); // 2 new CClass<T>().P2.ToString(); // 3 new CClass<T>().P3.ToString(); // 4 } static void M4<T>(T t4) where T : struct { new COpen<T>().P1.ToString(); new CStruct<T>().P4.ToString(); new COpen<T?>().P1.Value.ToString(); // 5 new CStruct<T>().P5.Value.ToString(); // 6 } }"; var expected = new[] { // (6,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>().P1.ToString(); // 0, 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>().P1").WithLocation(6, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>().P1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>().P1").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>().P2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>().P2").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>().P3.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>().P3").WithLocation(12, 9), // (18,9): warning CS8629: Nullable value type may be null. // new COpen<T?>().P1.Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new COpen<T?>().P1").WithLocation(18, 9), // (19,9): warning CS8629: Nullable value type may be null. // new CStruct<T>().P5.Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new CStruct<T>().P5").WithLocation(19, 9) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, MaybeNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void MaybeNull_Property_OnVirtualProperty() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [MaybeNull] public virtual string P => throw null!; public virtual string P2 => throw null!; } public class C : Base { public override string P => throw null!; [MaybeNull] public override string P2 => throw null!; // 0 static void M(C c, Base b) { b.P.ToString(); // 1 c.P.ToString(); b.P2.ToString(); c.P2.ToString(); // 2 } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,46): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [MaybeNull] public override string P2 => throw null!; // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "throw null!").WithLocation(11, 46), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.P").WithLocation(15, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // c.P2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P2").WithLocation(19, 9) ); } [Fact] public void MaybeNull_Property_OnVirtualProperty_OnlyOverridingSetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [MaybeNull] public virtual string P { get { throw null!; } set { throw null!; } } public virtual string P2 { get { throw null!; } set { throw null!; } } } public class C : Base { public override string P { set { throw null!; } } [MaybeNull] public override string P2 { set { throw null!; } } static void M(C c, Base b) { b.P.ToString(); // 1 c.P.ToString(); // 2 b.P2.ToString(); c.P2.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // b.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.P").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(16, 9) ); } [Fact] public void MaybeNull_Property_OnVirtualProperty_OnlyOverridingGetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [MaybeNull] public virtual string P { get { throw null!; } set { throw null!; } } public virtual string P2 { get { throw null!; } set { throw null!; } } } public class C : Base { public override string P { get { throw null!; } } [MaybeNull] public override string P2 { get { throw null!; } } // 0 static void M(C c, Base b) { b.P.ToString(); // 1 c.P.ToString(); b.P2.ToString(); c.P2.ToString(); // 2 } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,45): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [MaybeNull] public override string P2 { get { throw null!; } } // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(11, 45), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.P").WithLocation(15, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // c.P2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P2").WithLocation(19, 9) ); } [Fact] public void MaybeNull_Property_InDeconstructionAssignment_UnconstrainedGeneric() { var source = @"using System.Diagnostics.CodeAnalysis; public class C<T> { [MaybeNull] public T P { get; set; } = default!; void M(C<T> c, T t) { (c.P, _) = (t, 1); c.P.ToString(); // 1, 2 (c.P, _) = c; c.P.ToString(); // 3, 4 } void Deconstruct(out T x, out T y) => throw null!; }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(9, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(12, 9) ); } [Fact] public void MaybeNull_Indexer() { // Warn on redundant nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [MaybeNull]public TOpen this[int i] { get => throw null!; } } public class CClass<TClass> where TClass : class { [MaybeNull]public TClass this[int i] { get => throw null!; } } public class CClass2<TClass> where TClass : class { [MaybeNull]public TClass? this[int i] { get => throw null!; } } public class CStruct<TStruct> where TStruct : struct { [MaybeNull]public TStruct this[int i] { get => throw null!; } } public class CStruct2<TStruct> where TStruct : struct { [MaybeNull]public TStruct? this[int i] { get => throw null!; } }"; var lib = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, lib_cs }); var source = @" class C { static void M1<T>(T t1) { new COpen<T>()[0].ToString(); // 1 } static void M2<T>(T t2) where T : class { new COpen<T>()[0].ToString(); // 2 new CClass<T>()[0].ToString(); // 3 new CClass2<T>()[0].ToString(); // 4 } static void M4<T>(T t4) where T : struct { new COpen<T>()[0].ToString(); new CStruct<T>()[0].ToString(); new COpen<T?>()[0].Value.ToString(); // 5 new CStruct2<T>()[0].Value.ToString(); // 6 } }"; var expected = new[] { // (6,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>()[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>()[0]").WithLocation(6, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>()[0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>()[0]").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>()[0].ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>()[0]").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // new CClass2<T>()[0].ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass2<T>()[0]").WithLocation(12, 9), // (18,9): warning CS8629: Nullable value type may be null. // new COpen<T?>()[0].Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new COpen<T?>()[0]").WithLocation(18, 9), // (19,9): warning CS8629: Nullable value type may be null. // new CStruct2<T>()[0].Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new CStruct2<T>()[0]").WithLocation(19, 9) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, MaybeNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void MaybeNull_Indexer_OnVirtualIndexer_OnlyOverridingSetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [MaybeNull] public virtual string this[int i] { get { throw null!; } set { throw null!; } } public virtual string this[byte i] { get { throw null!; } set { throw null!; } } } public class C : Base { public override string this[int i] { set { throw null!; } } [MaybeNull] public override string this[byte i] { set { throw null!; } } static void M(C c, Base b) { b[(int)0].ToString(); // 1 c[(int)0].ToString(); // 2 b[(byte)0].ToString(); c[(byte)0].ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // b[(int)0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[(int)0]").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // c[(int)0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[(int)0]").WithLocation(16, 9) ); } [Fact] public void MaybeNull_Indexer_OnVirtualIndexer_OnlyOverridingGetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [MaybeNull] public virtual string this[int i] { get { throw null!; } set { throw null!; } } public virtual string this[byte i] { get { throw null!; } set { throw null!; } } } public class C : Base { public override string this[int i] { get { throw null!; } } [MaybeNull] public override string this[byte i] { get { throw null!; } } // 0 static void M(C c, Base b) { b[(int)0].ToString(); // 1 c[(int)0].ToString(); b[(byte)0].ToString(); c[(byte)0].ToString(); // 2 } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,55): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [MaybeNull] public override string this[byte i] { get { throw null!; } } // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(11, 55), // (15,9): warning CS8602: Dereference of a possibly null reference. // b[(int)0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[(int)0]").WithLocation(15, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // c[(byte)0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[(byte)0]").WithLocation(19, 9) ); } [Fact] public void MaybeNull_Indexer_Implementation() { var source = @"using System.Diagnostics.CodeAnalysis; public class CClass<TClass> where TClass : class { [MaybeNull]public TClass this[int i] { get => null; } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNull_Field() { // Warn on misused nullability attributes (f2, f3, f4, f5)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [MaybeNull]public TOpen f1 = default!; } public class CClass<TClass> where TClass : class { [MaybeNull]public TClass f2 = null!; [MaybeNull]public TClass? f3 = null; } public class CStruct<TStruct> where TStruct : struct { [MaybeNull]public TStruct f4; [MaybeNull]public TStruct? f5; } "; var lib = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, lib_cs }); var source = @" using System.Diagnostics.CodeAnalysis; class C { static void M1<T>([MaybeNull]T t1) { new COpen<T>().f1 = t1; new COpen<T>().f1.ToString(); // 0, 1 var xOpen = new COpen<T>(); xOpen.f1 = t1; xOpen.f1.ToString(); // 2, 3 var xOpen2 = new COpen<T>(); xOpen2.f1.ToString(); // 4, 5 xOpen2.f1.ToString(); var xOpen3 = new COpen<T>(); if (xOpen3.f1 is object) // 6 { xOpen3.f1.ToString(); } } static void M2<T>() where T : class { new COpen<T>().f1.ToString(); // 7 new CClass<T>().f2.ToString(); // 8 new CClass<T>().f3.ToString(); // 9 } static void M4<T>(T t4) where T : struct { new COpen<T>().f1.ToString(); new CStruct<T>().f4.ToString(); new CStruct<T>().f5.Value.ToString(); // 10 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>().f1.ToString(); // 0, 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>().f1").WithLocation(8, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // xOpen.f1.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xOpen.f1").WithLocation(12, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // xOpen2.f1.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xOpen2.f1").WithLocation(15, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>().f1.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>().f1").WithLocation(26, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>().f2.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>().f2").WithLocation(27, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>().f3.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>().f3").WithLocation(28, 9), // (34,9): warning CS8629: Nullable value type may be null. // new CStruct<T>().f5.Value.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new CStruct<T>().f5").WithLocation(34, 9) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, MaybeNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var field = copen.GetMembers().OfType<FieldSymbol>().Single(); var fieldAttributes = field.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" }, fieldAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableAttribute(1)", "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" }, fieldAttributes); } } } [Fact] public void MaybeNull_Field_WithAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [MaybeNull] string f1 = """"; void M() { f1.ToString(); // 1 f1 = """"; f1.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // f1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "f1").WithLocation(7, 9) ); } [Fact] public void MaybeNull_Field_WithAssignment_NullableInt() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [MaybeNull] int? f1 = 1; void M() { f1.Value.ToString(); // 1 f1 = 2; f1.Value.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (7,9): warning CS8629: Nullable value type may be null. // f1.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "f1").WithLocation(7, 9) ); } [Fact] public void MaybeNull_Field_WithContainerAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [MaybeNull] public string f1 = """"; void M(C c) { c.f1.ToString(); // 1 c.f1 = """"; c = new C(); c.f1.ToString(); // 2 } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // c.f1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.f1").WithLocation(7, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // c.f1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.f1").WithLocation(11, 9) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/37217"), WorkItem(36830, "https://github.com/dotnet/roslyn/issues/36830")] public void MaybeNull_Field_InDebugAssert() { var source = @"using System.Diagnostics.CodeAnalysis; class C { [MaybeNull] string? f1 = """"; void M() { System.Diagnostics.Debug.Assert(f1 != null); f1.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNull_Field_WithContainerAssignment_NullableInt() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [MaybeNull] public int? f1 = 1; void M(C c) { c.f1.Value.ToString(); // 1 c.f1 = 2; c = new C(); c.f1.Value.ToString(); // 2 } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (7,9): warning CS8629: Nullable value type may be null. // c.f1.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.f1").WithLocation(7, 9), // (11,9): warning CS8629: Nullable value type may be null. // c.f1.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.f1").WithLocation(11, 9) ); } [Fact] public void MaybeNullWhenTrue_OnImplicitReferenceConversion() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class A : Base { } public class Base { public void Main() { A a = new A(); _ = IsNull(a) ? a.ToString() // 1 : a.ToString(); } public static bool IsNull([MaybeNullWhen(true)] Base b) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // ? a.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(12, 15) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void MaybeNullWhenTrue_EqualsTrue() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (IsNull(s) == true) { s.ToString(); // warn } else { s.ToString(); // ok } s.ToString(); // ok } public static bool IsNull([MaybeNullWhen(true)] string s) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void IsNullEqualsTrue() { var c = CreateNullableCompilation(@" class C { void M(string s) { if ((s is null) == true) s.ToString(); // 1 else s.ToString(); } void M2(string s) { if (true == (s is null)) s.ToString(); // 2 else s.ToString(); } } "); c.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 13) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void IsNullEqualsTrueEqualsFalse() { var c = CreateNullableCompilation(@" class C { void M(string s) { if (((s is null) == true) == false) s.ToString(); else s.ToString(); // 1 } void M2(string s) { if (false == (true == (s is null))) s.ToString(); else s.ToString(); // 2 } } "); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 13) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void IsNullEqualsFalse() { var c = CreateNullableCompilation(@" class C { void M(string s) { if ((s is null) == false) s.ToString(); else s.ToString(); // 1 } void M2(string s) { if (false == (s is null)) s.ToString(); else s.ToString(); // 2 } } "); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 13) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void IsNullNotEqualsTrue() { var c = CreateNullableCompilation(@" class C { void M(string s) { if ((s is null) != true) s.ToString(); else s.ToString(); // 1 } void M2(string s) { if (true != (s is null)) s.ToString(); else s.ToString(); // 2 } } "); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 13) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void IsNullNotEqualsFalse() { var c = CreateNullableCompilation(@" class C { void M(string s) { if ((s is null) != false) s.ToString(); // 1 else s.ToString(); } void M2(string s) { if (false != (s is null)) s.ToString(); // 2 else s.ToString(); } } "); c.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 13) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void OnlySwapConditionalStatesWhenInConditionalState() { var c = CreateNullableCompilation(@" class C { void M(bool b) { if (b == (true != b)) { } } } "); c.VerifyDiagnostics(); } [Fact, WorkItem(41107, "https://github.com/dotnet/roslyn/issues/41107")] public void NullConditionalEqualsTrue() { var c = CreateNullableCompilation(new[] { @" public class C { public C? field; public bool value; static public void M(C c) { if (c.field?.value == true) { c.field.ToString(); } else { c.field.ToString(); // 1 } } static public void M2(C c) { if (false == c.field?.value) { c.field.ToString(); } else { c.field.ToString(); // 2 } } } ", NotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (15,13): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(15, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(27, 13) ); } [Fact, WorkItem(41107, "https://github.com/dotnet/roslyn/issues/41107")] public void EqualsComplicatedTrue() { var c = CreateNullableCompilation(new[] { @" public class C { public C? field; public bool value; static C? MaybeNull() => throw null!; static public void M(C c) { if ((c.field is null) == (true || MaybeNull()?.value == true)) { c.field.ToString(); // 1 } else { c.field.ToString(); // 2 } } static public void M2(C c) { if ((false && MaybeNull()?.value == true) == (c.field is null)) { c.field.ToString(); // 3 } else { c.field.ToString(); // 4 } } } ", NotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(13, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(17, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(25, 13), // (29,13): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(29, 13) ); } [Fact, WorkItem(41107, "https://github.com/dotnet/roslyn/issues/41107")] public void NullConditionalWithExtensionMethodEqualsTrue() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public C? field; static public void M(C c) { if (c.field?.field.IsKind() == true) { c.field.field.ToString(); } } static public void M2(C c) { if (true == c.field?.field.IsKind()) { c.field.field.ToString(); } } static public void M3(C c) { if (Extension.IsKind(c.field?.field) == true) { c.field.field.ToString(); } } } public static class Extension { public static bool IsKind([NotNullWhen(true)] this C? c) { throw null!; } } ", NotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact] public void MaybeNullWhenTrue_MaybeNullInitialState() { // Warn on redundant nullability attributes (warn on IsNull)? https://github.com/dotnet/roslyn/issues/36073 var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (IsNull(s)) { s.ToString(); // 1 } else { s.ToString(); // 2 } } public static bool IsNull([MaybeNullWhen(true)] string? s) => throw null!; } ", MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); } [Fact] public void MaybeNullWhenTrue_MaybeNullWhenFalseOnSameParameter() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (IsNull(s)) { s.ToString(); // 1 } else { s.ToString(); // MaybeNullWhen(false) was ignored } } public static bool IsNull([MaybeNullWhen(true), MaybeNullWhen(false)] string s) => throw null!; // 2 } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (16,53): error CS0579: Duplicate 'MaybeNullWhen' attribute // public static bool IsNull([MaybeNullWhen(true), MaybeNullWhen(false)] string s) => throw null!; // 2 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "MaybeNullWhen").WithArguments("MaybeNullWhen").WithLocation(16, 53) ); } [Fact] public void MaybeNullWhenTrue_MaybeNullOnSameParameter() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (IsNull(s)) { s.ToString(); // 1 } else { s.ToString(); // 2 } } public static bool IsNull([MaybeNullWhen(true), MaybeNull] string s) => throw null!; } ", MaybeNullWhenAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); } [Fact] public void MaybeNullWhenTrue_NotNullWhenTrueOnSecondParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (M(s, s)) { s.ToString(); } else { s.ToString(); } s.ToString(); } public static bool M([MaybeNullWhen(true)] string s, [NotNullWhen(true)] string s2) => throw null!; } ", MaybeNullWhenAttributeDefinition, NotNullWhenAttributeDefinition }); // post-condition attributes are applied on arguments left-to-right c.VerifyDiagnostics(); } [Fact] public void NotNullWhenTrue_MaybeNullWhenTrueOnSecondParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (M(s, s)) { s.ToString(); // 1 } else { s.ToString(); } } public static bool M([NotNullWhen(true)] string s, [MaybeNullWhen(true)] string s2) => throw null!; } ", MaybeNullWhenAttributeDefinition, NotNullWhenAttributeDefinition }); // Warn on redundant nullability attributes (warn on first parameter of M)? https://github.com/dotnet/roslyn/issues/36073 // post-condition attributes are applied on arguments left-to-right c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullWhenFalse_MaybeNullWhenFalseOnSecondParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (M(s, s)) { s.ToString(); } else { s.ToString(); // 1 } } public static bool M([NotNullWhen(false)] string s, [MaybeNullWhen(false)] string s2) => throw null!; } ", MaybeNullWhenAttributeDefinition, NotNullWhenAttributeDefinition }); // Warn on redundant nullability attributes (warn on first parameter of M)? https://github.com/dotnet/roslyn/issues/36073 // post-condition attributes are applied on arguments left-to-right c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); } [Fact] public void MaybeNullWhenFalse_NotNullWhenFalseOnSecondParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (M(s, s)) { s.ToString(); // 1 } else { s.ToString(); } } public static bool M([MaybeNullWhen(false)] string? s, [NotNullWhen(false)] string? s2) => throw null!; } ", MaybeNullWhenAttributeDefinition, NotNullWhenAttributeDefinition }); // Warn on redundant nullability attributes (warn on first parameter of M)? https://github.com/dotnet/roslyn/issues/36073 // post-condition attributes are applied on arguments left-to-right c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullWhenTrue_RefParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { string? s = null; _ = M(ref s) ? s.ToString() : s.ToString(); // 1 } public static bool M([NotNullWhen(true)] ref string? s) => throw null!; } ", NotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 15) ); } [Fact] public void NotNullWhenFalse_OutParameter_MiscTypes() { // Warn on redundant nullability attributes (F2, F4)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool F1<T>(T t, [NotNullWhen(false)]out T t2) => throw null!; static bool F2<T>(T t, [NotNullWhen(false)]out T t2) where T : class => throw null!; static bool F3<T>(T t, [NotNullWhen(false)]out T? t2) where T : class => throw null!; static bool F4<T>(T t, [NotNullWhen(false)]out T t2) where T : struct => throw null!; static bool F5<T>(T? t, [NotNullWhen(false)]out T? t2) where T : struct => throw null!; static void M1<T>(T t1) { _ = F1(t1, out var s2) ? s2.ToString() // 1 : s2.ToString(); } static void M2<T>(T t2) where T : class { _ = F1(t2, out var s3) ? s3.ToString() : s3.ToString(); _ = F2(t2, out var s4) ? s4.ToString() : s4.ToString(); _ = F3(t2, out var s5) ? s5.ToString() // 2 : s5.ToString(); t2 = null; // 3 _ = F1(t2, out var s6) ? s6.ToString() // 4 : s6.ToString(); _ = F2(t2, out var s7) // 5 ? s7.ToString() // 6 : s7.ToString(); _ = F3(t2, out var s8) // 7 ? s8.ToString() // 8 : s8.ToString(); } static void M3<T>(T? t3) where T : class { _ = F1(t3, out var s9) ? s9.ToString() // 9 : s9.ToString(); _ = F2(t3, out var s10) // 10 ? s10.ToString() // 11 : s10.ToString(); _ = F3(t3, out var s11) // 12 ? s11.ToString() // 13 : s11.ToString(); if (t3 == null) return; _ = F1(t3, out var s12) ? s12.ToString() : s12.ToString(); _ = F2(t3, out var s13) ? s13.ToString() : s13.ToString(); _ = F3(t3, out var s14) ? s14.ToString() // 14 : s14.ToString(); } static void M4<T>(T t4) where T : struct { _ = F1(t4, out var s15) ? s15.ToString() : s15.ToString(); _ = F4(t4, out var s16) ? s16.ToString() : s16.ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1(t5, out var s17) ? s17.Value // 15 : s17.Value; _ = F5(t5, out var s18) ? s18.Value // 16 : s18.Value; if (t5 == null) return; _ = F1(t5, out var s19) ? s19.Value // 17 : s19.Value; _ = F5(t5, out var s20) ? s20.Value // 18 : s20.Value; } }"; var comp = CreateNullableCompilation(new[] { NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // ? s2.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // ? s5.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(26, 15), // (29,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(29, 14), // (31,15): warning CS8602: Dereference of a possibly null reference. // ? s6.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(31, 15), // (34,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F2(t2, out var s7) // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(34, 13), // (35,15): warning CS8602: Dereference of a possibly null reference. // ? s7.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s7").WithLocation(35, 15), // (38,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F3(t2, out var s8) // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(38, 13), // (39,15): warning CS8602: Dereference of a possibly null reference. // ? s8.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s8").WithLocation(39, 15), // (45,15): warning CS8602: Dereference of a possibly null reference. // ? s9.ToString() // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s9").WithLocation(45, 15), // (48,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F2(t3, out var s10) // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(48, 13), // (49,15): warning CS8602: Dereference of a possibly null reference. // ? s10.ToString() // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s10").WithLocation(49, 15), // (52,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F3(t3, out var s11) // 12 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(52, 13), // (53,15): warning CS8602: Dereference of a possibly null reference. // ? s11.ToString() // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s11").WithLocation(53, 15), // (66,15): warning CS8602: Dereference of a possibly null reference. // ? s14.ToString() // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s14").WithLocation(66, 15), // (82,15): warning CS8629: Nullable value type may be null. // ? s17.Value // 15 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s17").WithLocation(82, 15), // (86,15): warning CS8629: Nullable value type may be null. // ? s18.Value // 16 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s18").WithLocation(86, 15), // (91,15): warning CS8629: Nullable value type may be null. // ? s19.Value // 17 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s19").WithLocation(91, 15), // (95,15): warning CS8629: Nullable value type may be null. // ? s20.Value // 18 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s20").WithLocation(95, 15) ); } [Fact] public void NotNullWhenFalse_OutParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { string? s; _ = M(out s) ? s.ToString() // 1 : s.ToString(); } public static bool M([NotNullWhen(false)] out string? s) => throw null!; } ", NotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 15) ); } [Fact] [WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void NotNullWhenFalse_EqualsTrue() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (MyIsNullOrEmpty(s) == true) { s.ToString(); // warn } else { s.ToString(); // ok } s.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullWhenFalse_Nested() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (MyIsNullOrEmpty(s?.ToString())) { s.ToString(); // warn } else { s.ToString(); } } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact, WorkItem(32335, "https://github.com/dotnet/roslyn/issues/32335")] public void NotNullWhenTrue_LearnFromNonNullTest() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void M(C? c1) { if (MyIsNullOrEmpty(c1?.Method())) c1.ToString(); // 1 else c1.ToString(); } C? Method() => throw null!; static bool MyIsNullOrEmpty([NotNullWhen(false)] C? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(8, 13) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void NotNullWhenFalse_EqualsTrue_InErrorInvocation() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (Missing(MyIsNullOrEmpty(s))) { s.ToString(); // 1 } else { s.ToString(); // 2 } s.ToString(); } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,13): error CS0103: The name 'Missing' does not exist in the current context // if (Missing(MyIsNullOrEmpty(s))) Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(7, 13), // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); } [Fact] [WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void NotNullWhenFalse_EqualsFalse() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (false == MyIsNullOrEmpty(s)) { s.ToString(); // ok } else { s.ToString(); // warn } s.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); } [Fact] [WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void NotNullWhenFalse_NotEqualsFalse() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (false != MyIsNullOrEmpty(s)) { s.ToString(); // warn } else { s.ToString(); // ok } s.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullWhenFalse_RequiresBoolReturn() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static object MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); VerifyAnnotations(c, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_RequiresBoolReturn_OnGenericMethod() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s) { if (MyIsNullOrEmpty(s, true)) { s.ToString(); // warn } else { s.ToString(); // ok } } public static T MyIsNullOrEmpty<T>([NotNullWhen(false)] string? s, T t) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullIfNotNull_Return() { // NotNullIfNotNull isn't enforced in scenarios like the following var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M(string? p) => null; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1).ToString(); c.M(p2).ToString(); // 1 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2)").WithLocation(8, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact, WorkItem(49077, "https://github.com/dotnet/roslyn/issues/49077")] public void NotNullIfNotNull_Return_Async() { var source = @" using System.Threading.Tasks; using System.Diagnostics.CodeAnalysis; string notNull = """"; var res = await C.M(notNull); res.ToString(); // 1 res = await C.M(null); // 2 res.ToString(); // 3 res = await C.M2(notNull); res.ToString(); // 4 public class C { [return: NotNullIfNotNull(""s1"")] public static async Task<string?>? M(string? s1) { await Task.Yield(); if (s1 is null) return null; else return null; } [return: NotNullIfNotNull(""s1"")] public static Task<string?>? M2(string? s1) { if (s1 is null) return null; else return null; // 5 } } "; var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }, options: TestOptions.DebugExe.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (7,1): warning CS8602: Dereference of a possibly null reference. // res.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "res").WithLocation(7, 1), // (9,13): warning CS8602: Dereference of a possibly null reference. // res = await C.M(null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C.M(null)").WithLocation(9, 13), // (10,1): warning CS8602: Dereference of a possibly null reference. // res.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "res").WithLocation(10, 1), // (13,1): warning CS8602: Dereference of a possibly null reference. // res.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "res").WithLocation(13, 1), // (33,13): warning CS8825: Return value must be non-null because parameter 's1' is non-null. // return null; // 5 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;").WithArguments("s1").WithLocation(33, 13) ); } [Fact, WorkItem(49077, "https://github.com/dotnet/roslyn/issues/49077")] public void NotNullIfNotNull_Parameter_Async() { var source = @" using System.Threading.Tasks; using System.Diagnostics.CodeAnalysis; public class C { public async Task M([NotNullIfNotNull(""s2"")] string? s1, string? s2) { await Task.Yield(); if (s2 is object) { return; // 1 } } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (12,13): warning CS8824: Parameter 's1' must have a non-null value when exiting because parameter 's2' is non-null. // return; // 1 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return;").WithArguments("s1", "s2").WithLocation(12, 13) ); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Return_Checked_01() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M0(string? p) { if (p is null) { return null; } if (p is object) { return null; // 1 } if (p is object) { return M1(); // 2 } if (p is object) { return p; } p = ""a""; return M1(); // 3 } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return null; // 1 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;", isSuppressed: false).WithArguments("p").WithLocation(15, 13), // (20,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return M1(); // 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return M1();", isSuppressed: false).WithArguments("p").WithLocation(20, 13), // (29,9): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return M1(); // 3 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return M1();", isSuppressed: false).WithArguments("p").WithLocation(29, 9)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Return_Checked_02() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] [return: NotNullIfNotNull(""q"")] public string? M0(string? p, string? q, string? s) { if (p is object || q is object) { return null; } if (p is null || q is null) { return null; } if (p is object && q is object) { return null; // 1 } if (p is object && q is object) { return M1(); // 2 } if (p is object && s is object) { return M1(); // 3 } if (s is object) { return null; } if (p is null && q is null) { return null; } return M1(); } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (21,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return null; // 1 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;", isSuppressed: false).WithArguments("p").WithLocation(21, 13), // (26,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return M1(); // 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return M1();", isSuppressed: false).WithArguments("p").WithLocation(26, 13), // (31,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return M1(); // 3 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return M1();", isSuppressed: false).WithArguments("p").WithLocation(31, 13)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Return_Checked_03() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] [return: NotNullIfNotNull(""q"")] public string? M0(string? p, string? q) { if (q is null) { return null; } else if (p is null) { return null; // 1 } return M1(); // 2 } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,13): warning CS8825: Return value must be non-null because parameter 'q' is non-null. // return null; // 1 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;", isSuppressed: false).WithArguments("q").WithLocation(15, 13), // (18,9): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return M1(); // 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return M1();", isSuppressed: false).WithArguments("p").WithLocation(18, 9)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Return_Checked_04() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""t"")] public T? M0<T>(T? t) { if (t is object) { return default; // 1 } if (t is object) { return t; } if (t is null) { return default; } return t; } [return: NotNullIfNotNull(""t"")] public T M1<T>(T t) { if (t is object) { return default; // 2, 3 } if (t is object) { return t; } if (t is null) { return default; // 4 } if (t is null) { return t; // should give WRN_NullReferenceReturn: https://github.com/dotnet/roslyn/issues/47646 } return t; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,13): warning CS8825: Return value must be non-null because parameter 't' is non-null. // return default; // 1 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return default;", isSuppressed: false).WithArguments("t").WithLocation(10, 13), // (31,13): warning CS8825: Return value must be non-null because parameter 't' is non-null. // return default; // 2, 3 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return default;", isSuppressed: false).WithArguments("t").WithLocation(31, 13), // (31,20): warning CS8603: Possible null reference return. // return default; // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default", isSuppressed: false).WithLocation(31, 20), // (41,20): warning CS8603: Possible null reference return. // return default; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default", isSuppressed: false).WithLocation(41, 20)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Param_Checked_01() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public void M0(string? p, [NotNullIfNotNull(""p"")] out string? pOut) { if (p is object) { pOut = p; return; } if (p is object) { pOut = null; return; // 1 } if (p is null) { pOut = null; return; } pOut = M1(); } // 2 string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (16,13): warning CS8824: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return; // 1 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return;", isSuppressed: false).WithArguments("pOut", "p").WithLocation(16, 13), // (26,5): warning CS8824: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // } // 2 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "}", isSuppressed: false).WithArguments("pOut", "p").WithLocation(26, 5)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_ParamAndReturn_Checked_01() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M0(string? p, [NotNullIfNotNull(""p"")] out string? pOut) { if (p is object) { pOut = null; return p; // 1 } if (p is object) { pOut = p; return null; // 2 } if (p is object) { pOut = null; return null; // 3, 4 } if (p is null) { pOut = null; return null; } pOut = M1(); return pOut; // 5, 6 } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,13): warning CS8824: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return p; // 1 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return p;", isSuppressed: false).WithArguments("pOut", "p").WithLocation(11, 13), // (17,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return null; // 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;", isSuppressed: false).WithArguments("p").WithLocation(17, 13), // (23,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return null; // 3, 4 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;", isSuppressed: false).WithArguments("p").WithLocation(23, 13), // (23,13): warning CS8824: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return null; // 3, 4 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return null;", isSuppressed: false).WithArguments("pOut", "p").WithLocation(23, 13), // (33,9): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return pOut; // 5, 6 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return pOut;", isSuppressed: false).WithArguments("p").WithLocation(33, 9), // (33,9): warning CS8824: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return pOut; // 5, 6 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return pOut;", isSuppressed: false).WithArguments("pOut", "p").WithLocation(33, 9)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_NestedLambda_01() { var source = @" using System; using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M0(string? p, [NotNullIfNotNull(""p"")] string? pOut) { Func<string?> a = () => { if (p is object) { pOut = null; return p; } if (p is object) { pOut = p; return null; } if (p is object) { pOut = null; return null; } if (p is null) { pOut = null; return null; } pOut = M1(); return pOut; }; if (p is object) { return null; // 1, 2 } return p; } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (41,13): warning CS8826: Return value must be non-null because parameter 'p' is non-null. // return null; // 1, 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;").WithArguments("p").WithLocation(41, 13), // (41,13): warning CS8825: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return null; // 1, 2 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return null;").WithArguments("pOut", "p").WithLocation(41, 13)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_NestedLocalFunction_01() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M0(string? p, [NotNullIfNotNull(""p"")] string? pOut) { string? local1() { if (p is object) { pOut = null; return p; } if (p is object) { pOut = p; return null; } if (p is object) { pOut = null; return null; } if (p is null) { pOut = null; return null; } pOut = M1(); return pOut; } if (p is object) { return local1(); // 1, 2 } return p; } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (40,13): warning CS8826: Return value must be non-null because parameter 'p' is non-null. // return local1(); // 1, 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return local1();").WithArguments("p").WithLocation(40, 13), // (40,13): warning CS8825: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return local1(); // 1, 2 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return local1();").WithArguments("pOut", "p").WithLocation(40, 13)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_NestedLocalFunction_02() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public string M0() { [return: NotNullIfNotNull(""p"")] string? local1(string? p, [NotNullIfNotNull(""p"")] string? pOut) { if (p is object) { pOut = null; return p; // 1 } if (p is object) { pOut = p; return null; // 2 } if (p is object) { pOut = null; return null; // 3, 4 } if (p is null) { pOut = null; return null; } pOut = M1(); return pOut; // 5, 6 } return local1(""a"", null); } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); // NotNullIfNotNull enforcement doesn't work on parameters of local functions // https://github.com/dotnet/roslyn/issues/47896 comp.VerifyDiagnostics( // (19,17): warning CS8826: Return value must be non-null because parameter 'p' is non-null. // return null; // 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;").WithArguments("p").WithLocation(19, 17), // (25,17): warning CS8826: Return value must be non-null because parameter 'p' is non-null. // return null; // 3, 4 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;").WithArguments("p").WithLocation(25, 17), // (35,13): warning CS8826: Return value must be non-null because parameter 'p' is non-null. // return pOut; // 5, 6 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return pOut;").WithArguments("p").WithLocation(35, 13)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Constructor_01() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public C(string? p, [NotNullIfNotNull(""p"")] out string? pOut) { if (p is object) { pOut = null; return; // 1 } if (p is object) { pOut = p; return; } if (p is null) { pOut = null; return; } pOut = M1(); } // 2 string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,13): warning CS8825: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return; // 1 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return;").WithArguments("pOut", "p").WithLocation(10, 13), // (26,5): warning CS8825: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // } // 2 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "}").WithArguments("pOut", "p").WithLocation(26, 5)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Constructor_02() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public C() { } public C(string? p, [NotNullIfNotNull(""p"")] out string? pOut) : this() { if (p is object) { pOut = null; return; // 1 } if (p is object) { pOut = p; return; } if (p is null) { pOut = null; return; } pOut = M1(); } // 2 string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (12,13): warning CS8825: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return; // 1 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return;").WithArguments("pOut", "p").WithLocation(12, 13), // (28,5): warning CS8825: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // } // 2 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "}").WithArguments("pOut", "p").WithLocation(28, 5)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Constructor_03() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public C(string x, string? y) : this(x, out y) { y.ToString(); } public C(string? p, [NotNullIfNotNull(""p"")] out string? pOut) { pOut = p; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNull_Constructor() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public C([NotNull] out string? pOut) { pOut = M1(); } // 1 string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (8,5): warning CS8777: Parameter 'pOut' must have a non-null value when exiting. // } // 1 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("pOut").WithLocation(8, 5)); } [Theory, WorkItem(48996, "https://github.com/dotnet/roslyn/issues/48996")] [InlineData("")] [InlineData("where T : class?")] public void NotNullProperty_Constructor(string constraints) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<T> " + constraints + @" { [NotNull] public T Prop { get; set; } public C() { } // 1 public C(T t) { Prop = t; } // 2 public C(T t, int x) { Prop = t; Prop.ToString(); } // 3 public C([DisallowNull] T t, int x, int y) { Prop = t; } [MemberNotNull(nameof(Prop))] public void Init(T t) { Prop = t; } // 4 } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition, MemberNotNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,12): warning CS8618: Non-nullable property 'Prop' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C() { } // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("property", "Prop").WithLocation(9, 12), // (10,12): warning CS8618: Non-nullable property 'Prop' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C(T t) { Prop = t; } // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("property", "Prop").WithLocation(10, 12), // (11,38): warning CS8602: Dereference of a possibly null reference. // public C(T t, int x) { Prop = t; Prop.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Prop").WithLocation(11, 38), // (18,5): warning CS8774: Member 'Prop' must have a non-null value when exiting. // } // 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("Prop").WithLocation(18, 5)); } [Theory, WorkItem(48996, "https://github.com/dotnet/roslyn/issues/48996")] [InlineData("")] [InlineData("where T : class?")] public void NotNullField_Constructor(string constraints) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<T> " + constraints + @" { [NotNull] public T field; public C() { } // 1 public C(T t) { field = t; } // 2 public C(T t, int x) { field = t; field.ToString(); } // 3 public C([DisallowNull] T t, int x, int y) { field = t; } [MemberNotNull(nameof(field))] public void Init(T t) { field = t; } // 4 } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition, MemberNotNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,12): warning CS8618: Non-nullable field 'field' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C() { } // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field").WithLocation(9, 12), // (10,12): warning CS8618: Non-nullable field 'field' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C(T t) { field = t; } // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field").WithLocation(10, 12), // (11,39): warning CS8602: Dereference of a possibly null reference. // public C(T t, int x) { field = t; field.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field").WithLocation(11, 39), // (18,5): warning CS8774: Member 'field' must have a non-null value when exiting. // } // 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field").WithLocation(18, 5)); } [Fact, WorkItem(48996, "https://github.com/dotnet/roslyn/issues/48996")] public void DisallowNullProperty_Constructor() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; public class C1 { [DisallowNull, NotNull] public string? F1 { get; set; } public C1() { } // 1 public C1(string? F1) // 2 { this.F1 = F1; // 3 } public C1(int i) { this.F1 = ""a""; } } public class C2 { [NotNull] public string? F2 { get; set; } public C2() { } public C2(string? F2) { this.F2 = F2; } public C2(int i) { this.F2 = ""a""; } } public class C3 { [DisallowNull] public string? F3 { get; set; } public C3() { } public C3(string? F3) { this.F3 = F3; // 4 } public C3(int i) { this.F3 = ""a""; } } "; // We expect no warnings on `C2(string?)` because `C2.F`'s getter and setter are not linked. var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,12): warning CS8618: Non-nullable property 'F1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C1() { } // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C1").WithArguments("property", "F1").WithLocation(9, 12), // (10,12): warning CS8618: Non-nullable property 'F1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C1(string? F1) // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C1").WithArguments("property", "F1").WithLocation(10, 12), // (12,19): warning CS8601: Possible null reference assignment. // this.F1 = F1; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "F1").WithLocation(12, 19), // (44,19): warning CS8601: Possible null reference assignment. // this.F3 = F3; // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "F3").WithLocation(44, 19)); } [Fact, WorkItem(48996, "https://github.com/dotnet/roslyn/issues/48996")] public void DisallowNullField_Constructor() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; public class C1 { [DisallowNull, NotNull] public string? F; public C1() { } // 1 public C1(string? F) // 2 { this.F = F; // 3 } public C1(int i) { this.F = ""a""; } } public class C2 { [NotNull] public string? F; public C2() { } // 4 public C2(string? F) // 5 { this.F = F; } public C2(int i) { this.F = ""a""; } } public class C3 { [DisallowNull] public string? F; public C3() { } public C3(string? F) { this.F = F; // 6 } public C3(int i) { this.F = ""a""; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,12): warning CS8618: Non-nullable field 'F' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C1() { } // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C1").WithArguments("field", "F").WithLocation(9, 12), // (10,12): warning CS8618: Non-nullable field 'F' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C1(string? F) // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C1").WithArguments("field", "F").WithLocation(10, 12), // (12,18): warning CS8601: Possible null reference assignment. // this.F = F; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "F").WithLocation(12, 18), // (25,12): warning CS8618: Non-nullable field 'F' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C2() { } // 4 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C2").WithArguments("field", "F").WithLocation(25, 12), // (26,12): warning CS8618: Non-nullable field 'F' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C2(string? F) // 5 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C2").WithArguments("field", "F").WithLocation(26, 12), // (44,18): warning CS8601: Possible null reference assignment. // this.F = F; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "F").WithLocation(44, 18)); } [Fact, WorkItem(49964, "https://github.com/dotnet/roslyn/issues/49964")] public void AdjustPropertyState_MaybeDefaultInput_MaybeNullOutput() { var source = @" using System.Diagnostics.CodeAnalysis; public class C<T> { [AllowNull] T Prop { get; set; } public C() { } public C(int unused) { M1(Prop); // 1 } public void M() { Prop = default; M1(Prop); // 2 Prop.ToString(); } public void M1(T t) { } } "; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); // It's not clear whether diagnostic 1 and 2 are appropriate. // Going by the principle of "if you put a good value in, you will get a good value out", // it seems like property state should be MaybeNull after assigning a MaybeDefault to the property. // https://github.com/dotnet/roslyn/issues/49964 // Note that the lack of constructor exit warning in 'C()' is expected due to presence of 'AllowNull' on the property declaration. comp.VerifyDiagnostics( // (12,12): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.M1(T t)'. // M1(Prop); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "Prop").WithArguments("t", "void C<T>.M1(T t)").WithLocation(12, 12), // (18,12): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.M1(T t)'. // M1(Prop); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "Prop").WithArguments("t", "void C<T>.M1(T t)").WithLocation(18, 12)); } [Fact, WorkItem(49964, "https://github.com/dotnet/roslyn/issues/49964")] public void AdjustPropertyState_Generic_MaybeNullInput_NotNullOutput() { var source = @" using System.Diagnostics.CodeAnalysis; public class C<T> { [NotNull] T Prop { get; set; } public C() // 1 { } public C(T t) // 2 { Prop = t; } public void M(T t) { Prop = t; Prop.ToString(); // 3 } public void M1(T t) { } } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); // It's not clear whether diagnostic 2 or 3 are appropriate. // Going by the principle of "if you put a good value in, you will get a good value out", // it seems like property state should be NotNull after assigning a MaybeNull to the property. // https://github.com/dotnet/roslyn/issues/49964 comp.VerifyDiagnostics( // (8,12): warning CS8618: Non-nullable property 'Prop' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("property", "Prop").WithLocation(8, 12), // (12,12): warning CS8618: Non-nullable property 'Prop' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C(T t) // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("property", "Prop").WithLocation(12, 12), // (19,9): warning CS8602: Dereference of a possibly null reference. // Prop.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Prop").WithLocation(19, 9)); } [Fact, WorkItem(49964, "https://github.com/dotnet/roslyn/issues/49964")] public void NotNull_MaybeNull_Property_Constructor() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [NotNull, MaybeNull] string Prop1 { get; set; } [NotNull, MaybeNull] string? Prop2 { get; set; } public C() { } public C(string prop1, string prop2) { Prop1 = prop1; Prop2 = prop2; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNullIfNotNull_Return_NullableInt() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public int? M(int? p) => throw null!; }"; var source = @" class D { static void M(C c, int? p1, int? p2) { _ = p1 ?? throw null!; c.M(p1).Value.ToString(); c.M(p2).Value.ToString(); // 1 } }"; var expected = new[] { // (8,9): warning CS8629: Nullable value type may be null. // c.M(p2).Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.M(p2)").WithLocation(8, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Return_UnconstrainedGeneric() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public T M<T>(T p) => throw null!; }"; var source = @" class D { static void M<T>(C c, T p1, T p2) { _ = p1 ?? throw null!; c.M(p1).ToString(); c.M(p2).ToString(); // 1 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2)").WithLocation(8, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Return_UnconstrainedGeneric2() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public U M<T, U>(T p, U p2) => throw null!; }"; var source = @" class D<U> { static void M<T>(C c, T p1, T p2, U u) { _ = p1 ?? throw null!; c.M(p1, u).ToString(); c.M(p2, u).ToString(); // 1 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2, u).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2, u)").WithLocation(8, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Return_MultipleParameters() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p""), NotNullIfNotNull(""p2"")] public string? M(string? p, string? p2) => throw null!; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1, p1).ToString(); c.M(p1, p2).ToString(); c.M(p2, p1).ToString(); c.M(p2, p2).ToString(); // 1 } }"; var expected = new[] { // (10,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2, p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2, p2)").WithLocation(10, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Return_DuplicateParameters() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p2""), NotNullIfNotNull(""p2"")] public string? M(string? p, string? p2) => throw null!; }"; // Warn on redundant attribute (duplicate parameter referenced)? https://github.com/dotnet/roslyn/issues/36073 var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1, p1).ToString(); c.M(p1, p2).ToString(); // 1 c.M(p2, p1).ToString(); c.M(p2, p2).ToString(); // 2 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // c.M(p1, p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p1, p2)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2, p2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2, p2)").WithLocation(10, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Return_MultipleParameters_SameName() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M(string? p, string? p) => throw null!; static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1, p1).ToString(); c.M(p1, p2).ToString(); c.M(p2, p1).ToString(); c.M(p2, p2).ToString(); // 1 } }"; var comp2 = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics( // (4,73): error CS0100: The parameter name 'p' is a duplicate // [return: NotNullIfNotNull("p")] public string? M(string? p, string? p) => throw null!; Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(4, 73), // (12,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2, p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2, p2)").WithLocation(12, 9) ); } [Fact] public void NotNullIfNotNull_Return_NonExistentName() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""missing"")] public string? M(string? p) => throw null!; static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1).ToString(); // 1 c.M(p2).ToString(); // 2 } }"; // Warn on misused attribute? https://github.com/dotnet/roslyn/issues/36073 var comp2 = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c.M(p1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p1)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2)").WithLocation(10, 9) ); } [Fact] public void NotNullIfNotNull_Return_NullName() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(null)] public string? M(string? p) => throw null!; // 1 static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1).ToString(); // 2 c.M(p2).ToString(); // 3 } }"; var comp2 = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics( // (4,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // [return: NotNullIfNotNull(null)] public string? M(string? p) => throw null!; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 31), // (9,9): warning CS8602: Dereference of a possibly null reference. // c.M(p1).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p1)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2)").WithLocation(10, 9) ); } [Fact] public void NotNullIfNotNull_Return_ParamsParameter() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M(params string?[]? p) => throw null!; }"; var source = @" class D { static void M(C c, string?[]? p1, string?[]? p2, string? p3, string? p4) { _ = p1 ?? throw null!; c.M(p1).ToString(); c.M(p2).ToString(); // 1 c.M(null).ToString(); // 2 _ = p3 ?? throw null!; c.M(p3).ToString(); c.M(p4).ToString(); } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // c.M(null).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(null)").WithLocation(9, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Return_ExtensionThis() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public static class Extension { [return: NotNullIfNotNull(""p"")] public static string? M(this string? p) => throw null!; }"; var source = @" class D { static void M(string? p1, string? p2) { _ = p1 ?? throw null!; p1.M().ToString(); p2.M().ToString(); // 1 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // p2.M().ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p2.M()").WithLocation(8, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact, WorkItem(37238, "https://github.com/dotnet/roslyn/issues/37238")] public void NotNullIfNotNull_Return_Indexer() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [NotNullIfNotNull(""p"")] public string? this[string? p] { get { throw null!; } } }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c[p1].ToString(); c[p2].ToString(); // 1 } }"; var expected = new[] { // (7,9): warning CS8602: Dereference of a possibly null reference. // c[p1].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[p1]").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // c[p2].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[p2]").WithLocation(8, 9) }; // NotNullIfNotNull not yet supported on indexers. https://github.com/dotnet/roslyn/issues/37238 var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Indexer_OutParameter() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { public int this[string? p, [NotNullIfNotNull(""p"")] out string? p2] { get { throw null!; } } }"; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,56): error CS0631: ref and out are not valid in this context // public int this[string? p, [NotNullIfNotNull("p")] out string? p2] { get { throw null!; } } Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(4, 56) ); } [Fact] public void NotNullIfNotNull_OutParameter() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public void M(string? p, [NotNullIfNotNull(""p"")] out string? p2) => throw null!; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1, out var x1); x1.ToString(); c.M(p2, out var x2); x2.ToString(); // 1 } }"; var expected = new[] { // (11,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(11, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_OutParameter_WithMaybeNullWhen() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public bool M(string? p, [NotNullIfNotNull(""p""), MaybeNullWhen(true)] out string p2) => throw null!; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; _ = c.M(p1, out var x1) ? x1.ToString() : x1.ToString(); _ = c.M(p2, out var x2) ? x2.ToString() // 1 : x2.ToString(); } }"; var expected = new[] { // (12,11): warning CS8602: Dereference of a possibly null reference. // ? x2.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(12, 11) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, MaybeNullWhenAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_RefParameter() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public void M(string? p, [NotNullIfNotNull(""p"")] ref string? p2) => throw null!; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; string? x1 = null; c.M(p1, ref x1); x1.ToString(); string? x2 = null; c.M(p2, ref x2); x2.ToString(); // 1 string? x3 = """"; c.M(p2, ref x3); x3.ToString(); // 2 } }"; var expected = new[] { // (13,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(13, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(17, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_ByValueParameter() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public void M(string? p, [NotNullIfNotNull(""p"")] string? p2) => throw null!; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; string? x1 = null; c.M(p1, x1); x1.ToString(); // 1 string? x2 = null; c.M(p2, x2); x2.ToString(); // 2 string? x3 = """"; c.M(p2, x3); x3.ToString(); // 3 } }"; var expected = new[] { // (9,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(9, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(13, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact, WorkItem(48489, "https://github.com/dotnet/roslyn/issues/48489")] public void NotNullIfNotNull_Return_BinaryOperator() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""x""), NotNullIfNotNull(""y"")] public static C? operator +(C? x, C? y) => null; public static C? operator *(C? x, C? y) => null; [return: NotNullIfNotNull(""x"")] public static C? operator -(C? x, C? y) => null; [return: NotNullIfNotNull(""y"")] public static C? operator /(C? x, C? y) => null; }"; var source = @" class D { static void M(C c1, C c2, C? cn1, C? cn2) { (c1 + c2).ToString(); // no warn (c1 + cn2).ToString(); // no warn (cn1 + c2).ToString(); // no warn (cn1 + cn2).ToString(); // warn (c1 * c2).ToString(); // warn (c1 * cn2).ToString(); // warn (cn1 * c2).ToString(); // warn (cn1 * cn2).ToString(); // warn (c1 - c2).ToString(); // no warn (c1 - cn2).ToString(); // no warn (cn1 - c2).ToString(); // warn (cn1 - cn2).ToString(); // warn (c1 / c2).ToString(); // no warn (c1 / cn2).ToString(); // warn (cn1 / c2).ToString(); // no warn (cn1 / cn2).ToString(); // warn } }"; var expected = new[] { // (9,10): warning CS8602: Dereference of a possibly null reference. // (cn1 + cn2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn1 + cn2").WithLocation(9, 10), // (11,10): warning CS8602: Dereference of a possibly null reference. // (c1 * c2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1 * c2").WithLocation(11, 10), // (12,10): warning CS8602: Dereference of a possibly null reference. // (c1 * cn2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1 * cn2").WithLocation(12, 10), // (13,10): warning CS8602: Dereference of a possibly null reference. // (cn1 * c2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn1 * c2").WithLocation(13, 10), // (14,10): warning CS8602: Dereference of a possibly null reference. // (cn1 * cn2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn1 * cn2").WithLocation(14, 10), // (18,10): warning CS8602: Dereference of a possibly null reference. // (cn1 - c2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn1 - c2").WithLocation(18, 10), // (19,10): warning CS8602: Dereference of a possibly null reference. // (cn1 - cn2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn1 - cn2").WithLocation(19, 10), // (22,10): warning CS8602: Dereference of a possibly null reference. // (c1 / cn2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1 / cn2").WithLocation(22, 10), // (24,10): warning CS8602: Dereference of a possibly null reference. // (cn1 / cn2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn1 / cn2").WithLocation(24, 10) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact, WorkItem(48489, "https://github.com/dotnet/roslyn/issues/48489")] public void NotNullIfNotNull_Return_BinaryOperatorWithStruct() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public struct S { public int Value; } public class C { [return: NotNullIfNotNull(""y"")] public static C? operator +(C? x, S? y) => null; #pragma warning disable CS8825 [return: NotNullIfNotNull(""y"")] public static C? operator -(C? x, S y) => null; #pragma warning restore CS8825 }"; var source = @" class D { static void M(C c, C? cn, S s, S? sn) { (c + s).ToString(); // no warn (cn + s).ToString(); // no warn (c + sn).ToString(); // warn (cn + sn).ToString(); // warn (c - s).ToString(); // no warn (cn - s).ToString(); // no warn } }"; var expected = new[] { // (8,10): warning CS8602: Dereference of a possibly null reference. // (c + sn).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c + sn").WithLocation(8, 10), // (9,10): warning CS8602: Dereference of a possibly null reference. // (cn + sn).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn + sn").WithLocation(9, 10) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact, WorkItem(48489, "https://github.com/dotnet/roslyn/issues/48489")] public void NotNullIfNotNull_Return_BinaryOperatorInCompoundAssignment() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""x""), NotNullIfNotNull(""y"")] public static C? operator +(C? x, C? y) => null; public static C? operator *(C? x, C? y) => null; [return: NotNullIfNotNull(""x"")] public static C? operator -(C? x, C? y) => null; [return: NotNullIfNotNull(""y"")] public static C? operator /(C? x, C? y) => null; }"; var source = @" class E { static void A(C ac, C? acn, C ar1, C ar2, C? arn1, C? arn2) { ar1 += ac; ar1.ToString(); ar2 += acn; ar2.ToString(); arn1 += ac; arn1.ToString(); arn2 += acn; arn2.ToString(); // warn reference } static void M(C mc, C? mcn, C mr1, C mr2, C? mrn1, C? mrn2) { mr1 *= mc; // warn assignment mr1.ToString(); // warn reference mr2 *= mcn; // warn assignment mr2.ToString(); // warn reference mrn1 *= mc; mrn1.ToString(); // warn reference mrn2 *= mcn; mrn2.ToString(); // warn reference } static void S(C sc, C? scn, C sr1, C sr2, C? srn1, C? srn2) { sr1 -= sc; sr1.ToString(); sr2 -= scn; sr2.ToString(); srn1 -= sc; srn1.ToString(); // warn reference srn2 -= scn; srn2.ToString(); // warn reference } static void D(C dc, C? dcn, C dr1, C dr2, C? drn1, C? drn2) { dr1 /= dc; dr1.ToString(); dr2 /= dcn; // warn assignment dr2.ToString(); // warn reference drn1 /= dc; drn1.ToString(); drn2 /= dcn; drn2.ToString(); // warn reference } }"; var expected = new[] { // (13,9): warning CS8602: Dereference of a possibly null reference. // arn2.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "arn2").WithLocation(13, 9), // (18,9): warning CS8601: Possible null reference assignment. // mr1 *= mc; // warn assignment Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "mr1 *= mc").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // mr1.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "mr1").WithLocation(19, 9), // (20,9): warning CS8601: Possible null reference assignment. // mr2 *= mcn; // warn assignment Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "mr2 *= mcn").WithLocation(20, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // mr2.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "mr2").WithLocation(21, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // mrn1.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "mrn1").WithLocation(23, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // mrn2.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "mrn2").WithLocation(25, 9), // (35,9): warning CS8602: Dereference of a possibly null reference. // srn1.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "srn1").WithLocation(35, 9), // (37,9): warning CS8602: Dereference of a possibly null reference. // srn2.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "srn2").WithLocation(37, 9), // (44,9): warning CS8601: Possible null reference assignment. // dr2 *= dcn; // warn assignment Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "dr2 /= dcn").WithLocation(44, 9), // (45,9): warning CS8602: Dereference of a possibly null reference. // dr2.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "dr2").WithLocation(45, 9), // (49,9): warning CS8602: Dereference of a possibly null reference. // drn2.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "drn2").WithLocation(49, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void MethodWithOutNullableParameter_AfterNotNullWhenTrue() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (M(s, out string? s2)) { s.ToString(); // ok s2.ToString(); // warn } else { s.ToString(); // warn 2 s2.ToString(); // warn 3 } s.ToString(); // ok s2.ToString(); // ok } public static bool M([NotNullWhen(true)] string? s, out string? s2) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(15, 13) ); } [Fact] public void NotNullIfNotNull_Return_WithMaybeNull() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p""), MaybeNull] public string M(string? p) => throw null!; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1).ToString(); c.M(p2).ToString(); // 1 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2)").WithLocation(8, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, MaybeNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition, MaybeNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_OptionalParameter_NonNullDefault() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] string? M1(string? p = ""hello"") => p; void M2() { _ = M1().ToString(); _ = M1(null).ToString(); // 1 _ = M1(""world"").ToString(); } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(null).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(null)").WithLocation(11, 13)); } [Fact] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_OptionalParameter_NullDefault() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] string? M1(string? p = null) => p; void M2() { _ = M1().ToString(); // 1 _ = M1(null).ToString(); // 2 _ = M1(""world"").ToString(); } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // _ = M1().ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1()").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(null).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(null)").WithLocation(11, 13)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/38801")] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_OptionalParameter_LocalFunction() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { void M1() { [return: NotNullIfNotNull(""p"")] string? local1(string? p = ""hello"") => p; _ = local1().ToString(); _ = local1(null).ToString(); // 1 _ = local1(""world"").ToString(); } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = local1(null).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "local1(null)").WithLocation(11, 13)); } [Fact] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_LabeledArguments() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p1"")] string? M1(string? p1, string? p2) => p1; void M2() { _ = M1(""hello"", null).ToString(); _ = M1(p1: ""hello"", p2: null).ToString(); _ = M1(p2: null, p1: ""hello"").ToString(); _ = M1(p2: ""world"", p1: null).ToString(); // 1 } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p2: "world", p1: null).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"M1(p2: ""world"", p1: null)").WithLocation(13, 13)); } [Theory] [InlineData(@"""b""")] [InlineData("null")] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_LabeledArguments_OptionalParameters_NonNullDefault(string p2Default) { var source = $@" using System.Diagnostics.CodeAnalysis; public class C {{ [return: NotNullIfNotNull(""p1"")] string? M1(string? p1 = ""a"", string? p2 = {p2Default}) => p1; void M2() {{ _ = M1(p2: null).ToString(); _ = M1(p1: null).ToString(); // 1 _ = M1(p1: ""hello"", p2: null).ToString(); _ = M1(p2: ""hello"", p1: null).ToString(); // 2 _ = M1(p1: null, p2: ""hello"").ToString(); // 3 _ = M1(p2: null, p1: ""hello"").ToString(); }} }} "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p1: null).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(p1: null)").WithLocation(11, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p2: "hello", p1: null).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"M1(p2: ""hello"", p1: null)").WithLocation(13, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p1: null, p2: "hello").ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"M1(p1: null, p2: ""hello"")").WithLocation(14, 13)); } [Theory] [InlineData(@"""b""")] [InlineData("null")] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_LabeledArguments_OptionalParameters_NullDefault(string p2Default) { var source = $@" using System.Diagnostics.CodeAnalysis; public class C {{ [return: NotNullIfNotNull(""p1"")] string? M1(string? p1 = null, string? p2 = {p2Default}) => p1; void M2() {{ _ = M1(p2: null).ToString(); // 1 _ = M1(p1: null).ToString(); // 2 _ = M1(p1: ""hello"", p2: null).ToString(); _ = M1(p2: ""hello"", p1: null).ToString(); // 3 _ = M1(p1: null, p2: ""hello"").ToString(); // 4 _ = M1(p2: null, p1: ""hello"").ToString(); }} }} "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p2: null).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(p2: null)").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p1: null).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(p1: null)").WithLocation(11, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p2: "hello", p1: null).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"M1(p2: ""hello"", p1: null)").WithLocation(13, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p1: null, p2: "hello").ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"M1(p1: null, p2: ""hello"")").WithLocation(14, 13)); } [Fact] [WorkItem(39868, "https://github.com/dotnet/roslyn/issues/39868")] public void NotNullIfNotNull_BadDefaultParameterValue() { var source = @" using System.Diagnostics.CodeAnalysis; class C { [return: NotNullIfNotNull(""s"")] string? M1(string? s = default(object)) => s; // 1 void M2() { _ = M1().ToString(); // 2 _ = M1(null).ToString(); // 3 _ = M1(""hello"").ToString(); } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (7,24): error CS1750: A value of type 'object' cannot be used as a default parameter because there are no standard conversions to type 'string' // string? M1(string? s = default(object)) => s; // 1 Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("object", "string").WithLocation(7, 24), // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = M1().ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1()").WithLocation(11, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(null).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(null)").WithLocation(12, 13)); } [Fact] [WorkItem(39868, "https://github.com/dotnet/roslyn/issues/39868")] public void NotNullIfNotNull_ParameterDefaultValue_Suppression() { var source1 = @" using System.Diagnostics.CodeAnalysis; public static class C1 { [return: NotNullIfNotNull(""s"")] public static string? M1(string? s = null!) => s; } "; var source2 = @" class C2 { static void M2() { _ = C1.M1().ToString(); _ = C1.M1(null).ToString(); _ = C1.M1(""hello"").ToString(); } } "; var comp1 = CreateNullableCompilation(new[] { source1, source2, NotNullIfNotNullAttributeDefinition }); // technically since the argument has not-null state, the return value should have not-null state here, // but it is such a corner case that it is unlikely to be of interest to modify the current behavior comp1.VerifyDiagnostics( // (6,13): warning CS8602: Dereference of a possibly null reference. // _ = C1.M1().ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C1.M1()").WithLocation(6, 13), // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = C1.M1(null).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C1.M1(null)").WithLocation(7, 13)); var reference = CreateNullableCompilation(new[] { source1, NotNullIfNotNullAttributeDefinition }).EmitToImageReference(); var comp2 = CreateNullableCompilation(source2, references: new[] { reference }); comp2.VerifyDiagnostics( // (6,13): warning CS8602: Dereference of a possibly null reference. // _ = C1.M1().ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C1.M1()").WithLocation(6, 13), // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = C1.M1(null).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C1.M1(null)").WithLocation(7, 13)); } [Fact] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_Indexer_OptionalParameters() { // NOTE: NotNullIfNotNullAttribute is not supported on indexers. // But we want to make sure we don't trip asserts related to analysis of NotNullIfNotNullAttribute. var source = @" using System.Diagnostics.CodeAnalysis; public class C { [NotNullIfNotNull(""p"")] string? this[int i, string? p = ""hello""] => p; void M2() { _ = this[0].ToString(); // 1 _ = this[0, null].ToString(); // 2 _ = this[0, ""world""].ToString(); // 3 } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // _ = this[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this[0]").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = this[0, null].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this[0, null]").WithLocation(11, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // _ = this[0, "world"].ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"this[0, ""world""]").WithLocation(12, 13)); } [Fact] [WorkItem(39802, "https://github.com/dotnet/roslyn/issues/39802")] public void NotNullIfNotNull_ImplicitUserDefinedOperator() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""c"")] public static implicit operator string?(C? c) => c?.ToString(); void M1(string s) { } void M2() { M1(new C()); M1((C?)null); // 1 } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,12): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M1(string s)'. // M1((C?)null); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(C?)null").WithArguments("s", "void C.M1(string s)").WithLocation(13, 12)); } [Fact] [WorkItem(39802, "https://github.com/dotnet/roslyn/issues/39802")] public void NotNullIfNotNull_ImplicitUserDefinedOperator_MultipleAttributes() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""b"")] [return: NotNullIfNotNull(""c"")] public static implicit operator string?(C? c) => c?.ToString(); void M1(string s) { } void M2() { M1(new C()); M1((C?)null); // 1 } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (14,12): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M1(string s)'. // M1((C?)null); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(C?)null").WithArguments("s", "void C.M1(string s)").WithLocation(14, 12)); } [Fact] [WorkItem(39802, "https://github.com/dotnet/roslyn/issues/39802")] public void NotNullIfNotNull_ExplicitUserDefinedOperator() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""c"")] public static explicit operator string?(C? c) => c?.ToString(); void M1(string s) { } void M2() { M1((string)new C()); M1((string?)new C()); // 1 M1((string?)(C?)null); // 2 } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,12): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M1(string s)'. // M1((string?)new C()); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(string?)new C()").WithArguments("s", "void C.M1(string s)").WithLocation(13, 12), // (14,12): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M1(string s)'. // M1((string?)(C?)null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(string?)(C?)null").WithArguments("s", "void C.M1(string s)").WithLocation(14, 12)); } [Fact] [WorkItem(39802, "https://github.com/dotnet/roslyn/issues/39802")] public void UserDefinedConversion_UnconditionalParamAttributes() { var source = @" using System.Diagnostics.CodeAnalysis; public struct A { } public struct B { public static implicit operator A([DisallowNull] B? b) { b.Value.ToString(); return new A(); } void M1(A a) { } void M2() { M1(new B()); M1((B?)null); // 1 } } public class C { public static implicit operator string?([AllowNull] C c) => c?.ToString(); void M1(string? s) { } void M2() { M1(new C()); M1((C?)null); } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (18,12): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // M1((B?)null); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(B?)null").WithLocation(18, 12)); } [Theory] [InlineData("struct")] [InlineData("class")] [WorkItem(39802, "https://github.com/dotnet/roslyn/issues/39802")] public void UserDefinedConversion_ReturnAttributes_Lifted(string typeKind) { var source = @" using System.Diagnostics.CodeAnalysis; public " + typeKind + @" A { public static void AllowNull(A? a) { } public static void DisallowNull([DisallowNull] A? a) { } } public struct B { public static implicit operator A(B b) { return new A(); } void M() { A.AllowNull((B?)new B()); A.AllowNull((B?)null); A.DisallowNull((B?)new B()); A.DisallowNull((B?)null); // 1 } } public struct C { public static implicit operator A(C? c) { return new A(); } void M() { A.AllowNull((C?)new C()); A.AllowNull((C?)null); A.DisallowNull((C?)new C()); A.DisallowNull((C?)null); } } public struct D { [return: NotNull] public static implicit operator A?(D? d) { return new A(); } void M() { A.AllowNull((D?)new D()); A.AllowNull((D?)null); A.DisallowNull((D?)new D()); A.DisallowNull((D?)null); } } public struct E { [return: NotNull] public static implicit operator A?(E e) { return new A(); } void M() { A.AllowNull((E?)new E()); A.AllowNull((E?)null); A.DisallowNull((E?)new E()); A.DisallowNull((E?)null); // 2 } } public struct F { [return: NotNullIfNotNull(""f"")] public static implicit operator A?(F f) { return new A(); } void M() { A.AllowNull((F?)new F()); A.AllowNull((F?)null); A.DisallowNull((F?)new F()); A.DisallowNull((F?)null); // 3 } } public struct G { [return: NotNull] public static implicit operator A(G g) { return new A(); } void M() { A.AllowNull((G?)new G()); A.AllowNull((G?)null); A.DisallowNull((G?)new G()); A.DisallowNull((G?)null); // 4 } } public struct H { // This scenario verifies that DisallowNull has no effect, even when the conversion is lifted. public static implicit operator A([DisallowNull] H h) { return new A(); } void M() { A.AllowNull((H?)new H()); A.AllowNull((H?)null); A.DisallowNull((H?)new H()); A.DisallowNull((H?)null); // 5 } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, DisallowNullAttributeDefinition, NotNullAttributeDefinition, NotNullIfNotNullAttributeDefinition, source }); if (typeKind == "struct") { comp.VerifyDiagnostics( // (23,24): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // A.DisallowNull((B?)null); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(B?)null").WithLocation(23, 24), // (76,24): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // A.DisallowNull((E?)null); // 2 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(E?)null").WithLocation(76, 24), // (94,24): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // A.DisallowNull((F?)null); // 3 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(F?)null").WithLocation(94, 24), // (112,24): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // A.DisallowNull((G?)null); // 4 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(G?)null").WithLocation(112, 24), // (130,24): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // A.DisallowNull((H?)null); // 5 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(H?)null").WithLocation(130, 24) ); } else { comp.VerifyDiagnostics( // (23,24): warning CS8604: Possible null reference argument for parameter 'a' in 'void A.DisallowNull(A? a)'. // A.DisallowNull((B?)null); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(B?)null").WithArguments("a", "void A.DisallowNull(A? a)").WithLocation(23, 24), // (76,24): warning CS8604: Possible null reference argument for parameter 'a' in 'void A.DisallowNull(A? a)'. // A.DisallowNull((E?)null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(E?)null").WithArguments("a", "void A.DisallowNull(A? a)").WithLocation(76, 24), // (94,24): warning CS8604: Possible null reference argument for parameter 'a' in 'void A.DisallowNull(A? a)'. // A.DisallowNull((F?)null); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(F?)null").WithArguments("a", "void A.DisallowNull(A? a)").WithLocation(94, 24), // (112,24): warning CS8604: Possible null reference argument for parameter 'a' in 'void A.DisallowNull(A? a)'. // A.DisallowNull((G?)null); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(G?)null").WithArguments("a", "void A.DisallowNull(A? a)").WithLocation(112, 24), // (130,24): warning CS8604: Possible null reference argument for parameter 'a' in 'void A.DisallowNull(A? a)'. // A.DisallowNull((H?)null); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(H?)null").WithArguments("a", "void A.DisallowNull(A? a)").WithLocation(130, 24) ); } } [Fact] [WorkItem(39802, "https://github.com/dotnet/roslyn/issues/39802")] public void UserDefinedConversion_UnconditionalReturnAttributes() { var source = @" using System.Diagnostics.CodeAnalysis; public struct A { } public struct B { [return: NotNull] public static implicit operator A?(B? b) { return new A(); } void M1([DisallowNull] A? a) { } void M2() { M1(new B()); M1((B?)null); } } public class C { [return: MaybeNull] public static implicit operator string(C? c) => null; void M1(string s) { } void M2() { M1(new C()); // 1 M1((C?)null); // 2 } } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullAttributeDefinition, DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (29,12): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M1(string s)'. // M1(new C()); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "new C()").WithArguments("s", "void C.M1(string s)").WithLocation(29, 12), // (30,12): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M1(string s)'. // M1((C?)null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(C?)null").WithArguments("s", "void C.M1(string s)").WithLocation(30, 12)); } [Fact] public void MethodWithOutNullableParameter_AfterNotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (M(s, out string? s2)) { s.ToString(); // ok s2.ToString(); // warn } else { s.ToString(); // ok s2.ToString(); // warn 2 } s.ToString(); // ok s2.ToString(); // ok } public static bool M([NotNull] string? s, out string? s2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(15, 13) ); } [Fact] public void MethodWithOutNullableParameter_AfterNotNull_InErrorInvocation() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (Missing(M(s, out string? s2))) { s.ToString(); s2.ToString(); // 1 } else { s.ToString(); s2.ToString(); // 2 } s.ToString(); s2.ToString(); } public static bool M([NotNull] string? s, out string? s2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,13): error CS0103: The name 'Missing' does not exist in the current context // if (Missing(M(s, out string? s2))) Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(7, 13), // (10,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(15, 13) ); } [Fact] public void MethodWithOutNonNullableParameter() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main() { M(out string s); s.ToString(); // ok } public static void M(out string value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void MethodWithOutNonNullableParameter_WithNullableOutArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main() { M(out string? s); s.ToString(); // ok } public static void M(out string value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void MethodWithRefNonNullableParameter() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main() { string s = ""hello""; M(ref s); s.ToString(); // ok } public static void M(ref string value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void MethodWithRefNonNullableParameter_WithNullableRefArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? s) { M(ref s); // warn s.ToString(); } public static void M(ref string value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,15): warning CS8601: Possible null reference assignment. // M(ref s); // warn Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(6, 15) ); } [Fact, WorkItem(34874, "https://github.com/dotnet/roslyn/issues/34874")] public void MethodWithRefNonNullableParameter_WithNonNullRefArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main() { string? s = ""hello""; M(ref s); s.ToString(); } public static void M(ref string value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void MethodWithRefNullableParameter_WithNonNullableRefArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string s) { M(ref s); // warn 1 s.ToString(); // warn 2 } public static void M(ref string? value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // M(ref s); // warn 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(6, 15), // (7,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithRefNullableParameter_WithNonNullableLocal() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main() { string s = ""hello""; M(ref s); // warn 1 s.ToString(); // warn 2 } public static void M(ref string? value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // M(ref s); // warn 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(7, 15), // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); } [Fact] public void MethodWithOutParameter_WithNullableOut() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { if (TryGetValue(key, out var s)) { s/*T:string?*/.ToString(); // warn } else { s/*T:string?*/.ToString(); // warn 2 } s.ToString(); // ok } public static bool TryGetValue(string key, out string? value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 13) ); } /// <summary> /// Check the inferred type of var from the semantic model, which currently means from initial binding. /// </summary> private static void VerifyOutVar(CSharpCompilation compilation, string expectedType) { if (SkipVerify(expectedType)) { return; } var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var outVar = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(outVar).Symbol.GetSymbol<LocalSymbol>(); Assert.Equal(expectedType, symbol.TypeWithAnnotations.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); Assert.Null(model.GetDeclaredSymbol(outVar)); } /// <summary> /// Check the inferred type of var from the semantic model, which currently means from initial binding. /// </summary> private static void VerifyVarLocal(CSharpCompilation compilation, string expectedType) { if (SkipVerify(expectedType)) { return; } var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varDecl = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Where(d => d.Declaration.Type.IsVar).Single(); var variable = varDecl.Declaration.Variables.Single(); var symbol = model.GetDeclaredSymbol(variable).GetSymbol<LocalSymbol>(); Assert.Equal(expectedType, symbol.TypeWithAnnotations.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); Assert.Null(model.GetSymbolInfo(variable).Symbol); } // https://github.com/dotnet/roslyn/issues/30150: VerifyOutVar and VerifyVarLocal are currently // checking the type and nullability from initial binding, but there are many cases where initial binding // sets nullability to unknown - in particular, for method type inference which is used in many // of the existing callers of these methods. Re-enable these methods when we're checking the // nullability from NullableWalker instead of initial binding. private static bool SkipVerify(string expectedType) { return expectedType.Contains('?') || expectedType.Contains('!'); } [Fact] public void MethodWithGenericOutParameter() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { Copy(key, out var s); s/*T:string?*/.ToString(); // warn } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string!"); // https://github.com/dotnet/roslyn/issues/29856: expecting string? c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericOutParameter_WithUnnecessarySuppression() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { Copy(key!, out var s); s/*T:string!*/.ToString(); } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void VarLocal_FromGenericMethod_WithUnnecessarySuppression() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { var s = Copy(key!); s/*T:string!*/.ToString(); s = null; } public static T Copy<T>(T key) => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact, WorkItem(40755, "https://github.com/dotnet/roslyn/pull/40755")] public void VarLocal_ValueTypeUsedAsRefArgument() { var source = @"#nullable enable public class C { delegate void Delegate<T>(ref T x); void M2<T>(ref T x, Delegate<T> f) { } void M() { var x = 1; M2(ref x, (ref int i) => { }); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void VarLocal_FromGenericMethod() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { var s = Copy(key); s/*T:string?*/.ToString(); // warn s = null; } public static T Copy<T>(T key) => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string!"); // https://github.com/dotnet/roslyn/issues/29856: expecting string? c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericOutParameter_WithNonNullArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { key = ""hello""; CopyOrDefault(key, out var s); s/*T:string!*/.ToString(); // ok s = null; } public static void CopyOrDefault<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void MethodWithGenericNullableOutParameter() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { CopyOrDefault(key, out var s); s/*T:string?*/.ToString(); // warn } public static void CopyOrDefault<T>(T key, out T? value) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericNullableOutParameter_WithNullableArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { CopyOrDefault(key, out var s); s/*T:string?*/.ToString(); // warn } public static void CopyOrDefault<T>(T key, out T? value) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (6,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.CopyOrDefault<T>(T, out T?)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // CopyOrDefault(key, out var s); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "CopyOrDefault").WithArguments("C.CopyOrDefault<T>(T, out T?)", "T", "string?").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericNullableOutParameter_WithNonNullArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { key = ""hello""; CopyOrDefault(key, out var s); s/*T:string?*/.ToString(); // warn } public static void CopyOrDefault<T>(T key, out T? value) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); } [Fact] public void MethodWithGenericNullableArrayOutParameter() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { CopyOrDefault(key, out var s); s/*T:string?[]!*/[0].ToString(); // warn } public static void CopyOrDefault<T>(T key, out T?[] value) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?[]!"); c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?[]!*/[0].ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s/*T:string?[]!*/[0]").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericNullableArrayOutParameter_WithNullableArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { CopyOrDefault(key, out var s); s/*T:string?[]!*/[0].ToString(); // warn } public static void CopyOrDefault<T>(T key, out T?[] value) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?[]!"); c.VerifyTypes(); c.VerifyDiagnostics( // (6,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.CopyOrDefault<T>(T, out T?[])'. Nullability of type argument 'string?' doesn't match 'class' constraint. // CopyOrDefault(key, out var s); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "CopyOrDefault").WithArguments("C.CopyOrDefault<T>(T, out T?[])", "T", "string?").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?[]!*/[0].ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s/*T:string?[]!*/[0]").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericArrayOutParameter_WithNonNullableArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { CopyOrDefault(key, out var s); s/*T:string![]!*/[0].ToString(); // ok } public static void CopyOrDefault<T>(T key, out T[] value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string![]!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] [WorkItem(29295, "https://github.com/dotnet/roslyn/issues/29295")] public void CatchException() { var c = CreateCompilation(@" class C { void M() { try { System.Console.WriteLine(); } catch (System.Exception e) { e.ToString(); } } } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(29295, "https://github.com/dotnet/roslyn/issues/29295")] public void CatchException_WithWhenIsOperator() { var c = CreateCompilation(@" class C { void M() { try { System.Console.WriteLine(); } catch (System.Exception e) when (!(e is System.ArgumentException)) { e.ToString(); } } } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(29295, "https://github.com/dotnet/roslyn/issues/29295")] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void CatchException_NullableType() { var c = CreateCompilation(@" class C { void M() { try { System.Console.WriteLine(); } catch (System.Exception? e) { var e2 = Copy(e); e2.ToString(); e2 = null; e.ToString(); } } static U Copy<U>(U u) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(29295, "https://github.com/dotnet/roslyn/issues/33540")] public void CatchException_ConstrainedGenericTypeParameter() { var c = CreateCompilation(@" class C { static void M<T>() where T : System.Exception? { try { } catch (T e) { var e2 = Copy(e); e2.ToString(); // 1 e.ToString(); } } static U Copy<U>(U u) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // e2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e2").WithLocation(12, 13)); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_TopLevelNullability() { var c = CreateCompilation(@" class C { public void M() { string? s = """"; M(ref s); s.ToString(); // 1 string s2 = """"; M(ref s2); // 2 s2.ToString(); // 3 string s3 = null; // 4 M2(ref s3); // 5 s3.ToString(); } void M(ref string? s) => throw null!; void M2(ref string s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (11,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // M(ref s2); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s2").WithLocation(11, 15), // (12,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 9), // (14,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string s3 = null; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 21), // (15,16): warning CS8601: Possible null reference assignment. // M2(ref s3); // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s3").WithLocation(15, 16) ); } [Fact] public void RefParameter_WarningKind() { var c = CreateCompilation(@" class C { string field = """"; public void M() { string local = """"; M(ref local); // 1, W-warning M(ref field); // 2 M(ref RefString()); // 3 } ref string RefString() => throw null!; void M(ref string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // M(ref local); // 1, W-warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "local").WithLocation(8, 15), // (10,15): warning CS8601: Possible null reference assignment. // M(ref field); // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "field").WithLocation(10, 15), // (12,15): warning CS8601: Possible null reference assignment. // M(ref RefString()); // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "RefString()").WithLocation(12, 15) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_TopLevelNullability_AlwaysSet() { var c = CreateCompilation(@" class C { public void M() { string? s = null; M(ref s); s.ToString(); } void M(ref string s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (7,15): warning CS8601: Possible null reference assignment. // M(ref s); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(7, 15) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_TopLevelNullability_Suppressed() { var c = CreateCompilation(@" class C { public void M() { string? s = """"; M(ref s!); s.ToString(); // no warning string s2 = """"; M(ref s2!); // no warning s2.ToString(); // no warning } void M(ref string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_VariousLValues() { var c = CreateCompilation(@" class C { string field = """"; string Property { get; set; } = """"; public void M() { M(ref null); // 1 M(ref """"); // 2 M(ref field); // 3 field.ToString(); // 4 M(ref Property); // 5 Property = null; // 6 } void M(ref string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,15): error CS1510: A ref or out value must be an assignable variable // M(ref null); // 1 Diagnostic(ErrorCode.ERR_RefLvalueExpected, "null").WithLocation(8, 15), // (9,15): error CS1510: A ref or out value must be an assignable variable // M(ref ""); // 2 Diagnostic(ErrorCode.ERR_RefLvalueExpected, @"""""").WithLocation(9, 15), // (11,15): warning CS8601: Possible null reference assignment. // M(ref field); // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "field").WithLocation(11, 15), // (12,9): warning CS8602: Dereference of a possibly null reference. // field.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field").WithLocation(12, 9), // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter // M(ref Property); // 5 Diagnostic(ErrorCode.ERR_RefProperty, "Property").WithArguments("C.Property").WithLocation(14, 15), // (15,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // Property = null; // 6 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 20) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_TopLevelNullability_Extension() { var c = CreateCompilation(@" public class C { public void M() { string? s = """"; this.M(ref s); s.ToString(); // 1 string s2 = """"; this.M(ref s2); // 2 s2.ToString(); // 3 } } public static class Extension { public static void M(this C c, ref string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (11,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // this.M(ref s2); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s2").WithLocation(11, 20), // (12,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 9) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_TopLevelNullability_Generic() { var c = CreateCompilation(@" class C { public void M<T>() where T : new() { T t = new T(); M(ref t); t.ToString(); // 1 } void M<T>(ref T t) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(8, 9) ); } [Fact] [WorkItem(37909, "https://github.com/dotnet/roslyn/issues/37909")] public void RefParameter_TypeInferenceUsesRValueType() { var c = CreateNullableCompilation(@" class C { public void M(string? s) { if (s is null) return; var t = M2(ref s); s.ToString(); t.ToString(); } T M2<T>(ref T t) => throw null!; } "); c.VerifyDiagnostics(); } [Fact] [WorkItem(37909, "https://github.com/dotnet/roslyn/issues/37909")] public void OutParameter_TypeInferenceUsesLValueType() { var c = CreateNullableCompilation(@" class C { void M() { string? s1; var t1 = M2(out s1); s1.ToString(); // 1 t1.ToString(); // 2 string? s2 = string.Empty; var t2 = M2(out s2); s2.ToString(); // 3 t2.ToString(); // 4 string? s3 = null; var t3 = M2(out s3); s3.ToString(); // 5 t3.ToString(); // 6 } T M2<T>(out T t) => throw null!; } "); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(9, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(14, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // s3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // t3.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3").WithLocation(19, 9) ); } [Fact] [WorkItem(47663, "https://github.com/dotnet/roslyn/issues/47663")] public void RefParameter_Issue_47663() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { static void X1<T>([NotNullIfNotNull(""value"")] ref T location, T value) where T : class? { } static void X2<T>(ref T location, T value) where T : class? { } private readonly double[] f1; private readonly double[] f2; C() { double[] bar = new double[3]; X1(ref f1, bar); X2(ref f2, bar); // 1, warn on outbound assignment } } "; var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (14,5): warning CS8618: Non-nullable field 'f2' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C", isSuppressed: false).WithArguments("field", "f2").WithLocation(14, 5), // (18,16): warning CS8601: Possible null reference assignment. // X2(ref f2, bar); // 1, warn on outbound assignment Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "f2", isSuppressed: false).WithLocation(18, 16) ); } [Fact] public void RefParameter_InterlockedExchange_ObliviousContext() { var source = @" #nullable enable warnings class C { object o; void M() { InterlockedExchange(ref o, null); } #nullable enable void InterlockedExchange<T>(ref T location, T value) { } } "; // This situation was encountered in VS codebases var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (10,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // InterlockedExchange(ref o, null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null", isSuppressed: false).WithLocation(10, 36) ); } [Fact] public void RefParameter_InterlockedExchange_NullableEnabledContext() { var source = @" #nullable enable class C { object? o; void M() { InterlockedExchange(ref o, null); } void InterlockedExchange<T>(ref T location, T value) { } } "; // With proper annotation on the field, we have no warning var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] public void RefParameter_MiscPermutations() { var source = @" #nullable enable class C { static T X<T>(ref T x, ref T y) => throw null!; void M1(string? maybeNull) { X(ref maybeNull, ref maybeNull).ToString(); // 1 } void M2(string? maybeNull, string notNull) { X(ref maybeNull, ref notNull).ToString(); // 2 } void M3(string notNull) { X(ref notNull, ref notNull).ToString(); } void M4(string? maybeNull, string notNull) { X(ref notNull, ref maybeNull).ToString(); // 3 } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // X(ref maybeNull, ref maybeNull).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "X(ref maybeNull, ref maybeNull)").WithLocation(10, 9), // (15,15): warning CS8601: Possible null reference assignment. // X(ref maybeNull, ref notNull).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "maybeNull").WithLocation(15, 15), // (25,28): warning CS8601: Possible null reference assignment. // X(ref notNull, ref maybeNull).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "maybeNull").WithLocation(25, 28) ); } [Fact] [WorkItem(35534, "https://github.com/dotnet/roslyn/issues/35534")] public void RefParameter_Issue_35534() { var source = @" #nullable enable public class C { void M2() { string? x = ""hello""; var y = M(ref x); y.ToString(); } T M<T>(ref T t) { throw null!; } }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(37909, "https://github.com/dotnet/roslyn/issues/37909")] public void RefParameter_TypeInferenceUsesRValueType_WithNullArgument() { var c = CreateNullableCompilation(@" class C { public void M(string? s) { if (s is null) return; var t = Copy(ref s, null); // 1 s.ToString(); t.ToString(); } public void M2(string? s) { if (s is null) return; var t = Copy2(s, null); // 2 s.ToString(); t.ToString(); } T Copy<T>(ref T t, T t2) => throw null!; T Copy2<T>(T t, T t2) => throw null!; } "); // known issue with null in method type inference: https://github.com/dotnet/roslyn/issues/43536 c.VerifyDiagnostics( // (7,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // var t = Copy(ref s, null); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 29), // (14,26): warning CS8625: Cannot convert null literal to non-nullable reference type. // var t = Copy2(s, null); // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 26) ); } [Fact] [WorkItem(37909, "https://github.com/dotnet/roslyn/issues/37909")] public void OutParameter_TypeInferenceUsesLValueType_WithNullArgument() { var c = CreateNullableCompilation(@" class C { public void M(string? s) { if (s is null) return; var t = Copy(out s, null); s.ToString(); // 1 t.ToString(); // 2 } T Copy<T>(out T t, T t2) => throw null!; } "); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(9, 9) ); } [Fact] [WorkItem(37909, "https://github.com/dotnet/roslyn/issues/37909")] public void ByValParameter_TypeInferenceUsesRValueType() { var c = CreateNullableCompilation(@" class C { public void M(string? s) { if (s is null) return; var t = M2(s); t.ToString(); } T M2<T>(T t) => throw null!; } "); c.VerifyDiagnostics(); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_TopLevelNullability_Generic_Suppressed() { var c = CreateCompilation(@" class C { public void M<T>() where T : new() { T t = new T(); M(ref t!); t.ToString(); // no warning } void M<T>(ref T t) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_NestedNullability() { var c = CreateCompilation(@" class C<T> { public void M(C<string?> s, C<string> s2) { M(ref s); s.ToString(); M(ref s2); // 1, 2 s2.ToString(); } void M(ref C<string?> s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (9,15): warning CS8620: Argument of type 'C<string>' cannot be used as an input of type 'C<string?>' for parameter 's' in 'void C<T>.M(ref C<string?> s)' due to differences in the nullability of reference types. // M(ref s2); // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2").WithArguments("C<string>", "C<string?>", "s", "void C<T>.M(ref C<string?> s)").WithLocation(9, 15)); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_EvaluationOrder() { var c = CreateCompilation(@" class C<T> { public void M(bool b) { string? s = """"; var v1 = M(ref s, b ? s : """"); s.ToString(); // 1 v1.ToString(); s = null; var v2 = M(ref s, s); s.ToString(); // 2 v2.ToString(); // 3 s = null; var v3 = M2(ref s, s); // 4 s.ToString(); v3.ToString(); // 5 } U M<U>(ref string? s, U u) => throw null!; U M2<U>(ref string s, U u) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // v2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v2").WithLocation(14, 9), // (17,25): warning CS8601: Possible null reference assignment. // var v3 = M2(ref s, s); // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(17, 25), // (19,9): warning CS8602: Dereference of a possibly null reference. // v3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v3").WithLocation(19, 9) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_EvaluationOrder_VisitLValuesOnce() { var c = CreateCompilation(@" class C { ref string? F(string? x) => throw null!; void G(ref string? s) => throw null!; public void M() { string s = """"; G(ref F(s = null)); } } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,16): warning CS0219: The variable 's' is assigned but its value is never used // string s = ""; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s").WithLocation(8, 16), // (9,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // G(ref F(s = null)); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(9, 21) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_EvaluationOrder_VisitMultipleLValues() { var c = CreateCompilation(@" class C { void F(ref string? s) => throw null!; public void M(bool b) { string? s = """"; string? s2 = """"; F(ref (b ? ref s : ref s2)); s.ToString(); // 1 s2.ToString(); // 2 } } ", options: WithNullableEnable()); // Missing warnings // Need to track that an expression as an L-value corresponds to multiple slots // Relates to https://github.com/dotnet/roslyn/issues/33365 c.VerifyDiagnostics(); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_TopLevelNullability() { var c = CreateCompilation(@" class C { public void M() { string? s = """"; M(out s); s.ToString(); // 1 string s2 = """"; M(out s2); // 2 s2.ToString(); // 3 } void M(out string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (11,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // M(out s2); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s2").WithLocation(11, 15), // (12,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 9) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_TopLevelNullability_DeclarationExpression() { var c = CreateCompilation(@" class C { public void M() { M(out string? s); s.ToString(); // 1 M(out string s2); // 2 s2.ToString(); // 3 } void M(out string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9), // (9,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // M(out string s2); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "string s2").WithLocation(9, 15), // (10,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 9) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_TopLevelNullability_Suppressed() { var c = CreateCompilation(@" class C { public void M() { string? s = """"; M(out s!); s.ToString(); // no warning string s2 = """"; M(out s2!); // no warning s2.ToString(); // no warning } void M(out string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_TopLevelNullability_Generic() { var c = CreateCompilation(@" class C { public void M<T>() where T : new() { T t = new T(); M(out t); t.ToString(); // 1 } void M<T>(out T t) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(8, 9) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_TopLevelNullability_Generic_Suppressed() { var c = CreateCompilation(@" class C { public void M<T>() where T : new() { T t = new T(); M(out t!); t.ToString(); // no warning } void M<T>(out T t) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_NestedNullability() { var c = CreateCompilation(@" class C<T> { public void M(C<string?> s, C<string> s2) { M(out s); s.ToString(); M(out s2); // 1 s2.ToString(); } void M(out C<string?> s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (9,15): warning CS8624: Argument of type 'C<string>' cannot be used as an output of type 'C<string?>' for parameter 's' in 'void C<T>.M(out C<string?> s)' due to differences in the nullability of reference types. // M(out s2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "s2").WithArguments("C<string>", "C<string?>", "s", "void C<T>.M(out C<string?> s)").WithLocation(9, 15) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_EvaluationOrder() { var c = CreateCompilation(@" class C<T> { public void M(bool b) { string? s = """"; var v1 = M(out s, b ? s : """"); s.ToString(); // 1 v1.ToString(); s = null; var v2 = M(out s, s); s.ToString(); // 2 v2.ToString(); // 3 s = null; var v3 = M2(out s, s); s.ToString(); v3.ToString(); // 4 } U M<U>(out string? s, U u) => throw null!; U M2<U>(out string s, U u) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // v2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v2").WithLocation(14, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // v3.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v3").WithLocation(19, 9) ); } [Fact] public void MethodWithGenericArrayOutParameter_WithNonNullArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { key = ""hello""; CopyOrDefault(key, out var s); s/*T:string![]!*/[0].ToString(); // ok } public static void CopyOrDefault<T>(T key, out T[] value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string![]!"); // https://github.com/dotnet/roslyn/issues/29856: expecting string?[]! c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void MethodWithGenericOutParameter_WithNotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? key) { Copy(key, out var s); // ok s/*T:string!*/.ToString(); // ok } public static void Copy<T>(T key, [NotNull] out T value) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); VerifyOutVar(c, "string!"); // https://github.com/dotnet/roslyn/issues/29856: T is inferred to string! instead of string?, so the `var` gets `string!` c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void MethodWithGenericNullableOutParameter_WithNotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? key) { Copy(key, out var s); // ok s/*T:string!*/.ToString(); // ok } public static void Copy<T>(T key, [NotNull] out T? value) where T : class => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.Copy<T>(T, out T?)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // Copy(key, out var s); // ok Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Copy").WithArguments("C.Copy<T>(T, out T?)", "T", "string?").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericOutParameter_WithNullLiteralArgument_WithNonNullableString() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main() { Copy(null, out string s); // warn s/*T:string!*/.ToString(); // ok } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics( // (6,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // Copy(null, out string s); // warn Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 14) ); } [Fact] public void MethodWithGenericOutParameter_WithNonNullableArgument_WithNonNullableString() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { Copy(key, out string s); s/*T:string!*/.ToString(); } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] [WorkItem(29857, "https://github.com/dotnet/roslyn/issues/29857")] public void MethodWithGenericOutParameter_WithNullableArgument_WithNonNullableString() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { Copy(key, out string s); s/*T:string?*/.ToString(); } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Copy(key, out string s); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "string s").WithLocation(6, 23), // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericOutParameter_WithNonNullableArgument_WithNullableString() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { Copy(key, out string? s); s/*T:string?*/.ToString(); } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericOutParameter_WithNullableArgument_WithNullableString() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { Copy(key, out string? s); s/*T:string?*/.ToString(); // warn } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void VarLocalFromGenericMethod() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { var s = Copy(key); s/*T:string!*/.ToString(); // ok } public T Copy<T>(T key) => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void VarLocalFromGenericMethod_WithNullableArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { var s = Copy(key); s/*T:string?*/.ToString(); // warn } public T Copy<T>(T key) => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string!"); // https://github.com/dotnet/roslyn/issues/29856: expecting string? c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void VarLocalFromGenericMethod_WithNonNullArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { key = ""hello""; var s = Copy(key); s/*T:string!*/.ToString(); // ok } public T Copy<T>(T key) => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void VarLocalFromGenericMethod_WithNullableReturn() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { var s = Copy(key); s/*T:string?*/.ToString(); // warn } public T? Copy<T>(T key) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (6,17): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.Copy<T>(T)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var s = Copy(key); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Copy").WithArguments("C.Copy<T>(T)", "T", "string?").WithLocation(6, 17), // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void VarLocalFromGenericMethod_WithNullableReturn_WithNonNullArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { key = ""hello""; var s = Copy(key); s/*T:string?*/.ToString(); // warn } public T? Copy<T>(T key) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); } [Fact] [WorkItem(29858, "https://github.com/dotnet/roslyn/issues/29858")] public void GenericMethod_WithNotNullOnMethod() { CSharpCompilation c = CreateCompilation(@" using System.Diagnostics.CodeAnalysis; public class C { [NotNull] public static T Copy<T>(T key) => throw null!; } " + NotNullAttributeDefinition); c.VerifyDiagnostics( // (5,6): error CS0592: Attribute 'NotNull' is not valid on this declaration type. It is only valid on 'property, indexer, field, parameter, return' declarations. // [NotNull] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "NotNull").WithArguments("NotNull", "property, indexer, field, parameter, return").WithLocation(5, 6) ); } [Fact] [WorkItem(29862, "https://github.com/dotnet/roslyn/issues/29862")] public void SuppressedNullGivesNonNullResult() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string s) { s = null!; var s2 = s; s2 /*T:string!*/ .ToString(); // ok s2 = null; } } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] [WorkItem(29862, "https://github.com/dotnet/roslyn/issues/29862")] public void SuppressedDefaultGivesNonNullResult() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string s) { s = default!; // default! returns a non-null result var s2 = s; s2/*T:string!*/.ToString(); // ok } } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void SuppressedObliviousValueGivesNonNullResult() { var libComp = CreateCompilation(@" public static class Static { public static string Oblivious = null; } ", parseOptions: TestOptions.Regular7); var comp = CreateCompilation(new[] { @" public class C { public void Main(string s, string? ns) { s = Static.Oblivious!; var s2 = s; s2/*T:string!*/.ToString(); // ok ns = Static.Oblivious!; ns.ToString(); // ok } } " }, options: WithNullableEnable(), references: new[] { libComp.EmitToImageReference() }); VerifyVarLocal(comp, "string!"); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void SuppressedValueGivesNonNullResult() { var comp = CreateCompilation(new[] { @" public class C { public void Main(string? ns, bool b) { var x1 = F(ns!); x1 /*T:string!*/ .ToString(); var listNS = List.Create(ns); listNS /*T:List<string?>!*/ .ToString(); var x2 = F2(listNS); x2 /*T:string!*/ .ToString(); } public T F<T>(T? x) where T : class => throw null!; public T F2<T>(List<T?> x) where T : class => throw null!; } public class List { public static List<T> Create<T>(T t) => throw null!; } public class List<T> { } " }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void NestedNullabilityMismatchIgnoresSuppression() { var obliviousComp = CreateCompilation(@" public static class Static { public static string Oblivious = null; } ", parseOptions: TestOptions.Regular7); var comp = CreateCompilation(new[] { @" public class C { public void Main(string s, string? ns) { var o = Static.Oblivious; { var listS = List.Create(s); var listNS = List.Create(ns); listS /*T:List<string!>!*/ .ToString(); listNS /*T:List<string?>!*/ .ToString(); listS = listNS!; // 1 } { var listS = List.Create(s); var listO = List.Create(o); listO /*T:List<string!>!*/ .ToString(); listS = listO; // ok } { var listNS = List.Create(ns); var listS = List.Create(s); listNS = listS!; // 2 } { var listNS = List.Create(ns); var listO = List.Create(o); listNS = listO!; // 3 } { var listO = List.Create(o); var listNS = List.Create(ns); listO = listNS!; // 4 } { var listO = List.Create(o); var listS = List.Create(s); listO = listS; // ok } } } public class List { public static List<T> Create<T>(T t) => throw null!; } public class List<T> { } " }, options: WithNullableEnable(), references: new[] { obliviousComp.EmitToImageReference() }); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void AssignNull() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string s) { s = null; // warn s.ToString(); // warn 2 } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // warn Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void AssignDefault() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string s) { s = default; // warn s.ToString(); // warn 2 } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = default; // warn Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void NotNullWhenTrue_Simple() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string key) { if (TryGetValue(key, out string? s)) { s.ToString(); // ok } else { s.ToString(); // warn } s.ToString(); // ok } public static bool TryGetValue(string key, [NotNullWhen(true)] out string? value) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); VerifyAnnotationsAndMetadata(c, "C.Main", None); VerifyAnnotationsAndMetadata(c, "C.TryGetValue", None, NotNullWhenTrue); } [Fact] public void NotNullWhenTrue_Ref() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string key) { string? s = null; if (TryGetValue(key, ref s)) { s.ToString(); // ok } else { s.ToString(); // warn } } public static bool TryGetValue(string key, [NotNullWhen(true)] ref string? value) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 13) ); } [Fact] public void NotNullWhenTrue_Nested() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (IsNotNull(s?.ToString())) { s.ToString(); } else { s.ToString(); // warn } } public static bool IsNotNull([NotNullWhen(true)] string? value) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); } [Fact] public void NotNullWhenTrue_WithNotNullWhenFalse_WithVoidReturn() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { M(out string? s); s.ToString(); // 1 } public static void M([NotNullWhen(true), NotNullWhen(false)] out string? value) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (10,46): error CS0579: Duplicate 'NotNullWhen' attribute // public static void M([NotNullWhen(true), NotNullWhen(false)] out string? value) => throw null!; Diagnostic(ErrorCode.ERR_DuplicateAttribute, "NotNullWhen").WithArguments("NotNullWhen").WithLocation(10, 46) ); VerifyAnnotations(c, "C.M", NotNullWhenTrue); } [Fact, WorkItem(37081, "https://github.com/dotnet/roslyn/issues/37081")] public void DoesNotReturn_Simple() { string lib_cs = @" using System.Diagnostics.CodeAnalysis; public class C { [DoesNotReturn] public static void Throw() => throw null!; } "; string source = @" class D { void Main(object? o) { string unassigned; C.Throw(); o.ToString(); // unreachable for purpose of nullability analysis so no warning unassigned.ToString(); // 1, reachable for purpose of definite assignment } } "; // Should [DoesNotReturn] affect all flow analyses? https://github.com/dotnet/roslyn/issues/37081 var expected = new[] { // (9,9): error CS0165: Use of unassigned local variable 'unassigned' // unassigned.ToString(); // 1, reachable for purpose of definite assignment Diagnostic(ErrorCode.ERR_UseDefViolation, "unassigned").WithArguments("unassigned").WithLocation(9, 9) }; var lib = CreateNullableCompilation(new[] { lib_cs, DoesNotReturnAttributeDefinition }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DoesNotReturnAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact, WorkItem(45795, "https://github.com/dotnet/roslyn/issues/45795")] public void DoesNotReturn_ReturnStatementInLocalFunction() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [DoesNotReturn] public void M() { _ = local1(); local2(); throw null!; int local1() { return 1; } void local2() { return; } } } "; var comp = CreateCompilation(new[] { source, DoesNotReturnAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(37081, "https://github.com/dotnet/roslyn/issues/37081")] public void LocalFunctionAlwaysThrows() { string source = @" class D { void Main(object? o) { string unassigned; boom(); o.ToString(); // 1 - reachable in nullable analysis unassigned.ToString(); // unreachable due to definite assignment analysis of local functions void boom() { throw null!; } } } "; // Should local functions which do not return affect nullability analysis? https://github.com/dotnet/roslyn/issues/45814 var comp = CreateNullableCompilation(new[] { source, DoesNotReturnAttributeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 1 - reachable in nullable analysis Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(8, 9)); } [Fact] [WorkItem(37081, "https://github.com/dotnet/roslyn/issues/37081")] public void DoesNotReturn_LocalFunction_CheckImpl() { string source = @" using System.Diagnostics.CodeAnalysis; class D { void Main(object? o) { boom(); [DoesNotReturn] void boom() { } } } "; // Should local functions support `[DoesNotReturn]`? https://github.com/dotnet/roslyn/issues/45814 var comp = CreateNullableCompilation(new[] { source, DoesNotReturnAttributeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact, WorkItem(45791, "https://github.com/dotnet/roslyn/issues/45791")] public void DoesNotReturn_VoidReturningMethod() { string source = @" using System.Diagnostics.CodeAnalysis; public class C { [DoesNotReturn] public void M() { return; } } "; var comp = CreateNullableCompilation(new[] { source, DoesNotReturnAttributeDefinition }); comp.VerifyDiagnostics( // (9,9): warning CS8763: A method marked [DoesNotReturn] should not return. // return; Diagnostic(ErrorCode.WRN_ShouldNotReturn, "return;").WithLocation(9, 9) ); } [Fact] public void DoesNotReturn_Operator() { // Annotations not honored on user-defined operators yet https://github.com/dotnet/roslyn/issues/32671 string lib_cs = @" using System.Diagnostics.CodeAnalysis; public class C { [DoesNotReturn] public static C operator +(C a, C b) => throw null!; } "; string source = @" class D { void Main(object? o, C c) { _ = c + c; o.ToString(); // unreachable so no warning } } "; var lib = CreateNullableCompilation(new[] { lib_cs, DoesNotReturnAttributeDefinition }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // unreachable so no warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(7, 9) ); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DoesNotReturnAttributeDefinition }); comp2.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // unreachable so no warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(7, 9) ); } [Fact] public void DoesNotReturn_WithDoesNotReturnIf() { string lib_cs = @" using System.Diagnostics.CodeAnalysis; public class C { [DoesNotReturn] public static bool Throw([DoesNotReturnIf(true)] bool x) => throw null!; } "; string source = @" class D { void Main(object? o, bool b) { _ = C.Throw(b) ? o.ToString() : o.ToString(); } } "; var lib = CreateNullableCompilation(new[] { lib_cs, DoesNotReturnAttributeDefinition, DoesNotReturnIfAttributeDefinition }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DoesNotReturnAttributeDefinition, DoesNotReturnIfAttributeDefinition }); comp2.VerifyDiagnostics(); } [Fact] public void DoesNotReturn_OnOverriddenMethod() { string lib_cs = @" using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool MayThrow() => throw null!; } public class C : Base { [DoesNotReturn] public override bool MayThrow() => throw null!; } "; string source = @" class D { void Main(object? o, object? o2, bool b) { _ = new Base().MayThrow() ? o.ToString() // 1 : o.ToString(); // 2 _ = new C().MayThrow() ? o2.ToString() : o2.ToString(); } } "; var expected = new[] { // (7,15): warning CS8602: Dereference of a possibly null reference. // ? o.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(7, 15), // (8,15): warning CS8602: Dereference of a possibly null reference. // : o.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(8, 15) }; var lib = CreateNullableCompilation(new[] { lib_cs, DoesNotReturnAttributeDefinition, DoesNotReturnIfAttributeDefinition }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DoesNotReturnAttributeDefinition, DoesNotReturnIfAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void DoesNotReturn_OnImplementation() { string source = @" using System.Diagnostics.CodeAnalysis; public interface I { bool MayThrow(); } public class C1 : I { [DoesNotReturn] public bool MayThrow() => throw null!; } public class C2 : I { [DoesNotReturn] bool I.MayThrow() => throw null!; } public interface I2 { [DoesNotReturn] bool MayThrow(); } public class C3 : I2 { public bool MayThrow() => throw null!; // 1 } public class C4 : I2 { bool I2.MayThrow() => throw null!; // 2 } "; var comp = CreateNullableCompilation(new[] { source, DoesNotReturnAttributeDefinition }); comp.VerifyDiagnostics( // (22,17): warning CS8770: Method 'bool C3.MayThrow()' lacks `[DoesNotReturn]` annotation to match implemented or overridden member. // public bool MayThrow() => throw null!; // 1 Diagnostic(ErrorCode.WRN_DoesNotReturnMismatch, "MayThrow").WithArguments("bool C3.MayThrow()").WithLocation(22, 17), // (26,13): warning CS8770: Method 'bool C4.MayThrow()' lacks `[DoesNotReturn]` annotation to match implemented or overridden member. // bool I2.MayThrow() => throw null!; // 2 Diagnostic(ErrorCode.WRN_DoesNotReturnMismatch, "MayThrow").WithArguments("bool C4.MayThrow()").WithLocation(26, 13) ); } [Fact] public void DoesNotReturnIfFalse_NotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { MyAssert(c != null); c.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(38124, "https://github.com/dotnet/roslyn/issues/38124")] public void DoesNotReturnIfFalse_AssertBooleanConstant() { var source = @" using System.Diagnostics.CodeAnalysis; class C { static void M(string? s, string? s2) { MyAssert(true); _ = s.Length; // 1 MyAssert(false); _ = s2.Length; } static void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, DoesNotReturnIfAttributeDefinition }); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13) ); } [Fact] public void DoesNotReturnIfFalse_NotNull_Nested() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { MyAssert(c?.ToString() != null); c.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void DoesNotReturnIfFalse_NotNull_InErrorInvocation() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { Missing(MyAssert(c != null)); c.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): error CS0103: The name 'Missing' does not exist in the current context // Missing(MyAssert(c != null)); Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(7, 9) ); } [Fact] public void DoesNotReturnIfFalse_NotNull_NullConditionalAccess() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { object? _o = null; void Main(C? c) { MyAssert(c?._o != null); c.ToString(); c._o.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DoesNotReturnIfFalse_Null() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { MyAssert(c == null); c.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void DoesNotReturnIfFalse_Null_InErrorInvocation() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { Missing(MyAssert(c == null)); c.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): error CS0103: The name 'Missing' does not exist in the current context // Missing(MyAssert(c == null)); Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9) ); } [Fact] public void DoesNotReturnIfFalse_RefOutInParameters() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(bool b) { MyAssert(ref b, out bool b2, in b); } void MyAssert([DoesNotReturnIf(false)] ref bool condition, [DoesNotReturnIf(true)] out bool condition2, [DoesNotReturnIf(false)] in bool condition3) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DoesNotReturnIfFalse_WithDoesNotReturnIfTrue() { CSharpCompilation c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void MyAssert([DoesNotReturnIf(false), DoesNotReturnIf(true)] bool condition) => throw null!; // 1 void MyAssert2([DoesNotReturnIf(true), DoesNotReturnIf(false)] bool condition) => throw null!; // 2 } ", DoesNotReturnIfAttributeDefinition }); c.VerifyDiagnostics( // (5,44): error CS0579: Duplicate 'DoesNotReturnIf' attribute // void MyAssert([DoesNotReturnIf(false), DoesNotReturnIf(true)] bool condition) => throw null!; // 1 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "DoesNotReturnIf").WithArguments("DoesNotReturnIf").WithLocation(5, 44), // (6,44): error CS0579: Duplicate 'DoesNotReturnIf' attribute // void MyAssert2([DoesNotReturnIf(true), DoesNotReturnIf(false)] bool condition) => throw null!; // 2 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "DoesNotReturnIf").WithArguments("DoesNotReturnIf").WithLocation(6, 44) ); } [Fact] public void DoesNotReturnIfFalse_MethodWithReturnType() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { if (MyAssert(c != null)) { c.ToString(); } else { c.ToString(); } } bool MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void AssertsTrue_NotNullAndNotEmpty() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? c) { Assert(c != null && c != """"); c.ToString(); } static void Assert([DoesNotReturnIf(false)] bool b) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void AssertsTrue_NotNullOrUnknown() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? c, bool b) { Assert(c != null || b); c.ToString(); } static void Assert([DoesNotReturnIf(false)] bool b) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9) ); } [Fact] public void AssertsTrue_IsNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C c) { Assert(c == null, ""hello""); c.ToString(); } static void Assert([DoesNotReturnIf(false)] bool b, string message) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9) ); } [Fact] public void DoesNotReturnIfFalse_NoDuplicateDiagnostics() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { Assert(Method(null), ""hello""); c.ToString(); } bool Method(string x) => throw null!; static void Assert([DoesNotReturnIf(false)] bool b, string message) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,23): warning CS8625: Cannot convert null literal to non-nullable reference type. // Assert(Method(null), "hello"); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 23), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9) ); } [Fact] public void DoesNotReturnIfFalse_InTry() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { try { Assert(c != null, ""hello""); } catch { } c.ToString(); } static void Assert([DoesNotReturnIf(false)] bool b, string message) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(13, 9) ); } [Fact] public void DoesNotReturnIfTrue_Null() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { MyAssert(c == null); c.ToString(); } void MyAssert([DoesNotReturnIf(true)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DoesNotReturnIfTrue_NotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { MyAssert(c != null); c.ToString(); } void MyAssert([DoesNotReturnIf(true)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9) ); } [Theory] [InlineData("true", "false")] [InlineData("false", "true")] public void DoesNotReturnIfTrue_DefaultArgument(string attributeArgument, string negatedArgument) { CSharpCompilation c = CreateCompilation(new[] { $@" using System.Diagnostics.CodeAnalysis; class C {{ void M1(C? c) {{ MyAssert1(); c.ToString(); }} void M2(C? c) {{ MyAssert1({attributeArgument}); c.ToString(); }} void M3(C? c) {{ MyAssert1({negatedArgument}); c.ToString(); // 1 }} void MyAssert1([DoesNotReturnIf({attributeArgument})] bool condition = {attributeArgument}) => throw null!; void M4(C? c) {{ MyAssert2(); c.ToString(); // 2 }} void M5(C? c) {{ MyAssert2({attributeArgument}); c.ToString(); }} void M6(C? c) {{ MyAssert2({negatedArgument}); c.ToString(); // 3 }} void MyAssert2([DoesNotReturnIf({attributeArgument})] bool condition = {negatedArgument}) => throw null!; }} ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (20,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(20, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(28, 9), // (40,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(40, 9)); } [Fact] [WorkItem(39868, "https://github.com/dotnet/roslyn/issues/39868")] public void BadNullableDefaultArgument() { string source = @" public struct MyStruct { static void M1(MyStruct? s = default(MyStruct)) { } // 1 static void M2() { M1(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (4,30): error CS1770: A value of type 'MyStruct' cannot be used as default parameter for nullable parameter 's' because 'MyStruct' is not a simple type // static void M1(MyStruct? s = default(MyStruct)) { } // 1 Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "s").WithArguments("MyStruct", "s").WithLocation(4, 30)); } [Fact] [WorkItem(51622, "https://github.com/dotnet/roslyn/issues/51622")] public void NullableEnumDefaultArgument_NonZeroValue() { string source = @" #nullable enable public enum E { E1 = 1 } class C { void M0(E? e = E.E1) { } void M1() { M0(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(39868, "https://github.com/dotnet/roslyn/issues/39868")] public void BadNonNullableReferenceDefaultArgument() { string source = @" public struct MyStruct { static void M1(string s = default(MyStruct)) { } // 1 static void M2() { M1(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (4,27): error CS1750: A value of type 'MyStruct' cannot be used as a default parameter because there are no standard conversions to type 'string' // static void M1(string s = default(MyStruct)) { } // 1 Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("MyStruct", "string").WithLocation(4, 27)); } [Fact] public void NotNullWhenFalse_Simple() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (MyIsNullOrEmpty(s)) { s.ToString(); // warn } else { s.ToString(); // ok } s.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); VerifyAnnotationsAndMetadata(c, "C.Main", None); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_BoolReturn() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static object MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); VerifyAnnotations(c, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_OnTwoParameters() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s, string? s2) { if (MyIsNullOrEmpty(s, s2)) { s.ToString(); // warn 1 s2.ToString(); // warn 2 } else { s.ToString(); // ok s2.ToString(); // ok } s.ToString(); // ok s2.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s, [NotNullWhen(false)] string? s2) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (10,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 13) ); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNullWhenFalse, NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_WithNotNullWhenTrueOnSecondParameter() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s, string? s2) { if (MyIsNullOrEmpty(s, s2)) { s.ToString(); // warn 1 s2.ToString(); // ok } else { s.ToString(); // ok s2.ToString(); // warn 2 } s.ToString(); // ok s2.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s, [NotNullWhen(true)] string? s2) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(15, 13) ); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNullWhenFalse, NotNullWhenTrue); } [Fact] public void NotNullWhenFalse_OnIndexer() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s, int x) { if (this[s, x]) { s.ToString(); // warn } else { s.ToString(); // ok } s.ToString(); // ok } public bool this[[NotNullWhen(false)] string? s, int x] => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullWhenFalse_SecondArgumentDereferences() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { if (Method(s, s.ToString())) // warn 1 { s.ToString(); // ok } else { s.ToString(); // ok } } static bool Method([NotNullWhen(false)] string? s, string s2) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,23): warning CS8602: Dereference of a possibly null reference. // if (Method(s, s.ToString())) // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 23) ); } [Fact] public void NotNullWhenFalse_SecondArgumentAssigns() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { if (Method(s, s = null)) { s.ToString(); // 1 } else { s.ToString(); } } static bool Method([NotNullWhen(false)] string? s, string? s2) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullWhenFalse_MissingAttribute() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void Main(string? s) { if (MyIsNullOrEmpty(s)) { s.ToString(); // warn } else { s.ToString(); // warn 2 } s.ToString(); // ok } static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (17,34): error CS0246: The type or namespace name 'NotNullWhenAttribute' could not be found (are you missing a using directive or an assembly reference?) // static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotNullWhen").WithArguments("NotNullWhenAttribute").WithLocation(17, 34), // (17,34): error CS0246: The type or namespace name 'NotNullWhen' could not be found (are you missing a using directive or an assembly reference?) // static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotNullWhen").WithArguments("NotNullWhen").WithLocation(17, 34), // (8,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 13) ); VerifyAnnotations(c, "C.MyIsNullOrEmpty", None); } private static void VerifyAnnotations(CSharpCompilation compilation, string memberName, params FlowAnalysisAnnotations[] expected) { var method = compilation.GetMember<MethodSymbol>(memberName); Assert.True((object)method != null, $"Could not find method '{memberName}'"); var actual = method.Parameters.Select(p => p.FlowAnalysisAnnotations); Assert.Equal(expected, actual); } private void VerifyAnnotationsAndMetadata(CSharpCompilation compilation, string memberName, params FlowAnalysisAnnotations[] expected) { VerifyAnnotations(compilation, memberName, expected); // Also verify from metadata var compilation2 = CreateCompilation("", references: new[] { compilation.EmitToImageReference() }); VerifyAnnotations(compilation2, memberName, expected); } [Fact] public void NotNullWhenFalse_BadAttribute() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (MyIsNullOrEmpty(s)) { s.ToString(); // warn 1 } else { s.ToString(); // warn 2 } } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] public class NotNullWhenAttribute : Attribute { public NotNullWhenAttribute(bool when, bool other = false) { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", None); } [Fact] public void NotNullWhenFalse_InvertIf() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (!MyIsNullOrEmpty(s)) { s.ToString(); // ok } else { s.ToString(); // warn } } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_WithNullLiteral() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { _ = MyIsNullOrEmpty(null); } static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNullWhenFalse_InstanceMethod() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (this.MyIsNullOrEmpty(s)) { s.ToString(); // warn } else { s.ToString(); // ok } } public bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_ExtensionMethod() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (this.MyIsNullOrEmpty(s)) { s.ToString(); // warn } else { s.ToString(); // ok } } } public static class Extension { public static bool MyIsNullOrEmpty(this C c, [NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); VerifyAnnotationsAndMetadata(c, "Extension.MyIsNullOrEmpty", None, NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_String_NotIsNullOrEmpty_NoDuplicateWarnings() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void M() { if (!string.IsNullOrEmpty(M2(null))) { } } string? M2(string s) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // if (!string.IsNullOrEmpty(M2(null))) Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 38) ); } [Fact] public void NotNullWhenFalse_String_NotIsNullOrEmpty_NotAString() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void M() { if (!string.IsNullOrEmpty(M2(null))) { } } void M2(string s) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,35): error CS1503: Argument 1: cannot convert from 'void' to 'string' // if (!string.IsNullOrEmpty(M2(null))) Diagnostic(ErrorCode.ERR_BadArgType, "M2(null)").WithArguments("1", "void", "string").WithLocation(6, 35), // (6,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // if (!string.IsNullOrEmpty(M2(null))) Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 38) ); } [Fact] public void NotNullWhenFalse_PartialMethod() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public partial class C { partial void M1(string? s); partial void M1([NotNullWhen(false)] string? s) => throw null!; partial void M2([NotNullWhen(false)] string? s); partial void M2(string? s) => throw null!; partial void M3([NotNullWhen(false)] string? s); partial void M3([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,22): error CS0579: Duplicate 'NotNullWhen' attribute // partial void M3([NotNullWhen(false)] string? s); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "NotNullWhen").WithArguments("NotNullWhen").WithLocation(11, 22) ); VerifyAnnotations(c, "C.M1", NotNullWhenFalse); VerifyAnnotations(c, "C.M2", NotNullWhenFalse); VerifyAnnotations(c, "C.M3", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_ReturningDynamic() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (MyIsNullOrEmpty(s)) { s.ToString(); // warn } else { s.ToString(); } } public dynamic MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); VerifyAnnotations(c, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_ReturningObject_FromMetadata() { string il = @" .class private auto ansi sealed beforefieldinit System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig instance object MyIsNullOrEmpty (string s) cil managed { .param [1] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void System.Diagnostics.CodeAnalysis.NotNullWhenAttribute::.ctor(bool) = ( 01 00 00 00 00 ) IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi beforefieldinit System.Diagnostics.CodeAnalysis.NotNullWhenAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 00 08 00 00 01 00 54 02 0d 41 6c 6c 6f 77 4d 75 6c 74 69 70 6c 65 00 ) .method public hidebysig specialname rtspecialname instance void .ctor (bool when) cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void Main(C c, string? s) { if ((bool)c.MyIsNullOrEmpty(s)) { s.ToString(); // warn 1 } else { s.ToString(); // warn 2 } } } "; var compilation = CreateCompilationWithIL(new[] { source }, il, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 13) ); VerifyAnnotations(compilation, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_ReturningObject() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { MyIsNullOrEmpty(s); s.ToString(); // warn } object MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); } [Fact] public void NotNullWhenFalse_FollowedByNotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (MyIsNullOrEmpty(s, s)) { s.ToString(); // ok } else { s.ToString(); // ok } s.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s, [NotNull] string? s2) => throw null!; } ", NotNullWhenAttributeDefinition, NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNullWhenFalse, NotNull); } [Fact] public void NotNullWhenFalse_AndNotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (MyIsNullOrEmpty(s)) { s.ToString(); // ok } else { s.ToString(); // ok } s.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false), NotNull] string? s) => throw null!; } ", NotNullWhenAttributeDefinition, NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNull); } [Fact] public void NotNull_Simple() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { ThrowIfNull(42, s); s.ToString(); // ok } public static void ThrowIfNull(int x, [NotNull] string? s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); VerifyAnnotationsAndMetadata(c, "C.ThrowIfNull", None, NotNull); } [Fact] public void NotNull_Nested() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { ThrowIfNull(s?.ToString()); s.ToString(); // ok } public static void ThrowIfNull([NotNull] string? s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact, WorkItem(32335, "https://github.com/dotnet/roslyn/issues/32335")] public void NotNull_LearningFromNotNullTest() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void M(C? c1) { ThrowIfNull(c1?.Method()); c1.ToString(); // ok } C? Method() => throw null!; static void ThrowIfNull([NotNull] C? c) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact, WorkItem(38522, "https://github.com/dotnet/roslyn/issues/38522")] public void AsType_LearningFromNotNullTest() { var c = CreateNullableCompilation(@" public class C { public void M(object? o) { if (o as string != null) { o.ToString(); } } public void M2(object? o) { if (o is string) { o.ToString(); } } } "); c.VerifyDiagnostics(); } [Fact, WorkItem(38522, "https://github.com/dotnet/roslyn/issues/38522")] public void AsType_LearningFromNullResult() { var c = CreateNullableCompilation(@" public class C { public void M(object o) { if ((o as object) == null) { o.ToString(); // note: we're not inferring that o was null here, but we could consider it } } public void M2(object o) { if ((o as string) == null) { o.ToString(); } } } "); c.VerifyDiagnostics(); } [Fact] public void NotNull_ResettingStateMatters() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s, string? s2) { ThrowIfNull(s = s2, s2 = ""hello""); s.ToString(); // warn s2.ToString(); // ok } public static void ThrowIfNull(string? s1, [NotNull] string? s2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); } [Fact] public void NotNull_ResettingStateMatters_InIndexer() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s, string? s2) { _ = this[s = s2, s2 = ""hello""]; s.ToString(); // warn s2.ToString(); // ok } public int this[string? s1, [NotNull] string? s2] { get { throw null!; } } } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); } [Fact] public void NotNull_NoDuplicateDiagnosticsWhenResettingState() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public interface I<T> { } public class C { void Main(string? s, I<object> i) { ThrowIfNull(i, s); // single warning on conversion failure } public static void ThrowIfNull(I<object?> x, [NotNull] string? s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,21): warning CS8620: Nullability of reference types in argument of type 'I<object>' doesn't match target type 'I<object?>' for parameter 'x' in 'void C.ThrowIfNull(I<object?> x, string? s)'. // ThrowIfNull(i, s); // single warning on conversion failure Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "i").WithArguments("I<object>", "I<object?>", "x", "void C.ThrowIfNull(I<object?> x, string? s)").WithLocation(8, 21) ); } [Fact] public void NotNull_Generic_WithRefType() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { ThrowIfNull(s); s.ToString(); // ok } public static void ThrowIfNull<T>([NotNull] T s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNull_Generic_WithValueType() { CSharpCompilation c = CreateCompilation(@" using System.Diagnostics.CodeAnalysis; public class C { void Main(int s) { ThrowIfNull(s); s.ToString(); } public static void ThrowIfNull<T>([NotNull] T s) => throw null!; } " + NotNullAttributeDefinition); c.VerifyDiagnostics(); } [Fact] public void NotNull_Generic_WithUnconstrainedGenericType() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M<U>(U u) { ThrowIfNull(u); u.ToString(); } public static void ThrowIfNull<T>([NotNull] T s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNull_OnInterface() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s, Interface i) { i.ThrowIfNull(42, s); s.ToString(); // ok } } public interface Interface { void ThrowIfNull(int x, [NotNull] string? s); } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); VerifyAnnotationsAndMetadata(c, "Interface.ThrowIfNull", None, NotNull); } [Fact] public void NotNull_OnInterface_ImplementedWithoutAttribute() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C : Interface { void Main(string? s) { this.ThrowIfNull(42, s); s.ToString(); // warn ((Interface)this).ThrowIfNull(42, s); s.ToString(); // ok } public void ThrowIfNull(int x, string? s) => throw null!; // warn } public interface Interface { void ThrowIfNull(int x, [NotNull] string? s); } public class C2 : Interface { public void ThrowIfNull(int x, [NotNull] string? s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (12,17): warning CS8767: Nullability of reference types in type of parameter 's' of 'void C.ThrowIfNull(int x, string? s)' doesn't match implicitly implemented member 'void Interface.ThrowIfNull(int x, string? s)' because of nullability attributes. // public void ThrowIfNull(int x, string? s) => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "ThrowIfNull").WithArguments("s", "void C.ThrowIfNull(int x, string? s)", "void Interface.ThrowIfNull(int x, string? s)").WithLocation(12, 17) ); VerifyAnnotationsAndMetadata(c, "Interface.ThrowIfNull", None, NotNull); VerifyAnnotationsAndMetadata(c, "C.ThrowIfNull", None, None); } [Fact] public void NotNull_OnInterface_ImplementedWithAttribute() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C : Interface { void Main(string? s) { ((Interface)this).ThrowIfNull(42, s); s.ToString(); // warn this.ThrowIfNull(42, s); s.ToString(); // ok } public void ThrowIfNull(int x, [NotNull] string? s) => throw null!; } public interface Interface { void ThrowIfNull(int x, string? s); } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); VerifyAnnotationsAndMetadata(c, "Interface.ThrowIfNull", None, None); VerifyAnnotationsAndMetadata(c, "C.ThrowIfNull", None, NotNull); } [Fact] public void NotNull_OnDelegate() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; delegate void D([NotNull] object? o); public class C { void Main(string? s, D d) { d(s); s.ToString(); // ok } } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNull_WithParams() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { static void NotNull([NotNull] params object?[]? args) { } // 0 static void F(object? x, object? y, object[]? a) { NotNull(); a.ToString(); // warn 1 NotNull(x, y); x.ToString(); // warn 2 y.ToString(); // warn 3 NotNull(a); a.ToString(); // ok } } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (5,61): warning CS8777: Parameter 'args' must have a non-null value when exiting. // static void NotNull([NotNull] params object?[]? args) { } // 0 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("args").WithLocation(5, 61), // (9,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(9, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // warn 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(13, 9) ); } [Fact] public void NotNullWhenTrue_WithParams() { CSharpCompilation c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { static bool NotNull([NotNullWhen(true)] params object?[]? args) => throw null!; static void F(object? x, object? y, object[]? a) { if (NotNull()) a.ToString(); // warn 1 if (NotNull(x, y)) { x.ToString(); // warn 2 y.ToString(); // warn 3 } if (NotNull(a)) a.ToString(); } } ", NotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // warn 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(14, 13) ); } [Fact] public void NotNull_WithParamsOnFirstParameter() { CSharpCompilation c = CreateCompilationWithIL(new[] { @" public class D { static void F(object[]? a, object? b, object? c) { C.NotNull(a, b, c); a.ToString(); // ok b.ToString(); // warn 1 c.ToString(); // warn 2 } } " }, @" .class private auto ansi sealed beforefieldinit System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } .method public hidebysig specialname rtspecialname instance void .ctor ( bool[] '' ) cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } } .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig static void NotNull ( object[] args, object[] args2 ) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 01 01 00 00 ) .custom instance void System.Diagnostics.CodeAnalysis.NotNullAttribute::.ctor() = ( 01 00 00 00 ) .param [2] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 01 01 00 00 ) .custom instance void System.Diagnostics.CodeAnalysis.NotNullAttribute::.ctor() = ( 01 00 00 00 ) IL_0000: nop IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } } .class public auto ansi beforefieldinit System.Diagnostics.CodeAnalysis.NotNullAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 00 08 00 00 01 00 54 02 0d 41 6c 6c 6f 77 4d 75 6c 74 69 70 6c 65 00 ) .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(9, 9) ); } [Fact] public void NotNull_WithNamedArguments() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { static void NotNull1([NotNull] object? x = null, object? y = null) => throw null!; static void NotNull2(object? x = null, [NotNull] object? y = null) => throw null!; static void F(object? x) { NotNull1(); NotNull1(y: x); x.ToString(); // warn NotNull2(y: x); x.ToString(); // ok } } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 9) ); } [Fact] public void NotNull_OnDifferentTypes() { CSharpCompilation c = CreateCompilation(@" using System.Diagnostics.CodeAnalysis; public class C { public static void Bad<T>([NotNull] int i) => throw null!; public static void ThrowIfNull<T>([NotNull] T t) => throw null!; } " + NotNullAttributeDefinition); c.VerifyDiagnostics(); VerifyAnnotations(c, "C.Bad", NotNull); VerifyAnnotations(c, "C.ThrowIfNull", NotNull); } [Fact] public void NotNull_GenericMethod() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M<T>(T t) { t.ToString(); // warn ThrowIfNull(t); t.ToString(); // ok } public static void ThrowIfNull<T>([NotNull] T s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(7, 9) ); VerifyAnnotationsAndMetadata(c, "C.ThrowIfNull", NotNull); } [Fact] [WorkItem(30079, "https://github.com/dotnet/roslyn/issues/30079")] public void NotNull_BeginInvoke() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public delegate void Delegate([NotNull] string? s); public class C { void M(Delegate d, string? s) { if (s != string.Empty) s.ToString(); // warn d.BeginInvoke(s, null, null); s.ToString(); } } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,32): warning CS8602: Dereference of a possibly null reference. // if (s != string.Empty) s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 32) ); } [Fact] public void NotNull_BackEffect() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1, string? s2) { ThrowIfNull(s2 = s1, s1); s2.ToString(); // warn } public static void ThrowIfNull(string? x1, [NotNull] string? x2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29865: Should we be able to trace that s2 was assigned a non-null value? c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(8, 9) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void NotNull_InErrorInvocation() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1, string? s2) { Missing(ThrowIfNull(s1, s2 = s1)); s2.ToString(); } public static void ThrowIfNull([NotNull] string? x1, string? x2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): error CS0103: The name 'Missing' does not exist in the current context // Missing(ThrowIfNull(s1, s2 = s1)); Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(8, 9) ); } [Fact] public void NotNull_NoForwardEffect() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1, string? s2) { ThrowIfNull(s1, s2 = s1); s1.ToString(); s2.ToString(); // 1 } public static void ThrowIfNull([NotNull] string? x1, string? x2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); // NotNull is a post-condition so it comes after all the arguments have been evaluated c.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(9, 9) ); } [Fact] public void NotNull_NoForwardEffect2() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1) { ThrowIfNull(s1, s1 = null); s1.ToString(); } public static void ThrowIfNull([NotNull] string? x1, string? x2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNull_NoForwardEffect3() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1, string? s2) { ThrowIfNull(s1 = null, s2 = s1, s1 = """", s1); s2.ToString(); // warn } public static void ThrowIfNull(string? x1, string? x2, string? x3, [NotNull] string? x4) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(8, 9) ); } [Fact] public void NotNullWhenTrue_NoForwardEffect() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1, string? s2) { if (ThrowIfNull(s1, s2 = s1)) { s1.ToString(); s2.ToString(); // 1 } else { s1.ToString(); // 2 s2.ToString(); // 3 } } public static bool ThrowIfNull([NotNullWhen(true)] string? x1, string? x2) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); // NotNullWhen is a post-condition so it comes after all the arguments have been evaluated c.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // s1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(14, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(15, 13) ); } [Fact] [WorkItem(29867, "https://github.com/dotnet/roslyn/issues/29867")] public void NotNull_TypeInference() { // Nullability flow analysis attributes do not affect type inference CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1) { ThrowIfNull(s1, out var s2); s2/*T:string?*/.ToString(); } public static void ThrowIfNull<T>([NotNull] T x1, out T x2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyTypes(); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s2/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(8, 9) ); } [Fact] public void NotNull_ConditionalMethodInReleaseMode() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { ThrowIfNull(42, s); s.ToString(); // ok } [System.Diagnostics.Conditional(""DEBUG"")] static void ThrowIfNull(int x, [NotNull] string? s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNull_SecondArgumentDereferences() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { ThrowIfNull(s, s.ToString()); // warn s.ToString(); // ok } public static void ThrowIfNull([NotNull] string? s, string s2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,24): warning CS8602: Dereference of a possibly null reference. // ThrowIfNull(s, s.ToString()); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 24) ); VerifyAnnotationsAndMetadata(c, "C.ThrowIfNull", NotNull, None); } [Fact] public void NotNull_SecondArgumentAssigns() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { ThrowIfNull(s, s = null); s.ToString(); } static void ThrowIfNull([NotNull] string? s, string? s2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNull_Indexer() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { _ = this[42, s]; s.ToString(); // ok } public int this[int x, [NotNull] string? s] => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectMethodBodies_ReferenceType() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { void M1([AllowNull]string x) { x.ToString(); // 1 } void M2([DisallowNull]string? x) { x.ToString(); x = null; } void M3([MaybeNull]out string x) { x = null; (x, _) = (null, 1); } void M4([NotNull]out string? x) { x = null; (x, _) = (null, 1); } // 2 [return: MaybeNull] string M5() { return null; } [return: NotNull] string? M6() { return null; // 3 } void M7([NotNull]string x) { x = null; // 4 (x, _) = (null, 1); // 5 } // 6 } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9), // (26,5): warning CS8777: Parameter 'x' must have a non-null value when exiting. // } // 2 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("x").WithLocation(26, 5), // (35,16): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(35, 16), // (40,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(40, 13), // (41,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // (x, _) = (null, 1); // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(41, 19), // (42,5): warning CS8777: Parameter 'x' must have a non-null value when exiting. // } // 6 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("x").WithLocation(42, 5) ); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectMethodBodies_NullableValueType() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { void M1([AllowNull]int? x) { x.Value.ToString(); // 1 } void M2([DisallowNull]int? x) { x.Value.ToString(); x = null; } void M3([MaybeNull]out int? x) { x = null; } void M4([NotNull]out int? x) { x = null; } // 2 [return: MaybeNull] int? M5() { return null; } [return: NotNull] int? M6() { return null; // 3 } void M7([NotNull]out int? x) { x = null; return; // 4 } } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8629: Nullable value type may be null. // x.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x", isSuppressed: false).WithLocation(7, 9), // (24,5): warning CS8777: Parameter 'x' must have a non-null value when exiting. // } // 2 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}", isSuppressed: false).WithArguments("x").WithLocation(24, 5), // (33,9): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // return null; // 3 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "return null;", isSuppressed: false).WithLocation(33, 9), // (39,9): warning CS8777: Parameter 'x' must have a non-null value when exiting. // return; // 4 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return;", isSuppressed: false).WithArguments("x").WithLocation(39, 9) ); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectMethodBodies_UnconstrainedGeneric() { var source = @" using System.Diagnostics.CodeAnalysis; public class C<T> { void M1([AllowNull]T x) { x.ToString(); // 1 } void M2([DisallowNull]T x) { x.ToString(); } void M3([MaybeNull]out T x) { x = default; } void M4([NotNull]out T x) { x = default; // 2 } // 3 [return: MaybeNull] T M5() { return default; } [return: NotNull] T M6() { return default; // 4 } } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9), // (22,13): warning CS8601: Possible null reference assignment. // x = default; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(22, 13), // (23,5): warning CS8777: Parameter 'x' must have a non-null value when exiting. // } // 3 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("x").WithLocation(23, 5), // (32,16): warning CS8603: Possible null reference return. // return default; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(32, 16) ); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectPropertyBodies_ReferenceType() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull] string? P1 { get { return null; } set { value.ToString(); } } [AllowNull] string P2 { get { return null; } // 1 set { value.ToString(); } // 2 } [MaybeNull] string P3 { get { return null; } set { value.ToString(); } } [NotNull] string? P4 { get { return null; } // 3 set { value.ToString(); } // 4 } } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,22): warning CS8603: Possible null reference return. // get { return null; } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(13, 22), // (14,15): warning CS8602: Dereference of a possibly null reference. // set { value.ToString(); } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(14, 15), // (25,22): warning CS8603: Possible null reference return. // get { return null; } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(25, 22), // (26,15): warning CS8602: Dereference of a possibly null reference. // set { value.ToString(); } // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(26, 15) ); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectPropertyBodies_ReferenceType_AutoProp() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull] string? P1 { get; set; } = """"; [AllowNull] string P2 { get; set; } = """"; [MaybeNull] string P3 { get; set; } = """"; [NotNull] string? P4 { get; set; } = """"; [DisallowNull] string? P5 { get; set; } = null; // 1 [AllowNull] string P6 { get; set; } = null; [MaybeNull] string P7 { get; set; } = null; // 2 [NotNull] string? P8 { get; set; } = null; } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,47): warning CS8625: Cannot convert null literal to non-nullable reference type. // [DisallowNull] string? P5 { get; set; } = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 47), // (12,43): warning CS8625: Cannot convert null literal to non-nullable reference type. // [MaybeNull] string P7 { get; set; } = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 43) ); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectPropertyBodies_NullableValueType() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull] int? P1 { get { return null; } set { value.Value.ToString(); } } [AllowNull] int? P2 { get { return null; } set { value.Value.ToString(); } // 1 } [MaybeNull] int? P3 { get { return null; } set { value.Value.ToString(); } // 2 } [NotNull] int? P4 { get { return null; } // 3 set { value.Value.ToString(); } // 4 } } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,15): warning CS8629: Nullable value type may be null. // set { value.Value.ToString(); } // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "value").WithLocation(14, 15), // (20,15): warning CS8629: Nullable value type may be null. // set { value.Value.ToString(); } // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "value").WithLocation(20, 15), // (25,15): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // get { return null; } // 3 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "return null;").WithLocation(25, 15), // (26,15): warning CS8629: Nullable value type may be null. // set { value.Value.ToString(); } // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "value").WithLocation(26, 15) ); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectPropertyBodies_UnconstrainedGeneric() { var source = @" using System.Diagnostics.CodeAnalysis; public class C<T> { [DisallowNull] T P1 { get { return default; } // 1 set { value.ToString(); } } [AllowNull] T P2 { get { return default; } // 2 set { value.ToString(); } // 3 } [MaybeNull] T P3 { get { return default; } set { value.ToString(); } // 4 } [NotNull] T P4 { get { return default; } // 5 set { value.ToString(); } // 6 } } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,22): warning CS8603: Possible null reference return. // get { return default; } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(7, 22), // (13,22): warning CS8603: Possible null reference return. // get { return default; } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(13, 22), // (14,15): warning CS8602: Dereference of a possibly null reference. // set { value.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(14, 15), // (20,15): warning CS8602: Dereference of a possibly null reference. // set { value.ToString(); } // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(20, 15), // (25,22): warning CS8603: Possible null reference return. // get { return default; } // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(25, 22), // (26,15): warning CS8602: Dereference of a possibly null reference. // set { value.ToString(); } // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(26, 15) ); } [Fact] public void AllowNull_01() { // Warn on redundant nullability attributes (all except F1)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>([AllowNull]T t) { } static void F2<T>([AllowNull]T t) where T : class { } static void F3<T>([AllowNull]T t) where T : struct { } static void F4<T>([AllowNull]T? t) where T : class { } static void F5<T>([AllowNull]T? t) where T : struct { } static void M1<T>(T t1) { F1(t1); } static void M2<T>(T t2) where T : class { F1(t2); F2(t2); F4(t2); t2 = null; // 1 F1(t2); F2(t2); // 2 F4(t2); } static void M3<T>(T? t3) where T : class { F1(t3); F2(t3); // 3 F4(t3); if (t3 == null) return; F1(t3); F2(t3); F4(t3); } static void M4<T>(T t4) where T : struct { F1(t4); F3(t4); } static void M5<T>(T? t5) where T : struct { F1(t5); F5(t5); if (t5 == null) return; F1(t5); F5(t5); } }"; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }, options: WithNullableEnable()); // The constraint warnings on F2(t2) and F2(t3) are not ideal but expected. comp.VerifyDiagnostics( // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 14), // (20,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(20, 9), // (26,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t3); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(26, 9)); } [Fact] public void AllowNull_WithMaybeNull() { // Warn on misused nullability attributes (AllowNull on type that could be marked with `?`, MaybeNull on an `in` or by-val parameter)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F0<T>([AllowNull, MaybeNull]T t) { } static void F1<T>([AllowNull, MaybeNull]ref T t) { } static void F2<T>([AllowNull, MaybeNull]T t) where T : class { } static void F3<T>([AllowNull, MaybeNull]T t) where T : struct { } static void F4<T>([AllowNull, MaybeNull]T? t) where T : class { } static void F5<T>([AllowNull, MaybeNull]T? t) where T : struct { } static void F6<T>([AllowNull, MaybeNull]in T t) { } static void M<T>(string? s1, string s2) { F0<string>(s1); s1.ToString(); // 1 F0<string>(s2); s2.ToString(); // 2 } static void M_WithRef<T>(string? s1, string s2) { F1<string>(ref s1); s1.ToString(); // 3 F1<string>(ref s2); // 4 s2.ToString(); // 5 } }"; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(15, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(18, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // s1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(23, 9), // (25,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // F1<string>(ref s2); // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s2").WithLocation(25, 24), // (26,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(26, 9) ); } [Fact] public void AllowNull_02() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>([AllowNull]T t) { } static void F2<T>([AllowNull]T t) where T : class { } static void F3<T>([AllowNull]T t) where T : struct { } static void F4<T>([AllowNull]T? t) where T : class { } static void F5<T>([AllowNull]T? t) where T : struct { } static void M1<T>(T t1) { F1<T>(t1); } static void M2<T>(T t2) where T : class { F1<T>(t2); F2<T>(t2); F4<T>(t2); t2 = null; // 1 F1<T>(t2); F2<T>(t2); F4<T>(t2); } static void M3<T>(T? t3) where T : class { F1<T>(t3); F2<T>(t3); F4<T>(t3); if (t3 == null) return; F1<T>(t3); F2<T>(t3); F4<T>(t3); } static void M4<T>(T t4) where T : struct { F1<T>(t4); F3<T>(t4); } static void M5<T>(T? t5) where T : struct { F1<T?>(t5); F5<T>(t5); if (t5 == null) return; F1<T?>(t5); F5<T>(t5); } }"; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 14)); } [Fact] public void AllowNull_03() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([AllowNull]string s) { } static void F2([AllowNull]string? s) { } static void M1(string s1) { F1(s1); F2(s1); s1 = null; // 1 F1(s1); F2(s1); } static void M2(string? s2) { F1(s2); F2(s2); if (s2 == null) return; F1(s2); F2(s2); } }"; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // s1 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(10, 14)); } [Fact] public void AllowNull_RefParameter_03() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([AllowNull]ref string s) { } static void F2([AllowNull]ref string? s) { } static void M1() { string s1 = """"; F1(ref s1); s1.ToString(); string? s2 = """"; F2(ref s2); s2.ToString(); // 1 string s3 = null; // 2 F1(ref s3); s3.ToString(); string? s4 = null; F2(ref s4); s4.ToString(); // 3 } }"; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(14, 9), // (16,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string s3 = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 21), // (22,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(22, 9) ); } [Fact] public void AllowNull_04() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([AllowNull]int i) { } static void F2([AllowNull]int? i) { } static void M1(int i1) { F1(i1); F2(i1); } static void M2(int? i2) { F2(i2); if (i2 == null) return; F2(i2); } }"; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void AllowNull_05() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static void F1<T>(T t) where T : class { } public static void F2<T>([AllowNull]T t) where T : class { } }"; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x); // 2 F1(y); F2(x); // 3 F2(x!); F2(y); } }"; comp = CreateCompilation(source, references: new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(x); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T)", "T", "object?").WithLocation(7, 9), // (9,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T)", "T", "object?").WithLocation(9, 9)); } [Fact] public void AllowNull_01_Property() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [AllowNull]public TOpen P1 { get; set; } = default!; } public class CClass<TClass> where TClass : class { [AllowNull]public TClass P2 { get; set; } = null!; [AllowNull]public TClass? P3 { get; set; } = null; } public class CStruct<TStruct> where TStruct : struct { [AllowNull]public TStruct P4 { get; set; } [AllowNull]public TStruct? P5 { get; set; } }"; var lib = CreateNullableCompilation(new[] { lib_cs, AllowNullAttributeDefinition }); var source = @" class Program { static void M1<T>(T t1) { new COpen<T>().P1 = t1; } static void M2<T>(T t2) where T : class { new COpen<T>().P1 = t2; new CClass<T>().P2 = t2; new CClass<T>().P3 = t2; t2 = null; // 1 new COpen<T>().P1 = t2; new CClass<T>().P2 = t2; new CClass<T>().P3 = t2; var xOpen = new COpen<T>(); xOpen.P1 = null; xOpen.P1.ToString(); var xClass = new CClass<T>(); xClass.P2 = null; xClass.P2.ToString(); xClass.P3 = null; xClass.P3.ToString(); // 2 } static void M3<T>(T? t3) where T : class { new COpen<T>().P1 = t3; new CClass<T>().P2 = t3; new CClass<T>().P3 = t3; if (t3 == null) return; new COpen<T>().P1 = t3; new CClass<T>().P2 = t3; new CClass<T>().P3 = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>().P1 = t4; new CStruct<T>().P4 = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>().P1 = t5; new CStruct<T>().P5 = t5; if (t5 == null) return; new COpen<T?>().P1 = t5; new CStruct<T>().P5 = t5; } }"; var expected = new[] { // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 14), // (26,9): warning CS8602: Dereference of a possibly null reference. // xClass.P3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xClass.P3").WithLocation(26, 9) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, AllowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void AllowNull_Property_WithNotNull() { var source = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [AllowNull, NotNull]public TOpen P1 { get; set; } = default!; } public class CClass<TClass> where TClass : class { [AllowNull, NotNull]public TClass P2 { get; set; } = null!; [AllowNull, NotNull]public TClass? P3 { get; set; } = null; } public class CStruct<TStruct> where TStruct : struct { [AllowNull, NotNull]public TStruct? P5 { get; set; } } class Program { static void M1<T>([MaybeNull]T t1) { var xOpen = new COpen<T>(); xOpen.P1 = t1; xOpen.P1.ToString(); } static void M2<T>(T t2) where T : class { var xOpen = new COpen<T>(); xOpen.P1 = null; xOpen.P1.ToString(); var xClass = new CClass<T>(); xClass.P2 = null; xClass.P2.ToString(); xClass.P3 = null; xClass.P3.ToString(); } static void M5<T>(T? t5) where T : struct { var xOpen = new COpen<T?>(); xOpen.P1 = null; xOpen.P1.ToString(); var xStruct = new CStruct<T>(); xStruct.P5 = null; xStruct.P5.Value.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void AllowNull_Property_WithNotNull_NoSuppression() { var source = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [AllowNull, NotNull]public TOpen P1 { get; set; } = default; } public class CNotNull<TNotNull> where TNotNull : notnull { [AllowNull, NotNull]public TNotNull P1 { get; set; } = default; } public class CClass<TClass> where TClass : class { [AllowNull, NotNull]public TClass P2 { get; set; } = null; }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void AllowNull_Property_InCompoundAssignment() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [AllowNull] public C P { get; set; } public static C? operator +(C? x, C? y) => throw null!; }"; var lib = CreateNullableCompilation(new[] { lib_cs, AllowNullAttributeDefinition }); lib.VerifyDiagnostics( ); var source = @" class Program { static void M(C c) { c.P += null; c.P.ToString(); } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39966, "https://github.com/dotnet/roslyn/issues/39966")] public void AllowNull_Property_InObjectInitializer() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [AllowNull] public C P { get; set; } } class Program { static void M(C c1) { c1.P = null; new C { P = null }; } }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39966, "https://github.com/dotnet/roslyn/issues/39966")] public void AllowNull_Field_InObjectInitializer() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [AllowNull] public C F; } class Program { static void M(C c1) { c1.F = null; new C { F = null }; } }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39966, "https://github.com/dotnet/roslyn/issues/39966")] public void DisallowNull_Property_InObjectInitializer() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull] public C? P { get; set; } } class Program { static void M(C c1) { c1.P = null; // 1 new C { P = null // 2 }; } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (12,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // c1.P = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 16), // (16,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // P = null // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 17)); } [Fact, WorkItem(39966, "https://github.com/dotnet/roslyn/issues/39966")] public void DisallowNull_Field_InObjectInitializer() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull] public C? F; } class Program { static void M(C c1) { c1.F = null; // 1 new C { F = null // 2 }; } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (12,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // c1.F = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 16), // (16,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 17)); } [Fact] public void AllowNull_Property_InDeconstructionAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [AllowNull] public C P { get; set; } = null; } class Program { void M(C c) { (c.P, _) = (null, 1); c.P.ToString(); ((c.P, _), _) = ((null, 1), 2); c.P.ToString(); (c.P, _) = this; c.P.ToString(); ((_, c.P), _) = (this, 1); c.P.ToString(); } void Deconstruct(out C? x, out C? y) => throw null!; }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void AllowNull_Field() { // Warn on misused nullability attributes (f3, f4, f5)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [AllowNull]public TOpen f1 = default!; } public class CClass<TClass> where TClass : class { [AllowNull]public TClass f2 = null; [AllowNull]public TClass? f3 = null; } public class CStruct<TStruct> where TStruct : struct { [AllowNull]public TStruct f4; [AllowNull]public TStruct? f5; } "; var lib = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, lib_cs }); var source = @" using System.Diagnostics.CodeAnalysis; class C { static void M1<T>([MaybeNull] T t1) { new COpen<T>().f1 = t1; } static void M2<T>(T t2) where T : class { new COpen<T>().f1 = t2; new CClass<T>().f2 = t2; new CClass<T>().f3 = t2; t2 = null; // 1 new COpen<T>().f1 = t2; new CClass<T>().f2 = t2; new CClass<T>().f3 = t2; var xOpen = new COpen<T>(); xOpen.f1 = null; xOpen.f1.ToString(); // 2 var xClass = new CClass<T>(); xClass.f2 = null; xClass.f2.ToString(); // 3 xClass.f3 = null; xClass.f3.ToString(); // 4 } static void M3<T>(T? t3) where T : class { new COpen<T>().f1 = t3; new CClass<T>().f2 = t3; new CClass<T>().f3 = t3; if (t3 == null) return; new COpen<T>().f1 = t3; new CClass<T>().f2 = t3; new CClass<T>().f3 = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>().f1 = t4; new CStruct<T>().f4 = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>().f1 = t5; new CStruct<T>().f5 = t5; if (t5 == null) return; new COpen<T?>().f1 = t5; new CStruct<T>().f5 = t5; } }"; var expected = new[] { // (14,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 14), // (21,9): warning CS8602: Dereference of a possibly null reference. // xOpen.f1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xOpen.f1").WithLocation(21, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // xClass.f2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xClass.f2").WithLocation(25, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // xClass.f3.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xClass.f3").WithLocation(27, 9) }; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var field = copen.GetMembers().OfType<FieldSymbol>().Single(); var fieldAttributes = field.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.AllowNullAttribute" }, fieldAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableAttribute(1)", "System.Diagnostics.CodeAnalysis.AllowNullAttribute" }, fieldAttributes); } } } [Fact] public void AllowNull_Field_NullInitializer() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [AllowNull]public string field = null; string M() => field.ToString(); } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void AllowNull_Operator_CompoundAssignment() { var source = @" using System.Diagnostics.CodeAnalysis; class CLeft { CLeft? Property { get; set; } public static CLeft? operator+([AllowNull] CLeft one, CLeft other) => throw null!; void M(CLeft c, CLeft? c2) { Property += c; Property += c2; // 1 } } class CRight { CRight Property { get { throw null!; } set { throw null!; } } // note not annotated public static CRight operator+(CRight one, [AllowNull] CRight other) => throw null!; void M(CRight c, CRight? c2) { Property += c; Property += c2; } } class CNone { CNone? Property { get; set; } public static CNone? operator+(CNone one, CNone other) => throw null!; void M(CNone c, CNone? c2) { Property += c; // 2 Property += c2; // 3, 4 } }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,21): warning CS8604: Possible null reference argument for parameter 'other' in 'CLeft? CLeft.operator +(CLeft one, CLeft other)'. // Property += c2; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c2").WithArguments("other", "CLeft? CLeft.operator +(CLeft one, CLeft other)").WithLocation(11, 21), // (32,9): warning CS8604: Possible null reference argument for parameter 'one' in 'CNone? CNone.operator +(CNone one, CNone other)'. // Property += c; // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "Property").WithArguments("one", "CNone? CNone.operator +(CNone one, CNone other)").WithLocation(32, 9), // (33,9): warning CS8604: Possible null reference argument for parameter 'one' in 'CNone? CNone.operator +(CNone one, CNone other)'. // Property += c2; // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "Property").WithArguments("one", "CNone? CNone.operator +(CNone one, CNone other)").WithLocation(33, 9), // (33,21): warning CS8604: Possible null reference argument for parameter 'other' in 'CNone? CNone.operator +(CNone one, CNone other)'. // Property += c2; // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c2").WithArguments("other", "CNone? CNone.operator +(CNone one, CNone other)").WithLocation(33, 21) ); } [Fact] public void AllowNull_01_Indexer() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [AllowNull]public TOpen this[int i] { set => throw null!; } } public class CClass<TClass> where TClass : class { [AllowNull]public TClass this[int i] { set => throw null!; } } public class CClass2<TClass> where TClass : class { [AllowNull]public TClass? this[int i] { set => throw null!; } } public class CStruct<TStruct> where TStruct : struct { [AllowNull]public TStruct this[int i] { set => throw null!; } } public class CStruct2<TStruct> where TStruct : struct { [AllowNull]public TStruct? this[int i] { set => throw null!; } }"; var lib = CreateNullableCompilation(new[] { lib_cs, AllowNullAttributeDefinition }); var source = @" class Program { static void M1<T>(T t1) { new COpen<T>()[0] = t1; } static void M2<T>(T t2) where T : class { new COpen<T>()[0] = t2; new CClass<T>()[0] = t2; new CClass2<T>()[0] = t2; t2 = null; // 1 new COpen<T>()[0] = t2; new CClass<T>()[0] = t2; new CClass2<T>()[0] = t2; } static void M3<T>(T? t3) where T : class { new COpen<T>()[0] = t3; new CClass<T>()[0] = t3; new CClass2<T>()[0] = t3; if (t3 == null) return; new COpen<T>()[0] = t3; new CClass<T>()[0] = t3; new CClass2<T>()[0] = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>()[0] = t4; new CStruct<T>()[0] = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>()[0] = t5; new CStruct2<T>()[0] = t5; if (t5 == null) return; new COpen<T?>()[0] = t5; new CStruct2<T>()[0] = t5; } }"; var expected = new[] { // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 14) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, AllowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var copenAttributes = copen.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(copenAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableContextAttribute(1)", "System.Runtime.CompilerServices.NullableAttribute(0)", "System.Reflection.DefaultMemberAttribute(\"Item\")" }, copenAttributes); } var property = copen.GetMembers().OfType<PropertySymbol>().Single(); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.AllowNullAttribute" }, propertyAttributes); } else { AssertEx.Empty(propertyAttributes); } var setter = property.SetMethod; var setterAttributes = setter.GetAttributes(); AssertEx.Empty(setterAttributes); var setterValueAttributes = setter.Parameters.Last().GetAttributes().Select(a => a.ToString()); Assert.Equal(FlowAnalysisAnnotations.AllowNull, setter.Parameters.Last().FlowAnalysisAnnotations); if (isSource) { AssertEx.Empty(setterValueAttributes); } else { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.AllowNullAttribute" }, setterValueAttributes); } Assert.Equal(FlowAnalysisAnnotations.None, setter.ReturnTypeFlowAnalysisAnnotations); var setterReturnAttributes = setter.GetReturnTypeAttributes(); AssertEx.Empty(setterReturnAttributes); } } [Fact] public void AllowNull_01_Indexer_WithDisallowNull() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [AllowNull, DisallowNull]public TOpen this[int i] { set => throw null!; } }"; var comp = CreateNullableCompilation(new[] { lib_cs, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics(); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var copenAttributes = copen.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(copenAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableContextAttribute(1)", "System.Runtime.CompilerServices.NullableAttribute(0)", "System.Reflection.DefaultMemberAttribute(\"Item\")" }, copenAttributes); } var property = copen.GetMembers().OfType<PropertySymbol>().Single(); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.AllowNullAttribute", "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" }, propertyAttributes); } else { AssertEx.Empty(propertyAttributes); } var setter = property.SetMethod; var setterAttributes = setter.GetAttributes(); AssertEx.Empty(setterAttributes); var setterValueAttributes = setter.Parameters.Last().GetAttributes().Select(a => a.ToString()); Assert.Equal(FlowAnalysisAnnotations.AllowNull | FlowAnalysisAnnotations.DisallowNull, setter.Parameters.Last().FlowAnalysisAnnotations); if (isSource) { AssertEx.Empty(setterValueAttributes); } else { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.DisallowNullAttribute", "System.Diagnostics.CodeAnalysis.AllowNullAttribute" }, setterValueAttributes); } } } [Fact] public void AllowNull_Indexer_OtherParameters() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public string this[[AllowNull] string s] { set => throw null!; } } "; var lib = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new C()[s] = s2; new C()[s2] = s2; } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, AllowNullAttributeDefinition }); comp2.VerifyDiagnostics(); } [Fact] public void AllowNull_Indexer_OtherParameters_OverridingSetter() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual string this[[AllowNull] string s] { set => throw null!; } } public class C : Base { public override string this[string s] { set => throw null!; } } "; var lib = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new C()[s] = s2; // 1 new C()[s2] = s2; } }"; var expected = new[] { // (6,17): warning CS8604: Possible null reference argument for parameter 's' in 'string C.this[string s]'. // new C()[s] = s2; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s").WithArguments("s", "string C.this[string s]").WithLocation(6, 17) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, AllowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void AllowNull_DoesNotAffectTypeInference() { var source = @"using System.Diagnostics.CodeAnalysis; public class A { public static void F1<T>(T t, T t2) where T : class { } public static void F2<T>([AllowNull]T t, T t2) where T : class { } static void Main() { object x = null; // 1 object? y = new object(); F1(x, x); // 2 F1(x, y); // 3 F1(y, y); F1(y, x); // 4 F2(x, x); // 5 F2(x, y); // 6 F2(y, y); F2(y, x); // 7 F2(x, x!); // 8 F2(x!, x); // 9 F2(x!, y); F2(y, x!); } }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (8,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 20), // (10,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(x, x); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T, T)", "T", "object?").WithLocation(10, 9), // (11,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(x, y); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T, T)", "T", "object?").WithLocation(11, 9), // (13,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(y, x); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T, T)", "T", "object?").WithLocation(13, 9), // (15,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x, x); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T, T)", "T", "object?").WithLocation(15, 9), // (16,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x, y); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T, T)", "T", "object?").WithLocation(16, 9), // (18,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(y, x); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T, T)", "T", "object?").WithLocation(18, 9), // (20,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x, x!); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T, T)", "T", "object?").WithLocation(20, 9), // (21,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x!, x); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T, T)", "T", "object?").WithLocation(21, 9) ); } [Fact] public void AllowNull_Parameter_Generic() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) => throw null!; public virtual void F2<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : class => throw null!; public virtual void F3<T>([AllowNull]T? t1, [AllowNull] out T? t2, [AllowNull] ref T? t3, [AllowNull] in T? t4) where T : class => throw null!; public virtual void F4<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : struct => throw null!; public virtual void F5<T>([AllowNull]T? t1, [AllowNull] out T? t2, [AllowNull] ref T? t3, [AllowNull] in T? t4) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(12, 26), // (12,26): error CS8762: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (12,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(12, 26), // (13,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(13, 26), // (13,26): error CS8762: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t3").WithLocation(13, 26), // (13,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(13, 26) ); } [Fact] public void AllowNull_Parameter_Generic_ObliviousBase() { var source = @"using System.Diagnostics.CodeAnalysis; #nullable disable public class Base { public virtual void F1<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) => throw null!; public virtual void F2<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : class => throw null!; public virtual void F4<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : struct => throw null!; } #nullable enable public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; } "; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(12, 26), // (12,26): warning CS8765: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (12,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(12, 26), // (13,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(13, 26), // (13,26): warning CS8765: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t3").WithLocation(13, 26), // (13,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(13, 26) ); } [Fact] public void AllowNull_Parameter_Generic_ObliviousDerived() { var source = @"using System.Diagnostics.CodeAnalysis; #nullable enable public class Base { public virtual void F1<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) => throw null!; public virtual void F2<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : class => throw null!; public virtual void F4<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : struct => throw null!; public virtual void F5<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : notnull => throw null!; } #nullable disable public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public override void F5<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; } "; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void AllowNull_Parameter_Generic_OnOverrides() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public virtual void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public virtual void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public virtual void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public virtual void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; public virtual void F6<T>(T t1, out T t2, ref T t3, in T t4) where T : notnull=> throw null!; } public class Derived : Base { public override void F1<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) => throw null!; public override void F2<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : class => throw null!; public override void F3<T>([AllowNull]T? t1, [AllowNull] out T? t2, [AllowNull] ref T? t3, [AllowNull] in T? t4) where T : class => throw null!; public override void F4<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : struct => throw null!; public override void F5<T>([AllowNull]T? t1, [AllowNull] out T? t2, [AllowNull] ref T? t3, [AllowNull] in T? t4) where T : struct => throw null!; public override void F6<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) => throw null!; } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void UnannotatedParam_UpdatesArgumentState() { var source = @" public class Program { void M0(string s0) { } void M1(string? s1) { M0(s1); // 1 _ = s1.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,12): warning CS8604: Possible null reference argument for parameter 's0' in 'void Program.M0(string s0)'. // M0(s1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s1").WithArguments("s0", "void Program.M0(string s0)").WithLocation(8, 12) ); } [Fact] public void UnannotatedTypeArgument_UpdatesArgumentState() { var source = @" public class Program { void M0<T>(T t) { } void M1<T>(T? t) where T : class { M0<T>(t); // 1 _ = t.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.M0<T>(T t)'. // M0<T>(t); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("t", "void Program.M0<T>(T t)").WithLocation(8, 15) ); } [Fact] public void UnannotatedTypeArgument_NullableClassConstrained_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0<T>(T t) { } void M1<T>(T t) where T : class? { M0(t); _ = t.ToString(); // 1 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(9, 13) ); } [Fact] public void UnannotatedParam_SuppressedArgument_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0(string s0) { } void M1(string? s1) { M0(s1!); _ = s1.ToString(); // 1 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 13) ); } [Fact] public void AnnotatedParam_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0(string? s0) { } void M1(string? s1) { M0(s1); _ = s1.ToString(); // 1 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 13) ); } [Fact] public void Params_AnnotatedElement_UnannotatedArray_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0(params string?[] s0) { } void M1(string? s1) { M0(s1); _ = s1.ToString(); // 1 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 13) ); } [Fact] public void Params_UnannotatedElement_AnnotatedArray_UpdatesArgumentState() { var source = @" public class Program { void M0(params string[]? s0) { } void M1(string? s1) { M0(s1); // 1 _ = s1.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,12): warning CS8604: Possible null reference argument for parameter 's0' in 'void Program.M0(params string[]? s0)'. // M0(s1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s1").WithArguments("s0", "void Program.M0(params string[]? s0)").WithLocation(8, 12) ); } [Fact] public void ObliviousParam_DoesNotUpdateArgumentState() { var source = @" public class Program { #nullable disable void M0(string s0) { } #nullable enable void M1(string? s1) { M0(s1); _ = s1.ToString(); // 1 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(10, 13) ); } [Fact] public void UnannotatedParam_MaybeNull_UpdatesArgumentState() { var source = @" using System.Diagnostics.CodeAnalysis; public class Program { void M0([MaybeNull] string s0) { } void M1(string s1) { M0(s1); _ = s1.ToString(); // 1 } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(11, 13) ); } [Fact] public void UnannotatedParam_MaybeNullWhen_UpdatesArgumentState() { var source = @" using System.Diagnostics.CodeAnalysis; public class Program { bool M0([MaybeNullWhen(true)] string s0) => false; void M1(string s1) { M0(s1); _ = s1.ToString(); // 1 } void M2(string s1) { _ = M0(s1) ? s1.ToString() // 2 : s1.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(11, 13), // (17,15): warning CS8602: Dereference of a possibly null reference. // ? s1.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(17, 15) ); } [Fact] public void AnnotatedParam_DisallowNull_UpdatesArgumentState() { var source = @" using System.Diagnostics.CodeAnalysis; public class Program { void M0([DisallowNull] int? i) { } void M1(int? i1) { M0(i1); // 1 _ = i1.Value.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,12): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // M0(i1); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "i1").WithLocation(10, 12) ); } [Fact] public void AnnotatedTypeParam_DisallowNull_UpdatesArgumentState() { var source = @" using System.Diagnostics.CodeAnalysis; public class Program<T> { void M0([DisallowNull] T? t) { } void M1(T t) { M0(t); // 1 _ = t.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,12): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // M0(t); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(10, 12) ); } [Fact] public void UnconstrainedTypeParam_ArgumentStateUpdatedToNotNull_01() { var source = @" public class Program<T> { void M0(T t) { } void M1() { T t = default; M0(t); // 1 M0(t); _ = t.ToString(); } } "; var comp = CreateNullableCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,12): warning CS8604: Possible null reference argument for parameter 't' in 'void Program<T>.M0(T t)'. // M0(t); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("t", "void Program<T>.M0(T t)").WithLocation(9, 12)); } [Fact] public void UnconstrainedTypeParam_ArgumentStateUpdatedToNotNull_02() { var source = @" public interface IHolder<T> { T Value { get; } } public class Program<T> where T : class?, IHolder<T?>? { void M0(T t) { } void M1() { T? t = default; M0(t?.Value); // 1 M0(t); _ = t.ToString(); M0(t.Value); _ = t.Value.ToString(); } void M2() { T? t = default; M0(t); // 2 M0(t); _ = t.ToString(); M0(t.Value); // 3 M0(t.Value); _ = t.Value.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (14,12): warning CS8604: Possible null reference argument for parameter 't' in 'void Program<T>.M0(T t)'. // M0(t?.Value); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t?.Value").WithArguments("t", "void Program<T>.M0(T t)").WithLocation(14, 12), // (24,12): warning CS8604: Possible null reference argument for parameter 't' in 'void Program<T>.M0(T t)'. // M0(t); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("t", "void Program<T>.M0(T t)").WithLocation(24, 12), // (27,12): warning CS8604: Possible null reference argument for parameter 't' in 'void Program<T>.M0(T t)'. // M0(t.Value); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t.Value").WithArguments("t", "void Program<T>.M0(T t)").WithLocation(27, 12) ); } [Fact, WorkItem(50602, "https://github.com/dotnet/roslyn/issues/50602")] public void UnconstrainedTypeParam_ArgumentStateUpdatedToNotNull_DisallowNull() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C1<T> { void M1(T t) { Test(t); // 1 Test(t); } void M2([AllowNull] T t) { Test(t); // 2 Test(t); } public void Test([DisallowNull] T s) { } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,14): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // Test(t); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(9, 14), // (15,14): warning CS8604: Possible null reference argument for parameter 's' in 'void C1<T>.Test(T s)'. // Test(t); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("s", "void C1<T>.Test(T s)").WithLocation(15, 14) ); } [Fact] [WorkItem(48605, "https://github.com/dotnet/roslyn/issues/48605")] [WorkItem(48134, "https://github.com/dotnet/roslyn/issues/48134")] [WorkItem(49136, "https://github.com/dotnet/roslyn/issues/49136")] public void AllowNullInputParam_DoesNotUpdateArgumentState() { var source = @" using System.Diagnostics.CodeAnalysis; public static class Program { public static void M1(string? s) { MExt(s); s.ToString(); // 1 } public static void M2(string? s) { s.MExt(); s.ToString(); // 2 } public static void M3(string? s) { C c = s; s.ToString(); // 3 } public static void MExt([AllowNull] this string s) { } public class C { public static implicit operator C([AllowNull] string s) => new C(); } } "; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(21, 9)); } [Fact] [WorkItem(48605, "https://github.com/dotnet/roslyn/issues/48605")] [WorkItem(48134, "https://github.com/dotnet/roslyn/issues/48134")] [WorkItem(49136, "https://github.com/dotnet/roslyn/issues/49136")] public void AllowNullNotNullInputParam_UpdatesArgumentState() { var source = @" using System.Diagnostics.CodeAnalysis; public static class Program { public static void M1(string? s) { MExt(s); s.ToString(); } public static void M2(string? s) { s.MExt(); s.ToString(); } public static void M3(string? s) { C c = s; s.ToString(); // 1 } public static void MExt([AllowNull, NotNull] this string s) { throw null!; } public class C { public static implicit operator C([AllowNull, NotNull] string s) { throw null!; } } } "; // we should respect postconditions on a conversion parameter // https://github.com/dotnet/roslyn/issues/49575 var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (21,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(21, 9)); } [Fact] [WorkItem(49136, "https://github.com/dotnet/roslyn/issues/49136")] public void DisallowNullInputParam_UpdatesArgumentState() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M1(int? x) { C c = x; // 1 Method(x); } void M2(int? x) { Method(x); // 2 C c = x; } void Method([DisallowNull] int? t) { } public static implicit operator C([DisallowNull] int? s) => new C(); } "; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,15): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // C c = x; // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "x").WithLocation(9, 15), // (15,16): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // Method(x); // 2 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "x").WithLocation(15, 16)); } [Fact] public void NotNullTypeParam_UpdatesArgumentState() { var source = @" public class Program<T> where T : notnull { void M0(T t) { } void M1() { T t = default; M0(t); // 2 _ = t.ToString(); } } "; var comp = CreateNullableCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,12): warning CS8604: Possible null reference argument for parameter 't' in 'void Program<T>.M0(T t)'. // M0(t); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("t", "void Program<T>.M0(T t)").WithLocation(9, 12) ); } [Fact] public void NotNullConstrainedParam_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0<T>(T t) where T : notnull { } void M1(string? s) { M0(s); // 1 _ = s.ToString(); // 2 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'Program.M0<T>(T)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M0(s); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M0").WithArguments("Program.M0<T>(T)", "T", "string?").WithLocation(8, 9), // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullConstrainedParam_SuppressedArgument_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0<T>(T t) where T : notnull { } void M1(string? s) { M0(s!); _ = s.ToString(); // 1 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void Params_NotNullConstrainedElement_AnnotatedArray_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0<T>(params T[]? s0) where T : notnull { } void M1(string? s1) { M0(s1); // 1 _ = s1.ToString(); // 2 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'Program.M0<T>(params T[]?)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M0(s1); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M0").WithArguments("Program.M0<T>(params T[]?)", "T", "string?").WithLocation(8, 9), // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 13) ); } [Fact] public void Params_NotNullTypeArgument_AnnotatedArray_UpdatesArgumentState() { var source = @" public class Program { void M0<T>(params T[]? s0) where T : notnull { } void M1(string? s1) { M0<string>(s1); // 1 _ = s1.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,20): warning CS8604: Possible null reference argument for parameter 's0' in 'void Program.M0<string>(params string[]? s0)'. // M0<string>(s1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s1").WithArguments("s0", "void Program.M0<string>(params string[]? s0)").WithLocation(8, 20) ); } [Fact] public void NotNull_Parameter_Generic() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) => throw null!; public virtual void F2<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : class => throw null!; public virtual void F3<T>([NotNull]T? t1, [NotNull] out T? t2, [NotNull] ref T? t3, [NotNull] in T? t4) where T : class => throw null!; public virtual void F4<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : struct => throw null!; public virtual void F5<T>([NotNull]T? t1, [NotNull] out T? t2, [NotNull] ref T? t3, [NotNull] in T? t4) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t2, t3, t4 public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t2, t3, t4 public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t2, t3, t4 } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(12, 26), // (12,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(12, 26), // (12,26): error CS8762: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (12,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(12, 26), // (13,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(13, 26), // (13,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(13, 26), // (14,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t1").WithLocation(14, 26), // (14,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t2").WithLocation(14, 26), // (14,26): error CS8762: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t3").WithLocation(14, 26), // (14,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t4").WithLocation(14, 26), // (15,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t1").WithLocation(15, 26), // (15,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t4").WithLocation(15, 26), // (16,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t1").WithLocation(16, 26), // (16,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t2").WithLocation(16, 26), // (16,26): error CS8762: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t3").WithLocation(16, 26), // (16,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t4").WithLocation(16, 26) ); } [Fact] public void NotNullWhenTrue_Parameter_Generic() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>([NotNullWhen(true)]T t1, [NotNullWhen(true)] out T t2, [NotNullWhen(true)] ref T t3, [NotNullWhen(true)] in T t4) => throw null!; public virtual bool F2<T>([NotNullWhen(true)]T t1, [NotNullWhen(true)] out T t2, [NotNullWhen(true)] ref T t3, [NotNullWhen(true)] in T t4) where T : class => throw null!; public virtual bool F3<T>([NotNullWhen(true)]T? t1, [NotNullWhen(true)] out T? t2, [NotNullWhen(true)] ref T? t3, [NotNullWhen(true)] in T? t4) where T : class => throw null!; public virtual bool F4<T>([NotNullWhen(true)]T t1, [NotNullWhen(true)] out T t2, [NotNullWhen(true)] ref T t3, [NotNullWhen(true)] in T t4) where T : struct => throw null!; public virtual bool F5<T>([NotNullWhen(true)]T? t1, [NotNullWhen(true)] out T? t2, [NotNullWhen(true)] ref T? t3, [NotNullWhen(true)] in T? t4) where T : struct => throw null!; } public class Derived : Base { public override bool F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t2, t3 public override bool F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public override bool F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t2, t3 public override bool F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public override bool F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t2, t3 } "; var comp = CreateNullableCompilation(new[] { NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): warning CS8765: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override bool F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(12, 26), // (12,26): warning CS8765: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override bool F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (14,26): warning CS8765: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override bool F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t2").WithLocation(14, 26), // (14,26): warning CS8765: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override bool F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t3").WithLocation(14, 26), // (16,26): warning CS8765: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override bool F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t2").WithLocation(16, 26), // (16,26): warning CS8765: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override bool F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t3").WithLocation(16, 26) ); } [Fact, WorkItem(42470, "https://github.com/dotnet/roslyn/issues/42470")] public void NotNullWhenTrue_Variance() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; interface I<T> { bool TryRead([MaybeNullWhen(false)] out T item); } class C : I<int[]> { public bool TryRead([NotNullWhen(true)] out int[]? item) => throw null!; } ", MaybeNullWhenAttributeDefinition, NotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(42470, "https://github.com/dotnet/roslyn/issues/42470")] public void MaybeNull_Variance() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; interface I<T> { [return: MaybeNull] T Get(); } class C : I<object> { public object? Get() => null!; } ", MaybeNullAttributeDefinition }); c.VerifyDiagnostics(); } [Fact] public void NotNull_Parameter_Generic_ObliviousBase() { var source = @"using System.Diagnostics.CodeAnalysis; #nullable disable public class Base { public virtual void F1<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) => throw null!; public virtual void F2<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : class => throw null!; public virtual void F4<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : struct => throw null!; } #nullable enable public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 } "; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(13, 26), // (13,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(13, 26), // (14,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(14, 26), // (14,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(14, 26), // (15,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t1").WithLocation(15, 26), // (15,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t4").WithLocation(15, 26) ); } [Fact] public void NotNull_Parameter_Generic_ObliviousDerived() { var source = @"using System.Diagnostics.CodeAnalysis; #nullable enable public class Base { public virtual void F1<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) => throw null!; public virtual void F2<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : class => throw null!; public virtual void F4<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : struct => throw null!; } #nullable disable annotations public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 } #nullable disable public class Derived2 : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; } "; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(13, 26), // (13,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(13, 26), // (14,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(14, 26), // (14,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(14, 26), // (15,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t1").WithLocation(15, 26), // (15,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t4").WithLocation(15, 26) ); } [Fact, WorkItem(40139, "https://github.com/dotnet/roslyn/issues/40139")] public void DisallowNull_EnforcedInMethodBody() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C<T> { object _f; C([DisallowNull]T t) { _f = t; } } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_MaybeNullWhen() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<T> { static void GetValue(T x, [MaybeNull] out T y) { y = x; } static bool TryGetValue(T x, [MaybeNullWhen(true)] out T y) { y = x; return y == null; } static bool TryGetValue2(T x, [MaybeNullWhen(true)] out T y) { y = x; return y != null; } static bool TryGetValue3(T x, [MaybeNullWhen(false)] out T y) { y = x; return y == null; } static bool TryGetValue4(T x, [MaybeNullWhen(false)] out T y) { y = x; return y != null; } } "; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Theory] [InlineData("TClass")] [InlineData("TNotNull")] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_MaybeNullWhen_NotNullableTypes(string type) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<TClass, TNotNull> where TClass : class where TNotNull : notnull { static bool TryGetValue(TYPE x, [MaybeNullWhen(true)] out TYPE y) { y = x; return y == null; } static bool TryGetValue2(TYPE x, [MaybeNullWhen(true)] out TYPE y) { y = x; return y != null; // 1 } static bool TryGetValue3(TYPE x, [MaybeNullWhen(false)] out TYPE y) { y = x; return y == null; // 2 } static bool TryGetValue4(TYPE x, [MaybeNullWhen(false)] out TYPE y) { y = x; return y != null; } } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, source.Replace("TYPE", type) }); comp.VerifyDiagnostics( // (18,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'false'. // return y != null; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return y != null;").WithArguments("y", "false").WithLocation(18, 9), // (24,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'true'. // return y == null; // 2 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return y == null;").WithArguments("y", "true").WithLocation(24, 9) ); } [Theory] [InlineData("T")] [InlineData("TClass")] [InlineData("TNotNull")] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_MaybeNullWhen_MaybeDefaultValue(string type) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<T, TClass, TNotNull> where TClass : class where TNotNull : notnull { static void GetValue([AllowNull] TYPE x, [MaybeNull] out TYPE y) { y = x; } static bool TryGetValue([AllowNull] TYPE x, [MaybeNullWhen(true)] out TYPE y) { y = x; return y == null; } static bool TryGetValue2([AllowNull] TYPE x, [MaybeNullWhen(true)] out TYPE y) { y = x; return y != null; // 1 } static bool TryGetValue3([AllowNull] TYPE x, [MaybeNullWhen(false)] out TYPE y) { y = x; return y == null; // 2 } static bool TryGetValue4([AllowNull] TYPE x, [MaybeNullWhen(false)] out TYPE y) { y = x; return y != null; } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, MaybeNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source.Replace("TYPE", type) }); comp.VerifyDiagnostics( // (24,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'false'. // return y != null; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return y != null;").WithArguments("y", "false").WithLocation(24, 9), // (30,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'true'. // return y == null; // 2 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return y == null;").WithArguments("y", "true").WithLocation(30, 9) ); } [Theory] [InlineData("T")] [InlineData("TClass")] [InlineData("TNotNull")] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_MaybeNullWhen_Composition(string type) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<T, TClass, TNotNull> where TClass : class where TNotNull : notnull { static void GetValue([AllowNull] TYPE x, [MaybeNull] out TYPE y) { GetValue(x, out y); } static bool TryGetValue([AllowNull] TYPE x, [MaybeNullWhen(true)] out TYPE y) { return TryGetValue(x, out y); } static bool TryGetValue3([AllowNull] TYPE x, [MaybeNullWhen(false)] out TYPE y) { return TryGetValue3(x, out y); } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, MaybeNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source.Replace("TYPE", type) }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_MaybeNullWhen_Composition_ImplementWithNotNullWhen() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { bool TryGetValue([MaybeNullWhen(true)] out string y) { return TryGetValueCore(out y); } bool TryGetValue2([MaybeNullWhen(true)] out string y) { return !TryGetValueCore(out y); // 1 } bool TryGetValueCore([NotNullWhen(false)] out string? y) { throw null!; } } "; var comp = CreateNullableCompilation(new[] { NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (15,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'false'. // return !TryGetValueCore(out y); // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return !TryGetValueCore(out y);").WithArguments("y", "false").WithLocation(15, 9) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_MaybeNullWhen_TwoParameter() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class Program { static bool TryGetValue<T>([AllowNull]T x, [MaybeNullWhen(true)]out T y, [MaybeNullWhen(true)]out T z) { y = x; z = x; return y != null || z != null; } static bool TryGetValue2<T>([AllowNull]T x, [MaybeNullWhen(false)]out T y, [MaybeNullWhen(false)]out T z) { y = x; z = x; return y != null && z != null; } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Theory] [InlineData("TStruct?")] [InlineData("TClass?")] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_NotNullWhen(string type) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<TStruct, TClass> where TStruct : struct where TClass : class { static bool TryGetValue([NotNullWhen(true)] out TYPE y) { y = null; if (y == null) { return true; // 1 } return false; } static bool TryGetValue2([NotNullWhen(true)] out TYPE y) { y = null; return y != null; } static bool TryGetValue2B([NotNullWhen(true)] out TYPE y) { y = null; return y == null; // 2 } static bool TryGetValue3([NotNullWhen(false)] out TYPE y) { y = null; return y == null; } static bool TryGetValue3B([NotNullWhen(false)] out TYPE y) { y = null; return y != null; // 3 } static bool TryGetValue4([NotNull] TYPE x, [NotNullWhen(false)] out TYPE y) { y = null; if (y != null) { return true; // 4 } return false; // 5, 6 } } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, NotNullWhenAttributeDefinition, source.Replace("TYPE", type) }); comp.VerifyDiagnostics( // (15,13): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'true'. // return true; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return true;").WithArguments("y", "true").WithLocation(15, 13), // (29,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'true'. // return y == null; // 2 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return y == null;").WithArguments("y", "true").WithLocation(29, 9), // (41,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'false'. // return y != null; // 3 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return y != null;").WithArguments("y", "false").WithLocation(41, 9), // (49,13): warning CS8777: Parameter 'x' must have a non-null value when exiting. // return true; // 4 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return true;").WithArguments("x").WithLocation(49, 13), // (51,9): warning CS8777: Parameter 'x' must have a non-null value when exiting. // return false; // 5, 6 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return false;").WithArguments("x").WithLocation(51, 9), // (51,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'false'. // return false; // 5, 6 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return false;").WithArguments("y", "false").WithLocation(51, 9) ); } [Fact] public void EnforcedInMethodBody_NotNull_MiscTypes() { var source = @" using System.Diagnostics.CodeAnalysis; class C<TStruct, TNotNull> where TStruct : struct where TNotNull : notnull { void M([NotNull] int? i, [NotNull] int i2, [NotNull] TStruct? s, [NotNull] TStruct s2, [NotNull] TNotNull n) { } } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (10,5): warning CS8777: Parameter 'i' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("i").WithLocation(10, 5), // (10,5): warning CS8777: Parameter 's' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("s").WithLocation(10, 5) ); } [Fact] public void EnforcedInMethodBody_NotNullImplementedWithDoesNotReturnIf() { var source = @" using System.Diagnostics.CodeAnalysis; class C { void M([NotNull] object? value) { Assert(value is object); } void Assert([DoesNotReturnIf(false)] bool b) => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition, DoesNotReturnIfAttributeDefinition }); comp.VerifyDiagnostics(); } [Theory] [InlineData("TStruct?")] [InlineData("TClass?")] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_NotNullWhen_Composition(string type) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<TStruct, TClass> where TStruct : struct where TClass : class { static bool TryGetValue([NotNullWhen(true)] out TYPE y) { return TryGetValue(out y); } static bool TryGetValue2([NotNullWhen(true)] out TYPE y) { return TryGetValue3(out y); // 1 } static bool TryGetValue3([NotNullWhen(false)] out TYPE y) { return TryGetValue3(out y); } static bool TryGetValue3B([NotNullWhen(false)] out TYPE y) { return TryGetValue2(out y); // 2 } static bool TryGetValue4([NotNull] TYPE x, [NotNullWhen(false)] out TYPE y) { return TryGetValue4(x, out y); } static bool TryGetValueString1(string key, [MaybeNullWhen(false)] out string value) => TryGetValueString2(key, out value); static bool TryGetValueString2(string key, [NotNullWhen(true)] out string? value) => TryGetValueString1(key, out value); } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, NotNullAttributeDefinition, NotNullWhenAttributeDefinition, source.Replace("TYPE", type) }); comp.VerifyDiagnostics( // (17,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'true'. // return TryGetValue3(out y); // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return TryGetValue3(out y);").WithArguments("y", "true").WithLocation(17, 9), // (27,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'false'. // return TryGetValue2(out y); // 2 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return TryGetValue2(out y);").WithArguments("y", "false").WithLocation(27, 9) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_NotNullWhen_Unreachable() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { static bool TryGetValue([NotNullWhen(true)] out string? y) { if (false) { y = null; return true; } y = """"; return false; } } "; var comp = CreateNullableCompilation(new[] { NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,13): warning CS0162: Unreachable code detected // y = null; Diagnostic(ErrorCode.WRN_UnreachableCode, "y").WithLocation(11, 13) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_Misc_ProducingWarnings() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class Program { static void GetValue<T>([AllowNull]T x, out T y) { y = x; // 1 } static void GetValue2<T>(T x, out T y) { y = x; } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, MaybeNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (10,13): warning CS8601: Possible null reference assignment. // y = x; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(10, 13) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_DoesNotReturn() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { [DoesNotReturn] static void ActuallyReturns() { } // 1 [DoesNotReturn] static bool ActuallyReturns2() { return true; // 2 } [DoesNotReturn] static bool ActuallyReturns3(bool b) { if (b) throw null!; else return true; // 3 } [DoesNotReturn] static bool ActuallyReturns4() => true; // 4 [DoesNotReturn] static void NeverReturns() { throw null!; } [DoesNotReturn] static bool NeverReturns2() { throw null!; } [DoesNotReturn] static bool NeverReturns3() => throw null!; [DoesNotReturn] static bool NeverReturns4() { return NeverReturns2(); } [DoesNotReturn] static void NeverReturns5() { NeverReturns(); } [DoesNotReturn] static void NeverReturns6() { while (true) { } } } "; var comp = CreateNullableCompilation(new[] { DoesNotReturnAttributeDefinition, source }); comp.VerifyDiagnostics( // (9,5): error CS8763: A method marked [DoesNotReturn] should not return. // } // 1 Diagnostic(ErrorCode.WRN_ShouldNotReturn, "}").WithLocation(9, 5), // (14,9): error CS8763: A method marked [DoesNotReturn] should not return. // return true; // 2 Diagnostic(ErrorCode.WRN_ShouldNotReturn, "return true;").WithLocation(14, 9), // (23,13): error CS8763: A method marked [DoesNotReturn] should not return. // return true; // 3 Diagnostic(ErrorCode.WRN_ShouldNotReturn, "return true;").WithLocation(23, 13), // (28,12): error CS8763: A method marked [DoesNotReturn] should not return. // => true; // 4 Diagnostic(ErrorCode.WRN_ShouldNotReturn, "true").WithLocation(28, 12) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void DoesNotReturn_OHI() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; public class Base { [DoesNotReturn] public virtual void M() => throw null!; } public class Derived : Base { public override void M() => throw null!; // 1 } public class Derived2 : Base { [DoesNotReturn] public override void M() => throw null!; } public class Derived3 : Base { [DoesNotReturn] public new void M() => throw null!; } public class Derived4 : Base { public new void M() => throw null!; } interface I { [DoesNotReturn] bool M(); } class C1 : I { bool I.M() => throw null!; // 2 } class C2 : I { [DoesNotReturn] bool I.M() => throw null!; } "; var comp = CreateNullableCompilation(new[] { DoesNotReturnAttributeDefinition, DoesNotReturnIfAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,26): warning CS8770: Method 'void Derived.M()' lacks `[DoesNotReturn]` annotation to match implemented or overridden member. // public override void M() => throw null!; // 1 Diagnostic(ErrorCode.WRN_DoesNotReturnMismatch, "M").WithArguments("void Derived.M()").WithLocation(11, 26), // (35,12): warning CS8770: Method 'bool C1.M()' lacks `[DoesNotReturn]` annotation to match implemented or overridden member. // bool I.M() => throw null!; // 2 Diagnostic(ErrorCode.WRN_DoesNotReturnMismatch, "M").WithArguments("bool C1.M()").WithLocation(35, 12) ); } [Fact] public void NotNull_Parameter_Generic_OnOverrides() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public virtual void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public virtual void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public virtual void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public virtual void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) => throw null!; public override void F2<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : class => throw null!; public override void F3<T>([NotNull]T? t1, [NotNull] out T? t2, [NotNull] ref T? t3, [NotNull] in T? t4) where T : class => throw null!; public override void F4<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : struct => throw null!; public override void F5<T>([NotNull]T? t1, [NotNull] out T? t2, [NotNull] ref T? t3, [NotNull] in T? t4) where T : struct => throw null!; } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void NotNullWhenFalse_Parameter_Generic_OnOverrides() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public virtual bool F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public virtual bool F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public virtual bool F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public virtual bool F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } public class Derived : Base { public override bool F1<T>([NotNullWhen(false)]T t1, [NotNullWhen(false)] out T t2, [NotNullWhen(false)] ref T t3, [NotNullWhen(false)] in T t4) => throw null!; public override bool F2<T>([NotNullWhen(false)]T t1, [NotNullWhen(false)] out T t2, [NotNullWhen(false)] ref T t3, [NotNullWhen(false)] in T t4) where T : class => throw null!; public override bool F3<T>([NotNullWhen(false)]T? t1, [NotNullWhen(false)] out T? t2, [NotNullWhen(false)] ref T? t3, [NotNullWhen(false)] in T? t4) where T : class => throw null!; public override bool F4<T>([NotNullWhen(false)]T t1, [NotNullWhen(false)] out T t2, [NotNullWhen(false)] ref T t3, [NotNullWhen(false)] in T t4) where T : struct => throw null!; public override bool F5<T>([NotNullWhen(false)]T? t1, [NotNullWhen(false)] out T? t2, [NotNullWhen(false)] ref T? t3, [NotNullWhen(false)] in T? t4) where T : struct => throw null!; } "; var comp = CreateNullableCompilation(new[] { NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact, WorkItem(42169, "https://github.com/dotnet/roslyn/issues/42169")] public void NotNullWhenTrue_WithMaybeNull_Overriding() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { internal virtual bool TryGetValueCore<TKey, TValue>(TKey key, [MaybeNull] [NotNullWhen(true)] out TValue value) where TKey : class { throw null!; } } public class Derived : C { internal override bool TryGetValueCore<TKey, TValue>(TKey key, [MaybeNull] [NotNullWhen(true)] out TValue value) { throw null!; } } "; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact, WorkItem(42169, "https://github.com/dotnet/roslyn/issues/42169")] public void NotNullWhenFalse_WithMaybeNull_Overriding() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { internal virtual bool TryGetValueCore<TKey, TValue>(TKey key, [MaybeNull] [NotNullWhen(false)] out TValue value) where TKey : class { throw null!; } } public class Derived : C { internal override bool TryGetValueCore<TKey, TValue>(TKey key, [MaybeNull] [NotNullWhen(false)] out TValue value) { throw null!; } } "; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact, WorkItem(42169, "https://github.com/dotnet/roslyn/issues/42169")] public void MaybeNullWhenTrue_WithNotNull_Overriding() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { internal virtual bool TryGetValueCore<TKey, TValue>(TKey key, [NotNull] [MaybeNullWhen(true)] out TValue value) where TKey : class { throw null!; } } public class Derived : C { internal override bool TryGetValueCore<TKey, TValue>(TKey key, [NotNull] [MaybeNullWhen(true)] out TValue value) { throw null!; } } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNull_Parameter_Generic() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; public virtual void F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; public virtual void F3<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : class => throw null!; public virtual void F4<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : struct => throw null!; public virtual void F5<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : struct => throw null!; public virtual void F6<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : notnull => throw null!; } public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t4 public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t4 public override void F6<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 } "; // [MaybeNull] on a by-value or `in` parameter means a null-test (only returns if null) var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(13, 26), // (13,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(13, 26), // (14,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(14, 26), // (14,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(14, 26), // (15,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t1").WithLocation(15, 26), // (15,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t4").WithLocation(15, 26), // (16,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t1").WithLocation(16, 26), // (16,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t4").WithLocation(16, 26), // (17,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t1").WithLocation(17, 26), // (17,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t4").WithLocation(17, 26), // (18,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F6<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t1").WithLocation(18, 26), // (18,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F6<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t4").WithLocation(18, 26) ); } [Fact] public void MaybeNullWhenTrue_Parameter_Generic() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) => throw null!; public virtual bool F2<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : class => throw null!; public virtual bool F3<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : class => throw null!; public virtual bool F4<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : struct => throw null!; public virtual bool F5<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : struct => throw null!; public virtual bool F6<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : notnull => throw null!; } public class Derived : Base { public override bool F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public override bool F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public override bool F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public override bool F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public override bool F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; public override bool F6<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNullWhenTrue_ImplementingAnnotatedInterface() { var source = @"using System.Diagnostics.CodeAnalysis; #nullable disable public interface I<T> { bool TryGetValue(out T t); } #nullable enable public class C<T> : I<T> { public bool TryGetValue([MaybeNullWhen(false)] out T t) => throw null!; } "; // Note: because we're implementing `I<T!>!`, we complain about returning a possible null value // through `bool TryGetValue(out T! t)` var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,17): warning CS8767: Nullability of reference types in type of parameter 't' of 'bool C<T>.TryGetValue(out T t)' doesn't match implicitly implemented member 'bool I<T>.TryGetValue(out T t)' because of nullability attributes. // public bool TryGetValue([MaybeNullWhen(false)] out T t) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "TryGetValue").WithArguments("t", "bool C<T>.TryGetValue(out T t)", "bool I<T>.TryGetValue(out T t)").WithLocation(11, 17) ); } [Fact] public void MaybeNullWhenTrue_ImplementingObliviousInterface() { var source = @"using System.Diagnostics.CodeAnalysis; #nullable disable public interface I<T> { bool TryGetValue(out T t); } #nullable enable public class C<T> : I< #nullable disable T #nullable enable > { public bool TryGetValue([MaybeNullWhen(false)] out T t) => throw null!; } "; var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNull_Parameter_Generic_OnOverrides() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public virtual void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public virtual void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public virtual void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public virtual void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; // t2, t3 public override void F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; // t2, t3 public override void F3<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : class => throw null!; public override void F4<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : struct => throw null!; public override void F5<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : struct => throw null!; } "; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(12, 26), // (12,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (13,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t2").WithLocation(13, 26), // (13,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t3").WithLocation(13, 26) ); } [Fact] public void MaybeNullWhenTrue_Parameter_Generic_OnOverrides() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public virtual bool F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public virtual bool F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public virtual bool F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public virtual bool F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } public class Derived : Base { public override bool F1<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) => throw null!; // t2, t3 public override bool F2<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : class => throw null!; // t2, t3 public override bool F3<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : class => throw null!; public override bool F4<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : struct => throw null!; public override bool F5<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : struct => throw null!; } public class Derived2 : Derived { } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F1<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(12, 26), // (12,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F1<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (13,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F2<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t2").WithLocation(13, 26), // (13,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F2<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t3").WithLocation(13, 26) ); } [Fact, WorkItem(41437, "https://github.com/dotnet/roslyn/issues/41437")] public void MaybeNullWhenTrue_Parameter_Generic_OnOverrides_WithMaybeNullWhenFalse() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) => throw null!; public virtual bool F2<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : class => throw null!; public virtual bool F3<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : class => throw null!; public virtual bool F4<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : struct => throw null!; public virtual bool F5<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : struct => throw null!; public virtual bool F6<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : notnull => throw null!; } public class Derived : Base { public override bool F1<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t2, t3 public override bool F2<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : class => throw null!; // t2, t3 public override bool F3<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : class => throw null!; public override bool F4<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : struct => throw null!; public override bool F5<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : struct => throw null!; public override bool F6<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F1<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(13, 26), // (13,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F1<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(13, 26), // (14,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F2<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t2").WithLocation(14, 26), // (14,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F2<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t3").WithLocation(14, 26), // (18,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F6<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t2").WithLocation(18, 26), // (18,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F6<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t3").WithLocation(18, 26) ); } [Fact, WorkItem(41437, "https://github.com/dotnet/roslyn/issues/41437")] public void AssigningMaybeNullTNotNullToTNotNullInOverride() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F6<T>([AllowNull] in T t4) where T : notnull => throw null!; } public class Derived : Base { public override bool F6<T>(in T t4) => throw null!; } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (8,26): warning CS8765: Nullability of type of parameter 't4' doesn't match overridden member (possibly because of nullability attributes). // public override bool F6<T>(in T t4) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t4").WithLocation(8, 26) ); } [Fact, WorkItem(41437, "https://github.com/dotnet/roslyn/issues/41437")] public void MaybeNullWhenTrue_Parameter_Generic_OnOverrides_WithMaybeNull() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) => throw null!; public virtual bool F2<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : class => throw null!; public virtual bool F3<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : class => throw null!; public virtual bool F4<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : struct => throw null!; public virtual bool F5<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : struct => throw null!; public virtual bool F6<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : notnull => throw null!; } public class Derived : Base { public override bool F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; // t2, t3 public override bool F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; // t2, t3 public override bool F3<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : class => throw null!; public override bool F4<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : struct => throw null!; public override bool F5<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : struct => throw null!; public override bool F6<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(13, 26), // (13,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(13, 26), // (14,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t2").WithLocation(14, 26), // (14,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t3").WithLocation(14, 26), // (18,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F6<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t2").WithLocation(18, 26), // (18,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F6<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t3").WithLocation(18, 26) ); } [Fact] public void MaybeNull_Parameter_Generic_OnOverrides_WithMaybeNullWhenFalse() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; public virtual bool F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; public virtual bool F3<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : class => throw null!; public virtual bool F4<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : struct => throw null!; public virtual bool F5<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : struct => throw null!; public virtual bool F6<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : notnull => throw null!; } public class Derived : Base { public override bool F1<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t1, t4 public override bool F2<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : class => throw null!; // t1, t4 public override bool F3<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : class => throw null!; // t1, t4 public override bool F4<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : struct => throw null!; // t1, t4 public override bool F5<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : struct => throw null!; // t1, t4 public override bool F6<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t1, t4 } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override bool F1<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(13, 26), // (13,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override bool F1<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(13, 26), // (14,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override bool F2<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(14, 26), // (14,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override bool F2<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(14, 26), // (15,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override bool F3<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t1").WithLocation(15, 26), // (15,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override bool F3<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t4").WithLocation(15, 26), // (16,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override bool F4<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t1").WithLocation(16, 26), // (16,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override bool F4<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t4").WithLocation(16, 26), // (17,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override bool F5<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t1").WithLocation(17, 26), // (17,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override bool F5<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t4").WithLocation(17, 26), // (18,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override bool F6<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t1").WithLocation(18, 26), // (18,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override bool F6<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t4").WithLocation(18, 26) ); } [Fact] public void DisallowNull_Parameter_Generic() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) => throw null!; public virtual void F2<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) where T : class => throw null!; public virtual void F3<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : class => throw null!; public virtual void F4<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) where T : struct => throw null!; public virtual void F5<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void DisallowNull_Parameter_Generic_OnOverrides() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public virtual void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public virtual void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public virtual void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public virtual void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) => throw null!; // t1, t3, t4 public override void F2<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) where T : class => throw null!; public override void F3<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : class => throw null!; // t1, t3, t4 public override void F4<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) where T : struct => throw null!; public override void F5<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : struct => throw null!; // t1, t3, t4 } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): warning CS8765: Nullability of type of parameter 't1' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(12, 26), // (12,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (12,26): warning CS8765: Nullability of type of parameter 't4' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(12, 26), // (14,26): warning CS8765: Nullability of type of parameter 't1' doesn't match overridden member (possibly because of nullability attributes). // public override void F3<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t1").WithLocation(14, 26), // (14,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override void F3<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t3").WithLocation(14, 26), // (14,26): warning CS8765: Nullability of type of parameter 't4' doesn't match overridden member (possibly because of nullability attributes). // public override void F3<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t4").WithLocation(14, 26), // (16,26): warning CS8765: Nullability of type of parameter 't1' doesn't match overridden member (possibly because of nullability attributes). // public override void F5<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : struct => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t1").WithLocation(16, 26), // (16,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override void F5<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : struct => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t3").WithLocation(16, 26), // (16,26): warning CS8765: Nullability of type of parameter 't4' doesn't match overridden member (possibly because of nullability attributes). // public override void F5<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : struct => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t4").WithLocation(16, 26) ); } [Fact] public void DisallowNull_Parameter_01() { // Warn on misused nullability attributes (F2, F3, F4)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool b = false; static void F1<T>([DisallowNull]T t) { } static void F2<T>([DisallowNull]T t) where T : class { } static void F3<T>([DisallowNull]T? t) where T : class { } static void F4<T>([DisallowNull]T t) where T : struct { } static void F5<T>([DisallowNull]T? t) where T : struct { } static void M1<T>(T t1) { F1(t1); // 0 } static void M2<T>(T t2) where T : class { F1(t2); F2(t2); F3(t2); t2 = null; // 1 if (b) F1(t2); // 2 if (b) F2(t2); // 3, 4 if (b) F3(t2); // 5 } static void M3<T>(T? t3) where T : class { if (b) F1(t3); // 6 if (b) F2(t3); // 7, 8 if (b) F3(t3); // 9 if (t3 == null) return; F1(t3); F2(t3); F3(t3); } static void M4<T>(T t4) where T : struct { F1(t4); F4(t4); } static void M5<T>(T? t5) where T : struct { if (b) F1(t5); // 10 if (b) F5(t5); // 11 if (t5 == null) return; F1(t5); F5(t5); } }"; var comp = CreateCompilation(new[] { DisallowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,12): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // F1(t1); // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(12, 12), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 14), // (20,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T?>(T? t)'. // if (b) F1(t2); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F1<T?>(T? t)").WithLocation(20, 19), // (21,16): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // if (b) F2(t2); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(21, 16), // (21,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T?>(T? t)'. // if (b) F2(t2); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F2<T?>(T? t)").WithLocation(21, 19), // (22,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T? t)'. // if (b) F3(t2); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F3<T>(T? t)").WithLocation(22, 19), // (26,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T?>(T? t)'. // if (b) F1(t3); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F1<T?>(T? t)").WithLocation(26, 19), // (27,16): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // if (b) F2(t3); // 7, 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(27, 16), // (27,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T?>(T? t)'. // if (b) F2(t3); // 7, 8 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F2<T?>(T? t)").WithLocation(27, 19), // (28,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T? t)'. // if (b) F3(t3); // 9 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F3<T>(T? t)").WithLocation(28, 19), // (41,19): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // if (b) F1(t5); // 10 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(41, 19), // (42,19): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // if (b) F5(t5); // 11 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(42, 19) ); } [Fact, WorkItem(36009, "https://github.com/dotnet/roslyn/issues/36009")] public void DisallowNull_Parameter_NullableValueType() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F5<T>([DisallowNull]T? t) where T : struct { } static void M5<T>(T? t5) where T : struct { F5(t5); // 1 if (t5 == null) return; F5(t5); } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (7,12): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // F5(t5); Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(7, 12) ); } [Fact, WorkItem(36009, "https://github.com/dotnet/roslyn/issues/36009")] public void DisallowNull_RefParameter_NullableValueType() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F5<T>([DisallowNull]ref T? t) where T : struct { } static void M5<T>(T? t5) where T : struct { F5(ref t5); // 1 if (t5 == null) return; F5(ref t5); } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (7,16): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // F5(ref t5); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(7, 16) ); } [Fact, WorkItem(36009, "https://github.com/dotnet/roslyn/issues/36009")] public void DisallowNull_InParameter_NullableValueType() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F5<T>([DisallowNull]in T? t) where T : struct { } static void M5<T>(T? t5) where T : struct { F5(in t5); // 1 if (t5 == null) return; F5(in t5); } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (7,15): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // F5(in t5); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(7, 15) ); } [Fact, WorkItem(36009, "https://github.com/dotnet/roslyn/issues/36009")] public void DisallowNull_ByValParameter_NullableValueTypeViaConstraint() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base<T> { public virtual void M<U>(U u) where U : T { } } public class C<T2> : Base<System.Nullable<T2>> where T2 : struct { public override void M<U>(U u) // U is constrained to be a Nullable<T2> type { M2(u); // 1 if (u is null) return; M2(u); } void M2<T3>([DisallowNull] T3 t) { } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,12): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // M2(u); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "u").WithLocation(11, 12) ); } [Fact] public void DisallowNull_Parameter_01_WithAllowNull() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool b = false; static void F1<T>([DisallowNull, AllowNull]T t) { } static void F2<T>([DisallowNull, AllowNull]T t) where T : class { } static void F3<T>([DisallowNull, AllowNull]T? t) where T : class { } static void F4<T>([DisallowNull, AllowNull]T t) where T : struct { } static void F5<T>([DisallowNull, AllowNull]T? t) where T : struct { } static void M1<T>(T t1) { F1(t1); // 0 } static void M2<T>(T t2) where T : class { F1(t2); F2(t2); F3(t2); t2 = null; // 1 if (b) F1(t2); // 2 if (b) F2(t2); // 3, 4 if (b) F3(t2); // 5 } static void M3<T>(T? t3) where T : class { if (b) F1(t3); // 6 if (b) F2(t3); // 7, 8 if (b) F3(t3); // 9 if (t3 == null) return; F1(t3); F2(t3); F3(t3); } static void M4<T>(T t4) where T : struct { F1(t4); F4(t4); } static void M5<T>(T? t5) where T : struct { if (b) F1(t5); // 10 if (b) F5(t5); // 11 if (t5 == null) return; F1(t5); F5(t5); } }"; var comp = CreateCompilation(new[] { DisallowNullAttributeDefinition, AllowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,12): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // F1(t1); // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(12, 12), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 14), // (20,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T?>(T? t)'. // if (b) F1(t2); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F1<T?>(T? t)").WithLocation(20, 19), // (21,16): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // if (b) F2(t2); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(21, 16), // (21,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T?>(T? t)'. // if (b) F2(t2); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F2<T?>(T? t)").WithLocation(21, 19), // (22,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T? t)'. // if (b) F3(t2); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F3<T>(T? t)").WithLocation(22, 19), // (26,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T?>(T? t)'. // if (b) F1(t3); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F1<T?>(T? t)").WithLocation(26, 19), // (27,16): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // if (b) F2(t3); // 7, 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(27, 16), // (27,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T?>(T? t)'. // if (b) F2(t3); // 7, 8 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F2<T?>(T? t)").WithLocation(27, 19), // (28,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T? t)'. // if (b) F3(t3); // 9 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F3<T>(T? t)").WithLocation(28, 19), // (41,19): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // if (b) F1(t5); // 10 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(41, 19), // (42,19): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // if (b) F5(t5); // 11 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(42, 19) ); } [Fact, WorkItem(36009, "https://github.com/dotnet/roslyn/issues/36009")] public void DisallowNull_Parameter_02() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool b = false; static void F1<T>([DisallowNull]T t) { } static void F2<T>([DisallowNull]T t) where T : class { } static void F3<T>([DisallowNull]T? t) where T : class { } static void F4<T>([DisallowNull]T t) where T : struct { } static void F5<T>([DisallowNull]T? t) where T : struct { } static void M1<T>(T t1) { F1<T>(t1); // 0 } static void M2<T>(T t2) where T : class { F1<T>(t2); F2<T>(t2); F3<T>(t2); t2 = null; // 1 if (b) F1<T>(t2); // 2 if (b) F2<T>(t2); // 3 if (b) F3<T>(t2); // 4 } static void M3<T>(T? t3) where T : class { if (b) F1<T>(t3); // 5 if (b) F2<T>(t3); // 6 if (b) F3<T>(t3); // 7 if (t3 == null) return; F1<T>(t3); F2<T>(t3); F3<T>(t3); } static void M4<T>(T t4) where T : struct { F1<T>(t4); F4<T>(t4); } static void M5<T>(T? t5) where T : struct { F1<T?>(t5); // 8 F5<T>(t5); // 9 if (t5 == null) return; F1<T?>(t5); F5<T>(t5); } }"; var comp = CreateCompilation(new[] { DisallowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,15): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // F1<T>(t1); // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(12, 15), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 14), // (20,22): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T>(T t)'. // if (b) F1<T>(t2); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F1<T>(T t)").WithLocation(20, 22), // (21,22): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T>(T t)'. // if (b) F2<T>(t2); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F2<T>(T t)").WithLocation(21, 22), // (22,22): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T? t)'. // if (b) F3<T>(t2); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F3<T>(T? t)").WithLocation(22, 22), // (26,22): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T>(T t)'. // if (b) F1<T>(t3); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F1<T>(T t)").WithLocation(26, 22), // (27,22): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T>(T t)'. // if (b) F2<T>(t3); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F2<T>(T t)").WithLocation(27, 22), // (28,22): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T? t)'. // if (b) F3<T>(t3); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F3<T>(T? t)").WithLocation(28, 22), // (41,16): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // F1<T?>(t5); // 8 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(41, 16) ); } [Fact] public void DisallowNull_Parameter_03() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool b = false; static void F1([DisallowNull]string s) { } static void F2([DisallowNull]string? s) { } static void M1(string s1) { F1(s1); F2(s1); s1 = null; // 1 if (b) F1(s1); // 2 if (b) F2(s1); // 3 } static void M2(string? s2) { if (b) F1(s2); // 4 if (b) F2(s2); // 5 if (s2 == null) return; F1(s2); F2(s2); } }"; var comp = CreateCompilation(new[] { DisallowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // s1 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 14), // (12,19): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.F1(string s)'. // if (b) F1(s1); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s1").WithArguments("s", "void Program.F1(string s)").WithLocation(12, 19), // (13,19): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.F2(string? s)'. // if (b) F2(s1); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s1").WithArguments("s", "void Program.F2(string? s)").WithLocation(13, 19), // (17,19): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.F1(string s)'. // if (b) F1(s2); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s2").WithArguments("s", "void Program.F1(string s)").WithLocation(17, 19), // (18,19): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.F2(string? s)'. // if (b) F2(s2); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s2").WithArguments("s", "void Program.F2(string? s)").WithLocation(18, 19)); } [Fact, WorkItem(36009, "https://github.com/dotnet/roslyn/issues/36009")] public void DisallowNull_Parameter_04() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([DisallowNull]int i) { } static void F2([DisallowNull]int? i) { } static void M1(int i1) { F1(i1); F2(i1); } static void M2(int? i2) { F2(i2); // 1 if (i2 == null) return; F2(i2); } }"; var comp = CreateCompilation(new[] { DisallowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,12): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // F2(i2); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "i2").WithLocation(13, 12) ); } [Fact] public void DisallowNull_Parameter_05() { // Warn on misused nullability attributes (F2)? https://github.com/dotnet/roslyn/issues/36073 var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static void F1<T>(T? t) where T : class { } public static void F2<T>([DisallowNull]T? t) where T : class { } }"; var comp = CreateCompilation(new[] { DisallowNullAttributeDefinition, source0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x); F1(y); F2(x); // 2 F2(y); } }"; comp = CreateNullableCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (9,12): warning CS8604: Possible null reference argument for parameter 't' in 'void A.F2<object>(object? t)'. // F2(x); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void A.F2<object>(object? t)").WithLocation(9, 12) ); } [Fact] public void DisallowNull_Parameter_OnOverride() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void M([DisallowNull] string? s) { } } public class C : Base { public override void M(string? s) { } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new Base().M(s); // 1 new Base().M(s2); new C().M(s); new C().M(s2); } }"; var expected = new[] { // (6,22): warning CS8604: Possible null reference argument for parameter 's' in 'void Base.M(string? s)'. // new Base().M(s); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s").WithArguments("s", "void Base.M(string? s)").WithLocation(6, 22) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact, WorkItem(36703, "https://github.com/dotnet/roslyn/issues/36703")] public void DisallowNull_RefReturnValue_05() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static T? F1<T>(T t) where T : class => throw null!; [return: DisallowNull] public static ref T? F2<T>(T t) where T : class => throw null!; }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source0 }); comp.VerifyDiagnostics( // (5,14): error CS0592: Attribute 'DisallowNull' is not valid on this declaration type. It is only valid on 'property, indexer, field, parameter' declarations. // [return: DisallowNull] public static ref T? F2<T>(T t) where T : class => throw null!; Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "DisallowNull").WithArguments("DisallowNull", "property, indexer, field, parameter").WithLocation(5, 14) ); var source1 = @"using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.All)] public sealed class DisallowNullAttribute : Attribute { } } public class A { public static ref T? F1<T>(T t) where T : class => throw null!; [return: DisallowNull] public static ref T? F2<T>(T t) where T : class => throw null!; static void Main() { object? y = new object(); F1(y) = y; F2(y) = y; // DisallowNull is ignored } }"; var comp2 = CreateNullableCompilation(source1); comp2.VerifyDiagnostics(); } [Fact] public void DisallowNull_OutParameter_03() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([DisallowNull]out string t) => throw null!; static void F2([DisallowNull]out string? t) => throw null!; static void M() { F1(out string? t1); t1.ToString(); F2(out string? t2); t2.ToString(); // 1 } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(12, 9) ); } [Fact] public void AllowNull_OutParameter_03() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([AllowNull]out string t) => throw null!; static void F2([AllowNull]out string? t) => throw null!; static void M() { F1(out string? t1); t1.ToString(); F2(out string? t2); t2.ToString(); // 1 } }"; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(12, 9) ); } [Fact] public void DisallowNull_RefParameter_03() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([DisallowNull]ref string s) { } static void F2([DisallowNull]ref string? s) { } static void M1() { string s1 = """"; F1(ref s1); s1.ToString(); string? s2 = """"; F2(ref s2); s2.ToString(); // 1 string s3 = null; // 2 F1(ref s3); // 3 s3.ToString(); string? s4 = null; // 4 F2(ref s4); // 5 s4.ToString(); // 6 } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(14, 9), // (16,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string s3 = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 21), // (17,16): warning CS8601: Possible null reference assignment. // F1(ref s3); // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s3").WithLocation(17, 16), // (21,16): warning CS8601: Possible null reference assignment. // F2(ref s4); // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s4").WithLocation(21, 16), // (22,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(22, 9) ); } [Fact] public void DisallowNull_Property() { // Warn on misused nullability attributes (P2, P3, P4)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [DisallowNull]public TOpen P1 { get; set; } = default!; } public class CClass<TClass> where TClass : class { [DisallowNull]public TClass P2 { get; set; } = null!; [DisallowNull]public TClass? P3 { get; set; } = null; } public class CStruct<TStruct> where TStruct : struct { [DisallowNull]public TStruct P4 { get; set; } [DisallowNull]public TStruct? P5 { get; set; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class C { static void M1<T>(T t1) { new COpen<T>().P1 = t1; // 0 } static void M2<T>(T t2) where T : class { new COpen<T>().P1 = t2; new CClass<T>().P2 = t2; new CClass<T>().P3 = t2; t2 = null; // 1 new COpen<T>().P1 = t2; // 2 new CClass<T>().P2 = t2; // 3 new CClass<T>().P3 = t2; // 4, [DisallowNull] honored on TClass? } static void M3<T>(T? t3) where T : class { new COpen<T>().P1 = t3; // 5 new CClass<T>().P2 = t3; // 6 new CClass<T>().P3 = t3; // 7, [DisallowNull] honored on TClass? if (t3 == null) return; new COpen<T>().P1 = t3; new CClass<T>().P2 = t3; new CClass<T>().P3 = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>().P1 = t4; new CStruct<T>().P4 = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>().P1 = t5; // 8 new CStruct<T>().P5 = t5; // 9 if (t5 == null) return; new COpen<T?>().P1 = t5; new CStruct<T>().P5 = t5; } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics( // (6,29): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T>().P1 = t1; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(6, 29), // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 14), // (14,29): warning CS8601: Possible null reference assignment. // new COpen<T>().P1 = t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(14, 29), // (15,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P2 = t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(15, 30), // (16,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P3 = t2; // 4, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(16, 30), // (20,29): warning CS8601: Possible null reference assignment. // new COpen<T>().P1 = t3; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(20, 29), // (21,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P2 = t3; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(21, 30), // (22,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P3 = t3; // 7, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(22, 30), // (35,30): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T?>().P1 = t5; // 8 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(35, 30), // (36,31): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new CStruct<T>().P5 = t5; // 9 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(36, 31)); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics( // (6,29): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T>().P1 = t1; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(6, 29), // (9,53): warning CS8625: Cannot convert null literal to non-nullable reference type. // [DisallowNull]public TClass? P3 { get; set; } = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 53), // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 14), // (14,29): warning CS8601: Possible null reference assignment. // new COpen<T>().P1 = t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(14, 29), // (15,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P2 = t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(15, 30), // (16,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P3 = t2; // 4, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(16, 30), // (20,29): warning CS8601: Possible null reference assignment. // new COpen<T>().P1 = t3; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(20, 29), // (21,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P2 = t3; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(21, 30), // (22,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P3 = t3; // 7, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(22, 30), // (35,30): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T?>().P1 = t5; // 8 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(35, 30), // (36,31): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new CStruct<T>().P5 = t5; // 9 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(36, 31)); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var copenAttributes = copen.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(copenAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableContextAttribute(1)", "System.Runtime.CompilerServices.NullableAttribute(0)" }, copenAttributes); } var property = copen.GetMembers().OfType<PropertySymbol>().Single(); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" }, propertyAttributes); } else { AssertEx.Empty(propertyAttributes); } var setter = property.SetMethod; var setterAttributes = setter.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(setterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, setterAttributes); } var setterValueAttributes = setter.Parameters.Last().GetAttributes().Select(a => a.ToString()); Assert.Equal(FlowAnalysisAnnotations.DisallowNull, setter.Parameters.Last().FlowAnalysisAnnotations); if (isSource) { AssertEx.Empty(setterValueAttributes); } else { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" }, setterValueAttributes); } } } [Fact] [WorkItem(39926, "https://github.com/dotnet/roslyn/issues/39926")] public void DisallowNull_Property_NullInitializer() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull]public string? P1 { get; set; } = null; } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,53): warning CS8625: Cannot convert null literal to non-nullable reference type. // [DisallowNull]public string? P1 { get; set; } = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 53)); } [Fact] public void DisallowNull_Property_InDeconstructionAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull]public int? P1 { get; set; } = null; // 0 void M() { (P1, _) = (null, 1); // 1 P1.Value.ToString(); // 2 (_, (P1, _)) = (1, (null, 2)); // 3 (_, P1) = this; // 4 P1.Value.ToString(); // 5 ((_, P1), _) = (this, 2); // 6 } void Deconstruct(out int? x, out int? y) => throw null!; } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,50): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // [DisallowNull]public int? P1 { get; set; } = null; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "null").WithLocation(4, 50), // (7,19): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // (P1, _) = (null, 1); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(null, 1)").WithLocation(7, 19), // (8,9): warning CS8629: Nullable value type may be null. // P1.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "P1").WithLocation(8, 9), // (10,28): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // (_, (P1, _)) = (1, (null, 2)); // 3 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(null, 2)").WithLocation(10, 28), // (12,13): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // (_, P1) = this; // 4 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "P1").WithLocation(12, 13), // (13,9): warning CS8629: Nullable value type may be null. // P1.Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "P1").WithLocation(13, 9), // (15,14): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // ((_, P1), _) = (this, 2); // 6 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "P1").WithLocation(15, 14) ); } [Fact] public void DisallowNull_Field() { // Warn on misused nullability attributes (f2, f3, f4)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [DisallowNull]public TOpen f1 = default!; } public class CClass<TClass> where TClass : class { [DisallowNull]public TClass f2 = null!; [DisallowNull]public TClass? f3 = null!; } public class CStruct<TStruct> where TStruct : struct { [DisallowNull]public TStruct f4; [DisallowNull]public TStruct? f5; } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class C { static void M1<T>(T t1) { new COpen<T>().f1 = t1; // 0 } static void M2<T>(T t2) where T : class { new COpen<T>().f1 = t2; new CClass<T>().f2 = t2; new CClass<T>().f3 = t2; t2 = null; // 1 new COpen<T>().f1 = t2; // 2 new CClass<T>().f2 = t2; // 3 new CClass<T>().f3 = t2; // 4 } static void M3<T>(T? t3) where T : class { new COpen<T>().f1 = t3; // 5 new CClass<T>().f2 = t3; // 6 new CClass<T>().f3 = t3; // 7 if (t3 == null) return; new COpen<T>().f1 = t3; new CClass<T>().f2 = t3; new CClass<T>().f3 = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>().f1 = t4; new CStruct<T>().f4 = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>().f1 = t5; // 8 new CStruct<T>().f5 = t5; // 9 if (t5 == null) return; new COpen<T?>().f1 = t5; new CStruct<T>().f5 = t5; } static void M6<T>([System.Diagnostics.CodeAnalysis.MaybeNull]T t6) where T : class { new CClass<T>().f2 = t6; } static void M7<T>([System.Diagnostics.CodeAnalysis.NotNull]T? t7) where T : class { new CClass<T>().f2 = t7; // 10 } // 11 static void M8<T>([System.Diagnostics.CodeAnalysis.AllowNull]T t8) where T : class { new CClass<T>().f2 = t8; // 12 } }"; var expected = new[] { // (6,29): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T>().f1 = t1; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(6, 29), // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 14), // (14,29): warning CS8601: Possible null reference assignment. // new COpen<T>().f1 = t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(14, 29), // (15,30): warning CS8601: Possible null reference assignment. // new CClass<T>().f2 = t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(15, 30), // (16,30): warning CS8601: Possible null reference assignment. // new CClass<T>().f3 = t2; // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(16, 30), // (20,29): warning CS8601: Possible null reference assignment. // new COpen<T>().f1 = t3; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(20, 29), // (21,30): warning CS8601: Possible null reference assignment. // new CClass<T>().f2 = t3; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(21, 30), // (22,30): warning CS8601: Possible null reference assignment. // new CClass<T>().f3 = t3; // 7 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(22, 30), // (35,30): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T?>().f1 = t5; // 8 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(35, 30), // (36,31): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new CStruct<T>().f5 = t5; // 9 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(36, 31), // (47,30): warning CS8601: Possible null reference assignment. // new CClass<T>().f2 = t7; // 10 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t7").WithLocation(47, 30), // (48,5): warning CS8777: Parameter 't7' must have a non-null value when exiting. // } // 11 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("t7").WithLocation(48, 5), // (51,30): warning CS8601: Possible null reference assignment. // new CClass<T>().f2 = t8; // 12 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t8").WithLocation(51, 30) }; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var field = copen.GetMembers().OfType<FieldSymbol>().Single(); var fieldAttributes = field.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" }, fieldAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableAttribute(1)", "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" }, fieldAttributes); } } } [Fact] public void DisallowNull_AndOtherAnnotations_StaticField() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull]public static string? disallowNull = null!; [AllowNull]public static string allowNull = null; [MaybeNull]public static string maybeNull = null!; [NotNull]public static string? notNull = null; } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, AllowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition, lib_cs }); var source = @" class D { static void M() { C.disallowNull = null; // 1 C.allowNull = null; C.maybeNull.ToString(); // 2 C.notNull.ToString(); } }"; var expected = new[] { // (6,26): warning CS8625: Cannot convert null literal to non-nullable reference type. // C.disallowNull = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 26), // (8,9): warning CS8602: Dereference of a possibly null reference. // C.maybeNull.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C.maybeNull").WithLocation(8, 9) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void DisallowNull_Field_NullInitializer() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull]public string? field = null; // 1 void M() { field.ToString(); // 2 } } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,42): warning CS8625: Cannot convert null literal to non-nullable reference type. // [DisallowNull]public string? field = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 42), // (8,9): warning CS8602: Dereference of a possibly null reference. // field.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field").WithLocation(8, 9) ); } [Fact, WorkItem(40975, "https://github.com/dotnet/roslyn/issues/40975")] public void AllowNull_Parameter_NullDefaultValue() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { void M([AllowNull] string p = null) { } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void Disallow_Property_OnVirtualProperty_OnlyOverridingGetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [DisallowNull] public virtual string? P { get { throw null!; } set { throw null!; } } public virtual string? P2 { get { throw null!; } set { throw null!; } } } public class C : Base { public override string? P { get { throw null!; } } [DisallowNull] public override string? P2 { get { throw null!; } } static void M(C c, Base b) { b.P = null; // 1 c.P = null; // 2 b.P2 = null; c.P2 = null; } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // b.P = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 15), // (16,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.P = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 15) ); } [Fact] public void Disallow_Indexer_OnVirtualIndexer_OnlyOverridingSetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [DisallowNull] public virtual string? this[int i] { get { throw null!; } set { throw null!; } } public virtual string? this[byte i] { get { throw null!; } set { throw null!; } } } public class C : Base { public override string? this[int it] { set { throw null!; } } [DisallowNull] public override string? this[byte i] { set { throw null!; } } // 0 static void M(C c, Base b) { b[(int)0] = null; // 1 c[(int)0] = null; b[(byte)0] = null; c[(byte)0] = null; // 2 } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,59): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // [DisallowNull] public override string? this[byte i] { set { throw null!; } } // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(11, 59), // (15,21): warning CS8625: Cannot convert null literal to non-nullable reference type. // b[(int)0] = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 21), // (19,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // c[(byte)0] = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 22) ); } [Fact] public void DisallowNull_Property_CompoundAssignment() { var source = @" using System.Diagnostics.CodeAnalysis; class C { [DisallowNull] C? Property { get; set; } = null!; public static C? operator+(C? one, C other) => throw null!; void M(C c) { Property += c; // 1 } } struct S { [DisallowNull] S? Property { get { throw null!; } set { throw null!; } } public static S? operator+(S? one, S other) => throw null!; void M(S s) { Property += s; // 2 } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,9): warning CS8601: Possible null reference assignment. // Property += c; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "Property += c").WithLocation(10, 9), // (20,9): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // Property += s; // 2 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "Property += s").WithLocation(20, 9) ); } [Fact] public void DisallowNull_Operator_CompoundAssignment() { var source = @" using System.Diagnostics.CodeAnalysis; class C { C? Property { get; set; } = null!; public static C? operator+([DisallowNull] C? one, C other) => throw null!; void M(C c) { Property += c; // 1 } } struct S { S? Property { get { throw null!; } set { throw null!; } } public static S? operator+([DisallowNull] S? one, S other) => throw null!; void M(S s) { Property += s; // 2 } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,9): warning CS8604: Possible null reference argument for parameter 'one' in 'C? C.operator +(C? one, C other)'. // Property += c; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "Property").WithArguments("one", "C? C.operator +(C? one, C other)").WithLocation(10, 9), // (20,9): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // Property += s; // 2 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "Property").WithLocation(20, 9) ); } [Fact] public void DisallowNull_Property_OnVirtualProperty() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [DisallowNull] public virtual string? P { get; set; } = null!; public virtual string? P2 { get; set; } = null!; } public class C : Base { public override string? P { get; set; } = null!; [DisallowNull] public override string? P2 { get; set; } = null!; // 0 static void M(C c, Base b) { b.P = null; // 1 c.P = null; b.P2 = null; c.P2 = null; // 2 } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,54): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // [DisallowNull] public override string? P2 { get; set; } = null!; // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(11, 54), // (15,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // b.P = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 15), // (19,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.P2 = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 16) ); } [Fact] public void DisallowNull_Property_Cycle() { var source = @" namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = true)] public sealed class DisallowNullAttribute : Attribute { [DisallowNull, DisallowNull(1)] int Property { get; set; } public DisallowNullAttribute() { } public DisallowNullAttribute([DisallowNull] int i) { } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void DisallowNull_Property_ExplicitSetter() { // Warn on misused nullability attributes (P2, P3, P4)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [DisallowNull]public TOpen P1 { get { throw null!; } set { throw null!; } } } public class CClass<TClass> where TClass : class { [DisallowNull]public TClass P2 { get { throw null!; } set { throw null!; } } [DisallowNull]public TClass? P3 { get { throw null!; } set { throw null!; } } } public class CStruct<TStruct> where TStruct : struct { [DisallowNull]public TStruct P4 { get { throw null!; } set { throw null!; } } [DisallowNull]public TStruct? P5 { get { throw null!; } set { throw null!; } } } class C { static void M1<T>(T t1) { new COpen<T>().P1 = t1; // 0 } static void M2<T>(T t2) where T : class { new COpen<T>().P1 = t2; new CClass<T>().P2 = t2; new CClass<T>().P3 = t2; t2 = null; // 1 new COpen<T>().P1 = t2; // 2 new CClass<T>().P2 = t2; // 3 new CClass<T>().P3 = t2; // 4, [DisallowNull] honored on TClass? } static void M3<T>(T? t3) where T : class { new COpen<T>().P1 = t3; // 5 new CClass<T>().P2 = t3; // 6 new CClass<T>().P3 = t3; // 7, [DisallowNull] honored on TClass? if (t3 == null) return; new COpen<T>().P1 = t3; new CClass<T>().P2 = t3; new CClass<T>().P3 = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>().P1 = t4; new CStruct<T>().P4 = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>().P1 = t5; // 8 new CStruct<T>().P5 = t5; // 9 if (t5 == null) return; new COpen<T?>().P1 = t5; new CStruct<T>().P5 = t5; } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (20,29): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T>().P1 = t1; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(20, 29), // (27,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(27, 14), // (28,29): warning CS8601: Possible null reference assignment. // new COpen<T>().P1 = t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(28, 29), // (29,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P2 = t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(29, 30), // (30,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P3 = t2; // 4, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(30, 30), // (34,29): warning CS8601: Possible null reference assignment. // new COpen<T>().P1 = t3; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(34, 29), // (35,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P2 = t3; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(35, 30), // (36,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P3 = t3; // 7, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(36, 30), // (49,30): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // new COpen<T?>().P1 = t5; // 8 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(49, 30), // (50,31): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // new CStruct<T>().P5 = t5; // 9 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(50, 31) ); } [Fact] public void DisallowNull_Property_OnSetter() { var source = @"using System.Diagnostics.CodeAnalysis; public class CClass<TClass> where TClass : class { public TClass P2 { get; [DisallowNull] set; } = null!; public TClass? P3 { get; [DisallowNull] set; } = null; }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,30): error CS0592: Attribute 'DisallowNull' is not valid on this declaration type. It is only valid on 'property, indexer, field, parameter' declarations. // public TClass P2 { get; [DisallowNull] set; } = null!; Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "DisallowNull").WithArguments("DisallowNull", "property, indexer, field, parameter").WithLocation(4, 30), // (5,31): error CS0592: Attribute 'DisallowNull' is not valid on this declaration type. It is only valid on 'property, indexer, field, parameter' declarations. // public TClass? P3 { get; [DisallowNull] set; } = null; Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "DisallowNull").WithArguments("DisallowNull", "property, indexer, field, parameter").WithLocation(5, 31) ); } [Fact] public void DisallowNull_Property_OnGetter() { var source = @"using System.Diagnostics.CodeAnalysis; public class CClass<TClass> where TClass : class { public TClass P2 { [DisallowNull] get; set; } = null!; public TClass? P3 { [DisallowNull] get; set; } = null; }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,25): error CS0592: Attribute 'DisallowNull' is not valid on this declaration type. It is only valid on 'property, indexer, field, parameter' declarations. // public TClass P2 { [DisallowNull] get; set; } = null!; Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "DisallowNull").WithArguments("DisallowNull", "property, indexer, field, parameter").WithLocation(4, 25), // (5,26): error CS0592: Attribute 'DisallowNull' is not valid on this declaration type. It is only valid on 'property, indexer, field, parameter' declarations. // public TClass? P3 { [DisallowNull] get; set; } = null; Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "DisallowNull").WithArguments("DisallowNull", "property, indexer, field, parameter").WithLocation(5, 26) ); } [Fact] public void DisallowNull_Property_NoGetter() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [DisallowNull]public TOpen P1 { set { throw null!; } } [DisallowNull]public TOpen P2 => default!; }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void DisallowNull_Indexer() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [DisallowNull]public TOpen this[int i] { set => throw null!; } } public class CClass<TClass> where TClass : class? { [DisallowNull]public TClass this[int i] { set => throw null!; } } public class CClass2<TClass> where TClass : class { [DisallowNull]public TClass? this[int i] { set => throw null!; } } public class CStruct<TStruct> where TStruct : struct { [DisallowNull]public TStruct this[int i] { set => throw null!; } } public class CStruct2<TStruct> where TStruct : struct { [DisallowNull]public TStruct? this[int i] { set => throw null!; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class C { static void M1<T>(T t1) { new COpen<T>()[0] = t1; // 0 } static void M2<T>(T t2) where T : class { new COpen<T>()[0] = t2; new CClass<T>()[0] = t2; new CClass2<T>()[0] = t2; t2 = null; // 1 new COpen<T>()[0] = t2; // 2 new CClass<T>()[0] = t2; // 3 new CClass2<T>()[0] = t2; // 4, [DisallowNull] honored on TClass? } static void M3<T>(T? t3) where T : class { new COpen<T>()[0] = t3; // 5 new CClass<T>()[0] = t3; // 6 new CClass2<T>()[0] = t3; // 7, [DisallowNull] honored on TClass? if (t3 == null) return; new COpen<T>()[0] = t3; new CClass<T>()[0] = t3; new CClass2<T>()[0] = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>()[0] = t4; new CStruct<T>()[0] = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>()[0] = t5; // 8 new CStruct2<T>()[0] = t5; // 9 if (t5 == null) return; new COpen<T?>()[0] = t5; new CStruct2<T>()[0] = t5; } }"; var expected = new[] { // (6,29): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T>()[0] = t1; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(6, 29), // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 14), // (14,29): warning CS8601: Possible null reference assignment. // new COpen<T>()[0] = t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(14, 29), // (15,30): warning CS8601: Possible null reference assignment. // new CClass<T>()[0] = t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(15, 30), // (16,31): warning CS8601: Possible null reference assignment. // new CClass2<T>()[0] = t2; // 4, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(16, 31), // (20,29): warning CS8601: Possible null reference assignment. // new COpen<T>()[0] = t3; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(20, 29), // (21,30): warning CS8601: Possible null reference assignment. // new CClass<T>()[0] = t3; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(21, 30), // (22,31): warning CS8601: Possible null reference assignment. // new CClass2<T>()[0] = t3; // 7, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(22, 31), // (35,30): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T?>()[0] = t5; // 8 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(35, 30), // (36,32): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new CStruct2<T>()[0] = t5; // 9 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(36, 32) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void DisallowNull_Indexer_OtherParameters_String() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public string? this[[DisallowNull] string? s] { set => throw null!; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new C()[s] = s; // 1 new C()[s2] = s; } }"; var expected = new[] { // (6,17): warning CS8604: Possible null reference argument for parameter 's' in 'string? C.this[string? s]'. // new C()[s] = s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s").WithArguments("s", "string? C.this[string? s]").WithLocation(6, 17) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void DisallowNull_Indexer_OtherParameters_NullableInt() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public int? this[[DisallowNull] int? s] { set => throw null!; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(int? i, int i2) { new C()[i] = i; // 1 new C()[i2] = i; } }"; var expected = new[] { // (6,17): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // new C()[i] = i; // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "i").WithLocation(6, 17) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void DisallowNull_Indexer_OtherParameters_OverridingGetter() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual string this[[DisallowNull] string? s] { get => throw null!; } } public class C : Base { public override string this[string? s] { get => throw null!; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new C()[s].ToString(); new C()[s2].ToString(); } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(); } [Fact, WorkItem(36630, "https://github.com/dotnet/roslyn/issues/36630")] public void DisallowNull_Indexer_OtherParameters_OverridingGetterOnly() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual string this[[DisallowNull] string? s] { get => throw null!; set => throw null!; } } public class C : Base { public override string this[string? s] { set => throw null!; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new C()[s].ToString(); // 1 new C()[s2].ToString(); } }"; // Should report a warning for explicit parameter on getter https://github.com/dotnet/roslyn/issues/36630 var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(); } [Fact] public void DisallowNull_Indexer_OtherParameters_OverridingSetterOnly() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual string this[[DisallowNull] string? s] { get => throw null!; set => throw null!; } } public class C : Base { public override string this[string? s] { get => throw null!; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new C()[s].ToString(); new C()[s2].ToString(); } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(); } [Fact] public void MaybeNullWhenFalse_WithNotNullWhenTrue() { var source = @"using System.Diagnostics.CodeAnalysis; internal class C<T> where T : class? { public bool TryGetTarget([MaybeNullWhen(false), NotNullWhen(true)] out T target) => throw null!; public string Method(C<string> wr) { if (!wr.TryGetTarget(out string? s)) { s = """"; } return s; } }"; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNull_WithNotNull() { var source = @"using System.Diagnostics.CodeAnalysis; internal class C<T> where T : class? { public bool F([MaybeNull, NotNull] out T target) => throw null!; [return: MaybeNull, NotNull] public T F2() => throw null!; public string Method(C<string> wr) { if (!wr.F(out string? s)) { s = """"; } return s; // 1 } public string Method2(C<string> wr, bool b) { var s = wr.F2(); if (b) return s; // 2 s = null; throw null!; } }"; // MaybeNull wins over NotNull var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,16): warning CS8603: Possible null reference return. // return s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(13, 16), // (19,20): warning CS8603: Possible null reference return. // return s; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(19, 20) ); } [Fact, WorkItem(36410, "https://github.com/dotnet/roslyn/issues/36410")] public void MaybeNull_WithNotNullWhenTrue() { var source = @"using System.Diagnostics.CodeAnalysis; internal class C<T> where T : class? { public bool TryGetTarget([MaybeNull, NotNullWhen(true)] out T target) => throw null!; public string Method(C<string> wr) { if (wr.TryGetTarget(out string? s)) { return s; } return s; // 1 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,16): warning CS8603: Possible null reference return. // return s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(11, 16) ); } [Fact, WorkItem(36410, "https://github.com/dotnet/roslyn/issues/36410")] public void MaybeNull_WithNotNullWhenFalse() { var source = @"using System.Diagnostics.CodeAnalysis; internal class C<T> where T : class? { public bool TryGetTarget([MaybeNull, NotNullWhen(false)] out T target) => throw null!; public string Method(C<string> wr) { if (wr.TryGetTarget(out string? s)) { return s; // 1 } return s; } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (9,20): warning CS8603: Possible null reference return. // return s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(9, 20) ); } [Fact] public void MaybeNull_ReturnValue_01() { // Warn on misused nullability attributes (F2, F3, F4)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull] static T F1<T>(T t) => t; [return: MaybeNull] static T F2<T>(T t) where T : class => t; [return: MaybeNull] static T? F3<T>(T t) where T : class => t; [return: MaybeNull] static T F4<T>(T t) where T : struct => t; [return: MaybeNull] static T? F5<T>(T? t) where T : struct => t; static void M1<T>(T t1) { F1(t1).ToString(); // 0, 1 _ = F1(t1)!; } static void M2<T>(T t2) where T : class { F1(t2).ToString(); // 2 F2(t2).ToString(); // 3 F3(t2).ToString(); // 4 t2 = null; // 5 F1(t2).ToString(); // 6 F2(t2).ToString(); // 7 F3(t2).ToString(); // 8 } static void M3<T>(T? t3) where T : class { F1(t3).ToString(); // 9 F2(t3).ToString(); // 10 F3(t3).ToString(); // 11 if (t3 == null) return; F1(t3).ToString(); // 12 F2(t3).ToString(); // 13 F3(t3).ToString(); // 14 } static void M4<T>(T t4) where T : struct { F1(t4).ToString(); F4(t4).ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1(t5).Value; // 15 _ = F5(t5).Value; // 16 if (t5 == null) return; _ = F1(t5).Value; // 17 _ = F5(t5).Value; // 18 } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(t1).ToString(); // 0, 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(t1)").WithLocation(11, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F1(t2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(t2)").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F2(t2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(t2)").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F3(t2).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(t2)").WithLocation(18, 9), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 14), // (20,9): warning CS8602: Dereference of a possibly null reference. // F1(t2).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(t2)").WithLocation(20, 9), // (21,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t2).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(21, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // F2(t2).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(t2)").WithLocation(21, 9), // (22,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t2).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T)", "T", "T?").WithLocation(22, 9), // (22,9): warning CS8602: Dereference of a possibly null reference. // F3(t2).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(t2)").WithLocation(22, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // F1(t3).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(t3)").WithLocation(26, 9), // (27,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t3).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(27, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // F2(t3).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(t3)").WithLocation(27, 9), // (28,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t3).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T)", "T", "T?").WithLocation(28, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // F3(t3).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(t3)").WithLocation(28, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // F1(t3).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(t3)").WithLocation(30, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // F2(t3).ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(t3)").WithLocation(31, 9), // (32,9): warning CS8602: Dereference of a possibly null reference. // F3(t3).ToString(); // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(t3)").WithLocation(32, 9), // (41,13): warning CS8629: Nullable value type may be null. // _ = F1(t5).Value; // 15 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(t5)").WithLocation(41, 13), // (42,13): warning CS8629: Nullable value type may be null. // _ = F5(t5).Value; // 16 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F5(t5)").WithLocation(42, 13), // (44,13): warning CS8629: Nullable value type may be null. // _ = F1(t5).Value; // 17 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(t5)").WithLocation(44, 13), // (45,13): warning CS8629: Nullable value type may be null. // _ = F5(t5).Value; // 18 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F5(t5)").WithLocation(45, 13)); } [Fact] public void MaybeNull_ReturnValue_02() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull] static T F1<T>(T t) => t; [return: MaybeNull] static T F2<T>(T t) where T : class => t; [return: MaybeNull] static T? F3<T>(T t) where T : class => t; [return: MaybeNull] static T F4<T>(T t) where T : struct => t; [return: MaybeNull] static T? F5<T>(T? t) where T : struct => t; static void M1<T>(T t1) { F1<T>(t1).ToString(); // 1 } static void M2<T>(bool b, T t2) where T : class { F1<T>(t2).ToString(); // 2 F2<T>(t2).ToString(); // 3 F3<T>(t2).ToString(); // 4 t2 = null; // 5 F1<T>(b ? t2 : default).ToString(); // 6 F2<T>(b ? t2 : default).ToString(); // 7 F3<T>(b ? t2 : default).ToString(); // 8 } static void M3<T>(bool b, T? t3) where T : class { F1<T>(b ? t3 : default).ToString(); // 9 F2<T>(b ? t3 : default).ToString(); // 10 F3<T>(b ? t3 : default).ToString(); // 11 if (t3 == null) return; F1<T>(t3).ToString(); // 12 F2<T>(t3).ToString(); // 13 F3<T>(t3).ToString(); // 14 } static void M4<T>(T t4) where T : struct { F1<T>(t4).ToString(); F4<T>(t4).ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1<T?>(t5).Value; // 15 _ = F5<T>(t5).Value; // 16 if (t5 == null) return; _ = F1<T?>(t5).Value; // 17 _ = F5<T>(t5).Value; // 18 } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(t1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(t1)").WithLocation(11, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(t2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(t2)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(t2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(t2)").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(t2).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(t2)").WithLocation(17, 9), // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 14), // (19,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(b ? t2 : default).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(b ? t2 : default)").WithLocation(19, 9), // (19,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F1<T>(T t)'. // F1<T>(b ? t2 : default).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "T Program.F1<T>(T t)").WithLocation(19, 15), // (20,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(b ? t2 : default).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(b ? t2 : default)").WithLocation(20, 9), // (20,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F2<T>(T t)'. // F2<T>(b ? t2 : default).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "T Program.F2<T>(T t)").WithLocation(20, 15), // (21,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(b ? t2 : default).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(b ? t2 : default)").WithLocation(21, 9), // (21,15): warning CS8604: Possible null reference argument for parameter 't' in 'T? Program.F3<T>(T t)'. // F3<T>(b ? t2 : default).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "T? Program.F3<T>(T t)").WithLocation(21, 15), // (25,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(b ? t3 : default).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(b ? t3 : default)").WithLocation(25, 9), // (25,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F1<T>(T t)'. // F1<T>(b ? t3 : default).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "T Program.F1<T>(T t)").WithLocation(25, 15), // (26,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(b ? t3 : default).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(b ? t3 : default)").WithLocation(26, 9), // (26,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F2<T>(T t)'. // F2<T>(b ? t3 : default).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "T Program.F2<T>(T t)").WithLocation(26, 15), // (27,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(b ? t3 : default).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(b ? t3 : default)").WithLocation(27, 9), // (27,15): warning CS8604: Possible null reference argument for parameter 't' in 'T? Program.F3<T>(T t)'. // F3<T>(b ? t3 : default).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "T? Program.F3<T>(T t)").WithLocation(27, 15), // (29,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(t3).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(t3)").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(t3).ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(t3)").WithLocation(30, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(t3).ToString(); // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(t3)").WithLocation(31, 9), // (40,13): warning CS8629: Nullable value type may be null. // _ = F1<T?>(t5).Value; // 15 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1<T?>(t5)").WithLocation(40, 13), // (41,13): warning CS8629: Nullable value type may be null. // _ = F5<T>(t5).Value; // 16 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F5<T>(t5)").WithLocation(41, 13), // (43,13): warning CS8629: Nullable value type may be null. // _ = F1<T?>(t5).Value; // 17 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1<T?>(t5)").WithLocation(43, 13), // (44,13): warning CS8629: Nullable value type may be null. // _ = F5<T>(t5).Value; // 18 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F5<T>(t5)").WithLocation(44, 13)); } [Fact] public void MaybeNull_ReturnValue_02_WithNotNull() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull, NotNull] static T F1<T>(T t) => t; // [return: MaybeNull, NotNull] static T F2<T>(T t) where T : class => t; [return: MaybeNull, NotNull] static T? F3<T>(T t) where T : class => t; [return: MaybeNull, NotNull] static T F4<T>(T t) where T : struct => t; [return: MaybeNull, NotNull] static T? F5<T>(T? t) where T : struct => t; // static void M1<T>(T t1) { F1<T>(t1).ToString(); // 0, 1 } static void M2<T>(bool b, T t2) where T : class { F1<T>(t2).ToString(); // 2 F2<T>(t2).ToString(); // 3 F3<T>(t2).ToString(); // 4 t2 = null; // 5 F1<T>(b ? t2 : default).ToString(); // 6 F2<T>(b ? t2 : default).ToString(); // 7 F3<T>(b ? t2 : default).ToString(); // 8 } static void M3<T>(bool b, T? t3) where T : class { F1<T>(b ? t3 : default).ToString(); // 9 F2<T>(b ? t3 : default).ToString(); // 10 F3<T>(b ? t3 : default).ToString(); // 11 if (t3 == null) return; F1<T>(t3).ToString(); // 12 F2<T>(t3).ToString(); // 13 F3<T>(t3).ToString(); // 14 } static void M4<T>(T t4) where T : struct { F1<T>(t4).ToString(); F4<T>(t4).ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1<T?>(t5).Value; // 15 _ = F5<T>(t5).Value; // 16 if (t5 == null) return; _ = F1<T?>(t5).Value; // 17 _ = F5<T>(t5).Value; // 18 } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,57): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: MaybeNull, NotNull] static T F1<T>(T t) => t; // Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(4, 57), // (8,76): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: MaybeNull, NotNull] static T? F5<T>(T? t) where T : struct => t; // Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(8, 76), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(t1).ToString(); // 0, 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(t1)").WithLocation(11, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(t2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(t2)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(t2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(t2)").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(t2).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(t2)").WithLocation(17, 9), // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 14), // (19,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(b ? t2 : default).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(b ? t2 : default)").WithLocation(19, 9), // (19,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F1<T>(T t)'. // F1<T>(b ? t2 : default).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "T Program.F1<T>(T t)").WithLocation(19, 15), // (20,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(b ? t2 : default).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(b ? t2 : default)").WithLocation(20, 9), // (20,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F2<T>(T t)'. // F2<T>(b ? t2 : default).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "T Program.F2<T>(T t)").WithLocation(20, 15), // (21,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(b ? t2 : default).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(b ? t2 : default)").WithLocation(21, 9), // (21,15): warning CS8604: Possible null reference argument for parameter 't' in 'T? Program.F3<T>(T t)'. // F3<T>(b ? t2 : default).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "T? Program.F3<T>(T t)").WithLocation(21, 15), // (25,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(b ? t3 : default).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(b ? t3 : default)").WithLocation(25, 9), // (25,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F1<T>(T t)'. // F1<T>(b ? t3 : default).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "T Program.F1<T>(T t)").WithLocation(25, 15), // (26,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(b ? t3 : default).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(b ? t3 : default)").WithLocation(26, 9), // (26,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F2<T>(T t)'. // F2<T>(b ? t3 : default).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "T Program.F2<T>(T t)").WithLocation(26, 15), // (27,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(b ? t3 : default).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(b ? t3 : default)").WithLocation(27, 9), // (27,15): warning CS8604: Possible null reference argument for parameter 't' in 'T? Program.F3<T>(T t)'. // F3<T>(b ? t3 : default).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "T? Program.F3<T>(T t)").WithLocation(27, 15), // (29,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(t3).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(t3)").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(t3).ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(t3)").WithLocation(30, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(t3).ToString(); // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(t3)").WithLocation(31, 9), // (40,13): warning CS8629: Nullable value type may be null. // _ = F1<T?>(t5).Value; // 15 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1<T?>(t5)").WithLocation(40, 13), // (41,13): warning CS8629: Nullable value type may be null. // _ = F5<T>(t5).Value; // 16 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F5<T>(t5)").WithLocation(41, 13), // (43,13): warning CS8629: Nullable value type may be null. // _ = F1<T?>(t5).Value; // 17 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1<T?>(t5)").WithLocation(43, 13), // (44,13): warning CS8629: Nullable value type may be null. // _ = F5<T>(t5).Value; // 18 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F5<T>(t5)").WithLocation(44, 13)); } [Fact] public void MaybeNull_ReturnValue_03() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull] static string F1() => string.Empty; [return: MaybeNull] static string? F2() => string.Empty; static void M() { F1().ToString(); // 1 F2().ToString(); // 2 } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F1().ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1()").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F2().ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2()").WithLocation(9, 9)); } [Fact] public void MaybeNull_ReturnValue_04() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull] static int F1() => 1; [return: MaybeNull] static int? F2() => 2; static void M() { F1().ToString(); _ = F2().Value; // 1 } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8629: Nullable value type may be null. // _ = F2().Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2()").WithLocation(9, 13)); } [Fact] public void MaybeNull_ReturnValue_05() { // Warn on misused nullability attributes (F2)? https://github.com/dotnet/roslyn/issues/36073 var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static T F1<T>(T t) where T : class => t; [return: MaybeNull] public static T F2<T>(T t) where T : class => t; }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x).ToString(); // 2, 3 F1(y).ToString(); F2(x).ToString(); // 4, 5 F2(y).ToString(); // 6 } }"; comp = CreateCompilation(source, references: new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(x).ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T)", "T", "object?").WithLocation(7, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (9,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x).ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T)", "T", "object?").WithLocation(9, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(10, 9) ); } [Fact] public void MaybeNull_ReturnValue_05_Unconstrained() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static T F1<T>(T t) => t; [return: MaybeNull] public static T F2<T>(T t) => t; }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x).ToString(); // 2 F1(y).ToString(); F2(x).ToString(); // 3 F2(y).ToString(); // 4 } }"; comp = CreateCompilation(source, references: new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(10, 9) ); } [Fact] public void MaybeNull_ReturnValue_06() { var source = @"using System.Diagnostics.CodeAnalysis; class C<T> { [return: MaybeNull] internal static T F() => throw null!; } class Program { static void M<T, U, V>() where U : class where V : struct { C<T>.F().ToString(); // 0, 1 C<U>.F().ToString(); // 2 C<U?>.F().ToString(); // 3 C<V>.F().ToString(); _ = C<V?>.F().Value; // 4 C<string>.F().ToString(); // 5 C<string?>.F().ToString(); // 6 C<int>.F().ToString(); _ = C<int?>.F().Value; // 7 } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // C<T>.F().ToString(); // 0, 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T>.F()").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // C<U>.F().ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<U>.F()").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // C<U?>.F().ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<U?>.F()").WithLocation(14, 9), // (16,13): warning CS8629: Nullable value type may be null. // _ = C<V?>.F().Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "C<V?>.F()").WithLocation(16, 13), // (17,9): warning CS8602: Dereference of a possibly null reference. // C<string>.F().ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<string>.F()").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // C<string?>.F().ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<string?>.F()").WithLocation(18, 9), // (20,13): warning CS8629: Nullable value type may be null. // _ = C<int?>.F().Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "C<int?>.F()").WithLocation(20, 13)); } [Fact] public void MaybeNull_InOrByValParameter() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s1, string s2) { _ = M(s1) ? s1.ToString() // 1 : s1.ToString(); // 2 _ = M(s2) ? s2.ToString() // 3 : s2.ToString(); // 4 } public static bool M([MaybeNull] in string s) => throw null!; public static bool M2([MaybeNull] string s) => throw null!; } ", MaybeNullAttributeDefinition }, options: WithNullableEnable()); // Warn on misused nullability attributes (warn on parameters of M and M2)? https://github.com/dotnet/roslyn/issues/36073 c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // ? s1.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(8, 15), // (9,15): warning CS8602: Dereference of a possibly null reference. // : s1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // ? s2.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 15), // (13,15): warning CS8602: Dereference of a possibly null reference. // : s2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(13, 15) ); } [Fact] public void MaybeNull_OutParameter_01() { // Warn on misused nullability attributes (F2, F3, F4 and probably F5)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>(T t, [MaybeNull]out T t2) { t2 = t; } static void F2<T>(T t, [MaybeNull]out T t2) where T : class { t2 = t; } static void F3<T>(T t, [MaybeNull]out T? t2) where T : class { t2 = t; } static void F4<T>(T t, [MaybeNull]out T t2) where T : struct { t2 = t; } static void F5<T>(T? t, [MaybeNull]out T? t2) where T : struct { t2 = t; } static void M1<T>(T t1) { F1(t1, out var s2); // 0 s2.ToString(); // 1 } static void M2<T>(T t2) where T : class { F1(t2, out var s3); s3.ToString(); // 2 F2(t2, out var s4); s4.ToString(); // 3 F3(t2, out var s5); s5.ToString(); // 4 t2 = null; // 5 F1(t2, out var s6); s6.ToString(); // 6 F2(t2, out var s7); // 7 s7.ToString(); // 8 F3(t2, out var s8); // 9 s8.ToString(); // 10 } static void M3<T>(T? t3) where T : class { F1(t3, out var s9); s9.ToString(); // 11 F2(t3, out var s10); // 12 s10.ToString(); // 13 F3(t3, out var s11); // 14 s11.ToString(); // 15 if (t3 == null) return; F1(t3, out var s12); s12.ToString(); // 16 F2(t3, out var s13); s13.ToString(); // 17 F3(t3, out var s14); s14.ToString(); // 18 } static void M4<T>(T t4) where T : struct { F1(t4, out var s15); s15.ToString(); F4(t4, out var s16); s16.ToString(); } static void M5<T>(T? t5) where T : struct { F1(t5, out var s17); _ = s17.Value; // 19 F5(t5, out var s18); _ = s18.Value; // 20 if (t5 == null) return; F1(t5, out var s19); _ = s19.Value; // 21 F5(t5, out var s20); _ = s20.Value; // 22 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // s3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(17, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(20, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // s5.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(23, 9), // (25,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(25, 14), // (27,9): warning CS8602: Dereference of a possibly null reference. // s6.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(27, 9), // (29,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t2, out var s7); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // s7.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s7").WithLocation(30, 9), // (32,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t2, out var s8); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(32, 9), // (33,9): warning CS8602: Dereference of a possibly null reference. // s8.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s8").WithLocation(33, 9), // (38,9): warning CS8602: Dereference of a possibly null reference. // s9.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s9").WithLocation(38, 9), // (40,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t3, out var s10); // 12 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(40, 9), // (41,9): warning CS8602: Dereference of a possibly null reference. // s10.ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s10").WithLocation(41, 9), // (43,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t3, out var s11); // 14 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(43, 9), // (44,9): warning CS8602: Dereference of a possibly null reference. // s11.ToString(); // 15 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s11").WithLocation(44, 9), // (48,9): warning CS8602: Dereference of a possibly null reference. // s12.ToString(); // 16 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s12").WithLocation(48, 9), // (51,9): warning CS8602: Dereference of a possibly null reference. // s13.ToString(); // 17 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s13").WithLocation(51, 9), // (54,9): warning CS8602: Dereference of a possibly null reference. // s14.ToString(); // 18 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s14").WithLocation(54, 9), // (67,13): warning CS8629: Nullable value type may be null. // _ = s17.Value; // 19 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s17").WithLocation(67, 13), // (70,13): warning CS8629: Nullable value type may be null. // _ = s18.Value; // 20 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s18").WithLocation(70, 13), // (74,13): warning CS8629: Nullable value type may be null. // _ = s19.Value; // 21 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s19").WithLocation(74, 13), // (77,13): warning CS8629: Nullable value type may be null. // _ = s20.Value; // 22 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s20").WithLocation(77, 13) ); } [Fact] public void MaybeNull_OutParameter_02() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>(T t, [MaybeNull]out T t2) => throw null!; static void F2<T>(T t, [MaybeNull]out T t2) where T : class => throw null!; static void F3<T>(T t, [MaybeNull]out T? t2) where T : class => throw null!; static void F4<T>(T t, [MaybeNull]out T t2) where T : struct => throw null!; static void F5<T>(T? t, [MaybeNull]out T? t2) where T : struct => throw null!; static void M1<T>(T t1) { F1<T>(t1, out var s1); // 0 s1.ToString(); // 1 } static void M2<T>(bool b, T t2) where T : class { F1<T>(t2, out var s2); s2.ToString(); // 2 F2<T>(t2, out var s3); s3.ToString(); // 3 F3<T>(t2, out var s4); s4.ToString(); // 4 t2 = null; // 5 F1<T>(b ? t2 : default, out var s5); // 6 s5.ToString(); // 6B F2<T>(b ? t2 : default, out var s6); // 7 s6.ToString(); // 7B F3<T>(b ? t2 : default, out var s7); // 8 s7.ToString(); // 8B } static void M3<T>(bool b, T? t3) where T : class { F1<T>(b ? t3 : default, out var s8); // 9 s8.ToString(); // 9B F2<T>(b ? t3 : default, out var s9); // 10 s9.ToString(); // 10B F3<T>(b ? t3 : default, out var s10); // 11 s10.ToString(); // 11B if (t3 == null) return; F1<T>(t3, out var s11); s11.ToString(); // 12 F2<T>(t3, out var s12); s12.ToString(); // 13 F3<T>(t3, out var s13); s13.ToString(); // 14 } static void M4<T>(T t4) where T : struct { F1<T>(t4, out var s14); s14.ToString(); F4<T>(t4, out var s15); s15.ToString(); } static void M5<T>(T? t5) where T : struct { F1<T?>(t5, out var s16); _ = s16.Value; // 15 F5<T>(t5, out var s17); _ = s17.Value; // 16 if (t5 == null) return; F1<T?>(t5, out var s18); _ = s18.Value; // 17 F5<T>(t5, out var s19); _ = s19.Value; // 18 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(12, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(17, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // s3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(20, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(23, 9), // (25,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(25, 14), // (26,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T>(T t, out T t2)'. // F1<T>(b ? t2 : default, out var s5); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "void Program.F1<T>(T t, out T t2)").WithLocation(26, 15), // (27,9): warning CS8602: Dereference of a possibly null reference. // s5.ToString(); // 6B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(27, 9), // (29,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T>(T t, out T t2)'. // F2<T>(b ? t2 : default, out var s6); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "void Program.F2<T>(T t, out T t2)").WithLocation(29, 15), // (30,9): warning CS8602: Dereference of a possibly null reference. // s6.ToString(); // 7B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(30, 9), // (32,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T t, out T? t2)'. // F3<T>(b ? t2 : default, out var s7); // 8 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "void Program.F3<T>(T t, out T? t2)").WithLocation(32, 15), // (33,9): warning CS8602: Dereference of a possibly null reference. // s7.ToString(); // 8B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s7").WithLocation(33, 9), // (37,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T>(T t, out T t2)'. // F1<T>(b ? t3 : default, out var s8); // 9 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "void Program.F1<T>(T t, out T t2)").WithLocation(37, 15), // (38,9): warning CS8602: Dereference of a possibly null reference. // s8.ToString(); // 9B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s8").WithLocation(38, 9), // (40,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T>(T t, out T t2)'. // F2<T>(b ? t3 : default, out var s9); // 10 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "void Program.F2<T>(T t, out T t2)").WithLocation(40, 15), // (41,9): warning CS8602: Dereference of a possibly null reference. // s9.ToString(); // 10B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s9").WithLocation(41, 9), // (43,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T t, out T? t2)'. // F3<T>(b ? t3 : default, out var s10); // 11 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "void Program.F3<T>(T t, out T? t2)").WithLocation(43, 15), // (44,9): warning CS8602: Dereference of a possibly null reference. // s10.ToString(); // 11B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s10").WithLocation(44, 9), // (48,9): warning CS8602: Dereference of a possibly null reference. // s11.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s11").WithLocation(48, 9), // (51,9): warning CS8602: Dereference of a possibly null reference. // s12.ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s12").WithLocation(51, 9), // (54,9): warning CS8602: Dereference of a possibly null reference. // s13.ToString(); // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s13").WithLocation(54, 9), // (67,13): warning CS8629: Nullable value type may be null. // _ = s16.Value; // 15 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s16").WithLocation(67, 13), // (70,13): warning CS8629: Nullable value type may be null. // _ = s17.Value; // 16 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s17").WithLocation(70, 13), // (74,13): warning CS8629: Nullable value type may be null. // _ = s18.Value; // 17 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s18").WithLocation(74, 13), // (77,13): warning CS8629: Nullable value type may be null. // _ = s19.Value; // 18 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s19").WithLocation(77, 13) ); } [Fact] public void MaybeNull_OutParameter_03() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([MaybeNull]out string t) => throw null!; static void F2([MaybeNull]out string? t) => throw null!; static void M() { F1(out var t1); t1.ToString(); // 1 F2(out var t2); t2.ToString(); // 2 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(9, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(12, 9) ); } [Fact] public void MaybeNull_OutParameter_04() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([MaybeNull]out int i) => throw null!; static void F2([MaybeNull]out int? i) => throw null!; static void M() { F1(out var i1); i1.ToString(); F2(out var i2); _ = i2.Value; // 1 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,13): warning CS8629: Nullable value type may be null. // _ = i2.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i2").WithLocation(12, 13) ); } [Fact] public void MaybeNull_OutParameter_05() { // Warn on misused nullability attributes (F2)? https://github.com/dotnet/roslyn/issues/36073 var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static void F1<T>(T t, out T t2) where T : class => throw null!; public static void F2<T>(T t, [MaybeNull]out T t2) where T : class => throw null!; }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source0 }); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x, out var o1); // 2 o1.ToString(); // 2B F1(y, out var o2); o2.ToString(); F2(x, out var o3); // 3 o3.ToString(); // 3B F2(y, out var o4); o4.ToString(); // 4 } }"; comp = CreateNullableCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T, out T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(x, out var o1); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T, out T)", "T", "object?").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // o1.ToString(); // 2B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o1").WithLocation(8, 9), // (13,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T, out T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x, out var o3); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T, out T)", "T", "object?").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // o3.ToString(); // 3B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o3").WithLocation(14, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // o4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o4").WithLocation(17, 9) ); } [Fact] public void MaybeNull_OutParameter_05_Unconstrained() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static void F2<T>(T t, [MaybeNull]out T t2) => throw null!; }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source0 }); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F2(x, out var o3); o3.ToString(); // 2 F2(y, out var o4); o4.ToString(); // 3 } }"; comp = CreateNullableCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (9,9): warning CS8602: Dereference of a possibly null reference. // o3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o3").WithLocation(9, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // o4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o4").WithLocation(12, 9) ); } [Fact] public void MaybeNull_OutParameter_06() { var source = @"using System.Diagnostics.CodeAnalysis; class C<T> { internal static void F([MaybeNull]out T t) => throw null!; } class Program { static void M<T, U, V>() where U : class where V : struct { C<T>.F(out var o1); // 0 o1.ToString(); // 1 C<U>.F(out var o2); o2.ToString(); // 2 C<U?>.F(out var o3); o3.ToString(); // 3 C<V>.F(out var o4); o4.ToString(); C<V?>.F(out var o5); _ = o5.Value; // 4 C<string>.F(out var o6); o6.ToString(); // 5 C<string?>.F(out var o7); o7.ToString(); // 6 C<int>.F(out var o8); o8.ToString(); C<int?>.F(out var o9); _ = o9.Value; // 7 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // o1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o1").WithLocation(13, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // o2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o2").WithLocation(16, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // o3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o3").WithLocation(19, 9), // (25,13): warning CS8629: Nullable value type may be null. // _ = o5.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "o5").WithLocation(25, 13), // (28,9): warning CS8602: Dereference of a possibly null reference. // o6.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o6").WithLocation(28, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // o7.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o7").WithLocation(31, 9), // (37,13): warning CS8629: Nullable value type may be null. // _ = o9.Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "o9").WithLocation(37, 13) ); } [Fact] public void MaybeNull_RefParameter_01() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>(T t, [MaybeNull]ref T t2) { t2 = t; } static void F2<T>(T t, [MaybeNull]ref T t2) where T : class { t2 = t; } static void F3<T>(T t, [MaybeNull]ref T? t2) where T : class { t2 = t; } static void F4<T>(T t, [MaybeNull]ref T t2) where T : struct { t2 = t; } static void F5<T>(T? t, [MaybeNull]ref T? t2) where T : struct { t2 = t; } static void M1<T>(T t1) { T s2 = default!; F1(t1, ref s2); // 0 s2.ToString(); // 1 } static void M2<T>(T t2) where T : class { T? s3 = default!; F1(t2, ref s3); s3.ToString(); // 2 T s4 = default!; F2(t2, ref s4); // 3 s4.ToString(); // 4 T s4b = default!; F2(t2, ref s4b!); // suppression applies after MaybeNull s4b.ToString(); T? s5 = default!; F3(t2, ref s5); s5.ToString(); // 5 t2 = null; // 6 T? s6 = default!; F1(t2, ref s6); s6.ToString(); // 7 T? s7 = default!; F2(t2, ref s7); // 8 s7.ToString(); // 9 T? s8 = default!; F3(t2, ref s8); // 10 s8.ToString(); // 11 } static void M3<T>(T? t3) where T : class { T? s9 = default!; F1(t3, ref s9); s9.ToString(); // 12 T s10 = default!; F2(t3, ref s10); // 13, 14 s10.ToString(); // 15 T? s11 = default!; F3(t3, ref s11); // 16 s11.ToString(); // 17 if (t3 == null) return; T s12 = default!; F1(t3, ref s12); // 18 s12.ToString(); // 19 T s13 = default!; F2(t3, ref s13); // 20 s13.ToString(); // 21 T? s14 = default!; F3(t3, ref s14); s14.ToString(); // 22 } static void M4<T>(T t4) where T : struct { T s15 = default; F1(t4, ref s15); s15.ToString(); T s16 = default; F4(t4, ref s16); s16.ToString(); } static void M5<T>(T? t5) where T : struct { T s17 = default!; F1(t5, ref s17); // 23 _ = s17.Value; // 24 T s18 = default!; F5(t5, ref s18); // 25 _ = s18.Value; // 26 if (t5 == null) return; T s19 = default!; F1(t5, ref s19); // 27 _ = s19.Value; // 28 T s20 = default!; F5(t5, ref s20); // 29 _ = s20.Value; // 30 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(13, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // s3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(19, 9), // (22,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // F2(t2, ref s4); // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s4").WithLocation(22, 20), // (23,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(23, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // s5.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(31, 9), // (33,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(33, 14), // (36,9): warning CS8602: Dereference of a possibly null reference. // s6.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(36, 9), // (39,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, ref T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t2, ref s7); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, ref T)", "T", "T?").WithLocation(39, 9), // (40,9): warning CS8602: Dereference of a possibly null reference. // s7.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s7").WithLocation(40, 9), // (43,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, ref T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t2, ref s8); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, ref T?)", "T", "T?").WithLocation(43, 9), // (44,9): warning CS8602: Dereference of a possibly null reference. // s8.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s8").WithLocation(44, 9), // (50,9): warning CS8602: Dereference of a possibly null reference. // s9.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s9").WithLocation(50, 9), // (53,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, ref T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t3, ref s10); // 12, 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, ref T)", "T", "T?").WithLocation(53, 9), // (53,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // F2(t3, ref s10); // 12, 13 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s10").WithLocation(53, 20), // (54,9): warning CS8602: Dereference of a possibly null reference. // s10.ToString(); // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s10").WithLocation(54, 9), // (57,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, ref T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t3, ref s11); // 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, ref T?)", "T", "T?").WithLocation(57, 9), // (58,9): warning CS8602: Dereference of a possibly null reference. // s11.ToString(); // 16 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s11").WithLocation(58, 9), // (62,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // F1(t3, ref s12); // 17 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s12").WithLocation(62, 20), // (63,9): warning CS8602: Dereference of a possibly null reference. // s12.ToString(); // 18 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s12").WithLocation(63, 9), // (66,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // F2(t3, ref s13); // 19 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s13").WithLocation(66, 20), // (67,9): warning CS8602: Dereference of a possibly null reference. // s13.ToString(); // 20 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s13").WithLocation(67, 9), // (71,9): warning CS8602: Dereference of a possibly null reference. // s14.ToString(); // 21 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s14").WithLocation(71, 9), // (86,9): error CS0411: The type arguments for method 'Program.F1<T>(T, ref T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(t5, ref s17); // 22 Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T, ref T)").WithLocation(86, 9), // (87,17): error CS1061: 'T' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // _ = s17.Value; // 23 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Value").WithArguments("T", "Value").WithLocation(87, 17), // (90,20): error CS1503: Argument 2: cannot convert from 'ref T' to 'ref T?' // F5(t5, ref s18); // 24 Diagnostic(ErrorCode.ERR_BadArgType, "s18").WithArguments("2", "ref T", "ref T?").WithLocation(90, 20), // (91,17): error CS1061: 'T' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // _ = s18.Value; // 25 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Value").WithArguments("T", "Value").WithLocation(91, 17), // (95,9): error CS0411: The type arguments for method 'Program.F1<T>(T, ref T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(t5, ref s19); // 26 Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T, ref T)").WithLocation(95, 9), // (96,17): error CS1061: 'T' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // _ = s19.Value; // 27 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Value").WithArguments("T", "Value").WithLocation(96, 17), // (99,20): error CS1503: Argument 2: cannot convert from 'ref T' to 'ref T?' // F5(t5, ref s20); // 28 Diagnostic(ErrorCode.ERR_BadArgType, "s20").WithArguments("2", "ref T", "ref T?").WithLocation(99, 20), // (100,17): error CS1061: 'T' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // _ = s20.Value; // 29 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Value").WithArguments("T", "Value").WithLocation(100, 17) ); } [Fact] public void MaybeNull_RefParameter_03() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([MaybeNull]ref string t) { t = null; } static void F2([MaybeNull]ref string? t) { t = null; } static void M() { string t1 = null!; F1(ref t1); // 1 t1.ToString(); // 2 string? t2 = null; F1(ref t2); // 3 t2.ToString(); // 4 string? t3 = null!; F2(ref t3); t3.ToString(); // 5 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (9,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // F1(ref t1); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t1").WithLocation(9, 16), // (10,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(10, 9), // (13,16): warning CS8601: Possible null reference assignment. // F1(ref t2); // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(13, 16), // (14,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(14, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // t3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3").WithLocation(18, 9) ); } [Fact] public void MaybeNull_MemberReference() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class C<T> { [MaybeNull] T F = default!; [MaybeNull] T P => default!; void M1() { _ = F; } static void M2(C<T> c) { _ = c.P; } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNull_MethodCall() { var source = @"#nullable enable using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; static class E { [return: MaybeNull] internal static T FirstOrDefault<T>(this IEnumerable<T> e) => throw null!; internal static bool TryGet<K, V>(this Dictionary<K, V> d, K key, [MaybeNullWhen(false)] out V value) => throw null!; } class Program { [return: MaybeNull] static T M1<T>(IEnumerable<T> e) { e.FirstOrDefault(); _ = e.FirstOrDefault(); return e.FirstOrDefault(); } static void M2<K, V>(Dictionary<K, V> d, K key) { d.TryGet(key, out var value); } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void NotNull_ReturnValue_01() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: NotNull] static T F1<T>(T t) => t; // 00 [return: NotNull] static T F2<T>(T t) where T : class => t; [return: NotNull] static T? F3<T>(T t) where T : class => t; [return: NotNull] static T F4<T>(T t) where T : struct => t; [return: NotNull] static T? F5<T>(T? t) where T : struct => t; // 0 static void M1<T>(T t1) { F1(t1).ToString(); } static void M2<T>(T t2) where T : class { F1(t2).ToString(); F2(t2).ToString(); F3(t2).ToString(); t2 = null; // 1 F1(t2).ToString(); F2(t2).ToString(); // 2 F3(t2).ToString(); // 3 } static void M3<T>(T? t3) where T : class { F1(t3).ToString(); F2(t3).ToString(); // 4 F3(t3).ToString(); // 5 if (t3 == null) return; F1(t3).ToString(); F2(t3).ToString(); F3(t3).ToString(); } static void M4<T>(T t4) where T : struct { F1(t4).ToString(); F4(t4).ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1(t5).Value; _ = F5(t5).Value; if (t5 == null) return; _ = F1(t5).Value; _ = F5(t5).Value; } }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,46): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull] static T F1<T>(T t) => t; // 00 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(4, 46), // (8,65): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull] static T? F5<T>(T? t) where T : struct => t; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(8, 65), // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 14), // (20,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(20, 9), // (21,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T)", "T", "T?").WithLocation(21, 9), // (26,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t3).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(26, 9), // (27,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t3).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T)", "T", "T?").WithLocation(27, 9) ); } [Fact] public void NotNull_ReturnValue_02() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: NotNull] static T F1<T>(T t) => t; // 00 [return: NotNull] static T F2<T>(T t) where T : class => t; [return: NotNull] static T? F3<T>(T t) where T : class => t; [return: NotNull] static T F4<T>(T t) where T : struct => t; [return: NotNull] static T? F5<T>(T? t) where T : struct => t; // 0 static void M1<T>(T t1) { F1<T>(t1).ToString(); } static void M2<T>(bool b, T t2) where T : class { F1<T>(t2).ToString(); F2<T>(t2).ToString(); F3<T>(t2).ToString(); t2 = null; // 1 if (b) F1<T>(t2).ToString(); // 2 if (b) F2<T>(t2).ToString(); // 3 if (b) F3<T>(t2).ToString(); // 4 } static void M3<T>(bool b, T? t3) where T : class { if (b) F1<T>(t3).ToString(); // 5 if (b) F2<T>(t3).ToString(); // 6 if (b) F3<T>(t3).ToString(); // 7 if (t3 == null) return; F1<T>(t3).ToString(); F2<T>(t3).ToString(); F3<T>(t3).ToString(); } static void M4<T>(T t4) where T : struct { F1<T>(t4).ToString(); F4<T>(t4).ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1<T?>(t5).Value; _ = F5<T>(t5).Value; if (t5 == null) return; _ = F1<T?>(t5).Value; _ = F5<T>(t5).Value; } }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,46): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull] static T F1<T>(T t) => t; // 00 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(4, 46), // (8,65): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull] static T? F5<T>(T? t) where T : struct => t; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(8, 65), // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 14), // (19,22): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F1<T>(T t)'. // if (b) F1<T>(t2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "T Program.F1<T>(T t)").WithLocation(19, 22), // (20,22): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F2<T>(T t)'. // if (b) F2<T>(t2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "T Program.F2<T>(T t)").WithLocation(20, 22), // (21,22): warning CS8604: Possible null reference argument for parameter 't' in 'T? Program.F3<T>(T t)'. // if (b) F3<T>(t2).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "T? Program.F3<T>(T t)").WithLocation(21, 22), // (25,22): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F1<T>(T t)'. // if (b) F1<T>(t3).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "T Program.F1<T>(T t)").WithLocation(25, 22), // (26,22): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F2<T>(T t)'. // if (b) F2<T>(t3).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "T Program.F2<T>(T t)").WithLocation(26, 22), // (27,22): warning CS8604: Possible null reference argument for parameter 't' in 'T? Program.F3<T>(T t)'. // if (b) F3<T>(t3).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "T? Program.F3<T>(T t)").WithLocation(27, 22)); } [Fact] public void NotNull_ReturnValue_03() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: NotNull] static string F1() => string.Empty; [return: NotNull] static string? F2() => string.Empty; static void M() { F1().ToString(); F2().ToString(); } }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NotNull_ReturnValue_04() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: NotNull] static int F1() => 1; [return: NotNull] static int? F2() => 2; static void M() { F1().ToString(); _ = F2().Value; } }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NotNull_ReturnValue_05() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static T F1<T>(T t) where T : class => t; [return: NotNull] public static T F2<T>(T t) where T : class => t; }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x).ToString(); // 2, 3 F1(y).ToString(); F2(x).ToString(); // 4 F2(y).ToString(); } }"; comp = CreateCompilation(source, references: new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(x).ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T)", "T", "object?").WithLocation(7, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (9,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T)", "T", "object?").WithLocation(9, 9) ); } [Fact] public void NotNull_ReturnValue_05_Unconstrained() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static T F1<T>(T t) => t; [return: NotNull] public static T F2<T>(T t) => t; }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source0 }); comp.VerifyDiagnostics( // (5,53): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull] public static T F2<T>(T t) => t; Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(5, 53) ); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x).ToString(); // 2 F1(y).ToString(); F2(x).ToString(); F2(y).ToString(); } }"; comp = CreateNullableCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9) ); } [Fact] public void NotNull_ReturnValue_05_Unconstrained_WithMaybeNull() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { [return: NotNull, MaybeNull] public static T F2<T>(T t) => t; }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullAttributeDefinition, source0 }); comp.VerifyDiagnostics( // (4,64): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull, MaybeNull] public static T F2<T>(T t) => t; Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(4, 64) ); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F2(x).ToString(); // 2 F2(y).ToString(); // 3 } }"; comp = CreateNullableCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(8, 9) ); } [Fact] public void NotNull_ReturnValue_05_Unconstrained_WithMaybeNull_InSource() { var source = @"using System.Diagnostics.CodeAnalysis; public class A { [return: NotNull, MaybeNull] public static T F2<T>(T t) => t; // 0 } class B : A { static void Main() { object x = null; // 1 object? y = new object(); F2(x).ToString(); // 2 F2(y).ToString(); // 3 } }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,64): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull, MaybeNull] public static T F2<T>(T t) => t; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(4, 64), // (10,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(10, 20), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(13, 9) ); } [Fact] public void NotNull_ReturnValue_06() { var source = @"using System.Diagnostics.CodeAnalysis; class C<T> { [return: NotNull] internal static T F() => throw null!; } class Program { static void M<T, U, V>() where U : class where V : struct { C<T>.F().ToString(); C<U>.F().ToString(); C<U?>.F().ToString(); C<V>.F().ToString(); _ = C<V?>.F().Value; C<string>.F().ToString(); C<string?>.F().ToString(); C<int>.F().ToString(); _ = C<int?>.F().Value; } }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NotNull_Property() { // Warn on misused nullability attributes (P3, P5)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [NotNull]public TOpen P1 { get; set; } = default!; } public class CClass<TClass> where TClass : class { [NotNull]public TClass P2 { get; set; } = null!; [NotNull]public TClass? P3 { get; set; } = null; } public class CStruct<TStruct> where TStruct : struct { [NotNull]public TStruct P4 { get; set; } [NotNull]public TStruct? P5 { get; set; } }"; var lib = CreateNullableCompilation(new[] { lib_cs, NotNullAttributeDefinition }); var source = @" class C { static void M1<T>(T t1) { new COpen<T>().P1.ToString(); } static void M2<T>(T t2) where T : class { new COpen<T>().P1.ToString(); new CClass<T>().P2.ToString(); new CClass<T>().P3.ToString(); } static void M4<T>(T t4) where T : struct { new COpen<T>().P1.ToString(); new CStruct<T>().P4.ToString(); } static void M5<T>(T? t5) where T : struct { new COpen<T?>().P1.Value.ToString(); new CStruct<T>().P5.Value.ToString(); } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullAttributeDefinition }); comp2.VerifyDiagnostics(); } [Fact, WorkItem(36073, "https://github.com/dotnet/roslyn/issues/36073")] public void NotNull_Property_InitializedInConstructor() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [NotNull]public TOpen P1 { get; set; } COpen() // 1 { P1 = default; // 2 } } public class CClass<TClass> where TClass : class { [NotNull]public TClass P2 { get; set; } [NotNull]public TClass? P3 { get; set; } CClass() // 3 { P2 = null; // 4 P3 = null; } } public class CStruct<TStruct> where TStruct : struct { [NotNull]public TStruct P4 { get; set; } [NotNull]public TStruct? P5 { get; set; } CStruct() { P4 = default; P5 = null; } }"; var comp = CreateNullableCompilation(new[] { lib_cs, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,5): warning CS8618: Non-nullable property 'P1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // COpen() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "COpen").WithArguments("property", "P1").WithLocation(5, 5), // (7,14): warning CS8601: Possible null reference assignment. // P1 = default; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(7, 14), // (14,5): warning CS8618: Non-nullable property 'P2' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // CClass() // 3 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "CClass").WithArguments("property", "P2").WithLocation(14, 5), // (16,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // P2 = null; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 14) ); } [Fact, WorkItem(36073, "https://github.com/dotnet/roslyn/issues/36073")] public void NotNull_Property_InitializedInConstructor_WithValues() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> where TOpen : new() { [NotNull]public TOpen P1 { get; set; } COpen() { P1 = new TOpen(); } } public class CClass<TClass> where TClass : class, new() { [NotNull]public TClass P2 { get; set; } [NotNull]public TClass? P3 { get; set; } CClass() { P2 = new TClass(); P3 = new TClass(); } } public class CStruct<TStruct> where TStruct : struct { [NotNull]public TStruct P4 { get; set; } [NotNull]public TStruct? P5 { get; set; } CStruct() { P4 = new TStruct(); P5 = new TStruct(); } }"; var comp = CreateNullableCompilation(new[] { lib_cs, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(36073, "https://github.com/dotnet/roslyn/issues/36073")] public void NotNull_Property_InitializedWithValues() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> where TOpen : new() { [NotNull]public TOpen P1 { get; set; } = new TOpen(); } public class CClass<TClass> where TClass : class, new() { [NotNull]public TClass P2 { get; set; } = new TClass(); [NotNull]public TClass? P3 { get; set; } = new TClass(); } public class CStruct<TStruct> where TStruct : struct { [NotNull]public TStruct P4 { get; set; } = new TStruct(); [NotNull]public TStruct? P5 { get; set; } = new TStruct(); }"; var comp = CreateNullableCompilation(new[] { lib_cs, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNull_Property_WithAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [NotNull] string? P { get; set; } void M() { P.ToString(); P = null; P.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNull_Property_OnVirtualProperty() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [NotNull] public virtual string? P => throw null!; public virtual string? P2 => throw null!; } public class C : Base { public override string? P => throw null!; // 0 [NotNull] public override string? P2 => throw null!; static void M(C c, Base b) { b.P.ToString(); c.P.ToString(); // 1 b.P2.ToString(); // 2 c.P2.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,34): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override string? P => throw null!; // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "throw null!").WithLocation(10, 34), // (16,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // b.P2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.P2").WithLocation(18, 9) ); } [Fact] public void NotNull_Property_OnVirtualProperty_OnlyOverridingGetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [NotNull] public virtual string? P { get { throw null!; } set { throw null!; } } public virtual string? P2 { get { throw null!; } set { throw null!; } } } public class C : Base { public override string? P { get { throw null!; } } // 0 [NotNull] public override string? P2 { get { throw null!; } } static void M(C c, Base b) { b.P.ToString(); c.P.ToString(); // 1 b.P2.ToString(); // 2 c.P2.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,33): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override string? P { get { throw null!; } } // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(10, 33), // (16,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // b.P2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.P2").WithLocation(18, 9) ); } [Fact] public void NotNull_Indexer_WithAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [NotNull] string? this[int i] { get => throw null!; set => throw null!; } void M() { this[0].ToString(); this[0] = null; this[0].ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNull_01_Indexer() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [NotNull]public TOpen this[int i] { get => throw null!; } } public class CClass<TClass> where TClass : class? { [NotNull]public TClass this[int i] { get => throw null!; } } public class CClass2<TClass> where TClass : class { [NotNull]public TClass? this[int i] { get => throw null!; } } public class CStruct<TStruct> where TStruct : struct { [NotNull]public TStruct this[int i] { get => throw null!; } } public class CStruct2<TStruct> where TStruct : struct { [NotNull]public TStruct? this[int i] { get => throw null!; } }"; var lib = CreateNullableCompilation(new[] { lib_cs, NotNullAttributeDefinition }); lib.VerifyDiagnostics(); var source = @" class C { static void M1<T>(T t1) { new COpen<T>()[0].ToString(); } static void M2<T>(T t2) where T : class { new COpen<T>()[0].ToString(); new CClass<T>()[0].ToString(); new CClass2<T>()[0].ToString(); } static void M4<T>(T t4) where T : struct { new COpen<T>()[0].ToString(); new CStruct<T>()[0].ToString(); new COpen<T?>()[0].Value.ToString(); new CStruct2<T>()[0].Value.ToString(); } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullAttributeDefinition }); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var copenAttributes = copen.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(copenAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableContextAttribute(1)", "System.Runtime.CompilerServices.NullableAttribute(0)", "System.Reflection.DefaultMemberAttribute(\"Item\")" }, copenAttributes); } var property = copen.GetMembers().OfType<PropertySymbol>().Single(); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.NotNullAttribute" }, propertyAttributes); } else { AssertEx.Empty(propertyAttributes); } var getter = property.GetMethod; Assert.Empty(getter.GetAttributes()); var getterReturnAttributes = getter.GetReturnTypeAttributes().Select(a => a.ToString()); Assert.Equal(FlowAnalysisAnnotations.NotNull, getter.ReturnTypeFlowAnalysisAnnotations); if (isSource) { AssertEx.Empty(getterReturnAttributes); } else { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.NotNullAttribute" }, getterReturnAttributes); } } } [Fact] public void NotNull_01_Indexer_Implementation() { var source = @"using System.Diagnostics.CodeAnalysis; public class CClass2<TClass> where TClass : class { [NotNull]public TClass? this[int i] { get => null; } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (4,50): warning CS8603: Possible null reference return. // [NotNull]public TClass? this[int i] { get => null; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(4, 50) ); } [Fact] public void NotNull_Field() { // Warn on misused nullability attributes (f2, f3, f4, f5)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [NotNull]public TOpen f1 = default!; } public class CClass<TClass> where TClass : class { [NotNull]public TClass f2 = null!; [NotNull]public TClass? f3 = null; } public class CStruct<TStruct> where TStruct : struct { [NotNull]public TStruct f4; [NotNull]public TStruct? f5; } "; var lib = CreateNullableCompilation(new[] { NotNullAttributeDefinition, lib_cs }); var source = @" class C { static void M1<T>(T t1) { new COpen<T>().f1.ToString(); } static void M2<T>() where T : class { new COpen<T>().f1.ToString(); new CClass<T>().f2.ToString(); new CClass<T>().f3.ToString(); } static void M4<T>(T t4) where T : struct { new COpen<T>().f1.ToString(); new CStruct<T>().f4.ToString(); new CStruct<T>().f5.Value.ToString(); } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullAttributeDefinition }); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var field = copen.GetMembers().OfType<FieldSymbol>().Single(); var fieldAttributes = field.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.NotNullAttribute" }, fieldAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableAttribute(1)", "System.Diagnostics.CodeAnalysis.NotNullAttribute" }, fieldAttributes); } } } [Fact] public void NotNull_Field_WithAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [NotNull] string? f1 = default!; void M() { f1.ToString(); f1 = null; f1.ToString(); // 1 } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // f1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "f1").WithLocation(9, 9) ); } [Fact] public void NotNull_Field_WithContainerAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [NotNull] public string? f1 = default!; void M(C c) { c.f1.ToString(); c.f1 = null; c = new C(); c.f1.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNull_OutParameter_GenericType() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>(T t, [NotNull]out T t2) { t2 = t; } // 00 static void F2<T>(T t, [NotNull]out T t2) where T : class { t2 = t; } static void F3<T>(T t, [NotNull]out T? t2) where T : class { t2 = t; } static void F4<T>(T t, [NotNull]out T t2) where T : struct { t2 = t; } static void F5<T>(T? t, [NotNull]out T? t2) where T : struct { t2 = t; } // 0 static void M1<T>(T t1) { F1(t1, out var s1); s1.ToString(); } static void M2<T>(T t2) where T : class { F1(t2, out var s2); s2.ToString(); F2(t2, out var s3); s3.ToString(); F3(t2, out var s4); s4.ToString(); t2 = null; // 1 F1(t2, out var s5); s5.ToString(); F2(t2, out var s6); // 2 s6.ToString(); F3(t2, out var s7); // 3 s7.ToString(); } static void M3<T>(T? t3) where T : class { F1(t3, out var s8); s8.ToString(); F2(t3, out var s9); // 4 s9.ToString(); F3(t3, out var s10); // 5 s10.ToString(); if (t3 == null) return; F1(t3, out var s11); s11.ToString(); F2(t3, out var s12); s12.ToString(); F3(t3, out var s13); s13.ToString(); } static void M4<T>(T t4) where T : struct { F1(t4, out var s14); s14.ToString(); F4(t4, out var s15); s15.ToString(); } static void M5<T>(T? t5) where T : struct { F1(t5, out var s16); _ = s16.Value; F5(t5, out var s17); _ = s17.Value; if (t5 == null) return; F1(t5, out var s18); _ = s18.Value; F5(t5, out var s19); _ = s19.Value; } }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,57): warning CS8777: Parameter 't2' must have a non-null value when exiting. // static void F1<T>(T t, [NotNull]out T t2) { t2 = t; } // 00 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("t2").WithLocation(4, 57), // (8,76): warning CS8777: Parameter 't2' must have a non-null value when exiting. // static void F5<T>(T? t, [NotNull]out T? t2) where T : struct { t2 = t; } // 0 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("t2").WithLocation(8, 76), // (25,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(25, 14), // (29,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t2, out var s6); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(29, 9), // (32,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t2, out var s7); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(32, 9), // (40,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t3, out var s9); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(40, 9), // (43,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t3, out var s10); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(43, 9)); } [Fact] public void NotNull_RefParameter_03() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([NotNull]ref string t) { t = null; } // 0 static void F2([NotNull]ref string? t) { t = null; } // 1 static void M() { string t1 = null; // 2 F1(ref t1); // 3 t1.ToString(); string? t2 = null; F1(ref t2); // 4 t2.ToString(); string? t3 = null; F2(ref t3); t3.ToString(); } static void F3([NotNull]ref string? t) { t = null!; } }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,49): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F1([NotNull]ref string t) { t = null; } // 0 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 49), // (4,55): warning CS8777: Parameter 't' must have a non-null value when exiting. // static void F1([NotNull]ref string t) { t = null; } // 0 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("t").WithLocation(4, 55), // (5,56): warning CS8777: Parameter 't' must have a non-null value when exiting. // static void F2([NotNull]ref string? t) { t = null; } // 1 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("t").WithLocation(5, 56), // (8,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string t1 = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 21), // (9,16): warning CS8601: Possible null reference assignment. // F1(ref t1); // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t1").WithLocation(9, 16), // (13,16): warning CS8601: Possible null reference assignment. // F1(ref t2); // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(13, 16) ); } [Fact] public void NotNull_ReturnValue_GenericType_Loosening() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { [return: NotNull] public virtual T F1<T>(T t) => throw null!; [return: NotNull] public virtual T F2<T>(T t) where T : class => t; [return: NotNull] public virtual T? F3<T>(T t) where T : class => t; [return: NotNull] public virtual T F4<T>(T t) where T : struct => t; [return: NotNull] public virtual T? F5<T>(T t) where T : struct => t; } public class Derived : Base { public override T F1<T>(T t) => t; // 1 public override T F2<T>(T t) where T : class => t; public override T? F3<T>(T t) where T : class => t; // 2 public override T F4<T>(T t) where T : struct => t; public override T? F5<T>(T t) where T : struct => t; // 3 } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,23): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T F1<T>(T t) => t; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F1").WithLocation(12, 23), // (14,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F3<T>(T t) where T : class => t; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F3").WithLocation(14, 24), // (16,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F5<T>(T t) where T : struct => t; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F5").WithLocation(16, 24) ); } [Fact] public void NotNull_ReturnValue_GenericType_Loosening_MaybeNull() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { [return: NotNull] public virtual T F1<T>() => throw null!; [return: NotNull] public virtual T F2<T>() where T : class => throw null!; [return: NotNull] public virtual T? F3<T>() where T : class => throw null!; [return: NotNull] public virtual T F4<T>() where T : struct => throw null!; [return: NotNull, MaybeNull] public virtual T F4B<T>() where T : struct => throw null!; [return: NotNull] public virtual T? F5<T>() where T : struct => throw null!; public virtual T F6<T>() where T : notnull => throw null!; } public class Derived : Base { [return: MaybeNull] public override T F1<T>() => throw null!; // 1 [return: MaybeNull] public override T F2<T>() where T : class => throw null!; // 2 [return: MaybeNull] public override T? F3<T>() where T : class => throw null!; // 3 [return: MaybeNull] public override T F4<T>() where T : struct => throw null!; [return: MaybeNull] public override T F4B<T>() where T : struct => throw null!; [return: MaybeNull] public override T? F5<T>() where T : struct => throw null!; // 4 [return: MaybeNull] public override T F6<T>() => throw null!; // 5 } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (14,43): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T F1<T>() => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F1").WithLocation(14, 43), // (15,43): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T F2<T>() where T : class => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F2").WithLocation(15, 43), // (16,44): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T? F3<T>() where T : class => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F3").WithLocation(16, 44), // (19,44): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T? F5<T>() where T : struct => throw null!; // 4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F5").WithLocation(19, 44), // (20,43): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T F6<T>() => throw null!; // 5 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F6").WithLocation(20, 43) ); } [Fact] public void NotNull_ReturnValue_GenericType_Loosening_MaybeNull_FromMetadata() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { [return: NotNull] public virtual T F1<T>() => throw null!; [return: NotNull] public virtual T F2<T>() where T : class => throw null!; [return: NotNull] public virtual T? F3<T>() where T : class => throw null!; [return: NotNull] public virtual T F4<T>() where T : struct => throw null!; [return: NotNull, MaybeNull] public virtual T F4B<T>() where T : struct => throw null!; [return: NotNull] public virtual T? F5<T>() where T : struct => throw null!; public virtual T F6<T>() where T : notnull => throw null!; } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullAttributeDefinition, source }); var source2 = @"using System.Diagnostics.CodeAnalysis; public class Derived : Base { [return: MaybeNull] public override T F1<T>() => throw null!; // 1 [return: MaybeNull] public override T F2<T>() where T : class => throw null!; // 2 [return: MaybeNull] public override T? F3<T>() where T : class => throw null!; // 3 [return: MaybeNull] public override T F4<T>() where T : struct => throw null!; [return: MaybeNull] public override T F4B<T>() where T : struct => throw null!; [return: MaybeNull] public override T? F5<T>() where T : struct => throw null!; // 4 [return: MaybeNull] public override T F6<T>() => throw null!; // 5 } "; var comp2 = CreateNullableCompilation(source2, references: new[] { comp.EmitToImageReference() }); comp2.VerifyDiagnostics( // (4,43): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T F1<T>() => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F1").WithLocation(4, 43), // (5,43): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T F2<T>() where T : class => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F2").WithLocation(5, 43), // (6,44): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T? F3<T>() where T : class => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F3").WithLocation(6, 44), // (9,44): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T? F5<T>() where T : struct => throw null!; // 4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F5").WithLocation(9, 44), // (10,43): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T F6<T>() => throw null!; // 5 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F6").WithLocation(10, 43) ); } [Fact] public void NotNull_ReturnValue_GenericType_Loosening_MaybeNull_SpecificType() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base<TOpen, TClass, TStruct, TNotNull> where TClass : class where TStruct : struct where TNotNull : notnull { [return: NotNull] public virtual TOpen F1() => throw null!; [return: NotNull] public virtual TClass F2() => throw null!; [return: NotNull] public virtual TClass? F3() => throw null!; [return: NotNull] public virtual TStruct F4() => throw null!; [return: NotNull, MaybeNull] public virtual TStruct F4B() => throw null!; [return: NotNull] public virtual TStruct? F5() => throw null!; public virtual TNotNull F6() => throw null!; } public class Derived<TNotNull> : Base<string?, string, int, TNotNull> where TNotNull : notnull { [return: MaybeNull] public override string? F1() => throw null!; // 1 [return: MaybeNull] public override string F2() => throw null!; // 2 [return: MaybeNull] public override string? F3() => throw null!; // 3 [return: MaybeNull] public override int F4() => throw null!; [return: MaybeNull] public override int F4B() => throw null!; [return: MaybeNull] public override int? F5() => throw null!; // 4 [return: MaybeNull] public override TNotNull F6() => throw null!; // 5 } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (18,49): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [return: MaybeNull] public override string? F1() => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F1").WithLocation(18, 49), // (19,48): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [return: MaybeNull] public override string F2() => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F2").WithLocation(19, 48), // (20,49): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [return: MaybeNull] public override string? F3() => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F3").WithLocation(20, 49), // (23,46): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [return: MaybeNull] public override int? F5() => throw null!; // 4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F5").WithLocation(23, 46), // (24,50): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [return: MaybeNull] public override TNotNull F6() => throw null!; // 5 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F6").WithLocation(24, 50) ); } [Fact] public void DisallowNull_Parameter_Loosening_SpecificType() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base<TOpen, TClass, TStruct, TNotNull> where TClass : class where TStruct : struct where TNotNull : notnull { public virtual void F1([DisallowNull] TOpen p) => throw null!; public virtual void F2([DisallowNull] TClass p) => throw null!; public virtual void F3([DisallowNull] TClass? p) => throw null!; public virtual void F4([DisallowNull] TStruct p) => throw null!; public virtual void F4B([DisallowNull] TStruct p) => throw null!; public virtual void F5([DisallowNull] TStruct? p) => throw null!; public virtual void F6([DisallowNull] TNotNull p) => throw null!; } public class Derived<TNotNull> : Base<string?, string, int, TNotNull> where TNotNull : notnull { public override void F1(string? p) => throw null!; public override void F2(string p) => throw null!; public override void F3(string? p) => throw null!; public override void F4(int p) => throw null!; public override void F4B(int p) => throw null!; public override void F5(int? p) => throw null!; public override void F6(TNotNull p) => throw null!; } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void DisallowNull_Parameter_Tightening_SpecificType() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base<TOpen, TClass, TStruct, TNotNull> where TClass : class where TStruct : struct where TNotNull : notnull { public virtual void F1(TOpen p) => throw null!; public virtual void F2(TClass p) => throw null!; public virtual void F3(TClass? p) => throw null!; public virtual void F4(TStruct p) => throw null!; public virtual void F5(TStruct? p) => throw null!; public virtual void F6(TNotNull p) => throw null!; } public class Derived<TNotNull> : Base<string?, string, int, TNotNull> where TNotNull : notnull { public override void F1([DisallowNull] string? p) => throw null!; // 1 public override void F2([DisallowNull] string p) => throw null!; public override void F3([DisallowNull] string? p) => throw null!; // 2 public override void F4([DisallowNull] int p) => throw null!; public override void F5([DisallowNull] int? p) => throw null!; // 3 public override void F6([DisallowNull] TNotNull p) => throw null!; } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (17,26): error CS8765: Type of parameter 'p' doesn't match overridden member because of nullability attributes. // public override void F1([DisallowNull] string? p) => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("p").WithLocation(17, 26), // (19,26): error CS8765: Type of parameter 'p' doesn't match overridden member because of nullability attributes. // public override void F3([DisallowNull] string? p) => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("p").WithLocation(19, 26), // (21,26): error CS8765: Type of parameter 'p' doesn't match overridden member because of nullability attributes. // public override void F5([DisallowNull] int? p) => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("p").WithLocation(21, 26) ); } [Fact] public void AllowNull_Parameter_Tightening_SpecificType() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base<TOpen, TClass, TStruct, TNotNull> where TClass : class where TStruct : struct where TNotNull : notnull { public virtual void F1([AllowNull] TOpen p) => throw null!; public virtual void F2([AllowNull] TClass p) => throw null!; public virtual void F3([AllowNull] TClass? p) => throw null!; public virtual void F4([AllowNull] TStruct p) => throw null!; public virtual void F5([AllowNull] TStruct? p) => throw null!; public virtual void F6([AllowNull] TNotNull p) => throw null!; } public class Derived<TNotNull> : Base<string?, string, int, TNotNull> where TNotNull : notnull { public override void F1(string? p) => throw null!; public override void F2(string p) => throw null!; // 1 public override void F3(string? p) => throw null!; public override void F4(int p) => throw null!; public override void F5(int? p) => throw null!; public override void F6(TNotNull p) => throw null!; // 2 } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (18,26): error CS8765: Type of parameter 'p' doesn't match overridden member because of nullability attributes. // public override void F2(string p) => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("p").WithLocation(18, 26), // (22,26): error CS8765: Type of parameter 'p' doesn't match overridden member because of nullability attributes. // public override void F6(TNotNull p) => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("p").WithLocation(22, 26) ); } [Fact, WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void NotNull_OutParameter_GenericType_Loosening() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>([NotNull]out T t2) => throw null!; public virtual void F2<T>([NotNull]out T t2) where T : class => throw null!; public virtual void F3<T>([NotNull]out T? t2) where T : class => throw null!; public virtual void F4<T>([NotNull]out T t2) where T : struct => throw null!; public virtual void F5<T>([NotNull]out T? t2) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>(out T t2) => throw null!; // 1 public override void F2<T>(out T t2) where T : class => throw null!; public override void F3<T>(out T? t2) where T : class => throw null!; // 2 public override void F4<T>(out T t2) where T : struct => throw null!; public override void F5<T>(out T? t2) where T : struct => throw null!; // 3 } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F1<T>(out T t2) => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(12, 26), // (14,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F3<T>(out T? t2) where T : class => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t2").WithLocation(14, 26), // (16,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F5<T>(out T? t2) where T : struct => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t2").WithLocation(16, 26) ); } [Fact, WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void NotNull_OutParameter_GenericType_Loosening_SpecificType() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base<TOpen, TClass, TStruct> where TClass : class where TStruct : struct { public virtual void F1([NotNull]out TOpen t2) => throw null!; public virtual void F2([NotNull]out TClass t2) => throw null!; public virtual void F3([NotNull]out TClass? t2) => throw null!; public virtual void F4([NotNull]out TStruct t2) => throw null!; public virtual void F5([NotNull]out TStruct? t2) => throw null!; } public class Derived : Base<string?, string, int> { public override void F1(out string? t2) => throw null!; // 1 public override void F2(out string t2) => throw null!; public override void F3(out string? t2) => throw null!; // 2 public override void F4(out int t2) => throw null!; public override void F5(out int? t2) => throw null!; // 3 } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (14,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F1(out string? t2) => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(14, 26), // (16,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F3(out string? t2) => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t2").WithLocation(16, 26), // (18,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F5(out int? t2) => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t2").WithLocation(18, 26) ); } [Fact] public void NotNull_ReturnValue_GenericType_Tightening() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual T F1<T>(T t) => t; public virtual T F2<T>(T t) where T : class => t; public virtual T? F3<T>(T t) where T : class => t; public virtual T F4<T>(T t) where T : struct => t; public virtual T? F5<T>(T t) where T : struct => t; public virtual T F6<T>(T t) where T : notnull => t; } public class Derived : Base { [return: NotNull] public override T F1<T>(T t) => t; // 1 [return: NotNull] public override T F2<T>(T t) where T : class => t; [return: NotNull] public override T? F3<T>(T t) where T : class => t; [return: NotNull] public override T F4<T>(T t) where T : struct => t; [return: NotNull] public override T? F5<T>(T t) where T : struct => t; [return: NotNull] public override T F6<T>(T t) => t; } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,55): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull] public override T F1<T>(T t) => t; // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(13, 55) ); } [Fact, WorkItem(36410, "https://github.com/dotnet/roslyn/issues/36410")] public void NotNull_WithMaybeNullWhenTrue() { var source = @"using System.Diagnostics.CodeAnalysis; internal class C<T> where T : class? { public bool TryGetTarget([NotNull, MaybeNullWhen(true)] out T target) => throw null!; public string Method(C<string?> wr) { if (wr.TryGetTarget(out string? s)) { return s; // 1 } return s; } }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (9,20): warning CS8603: Possible null reference return. // return s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(9, 20) ); } [Fact, WorkItem(36410, "https://github.com/dotnet/roslyn/issues/36410")] public void NotNull_WithMaybeNullWhenFalse() { var source = @"using System.Diagnostics.CodeAnalysis; internal class C<T> where T : class? { public bool TryGetTarget([NotNull, MaybeNullWhen(false)] out T target) => throw null!; public string Method(C<string?> wr) { if (wr.TryGetTarget(out string? s)) { return s; } return s; // 1 } }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,16): warning CS8603: Possible null reference return. // return s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(11, 16) ); } [Fact] public void NullableAnnotationAttributes_Deconstruction() { var source = @"using System.Diagnostics.CodeAnalysis; class Pair<T, U> { internal void Deconstruct([MaybeNull] out T t, [NotNull] out U u) => throw null!; } class Program { static void F1<T>(Pair<T, T> p) { var (x1, y1) = p; x1.ToString(); // 1 y1.ToString(); } static void F2<T>(Pair<T, T> p) where T : class { var (x2, y2) = p; x2.ToString(); // 2 y2.ToString(); x2 = null; y2 = null; } static void F3<T>(Pair<T, T> p) where T : class? { var (x3, y3) = p; x3.ToString(); // 3 y3.ToString(); x3 = null; y3 = null; } static void F4<T>(Pair<T?, T?> p) where T : struct { var (x4, y4) = p; _ = x4.Value; // 4 _ = y4.Value; } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, NotNullAttributeDefinition, source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(17, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(25, 9), // (33,13): warning CS8629: Nullable value type may be null. // _ = x4.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x4").WithLocation(33, 13) ); } [Fact] public void NullableAnnotationAttributes_ExtensionMethodThis() { var source = @"using System.Diagnostics.CodeAnalysis; delegate void D(); static class Program { static void E1<T>([AllowNull] this T t) where T : class { } static void E2<T>([DisallowNull] this T t) where T : class? { } static void F1<T>(T t1) where T : class { D d; d = t1.E1; d = t1.E2; t1 = null; // 1 d = t1.E1; // 2 d = t1.E2; // 3 } static void F2<T>(T t2) where T : class? { D d; d = t2.E1; // 4 d = t2.E2; // 5 } }"; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, DisallowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t1 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 14), // (13,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.E1<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // d = t1.E1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "t1.E1").WithArguments("Program.E1<T>(T)", "T", "T?").WithLocation(13, 13), // (14,13): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.E2<T?>(T? t)'. // d = t1.E2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t1").WithArguments("t", "void Program.E2<T?>(T? t)").WithLocation(14, 13), // (19,13): warning CS8634: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Program.E1<T>(T)'. Nullability of type argument 'T' doesn't match 'class' constraint. // d = t2.E1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "t2.E1").WithArguments("Program.E1<T>(T)", "T", "T").WithLocation(19, 13)); } [Fact] public void ConditionalBranching_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 x1, CL1? y1, CL1 z1) { if (y1 != null) { x1 = y1; } else { z1 = y1; } } void Test2(CL1 x2, CL1? y2, CL1 z2) { if (y2 == null) { x2 = y2; } else { z2 = y2; } } void Test3(CL2 x3, CL2? y3, CL2 z3) { if (y3 != null) { x3 = y3; } else { z3 = y3; } } void Test4(CL2 x4, CL2? y4, CL2 z4) { if (y4 == null) { x4 = y4; } else { z4 = y4; } } void Test5(CL1 x5, CL1 y5, CL1 z5) { if (y5 != null) { x5 = y5; } else { z5 = y5; } } } class CL1 { } class CL2 { public static bool operator == (CL2? x, CL2? y) { return false; } public static bool operator != (CL2? x, CL2? y) { return false; } public override bool Equals(object obj) { return false; } public override int GetHashCode() { return 0; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(16, 18), // (24,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2").WithLocation(24, 18), // (40,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z3 = y3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y3").WithLocation(40, 18), // (48,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = y4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y4").WithLocation(48, 18), // (64,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z5 = y5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y5").WithLocation(64, 18) ); } [Fact] public void ConditionalBranching_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 x1, CL1? y1, CL1 z1) { if (null != y1) { x1 = y1; } else { z1 = y1; } } void Test2(CL1 x2, CL1? y2, CL1 z2) { if (null == y2) { x2 = y2; } else { z2 = y2; } } void Test3(CL2 x3, CL2? y3, CL2 z3) { if (null != y3) { x3 = y3; } else { z3 = y3; } } void Test4(CL2 x4, CL2? y4, CL2 z4) { if (null == y4) { x4 = y4; } else { z4 = y4; } } void Test5(CL1 x5, CL1 y5, CL1 z5) { if (null == y5) { x5 = y5; } else { z5 = y5; } } } class CL1 { } class CL2 { public static bool operator == (CL2? x, CL2? y) { return false; } public static bool operator != (CL2? x, CL2? y) { return false; } public override bool Equals(object obj) { return false; } public override int GetHashCode() { return 0; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(16, 18), // (24,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2").WithLocation(24, 18), // (40,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z3 = y3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y3").WithLocation(40, 18), // (48,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = y4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y4").WithLocation(48, 18), // (60,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x5 = y5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y5").WithLocation(60, 18) ); } [Fact] public void ConditionalBranching_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 x1, CL1? y1, CL1 z1, bool u1) { if (null != y1 || u1) { x1 = y1; } else { z1 = y1; } } void Test2(CL1 x2, CL1? y2, CL1 z2, bool u2) { if (y2 != null && u2) { x2 = y2; } else { z2 = y2; } } bool Test3(CL1? x3) { return x3.M1(); } bool Test4(CL1? x4) { return x4 != null && x4.M1(); } bool Test5(CL1? x5) { return x5 == null && x5.M1(); } } class CL1 { public bool M1() { return true; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(12, 18), // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(16, 18), // (28,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z2 = y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2").WithLocation(28, 18), // (34,16): warning CS8602: Dereference of a possibly null reference. // return x3.M1(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(34, 16), // (44,30): warning CS8602: Dereference of a possibly null reference. // return x5 == null && x5.M1(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x5").WithLocation(44, 30) ); } [Fact] public void ConditionalBranching_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 x1, CL1? y1) { CL1 z1 = y1 ?? x1; } void Test2(CL1? x2, CL1? y2) { CL1 z2 = y2 ?? x2; } void Test3(CL1 x3, CL1? y3) { CL1 z3 = x3 ?? y3; } void Test4(CL1? x4, CL1 y4) { x4 = y4; CL1 z4 = x4 ?? x4.M1(); } void Test5(CL1 x5) { const CL1? y5 = null; CL1 z5 = y5 ?? x5; } void Test6(CL1 x6) { const string? y6 = """"; string z6 = y6 ?? x6.M2(); } } class CL1 { public CL1 M1() { return new CL1(); } public string? M2() { return null; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = y2 ?? x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2 ?? x2").WithLocation(15, 18), // (20,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z3 = x3 ?? y3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3 ?? y3").WithLocation(20, 18), // (26,24): warning CS8602: Dereference of a possibly null reference. // CL1 z4 = x4 ?? x4.M1(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(26, 24)); } [Fact] public void ConditionalBranching_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1? x1) { CL1 z1 = x1?.M1(); } void Test2(CL1? x2, CL1 y2) { x2 = y2; CL1 z2 = x2?.M1(); } void Test3(CL1? x3, CL1 y3) { x3 = y3; CL1 z3 = x3?.M2(); } void Test4(CL1? x4) { x4?.M3(x4); } } class CL1 { public CL1 M1() { return new CL1(); } public CL1? M2() { return null; } public void M3(CL1 x) { } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z1 = x1?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1?.M1()").WithLocation(10, 18), // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = x2?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2?.M1()").WithLocation(16, 18), // (22,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z3 = x3?.M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3?.M2()").WithLocation(22, 18) ); } [Fact] public void ConditionalBranching_06() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 x1, CL1? y1) { CL1 z1 = y1 != null ? y1 : x1; } void Test2(CL1? x2, CL1? y2) { CL1 z2 = y2 != null ? y2 : x2; } void Test3(CL1 x3, CL1? y3) { CL1 z3 = x3 != null ? x3 : y3; } void Test4(CL1? x4, CL1 y4) { x4 = y4; CL1 z4 = x4 != null ? x4 : x4.M1(); } void Test5(CL1 x5) { const CL1? y5 = null; CL1 z5 = y5 != null ? y5 : x5; } void Test6(CL1 x6) { const string? y6 = """"; string z6 = y6 != null ? y6 : x6.M2(); } void Test7(CL1 x7) { const string? y7 = null; string z7 = y7 != null ? y7 : x7.M2(); } } class CL1 { public CL1 M1() { return new CL1(); } public string? M2() { return null; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = y2 != null ? y2 : x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2 != null ? y2 : x2").WithLocation(15, 18), // (20,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z3 = x3 != null ? x3 : y3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3 != null ? x3 : y3").WithLocation(20, 18), // (26,36): warning CS8602: Dereference of a possibly null reference. // CL1 z4 = x4 != null ? x4 : x4.M1(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(26, 36), // (44,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string z7 = y7 != null ? y7 : x7.M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y7 != null ? y7 : x7.M2()").WithLocation(44, 21) ); } [Fact] public void ConditionalBranching_07() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 x1, CL1? y1) { CL1 z1 = y1 == null ? x1 : y1; } void Test2(CL1? x2, CL1? y2) { CL1 z2 = y2 == null ? x2 : y2; } void Test3(CL1 x3, CL1? y3) { CL1 z3 = x3 == null ? y3 : x3; } void Test4(CL1? x4, CL1 y4) { x4 = y4; CL1 z4 = x4 == null ? x4.M1() : x4; } void Test5(CL1 x5) { const CL1? y5 = null; CL1 z5 = y5 == null ? x5 : y5; } void Test6(CL1 x6) { const string? y6 = """"; string z6 = y6 == null ? x6.M2() : y6; } void Test7(CL1 x7) { const string? y7 = null; string z7 = y7 == null ? x7.M2() : y7; } } class CL1 { public CL1 M1() { return new CL1(); } public string? M2() { return null; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = y2 == null ? x2 : y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2 == null ? x2 : y2").WithLocation(15, 18), // (20,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z3 = x3 == null ? y3 : x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3 == null ? y3 : x3").WithLocation(20, 18), // (26,31): warning CS8602: Dereference of a possibly null reference. // CL1 z4 = x4 == null ? x4.M1() : x4; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(26, 31), // (44,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string z7 = y7 == null ? x7.M2() : y7; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y7 == null ? x7.M2() : y7").WithLocation(44, 21) ); } [Fact] [WorkItem(26624, "https://github.com/dotnet/roslyn/issues/26624")] public void ConditionalBranching_08() { CSharpCompilation c = CreateCompilation(@" class C { bool Test1(CL1? x1) { if (x1?.P1 == true) { return x1.P2; } return x1.P2; // 1 } } class CL1 { public bool P1 { get { return true;} } public bool P2 { get { return true;} } } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (11,16): warning CS8602: Dereference of a possibly null reference. // return x1.P2; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 16) ); } [Fact] public void ConditionalBranching_09() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(object x1, object? y1) { y1 = x1; y1.ToString(); object z1 = y1 ?? x1; y1.ToString(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(13, 9)); } [Fact] public void ConditionalBranching_10() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(object x1, object? y1) { y1 = x1; y1.ToString(); object z1 = y1 != null ? y1 : x1; y1.ToString(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(13, 9) ); } [Fact] public void ConditionalBranching_11() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void Test1(object x1, object? y1) { y1 = x1; y1.ToString(); y1?.GetHashCode(); y1.ToString(); // 1 } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(9, 9) ); } [Fact] public void ConditionalBranching_12() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(object x1, object? y1) { y1 = x1; y1.ToString(); if (y1 == null) { System.Console.WriteLine(1); } else { System.Console.WriteLine(2); } y1.ToString(); // 1 } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (22,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(22, 9) ); } [Fact] public void ConditionalBranching_13() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(object x1, object? y1) { y1 = x1; y1.ToString(); if (y1 != null) { System.Console.WriteLine(1); } else { System.Console.WriteLine(2); } y1.ToString(); // 1 } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (22,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(22, 9) ); } [Fact] public void ConditionalBranching_14() { var compilation = CreateCompilation(new[] { @" class C { C? _cField = null; C _nonNullCField = new C(); C? GetC() => null; C? CProperty { get => null; } void Test1(C? c1) { if (c1?._cField != null) { c1._cField.ToString(); } else { c1._cField.ToString(); // warn 1 2 } } void Test2() { C? c2 = GetC(); if (c2?._cField != null) { c2._cField.ToString(); } else { c2._cField.ToString(); // warn 3 4 } } void Test3(C? c3) { if (c3?._cField?._cField != null) { c3._cField._cField.ToString(); } else if (c3?._cField != null) { c3._cField.ToString(); c3._cField._cField.ToString(); // warn 5 } else { c3.ToString(); // warn 6 } } void Test4(C? c4) { if (c4?._nonNullCField._cField?._nonNullCField._cField != null) { c4._nonNullCField._cField._nonNullCField._cField.ToString(); } else { c4._nonNullCField._cField._nonNullCField._cField.ToString(); // warn 7 8 9 } } void Test5(C? c5) { if (c5?._cField == null) { c5._cField.ToString(); // warn 10 11 } else { c5._cField.ToString(); } } void Test6(C? c6) { if (c6?._cField?.GetC() != null) { c6._cField.GetC().ToString(); // warn 12 } } void Test7(C? c7) { if (c7?._cField?.CProperty != null) { c7._cField.CProperty.ToString(); } } } " }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (17,13): warning CS8602: Dereference of a possibly null reference. // c1._cField.ToString(); // warn 1 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(17, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // c1._cField.ToString(); // warn 1 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1._cField").WithLocation(17, 13), // (30,13): warning CS8602: Dereference of a possibly null reference. // c2._cField.ToString(); // warn 3 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(30, 13), // (30,13): warning CS8602: Dereference of a possibly null reference. // c2._cField.ToString(); // warn 3 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2._cField").WithLocation(30, 13), // (43,13): warning CS8602: Dereference of a possibly null reference. // c3._cField._cField.ToString(); // warn 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c3._cField._cField").WithLocation(43, 13), // (47,13): warning CS8602: Dereference of a possibly null reference. // c3.ToString(); // warn 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c3").WithLocation(47, 13), // (59,13): warning CS8602: Dereference of a possibly null reference. // c4._nonNullCField._cField._nonNullCField._cField.ToString(); // warn 7 8 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c4").WithLocation(59, 13), // (59,13): warning CS8602: Dereference of a possibly null reference. // c4._nonNullCField._cField._nonNullCField._cField.ToString(); // warn 7 8 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c4._nonNullCField._cField").WithLocation(59, 13), // (59,13): warning CS8602: Dereference of a possibly null reference. // c4._nonNullCField._cField._nonNullCField._cField.ToString(); // warn 7 8 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c4._nonNullCField._cField._nonNullCField._cField").WithLocation(59, 13), // (67,13): warning CS8602: Dereference of a possibly null reference. // c5._cField.ToString(); // warn 10 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c5").WithLocation(67, 13), // (67,13): warning CS8602: Dereference of a possibly null reference. // c5._cField.ToString(); // warn 10 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c5._cField").WithLocation(67, 13), // (79,13): warning CS8602: Dereference of a possibly null reference. // c6._cField.GetC().ToString(); // warn 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c6._cField.GetC()").WithLocation(79, 13) ); } [Fact] public void ConditionalBranching_15() { var compilation = CreateCompilation(new[] { @" class C { void Test(C? c1) { if (c1?[0] != null) { c1.ToString(); c1[0].ToString(); // warn 1 } else { c1.ToString(); // warn 2 } } object? this[int i] { get => null; } } " }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // c1[0].ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1[0]").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // c1.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(13, 13) ); } [Fact] public void ConditionalBranching_16() { var compilation = CreateCompilation(new[] { @" class C { void Test<T>(T t) { if (t?.ToString() != null) { t.ToString(); } else { t.ToString(); // warn } } }" }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(12, 13) ); } [Fact] public void ConditionalBranching_17() { var compilation = CreateCompilation(new[] { @" class C { object? Prop { get; } object? GetObj(bool val) => null; void Test(C? c1, C? c2) { if (c1?.GetObj(c2?.Prop != null) != null) { c2.Prop.ToString(); // warn 1 2 } } }" }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // c2.Prop.ToString(); // warn 1 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(10, 13), // (10,13): warning CS8602: Dereference of a possibly null reference. // c2.Prop.ToString(); // warn 1 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2.Prop").WithLocation(10, 13) ); } [Fact] public void ConditionalBranching_18() { var compilation = CreateCompilation(new[] { @" class C { void Test(C? x, C? y) { if ((x = y)?.GetHashCode() != null) { x.ToString(); y.ToString(); // warn } } }" }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 13) ); } [Fact] [WorkItem(26624, "https://github.com/dotnet/roslyn/issues/26624")] [WorkItem(39424, "https://github.com/dotnet/roslyn/issues/39424")] public void ConditionalBranching_19() { CSharpCompilation c = CreateCompilation(@" class C { void Test1(CL1? x1) { _ = x1?.P1 ?? false ? x1.P1 : x1.P1; // 1 _ = x1?.P1 ?? true ? x1.P1 // 2 : x1.P1; } } class CL1 { public bool P1 { get { return true; } } } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x1.P1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(8, 15), // (11,15): warning CS8602: Dereference of a possibly null reference. // ? x1.P1 // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 15)); } [Fact] [WorkItem(26624, "https://github.com/dotnet/roslyn/issues/26624")] public void ConditionalBranching_20() { CSharpCompilation c = CreateCompilation(@" class C { void Test1(CL1? x1) { _ = x1?.Next?.Next?.P1 ?? false ? x1.ToString() + x1.Next.Next.ToString() : x1.ToString(); // 1 _ = x1?.Next?.Next?.P1 ?? true ? x1.ToString() // 2 : x1.ToString() + x1.Next.Next.ToString(); } } class CL1 { public bool P1 { get { return true; } } public CL1? Next { get { return null; } } } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(8, 15), // (11,15): warning CS8602: Dereference of a possibly null reference. // ? x1.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 15)); } /// <remarks>Ported from <see cref="FlowTests.IfConditionalConstant" />.</remarks> [Theory] [InlineData("true", "false")] [InlineData("FIELD_TRUE", "FIELD_FALSE")] [InlineData("LOCAL_TRUE", "LOCAL_FALSE")] [InlineData("true || false", "true && false")] [InlineData("!false", "!true")] public void ConditionalConstant_01(string @true, string @false) { var source = @" #pragma warning disable 219 // The variable is assigned but its value is never used class C { const bool FIELD_TRUE = true; const bool FIELD_FALSE = false; static void M(bool b, object? x) { const bool LOCAL_TRUE = true; const bool LOCAL_FALSE = false; x = null; _ = (b ? x != null : " + @false + @") // `b && x != null` ? x.ToString() : x.ToString(); // 1 x = new object(); _ = (b ? x != null : " + @false + @") // `b && x != null` ? x.ToString() : x.ToString(); // 2 x = null; _ = (b ? x != null : " + @true + @") // `!b || x != null` ? x.ToString() // 3 : x.ToString(); // 4 x = new object(); _ = (b ? x != null : " + @true + @") // `!b || x != null` ? x.ToString() : x.ToString(); // 5 x = null; _ = (b ? " + @false + @" : x != null) // `!b && x != null` ? x.ToString() : x.ToString(); // 6 x = new object(); _ = (b ? " + @false + @" : x != null) // `!b && x != null` ? x.ToString() : x.ToString(); // 7 x = null; _ = (b ? " + @true + @" : x != null) // `b || x != null` ? x.ToString() // 8 : x.ToString(); // 9 x = new object(); _ = (b ? " + @true + @" : x != null) // `b || x != null` ? x.ToString() : x.ToString(); // 10 x = null; _ = !(b ? " + @true + @" : x != null) // `!(b || x != null)` -> `!b && x == null` ? x.ToString() // 11 : x.ToString(); // 12 x = new object(); _ = !(b ? " + @true + @" : x != null) // `!(b || x != null)` -> `!b && x == null` ? x.ToString() // 13 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 15), // (27,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(27, 15), // (28,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(28, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(33, 15), // (39,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(39, 15), // (44,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(44, 15), // (49,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(49, 15), // (50,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(50, 15), // (55,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(55, 15), // (60,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(60, 15), // (61,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(61, 15), // (65,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(65, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IfConditionalConstant" />.</remarks> [Theory] [InlineData("true", "false")] [InlineData("FIELD_TRUE", "FIELD_FALSE")] [InlineData("LOCAL_TRUE", "LOCAL_FALSE")] [InlineData("true || false", "true && false")] [InlineData("!false", "!true")] public void ConditionalConstant_02(string @true, string @false) { var source = @" #pragma warning disable 219 // The variable is assigned but its value is never used class C { const bool FIELD_TRUE = true; const bool FIELD_FALSE = false; static void M(bool b, object? x) { const bool LOCAL_TRUE = true; const bool LOCAL_FALSE = false; x = null; _ = (b ? x == null : " + @false + @") // `b && x == null` ? x.ToString() // 1 : x.ToString(); // 2 x = new object(); _ = (b ? x == null : " + @false + @") // `b && x == null` ? x.ToString() // 3 : x.ToString(); x = null; _ = (b ? x == null : " + @true + @") // `!b || x == null` ? x.ToString() // 4 : x.ToString(); x = new object(); _ = (b ? x == null : " + @true + @") // `!b || x == null` ? x.ToString() // 5 : x.ToString(); x = null; _ = (b ? " + @false + @" : x == null) // `!b && x == null` ? x.ToString() // 6 : x.ToString(); // 7 x = new object(); _ = (b ? " + @false + @" : x == null) // `!b && x == null` ? x.ToString() // 8 : x.ToString(); x = null; _ = !(b ? " + @false + @" : x == null) // `!(!b && x == null)` -> `b || x != null` ? x.ToString() // 9 : x.ToString(); // 10 x = new object(); _ = !(b ? " + @false + @" : x == null) // `!(!b && x == null)` -> `b || x != null` ? x.ToString() : x.ToString(); // 11 x = null; _ = (b ? " + @true + @" : x == null) // `b || x == null` ? x.ToString() // 12 : x.ToString(); x = new object(); _ = (b ? " + @true + @" : x == null) // `b || x == null` ? x.ToString() // 13 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (17,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (27,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(27, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(32, 15), // (38,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(38, 15), // (39,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(39, 15), // (43,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(43, 15), // (49,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(49, 15), // (50,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(50, 15), // (55,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(55, 15), // (60,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(60, 15), // (65,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(65, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IfConditional_ComplexCondition_ConstantConsequence" /></remarks> [Fact] public void IfConditional_ComplexCondition_ConstantConsequence() { var source = @" class C { bool M0(int x) => true; void M1(object? x) { _ = (x != null ? true : false) ? x.ToString() : x.ToString(); // 1 } void M2(object? x) { _ = (x != null ? false : true) ? x.ToString() // 2 : x.ToString(); } void M3(object? x) { _ = (x == null ? true : false) ? x.ToString() // 3 : x.ToString(); } void M4(object? x) { _ = (x == null ? false : true) ? x.ToString() : x.ToString(); // 4 } void M5(object? x) { _ = (!(x == null ? false : true)) ? x.ToString() // 5 : x.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (23,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(23, 15), // (31,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(31, 15), // (37,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(37, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void EqualsCondAccess_NotNullWhenTrue_RightBoolConstant(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c) { _ = c?.M0(out var obj) == true ? obj.ToString() : obj.ToString(); // 1, 2 } static void M2(C? c) { _ = c?.M0(out var obj) == false ? obj.ToString() // 3 : obj.ToString(); // 4, 5 } static void M3(C? c) { _ = c?.M0(out var obj) != true ? obj.ToString() // 6, 7 : obj.ToString(); // 8 } static void M4(C? c) { _ = c?.M0(out var obj) != false ? obj.ToString() // 9, 10 : obj.ToString(); // 11 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (12,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 1, 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (19,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 4, 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 6, 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(25, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(26, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(32, 15), // (32,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 9, 10 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(32, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(33, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void EqualsCondAccess_NotNullWhenTrue_LeftBoolConstant(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c) { _ = true == c?.M0(out var obj) ? obj.ToString() : obj.ToString(); // 1, 2 } static void M2(C? c) { _ = false == c?.M0(out var obj) ? obj.ToString() // 3 : obj.ToString(); // 4, 5 } static void M3(C? c) { _ = true != c?.M0(out var obj) ? obj.ToString() // 6, 7 : obj.ToString(); // 8 } static void M4(C? c) { _ = false != c?.M0(out var obj) ? obj.ToString() // 9, 10 : obj.ToString(); // 11 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (12,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 1, 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (19,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 4, 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 6, 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(25, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(26, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(32, 15), // (32,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 9, 10 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(32, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(33, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void EqualsCondAccess_NotNullWhenTrue_RightBool(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, bool b) { _ = c?.M0(out var obj1) == b ? obj1.ToString() // 1 : """"; } static void M2(C? c, bool b) { _ = c?.M0(out var obj2) == b ? """" : obj2.ToString(); // 2, 3 } static void M3(C? c, bool b) { _ = c?.M0(out var obj3) != b ? obj3.ToString() // 4, 5 : """"; } static void M4(C? c, bool b) { _ = c?.M0(out var obj4) != b ? """" : obj4.ToString(); // 6 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(11, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(19, 15), // (19,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 2, 3 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj3.ToString() // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj3").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj3' // ? obj3.ToString() // 4, 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj3").WithArguments("obj3").WithLocation(25, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj4").WithLocation(33, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void EqualsCondAccess_NotNullWhenTrue_LeftBool(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, bool b) { _ = b == c?.M0(out var obj1) ? obj1.ToString() // 1 : """"; } static void M2(C? c, bool b) { _ = b == c?.M0(out var obj2) ? """" : obj2.ToString(); // 2, 3 } static void M3(C? c, bool b) { _ = b != c?.M0(out var obj3) ? obj3.ToString() // 4, 5 : """"; } static void M4(C? c, bool b) { _ = b != c?.M0(out var obj4) ? """" : obj4.ToString(); // 6 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(11, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(19, 15), // (19,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 2, 3 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj3.ToString() // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj3").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj3' // ? obj3.ToString() // 4, 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj3").WithArguments("obj3").WithLocation(25, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj4").WithLocation(33, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void EqualsCondAccess_NotNullWhenTrue_RightNullableBool(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c) { _ = c?.M0(out var obj) == null ? obj.ToString() // 1, 2 : obj.ToString(); // 3 } static void M2(C? c) { _ = c?.M0(out var obj) != null ? obj.ToString() // 4 : obj.ToString(); // 5, 6 } static void M3(C? c, bool? b) { _ = c?.M0(out var obj1) == b ? obj1.ToString() // 7, 8 : """"; // 9, 10 _ = c?.M0(out var obj2) == b ? """" // 7, 8 : obj2.ToString(); // 9, 10 } static void M4(C? c, bool? b) { _ = c?.M0(out var obj1) != b ? obj1.ToString() // 11, 12 : """"; // 9, 10 _ = c?.M0(out var obj2) != b ? """" // 7, 8 : obj2.ToString(); // 13, 14 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (11,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 1, 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 5, 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (19,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 5, 6 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 7, 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj1' // ? obj1.ToString() // 7, 8 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(25, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(30, 15), // (30,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 9, 10 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(30, 15), // (36,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 11, 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(36, 15), // (36,15): error CS0165: Use of unassigned local variable 'obj1' // ? obj1.ToString() // 11, 12 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(36, 15), // (41,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 13, 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(41, 15), // (41,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 13, 14 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(41, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void EqualsCondAccess_NotNullWhenTrue_LeftNullableBool(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c) { _ = null == c?.M0(out var obj) ? obj.ToString() // 1, 2 : obj.ToString(); // 3 } static void M2(C? c) { _ = null != c?.M0(out var obj) ? obj.ToString() // 4 : obj.ToString(); // 5, 6 } static void M3(C? c, bool? b) { _ = b == c?.M0(out var obj1) ? obj1.ToString() // 7, 8 : """"; // 9, 10 _ = b == c?.M0(out var obj2) ? """" // 7, 8 : obj2.ToString(); // 9, 10 } static void M4(C? c, bool? b) { _ = b != c?.M0(out var obj1) ? obj1.ToString() // 11, 12 : """"; // 9, 10 _ = b != c?.M0(out var obj2) ? """" // 7, 8 : obj2.ToString(); // 13, 14 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (11,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 1, 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 5, 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (19,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 5, 6 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 7, 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj1' // ? obj1.ToString() // 7, 8 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(25, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(30, 15), // (30,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 9, 10 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(30, 15), // (36,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 11, 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(36, 15), // (36,15): error CS0165: Use of unassigned local variable 'obj1' // ? obj1.ToString() // 11, 12 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(36, 15), // (41,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 13, 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(41, 15), // (41,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 13, 14 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(41, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_01"/>.</remarks> [Theory] [InlineData("b")] [InlineData("true")] [InlineData("false")] public void EqualsCondAccess_01(string operand) { var source = @" class C { public bool M0(out object x) { x = 42; return true; } public void M1(C? c, object? x, bool b) { _ = c?.M0(out x) == " + operand + @" ? x.ToString() : x.ToString(); // 1 } public void M2(C? c, object? x, bool b) { _ = c?.M0(out x) != " + operand + @" ? x.ToString() // 2 : x.ToString(); } public void M3(C? c, object? x, bool b) { _ = " + operand + @" == c?.M0(out x) ? x.ToString() : x.ToString(); // 3 } public void M4(C? c, object? x, bool b) { _ = " + operand + @" != c?.M0(out x) ? x.ToString() // 4 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(30, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_02"/>.</remarks> [Theory] [InlineData("i")] [InlineData("42")] public void EqualsCondAccess_02(string operand) { var source = @" class C { public int M0(out object x) { x = 1; return 0; } public void M1(C? c, object? x, int i) { _ = c?.M0(out x) == " + operand + @" ? x.ToString() : x.ToString(); // 1 } public void M2(C? c, object? x, int i) { _ = c?.M0(out x) != " + operand + @" ? x.ToString() // 2 : x.ToString(); } public void M3(C? c, object? x, int i) { _ = " + operand + @" == c?.M0(out x) ? x.ToString() : x.ToString(); // 3 } public void M4(C? c, object? x, int i) { _ = " + operand + @" != c?.M0(out x) ? x.ToString() // 4 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(30, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_03"/>.</remarks> [Theory] [InlineData("object?")] [InlineData("int?")] [InlineData("bool?")] public void EqualsCondAccess_03(string returnType) { var source = @" class C { public " + returnType + @" M0(out object x) { x = 42; return null; } public void M1(C? c, object? x) { _ = c?.M0(out x) != null ? x.ToString() : x.ToString(); // 1 } public void M2(C? c, object? x) { _ = c?.M0(out x) == null ? x.ToString() // 2 : x.ToString(); } public void M3(C? c, object? x) { _ = null != c?.M0(out x) ? x.ToString() : x.ToString(); // 3 } public void M4(C? c, object? x) { _ = null == c?.M0(out x) ? x.ToString() // 4 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(30, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_04"/>.</remarks> [Theory] [InlineData("bool", "false")] [InlineData("int", "1")] [InlineData("object", "1")] public void EqualsCondAccess_04_01(string returnType, string returnValue) { var source = @" class C { public " + returnType + @" M0(out object x) { x = 42; return " + returnValue + @"; } public void M1(C? c, object? x, object? y) { _ = c?.M0(out x) == c!.M0(out y) ? x.ToString() + y.ToString() : x.ToString() + y.ToString(); // 1 } public void M2(C? c, object? x, object? y) { _ = c?.M0(out x) != c!.M0(out y) ? x.ToString() + y.ToString() // 2 : x.ToString() + y.ToString(); } public void M3(C? c, object? x, object? y) { _ = c!.M0(out x) == c?.M0(out y) ? x.ToString() + y.ToString() : x.ToString() + y.ToString(); // 3 } public void M4(C? c, object? x, object? y) { _ = c!.M0(out x) != c?.M0(out y) ? x.ToString() + y.ToString() // 4 : x.ToString() + y.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (24,30): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(24, 30), // (30,30): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(30, 30) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_04"/>.</remarks> [Fact] public void EqualsCondAccess_04_02() { var source = @" class C { public object? M0(out object x) { x = 42; return null; } public void M1(C? c, object? x, object? y) { _ = c?.M0(out x) == c!.M0(out y) ? x.ToString() + y.ToString() // 1 : x.ToString() + y.ToString(); // 2 } public void M2(C? c, object? x, object? y) { _ = c?.M0(out x) != c!.M0(out y) ? x.ToString() + y.ToString() // 3 : x.ToString() + y.ToString(); // 4 } public void M3(C? c, object? x, object? y) { _ = c!.M0(out x) == c?.M0(out y) ? x.ToString() + y.ToString() // 5 : x.ToString() + y.ToString(); // 6 } public void M4(C? c, object? x, object? y) { _ = c!.M0(out x) != c?.M0(out y) ? x.ToString() + y.ToString() // 7 : x.ToString() + y.ToString(); // 8 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15), // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (17,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 15), // (23,30): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(23, 30), // (24,30): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(24, 30), // (30,30): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(30, 30), // (31,30): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(31, 30) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_04"/>.</remarks> [Fact] public void EqualsCondAccess_04_03() { var source = @" class C { public object M0(object? x) => new object(); public void M1(C? c, object? x) { _ = c?.M0(x = null) == c!.M0(x = new object()) ? x.ToString() : x.ToString(); } public void M2(C? c, object? x) { _ = c?.M0(x = new object()) != c!.M0(x = null) ? x.ToString() // 1 : x.ToString(); // 2 } public void M3(C? c, object? x) { _ = c!.M0(x = new object()) != c?.M0(x = null) ? x.ToString() // 3 : x.ToString(); // 4 } public void M4(C? c, object? x) { _ = c!.M0(x = null) != c?.M0(x = new object()) ? x.ToString() // 5 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (17,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 15), // (23,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(23, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(30, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_04"/>.</remarks> [Fact] public void EqualsCondAccess_04_04() { var source = @" class C { public object M0(object? x) => new object(); public void M1(C? c, object? x, object? y) { _ = c?.M0(x = new object()) == c!.M0(y = x) ? y.ToString() : y.ToString(); // 1 } public void M2(C? c, object? x, object? y) { _ = c?.M0(x = new object()) != c!.M0(y = x) ? y.ToString() // 2 : y.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? y.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(16, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_05"/>.</remarks> [Fact] public void EqualsCondAccess_05() { var source = @" class C { public static bool operator ==(C? left, C? right) => false; public static bool operator !=(C? left, C? right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public C? M0(out object x) { x = 42; return this; } public void M1(C? c, object? x) { _ = c?.M0(out x) != null ? x.ToString() : x.ToString(); // 1 } public void M2(C? c, object? x) { _ = c?.M0(out x) == null ? x.ToString() // 2 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_06"/>.</remarks> [Fact] public void EqualsCondAccess_06() { var source = @" class C { public C? M0(out object x) { x = 42; return this; } public void M1(C c, object? x, object? y) { _ = c.M0(out x)?.M0(out y) != null ? x.ToString() + y.ToString() : x.ToString() + y.ToString(); // 1 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,30): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(10, 30) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_07"/>.</remarks> [Fact] public void EqualsCondAccess_07() { var source = @" struct S { public static bool operator ==(S left, S right) => false; public static bool operator !=(S left, S right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public S M0(out object x) { x = 42; return this; } public void M1(S? s, object? x) { _ = s?.M0(out x) != null ? x.ToString() : x.ToString(); // 1 } public void M2(S? s, object? x) { _ = s?.M0(out x) == null ? x.ToString() // 2 : x.ToString(); } public void M3(S? s, object? x) { _ = null != s?.M0(out x) ? x.ToString() : x.ToString(); // 3 } public void M4(S? s, object? x) { _ = null == s?.M0(out x) ? x.ToString() // 4 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (29,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(29, 15), // (35,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(35, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_08"/>.</remarks> [Fact] public void EqualsCondAccess_08() { var source = @" #nullable enable struct S { public static bool operator ==(S left, S right) => false; public static bool operator !=(S left, S right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public S M0(out object x) { x = 42; return this; } public void M1(S? s, object? x) { _ = s?.M0(out x) != new S() ? x.ToString() // 1 : x.ToString(); } public void M2(S? s, object? x) { _ = s?.M0(out x) == new S() ? x.ToString() : x.ToString(); // 2 } public void M3(S? s, object? x) { _ = new S() != s?.M0(out x) ? x.ToString() // 3 : x.ToString(); } public void M4(S? s, object? x) { _ = new S() == s?.M0(out x) ? x.ToString() : x.ToString(); // 4 } } "; CreateCompilation(source).VerifyDiagnostics( // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(30, 15), // (38,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(38, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_09"/>.</remarks> [Fact] public void EqualsCondAccess_09() { var source = @" struct S { public static bool operator ==(S left, S right) => false; public static bool operator !=(S left, S right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public S M0(out object x) { x = 42; return this; } public void M1(S? s, object? x) { _ = s?.M0(out x) != s ? x.ToString() // 1 : x.ToString(); // 2 } public void M2(S? s, object? x) { _ = s?.M0(out x) == s ? x.ToString() // 3 : x.ToString(); // 4 } public void M3(S? s, object? x) { _ = s != s?.M0(out x) ? x.ToString() // 5 : x.ToString(); // 6 } public void M4(S? s, object? x) { _ = s == s?.M0(out x) ? x.ToString() // 7 : x.ToString(); // 8 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (14,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 15), // (28,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(28, 15), // (29,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(29, 15), // (35,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(35, 15), // (36,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(36, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_10"/>.</remarks> [Theory] [InlineData("S? left, S? right")] [InlineData("S? left, S right")] public void EqualsCondAccess_10(string operatorParameters) { var source = @" struct S { public static bool operator ==(" + operatorParameters + @") => false; public static bool operator !=(" + operatorParameters + @") => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public S M0(out object x) { x = 42; return this; } public void M1(S? s, object? x) { _ = s?.M0(out x) != new S() ? x.ToString() // 1 : x.ToString(); } public void M2(S? s, object? x) { _ = s?.M0(out x) == new S() ? x.ToString() : x.ToString(); // 2 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (14,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_11"/>.</remarks> [Fact] public void EqualsCondAccess_11() { var source = @" struct T { public static implicit operator S(T t) => new S(); public T M0(out object x) { x = 42; return this; } } struct S { public static bool operator ==(S left, S right) => false; public static bool operator !=(S left, S right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public void M1(T? t, object? x) { _ = t?.M0(out x) != new S() ? x.ToString() // 1 : x.ToString(); } public void M2(T? t, object? x) { _ = t?.M0(out x) == new S() ? x.ToString() : x.ToString(); // 2 } public void M3(T? t, object? x) { _ = new S() != t?.M0(out x) ? x.ToString() // 3 : x.ToString(); } public void M4(T? t, object? x) { _ = new S() == t?.M0(out x) ? x.ToString() : x.ToString(); // 4 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (18,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(18, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(26, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(32, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(40, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_12"/>.</remarks> [Fact] public void EqualsCondAccess_12() { var source = @" class C { int? M0(object obj) => null; void M1(C? c, object? x, object? obj) { _ = (c?.M0(x = 0) == (int?)obj) ? x.ToString() // 1 : x.ToString(); // 2 } void M2(C? c, object? x, object? obj) { _ = (c?.M0(x = 0) == (int?)null) ? x.ToString() // 3 : x.ToString(); } void M3(C? c, object? x, object? obj) { _ = (c?.M0(x = 0) == null) ? x.ToString() // 4 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15), // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (23,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(23, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_13"/>.</remarks> [Fact] public void EqualsCondAccess_13() { var source = @" class C { long? M0(object obj) => null; void M(C? c, object? x, int i) { _ = (c?.M0(x = 0) == i) ? x.ToString() : x.ToString(); // 1 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_14"/>.</remarks> [Fact] public void EqualsCondAccess_14() { var source = @" using System.Diagnostics.CodeAnalysis; class C { long? M0(object obj) => null; void M1(C? c, object? x, int? i) { _ = (c?.M0(x = 0) == i) ? x.ToString() // 1 : x.ToString(); // 2 } void M2(C? c, object? x, int? i) { if (i is null) throw null!; _ = (c?.M0(x = 0) == i) ? x.ToString() : x.ToString(); // 3 } void M3(C? c, object? x, [DisallowNull] int? i) { _ = (c?.M0(x = 0) == i) ? x.ToString() : x.ToString(); // 4 } } "; CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }).VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (28,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(28, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_15"/>.</remarks> [Fact] public void EqualsCondAccess_15() { var source = @" class C { C M0(object obj) => this; void M(C? c, object? x) { _ = ((object?)c?.M0(x = 0) != null) ? x.ToString() : x.ToString(); // 1 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_16"/>.</remarks> [Fact] public void EqualsCondAccess_16() { var source = @" class C { void M(object? x) { _ = ""a""?.Equals(x = 0) == true ? x.ToString() : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_17"/>.</remarks> [Fact] public void EqualsCondAccess_17() { var source = @" class C { void M(C? c, object? x, object? y) { _ = (c?.Equals(x = 0), c?.Equals(y = 0)) == (true, true) ? x.ToString() // 1 : y.ToString(); // 2 } } "; // https://github.com/dotnet/roslyn/issues/50980 CreateNullableCompilation(source).VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 15), // (8,15): warning CS8602: Dereference of a possibly null reference. // : y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(8, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_18"/>.</remarks> [Fact] public void EqualsCondAccess_18() { var source = @" class C { public static bool operator ==(C? left, C? right) => false; public static bool operator !=(C? left, C? right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public C M0(out object x) { x = 42; return this; } public void M1(C? c, object? x) { _ = c?.M0(out x) != null ? x.ToString() : x.ToString(); // 1 } public void M2(C? c, object? x) { _ = c?.M0(out x) == null ? x.ToString() // 2 : x.ToString(); } public void M3(C? c, object? x) { _ = null != c?.M0(out x) ? x.ToString() : x.ToString(); // 3 } public void M4(C? c, object? x) { _ = null == c?.M0(out x) ? x.ToString() // 4 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (29,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(29, 15), // (35,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(35, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_19"/>.</remarks> [Fact] public void EqualsCondAccess_19() { var source = @" class C { public string M0(object obj) => obj.ToString(); public void M1(C? c, object? x, object? y) { _ = c?.M0(x = y = 1) != x.ToString() // 1 ? y.ToString() // 2 : y.ToString(); } public void M2(C? c, object? x, object? y) { _ = x.ToString() != c?.M0(x = y = 1) // 3 ? y.ToString() // 4 : y.ToString(); } public void M3(C? c, string? x) { _ = c?.M0(x = ""a"") != x ? x.ToString() // 5 : x.ToString(); // 6 } public void M4(C? c, string? x) { _ = x != c?.M0(x = ""a"") ? x.ToString() // 7 : x.ToString(); // 8 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (8,33): warning CS8602: Dereference of a possibly null reference. // _ = c?.M0(x = y = 1) != x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 33), // (9,15): warning CS8602: Dereference of a possibly null reference. // ? y.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 15), // (15,13): warning CS8602: Dereference of a possibly null reference. // _ = x.ToString() != c?.M0(x = y = 1) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 13), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? y.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(16, 15), // (23,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(23, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(30, 15), // (31,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(31, 15) ); } [Fact] public void EqualsBoolConstant_UserDefinedOperator_BoolRight() { var source = @" class C { public static bool operator ==(C? left, bool right) => false; public static bool operator !=(C? left, bool right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public void M1(C? c, object? x) { _ = c == (x != null) ? x.ToString() // 1 : x.ToString(); // 2 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 15), // (13,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_01"/>.</remarks> [Fact] public void IsCondAccess_01() { var source = @" class C { C M0(object obj) => this; void M1(C? c, object? x) { _ = c?.M0(x = 0) is C ? x.ToString() : x.ToString(); // 1 } void M2(C? c, object? x) { _ = c?.Equals(x = 0) is bool ? x.ToString() : x.ToString(); // 2 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (17,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_02"/>.</remarks> [Fact] public void IsCondAccess_02() { var source = @" class C { C M0(object obj) => this; void M1(C? c, object? x) { _ = c?.M0(x = 0) is (_) ? x.ToString() // 1 : x.ToString(); // unreachable } void M2(C? c, object? x) { _ = c?.M0(x = 0) is var y ? x.ToString() // 2 : x.ToString(); // unreachable } void M3(C? c, object? x) { _ = c?.M0(x = 0) is { } ? x.ToString() : x.ToString(); // 3 } void M4(C? c, object? x) { _ = c?.M0(x = 0) is { } c1 ? x.ToString() : x.ToString(); // 4 } void M5(C? c, object? x) { _ = c?.M0(x = 0) is C c1 ? x.ToString() : x.ToString(); // 5 } void M6(C? c, object? x) { _ = c?.M0(x = 0) is not null ? x.ToString() : x.ToString(); // 6 } void M7(C? c, object? x) { _ = c?.M0(x = 0) is not C ? x.ToString() // 7 : x.ToString(); } void M8(C? c, object? x) { _ = c?.M0(x = 0) is null ? x.ToString() // 8 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (31,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(31, 15), // (38,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(38, 15), // (45,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(45, 15), // (51,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(51, 15), // (58,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(58, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_03"/>.</remarks> [Fact] public void IsCondAccess_03() { var source = @" #nullable enable class C { (C, C) M0(object obj) => (this, this); void M1(C? c, object? x) { _ = c?.M0(x = 0) is (_, _) ? x.ToString() : x.ToString(); // 1 } void M2(C? c, object? x) { _ = c?.M0(x = 0) is not null ? x.ToString() : x.ToString(); // 2 } void M3(C? c, object? x) { _ = c?.M0(x = 0) is (not null, null) ? x.ToString() : x.ToString(); // 3 } void M4(C? c, object? x) { _ = c?.M0(x = 0) is null ? x.ToString() // 4 : x.ToString(); } void M5(C? c, object? x, object? y) { _ = (c?.M0(x = 0), c?.M0(y = 0)) is (not null, not null) ? x.ToString() // 5 : y.ToString(); // 6 } } "; // note: "state when not null" is not tracked when pattern matching against tuples containing conditional accesses. CreateCompilation(source).VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(19, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(26, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(32, 15), // (39,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(39, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : y.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(40, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_04"/>.</remarks> [Fact] public void IsCondAccess_04() { var source = @" #pragma warning disable 8794 // An expression always matches the provided pattern class C { C M0(object obj) => this; void M1(C? c, object? x) { _ = c?.M0(x = 0) is null or not null ? x.ToString() // 1 : x.ToString(); // unreachable } void M2(C? c, object? x) { _ = c?.M0(x = 0) is C or null ? x.ToString() // 2 : x.ToString(); // unreachable } void M3(C? c, object? x) { _ = c?.M0(x = 0) is not null and C ? x.ToString() : x.ToString(); // 3 } void M4(C? c, object? x) { _ = c?.M0(x = 0) is null ? x.ToString() // 4 : x.ToString(); } void M5(C? c, object? x) { _ = c?.M0(x = 0) is not (C or { }) ? x.ToString() // 5 : x.ToString(); } void M6(C? c, object? x) { _ = c?.M0(x = 0) is _ and C ? x.ToString() : x.ToString(); // 6 } void M7(C? c, object? x) { _ = c?.M0(x = 0) is C and _ ? x.ToString() : x.ToString(); // 7 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(18, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(26, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(32, 15), // (39,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(39, 15), // (47,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(47, 15), // (54,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(54, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_05"/>.</remarks> [Theory] [InlineData("int")] [InlineData("int?")] public void IsCondAccess_05(string returnType) { var source = @" class C { " + returnType + @" M0(object obj) => 1; void M1(C? c, object? x) { _ = c?.M0(x = 0) is 1 ? x.ToString() : x.ToString(); // 1 } void M2(C? c, object? x) { _ = c?.M0(x = 0) is > 10 ? x.ToString() : x.ToString(); // 2 } void M3(C? c, object? x) { _ = c?.M0(x = 0) is > 10 or < 0 ? x.ToString() : x.ToString(); // 3 } void M4(C? c, object? x) { _ = c?.M0(x = 0) is 1 or 2 ? x.ToString() : x.ToString(); // 4 } void M5(C? c, object? x) { _ = c?.M0(x = 0) is null ? x.ToString() // 5 : x.ToString(); } void M6(C? c, object? x) { _ = c?.M0(x = 0) is not null ? x.ToString() : x.ToString(); // 6 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (17,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (31,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(31, 15), // (37,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(37, 15), // (45,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(45, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_06"/>.</remarks> [Fact] public void IsCondAccess_06() { var source = @" class C { int M0(object obj) => 1; void M1(C? c, object? x) { _ = c?.M0(x = 0) is not null is true ? x.ToString() : x.ToString(); // 1 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_07"/>.</remarks> [Fact] public void IsCondAccess_07() { var source = @" class C { bool M0(object obj) => false; void M1(C? c, object? x) { _ = c?.M0(x = 0) is true or false ? x.ToString() : x.ToString(); // 1 } void M2(C? c, object? x) { _ = c?.M0(x = 0) is not (true or false) ? x.ToString() // 2 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_08"/>.</remarks> [Fact] public void IsCondAccess_08() { var source = @" #nullable enable class C { bool M0(object obj) => false; void M1(C? c, object? x) { _ = c?.M0(x = 0) is null or false ? x.ToString() // 1 : x.ToString(); } void M2(C? c, object? x) { _ = c?.M0(x = 0) is not (true or null) ? x.ToString() : x.ToString(); // 2 } } "; CreateCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(18, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_09"/>.</remarks> [Fact] public void IsCondAccess_09() { var source = @" #nullable enable class C { bool M0(object obj) => false; void M1(C? c, object? x) { _ = c?.M0(x = 0) is var z ? x.ToString() // 1 : x.ToString(); // unreachable } } "; CreateCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15) ); } [Fact] public void IsCondAccess_10() { var source = @" #nullable enable class C { object M0() => """"; void M1(C? c) { _ = c?.M0() is { } z ? z.ToString() : z.ToString(); // 1 } void M2(C? c) { _ = c?.M0() is """" and { } z ? z.ToString() : z.ToString(); // 2 } void M3(C? c) { _ = (string?)c?.M0() is 42 and { } z // 3 ? z.ToString() : z.ToString(); // 4 } void M4(C? c) { _ = c?.M0() is string z ? z.ToString() : z.ToString(); // 5 } } "; CreateCompilation(source).VerifyDiagnostics( // (11,15): error CS0165: Use of unassigned local variable 'z' // : z.ToString(); // 1 Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(11, 15), // (18,15): error CS0165: Use of unassigned local variable 'z' // : z.ToString(); // 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(18, 15), // (23,33): error CS0029: Cannot implicitly convert type 'int' to 'string' // _ = (string?)c?.M0() is 42 and { } z // 3 Diagnostic(ErrorCode.ERR_NoImplicitConv, "42").WithArguments("int", "string").WithLocation(23, 33), // (25,15): error CS0165: Use of unassigned local variable 'z' // : z.ToString(); // 4 Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(25, 15), // (32,15): error CS0165: Use of unassigned local variable 'z' // : z.ToString(); // 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(32, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void IsCondAccess_NotNullWhenTrue_01(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) is true ? obj.ToString() : obj.ToString(); // 1 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) is false ? obj.ToString() // 2 : obj.ToString(); // 3 } static void M3(C? c, object? obj) { _ = c?.M0(out obj) is not true // `is null or false` ? obj.ToString() // 4 : obj.ToString(); // 5 } static void M4(C? c, object? obj) { _ = c?.M0(out obj) is not false // `is null or true` ? obj.ToString() // 6 : obj.ToString(); // 7 } static void M5(C? c, object? obj) { _ = c?.M0(out obj) is not (true or null) // `is false` ? obj.ToString() // 8 : obj.ToString(); // 9 } static void M6(C? c, object? obj) { _ = c?.M0(out obj) is not (false or null) // `is true` ? obj.ToString() : obj.ToString(); // 10 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(25, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(32, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(33, 15), // (39,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(39, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(40, 15), // (47,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(47, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void IsCondAccess_NotNullWhenTrue_02(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) is true and 1 // 1 ? obj.ToString() // 2 : obj.ToString(); // 3 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) is true and var x ? obj.ToString() : obj.ToString(); // 4 } static void M3(C? c, object? obj) { _ = c?.M0(out obj) is _ and true ? obj.ToString() : obj.ToString(); // 5 } static void M4(C? c, object? obj) { _ = c?.M0(out obj) is true and bool b ? obj.ToString() : obj.ToString(); // 6 } static void M5(C? c, object? obj) { _ = c?.M0(out obj) is bool and true ? obj.ToString() : obj.ToString(); // 7 } static void M6(C? c, object? obj) { _ = c?.M0(out obj) is { } and true ? obj.ToString() : obj.ToString(); // 8 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (10,40): error CS0029: Cannot implicitly convert type 'int' to 'bool' // _ = c?.M0(out obj) is true and 1 // 1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool").WithLocation(10, 40), // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(26, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(33, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(40, 15), // (47,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(47, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void IsCondAccess_NotNullWhenTrue_03(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) is true or 1 // 1 ? obj.ToString() // 2 : obj.ToString(); // 3 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) is true or var x // 4, 5 ? obj.ToString() // 6 : obj.ToString(); // unreachable } static void M3(C? c, object? obj) { _ = c?.M0(out obj) is _ or true // 7 ? obj.ToString() // 8 : obj.ToString(); // unreachable } static void M4(C? c, object? obj) { _ = c?.M0(out obj) is true or bool b // 9 ? obj.ToString() // 10 : obj.ToString(); // 11 } static void M5(C? c, object? obj) { _ = c?.M0(out obj) is bool or true ? obj.ToString() // 12 : obj.ToString(); // 13 } static void M6(C? c, object? obj) { _ = c?.M0(out obj) is { } or true ? obj.ToString() // 14 : obj.ToString(); // 15 } static void M7(C? c, object? obj) { _ = c?.M0(out obj) is true or false ? obj.ToString() // 16 : obj.ToString(); // 17 } static void M8(C? c, object? obj) { _ = c?.M0(out obj) is null ? obj.ToString() // 18 : obj.ToString(); // 19 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (10,39): error CS0029: Cannot implicitly convert type 'int' to 'bool?' // _ = c?.M0(out obj) is true or 1 // 1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool?").WithLocation(10, 39), // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (17,13): warning CS8794: An expression of type 'bool?' always matches the provided pattern. // _ = c?.M0(out obj) is true or var x // 4, 5 Diagnostic(ErrorCode.WRN_IsPatternAlways, "c?.M0(out obj) is true or var x").WithArguments("bool?").WithLocation(17, 13), // (17,43): error CS8780: A variable may not be declared within a 'not' or 'or' pattern. // _ = c?.M0(out obj) is true or var x // 4, 5 Diagnostic(ErrorCode.ERR_DesignatorBeneathPatternCombinator, "x").WithLocation(17, 43), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (24,13): warning CS8794: An expression of type 'bool?' always matches the provided pattern. // _ = c?.M0(out obj) is _ or true // 7 Diagnostic(ErrorCode.WRN_IsPatternAlways, "c?.M0(out obj) is _ or true").WithArguments("bool?").WithLocation(24, 13), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(25, 15), // (31,44): error CS8780: A variable may not be declared within a 'not' or 'or' pattern. // _ = c?.M0(out obj) is true or bool b // 9 Diagnostic(ErrorCode.ERR_DesignatorBeneathPatternCombinator, "b").WithLocation(31, 44), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(32, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(33, 15), // (39,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(39, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(40, 15), // (46,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(46, 15), // (47,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 15 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(47, 15), // (53,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 16 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(53, 15), // (54,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 17 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(54, 15), // (60,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 18 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(60, 15), // (61,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 19 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(61, 15) ); } [Theory] [InlineData("[NotNullWhen(false)] out object? obj")] [InlineData("[MaybeNullWhen(true)] out object obj")] public void IsCondAccess_NotNullWhenFalse(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) is true ? obj.ToString() // 1 : obj.ToString(); // 2 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) is false ? obj.ToString() : obj.ToString(); // 3 } static void M3(C? c, object? obj) { _ = c?.M0(out obj) is not true // `is null or false` ? obj.ToString() // 4 : obj.ToString(); // 5 } static void M4(C? c, object? obj) { _ = c?.M0(out obj) is not false // `is null or true` ? obj.ToString() // 6 : obj.ToString(); } static void M5(C? c, object? obj) { _ = c?.M0(out obj) is not (true or null) // `is false` ? obj.ToString() : obj.ToString(); // 7 } static void M6(C? c, object? obj) { _ = c?.M0(out obj) is not (false or null) // `is true` ? obj.ToString() // 8 : obj.ToString(); // 9 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(25, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(26, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(32, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(40, 15), // (46,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(46, 15), // (47,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(47, 15) ); } [Fact] public void IsPattern_LeftConditionalState() { var source = @" class C { void M(object? obj) { _ = (obj != null) is true ? obj.ToString() : obj.ToString(); // 1 } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(8, 15)); } [Fact, WorkItem(53308, "https://github.com/dotnet/roslyn/issues/53308")] public void IsPattern_LeftCondAccess_PropertyPattern_01() { var source = @" class Program { void M1(B? b) { if (b is { C: { Prop: { } } }) { b.C.Prop.ToString(); } } void M2(B? b) { if (b?.C is { Prop: { } }) { b.C.Prop.ToString(); // 1 } } } class B { public C? C { get; set; } } class C { public string? Prop { get; set; } }"; // Ideally we would not issue diagnostic (1). // However, additional work is needed in nullable pattern analysis to make this work. var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // b.C.Prop.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.C.Prop").WithLocation(16, 13)); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_LeftCondAccess"/>.</remarks> [Fact] public void EqualsCondAccess_LeftCondAccess() { var source = @" class C { public C M0(object x) => this; public void M1(C? c, object? x, object? y) { _ = (c?.M0(x = 1))?.M0(y = 1) != null ? c.ToString() + x.ToString() + y.ToString() : c.ToString() + x.ToString() + y.ToString(); // 1, 2, 3 } public void M2(C? c, object? x, object? y, object? z) { _ = (c?.M0(x = 1)?.M0(y = 1))?.M0(z = 1) != null ? c.ToString() + x.ToString() + y.ToString() + z.ToString() : c.ToString() + x.ToString() + y.ToString() + z.ToString(); // 4, 5, 6, 7 } public void M3(C? c, object? x, object? y) { _ = ((object?)c?.M0(x = 1))?.Equals(y = 1) != null ? c.ToString() + x.ToString() + y.ToString() : c.ToString() + x.ToString() + y.ToString(); // 8, 9, 10 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString(); // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(10, 15), // (10,30): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString(); // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 30), // (10,45): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString(); // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(10, 45), // (17,15): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString() + z.ToString(); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(17, 15), // (17,30): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString() + z.ToString(); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 30), // (17,45): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString() + z.ToString(); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(17, 45), // (17,60): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString() + z.ToString(); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(17, 60), // (24,15): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString(); // 8, 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(24, 15), // (24,30): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString(); // 8, 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 30), // (24,45): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString(); // 8, 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(24, 45) ); } [Fact] public void ConditionalOperator_OperandConditionalState() { var source = @" class C { void M1(object? x, bool b) { _ = (b ? x != null : x != null) ? x.ToString() : x.ToString(); // 1 } void M2(object? x, bool b) { _ = (b ? x != null : x == null) ? x.ToString() // 2 : x.ToString(); // 3 } void M3(object? x, bool b) { _ = (b ? x == null : x != null) ? x.ToString() // 4 : x.ToString(); // 5 } void M4(object? x, bool b) { _ = (b ? x == null : x == null) ? x.ToString() // 6 : x.ToString(); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (14,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 15), // (28,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(28, 15)); } [Fact] public void ConditionalOperator_OperandUnreachable() { var source = @" class C { void M1(object? x, bool b) { _ = (b ? x != null : throw null!) ? x.ToString() : x.ToString(); // 1 } void M2(object? x, bool b) { _ = (b ? throw null! : x == null) ? x.ToString() // 2 : x.ToString(); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (14,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 15) ); } [Fact] public void NullCoalescing_RightSideBoolConstant() { var source = @" class C { bool M0(out object obj) { obj = new object(); return false; } static void M3(C? c, object? obj) { _ = c?.M0(out obj) ?? false ? obj.ToString() : obj.ToString(); // 1 } static void M4(C? c, object? obj) { _ = c?.M0(out obj) ?? true ? obj.ToString() // 2 : obj.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(16, 15) ); } [Fact] public void NullCoalescing_RightSideNullTest() { var source = @" class C { bool M0(out object obj) { obj = new object(); return false; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) ?? obj != null ? obj.ToString() : obj.ToString(); // 1 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) ?? obj == null ? obj.ToString() // 2 : obj.ToString(); } static void M5(C? c) { _ = c?.M0(out var obj) ?? obj != null // 3 ? obj.ToString() : obj.ToString(); // 4 } static void M6(C? c) { _ = c?.M0(out var obj) ?? obj == null // 5 ? obj.ToString() // 6 : obj.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(16, 15), // (22,35): error CS0165: Use of unassigned local variable 'obj' // _ = c?.M0(out var obj) ?? obj != null // 3 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(22, 35), // (24,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(24, 15), // (29,35): error CS0165: Use of unassigned local variable 'obj' // _ = c?.M0(out var obj) ?? obj == null // 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(29, 35), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(30, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void NotNullWhenTrue_NullCoalescing_RightSideBool(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c) { _ = c?.M0(out var obj) ?? false ? obj.ToString() : obj.ToString(); // 1, 2 } static void M2(C? c) { _ = c?.M0(out var obj) ?? true ? obj.ToString() // 3, 4 : obj.ToString(); // 5 } static void M3(C? c, bool b) { _ = c?.M0(out var obj1) ?? b ? obj1.ToString() // 6, 7 : """"; _ = c?.M0(out var obj2) ?? b ? """" : obj2.ToString(); // 8, 9 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (12,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 1, 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (18,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 3, 4 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj1' // ? obj1.ToString() // 6, 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(25, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 8, 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(30, 15), // (30,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 8, 9 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(30, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void NotNullWhenTrue_NullCoalescing_RightSideNullTest(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) ?? obj != null ? obj.ToString() : obj.ToString(); // 1 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) ?? obj == null ? obj.ToString() // 2 : obj.ToString(); // 3 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15) ); } [Theory] [InlineData("[NotNullWhen(false)] out object? obj")] [InlineData("[MaybeNullWhen(true)] out object obj")] public void NotNullWhenFalse_NullCoalescing_RightSideNullTest(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) ?? obj != null ? obj.ToString() // 1 : obj.ToString(); // 2 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) ?? obj == null ? obj.ToString() // 3 : obj.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15) ); } [Theory] [InlineData("[NotNullWhen(false)] out object? obj")] [InlineData("[MaybeNullWhen(true)] out object obj")] public void NotNullWhenFalse_NullCoalescing(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return false; } static void M1(C? c) { _ = c?.M0(out var obj) ?? false ? obj.ToString() // 1 : obj.ToString(); // 2, 3 } static void M2(C? c) { _ = c?.M0(out var obj) ?? true ? obj.ToString() // 4, 5 : obj.ToString(); } static void M3(C? c, bool b) { _ = c?.M0(out var obj1) ?? b ? obj1.ToString() // 6, 7 : """"; _ = c?.M0(out var obj2) ?? b ? """" : obj2.ToString(); // 8, 9 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (12,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 2, 3 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (18,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 4, 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(18, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj1' // ? obj1.ToString() // 6, 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(25, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 8, 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(30, 15), // (30,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 8, 9 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(30, 15) ); } [Fact] [WorkItem(26624, "https://github.com/dotnet/roslyn/issues/26624")] public void CondAccess_Multiple_Arguments() { var source = @" static class C { static bool? M0(this bool b, object? obj) { return b; } static void M1(bool? b, object? obj) { _ = b?.M0(obj = new object()) ?? false ? obj.ToString() : obj.ToString(); // 1 } static void M2(bool? b) { var obj = new object(); _ = b?.M0(obj = null)?.M0(obj = new object()) ?? false ? obj.ToString() : obj.ToString(); // 2 } static void M3(bool? b) { var obj = new object(); _ = b?.M0(obj = new object())?.M0(obj = null) ?? false ? obj.ToString() // 3 : obj.ToString(); // 4 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(10, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(25, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(26, 15) ); } [Fact] [WorkItem(26624, "https://github.com/dotnet/roslyn/issues/26624")] public void NullCoalescing_LeftStateAfterExpression() { var source = @" class C { static void M1(bool? flag) { _ = flag ?? false ? flag.Value : flag.Value; // 1 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (8,15): warning CS8629: Nullable value type may be null. // : flag.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "flag").WithLocation(8, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_01"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_01() { var source = @" class C { void M1(C c, object? x) { _ = c?.M(x = new object()) ?? true ? x.ToString() // 1 : x.ToString(); } void M2(C c, object? x) { _ = c?.M(x = new object()) ?? false ? x.ToString() : x.ToString(); // 2; } bool M(object x) => true; } "; CreateNullableCompilation(source).VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_02"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_02() { var source = @" class C { void M1(C c1, C c2, object? x) { _ = c1?.M(x = new object()) ?? c2?.M(x = new object()) ?? true ? x.ToString() // 1 : x.ToString(); } void M2(C c1, C c2, object? x) { _ = c1?.M(x = new object()) ?? c2?.M(x = new object()) ?? false ? x.ToString() : x.ToString(); // 2; } bool M(object x) => true; } "; CreateNullableCompilation(source).VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_03"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_03() { var source = @" class C { void M1(C c1, object? x) { _ = c1?.MA().MB(x = new object()) ?? false ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = c1?.MA()?.MB(x = new object()) ?? false ? x.ToString() : x.ToString(); // 2; } C MA() => this; bool MB(object x) => true; } "; CreateNullableCompilation(source).VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_04"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_04() { var source = @" class C { void M1(C c1, object? x) { _ = c1?.MA(x = new object()).MB() ?? false ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = c1?.MA(x = new object())?.MB() ?? false ? x.ToString() : x.ToString(); // 2; } C MA(object x) => this; bool MB() => true; } "; CreateNullableCompilation(source).VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_05"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_05() { var source = @" class C { void M1(C c1, object? x) { _ = c1?.MA(c1.MB(x = new object())) ?? false ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = c1?.MA(c1?.MB(x = new object())) ?? false ? x.ToString() // 2 : x.ToString(); // 3 } bool MA(object? obj) => true; C MB(object x) => this; } "; CreateNullableCompilation(source).VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (14,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_06"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_06() { var source = @" class C { void M1(C c1, object? x) { _ = c1?.M(out x) ?? false ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = c1?.M(out x) ?? false ? x.ToString() : x.ToString(); // 2 } bool M(out object obj) { obj = new object(); return true; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_07"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_07() { var source = @" class C { void M1(bool b, C c1, object? x) { _ = c1?.M(x = new object()) ?? b ? x.ToString() // 1 : x.ToString(); // 2 } bool M(object obj) { return true; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 15), // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_08"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_08() { var source = @" class C { void M1(C c1, object? x) { _ = (c1?.M(x = 0)) ?? false ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = c1?.M(x = 0)! ?? false ? x.ToString() : x.ToString(); // 2 } void M3(C c1, object? x) { _ = (c1?.M(x = 0))! ?? false ? x.ToString() : x.ToString(); // 3 } bool M(object obj) { return true; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_09"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_09() { var source = @" class C { void M1(C c1, object? x) { _ = (c1?[x = 0]) ?? false ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = (c1?[x = 0]) ?? true ? x.ToString() // 2 : x.ToString(); } public bool this[object x] => false; } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_10"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_10() { var source = @" class C { void M1(C c1, object? x) { _ = (bool?)null ?? (c1?.M(x = 0) ?? false) ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = (bool?)null ?? (c1?.M(x = 0) ?? true) ? x.ToString() // 2 : x.ToString(); } bool M(object obj) { return true; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15)); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_ConditionalLeft"/>.</remarks> [Fact] public void NullCoalescing_ConditionalLeft() { var source = @" class C { void M1(C c1, bool b, object? x) { _ = (bool?)(b && c1.M(x = 0)) ?? false ? x.ToString() // 1 : x.ToString(); // 2 } void M2(C c1, bool b, object? x) { _ = (bool?)c1.M(x = 0) ?? false ? x.ToString() : x.ToString(); } void M3(C c1, bool b, object? x, object? y) { _ = (bool?)((y = 0) is 0 && c1.M(x = 0)) ?? false ? x.ToString() + y.ToString() // 3 : x.ToString() + y.ToString(); // 4 } bool M(object obj) { return true; } } "; // Note that we unsplit any conditional state after visiting the left side of `??`. CreateNullableCompilation(source).VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 15), // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 15) ); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_Throw"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_Throw() { var source = @" class C { void M1(C c1, bool b, object? x) { _ = c1?.M(x = 0) ?? throw new System.Exception(); x.ToString(); } bool M(object obj) { return true; } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_Cast"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_Cast() { var source = @" class C { void M1(C c1, bool b, object? x) { _ = (object)c1?.M(x = 0) ?? throw new System.Exception(); // 1 x.ToString(); } C M(object obj) { return this; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // _ = (object)c1?.M(x = 0) ?? throw new System.Exception(); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)c1?.M(x = 0)").WithLocation(6, 13)); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_01"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_UserDefinedConv_01() { var source = @" struct S { } struct C { public static implicit operator S(C? c) { return default(S); } void M1(C? c1, object? x) { S s = c1?.M2(x = 0) ?? c1!.Value.M3(x = 0); x.ToString(); } C M2(object obj) { return this; } S M3(object obj) { return this; } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_02"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_UserDefinedConv_02() { var source = @" class B { } class C { public static implicit operator B(C c) => new B(); void M1(C c1, object? x) { B b = c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_03"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_UserDefinedConv_03() { var source = @" struct B { } struct C { public static implicit operator B(C c) => new B(); void M1(C? c1, object? x) { B b = c1?.M1(x = 0) ?? c1!.Value.M2(x = 0); x.ToString(); } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_04"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_UserDefinedConv_04() { var source = @" struct B { } struct C { public static implicit operator B?(C c) => null; void M1(C? c1, object? x) { B? b = c1?.M1(x = 0) ?? c1!.Value.M2(x = 0); x.ToString(); } C M1(object obj) { return this; } B? M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_05"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_UserDefinedConv_05() { var source = @" struct B { public static implicit operator B(C c) => default; } class C { static void M1(C c1, object? x) { B b = c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); } C M1(object obj) { return this; } B M2(object obj) { return this; } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_01"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_01_01(string conversionKind) { var source = @" struct S { } struct C { public static " + conversionKind + @" operator S(C? c) { return default(S); } void M1(C? c1, object? x) { S s = (S?)c1?.M2(x = 0) ?? c1!.Value.M3(x = 0); x.ToString(); // 1 } C M2(object obj) { return this; } S M3(object obj) { return (S)this; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 9) ); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_01"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_01_02(string conversionKind) { var source = @" using System.Diagnostics.CodeAnalysis; struct S { } struct C { public static " + conversionKind + @" operator S([DisallowNull] C? c) { return default(S); } void M1(C? c1, object? x) { S s = (S?)c1?.M2(x = 0) ?? c1!.Value.M3(x = 0); // 1 x.ToString(); // 2 } C M2(object obj) { return this; } S M3(object obj) { return (S)this; } } "; CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }).VerifyDiagnostics( // (15,19): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // S s = (S?)c1?.M2(x = 0) ?? c1!.Value.M3(x = 0); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "c1?.M2(x = 0)").WithLocation(15, 19), // (16,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 9) ); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_02"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_02_01(string conversionKind) { var source = @" class B { } class C { public static " + conversionKind + @" operator B(C? c) => new B(); void M1(C c1, object? x) { B b = (B)c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); // 1 } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9)); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_02"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_02_02(string conversionKind) { var source = @" class B { } class C { public static " + conversionKind + @" operator B?(C? c) => new B(); void M1(C c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); // 1 } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9)); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_02"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_02_03(string conversionKind) { var source = @" using System.Diagnostics.CodeAnalysis; class B { } class C { [return: NotNullIfNotNull(""c"")] public static " + conversionKind + @" operator B?(C? c) => new B(); void M1(C c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); // 1 } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }).VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 9)); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_02"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_02_04(string conversionKind) { var source = @" using System.Diagnostics.CodeAnalysis; class B { } class C { [return: NotNull] public static " + conversionKind + @" operator B?(C? c) => new B(); void M1(C c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); // 1 } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }).VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 9)); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_02"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_02_05(string conversionKind) { var source = @" class B { } class C { public static " + conversionKind + @" operator B(C c) => new B(); void M1(C c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); // 1 x.ToString(); // 2 } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,19): warning CS8604: Possible null reference argument for parameter 'c' in 'C.implicit operator B(C c)'. // B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c1?.M1(x = 0)").WithArguments("c", "C." + conversionKind + " operator B(C c)").WithLocation(9, 19), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9) ); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_03"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_03(string conversionKind) { var source = @" struct B { } struct C { public static " + conversionKind + @" operator B(C c) => new B(); void M1(C? c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.Value.M2(x = 0); x.ToString(); } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_04"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_04(string conversionKind) { var source = @" struct B { } struct C { public static " + conversionKind + @" operator B?(C c) => null; void M1(C? c1, object? x) { B? b = (B?)c1?.M1(x = 0) ?? c1!.Value.M2(x = 0); x.ToString(); } C M1(object obj) { return this; } B? M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_05"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_05_01(string conversionKind) { var source = @" struct B { public static " + conversionKind + @" operator B(C? c) => default; } class C { static void M1(C c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); // 1 } C M1(object obj) { return this; } B M2(object obj) { return default; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 9) ); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_05"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_05_02(string conversionKind) { var source = @" using System.Diagnostics.CodeAnalysis; struct B { public static " + conversionKind + @" operator B([DisallowNull] C? c) => default; } class C { static void M1(C c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); // 1 x.ToString(); // 2 } C M1(object obj) { return this; } B M2(object obj) { return default; } } "; CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }).VerifyDiagnostics( // (13,19): warning CS8604: Possible null reference argument for parameter 'c' in 'B.implicit operator B(C? c)'. // B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c1?.M1(x = 0)").WithArguments("c", "B." + conversionKind + " operator B(C? c)").WithLocation(13, 19), // (14,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 9) ); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_NullableEnum"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_NullableEnum() { var source = @" public enum E { E1 = 1 } public static class Extensions { public static E M1(this E e, object obj) => e; static void M2(E? e, object? x) { E e2 = e?.M1(x = 0) ?? e!.Value.M1(x = 0); x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } /// <remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_NonNullConstantLeft"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_NonNullConstantLeft() { var source = @" static class C { static string M0(this string s, object? x) => s; static void M1(object? x) { _ = """"?.Equals(x = new object()) ?? false ? x.ToString() : x.ToString(); } static void M2(object? x, object? y) { _ = """"?.M0(x = new object())?.Equals(y = new object()) ?? false ? x.ToString() + y.ToString() : x.ToString() + y.ToString(); // 1 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (17,30): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(17, 30)); } /// <remarks>Ported from <see cref="FlowTests.NullCoalescing_NonNullConstantLeft"/>.</remarks> [Fact] public void NullCoalescing_NonNullConstantLeft() { var source = @" static class C { static void M1(object? x) { _ = """" ?? $""{x.ToString()}""; // unreachable _ = """".ToString() ?? $""{x.ToString()}""; // 1 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (7,33): warning CS8602: Dereference of a possibly null reference. // _ = "".ToString() ?? $"{x.ToString()}"; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 33) ); } [Fact] public void NullCoalescing_CondAccess_NullableClassConstraint() { var source = @" interface I { bool M0(object obj); } static class C<T> where T : class?, I { static void M1(T t, object? x) { _ = t?.M0(x = 1) ?? false ? t.ToString() + x.ToString() : t.ToString() + x.ToString(); // 1, 2 } static void M2(T t, object? x) { _ = t?.M0(x = 1) ?? false ? M2(t) + x.ToString() : M2(t) + x.ToString(); // 3, 4 } // 'T' is allowed as an argument with a maybe-null state, but not with a maybe-default state. static string M2(T t) => t!.ToString(); } "; CreateNullableCompilation(source).VerifyDiagnostics( // (13,15): warning CS8602: Dereference of a possibly null reference. // : t.ToString() + x.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(13, 15), // (13,30): warning CS8602: Dereference of a possibly null reference. // : t.ToString() + x.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 30), // (20,18): warning CS8604: Possible null reference argument for parameter 't' in 'string C<T>.M2(T t)'. // : M2(t) + x.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("t", "string C<T>.M2(T t)").WithLocation(20, 18), // (20,23): warning CS8602: Dereference of a possibly null reference. // : M2(t) + x.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(20, 23) ); } [Fact] public void ConditionalBranching_Is_ReferenceType() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void Test(object? x) { if (x is C) { x.ToString(); } else { x.ToString(); // warn } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 13) ); } [Fact] public void ConditionalBranching_Is_GenericType() { CSharpCompilation c = CreateCompilation(new[] { @" class Base { } class C : Base { void Test<T>(C? x) where T : Base { if (x is T) { x.ToString(); } else { x.ToString(); // warn } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 13) ); } [Fact] public void ConditionalBranching_Is_UnconstrainedGenericType() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void F<T>(object? o) { if (o is T) { o.ToString(); } else { o.ToString(); // warn } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(12, 13) ); } [Fact] public void ConditionalBranching_Is_StructConstrainedGenericType() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void F<T>(object? o) where T : struct { if (o is T) { o.ToString(); } else { o.ToString(); // warn } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(12, 13) ); } [Fact] public void ConditionalBranching_Is_ClassConstrainedGenericType() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void F<T>(object? o) where T : class { if (o is T) { o.ToString(); } else { o.ToString(); // warn } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(12, 13) ); } [Fact] public void ConditionalBranching_Is_UnconstrainedGenericOperand() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void F<T>(T t, object? o) { if (t is string) t.ToString(); if (t is string s) { t.ToString(); s.ToString(); } if (t != null) t.ToString(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void ConditionalBranching_Is_NullOperand() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void F(object? o) { if (null is string) return; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,13): warning CS0184: The given expression is never of the provided ('string') type // if (null is string) return; Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null is string").WithArguments("string").WithLocation(6, 13) ); } [Fact] public void ConditionalOperator_01() { var source = @"class C { static void F(bool b, object x, object? y) { var z = b ? x : y; z.ToString(); var w = b ? y : x; w.ToString(); var v = true ? y : x; v.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // w.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // v.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v").WithLocation(10, 9)); } [Fact] public void ConditionalOperator_02() { var source = @"class C { static void F(bool b, object x, object? y) { (b ? x : y).ToString(); (b ? y : x).ToString(); if (y != null) (b ? x : y).ToString(); if (y != null) (b ? y : x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,10): warning CS8602: Dereference of a possibly null reference. // (b ? x : y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x : y").WithLocation(5, 10), // (6,10): warning CS8602: Dereference of a possibly null reference. // (b ? y : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? y : x").WithLocation(6, 10)); } [Fact] public void ConditionalOperator_03() { var source = @"class C { static void F(object x, object? y) { (false ? x : y).ToString(); (false ? y : x).ToString(); (true ? x : y).ToString(); (true ? y : x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,10): warning CS8602: Dereference of a possibly null reference. // (false ? x : y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "false ? x : y").WithLocation(5, 10), // (8,10): warning CS8602: Dereference of a possibly null reference. // (true ? y : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "true ? y : x").WithLocation(8, 10)); } [Fact] public void ConditionalOperator_04() { var source = @"class C { static void F(bool b, object x, string? y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } static void G(bool b, object? x, string y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,10): warning CS8602: Dereference of a possibly null reference. // (b ? x : y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x : y").WithLocation(5, 10), // (6,10): warning CS8602: Dereference of a possibly null reference. // (b ? y : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? y : x").WithLocation(6, 10), // (10,10): warning CS8602: Dereference of a possibly null reference. // (b ? x : y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x : y").WithLocation(10, 10), // (11,10): warning CS8602: Dereference of a possibly null reference. // (b ? y : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? y : x").WithLocation(11, 10)); } [Fact] public void ConditionalOperator_05() { var source = @"#pragma warning disable 0649 class A<T> { } class B1 : A<object?> { } class B2 : A<object> { } class C { static void F(bool b, A<object> x, A<object?> y, B1 z, B2 w) { object o; o = (b ? x : z)/*T:A<object!>!*/; o = (b ? x : w)/*T:A<object!>!*/; o = (b ? z : x)/*T:A<object!>!*/; o = (b ? w : x)/*T:A<object!>!*/; o = (b ? y : z)/*T:A<object?>!*/; o = (b ? y : w)/*T:A<object?>!*/; o = (b ? z : y)/*T:A<object?>!*/; o = (b ? w : y)/*T:A<object?>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (10,22): warning CS8619: Nullability of reference types in value of type 'B1' doesn't match target type 'A<object>'. // o = (b ? x : z)/*T:A<object!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "z").WithArguments("B1", "A<object>").WithLocation(10, 22), // (12,18): warning CS8619: Nullability of reference types in value of type 'B1' doesn't match target type 'A<object>'. // o = (b ? z : x)/*T:A<object!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "z").WithArguments("B1", "A<object>").WithLocation(12, 18), // (15,22): warning CS8619: Nullability of reference types in value of type 'B2' doesn't match target type 'A<object?>'. // o = (b ? y : w)/*T:A<object?>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("B2", "A<object?>").WithLocation(15, 22), // (17,18): warning CS8619: Nullability of reference types in value of type 'B2' doesn't match target type 'A<object?>'. // o = (b ? w : y)/*T:A<object?>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("B2", "A<object?>").WithLocation(17, 18)); } [Fact] public void ConditionalOperator_06() { var source = @"class C { static void F(bool b, object x, string? y) { (b ? null : x).ToString(); (b ? null : y).ToString(); (b ? x: null).ToString(); (b ? y: null).ToString(); (b ? null: null).ToString(); (b ? default : x).ToString(); (b ? default : y).ToString(); (b ? x: default).ToString(); (b ? y: default).ToString(); (b ? default: default).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and '<null>' // (b ? null: null).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? null: null").WithArguments("<null>", "<null>").WithLocation(9, 10), // (14,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'default' and 'default' // (b ? default: default).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? default: default").WithArguments("default", "default").WithLocation(14, 10), // (5,10): warning CS8602: Dereference of a possibly null reference. // (b ? null : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? null : x").WithLocation(5, 10), // (6,10): warning CS8602: Dereference of a possibly null reference. // (b ? null : y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? null : y").WithLocation(6, 10), // (7,10): warning CS8602: Dereference of a possibly null reference. // (b ? x: null).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x: null").WithLocation(7, 10), // (8,10): warning CS8602: Dereference of a possibly null reference. // (b ? y: null).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? y: null").WithLocation(8, 10), // (10,10): warning CS8602: Dereference of a possibly null reference. // (b ? default : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? default : x").WithLocation(10, 10), // (11,10): warning CS8602: Dereference of a possibly null reference. // (b ? default : y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? default : y").WithLocation(11, 10), // (12,10): warning CS8602: Dereference of a possibly null reference. // (b ? x: default).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x: default").WithLocation(12, 10), // (13,10): warning CS8602: Dereference of a possibly null reference. // (b ? y: default).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? y: default").WithLocation(13, 10) ); } [Fact] public void ConditionalOperator_07() { var source = @"class C { static void F(bool b, Unknown x, Unknown? y) { (b ? null : x).ToString(); (b ? null : y).ToString(); (b ? x: null).ToString(); (b ? y: null).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,27): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // static void F(bool b, Unknown x, Unknown? y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(3, 27), // (3,38): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // static void F(bool b, Unknown x, Unknown? y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(3, 38) ); } [Fact] public void ConditionalOperator_08() { var source = @"class C { static void F1(bool b, UnknownA x, UnknownB y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } static void F2(bool b, UnknownA? x, UnknownB y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } static void F3(bool b, UnknownA? x, UnknownB? y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,28): error CS0246: The type or namespace name 'UnknownA' could not be found (are you missing a using directive or an assembly reference?) // static void F2(bool b, UnknownA? x, UnknownB y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnknownA").WithArguments("UnknownA").WithLocation(8, 28), // (8,41): error CS0246: The type or namespace name 'UnknownB' could not be found (are you missing a using directive or an assembly reference?) // static void F2(bool b, UnknownA? x, UnknownB y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnknownB").WithArguments("UnknownB").WithLocation(8, 41), // (13,28): error CS0246: The type or namespace name 'UnknownA' could not be found (are you missing a using directive or an assembly reference?) // static void F3(bool b, UnknownA? x, UnknownB? y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnknownA").WithArguments("UnknownA").WithLocation(13, 28), // (13,41): error CS0246: The type or namespace name 'UnknownB' could not be found (are you missing a using directive or an assembly reference?) // static void F3(bool b, UnknownA? x, UnknownB? y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnknownB").WithArguments("UnknownB").WithLocation(13, 41), // (3,28): error CS0246: The type or namespace name 'UnknownA' could not be found (are you missing a using directive or an assembly reference?) // static void F1(bool b, UnknownA x, UnknownB y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnknownA").WithArguments("UnknownA").WithLocation(3, 28), // (3,40): error CS0246: The type or namespace name 'UnknownB' could not be found (are you missing a using directive or an assembly reference?) // static void F1(bool b, UnknownA x, UnknownB y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnknownB").WithArguments("UnknownB").WithLocation(3, 40), // (15,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'UnknownA?' and 'UnknownB?' // (b ? x : y).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? x : y").WithArguments("UnknownA?", "UnknownB?").WithLocation(15, 10), // (16,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'UnknownB?' and 'UnknownA?' // (b ? y : x).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? y : x").WithArguments("UnknownB?", "UnknownA?").WithLocation(16, 10) ); } [Fact] public void ConditionalOperator_09() { var source = @"struct A { } struct B { } class C { static void F1(bool b, A x, B y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } static void F2(bool b, A x, C y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } static void F3(bool b, B x, C? y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'B' // (b ? x : y).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? x : y").WithArguments("A", "B").WithLocation(7, 10), // (8,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'B' and 'A' // (b ? y : x).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? y : x").WithArguments("B", "A").WithLocation(8, 10), // (12,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'C' // (b ? x : y).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? x : y").WithArguments("A", "C").WithLocation(12, 10), // (13,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'C' and 'A' // (b ? y : x).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? y : x").WithArguments("C", "A").WithLocation(13, 10), // (17,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'B' and 'C' // (b ? x : y).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? x : y").WithArguments("B", "C").WithLocation(17, 10), // (18,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'C' and 'B' // (b ? y : x).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? y : x").WithArguments("C", "B").WithLocation(18, 10) ); } [Fact] public void ConditionalOperator_10() { var source = @"using System; class C { static void F(bool b, object? x, object y) { (b ? x : throw new Exception()).ToString(); (b ? y : throw new Exception()).ToString(); (b ? throw new Exception() : x).ToString(); (b ? throw new Exception() : y).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (b ? x : throw new Exception()).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x : throw new Exception()").WithLocation(6, 10), // (8,10): warning CS8602: Dereference of a possibly null reference. // (b ? throw new Exception() : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? throw new Exception() : x").WithLocation(8, 10)); } [Fact] public void ConditionalOperator_11() { var source = @"class C { static void F(bool b, object x) { (b ? x : throw null!).ToString(); (b ? throw null! : x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ConditionalOperator_12() { var source = @"using System; class C { static void F(bool b) { (b ? throw new Exception() : throw new Exception()).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between '<throw expression>' and '<throw expression>' // (b ? throw new Exception() : throw new Exception()).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? throw new Exception() : throw new Exception()").WithArguments("<throw expression>", "<throw expression>").WithLocation(6, 10)); } [Fact] public void ConditionalOperator_13() { var source = @"class C { static bool F(object? x) { return true; } static void F1(bool c, bool b1, bool b2, object v1) { object x1; object y1; object? z1 = null; object? w1 = null; if (c ? b1 && F(x1 = v1) && F(z1 = v1) : b2 && F(y1 = v1) && F(w1 = v1)) { x1.ToString(); // unassigned (if) y1.ToString(); // unassigned (if) z1.ToString(); // may be null (if) w1.ToString(); // may be null (if) } else { x1.ToString(); // unassigned (no error) (else) y1.ToString(); // unassigned (no error) (else) z1.ToString(); // may be null (else) w1.ToString(); // may be null (else) } } static void F2(bool b1, bool b2, object v2) { object x2; object y2; object? z2 = null; object? w2 = null; if (true ? b1 && F(x2 = v2) && F(z2 = v2) : b2 && F(y2 = v2) && F(w2 = v2)) { x2.ToString(); // ok (if) y2.ToString(); // unassigned (if) z2.ToString(); // ok (if) w2.ToString(); // may be null (if) } else { x2.ToString(); // unassigned (else) y2.ToString(); // unassigned (no error) (else) z2.ToString(); // may be null (else) w2.ToString(); // may be null (else) } } static void F3(bool b1, bool b2, object v3) { object x3; object y3; object? z3 = null; object? w3 = null; if (false ? b1 && F(x3 = v3) && F(z3 = v3) : b2 && F(y3 = v3) && F(w3 = v3)) { x3.ToString(); // unassigned (if) y3.ToString(); // ok (if) z3.ToString(); // may be null (if) w3.ToString(); // ok (if) } else { x3.ToString(); // unassigned (no error) (else) y3.ToString(); // unassigned (else) z3.ToString(); // may be null (else) w3.ToString(); // may be null (else) } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): error CS0165: Use of unassigned local variable 'x1' // x1.ToString(); // unassigned (if) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(15, 13), // (16,13): error CS0165: Use of unassigned local variable 'y1' // y1.ToString(); // unassigned (if) Diagnostic(ErrorCode.ERR_UseDefViolation, "y1").WithArguments("y1").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // z1.ToString(); // may be null (if) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1").WithLocation(17, 13), // (18,13): warning CS8602: Dereference of a possibly null reference. // w1.ToString(); // may be null (if) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w1").WithLocation(18, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // z1.ToString(); // may be null (else) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1").WithLocation(24, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // w1.ToString(); // may be null (else) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w1").WithLocation(25, 13), // (37,13): error CS0165: Use of unassigned local variable 'y2' // y2.ToString(); // unassigned (if) Diagnostic(ErrorCode.ERR_UseDefViolation, "y2").WithArguments("y2").WithLocation(37, 13), // (43,13): error CS0165: Use of unassigned local variable 'x2' // x2.ToString(); // unassigned (else) Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(43, 13), // (39,13): warning CS8602: Dereference of a possibly null reference. // w2.ToString(); // may be null (if) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w2").WithLocation(39, 13), // (45,13): warning CS8602: Dereference of a possibly null reference. // z2.ToString(); // may be null (else) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2").WithLocation(45, 13), // (46,13): warning CS8602: Dereference of a possibly null reference. // w2.ToString(); // may be null (else) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w2").WithLocation(46, 13), // (57,13): error CS0165: Use of unassigned local variable 'x3' // x3.ToString(); // unassigned (if) Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(57, 13), // (65,13): error CS0165: Use of unassigned local variable 'y3' // y3.ToString(); // unassigned (else) Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(65, 13), // (59,13): warning CS8602: Dereference of a possibly null reference. // z3.ToString(); // may be null (if) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z3").WithLocation(59, 13), // (66,13): warning CS8602: Dereference of a possibly null reference. // z3.ToString(); // may be null (else) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z3").WithLocation(66, 13), // (67,13): warning CS8602: Dereference of a possibly null reference. // w3.ToString(); // may be null (else) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w3").WithLocation(67, 13)); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_14() { var source = @"interface I<T> { T P { get; } } interface IIn<in T> { } interface IOut<out T> { T P { get; } } class C { static void F1(bool b, ref string? x1, ref string y1) { (b ? ref x1 : ref x1)/*T:string?*/.ToString(); // 1 (b ? ref x1 : ref y1)/*T:string?*/.ToString(); // 2, 3 (b ? ref y1 : ref x1)/*T:string?*/.ToString(); // 4, 5 (b ? ref y1 : ref y1)/*T:string!*/.ToString(); } static void F2(bool b, ref I<string?> x2, ref I<string> y2) { (b ? ref x2 : ref x2)/*T:I<string?>!*/.P.ToString(); // 6 (b ? ref y2 : ref x2)/*T:I<string>!*/.P.ToString(); // 7 (b ? ref x2 : ref y2)/*T:I<string>!*/.P.ToString(); // 8, 9 (b ? ref y2 : ref y2)/*T:I<string!>!*/.P.ToString(); } static void F3(bool b, ref IIn<string?> x3, ref IIn<string> y3) { (b ? ref x3 : ref x3)/*T:IIn<string?>!*/.ToString(); (b ? ref y3 : ref x3)/*T:IIn<string>!*/.ToString(); // 10 (b ? ref x3 : ref y3)/*T:IIn<string>!*/.ToString(); // 11 (b ? ref y3 : ref y3)/*T:IIn<string!>!*/.ToString(); } static void F4(bool b, ref IOut<string?> x4, ref IOut<string> y4) { (b ? ref x4 : ref x4)/*T:IOut<string?>!*/.P.ToString(); // 12 (b ? ref y4 : ref x4)/*T:IOut<string>!*/.P.ToString(); // 13 (b ? ref x4 : ref y4)/*T:IOut<string>!*/.P.ToString(); // 14 (b ? ref y4 : ref y4)/*T:IOut<string!>!*/.P.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (8,10): warning CS8602: Possible dereference of a null reference. // (b ? ref x1 : ref x1)/*T:string?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref x1 : ref x1").WithLocation(8, 10), // (9,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // (b ? ref x1 : ref y1)/*T:string?*/.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x1 : ref y1").WithArguments("string?", "string").WithLocation(9, 10), // (9,10): warning CS8602: Possible dereference of a null reference. // (b ? ref x1 : ref y1)/*T:string?*/.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref x1 : ref y1").WithLocation(9, 10), // (10,10): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // (b ? ref y1 : ref x1)/*T:string?*/.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y1 : ref x1").WithArguments("string", "string?").WithLocation(10, 10), // (10,10): warning CS8602: Possible dereference of a null reference. // (b ? ref y1 : ref x1)/*T:string?*/.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref y1 : ref x1").WithLocation(10, 10), // (15,9): warning CS8602: Possible dereference of a null reference. // (b ? ref x2 : ref x2)/*T:I<string?>!*/.P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b ? ref x2 : ref x2)/*T:I<string?>!*/.P").WithLocation(15, 9), // (16,10): warning CS8619: Nullability of reference types in value of type 'I<string>' doesn't match target type 'I<string?>'. // (b ? ref y2 : ref x2)/*T:I<string>!*/.P.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y2 : ref x2").WithArguments("I<string>", "I<string?>").WithLocation(16, 10), // (17,10): warning CS8619: Nullability of reference types in value of type 'I<string?>' doesn't match target type 'I<string>'. // (b ? ref x2 : ref y2)/*T:I<string>!*/.P.ToString(); // 8, 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x2 : ref y2").WithArguments("I<string?>", "I<string>").WithLocation(17, 10), // (23,10): warning CS8619: Nullability of reference types in value of type 'IIn<string>' doesn't match target type 'IIn<string?>'. // (b ? ref y3 : ref x3)/*T:IIn<string>!*/.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y3 : ref x3").WithArguments("IIn<string>", "IIn<string?>").WithLocation(23, 10), // (24,10): warning CS8619: Nullability of reference types in value of type 'IIn<string?>' doesn't match target type 'IIn<string>'. // (b ? ref x3 : ref y3)/*T:IIn<string>!*/.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x3 : ref y3").WithArguments("IIn<string?>", "IIn<string>").WithLocation(24, 10), // (29,9): warning CS8602: Possible dereference of a null reference. // (b ? ref x4 : ref x4)/*T:IOut<string?>!*/.P.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b ? ref x4 : ref x4)/*T:IOut<string?>!*/.P").WithLocation(29, 9), // (30,10): warning CS8619: Nullability of reference types in value of type 'IOut<string>' doesn't match target type 'IOut<string?>'. // (b ? ref y4 : ref x4)/*T:IOut<string>!*/.P.ToString(); // 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y4 : ref x4").WithArguments("IOut<string>", "IOut<string?>").WithLocation(30, 10), // (31,10): warning CS8619: Nullability of reference types in value of type 'IOut<string?>' doesn't match target type 'IOut<string>'. // (b ? ref x4 : ref y4)/*T:IOut<string>!*/.P.ToString(); // 14, 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x4 : ref y4").WithArguments("IOut<string?>", "IOut<string>").WithLocation(31, 10)); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_WithLambdaConversions() { var source = @" using System; class C { Func<bool, T> D1<T>(T t) => k => t; void M1(bool b, string? s) { _ = (b ? D1(s) : k => s) /*T:System.Func<bool, string?>!*/; _ = (b ? k => s : D1(s)) /*T:System.Func<bool, string?>!*/; _ = (true ? D1(s) : k => s) /*T:System.Func<bool, string?>!*/; _ = (true ? k => s : D1(s)) /*T:System.Func<bool, string>!*/; // unexpected type _ = (false ? D1(s) : k => s) /*T:System.Func<bool, string>!*/; // unexpected type _ = (false ? k => s : D1(s)) /*T:System.Func<bool, string?>!*/; _ = (b ? D1(s!) : k => s) /*T:System.Func<bool, string>!*/; // 1, unexpected type _ = (b ? k => s : D1(s!)) /*T:System.Func<bool, string>!*/; // 2, unexpected type _ = (true ? D1(s!) : k => s) /*T:System.Func<bool, string>!*/; // unexpected type _ = (true ? k => s : D1(s!)) /*T:System.Func<bool, string>!*/; // 3, unexpected type _ = (false ? D1(s!) : k => s) /*T:System.Func<bool, string>!*/; // 4, unexpected type _ = (false ? k => s : D1(s!)) /*T:System.Func<bool, string>!*/; // unexpected type _ = (b ? D1(true ? throw null! : s) : k => s) /*T:System.Func<bool, string>!*/; // 5, unexpected type _ = (b ? k => s : D1(true ? throw null! : s)) /*T:System.Func<bool, string>!*/; // 6, unexpected type _ = (true ? D1(true ? throw null! : s) : k => s) /*T:System.Func<bool, string>!*/; // unexpected type _ = (true ? k => s : D1(true ? throw null! : s)) /*T:System.Func<bool, string>!*/; // 7, unexpected type _ = (false ? D1(true ? throw null! : s) : k => s) /*T:System.Func<bool, string>!*/; // 8, unexpected type _ = (false ? k => s : D1(true ? throw null! : s)) /*T:System.Func<bool, string>!*/; // unexpected type } delegate T MyDelegate<T>(bool b); ref MyDelegate<T> D2<T>(T t) => throw null!; void M(bool b, string? s) { _ = (b ? ref D2(s) : ref D2(s!)) /*T:C.MyDelegate<string>!*/; // 9 _ = (b ? ref D2(s!) : ref D2(s)) /*T:C.MyDelegate<string>!*/; // 10 _ = (true ? ref D2(s) : ref D2(s!)) /*T:C.MyDelegate<string>!*/; // 11 _ = (true ? ref D2(s!) : ref D2(s)) /*T:C.MyDelegate<string!>!*/; _ = (false ? ref D2(s) : ref D2(s!)) /*T:C.MyDelegate<string!>!*/; _ = (false ? ref D2(s!) : ref D2(s)) /*T:C.MyDelegate<string>!*/; // 12 } }"; // See https://github.com/dotnet/roslyn/issues/34392 // Best type inference involving lambda conversion should agree with method type inference // Missing diagnostics var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (36,14): warning CS8619: Nullability of reference types in value of type 'C.MyDelegate<string?>' doesn't match target type 'C.MyDelegate<string>'. // _ = (b ? ref D2(s) : ref D2(s!)) /*T:C.MyDelegate<string>!*/; // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref D2(s) : ref D2(s!)").WithArguments("C.MyDelegate<string?>", "C.MyDelegate<string>").WithLocation(36, 14), // (37,14): warning CS8619: Nullability of reference types in value of type 'C.MyDelegate<string>' doesn't match target type 'C.MyDelegate<string?>'. // _ = (b ? ref D2(s!) : ref D2(s)) /*T:C.MyDelegate<string>!*/; // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref D2(s!) : ref D2(s)").WithArguments("C.MyDelegate<string>", "C.MyDelegate<string?>").WithLocation(37, 14), // (38,14): warning CS8619: Nullability of reference types in value of type 'C.MyDelegate<string?>' doesn't match target type 'C.MyDelegate<string>'. // _ = (true ? ref D2(s) : ref D2(s!)) /*T:C.MyDelegate<string>!*/; // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "true ? ref D2(s) : ref D2(s!)").WithArguments("C.MyDelegate<string?>", "C.MyDelegate<string>").WithLocation(38, 14), // (41,14): warning CS8619: Nullability of reference types in value of type 'C.MyDelegate<string>' doesn't match target type 'C.MyDelegate<string?>'. // _ = (false ? ref D2(s!) : ref D2(s)) /*T:C.MyDelegate<string>!*/; // unexpected type Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "false ? ref D2(s!) : ref D2(s)").WithArguments("C.MyDelegate<string>", "C.MyDelegate<string?>").WithLocation(41, 14) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_WithUserDefinedConversion() { var source = @" class D { } class C { public static implicit operator D?(C c) => throw null!; static void M1(bool b, C c, D d) { _ = (b ? c : d) /*T:D?*/; _ = (b ? d : c) /*T:D?*/; _ = (true ? c : d) /*T:D?*/; _ = (true ? d : c) /*T:D!*/; _ = (false ? c : d) /*T:D!*/; _ = (false ? d : c) /*T:D?*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_NestedNullabilityMismatch() { var source = @" class C<T1, T2> { static void M1(bool b, string s, string? s2) { (b ? ref Create(s, s2) : ref Create(s2, s)) /*T:C<string, string>!*/ = null; (b ? ref Create(s2, s) : ref Create(s, s2)) /*T:C<string, string>!*/ = null; } static ref C<U1, U2> Create<U1, U2>(U1 x, U2 y) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,10): warning CS8619: Nullability of reference types in value of type 'C<string, string?>' doesn't match target type 'C<string?, string>'. // (b ? ref Create(s, s2) : ref Create(s2, s)) /*T:C<string, string>!*/ = null; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref Create(s, s2) : ref Create(s2, s)").WithArguments("C<string, string?>", "C<string?, string>").WithLocation(6, 10), // (6,80): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref Create(s, s2) : ref Create(s2, s)) /*T:C<string, string>!*/ = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 80), // (7,10): warning CS8619: Nullability of reference types in value of type 'C<string?, string>' doesn't match target type 'C<string, string?>'. // (b ? ref Create(s2, s) : ref Create(s, s2)) /*T:C<string, string>!*/ = null; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref Create(s2, s) : ref Create(s, s2)").WithArguments("C<string?, string>", "C<string, string?>").WithLocation(7, 10), // (7,80): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref Create(s2, s) : ref Create(s, s2)) /*T:C<string, string>!*/ = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 80) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_WithAlteredStates() { var source = @" class C { static void F1(bool b, ref string? x1, ref string y1) { y1 = null; // 1 (b ? ref x1 : ref x1)/*T:string?*/.ToString(); // 2 (b ? ref x1 : ref y1)/*T:string?*/.ToString(); // 3, 4 (b ? ref y1 : ref x1)/*T:string?*/.ToString(); // 5, 6 (b ? ref y1 : ref y1)/*T:string?*/.ToString(); // 7 x1 = """"; y1 = """"; (b ? ref x1 : ref x1)/*T:string!*/.ToString(); (b ? ref x1 : ref y1)/*T:string!*/.ToString(); // 8 (b ? ref y1 : ref x1)/*T:string!*/.ToString(); // 9 (b ? ref y1 : ref y1)/*T:string!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // y1 = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 14), // (7,10): warning CS8602: Possible dereference of a null reference. // (b ? ref x1 : ref x1)/*T:string?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref x1 : ref x1").WithLocation(7, 10), // (8,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // (b ? ref x1 : ref y1)/*T:string?*/.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x1 : ref y1").WithArguments("string?", "string").WithLocation(8, 10), // (8,10): warning CS8602: Possible dereference of a null reference. // (b ? ref x1 : ref y1)/*T:string?*/.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref x1 : ref y1").WithLocation(8, 10), // (9,10): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // (b ? ref y1 : ref x1)/*T:string?*/.ToString(); // 5, 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y1 : ref x1").WithArguments("string", "string?").WithLocation(9, 10), // (9,10): warning CS8602: Possible dereference of a null reference. // (b ? ref y1 : ref x1)/*T:string?*/.ToString(); // 5, 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref y1 : ref x1").WithLocation(9, 10), // (10,10): warning CS8602: Possible dereference of a null reference. // (b ? ref y1 : ref y1)/*T:string?*/.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref y1 : ref y1").WithLocation(10, 10), // (15,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // (b ? ref x1 : ref y1)/*T:string!*/.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x1 : ref y1").WithArguments("string?", "string").WithLocation(15, 10), // (16,10): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // (b ? ref y1 : ref x1)/*T:string!*/.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y1 : ref x1").WithArguments("string", "string?").WithLocation(16, 10) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_WithUnreachable() { var source = @" class C { static void F1(bool b, string? x1, string y1) { ((b && false) ? x1 : x1)/*T:string?*/.ToString(); // 1 ((b && false) ? x1 : y1)/*T:string!*/.ToString(); ((b && false) ? y1 : x1)/*T:string?*/.ToString(); // 2 ((b && false) ? y1 : y1)/*T:string!*/.ToString(); ((b || true) ? x1 : x1)/*T:string?*/.ToString(); // 3 ((b || true) ? x1 : y1)/*T:string?*/.ToString(); // 4 ((b || true) ? y1 : x1)/*T:string!*/.ToString(); ((b || true) ? y1 : y1)/*T:string!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,10): warning CS8602: Possible dereference of a null reference. // ((b && false) ? x1 : x1)/*T:string?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b && false) ? x1 : x1").WithLocation(6, 10), // (8,10): warning CS8602: Possible dereference of a null reference. // ((b && false) ? y1 : x1)/*T:string?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b && false) ? y1 : x1").WithLocation(8, 10), // (11,10): warning CS8602: Possible dereference of a null reference. // ((b || true) ? x1 : x1)/*T:string?*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b || true) ? x1 : x1").WithLocation(11, 10), // (12,10): warning CS8602: Possible dereference of a null reference. // ((b || true) ? x1 : y1)/*T:string?*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b || true) ? x1 : y1").WithLocation(12, 10) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_SideEffectsInUnreachableBranch() { var source = @" class C { void M1(string? s, string? s2) { s = """"; (false ? ref M3(s = null) : ref s2) = null; s.ToString(); (true ? ref M3(s = null) : ref s2) = null; s.ToString(); // 1 } void M2(string? s, string? s2) { s = """"; (true ? ref s2 : ref M3(s = null)) = null; s.ToString(); (false ? ref s2 : ref M3(s = null)) = null; s.ToString(); // 2 } ref string? M3(string? x) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Possible dereference of a null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 9), // (18,9): warning CS8602: Possible dereference of a null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 9)); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_WithReachableBranchThatThrows() { var source = @" class C { static void F1(bool b) { (b ? M1(false ? 1 : throw new System.Exception()) : M2(2))/*T:string!*/.ToString(); (b ? M1(1) : M2(false ? 2 : throw new System.Exception()))/*T:string?*/.ToString(); // 1 } static string? M1(int i) => throw null!; static string M2(int i) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (7,10): warning CS8602: Possible dereference of a null reference. // (b ? M1(1) : M2(false ? 2 : throw new System.Exception()))/*T:string?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? M1(1) : M2(false ? 2 : throw new System.Exception())").WithLocation(7, 10) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_EndNotReachable() { var source = @" class C { static void F1(bool b) { (true ? M1(false ? 1 : throw new System.Exception()) : M2(2)) /*T:string!*/.ToString(); (false ? M1(1) : M2(false ? 2 : throw new System.Exception())) /*T:string!*/.ToString(); } static string? M1(int i) => throw null!; static string M2(int i) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_WithReachableBranchThatThrows() { var source = @" class C { static void F1(bool b) { (b ? ref M1(false ? 1 : throw new System.Exception()) : ref M2(2)) /*T:string!*/ = null; // 1, 2 (b ? ref M1(1) : ref M2(false ? 2 : throw new System.Exception())) /*T:string?*/ = null; // 3, 4 } static ref string? M1(int i) => throw null!; static ref string M2(int i) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // (b ? ref M1(false ? 1 : throw new System.Exception()) : ref M2(2)) /*T:string!*/ = null; // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref M1(false ? 1 : throw new System.Exception()) : ref M2(2)").WithArguments("string?", "string").WithLocation(6, 10), // (6,92): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref M1(false ? 1 : throw new System.Exception()) : ref M2(2)) /*T:string!*/ = null; // 1, 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 92), // (7,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // (b ? ref M1(1) : ref M2(false ? 2 : throw new System.Exception())) /*T:string?*/ = null; // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref M1(1) : ref M2(false ? 2 : throw new System.Exception())").WithArguments("string?", "string").WithLocation(7, 10), // (7,92): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref M1(1) : ref M2(false ? 2 : throw new System.Exception())) /*T:string?*/ = null; // 3, 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 92) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_EndNotReachable() { var source = @" class C { static void F1(bool b) { (true ? ref M1(false ? 1 : throw new System.Exception()) : ref M2(2)) /*T:string!*/ = null; (false ? ref M1(1) : ref M2(false ? 2 : throw new System.Exception())) /*T:string!*/ = null; } static ref string? M1(int i) => throw null!; static ref string M2(int i) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_WithUnreachable() { var source = @" class C { static void F1(bool b, ref string? x1, ref string y1) { ((b && false) ? ref x1 : ref x1)/*T:string?*/ = null; ((b && false) ? ref x1 : ref y1)/*T:string!*/ = null; // 1, 2 ((b && false) ? ref y1 : ref x1)/*T:string?*/ = null; // 3, 4 ((b && false) ? ref y1 : ref y1)/*T:string!*/ = null; // 5 ((b || true) ? ref x1 : ref x1)/*T:string?*/ = null; ((b || true) ? ref x1 : ref y1)/*T:string?*/ = null; // 6, 7 ((b || true) ? ref y1 : ref x1)/*T:string!*/ = null; // 8, 9 ((b || true) ? ref y1 : ref y1)/*T:string!*/ = null; // 10 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (7,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // ((b && false) ? ref x1 : ref y1)/*T:string!*/ = null; // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(b && false) ? ref x1 : ref y1").WithArguments("string?", "string").WithLocation(7, 10), // (7,57): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((b && false) ? ref x1 : ref y1)/*T:string!*/ = null; // 1, 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 57), // (8,10): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // ((b && false) ? ref y1 : ref x1)/*T:string?*/ = null; // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(b && false) ? ref y1 : ref x1").WithArguments("string", "string?").WithLocation(8, 10), // (8,57): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((b && false) ? ref y1 : ref x1)/*T:string?*/ = null; // 3, 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 57), // (9,57): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((b && false) ? ref y1 : ref y1)/*T:string!*/ = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 57), // (12,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // ((b || true) ? ref x1 : ref y1)/*T:string?*/ = null; // 6, 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(b || true) ? ref x1 : ref y1").WithArguments("string?", "string").WithLocation(12, 10), // (12,56): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((b || true) ? ref x1 : ref y1)/*T:string?*/ = null; // 6, 7 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 56), // (13,10): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // ((b || true) ? ref y1 : ref x1)/*T:string!*/ = null; // 8, 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(b || true) ? ref y1 : ref x1").WithArguments("string", "string?").WithLocation(13, 10), // (13,56): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((b || true) ? ref y1 : ref x1)/*T:string!*/ = null; // 8, 9 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 56), // (14,56): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((b || true) ? ref y1 : ref y1)/*T:string!*/ = null; // 10 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 56) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_WithError() { var source = @" class C { static void F1(bool b, ref string? x1) { (b ? ref x1 : ref error)/*T:!*/.ToString(); (b ? ref x1 : ref error)/*T:!*/.ToString(); (b ? ref error : ref x1)/*T:!*/.ToString(); (b ? ref error : ref error)/*T:!*/.ToString(); x1 = """"; (b ? ref x1 : ref error)/*T:!*/.ToString(); (b ? ref x1 : ref error)/*T:!*/.ToString(); (b ? ref error : ref x1)/*T:!*/.ToString(); (b ? ref error : ref error)/*T:!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref x1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(6, 27), // (7,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref x1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(7, 27), // (8,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref x1)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 18), // (9,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(9, 18), // (9,30): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(9, 30), // (12,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref x1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(12, 27), // (13,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref x1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(13, 27), // (14,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref x1)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(14, 18), // (15,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(15, 18), // (15,30): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(15, 30) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_WithError_Nested() { var source = @" class C<T> { static void F1(bool b, ref C<string?> x1, ref C<string> y1) { (b ? ref x1 : ref error)/*T:!*/.ToString(); (b ? ref x1 : ref error)/*T:!*/.ToString(); (b ? ref error : ref x1)/*T:!*/.ToString(); (b ? ref error : ref error)/*T:!*/.ToString(); (b ? ref y1 : ref error)/*T:!*/.ToString(); (b ? ref y1 : ref error)/*T:!*/.ToString(); (b ? ref error : ref y1)/*T:!*/.ToString(); (b ? ref error : ref error)/*T:!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref x1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(6, 27), // (7,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref x1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(7, 27), // (8,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref x1)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 18), // (9,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(9, 18), // (9,30): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(9, 30), // (11,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref y1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(11, 27), // (12,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref y1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(12, 27), // (13,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref y1)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(13, 18), // (14,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(14, 18), // (14,30): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(14, 30) ); } [Fact] public void ConditionalOperator_15() { // We likely shouldn't be warning on the x[0] access, as code is an error. However, we currently do // because of fallout from https://github.com/dotnet/roslyn/issues/34158: when we calculate the // type of new[] { x }, the type of the BoundLocal x is ErrorType var, but the type of the local // symbol is ErrorType var[]. VisitLocal prefers the type of the BoundLocal, and so the // new[] { x } expression is calculated to have a final type of ErrorType var[]. The default is // target typed to ErrorType var[] as well, and the logic in VisitConditionalOperator therefore // uses that type as the final type of the expression. This calculation succeeded, so that result // is stored as the current nullability of x, causing us to warn on the subsequent line. var source = @"class Program { static void F(bool b) { var x = b ? new[] { x } : default; x[0].ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,29): error CS0841: Cannot use local variable 'x' before it is declared // var x = b ? new[] { x } : default; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(5, 29), // (6,9): warning CS8602: Dereference of a possibly null reference. // x[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9)); } [Fact] public void ConditionalOperator_16() { var source = @"class Program { static bool F(object? x) { return true; } static void F1(bool b, bool c, object x1, object? y1) { if (b ? c && F(x1 = y1) : true) // 1 { x1.ToString(); // 2 } } static void F2(bool b, bool c, object x2, object? y2) { if (b ? true : c && F(x2 = y2)) // 3 { x2.ToString(); // 4 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,29): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (b ? c && F(x1 = y1) : true) // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(9, 29), // (11,13): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 13), // (16,36): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (b ? true : c && F(x2 = y2)) // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2").WithLocation(16, 36), // (18,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(18, 13)); } [Fact] public void ConditionalOperator_17() { var source = @"class Program { static void F(bool x, bool y, bool z, bool? w) { object o; o = x ? y && z : w; // 1 o = true ? y && z : w; o = false ? w : y && z; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = x ? y && z : w; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x ? y && z : w").WithLocation(6, 13)); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_18() { var comp = CreateCompilation(@" using System; class C { public void M(bool b, Action? action) { _ = b ? () => { action(); } : action = new Action(() => {}); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,25): warning CS8602: Dereference of a possibly null reference. // _ = b ? () => { action(); } Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "action").WithLocation(6, 25) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_01() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { string? s = null; Func<string> a = b ? () => s.ToString() : () => s?.ToString(); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,36): warning CS8602: Dereference of a possibly null reference. // Func<string> a = b ? () => s.ToString() : () => s?.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 36), // (8,57): warning CS8603: Possible null reference return. // Func<string> a = b ? () => s.ToString() : () => s?.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s?.ToString()").WithLocation(8, 57) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_02() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { string? s = null; object a = (Func<string>)(b ? () => s.ToString() : () => s?.ToString()); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,45): warning CS8602: Dereference of a possibly null reference. // object a = (Func<string>)(b ? () => s.ToString() : () => s?.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 45), // (8,66): warning CS8603: Possible null reference return. // object a = (Func<string>)(b ? () => s.ToString() : () => s?.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s?.ToString()").WithLocation(8, 66) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_03() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { Func<string>? s = () => """"; Func<object>? o = b ? () => s() : s = null; } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_04() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { Func<string>? s = () => """"; Func<object>? o = b ? s = null : () => s(); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_05() { var comp = CreateCompilation(@" class C { static void M(bool b) { string? s = null; object a = b ? () => s.ToString() : () => s?.ToString(); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,30): warning CS8602: Dereference of a possibly null reference. // object a = b ? () => s.ToString() : () => s?.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 30) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_06() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { string? s1 = null; string? s2 = """"; M1(s2, b ? () => s1.ToString() : () => s1?.ToString()).ToString(); } static T M1<T>(T t1, Func<T> t2) => t1; } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,26): warning CS8602: Dereference of a possibly null reference. // M1(s2, b ? () => s1.ToString() : () => s1?.ToString()).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 26), // (9,48): warning CS8603: Possible null reference return. // M1(s2, b ? () => s1.ToString() : () => s1?.ToString()).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s1?.ToString()").WithLocation(9, 48) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_07() { var comp = CreateCompilation(@" interface I {} class A : I {} class B : I {} class C { static void M(I i, A a, B? b, bool @bool) { M1(i, @bool ? a : b).ToString(); } static T M1<T>(T t1, T t2) => t1; } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,15): warning CS8604: Possible null reference argument for parameter 't2' in 'I C.M1<I>(I t1, I t2)'. // M1(i, @bool ? a : b).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "@bool ? a : b").WithArguments("t2", "I C.M1<I>(I t1, I t2)").WithLocation(9, 15) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461"), WorkItem(49735, "https://github.com/dotnet/roslyn/issues/49735")] public void ConditionalOperator_TargetTyped_08() { var comp = CreateCompilation(@" C? c = """".Length > 0 ? new A() : new B(); c.ToString(); class C { } class A { public static implicit operator C?(A a) => null; } class B { public static implicit operator C?(B b) => null; } ", options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (3,1): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(3, 1) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461"), WorkItem(49735, "https://github.com/dotnet/roslyn/issues/49735")] public void ConditionalOperator_TargetTyped_09() { var comp = CreateCompilation(@" C? c = true ? new A() : new B(); c.ToString(); class C { } class A { public static implicit operator C(A a) => new C(); } class B { public static implicit operator C?(B b) => null; } ", options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461"), WorkItem(49735, "https://github.com/dotnet/roslyn/issues/49735")] public void ConditionalOperator_TargetTyped_10() { var comp = CreateCompilation(@" C? c = false ? new A() : new B(); c.ToString(); class C { } class A { public static implicit operator C?(A a) => null; } class B { public static implicit operator C(B b) => new C(); } ", options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_ConditionalOperator_WithoutType_WithNullLiterals() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { if (b) return b ? null : null; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nullNode = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("null", nullNode.ToString()); Assert.Null(model.GetTypeInfo(nullNode).Type); Assert.Equal("System.Object?", model.GetTypeInfo(nullNode).ConvertedType.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model.GetTypeInfo(nullNode).ConvertedNullability.FlowState); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( // (9,24): warning CS8603: Possible null reference return. // return b ? null : null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? null : null").WithLocation(9, 24) ); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ArrayTypeInference_ConditionalOperator_WithoutType_WithNullLiterals() { var source = @"class Program { static void F(bool b) { var x = new[] { b ? null : null, new object() }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nullNode = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("null", nullNode.ToString()); Assert.Null(model.GetTypeInfo(nullNode).Type); Assert.Equal("System.Object?", model.GetTypeInfo(nullNode).ConvertedType.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model.GetTypeInfo(nullNode).ConvertedNullability.FlowState); var invocationNode = tree.GetRoot().DescendantNodes().OfType<ImplicitArrayCreationExpressionSyntax>().Single(); Assert.Equal("System.Object?[]", model.GetTypeInfo(invocationNode).Type.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_ConditionalOperator_WithoutType_WithDefaultLiterals() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F<U>(bool b) where U : new() { M(() => { if (b) return b ? default : default; else return new U(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var defaultNode = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", defaultNode.ToString()); Assert.Equal("U?", model.GetTypeInfo(defaultNode).Type.ToTestDisplayString()); Assert.Equal("U?", model.GetTypeInfo(defaultNode).ConvertedType.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model.GetTypeInfo(defaultNode).ConvertedNullability.FlowState); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<U>(System.Func<U> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( // (9,24): warning CS8603: Possible null reference return. // return b ? default : default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? default : default").WithLocation(9, 24) ); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_ConditionalOperator_WithoutType_WithDefaultLiterals_StructType() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F<U>(bool b) where U : struct { M(() => { if (b) return b ? default : default; else return new U(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var defaultNode = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", defaultNode.ToString()); Assert.Equal("U", model.GetTypeInfo(defaultNode).Type.ToTestDisplayString()); Assert.Equal("U", model.GetTypeInfo(defaultNode).ConvertedType.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableFlowState.NotNull, model.GetTypeInfo(defaultNode).ConvertedNullability.FlowState); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<U>(System.Func<U> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_ConditionalOperator_WithoutType_WithMaybeNullVariables() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { Program? x = null; string? y = null; if (b) return b ? x : y; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( // (11,24): warning CS8603: Possible null reference return. // return b ? x : y; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? x : y").WithLocation(11, 24) ); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_ConditionalOperator_WithoutType_WithNotNullVariables() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { Program? x = new(); string? y = string.Empty; if (b) return b ? x : y; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954"), WorkItem(51403, "https://github.com/dotnet/roslyn/issues/51403")] public void ReturningValues_ConditionalOperator_WithoutType_WithMaybeNullVariables_UserDefinedConversion() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool @bool, A a, B? b, C? c) { M(() => { if (@bool) return @bool ? b : c; else return a; }); } } class A {} class B { public static implicit operator A(B? b) => new A(); } class C { public static implicit operator A(C? c) => new A(); }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<A>(System.Func<A> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_SwitchExpression_WithoutType_NullLiteral() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { if (b) return b switch { _ => null }; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nullNode = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("null", nullNode.ToString()); Assert.Null(model.GetTypeInfo(nullNode).Type); Assert.Equal("System.Object?", model.GetTypeInfo(nullNode).ConvertedType.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model.GetTypeInfo(nullNode).ConvertedNullability.FlowState); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( // (9,24): warning CS8603: Possible null reference return. // return b switch { _ => null }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { _ => null }").WithLocation(9, 24) ); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_SwitchExpression_WithoutType_WithMaybeNullVariables() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { Program? x = null; string? y = null; if (b) return b switch { true => x, _ => y }; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( // (11,24): warning CS8603: Possible null reference return. // return b switch { true => x, _ => y }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { true => x, _ => y }").WithLocation(11, 24) ); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_SwitchExpression_WithoutType_WithNotNullVariables() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { Program? x = new(); string? y = string.Empty; if (b) return b switch { true => x, _ => y }; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954"), WorkItem(51403, "https://github.com/dotnet/roslyn/issues/51403")] public void ReturningValues_SwitchExpression_WithoutType_WithMaybeNullVariables_UserDefinedConversion() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool @bool, A a, B? b, C? c) { M(() => { if (@bool) return @bool switch { true => b, false => c }; else return a; }); } } class A {} class B { public static implicit operator A(B? b) => new A(); } class C { public static implicit operator A(C? c) => new A(); }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<A>(System.Func<A> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_WithoutType_New() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { if (b) return new(); else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var newNode = tree.GetRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().First(); Assert.Equal("new()", newNode.ToString()); Assert.Equal("System.Object", model.GetTypeInfo(newNode).Type.ToTestDisplayString()); Assert.Equal("System.Object", model.GetTypeInfo(newNode).ConvertedType.ToTestDisplayString()); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_WithoutType_NewWithArguments() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { if (b) return new(null); else return new Program(string.Empty); }); } Program(string s) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var newNode = tree.GetRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().First(); Assert.Equal("new(null)", newNode.ToString()); Assert.Equal("Program", model.GetTypeInfo(newNode).Type.ToTestDisplayString()); Assert.Equal("Program", model.GetTypeInfo(newNode).ConvertedType.ToTestDisplayString()); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<Program>(System.Func<Program> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( // (10,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // return new(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 28) ); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_WithoutType() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { if (b) return null; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nullNode = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("null", nullNode.ToString()); Assert.Null(model.GetTypeInfo(nullNode).Type); Assert.Equal("System.Object?", model.GetTypeInfo(nullNode).ConvertedType.ToTestDisplayString()); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object?>(System.Func<System.Object?> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(44339, "https://github.com/dotnet/roslyn/issues/44339")] public void TypeInference_LambdasWithNullsAndDefaults() { var source = @" #nullable enable public class C<T1, T2> { public void M1(bool b) { var map = new C<string, string>(); map.GetOrAdd("""", _ => default); // 1 map.GetOrAdd("""", _ => null); // 2 map.GetOrAdd("""", _ => { if (b) return default; return """"; }); // 3 map.GetOrAdd("""", _ => { if (b) return null; return """"; }); // 4 map.GetOrAdd("""", _ => { if (b) return """"; return null; }); // 5 } } public static class Extensions { public static V GetOrAdd<K, V>(this C<K, V> dictionary, K key, System.Func<K, V> function) => throw null!; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,31): warning CS8603: Possible null reference return. // map.GetOrAdd("", _ => default); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(10, 31), // (11,31): warning CS8603: Possible null reference return. // map.GetOrAdd("", _ => null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(11, 31), // (13,9): warning CS8620: Argument of type 'C<string, string>' cannot be used for parameter 'dictionary' of type 'C<string, string?>' in 'string? Extensions.GetOrAdd<string, string?>(C<string, string?> dictionary, string key, Func<string, string?> function)' due to differences in the nullability of reference types. // map.GetOrAdd("", _ => { if (b) return default; return ""; }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "map").WithArguments("C<string, string>", "C<string, string?>", "dictionary", "string? Extensions.GetOrAdd<string, string?>(C<string, string?> dictionary, string key, Func<string, string?> function)").WithLocation(13, 9), // (14,9): warning CS8620: Argument of type 'C<string, string>' cannot be used for parameter 'dictionary' of type 'C<string, string?>' in 'string? Extensions.GetOrAdd<string, string?>(C<string, string?> dictionary, string key, Func<string, string?> function)' due to differences in the nullability of reference types. // map.GetOrAdd("", _ => { if (b) return null; return ""; }); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "map").WithArguments("C<string, string>", "C<string, string?>", "dictionary", "string? Extensions.GetOrAdd<string, string?>(C<string, string?> dictionary, string key, Func<string, string?> function)").WithLocation(14, 9), // (15,9): warning CS8620: Argument of type 'C<string, string>' cannot be used for parameter 'dictionary' of type 'C<string, string?>' in 'string? Extensions.GetOrAdd<string, string?>(C<string, string?> dictionary, string key, Func<string, string?> function)' due to differences in the nullability of reference types. // map.GetOrAdd("", _ => { if (b) return ""; return null; }); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "map").WithArguments("C<string, string>", "C<string, string?>", "dictionary", "string? Extensions.GetOrAdd<string, string?>(C<string, string?> dictionary, string key, Func<string, string?> function)").WithLocation(15, 9) ); } [Fact, WorkItem(43536, "https://github.com/dotnet/roslyn/issues/43536")] public void TypeInference_StringAndNullOrDefault() { var source = @" #nullable enable class C { void M(string s) { Infer(s, default); Infer(s, null); } T Infer<T>(T t1, T t2) => t1 ?? t2; } "; // We're expecting the same inference and warnings for both invocations // Tracked by issue https://github.com/dotnet/roslyn/issues/43536 var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("System.String? C.Infer<System.String?>(System.String? t1, System.String? t2)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); var invocationNode2 = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Last(); Assert.Equal("System.String C.Infer<System.String>(System.String t1, System.String t2)", model.GetSymbolInfo(invocationNode2).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( // (9,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // Infer(s, null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 18) ); } [Fact] public void ConditionalOperator_WithoutType_Lambda() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b, System.Action a) { M(() => { if (b) return () => { }; else return a; }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var lambdaNode = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Last(); Assert.Equal("() => { }", lambdaNode.ToString()); Assert.Null(model.GetTypeInfo(lambdaNode).Type); Assert.Equal("System.Action", model.GetTypeInfo(lambdaNode).ConvertedType.ToTestDisplayString()); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Action>(System.Func<System.Action> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact] public void ConditionalOperator_TopLevelNullability() { var source = @"class C { static void F(bool b, object? x, object y) { object? o; o = (b ? x : x)/*T:object?*/; o = (b ? x : y)/*T:object?*/; o = (b ? y : x)/*T:object?*/; o = (b ? y : y)/*T:object!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] [Fact] public void ConditionalOperator_NestedNullability_Invariant() { var source0 = @"public class A { public static B<object> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F(bool b, B<object?> x, B<object> y) { var z = A.F/*T:B<object>!*/; object o; o = (b ? x : x)/*T:B<object?>!*/; o = (b ? x : y)/*T:B<object!>!*/; // 1 o = (b ? x : z)/*T:B<object?>!*/; o = (b ? y : x)/*T:B<object!>!*/; // 2 o = (b ? y : y)/*T:B<object!>!*/; o = (b ? y : z)/*T:B<object!>!*/; o = (b ? z : x)/*T:B<object?>!*/; o = (b ? z : y)/*T:B<object!>!*/; o = (b ? z : z)/*T:B<object>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,18): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // o = (b ? x : y)/*T:B<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(8, 18), // (10,22): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // o = (b ? y : x)/*T:B<object!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(10, 22) ); comp.VerifyTypes(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void ConditionalOperator_NestedNullability_Variant() { var source0 = @"public class A { public static I<object> F; public static IIn<object> FIn; public static IOut<object> FOut; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F1(bool b, I<object> x, I<object?> y) { var z = A.F/*T:I<object>!*/; object o; o = (b ? x : x)/*T:I<object!>!*/; o = (b ? x : y)/*T:I<object!>!*/; // 1 o = (b ? x : z)/*T:I<object!>!*/; o = (b ? y : x)/*T:I<object!>!*/; // 2 o = (b ? y : y)/*T:I<object?>!*/; o = (b ? y : z)/*T:I<object?>!*/; o = (b ? z : x)/*T:I<object!>!*/; o = (b ? z : y)/*T:I<object?>!*/; o = (b ? z : z)/*T:I<object>!*/; } static void F2(bool b, IIn<object> x, IIn<object?> y) { var z = A.FIn/*T:IIn<object>!*/; object o; o = (b ? x : x)/*T:IIn<object!>!*/; o = (b ? x : y)/*T:IIn<object!>!*/; o = (b ? x : z)/*T:IIn<object!>!*/; o = (b ? y : x)/*T:IIn<object!>!*/; o = (b ? y : y)/*T:IIn<object?>!*/; o = (b ? y : z)/*T:IIn<object>!*/; o = (b ? z : x)/*T:IIn<object!>!*/; o = (b ? z : y)/*T:IIn<object>!*/; o = (b ? z : z)/*T:IIn<object>!*/; } static void F3(bool b, IOut<object> x, IOut<object?> y) { var z = A.FOut/*T:IOut<object>!*/; object o; o = (b ? x : x)/*T:IOut<object!>!*/; o = (b ? x : y)/*T:IOut<object?>!*/; o = (b ? x : z)/*T:IOut<object>!*/; o = (b ? y : x)/*T:IOut<object?>!*/; o = (b ? y : y)/*T:IOut<object?>!*/; o = (b ? y : z)/*T:IOut<object?>!*/; o = (b ? z : x)/*T:IOut<object>!*/; o = (b ? z : y)/*T:IOut<object?>!*/; o = (b ? z : z)/*T:IOut<object>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,22): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // o = (b ? x : y)/*T:I<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(8, 22), // (10,18): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // o = (b ? y : x)/*T:I<object!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(10, 18) ); comp.VerifyTypes(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void ConditionalOperator_NestedNullability_VariantAndInvariant() { var source0 = @"public class A { public static IIn<object, string> F1; public static IOut<object, string> F2; } public interface IIn<in T, U> { } public interface IOut<T, out U> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F1(bool b, IIn<object, string> x1, IIn<object?, string?> y1) { var z1 = A.F1/*T:IIn<object, string>!*/; object o; o = (b ? x1 : x1)/*T:IIn<object!, string!>!*/; o = (b ? x1 : y1)/*T:IIn<object!, string!>!*/; // 1 o = (b ? x1 : z1)/*T:IIn<object!, string!>!*/; o = (b ? y1 : x1)/*T:IIn<object!, string!>!*/; // 2 o = (b ? y1 : y1)/*T:IIn<object?, string?>!*/; o = (b ? y1 : z1)/*T:IIn<object, string?>!*/; o = (b ? z1 : x1)/*T:IIn<object!, string!>!*/; o = (b ? z1 : y1)/*T:IIn<object, string?>!*/; o = (b ? z1 : z1)/*T:IIn<object, string>!*/; } static void F2(bool b, IOut<object, string> x2, IOut<object?, string?> y2) { var z2 = A.F2/*T:IOut<object, string>!*/; object o; o = (b ? x2 : x2)/*T:IOut<object!, string!>!*/; o = (b ? x2 : y2)/*T:IOut<object!, string?>!*/; // 3 o = (b ? x2 : z2)/*T:IOut<object!, string>!*/; o = (b ? y2 : x2)/*T:IOut<object!, string?>!*/; // 4 o = (b ? y2 : y2)/*T:IOut<object?, string?>!*/; o = (b ? y2 : z2)/*T:IOut<object?, string?>!*/; o = (b ? z2 : x2)/*T:IOut<object!, string>!*/; o = (b ? z2 : y2)/*T:IOut<object?, string?>!*/; o = (b ? z2 : z2)/*T:IOut<object, string>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,23): warning CS8619: Nullability of reference types in value of type 'IIn<object?, string?>' doesn't match target type 'IIn<object, string>'. // o = (b ? x1 : y1)/*T:IIn<object!, string!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("IIn<object?, string?>", "IIn<object, string>").WithLocation(8, 23), // (10,18): warning CS8619: Nullability of reference types in value of type 'IIn<object?, string?>' doesn't match target type 'IIn<object, string>'. // o = (b ? y1 : x1)/*T:IIn<object!, string!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("IIn<object?, string?>", "IIn<object, string>").WithLocation(10, 18), // (22,23): warning CS8619: Nullability of reference types in value of type 'IOut<object?, string?>' doesn't match target type 'IOut<object, string?>'. // o = (b ? x2 : y2)/*T:IOut<object!, string?>!*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y2").WithArguments("IOut<object?, string?>", "IOut<object, string?>").WithLocation(22, 23), // (24,18): warning CS8619: Nullability of reference types in value of type 'IOut<object?, string?>' doesn't match target type 'IOut<object, string?>'. // o = (b ? y2 : x2)/*T:IOut<object!, string?>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y2").WithArguments("IOut<object?, string?>", "IOut<object, string?>").WithLocation(24, 18) ); comp.VerifyTypes(); } [Fact] public void ConditionalOperator_NestedNullability_Tuples() { var source0 = @"public class A { public static I<object> F; } public interface I<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @" class C { static void F1(bool b, object x1, object? y1) { object o; o = (b ? (x1, x1) : (x1, y1))/*T:(object!, object?)*/; o = (b ? (x1, y1) : (y1, y1))/*T:(object?, object?)*/; } static void F2(bool b, I<object> x2, I<object?> y2) { var z2 = A.F/*T:I<object>!*/; object o; o = (b ? (x2, x2) : (x2, y2))/*T:(I<object!>!, I<object!>!)*/; o = (b ? (z2, x2) : (x2, x2))/*T:(I<object!>!, I<object!>!)*/; o = (b ? (y2, y2) : (y2, z2))/*T:(I<object?>!, I<object?>!)*/; o = (b ? (x2, y2) : (y2, y2))/*T:(I<object!>!, I<object?>!)*/; o = (b ? (z2, z2) : (z2, x2))/*T:(I<object>!, I<object!>!)*/; o = (b ? (y2, z2) : (z2, z2))/*T:(I<object?>!, I<object>!)*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (14,29): warning CS8619: Nullability of reference types in value of type '(I<object> x2, I<object?> y2)' doesn't match target type '(I<object>, I<object>)'. // o = (b ? (x2, x2) : (x2, y2))/*T:(I<object!>!, I<object!>!)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x2, y2)").WithArguments("(I<object> x2, I<object?> y2)", "(I<object>, I<object>)").WithLocation(14, 29), // (17,29): warning CS8619: Nullability of reference types in value of type '(I<object?>, I<object?>)' doesn't match target type '(I<object>, I<object?>)'. // o = (b ? (x2, y2) : (y2, y2))/*T:(I<object!>!, I<object?>!)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(y2, y2)").WithArguments("(I<object?>, I<object?>)", "(I<object>, I<object?>)").WithLocation(17, 29) ); comp.VerifyTypes(); } [WorkItem(30432, "https://github.com/dotnet/roslyn/issues/30432")] [Fact] public void ConditionalOperator_TopLevelNullability_Ref() { var source0 = @"public class A { public static object F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F(bool b, object? x, object y) { ref var xx = ref b ? ref x : ref x; ref var xy = ref b ? ref x : ref y; // 1 ref var xz = ref b ? ref x : ref A.F; ref var yx = ref b ? ref y : ref x; // 2 ref var yy = ref b ? ref y : ref y; ref var yz = ref b ? ref y : ref A.F; ref var zx = ref b ? ref A.F : ref x; ref var zy = ref b ? ref A.F : ref y; ref var zz = ref b ? ref A.F : ref A.F; } }"; var comp = CreateCompilation(source, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (6,26): warning CS8619: Nullability of reference types in value of type 'object?' doesn't match target type 'object'. // ref var xy = ref b ? ref x : ref y; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x : ref y").WithArguments("object?", "object").WithLocation(6, 26), // (8,26): warning CS8619: Nullability of reference types in value of type 'object' doesn't match target type 'object?'. // ref var yx = ref b ? ref y : ref x; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y : ref x").WithArguments("object", "object?").WithLocation(8, 26) ); } [WorkItem(30432, "https://github.com/dotnet/roslyn/issues/30432")] [Fact] public void ConditionalOperator_NestedNullability_Ref() { var source0 = @"public class A { public static I<object> IOblivious; public static IIn<object> IInOblivious; public static IOut<object> IOutOblivious; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F1(bool b, I<object> x1, I<object?> y1) { var z1 = A.IOblivious/*T:I<object>!*/; ref var xx = ref b ? ref x1 : ref x1; ref var xy = ref b ? ref x1 : ref y1; // 1 ref var xz = ref b ? ref x1 : ref z1; // 2 ref var yx = ref b ? ref y1 : ref x1; // 3 ref var yy = ref b ? ref y1 : ref y1; ref var yz = ref b ? ref y1 : ref z1; // 4 ref var zx = ref b ? ref z1 : ref x1; // 5 ref var zy = ref b ? ref z1 : ref y1; // 6 ref var zz = ref b ? ref z1 : ref z1; } static void F2(bool b, IIn<object> x2, IIn<object?> y2) { var z2 = A.IInOblivious/*T:IIn<object>!*/; ref var xx = ref b ? ref x2 : ref x2; ref var xy = ref b ? ref x2 : ref y2; // 7 ref var xz = ref b ? ref x2 : ref z2; // 8 ref var yx = ref b ? ref y2 : ref x2; // 9 ref var yy = ref b ? ref y2 : ref y2; ref var yz = ref b ? ref y2 : ref z2; // 10 ref var zx = ref b ? ref z2 : ref x2; // 11 ref var zy = ref b ? ref z2 : ref y2; // 12 ref var zz = ref b ? ref z2 : ref z2; } static void F3(bool b, IOut<object> x3, IOut<object?> y3) { var z3 = A.IOutOblivious/*T:IOut<object>!*/; ref var xx = ref b ? ref x3 : ref x3; ref var xy = ref b ? ref x3 : ref y3; // 13 ref var xz = ref b ? ref x3 : ref z3; // 14 ref var yx = ref b ? ref y3 : ref x3; // 15 ref var yy = ref b ? ref y3 : ref y3; // 16 ref var yz = ref b ? ref y3 : ref z3; // 17 ref var zx = ref b ? ref z3 : ref x3; // 18 ref var zy = ref b ? ref z3 : ref y3; // 19 ref var zz = ref b ? ref z3 : ref z3; } }"; var comp = CreateCompilation(source, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (7,26): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // ref var xy = ref b ? ref x1 : ref y1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x1 : ref y1").WithArguments("I<object>", "I<object?>").WithLocation(7, 26), // (8,26): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object>?'. // ref var xz = ref b ? ref x1 : ref z1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x1 : ref z1").WithArguments("I<object>", "I<object>?").WithLocation(8, 26), // (9,26): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // ref var yx = ref b ? ref y1 : ref x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y1 : ref x1").WithArguments("I<object?>", "I<object>").WithLocation(9, 26), // (11,26): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>?'. // ref var yz = ref b ? ref y1 : ref z1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y1 : ref z1").WithArguments("I<object?>", "I<object>?").WithLocation(11, 26), // (12,26): warning CS8619: Nullability of reference types in value of type 'I<object>?' doesn't match target type 'I<object>'. // ref var zx = ref b ? ref z1 : ref x1; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref z1 : ref x1").WithArguments("I<object>?", "I<object>").WithLocation(12, 26), // (13,26): warning CS8619: Nullability of reference types in value of type 'I<object>?' doesn't match target type 'I<object?>'. // ref var zy = ref b ? ref z1 : ref y1; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref z1 : ref y1").WithArguments("I<object>?", "I<object?>").WithLocation(13, 26), // (20,26): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // ref var xy = ref b ? ref x2 : ref y2; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x2 : ref y2").WithArguments("IIn<object>", "IIn<object?>").WithLocation(20, 26), // (21,26): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object>?'. // ref var xz = ref b ? ref x2 : ref z2; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x2 : ref z2").WithArguments("IIn<object>", "IIn<object>?").WithLocation(21, 26), // (22,26): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'IIn<object>'. // ref var yx = ref b ? ref y2 : ref x2; // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y2 : ref x2").WithArguments("IIn<object?>", "IIn<object>").WithLocation(22, 26), // (24,26): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'IIn<object>?'. // ref var yz = ref b ? ref y2 : ref z2; // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y2 : ref z2").WithArguments("IIn<object?>", "IIn<object>?").WithLocation(24, 26), // (25,26): warning CS8619: Nullability of reference types in value of type 'IIn<object>?' doesn't match target type 'IIn<object>'. // ref var zx = ref b ? ref z2 : ref x2; // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref z2 : ref x2").WithArguments("IIn<object>?", "IIn<object>").WithLocation(25, 26), // (26,26): warning CS8619: Nullability of reference types in value of type 'IIn<object>?' doesn't match target type 'IIn<object?>'. // ref var zy = ref b ? ref z2 : ref y2; // 12 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref z2 : ref y2").WithArguments("IIn<object>?", "IIn<object?>").WithLocation(26, 26), // (33,26): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'IOut<object?>'. // ref var xy = ref b ? ref x3 : ref y3; // 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x3 : ref y3").WithArguments("IOut<object>", "IOut<object?>").WithLocation(33, 26), // (34,26): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'IOut<object>?'. // ref var xz = ref b ? ref x3 : ref z3; // 14 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x3 : ref z3").WithArguments("IOut<object>", "IOut<object>?").WithLocation(34, 26), // (35,26): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // ref var yx = ref b ? ref y3 : ref x3; // 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y3 : ref x3").WithArguments("IOut<object?>", "IOut<object>").WithLocation(35, 26), // (37,26): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>?'. // ref var yz = ref b ? ref y3 : ref z3; // 17 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y3 : ref z3").WithArguments("IOut<object?>", "IOut<object>?").WithLocation(37, 26), // (38,26): warning CS8619: Nullability of reference types in value of type 'IOut<object>?' doesn't match target type 'IOut<object>'. // ref var zx = ref b ? ref z3 : ref x3; // 18 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref z3 : ref x3").WithArguments("IOut<object>?", "IOut<object>").WithLocation(38, 26), // (39,26): warning CS8619: Nullability of reference types in value of type 'IOut<object>?' doesn't match target type 'IOut<object?>'. // ref var zy = ref b ? ref z3 : ref y3; // 19 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref z3 : ref y3").WithArguments("IOut<object>?", "IOut<object?>").WithLocation(39, 26) ); comp.VerifyTypes(); } [Fact, WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_AssigningToRefConditional() { var source0 = @"public class A { public static string F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var comp = CreateCompilation(@" class C { void M(bool c, ref string x, ref string? y) { (c ? ref x : ref y) = null; // 1, 2 } void M2(bool c, ref string x, ref string? y) { (c ? ref y : ref x) = null; // 3, 4 } void M3(bool c, ref string x, ref string? y) { (c ? ref x : ref A.F) = null; // 5 (c ? ref y : ref A.F) = null; } void M4(bool c, ref string x, ref string? y) { (c ? ref A.F : ref x) = null; // 6 (c ? ref A.F : ref y) = null; } }", options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (6,10): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // (c ? ref x : ref y) = null; // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? ref x : ref y").WithArguments("string", "string?").WithLocation(6, 10), // (6,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // (c ? ref x : ref y) = null; // 1, 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 31), // (10,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // (c ? ref y : ref x) = null; // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? ref y : ref x").WithArguments("string?", "string").WithLocation(10, 10), // (10,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // (c ? ref y : ref x) = null; // 3, 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 31), // (14,33): warning CS8625: Cannot convert null literal to non-nullable reference type. // (c ? ref x : ref A.F) = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 33), // (19,33): warning CS8625: Cannot convert null literal to non-nullable reference type. // (c ? ref A.F : ref x) = null; // 6 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 33) ); } [Fact] public void IdentityConversion_ConditionalOperator() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(bool c, I<object> x, I<object?> y) { I<object> a; a = c ? x : y; a = false ? x : y; a = true ? x : y; // ok I<object?> b; b = c ? x : y; b = false ? x : y; b = true ? x : y; } static void F(bool c, IIn<object> x, IIn<object?> y) { IIn<object> a; a = c ? x : y; a = false ? x : y; a = true ? x : y; IIn<object?> b; b = c ? x : y; b = false ? x : y; b = true ? x : y; } static void F(bool c, IOut<object> x, IOut<object?> y) { IOut<object> a; a = c ? x : y; a = false ? x : y; a = true ? x : y; IOut<object?> b; b = c ? x : y; b = false ? x : y; b = true ? x : y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,21): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // a = c ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(9, 21), // (10,25): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // a = false ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(10, 25), // (13,13): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // b = c ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x : y").WithArguments("I<object>", "I<object?>").WithLocation(13, 13), // (13,21): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // b = c ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(13, 21), // (14,13): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // b = false ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "false ? x : y").WithArguments("I<object>", "I<object?>").WithLocation(14, 13), // (14,25): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // b = false ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(14, 25), // (15,13): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // b = true ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "true ? x : y").WithArguments("I<object>", "I<object?>").WithLocation(15, 13), // (24,13): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // b = c ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x : y").WithArguments("IIn<object>", "IIn<object?>").WithLocation(24, 13), // (25,13): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // b = false ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "false ? x : y").WithArguments("IIn<object>", "IIn<object?>").WithLocation(25, 13), // (26,13): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // b = true ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "true ? x : y").WithArguments("IIn<object>", "IIn<object?>").WithLocation(26, 13), // (31,13): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // a = c ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x : y").WithArguments("IOut<object?>", "IOut<object>").WithLocation(31, 13), // (32,13): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // a = false ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "false ? x : y").WithArguments("IOut<object?>", "IOut<object>").WithLocation(32, 13), // (33,13): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // a = true ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "true ? x : y").WithArguments("IOut<object?>", "IOut<object>").WithLocation(33, 13)); } [Fact] public void NullCoalescingOperator_01() { var source = @"class C { static void F(object? x, object? y) { var z = x ?? y; z.ToString(); if (y == null) return; var w = x ?? y; w.ToString(); var v = null ?? x; v.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(6, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // v.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v").WithLocation(11, 9)); } [Fact] public void NullCoalescingOperator_02() { var source = @"class C { static void F(int i, object? x, object? y) { switch (i) { case 1: (x ?? y).ToString(); // 1 break; case 2: if (y != null) (x ?? y).ToString(); break; case 3: if (y != null) (y ?? x).ToString(); // 2 break; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,18): warning CS8602: Dereference of a possibly null reference. // (x ?? y).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x ?? y").WithLocation(8, 18), // (14,33): warning CS8602: Dereference of a possibly null reference. // if (y != null) (y ?? x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y ?? x").WithLocation(14, 33) ); } [Fact] public void NullCoalescingOperator_03() { var source = @"class C { static void F(object x, object? y) { (null ?? null).ToString(); (null ?? x).ToString(); (null ?? y).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,10): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and '<null>' // (null ?? null).ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? null").WithArguments("??", "<null>", "<null>").WithLocation(5, 10), // (7,10): warning CS8602: Dereference of a possibly null reference. // (null ?? y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "null ?? y").WithLocation(7, 10)); } [Fact] public void NullCoalescingOperator_04() { var source = @"class C { static void F(string x, string? y) { ("""" ?? x).ToString(); ("""" ?? y).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); } [Fact] public void NullCoalescingOperator_05() { var source0 = @"public class A { } public class B { } public class UnknownNull { public A A; public B B; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source1 = @"public class MaybeNull { public A? A; public B? B; } public class NotNull { public A A = new A(); public B B = new B(); }"; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { ref0 }); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var source = @"class C { static void F1(UnknownNull x1, UnknownNull y1) { (x1.A ?? y1.B)/*T:!*/.ToString(); } static void F2(UnknownNull x2, MaybeNull y2) { (x2.A ?? y2.B)/*T:!*/.ToString(); } static void F3(MaybeNull x3, UnknownNull y3) { (x3.A ?? y3.B)/*T:!*/.ToString(); } static void F4(MaybeNull x4, MaybeNull y4) { (x4.A ?? y4.B)/*T:!*/.ToString(); } static void F5(UnknownNull x5, NotNull y5) { (x5.A ?? y5.B)/*T:!*/.ToString(); } static void F6(NotNull x6, UnknownNull y6) { (x6.A ?? y6.B)/*T:!*/.ToString(); } static void F7(MaybeNull x7, NotNull y7) { (x7.A ?? y7.B)/*T:!*/.ToString(); } static void F8(NotNull x8, MaybeNull y8) { (x8.A ?? y8.B)/*T:!*/.ToString(); } static void F9(NotNull x9, NotNull y9) { (x9.A ?? y9.B)/*T:!*/.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0, ref1 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (5,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x1.A ?? y1.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1.A ?? y1.B").WithArguments("??", "A", "B").WithLocation(5, 10), // (9,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x2.A ?? y2.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x2.A ?? y2.B").WithArguments("??", "A", "B").WithLocation(9, 10), // (13,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x3.A ?? y3.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x3.A ?? y3.B").WithArguments("??", "A", "B").WithLocation(13, 10), // (17,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x4.A ?? y4.B)/*T:?*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x4.A ?? y4.B").WithArguments("??", "A", "B").WithLocation(17, 10), // (21,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x5.A ?? y5.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x5.A ?? y5.B").WithArguments("??", "A", "B").WithLocation(21, 10), // (25,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x6.A ?? y6.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x6.A ?? y6.B").WithArguments("??", "A", "B").WithLocation(25, 10), // (29,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x7.A ?? y7.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x7.A ?? y7.B").WithArguments("??", "A", "B").WithLocation(29, 10), // (33,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x8.A ?? y8.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x8.A ?? y8.B").WithArguments("??", "A", "B").WithLocation(33, 10), // (37,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x9.A ?? y9.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x9.A ?? y9.B").WithArguments("??", "A", "B").WithLocation(37, 10) ); } [Fact] public void NullCoalescingOperator_06() { var source = @"class C { static void F1(int i, C x1, Unknown? y1) { switch (i) { case 1: (x1 ?? y1)/*T:!*/.ToString(); break; case 2: (y1 ?? x1)/*T:!*/.ToString(); break; case 3: (null ?? y1)/*T:Unknown?*/.ToString(); break; case 4: (y1 ?? null)/*T:Unknown!*/.ToString(); break; } } static void F2(int i, C? x2, Unknown y2) { switch (i) { case 1: (x2 ?? y2)/*T:!*/.ToString(); break; case 2: (y2 ?? x2)/*T:!*/.ToString(); break; case 3: (null ?? y2)/*T:!*/.ToString(); break; case 4: (y2 ?? null)/*T:!*/.ToString(); break; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // Note: Unknown type is treated as a value type comp.VerifyTypes(); comp.VerifyDiagnostics( // (3,33): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // static void F1(int i, C x1, Unknown? y1) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(3, 33), // (21,34): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // static void F2(int i, C? x2, Unknown y2) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(21, 34), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'C' and 'Unknown?' // (x1 ?? y1)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 ?? y1").WithArguments("??", "C", "Unknown?").WithLocation(8, 18), // (11,18): error CS0019: Operator '??' cannot be applied to operands of type 'Unknown?' and 'C' // (y1 ?? x1)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "y1 ?? x1").WithArguments("??", "Unknown?", "C").WithLocation(11, 18)); } [Fact] public void NullCoalescingOperator_07() { var source = @"class C { static void F(object? o, object[]? a, object?[]? b) { if (o == null) { var c = new[] { o }; (a ?? c)[0].ToString(); (b ?? c)[0].ToString(); } else { var c = new[] { o }; (a ?? c)[0].ToString(); (b ?? c)[0].ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // (a ?? c)[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(a ?? c)[0]").WithLocation(8, 13), // (9,13): warning CS8602: Dereference of a possibly null reference. // (b ?? c)[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b ?? c)[0]").WithLocation(9, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // (b ?? c)[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b ?? c)[0]").WithLocation(15, 13)); } [Fact] public void NullCoalescingOperator_08() { var source = @"interface I<T> { } class C { static object? F((I<object>, I<object?>)? x, (I<object?>, I<object>)? y) { return x ?? y; } static object F((I<object>, I<object?>)? x, (I<object?>, I<object>) y) { return x ?? y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,21): warning CS8619: Nullability of reference types in value of type '(I<object?>, I<object>)?' doesn't match target type '(I<object>, I<object?>)?'. // return x ?? y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("(I<object?>, I<object>)?", "(I<object>, I<object?>)?").WithLocation(6, 21), // (10,21): warning CS8619: Nullability of reference types in value of type '(I<object?>, I<object>)' doesn't match target type '(I<object>, I<object?>)'. // return x ?? y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("(I<object?>, I<object>)", "(I<object>, I<object?>)").WithLocation(10, 21)); } [Fact, WorkItem(51975, "https://github.com/dotnet/roslyn/issues/51975")] public void NullCoalescingOperator_09() { var source = @"C? c = new C(); D d = c ?? new D(); d.ToString(); class C {} class D { public static implicit operator D?(C c) => default; } "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (2,7): warning CS8600: Converting null literal or possible null value to non-nullable type. // D d = c ?? new D(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ?? new D()").WithLocation(2, 7), // (4,1): warning CS8602: Dereference of a possibly null reference. // d.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d").WithLocation(4, 1) ); } [Fact, WorkItem(51975, "https://github.com/dotnet/roslyn/issues/51975")] public void NullCoalescingOperator_10() { var source = @"C? c = new C(); D d = c ?? new D(); d.ToString(); class C { public static implicit operator D?(C c) => default; } class D {} "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (2,7): warning CS8600: Converting null literal or possible null value to non-nullable type. // D d = c ?? new D(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ?? new D()").WithLocation(2, 7), // (4,1): warning CS8602: Dereference of a possibly null reference. // d.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d").WithLocation(4, 1) ); } [Fact, WorkItem(51975, "https://github.com/dotnet/roslyn/issues/51975")] public void NullCoalescingOperator_11() { var source = @"C? c = new C(); D d = c ?? new D(); d.ToString(); struct C { public static implicit operator D?(C c) => default; } class D {} "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (2,7): warning CS8600: Converting null literal or possible null value to non-nullable type. // D d = c ?? new D(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ?? new D()").WithLocation(2, 7), // (4,1): warning CS8602: Dereference of a possibly null reference. // d.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d").WithLocation(4, 1) ); } [Fact, WorkItem(51975, "https://github.com/dotnet/roslyn/issues/51975")] public void NullCoalescingOperator_12() { var source = @"C? c = new C(); C c2 = c ?? new D(); c2.ToString(); class C { public static implicit operator C?(D c) => default; } class D {} "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (2,8): warning CS8600: Converting null literal or possible null value to non-nullable type. // C c2 = c ?? new D(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ?? new D()").WithLocation(2, 8), // (4,1): warning CS8602: Dereference of a possibly null reference. // c2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(4, 1) ); } [Fact, WorkItem(29955, "https://github.com/dotnet/roslyn/issues/29955")] public void NullCoalescingOperator_13() { var source = @"C<string?> c = new C<string?>(); C<string?> c2 = c ?? new D<string>(); c2.ToString(); class C<T> { public static implicit operator C<T>(D<T> c) => default!; } class D<T> {} "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (2,22): warning CS8619: Nullability of reference types in value of type 'D<string>' doesn't match target type 'D<string?>'. // C<string?> c2 = c ?? new D<string>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new D<string>()").WithArguments("D<string>", "D<string?>").WithLocation(2, 22) ); } [Fact, WorkItem(29955, "https://github.com/dotnet/roslyn/issues/29955")] public void NullCoalescingOperator_14() { var source = @"using System; Action<string?> a1 = param => {}; Action<string?> a2 = a1 ?? ((string s) => {}); "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (3,29): warning CS8622: Nullability of reference types in type of parameter 's' of 'lambda expression' doesn't match the target delegate 'Action<string?>' (possibly because of nullability attributes). // Action<string?> a2 = a1 ?? ((string s) => {}); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(string s) => {}").WithArguments("s", "lambda expression", "System.Action<string?>").WithLocation(3, 29) ); } [Fact, WorkItem(29955, "https://github.com/dotnet/roslyn/issues/29955")] public void NullCoalescingOperator_15() { var source = @"using System; Action<string?> a1 = param => {}; Action<string?> a2 = a1 ?? (Action<string>)((string s) => {}); "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (3,22): warning CS8619: Nullability of reference types in value of type 'Action<string>' doesn't match target type 'Action<string?>'. // Action<string?> a2 = a1 ?? (Action<string>)((string s) => {}); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1 ?? (Action<string>)((string s) => {})").WithArguments("System.Action<string>", "System.Action<string?>").WithLocation(3, 22) ); } [Fact, WorkItem(29955, "https://github.com/dotnet/roslyn/issues/29955")] public void NullCoalescingOperator_16() { var source = @"using System; Func<string> a1 = () => string.Empty; Func<string> a2 = a1 ?? (() => null); "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (3,32): warning CS8603: Possible null reference return. // Func<string> a2 = a1 ?? (() => null); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(3, 32) ); } [Fact, WorkItem(29955, "https://github.com/dotnet/roslyn/issues/29955")] public void NullCoalescingOperator_17() { var source = @"using System; Func<string> a1 = () => string.Empty; Func<string> a2 = a1 ?? (Func<string?>)(() => null); "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (3,19): warning CS8619: Nullability of reference types in value of type 'Func<string?>' doesn't match target type 'Func<string>'. // Func<string> a2 = a1 ?? (Func<string?>)(() => null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1 ?? (Func<string?>)(() => null)").WithArguments("System.Func<string?>", "System.Func<string>").WithLocation(3, 19) ); } [Fact, WorkItem(51975, "https://github.com/dotnet/roslyn/issues/51975")] public void NullCoalescingOperator_18() { var source = @"using System.Diagnostics.CodeAnalysis; C? c = new C(); D d1 = c ?? new D(); d1.ToString(); D d2 = ((C?)null) ?? new D(); d2.ToString(); c = null; D d3 = c ?? new D(); d3.ToString(); class C {} class D { [return: NotNullIfNotNull(""c"")] public static implicit operator D?(C c) => default!; } "; var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics(); } [Fact] public void IdentityConversion_NullCoalescingOperator_01() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F1(I<object>? x1, I<object?> y1) { I<object> z1 = x1 ?? y1; I<object?> w1 = y1 ?? x1; } static void F2(IIn<object>? x2, IIn<object?> y2) { IIn<object> z2 = x2 ?? y2; IIn<object?> w2 = y2 ?? x2; } static void F3(IOut<object>? x3, IOut<object?> y3) { IOut<object> z3 = x3 ?? y3; IOut<object?> w3 = y3 ?? x3; } static void F4(IIn<object>? x4, IIn<object> y4) { IIn<object> z4; z4 = ((IIn<object?>)x4) ?? y4; z4 = x4 ?? (IIn<object?>)y4; } static void F5(IIn<object?>? x5, IIn<object?> y5) { IIn<object> z5; z5 = ((IIn<object>)x5) ?? y5; z5 = x5 ?? (IIn<object>)y5; } static void F6(IOut<object?>? x6, IOut<object?> y6) { IOut<object?> z6; z6 = ((IOut<object>)x6) ?? y6; z6 = x6 ?? (IOut<object>)y6; } static void F7(IOut<object>? x7, IOut<object> y7) { IOut<object?> z7; z7 = ((IOut<object?>)x7) ?? y7; z7 = x7 ?? (IOut<object?>)y7; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,30): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // I<object> z1 = x1 ?? y1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("I<object?>", "I<object>").WithLocation(8, 30), // (9,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // I<object?> w1 = y1 ?? x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1 ?? x1").WithLocation(9, 25), // (9,31): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // I<object?> w1 = y1 ?? x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("I<object>", "I<object?>").WithLocation(9, 31), // (14,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // IIn<object?> w2 = y2 ?? x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2 ?? x2").WithLocation(14, 27), // (14,27): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // IIn<object?> w2 = y2 ?? x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y2 ?? x2").WithArguments("IIn<object>", "IIn<object?>").WithLocation(14, 27), // (18,27): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // IOut<object> z3 = x3 ?? y3; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3 ?? y3").WithArguments("IOut<object?>", "IOut<object>").WithLocation(18, 27), // (19,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // IOut<object?> w3 = y3 ?? x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y3 ?? x3").WithLocation(19, 28), // (24,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // z4 = ((IIn<object?>)x4) ?? y4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IIn<object?>)x4").WithLocation(24, 15), // (30,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // z5 = ((IIn<object>)x5) ?? y5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IIn<object>)x5").WithLocation(30, 15), // (36,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // z6 = ((IOut<object>)x6) ?? y6; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IOut<object>)x6").WithLocation(36, 15), // (42,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // z7 = ((IOut<object?>)x7) ?? y7; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IOut<object?>)x7").WithLocation(42, 15)); } [Fact] [WorkItem(35012, "https://github.com/dotnet/roslyn/issues/35012")] public void IdentityConversion_NullCoalescingOperator_02() { var source = @"interface IIn<in T> { } interface IOut<out T> { } class C { static IIn<T>? FIn<T>(T x) { return null; } static IOut<T>? FOut<T>(T x) { return null; } static void FIn(IIn<object?>? x) { } static T FOut<T>(IOut<T>? x) { throw new System.Exception(); } static void F1(IIn<object>? x1, IIn<object?>? y1) { FIn((x1 ?? y1)/*T:IIn<object!>?*/); FIn((y1 ?? x1)/*T:IIn<object!>?*/); } static void F2(IOut<object>? x2, IOut<object?>? y2) { FOut((x2 ?? y2)/*T:IOut<object?>?*/).ToString(); FOut((y2 ?? x2)/*T:IOut<object?>?*/).ToString(); } static void F3(object? x3, object? y3) { FIn((FIn(x3) ?? FIn(y3))/*T:IIn<object?>?*/); // A if (x3 == null) return; FIn((FIn(x3) ?? FIn(y3))/*T:IIn<object!>?*/); // B FIn((FIn(y3) ?? FIn(x3))/*T:IIn<object!>?*/); // C if (y3 == null) return; FIn((FIn(x3) ?? FIn(y3))/*T:IIn<object!>?*/); // D } static void F4(object? x4, object? y4) { FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object?>?*/).ToString(); // A if (x4 == null) return; FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object?>?*/).ToString(); // B FOut((FOut(y4) ?? FOut(x4))/*T:IOut<object?>?*/).ToString(); // C if (y4 == null) return; FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object!>?*/).ToString(); // D } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (22,14): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'x' in 'void C.FIn(IIn<object?>? x)'. // FIn((x1 ?? y1)/*T:IIn<object!>?*/); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1 ?? y1").WithArguments("IIn<object>", "IIn<object?>", "x", "void C.FIn(IIn<object?>? x)").WithLocation(22, 14), // (23,14): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'x' in 'void C.FIn(IIn<object?>? x)'. // FIn((y1 ?? x1)/*T:IIn<object!>?*/); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1 ?? x1").WithArguments("IIn<object>", "IIn<object?>", "x", "void C.FIn(IIn<object?>? x)").WithLocation(23, 14), // (27,9): warning CS8602: Dereference of a possibly null reference. // FOut((x2 ?? y2)/*T:IOut<object?>?*/).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "FOut((x2 ?? y2)/*T:IOut<object?>?*/)").WithLocation(27, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // FOut((y2 ?? x2)/*T:IOut<object?>?*/).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "FOut((y2 ?? x2)/*T:IOut<object?>?*/)").WithLocation(28, 9), // (34,14): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'x' in 'void C.FIn(IIn<object?>? x)'. // FIn((FIn(x3) ?? FIn(y3))/*T:IIn<object!>?*/); // B Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "FIn(x3) ?? FIn(y3)").WithArguments("IIn<object>", "IIn<object?>", "x", "void C.FIn(IIn<object?>? x)").WithLocation(34, 14), // (35,14): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'x' in 'void C.FIn(IIn<object?>? x)'. // FIn((FIn(y3) ?? FIn(x3))/*T:IIn<object!>?*/); // C Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "FIn(y3) ?? FIn(x3)").WithArguments("IIn<object>", "IIn<object?>", "x", "void C.FIn(IIn<object?>? x)").WithLocation(35, 14), // (37,14): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'x' in 'void C.FIn(IIn<object?>? x)'. // FIn((FIn(x3) ?? FIn(y3))/*T:IIn<object!>?*/); // D Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "FIn(x3) ?? FIn(y3)").WithArguments("IIn<object>", "IIn<object?>", "x", "void C.FIn(IIn<object?>? x)").WithLocation(37, 14), // (41,9): warning CS8602: Dereference of a possibly null reference. // FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object?>?*/).ToString(); // A Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object?>?*/)").WithLocation(41, 9), // (43,9): warning CS8602: Dereference of a possibly null reference. // FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object?>?*/).ToString(); // B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object?>?*/)").WithLocation(43, 9), // (44,9): warning CS8602: Dereference of a possibly null reference. // FOut((FOut(y4) ?? FOut(x4))/*T:IOut<object?>?*/).ToString(); // C Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "FOut((FOut(y4) ?? FOut(x4))/*T:IOut<object?>?*/)").WithLocation(44, 9)); } [Fact] public void IdentityConversion_NullCoalescingOperator_03() { var source = @"class C { static void F((object?, object?)? x, (object, object) y) { (x ?? y).Item1.ToString(); } static void G((object, object)? x, (object?, object?) y) { (x ?? y).Item1.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // (x ?? y).Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x ?? y).Item1").WithLocation(5, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // (x ?? y).Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x ?? y).Item1").WithLocation(9, 9)); } [Fact] public void IdentityConversion_NullCoalescingOperator_04() { var source = @"#pragma warning disable 0649 struct A<T> { public static implicit operator B<T>(A<T> a) => default; } struct B<T> { internal T F; } class C { static void F1(A<object>? x1, B<object?> y1) { (x1 ?? y1)/*T:B<object?>*/.F.ToString(); } static void F2(A<object?>? x2, B<object> y2) { (x2 ?? y2)/*T:B<object!>*/.F.ToString(); } static void F3(A<object> x3, B<object?>? y3) { (y3 ?? x3)/*T:B<object?>*/.F.ToString(); } static void F4(A<object?> x4, B<object>? y4) { (y4 ?? x4)/*T:B<object!>*/.F.ToString(); } static void F5(A<object>? x5, B<object?>? y5) { (x5 ?? y5)/*T:B<object?>?*/.Value.F.ToString(); (y5 ?? x5)/*T:B<object?>?*/.Value.F.ToString(); } static void F6(A<object?>? x6, B<object>? y6) { (x6 ?? y6)/*T:B<object!>?*/.Value.F.ToString(); (y6 ?? x6)/*T:B<object!>?*/.Value.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (14,10): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'B<object?>'. // (x1 ?? y1)/*T:B<object?>*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("A<object>", "B<object?>").WithLocation(14, 10), // (14,9): warning CS8602: Dereference of a possibly null reference. // (x1 ?? y1)/*T:B<object?>*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x1 ?? y1)/*T:B<object?>*/.F").WithLocation(14, 9), // (18,10): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'B<object>'. // (x2 ?? y2)/*T:B<object!>*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("A<object?>", "B<object>").WithLocation(18, 10), // (22,16): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'B<object?>'. // (y3 ?? x3)/*T:B<object?>*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("B<object>", "B<object?>").WithLocation(22, 16), // (22,9): warning CS8602: Dereference of a possibly null reference. // (y3 ?? x3)/*T:B<object?>*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(y3 ?? x3)/*T:B<object?>*/.F").WithLocation(22, 9), // (26,16): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // (y4 ?? x4)/*T:B<object!>*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x4").WithArguments("B<object?>", "B<object>").WithLocation(26, 16), // (30,10): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'B<object?>?'. // (x5 ?? y5)/*T:B<object?>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x5").WithArguments("A<object>", "B<object?>?").WithLocation(30, 10), // (30,10): warning CS8629: Nullable value type may be null. // (x5 ?? y5)/*T:B<object?>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x5 ?? y5").WithLocation(30, 10), // (30,9): warning CS8602: Dereference of a possibly null reference. // (x5 ?? y5)/*T:B<object?>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x5 ?? y5)/*T:B<object?>?*/.Value.F").WithLocation(30, 9), // (31,16): warning CS8619: Nullability of reference types in value of type 'B<object>?' doesn't match target type 'B<object?>?'. // (y5 ?? x5)/*T:B<object?>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x5").WithArguments("B<object>?", "B<object?>?").WithLocation(31, 16), // (31,10): warning CS8629: Nullable value type may be null. // (y5 ?? x5)/*T:B<object?>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y5 ?? x5").WithLocation(31, 10), // (31,9): warning CS8602: Dereference of a possibly null reference. // (y5 ?? x5)/*T:B<object?>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(y5 ?? x5)/*T:B<object?>?*/.Value.F").WithLocation(31, 9), // (35,10): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'B<object>?'. // (x6 ?? y6)/*T:B<object!>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x6").WithArguments("A<object?>", "B<object>?").WithLocation(35, 10), // (35,10): warning CS8629: Nullable value type may be null. // (x6 ?? y6)/*T:B<object!>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x6 ?? y6").WithLocation(35, 10), // (36,16): warning CS8619: Nullability of reference types in value of type 'B<object?>?' doesn't match target type 'B<object>?'. // (y6 ?? x6)/*T:B<object!>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x6").WithArguments("B<object?>?", "B<object>?").WithLocation(36, 16), // (36,10): warning CS8629: Nullable value type may be null. // (y6 ?? x6)/*T:B<object!>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y6 ?? x6").WithLocation(36, 10) ); } [Fact] [WorkItem(29871, "https://github.com/dotnet/roslyn/issues/29871")] public void IdentityConversion_NullCoalescingOperator_05() { var source = @"#pragma warning disable 0649 struct A<T> { public static implicit operator B<T>(A<T> a) => new B<T>(); } class B<T> { internal T F; } class C { static void F1(A<object>? x1, B<object?> y1) { (x1 ?? y1)/*T:B<object?>!*/.F.ToString(); } static void F2(A<object?>? x2, B<object> y2) { (x2 ?? y2)/*T:B<object!>!*/.F.ToString(); } static void F3(A<object> x3, B<object?>? y3) { (y3 ?? x3)/*T:B<object?>!*/.F.ToString(); } static void F4(A<object?> x4, B<object>? y4) { (y4 ?? x4)/*T:B<object!>!*/.F.ToString(); } static void F5(A<object>? x5, B<object?>? y5) { (x5 ?? y5)/*T:B<object?>?*/.F.ToString(); (y5 ?? x5)/*T:B<object?>?*/.F.ToString(); } static void F6(A<object?>? x6, B<object>? y6) { (x6 ?? y6)/*T:B<object!>?*/.F.ToString(); (y6 ?? x6)/*T:B<object!>?*/.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (8,16): warning CS8618: Non-nullable field 'F' is uninitialized. Consider declaring the field as nullable. // internal T F; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "F").WithArguments("field", "F").WithLocation(8, 16), // (14,10): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'B<object?>'. // (x1 ?? y1)/*T:B<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("A<object>", "B<object?>").WithLocation(14, 10), // (14,9): warning CS8602: Dereference of a possibly null reference. // (x1 ?? y1)/*T:B<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x1 ?? y1)/*T:B<object?>!*/.F").WithLocation(14, 9), // (18,10): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'B<object>'. // (x2 ?? y2)/*T:B<object!>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("A<object?>", "B<object>").WithLocation(18, 10), // (22,16): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'B<object?>'. // (y3 ?? x3)/*T:B<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("B<object>", "B<object?>").WithLocation(22, 16), // (22,9): warning CS8602: Dereference of a possibly null reference. // (y3 ?? x3)/*T:B<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(y3 ?? x3)/*T:B<object?>!*/.F").WithLocation(22, 9), // (26,16): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // (y4 ?? x4)/*T:B<object!>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x4").WithArguments("B<object?>", "B<object>").WithLocation(26, 16), // (30,10): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'B<object?>'. // (x5 ?? y5)/*T:B<object?>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x5").WithArguments("A<object>", "B<object?>").WithLocation(30, 10), // (30,10): warning CS8602: Dereference of a possibly null reference. // (x5 ?? y5)/*T:B<object?>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x5 ?? y5").WithLocation(30, 10), // (30,9): warning CS8602: Dereference of a possibly null reference. // (x5 ?? y5)/*T:B<object?>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x5 ?? y5)/*T:B<object?>?*/.F").WithLocation(30, 9), // (31,16): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'B<object?>'. // (y5 ?? x5)/*T:B<object?>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x5").WithArguments("B<object>", "B<object?>").WithLocation(31, 16), // (31,10): warning CS8602: Dereference of a possibly null reference. // (y5 ?? x5)/*T:B<object?>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y5 ?? x5").WithLocation(31, 10), // (31,9): warning CS8602: Dereference of a possibly null reference. // (y5 ?? x5)/*T:B<object?>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(y5 ?? x5)/*T:B<object?>?*/.F").WithLocation(31, 9), // (35,10): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'B<object>'. // (x6 ?? y6)/*T:B<object!>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x6").WithArguments("A<object?>", "B<object>").WithLocation(35, 10), // (35,10): warning CS8602: Dereference of a possibly null reference. // (x6 ?? y6)/*T:B<object!>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x6 ?? y6").WithLocation(35, 10), // (36,16): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // (y6 ?? x6)/*T:B<object!>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x6").WithArguments("B<object?>", "B<object>").WithLocation(36, 16), // (36,10): warning CS8602: Dereference of a possibly null reference. // (y6 ?? x6)/*T:B<object!>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y6 ?? x6").WithLocation(36, 10)); } [Fact] public void IdentityConversion_NullCoalescingOperator_06() { var source = @"class C { static void F1(object? x, dynamic? y, dynamic z) { (x ?? y).ToString(); // 1 (x ?? z).ToString(); // ok (y ?? x).ToString(); // 2 (y ?? z).ToString(); // ok (z ?? x).ToString(); // 3 (z ?? y).ToString(); // 4 } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,10): warning CS8602: Dereference of a possibly null reference. // (x ?? y).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x ?? y").WithLocation(5, 10), // (7,10): warning CS8602: Dereference of a possibly null reference. // (y ?? x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y ?? x").WithLocation(7, 10), // (9,10): warning CS8602: Dereference of a possibly null reference. // (z ?? x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z ?? x").WithLocation(9, 10), // (10,10): warning CS8602: Dereference of a possibly null reference. // (z ?? y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z ?? y").WithLocation(10, 10)); } [Fact] public void ImplicitConversion_NullCoalescingOperator_01() { var source0 = @"public class UnknownNull { public object Object; public string String; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source1 = @"public class MaybeNull { public object? Object; public string? String; } public class NotNull { public object Object = new object(); public string String = string.Empty; }"; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var source = @"class C { static void F1(bool b, UnknownNull x1, UnknownNull y1) { if (b) { (x1.Object ?? y1.String)/*T:object!*/.ToString(); } else { (y1.String ?? x1.Object)/*T:object!*/.ToString(); } } static void F2(bool b, UnknownNull x2, MaybeNull y2) { if (b) { (x2.Object ?? y2.String)/*T:object?*/.ToString(); // 1 } else { (y2.String ?? x2.Object)/*T:object!*/.ToString(); } } static void F3(bool b, MaybeNull x3, UnknownNull y3) { if (b) { (x3.Object ?? y3.String)/*T:object!*/.ToString(); } else { (y3.String ?? x3.Object)/*T:object?*/.ToString(); // 2 } } static void F4(bool b, MaybeNull x4, MaybeNull y4) { if (b) { (x4.Object ?? y4.String)/*T:object?*/.ToString(); // 3 } else { (y4.String ?? x4.Object)/*T:object?*/.ToString(); // 4 } } static void F5(bool b, UnknownNull x5, NotNull y5) { if (b) { (x5.Object ?? y5.String)/*T:object!*/.ToString(); } else { (y5.String ?? x5.Object)/*T:object!*/.ToString(); } } static void F6(bool b, NotNull x6, UnknownNull y6) { if (b) { (x6.Object ?? y6.String)/*T:object!*/.ToString(); } else { (y6.String ?? x6.Object)/*T:object!*/.ToString(); } } static void F7(bool b, MaybeNull x7, NotNull y7) { if (b) { (x7.Object ?? y7.String)/*T:object!*/.ToString(); } else { (y7.String ?? x7.Object)/*T:object?*/.ToString(); // 5 } } static void F8(bool b, NotNull x8, MaybeNull y8) { if (b) { (x8.Object ?? y8.String)/*T:object?*/.ToString(); // 6 } else { (y8.String ?? x8.Object)/*T:object!*/.ToString(); } } static void F9(bool b, NotNull x9, NotNull y9) { if (b) { (x9.Object ?? y9.String)/*T:object!*/.ToString(); } else { (y9.String ?? x9.Object)/*T:object!*/.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0, ref1 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (14,14): warning CS8602: Dereference of a possibly null reference. // (x2.Object ?? y2.String)/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2.Object ?? y2.String").WithLocation(14, 14), // (24,14): warning CS8602: Dereference of a possibly null reference. // (y3.String ?? x3.Object)/*T:object?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y3.String ?? x3.Object").WithLocation(24, 14), // (30,14): warning CS8602: Dereference of a possibly null reference. // (x4.Object ?? y4.String)/*T:object?*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4.Object ?? y4.String").WithLocation(30, 14), // (32,14): warning CS8602: Dereference of a possibly null reference. // (y4.String ?? x4.Object)/*T:object?*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y4.String ?? x4.Object").WithLocation(32, 14), // (56,14): warning CS8602: Dereference of a possibly null reference. // (y7.String ?? x7.Object)/*T:object?*/.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y7.String ?? x7.Object").WithLocation(56, 14), // (62,14): warning CS8602: Dereference of a possibly null reference. // (x8.Object ?? y8.String)/*T:object?*/.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x8.Object ?? y8.String").WithLocation(62, 14)); } [Fact] public void ImplicitConversion_NullCoalescingOperator_02() { var source = @"#pragma warning disable 0649 class A<T> { internal T F; } class B<T> : A<T> { } class C { static void F(A<object>? x, B<object?> y) { (x ?? y).F.ToString(); // 1 (y ?? x).F.ToString(); // 2 } static void G(A<object?> z, B<object>? w) { (z ?? w).F.ToString(); // 3 (w ?? z).F.ToString(); // 4 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,16): warning CS8618: Non-nullable field 'F' is uninitialized. Consider declaring the field as nullable. // internal T F; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "F").WithArguments("field", "F").WithLocation(4, 16), // (11,15): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'A<object>'. // (x ?? y).F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("B<object?>", "A<object>").WithLocation(11, 15), // (12,10): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'A<object>'. // (y ?? x).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("B<object?>", "A<object>").WithLocation(12, 10), // (12,10): warning CS8602: Dereference of a possibly null reference. // (y ?? x).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y ?? x").WithLocation(12, 10), // (16,15): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // (z ?? w).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("B<object>", "A<object?>").WithLocation(16, 15), // (16,10): warning CS8602: Dereference of a possibly null reference. // (z ?? w).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z ?? w").WithLocation(16, 10), // (16,9): warning CS8602: Dereference of a possibly null reference. // (z ?? w).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(z ?? w).F").WithLocation(16, 9), // (17,10): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // (w ?? z).F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("B<object>", "A<object?>").WithLocation(17, 10), // (17,10): warning CS8602: Dereference of a possibly null reference. // (w ?? z).F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w ?? z").WithLocation(17, 10), // (17,9): warning CS8602: Dereference of a possibly null reference. // (w ?? z).F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(w ?? z).F").WithLocation(17, 9)); } [Fact] public void ImplicitConversion_NullCoalescingOperator_03() { var source = @"interface IIn<in T> { void F(T x, T y); } class C { static void F(bool b, IIn<object>? x, IIn<string?> y) { if (b) { (x ?? y)/*T:IIn<string?>!*/.F(string.Empty, null); // 1 } else { (y ?? x)/*T:IIn<string?>?*/.F(string.Empty, null); // 2 } } static void G(bool b, IIn<object?> z, IIn<string>? w) { if (b) { (z ?? w)/*T:IIn<string!>?*/.F(string.Empty, null); // 3 } else { (w ?? z)/*T:IIn<string!>!*/.F(string.Empty, null); // 4 } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (10,14): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<string?>'. // (x ?? y)/*T:IIn<string?>!*/.F(string.Empty, null); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object>", "IIn<string?>").WithLocation(10, 14), // (12,14): warning CS8602: Dereference of a possibly null reference. // (y ?? x)/*T:IIn<string?>?*/.F(string.Empty, null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y ?? x").WithLocation(12, 14), // (12,19): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<string?>'. // (y ?? x)/*T:IIn<string?>?*/.F(string.Empty, null); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object>", "IIn<string?>").WithLocation(12, 19), // (18,14): warning CS8602: Dereference of a possibly null reference. // (z ?? w)/*T:IIn<string!>?*/.F(string.Empty, null); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z ?? w").WithLocation(18, 14), // (18,57): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // (z ?? w)/*T:IIn<string!>?*/.F(string.Empty, null); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(18, 57), // (20,57): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // (w ?? z)/*T:IIn<string!>!*/.F(string.Empty, null); // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 57)); } [Fact] public void ImplicitConversion_NullCoalescingOperator_04() { var source = @"interface IOut<out T> { T P { get; } } class C { static void F(bool b, IOut<object>? x, IOut<string?> y) { if (b) { (x ?? y)/*T:IOut<object!>!*/.P.ToString(); // 1 } else { (y ?? x)/*T:IOut<object!>?*/.P.ToString(); // 2 } } static void G(bool b, IOut<object?> z, IOut<string>? w) { if (b) { (z ?? w)/*T:IOut<object?>?*/.P.ToString(); // 3 } else { (w ?? z)/*T:IOut<object?>!*/.P.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (10,19): warning CS8619: Nullability of reference types in value of type 'IOut<string?>' doesn't match target type 'IOut<object>'. // (x ?? y)/*T:IOut<object!>!*/.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("IOut<string?>", "IOut<object>").WithLocation(10, 19), // (12,14): warning CS8619: Nullability of reference types in value of type 'IOut<string?>' doesn't match target type 'IOut<object>'. // (y ?? x)/*T:IOut<object!>?*/.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("IOut<string?>", "IOut<object>").WithLocation(12, 14), // (12,14): warning CS8602: Dereference of a possibly null reference. // (y ?? x)/*T:IOut<object!>?*/.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y ?? x").WithLocation(12, 14), // (18,13): warning CS8602: Dereference of a possibly null reference. // (z ?? w)/*T:IOut<object?>?*/.P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(z ?? w)/*T:IOut<object?>?*/.P").WithLocation(18, 13), // (18,14): warning CS8602: Dereference of a possibly null reference. // (z ?? w)/*T:IOut<object?>?*/.P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z ?? w").WithLocation(18, 14), // (20,13): warning CS8602: Dereference of a possibly null reference. // (w ?? z)/*T:IOut<object?>!*/.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(w ?? z)/*T:IOut<object?>!*/.P").WithLocation(20, 13)); } [Fact] public void Loop_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1? x1, CL1 y1, CL1? z1) { x1 = y1; x1.M1(); // 1 for (int i = 0; i < 2; i++) { x1.M1(); // 2 x1 = z1; } } CL1 Test2(CL1? x2, CL1 y2, CL1? z2) { x2 = y2; x2.M1(); // 1 for (int i = 0; i < 2; i++) { x2 = z2; x2.M1(); // 2 y2 = z2; y2.M2(y2); if (i == 1) { return x2; } } return y2; } } class CL1 { public void M1() { } public void M2(CL1 x) { } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,13): warning CS8602: Dereference of a possibly null reference. // x1.M1(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(15, 13), // (28,13): warning CS8602: Dereference of a possibly null reference. // x2.M1(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(28, 13), // (29,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // y2 = z2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z2").WithLocation(29, 18), // (30,13): warning CS8602: Dereference of a possibly null reference. // y2.M2(y2); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(30, 13)); } [Fact] public void Loop_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1? x1, CL1 y1, CL1? z1) { x1 = y1; if (x1 == null) {} // 1 for (int i = 0; i < 2; i++) { if (x1 == null) {} // 2 x1 = z1; } } void Test2(CL1? x2, CL1 y2, CL1? z2) { x2 = y2; if (x2 == null) {} // 1 for (int i = 0; i < 2; i++) { x2 = z2; if (x2 == null) {} // 2 } } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Loop_03() { var source0 = @"public class A { public object F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var source1 = @"#pragma warning disable 8618 class B { object G; static object F1(B b1, object? o) { for (int i = 0; i < 2; i++) { b1.G = o; } return b1.G; } static object F2(B b2, A a) { for (int i = 0; i < 2; i++) { b2.G = a.F; } return b2.G; } static object F3(B b3, object? o, A a) { for (int i = 0; i < 2; i++) { if (i % 2 == 0) b3.G = o; else b3.G = a.F; } return b3.G; } }"; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { comp0.EmitToImageReference() }); comp1.VerifyDiagnostics( // (9,20): warning CS8601: Possible null reference assignment. // b1.G = o; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "o").WithLocation(9, 20), // (11,16): warning CS8603: Possible null reference return. // return b1.G; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b1.G").WithLocation(11, 16), // (26,24): warning CS8601: Possible null reference assignment. // b3.G = o; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "o").WithLocation(26, 24), // (30,16): warning CS8603: Possible null reference return. // return b3.G; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b3.G").WithLocation(30, 16)); } [Fact] public void Loop_04() { var source0 = @"public class A { public object F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var source1 = @"#pragma warning disable 8618 class C { static object F1(A a1, object? o) { for (int i = 0; i < 2; i++) { a1.F = o; } return a1.F; } static object F2(A a2, object o) { for (int i = 0; i < 2; i++) { a2.F = o; } return a2.F; } static object F3(A a3, object? o, A a) { for (int i = 0; i < 2; i++) { if (i % 2 == 0) a3.F = o; else a3.F = a.F; } return a3.F; } }"; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { comp0.EmitToImageReference() }); comp1.VerifyDiagnostics( // (10,16): warning CS8603: Possible null reference return. // return a1.F; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "a1.F").WithLocation(10, 16), // (29,16): warning CS8603: Possible null reference return. // return a3.F; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "a3.F").WithLocation(29, 16)); } [Fact, WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void Var_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? Test1() { var x1 = (CL1)null; return x1; } CL1? Test2(CL1 x2) { var y2 = x2; y2 = null; return y2; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // var x1 = (CL1)null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(CL1)null").WithLocation(10, 18)); } [Fact, WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void Var_NonNull() { var source = @"class C { static void F(string str) { var s = str; s.ToString(); s = null; s.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclarationSyntax>().First(); Assert.Equal("System.String?", model.GetTypeInfoAndVerifyIOperation(declaration.Type).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, model.GetTypeInfo(declaration.Type).Nullability.Annotation); Assert.Equal("System.String?", model.GetTypeInfo(declaration.Type).ConvertedType.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, model.GetTypeInfo(declaration.Type).ConvertedNullability.Annotation); } [Fact] public void Var_NonNull_CSharp7() { var source = @"class C { static void Main() { var s = string.Empty; s.ToString(); s = null; s.ToString(); } }"; var comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Oblivious, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_01() { var source = @"class C { static void F(string? s) { var t = s; t.ToString(); t = null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(6, 9)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_02() { var source = @"class C { static void F(string? s) { t = null/*T:<null>?*/; var t = s; t.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS0841: Cannot use local variable 't' before it is declared // t = null; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "t").WithArguments("t").WithLocation(5, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(7, 9)); comp.VerifyTypes(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_03() { var source = @"class C { static void F(string? s) { if (s == null) { return; } var t = s; t.ToString(); t = null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_04() { var source = @"class C { static void F(int n) { string? s = string.Empty; while (n-- > 0) { var t = s; t.ToString(); t = null; s = null; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(9, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_05() { var source = @"class C { static void F(int n, string? s) { while (n-- > 0) { var t = s; t.ToString(); t = null; s = string.Empty; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(8, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_06() { var source = @"class C { static void F(int n) { string? s = string.Empty; while (n-- > 0) { var t = s; t.ToString(); t = null; if (n % 2 == 0) s = null; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(9, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Skip(1).First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_07() { var source = @"class C { static void F(int n) { string? s = string.Empty; while (n-- > 0) { var t = s; t.ToString(); t = null; if (n % 2 == 0) s = string.Empty; else s = null; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(9, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Skip(1).First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_08() { var source = @"class C { static void F(string? s) { var t = s!; t/*T:string!*/.ToString(); t = null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_Cycle() { var source = @"class C { static void Main() { var s = s; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,17): error CS0841: Cannot use local variable 's' before it is declared // var s = s; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "s").WithArguments("s").WithLocation(5, 17)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); var type = symbol.TypeWithAnnotations; Assert.True(type.Type.IsErrorType()); Assert.Equal("var?", type.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, type.NullableAnnotation); } [Fact] public void Var_ConditionalOperator() { var source = @"class C { static void F(bool b, string s) { var s0 = b ? s : s; var s1 = b ? s : null; var s2 = b ? null : s; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[2]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_Array_01() { var source = @"class C { static void F(string str) { var s = new[] { str }; s[0].ToString(); var t = new[] { str, null }; t[0].ToString(); var u = new[] { 1, null }; u[0].ToString(); var v = new[] { null, (int?)2 }; v[0].ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,28): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // var u = new[] { 1, null }; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(9, 28), // (8,9): warning CS8602: Dereference of a possibly null reference. // t[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t[0]").WithLocation(8, 9)); } [Fact] public void Var_Array_02() { var source = @"delegate void D(); class C { static void Main() { var a = new[] { new D(Main), () => { } }; a[0].ToString(); var b = new[] { new D(Main), null }; b[0].ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // b[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0]").WithLocation(9, 9)); } [Fact] public void Array_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1? [] x1) { CL1? y1 = x1[0]; CL1 z1 = x1[0]; } void Test2(CL1 [] x2, CL1 y2, CL1? z2) { x2[0] = y2; x2[1] = z2; } void Test3(CL1 [] x3) { CL1? y3 = x3[0]; CL1 z3 = x3[0]; } void Test4(CL1? [] x4, CL1 y4, CL1? z4) { x4[0] = y4; x4[1] = z4; } void Test5(CL1 y5, CL1? z5) { var x5 = new CL1 [] { y5, z5 }; } void Test6(CL1 y6, CL1? z6) { var x6 = new CL1 [,] { {y6}, {z6} }; } void Test7(CL1 y7, CL1? z7) { var u7 = new CL1? [] { y7, z7 }; var v7 = new CL1? [,] { {y7}, {z7} }; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z1 = x1[0]; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1[0]").WithLocation(11, 18), // (17,17): warning CS8601: Possible null reference assignment. // x2[1] = z2; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "z2").WithLocation(17, 17), // (34,35): warning CS8601: Possible null reference assignment. // var x5 = new CL1 [] { y5, z5 }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "z5").WithLocation(34, 35), // (39,39): warning CS8601: Possible null reference assignment. // var x6 = new CL1 [,] { {y6}, {z6} }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "z6").WithLocation(39, 39) ); } [Fact] public void Array_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 y1, CL1? z1) { CL1? [] u1 = new [] { y1, z1 }; CL1? [,] v1 = new [,] { {y1}, {z1} }; } void Test2(CL1 y2, CL1? z2) { var u2 = new [] { y2, z2 }; var v2 = new [,] { {y2}, {z2} }; u2[0] = z2; v2[0,0] = z2; } void Test3(CL1 y3, CL1? z3) { CL1? [] u3; CL1? [,] v3; u3 = new [] { y3, z3 }; v3 = new [,] { {y3}, {z3} }; } void Test4(CL1 y4, CL1? z4) { var u4 = new [] { y4 }; var v4 = new [,] {{y4}}; u4[0] = z4; v4[0,0] = z4; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (37,17): warning CS8601: Possible null reference assignment. // u4[0] = z4; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "z4").WithLocation(37, 17), // (38,19): warning CS8601: Possible null reference assignment. // v4[0,0] = z4; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "z4").WithLocation(38, 19) ); } [Fact] public void Array_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1() { int[]? u1 = new [] { 1, 2 }; u1 = null; var z1 = u1[0]; } void Test2() { int[]? u1 = new [] { 1, 2 }; u1 = null; var z1 = u1?[u1[0]]; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,18): warning CS8602: Dereference of a possibly null reference. // var z1 = u1[0]; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u1").WithLocation(12, 18) ); } [Fact] public void Array_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 y1, CL1? z1) { CL1 [] u1; CL1 [,] v1; u1 = new [] { y1, z1 }; v1 = new [,] { {y1}, {z1} }; } void Test3(CL1 y2, CL1? z2) { CL1 [] u2; CL1 [,] v2; var a2 = new [] { y2, z2 }; var b2 = new [,] { {y2}, {z2} }; u2 = a2; v2 = b2; } void Test8(CL1 y8, CL1? z8) { CL1 [] x8 = new [] { y8, z8 }; } void Test9(CL1 y9, CL1? z9) { CL1 [,] x9 = new [,] { {y9}, {z9} }; } void Test11(CL1 y11, CL1? z11) { CL1? [] u11; CL1? [,] v11; u11 = new [] { y11, z11 }; v11 = new [,] { {y11}, {z11} }; } void Test13(CL1 y12, CL1? z12) { CL1? [] u12; CL1? [,] v12; var a12 = new [] { y12, z12 }; var b12 = new [,] { {y12}, {z12} }; u12 = a12; v12 = b12; } void Test18(CL1 y18, CL1? z18) { CL1? [] x18 = new [] { y18, z18 }; } void Test19(CL1 y19, CL1? z19) { CL1? [,] x19 = new [,] { {y19}, {z19} }; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,14): warning CS8619: Nullability of reference types in value of type 'CL1?[]' doesn't match target type 'CL1[]'. // u1 = new [] { y1, z1 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new [] { y1, z1 }").WithArguments("CL1?[]", "CL1[]").WithLocation(13, 14), // (14,14): warning CS8619: Nullability of reference types in value of type 'CL1?[*,*]' doesn't match target type 'CL1[*,*]'. // v1 = new [,] { {y1}, {z1} }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new [,] { {y1}, {z1} }").WithArguments("CL1?[*,*]", "CL1[*,*]").WithLocation(14, 14), // (25,14): warning CS8619: Nullability of reference types in value of type 'CL1?[]' doesn't match target type 'CL1[]'. // u2 = a2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("CL1?[]", "CL1[]").WithLocation(25, 14), // (26,14): warning CS8619: Nullability of reference types in value of type 'CL1?[*,*]' doesn't match target type 'CL1[*,*]'. // v2 = b2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b2").WithArguments("CL1?[*,*]", "CL1[*,*]").WithLocation(26, 14), // (31,21): warning CS8619: Nullability of reference types in value of type 'CL1?[]' doesn't match target type 'CL1[]'. // CL1 [] x8 = new [] { y8, z8 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new [] { y8, z8 }").WithArguments("CL1?[]", "CL1[]").WithLocation(31, 21), // (36,22): warning CS8619: Nullability of reference types in value of type 'CL1?[*,*]' doesn't match target type 'CL1[*,*]'. // CL1 [,] x9 = new [,] { {y9}, {z9} }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new [,] { {y9}, {z9} }").WithArguments("CL1?[*,*]", "CL1[*,*]").WithLocation(36, 22) ); } [Fact] public void Array_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1() { int[]? u1 = new [] { 1, 2 }; var z1 = u1.Length; } void Test2() { int[]? u2 = new [] { 1, 2 }; u2 = null; var z2 = u2.Length; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (18,18): warning CS8602: Dereference of a possibly null reference. // var z2 = u2.Length; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2").WithLocation(18, 18) ); } [Fact] public void Array_06() { const string source = @" class C { static void Main() { } object Test1() { object []? u1 = null; return u1; } object Test2() { object [][]? u2 = null; return u2; } object Test3() { object []?[]? u3 = null; return u3; } } "; var expected = new[] { // (10,18): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // object []? u1 = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(10, 18), // (15,20): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // object [][]? u2 = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(15, 20), // (20,18): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // object []?[]? u3 = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(20, 18), // (20,21): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // object []?[]? u3 = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(20, 21) }; var c = CreateCompilation(source, parseOptions: TestOptions.Regular7); c.VerifyDiagnostics(expected); } [Fact] public void Array_07() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1() { object? [] u1 = new [] { null, new object() }; u1 = null; } void Test2() { object [] u2 = new [] { null, new object() }; } void Test3() { var u3 = new object [] { null, new object() }; } object? Test4() { object []? u4 = null; return u4; } object Test5() { object? [] u5 = null; return u5; } void Test6() { object [][,]? u6 = null; u6[0] = null; u6[0][0,0] = null; u6[0][0,0].ToString(); } void Test7() { object [][,] u7 = null; u7[0] = null; u7[0][0,0] = null; } void Test8() { object []?[,] u8 = null; u8[0,0] = null; u8[0,0].ToString(); u8[0,0][0] = null; u8[0,0][0].ToString(); } void Test9() { object []?[,]? u9 = null; u9[0,0] = null; u9[0,0][0] = null; u9[0,0][0].ToString(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // u1 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 14), // (16,24): warning CS8619: Nullability of reference types in value of type 'object?[]' doesn't match target type 'object[]'. // object [] u2 = new [] { null, new object() }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new [] { null, new object() }").WithArguments("object?[]", "object[]").WithLocation(16, 24), // (21,34): warning CS8625: Cannot convert null literal to non-nullable reference type. // var u3 = new object [] { null, new object() }; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 34), // (32,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // object? [] u5 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(32, 25), // (33,16): warning CS8603: Possible null reference return. // return u5; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u5").WithLocation(33, 16), // (39,9): warning CS8602: Dereference of a possibly null reference. // u6[0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u6").WithLocation(39, 9), // (39,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // u6[0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(39, 17), // (40,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u6[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(40, 22), // (46,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // object [][,] u7 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(46, 27), // (47,9): warning CS8602: Dereference of a possibly null reference. // u7[0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u7").WithLocation(47, 9), // (47,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // u7[0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(47, 17), // (48,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u7[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(48, 22), // (53,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // object []?[,] u8 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(53, 28), // (54,9): warning CS8602: Dereference of a possibly null reference. // u8[0,0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u8").WithLocation(54, 9), // (55,9): warning CS8602: Dereference of a possibly null reference. // u8[0,0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u8[0,0]").WithLocation(55, 9), // (56,9): warning CS8602: Dereference of a possibly null reference. // u8[0,0][0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u8[0,0]").WithLocation(56, 9), // (56,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u8[0,0][0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(56, 22), // (57,9): warning CS8602: Dereference of a possibly null reference. // u8[0,0][0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u8[0,0]").WithLocation(57, 9), // (63,9): warning CS8602: Dereference of a possibly null reference. // u9[0,0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u9").WithLocation(63, 9), // (64,9): warning CS8602: Dereference of a possibly null reference. // u9[0,0][0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u9[0,0]").WithLocation(64, 9), // (64,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u9[0,0][0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(64, 22), // (65,9): warning CS8602: Dereference of a possibly null reference. // u9[0,0][0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u9[0,0]").WithLocation(65, 9) ); } [Fact] public void Array_08() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test3() { var u3 = new object? [] { null }; } void Test6() { var u6 = new object [,]?[] {null, new object[,] {{null}}}; u6[0] = null; u6[0][0,0] = null; u6[0][0,0].ToString(); } void Test7() { var u7 = new object [][,] {null, new object[,] {{null}}}; u7[0] = null; u7[0][0,0] = null; } void Test8() { object [][,]? u8 = new object [][,] {null, new object[,] {{null}}}; u8[0] = null; u8[0][0,0] = null; u8[0][0,0].ToString(); } void Test9() { object [,]?[]? u9 = new object [,]?[] {null, new object[,] {{null}}}; u9[0] = null; u9[0][0,0] = null; u9[0][0,0].ToString(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (16,53): warning CS8625: Cannot convert null literal to non-nullable reference type. // new object[,] {{null}}}; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 53), // (18,9): warning CS8602: Dereference of a possibly null reference. // u6[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u6[0]").WithLocation(18, 9), // (18,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u6[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(18, 22), // (19,9): warning CS8602: Dereference of a possibly null reference. // u6[0][0,0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u6[0]").WithLocation(19, 9), // (24,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // var u7 = new object [][,] {null, Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(24, 36), // (25,52): warning CS8625: Cannot convert null literal to non-nullable reference type. // new object[,] {{null}}}; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(25, 52), // (26,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // u7[0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(26, 17), // (27,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u7[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(27, 22), // (32,46): warning CS8625: Cannot convert null literal to non-nullable reference type. // object [][,]? u8 = new object [][,] {null, Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(32, 46), // (33,53): warning CS8625: Cannot convert null literal to non-nullable reference type. // new object[,] {{null}}}; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(33, 53), // (34,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // u8[0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(34, 17), // (35,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u8[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(35, 22), // (42,54): warning CS8625: Cannot convert null literal to non-nullable reference type. // new object[,] {{null}}}; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(42, 54), // (44,9): warning CS8602: Dereference of a possibly null reference. // u9[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u9[0]").WithLocation(44, 9), // (44,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u9[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(44, 22), // (45,9): warning CS8602: Dereference of a possibly null reference. // u9[0][0,0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u9[0]").WithLocation(45, 9) ); } [Fact] public void Array_09() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0<string?> x1, CL0<string> y1) { var u1 = new [] { x1, y1 }; var a1 = new [] { y1, x1 }; var v1 = new CL0<string?>[] { x1, y1 }; var w1 = new CL0<string>[] { x1, y1 }; } } class CL0<T> {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,27): warning CS8619: Nullability of reference types in value of type 'CL0<string?>' doesn't match target type 'CL0<string>'. // var u1 = new [] { x1, y1 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("CL0<string?>", "CL0<string>").WithLocation(10, 27), // (11,31): warning CS8619: Nullability of reference types in value of type 'CL0<string?>' doesn't match target type 'CL0<string>'. // var a1 = new [] { y1, x1 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("CL0<string?>", "CL0<string>").WithLocation(11, 31), // (12,43): warning CS8619: Nullability of reference types in value of type 'CL0<string>' doesn't match target type 'CL0<string?>'. // var v1 = new CL0<string?>[] { x1, y1 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("CL0<string>", "CL0<string?>").WithLocation(12, 43), // (13,38): warning CS8619: Nullability of reference types in value of type 'CL0<string?>' doesn't match target type 'CL0<string>'. // var w1 = new CL0<string>[] { x1, y1 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("CL0<string?>", "CL0<string>").WithLocation(13, 38) ); } [Fact] public void Array_10() { var source = @"class C { static void F1<T>() { T[] a1; a1 = new T[] { default }; // 1 a1 = new T[] { default(T) }; // 2 } static void F2<T>() where T : class { T[] a2; a2 = new T[] { null }; // 3 a2 = new T[] { default }; // 4 a2 = new T[] { default(T) }; // 5 } static void F3<T>() where T : struct { T[] a3; a3 = new T[] { default }; a3 = new T[] { default(T) }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,24): warning CS8601: Possible null reference assignment. // a1 = new T[] { default }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(6, 24), // (7,24): warning CS8601: Possible null reference assignment. // a1 = new T[] { default(T) }; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default(T)").WithLocation(7, 24), // (12,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // a2 = new T[] { null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 24), // (13,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // a2 = new T[] { default }; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(13, 24), // (14,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // a2 = new T[] { default(T) }; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default(T)").WithLocation(14, 24) ); } [Fact] public void ImplicitlyTypedArrayCreation_01() { var source = @"class C { static void F(object x, object? y) { var a = new[] { x, x }; a.ToString(); a[0].ToString(); var b = new[] { x, y }; b.ToString(); b[0].ToString(); var c = new[] { b }; c[0].ToString(); c[0][0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // b[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0]").WithLocation(10, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // c[0][0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[0][0]").WithLocation(13, 9)); } [Fact] [WorkItem(33346, "https://github.com/dotnet/roslyn/issues/33346")] [WorkItem(30376, "https://github.com/dotnet/roslyn/issues/30376")] public void ImplicitlyTypedArrayCreation_02() { var source = @"class C { static void F(object x, object? y) { var a = new[] { x }; a[0].ToString(); var b = new[] { y }; b[0].ToString(); // 1 } static void F(object[] a, object?[] b) { var c = new[] { a, b }; c[0][0].ToString(); // 2 var d = new[] { a, b! }; d[0][0].ToString(); // 3 var e = new[] { b!, a }; e[0][0].ToString(); // 4 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // b[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0]").WithLocation(8, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // c[0][0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[0][0]").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // d[0][0].ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d[0][0]").WithLocation(15, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // e[0][0].ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e[0][0]").WithLocation(17, 9) ); } [Fact, WorkItem(30376, "https://github.com/dotnet/roslyn/issues/30376")] public void ImplicitlyTypedArrayCreation_02_TopLevelNullability() { var source = @"class C { static void F(object? y) { var b = new[] { y! }; b[0].ToString(); } static void F(object[]? a, object?[]? b) { var c = new[] { a, b }; _ = c[0].Length; var d = new[] { a, b! }; _ = d[0].Length; var e = new[] { b!, a }; _ = e[0].Length; var f = new[] { b!, a! }; _ = f[0].Length; var g = new[] { a!, b! }; _ = g[0].Length; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = c[0].Length; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[0]").WithLocation(11, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = d[0].Length; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d[0]").WithLocation(13, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // _ = e[0].Length; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e[0]").WithLocation(15, 13)); } [Fact] public void ImplicitlyTypedArrayCreation_03() { var source = @"class C { static void F(object x, object? y) { (new[] { x, x })[1].ToString(); (new[] { y, x })[1].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, x })[1].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, x })[1]").WithLocation(6, 9)); } [Fact] public void ImplicitlyTypedArrayCreation_04() { var source = @"class C { static void F() { object? o = new object(); var a = new[] { o }; a[0].ToString(); var b = new[] { a }; b[0][0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedArrayCreation_05() { var source = @"class C { static void F(int n) { object? o = new object(); while (n-- > 0) { var a = new[] { o }; a[0].ToString(); var b = new[] { a }; b[0][0].ToString(); o = null; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // a[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a[0]").WithLocation(9, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // b[0][0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0][0]").WithLocation(11, 13)); } [Fact] public void ImplicitlyTypedArrayCreation_06() { var source = @"class C { static void F(string s) { var a = new[] { new object(), (string)null }; a[0].ToString(); var b = new[] { (object)null, s }; b[0].ToString(); var c = new[] { s, (object)null }; c[0].ToString(); var d = new[] { (string)null, new object() }; d[0].ToString(); var e = new[] { new object(), (string)null! }; e[0].ToString(); var f = new[] { (object)null!, s }; f[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,39): warning CS8600: Converting null literal or possible null value to non-nullable type. // var a = new[] { new object(), (string)null }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(5, 39), // (6,9): warning CS8602: Dereference of a possibly null reference. // a[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a[0]").WithLocation(6, 9), // (7,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // var b = new[] { (object)null, s }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)null").WithLocation(7, 25), // (8,9): warning CS8602: Dereference of a possibly null reference. // b[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0]").WithLocation(8, 9), // (9,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // var c = new[] { s, (object)null }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)null").WithLocation(9, 28), // (10,9): warning CS8602: Dereference of a possibly null reference. // c[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[0]").WithLocation(10, 9), // (11,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // var d = new[] { (string)null, new object() }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(11, 25), // (12,9): warning CS8602: Dereference of a possibly null reference. // d[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d[0]").WithLocation(12, 9)); } [Fact] public void ImplicitlyTypedArrayCreation_NestedNullability_Derived() { var source0 = @"public class A { public static B<object> F; } public class B<T> { } public class C0 : B<object> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C1 : B<object?> { } class C2 : B<object> { } class Program { static void F(B<object?> x, B<object> y, C0 cz, C1 cx, C2 cy) { var z = A.F/*T:B<object>!*/; object o; o = (new[] { x, cx })[0]/*B<object?>*/; o = (new[] { x, cy })[0]/*B<object>*/; // 1 o = (new[] { x, cz })[0]/*B<object?>*/; o = (new[] { y, cx })[0]/*B<object>*/; // 2 o = (new[] { cy, y })[0]/*B<object!>*/; o = (new[] { cz, y })[0]/*B<object!>*/; o = (new[] { cx, z })[0]/*B<object?>*/; o = (new[] { cy, z })[0]/*B<object!>*/; o = (new[] { cz, z })[0]/*B<object>*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (10,25): warning CS8619: Nullability of reference types in value of type 'C2' doesn't match target type 'B<object?>'. // o = (new[] { x, cy })[0]/*B<object>*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "cy").WithArguments("C2", "B<object?>").WithLocation(10, 25), // (12,25): warning CS8619: Nullability of reference types in value of type 'C1' doesn't match target type 'B<object>'. // o = (new[] { y, cx })[0]/*B<object>*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "cx").WithArguments("C1", "B<object>").WithLocation(12, 25) ); comp.VerifyTypes(); } [Fact] [WorkItem(29888, "https://github.com/dotnet/roslyn/issues/29888")] public void ImplicitlyTypedArrayCreation_08() { var source = @"class C<T> { } class C { static void F(C<object>? a, C<object?> b) { if (a == null) { var c = new[] { a, b }; c[0].ToString(); var d = new[] { b, a }; d[0].ToString(); } else { var c = new[] { a, b }; c[0].ToString(); var d = new[] { b, a }; d[0].ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,32): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var c = new[] { a, b }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b").WithArguments("C<object?>", "C<object>").WithLocation(8, 32), // (9,13): warning CS8602: Dereference of a possibly null reference. // c[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[0]").WithLocation(9, 13), // (10,29): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var d = new[] { b, a }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b").WithArguments("C<object?>", "C<object>").WithLocation(10, 29), // (11,13): warning CS8602: Dereference of a possibly null reference. // d[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d[0]").WithLocation(11, 13), // (15,32): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var c = new[] { a, b }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b").WithArguments("C<object?>", "C<object>").WithLocation(15, 32), // (17,29): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var d = new[] { b, a }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b").WithArguments("C<object?>", "C<object>").WithLocation(17, 29) ); } [Fact] public void ImplicitlyTypedArrayCreation_09() { var source = @"class C { static void F(C x1, Unknown? y1) { var a1 = new[] { x1, y1 }; a1[0].ToString(); var b1 = new[] { y1, x1 }; b1[0].ToString(); } static void G(C? x2, Unknown y2) { var a2 = new[] { x2, y2 }; a2[0].ToString(); var b2 = new[] { y2, x2 }; b2[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,26): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // static void G(C? x2, Unknown y2) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(10, 26), // (3,25): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // static void F(C x1, Unknown? y1) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(3, 25), // (5,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { x1, y1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x1, y1 }").WithLocation(5, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var b1 = new[] { y1, x1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { y1, x1 }").WithLocation(7, 18)); } [Fact] public void ImplicitlyTypedArrayCreation_TopLevelNullability_01() { var source0 = @"public class A { public static object F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F(object? x, object y) { var z = A.F/*T:object!*/; object? o; o = (new[] { x, x })[0]/*T:object?*/; o = (new[] { x, y })[0]/*T:object?*/; o = (new[] { x, z })[0]/*T:object?*/; o = (new[] { y, x })[0]/*T:object?*/; o = (new[] { y, y })[0]/*T:object!*/; o = (new[] { y, z })[0]/*T:object!*/; o = (new[] { z, x })[0]/*T:object?*/; o = (new[] { z, y })[0]/*T:object!*/; o = (new[] { z, z })[0]/*T:object!*/; o = (new[] { x, y, z })[0]/*T:object?*/; o = (new[] { z, y, x })[0]/*T:object?*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void ImplicitlyTypedArrayCreation_TopLevelNullability_02() { var source = @"class C { static void F<T, U>(T t, U u) where T : class? where U : class, T { object? o; o = (new[] { t, t })[0]/*T:T*/; o = (new[] { t, u })[0]/*T:T*/; o = (new[] { u, t })[0]/*T:T*/; o = (new[] { u, u })[0]/*T:U!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] [Fact] public void ImplicitlyTypedArrayCreation_NestedNullability_Invariant() { var source0 = @"public class A { public static B<object> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class Program { static void F(bool b, B<object?> x, B<object> y) { var z = A.F/*T:B<object>!*/; object o; o = (new[] { x, y })[0]/*T:B<object!>!*/; // 1 o = (new[] { x, z })[0]/*T:B<object?>!*/; o = (new[] { y, x })[0]/*T:B<object!>!*/; // 2 o = (new[] { y, z })[0]/*T:B<object!>!*/; o = (new[] { z, x })[0]/*T:B<object?>!*/; o = (new[] { z, y })[0]/*T:B<object!>!*/; o = (new[] { x, y, z })[0]/*T:B<object!>!*/; // 3 o = (new[] { z, y, x })[0]/*T:B<object!>!*/; // 4 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (7,22): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // o = (new[] { x, y })[0]/*T:B<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(7, 22), // (9,25): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // o = (new[] { y, x })[0]/*T:B<object!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(9, 25), // (13,22): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // o = (new[] { x, y, z })[0]/*T:B<object!>!*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(13, 22), // (14,28): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // o = (new[] { z, y, x })[0]/*T:B<object!>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(14, 28) ); comp.VerifyTypes(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] public void ImplicitlyTypedArrayCreation_NestedNullability_Variant_01() { var source0 = @"public class A { public static I<object> F; public static IIn<object> FIn; public static IOut<object> FOut; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F(I<object> x, I<object?> y) { var z = A.F/*T:I<object>!*/; object o; o = (new[] { x, x })[0]/*T:I<object!>!*/; o = (new[] { x, y })[0]/*T:I<object!>!*/; // 1 o = (new[] { x, z })[0]/*T:I<object!>!*/; o = (new[] { y, x })[0]/*T:I<object!>!*/; // 2 o = (new[] { y, y })[0]/*T:I<object?>!*/; o = (new[] { y, z })[0]/*T:I<object?>!*/; o = (new[] { z, x })[0]/*T:I<object!>!*/; o = (new[] { z, y })[0]/*T:I<object?>!*/; o = (new[] { z, z })[0]/*T:I<object>!*/; } static void F(IIn<object> x, IIn<object?> y) { var z = A.FIn/*T:IIn<object>!*/; object o; o = (new[] { x, x })[0]/*T:IIn<object!>!*/; o = (new[] { x, y })[0]/*T:IIn<object!>!*/; o = (new[] { x, z })[0]/*T:IIn<object!>!*/; o = (new[] { y, x })[0]/*T:IIn<object!>!*/; o = (new[] { y, y })[0]/*T:IIn<object?>!*/; o = (new[] { y, z })[0]/*T:IIn<object>!*/; o = (new[] { z, x })[0]/*T:IIn<object!>!*/; o = (new[] { z, y })[0]/*T:IIn<object>!*/; o = (new[] { z, z })[0]/*T:IIn<object>!*/; } static void F(IOut<object> x, IOut<object?> y) { var z = A.FOut/*T:IOut<object>!*/; object o; o = (new[] { x, x })[0]/*T:IOut<object!>!*/; o = (new[] { x, y })[0]/*T:IOut<object?>!*/; o = (new[] { x, z })[0]/*T:IOut<object>!*/; o = (new[] { y, x })[0]/*T:IOut<object?>!*/; o = (new[] { y, y })[0]/*T:IOut<object?>!*/; o = (new[] { y, z })[0]/*T:IOut<object?>!*/; o = (new[] { z, x })[0]/*T:IOut<object>!*/; o = (new[] { z, y })[0]/*T:IOut<object?>!*/; o = (new[] { z, z })[0]/*T:IOut<object>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,25): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // o = (new[] { x, y })[0]/*T:I<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(8, 25), // (10,22): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // o = (new[] { y, x })[0]/*T:I<object!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(10, 22) ); comp.VerifyTypes(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] public void ImplicitlyTypedArrayCreation_NestedNullability_Variant_02() { var source0 = @"public class A { public static I<string> F; public static IIn<string> FIn; public static IOut<string> FOut; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static I<T> Create1<T>(T t) => throw null!; static void G1(I<IOut<string?>> x1, I<IOut<string>> y1) { var z1 = Create1(A.FOut)/*T:I<IOut<string>!>!*/; object o; o = (new [] { x1, x1 })[0]/*T:I<IOut<string?>!>!*/; o = (new [] { x1, y1 })[0]/*T:I<IOut<string!>!>!*/; // 1 o = (new [] { x1, z1 })[0]/*T:I<IOut<string?>!>!*/; o = (new [] { y1, x1 })[0]/*T:I<IOut<string!>!>!*/; // 2 o = (new [] { y1, y1 })[0]/*T:I<IOut<string!>!>!*/; o = (new [] { y1, z1 })[0]/*T:I<IOut<string!>!>!*/; o = (new [] { z1, x1 })[0]/*T:I<IOut<string?>!>!*/; o = (new [] { z1, y1 })[0]/*T:I<IOut<string!>!>!*/; o = (new [] { z1, z1 })[0]/*T:I<IOut<string>!>!*/; } static IOut<T> Create2<T>(T t) => throw null!; static void G2(IOut<IIn<string?>> x2, IOut<IIn<string>> y2) { var z2 = Create2(A.FIn)/*T:IOut<IIn<string>!>!*/; object o; o = (new [] { x2, x2 })[0]/*T:IOut<IIn<string?>!>!*/; o = (new [] { x2, y2 })[0]/*T:IOut<IIn<string!>!>!*/; o = (new [] { x2, z2 })[0]/*T:IOut<IIn<string>!>!*/; o = (new [] { y2, x2 })[0]/*T:IOut<IIn<string!>!>!*/; o = (new [] { y2, y2 })[0]/*T:IOut<IIn<string!>!>!*/; o = (new [] { y2, z2 })[0]/*T:IOut<IIn<string!>!>!*/; o = (new [] { z2, x2 })[0]/*T:IOut<IIn<string>!>!*/; o = (new [] { z2, y2 })[0]/*T:IOut<IIn<string!>!>!*/; o = (new [] { z2, z2 })[0]/*T:IOut<IIn<string>!>!*/; } static IIn<T> Create3<T>(T t) => throw null!; static void G3(IIn<IOut<string?>> x3, IIn<IOut<string>> y3) { var z3 = Create3(A.FOut)/*T:IIn<IOut<string>!>!*/; object o; o = (new [] { x3, x3 })[0]/*T:IIn<IOut<string?>!>!*/; o = (new [] { x3, y3 })[0]/*T:IIn<IOut<string!>!>!*/; o = (new [] { x3, z3 })[0]/*T:IIn<IOut<string>!>!*/; o = (new [] { y3, x3 })[0]/*T:IIn<IOut<string!>!>!*/; o = (new [] { y3, y3 })[0]/*T:IIn<IOut<string!>!>!*/; o = (new [] { y3, z3 })[0]/*T:IIn<IOut<string!>!>!*/; o = (new [] { z3, x3 })[0]/*T:IIn<IOut<string>!>!*/; o = (new [] { z3, y3 })[0]/*T:IIn<IOut<string!>!>!*/; o = (new [] { z3, z3 })[0]/*T:IIn<IOut<string>!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (10,23): warning CS8619: Nullability of reference types in value of type 'I<IOut<string?>>' doesn't match target type 'I<IOut<string>>'. // o = (new [] { x1, y1 })[0]/*T:I<IOut<string!>!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("I<IOut<string?>>", "I<IOut<string>>").WithLocation(10, 23), // (12,27): warning CS8619: Nullability of reference types in value of type 'I<IOut<string?>>' doesn't match target type 'I<IOut<string>>'. // o = (new [] { y1, x1 })[0]/*T:I<IOut<string!>!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("I<IOut<string?>>", "I<IOut<string>>").WithLocation(12, 27) ); comp.VerifyTypes(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] public void ImplicitlyTypedArrayCreation_NestedNullability_Variant_03() { var source0 = @"public class A { public static object F1; public static string F2; public static B<object>.INone BON; public static B<object>.I<string> BOI; public static B<object>.IIn<string> BOIIn; public static B<object>.IOut<string> BOIOut; } public class B<T> { public interface INone { } public interface I<U> { } public interface IIn<in U> { } public interface IOut<out U> { } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static void G0(B<object>.INone x0, B<object?>.INone y0) { var z0 = A.BON/*T:B<object>.INone!*/; object o; o = (new[] { x0, x0 })[0]/*T:B<object!>.INone!*/; o = (new[] { x0, y0 })[0]/*T:B<object!>.INone!*/; // 1 o = (new[] { x0, z0 })[0]/*T:B<object!>.INone!*/; o = (new[] { y0, x0 })[0]/*T:B<object!>.INone!*/; // 2 o = (new[] { y0, y0 })[0]/*T:B<object?>.INone!*/; o = (new[] { y0, z0 })[0]/*T:B<object?>.INone!*/; o = (new[] { z0, x0 })[0]/*T:B<object!>.INone!*/; o = (new[] { z0, y0 })[0]/*T:B<object?>.INone!*/; o = (new[] { z0, z0 })[0]/*T:B<object>.INone!*/; } static void G1(B<object>.I<string> x1, B<object?>.I<string?> y1) { var z1 = A.BOI/*T:B<object>.I<string>!*/; object o; o = (new[] { x1, x1 })[0]/*T:B<object!>.I<string!>!*/; o = (new[] { x1, y1 })[0]/*T:B<object!>.I<string!>!*/; // 3 o = (new[] { x1, z1 })[0]/*T:B<object!>.I<string!>!*/; o = (new[] { y1, x1 })[0]/*T:B<object!>.I<string!>!*/; // 4 o = (new[] { y1, y1 })[0]/*T:B<object?>.I<string?>!*/; o = (new[] { y1, z1 })[0]/*T:B<object?>.I<string?>!*/; o = (new[] { z1, x1 })[0]/*T:B<object!>.I<string!>!*/; o = (new[] { z1, y1 })[0]/*T:B<object?>.I<string?>!*/; o = (new[] { z1, z1 })[0]/*T:B<object>.I<string>!*/; } static void G2(B<object>.IIn<string> x2, B<object?>.IIn<string?> y2) { var z2 = A.BOIIn/*T:B<object>.IIn<string>!*/; object o; o = (new[] { x2, x2 })[0]/*T:B<object!>.IIn<string!>!*/; o = (new[] { x2, y2 })[0]/*T:B<object!>.IIn<string!>!*/; // 5 o = (new[] { x2, z2 })[0]/*T:B<object!>.IIn<string!>!*/; o = (new[] { y2, x2 })[0]/*T:B<object!>.IIn<string!>!*/; // 6 o = (new[] { y2, y2 })[0]/*T:B<object?>.IIn<string?>!*/; o = (new[] { y2, z2 })[0]/*T:B<object?>.IIn<string>!*/; o = (new[] { z2, x2 })[0]/*T:B<object!>.IIn<string!>!*/; o = (new[] { z2, y2 })[0]/*T:B<object?>.IIn<string>!*/; o = (new[] { z2, z2 })[0]/*T:B<object>.IIn<string>!*/; } static void G3(B<object>.IOut<string> x3, B<object?>.IOut<string?> y3) { var z3 = A.BOIOut/*T:B<object>.IOut<string>!*/; object o; o = (new[] { x3, x3 })[0]/*T:B<object!>.IOut<string!>!*/; o = (new[] { x3, y3 })[0]/*T:B<object!>.IOut<string?>!*/; // 7 o = (new[] { x3, z3 })[0]/*T:B<object!>.IOut<string>!*/; o = (new[] { y3, x3 })[0]/*T:B<object!>.IOut<string?>!*/; // 8 o = (new[] { y3, y3 })[0]/*T:B<object?>.IOut<string?>!*/; o = (new[] { y3, z3 })[0]/*T:B<object?>.IOut<string?>!*/; o = (new[] { z3, x3 })[0]/*T:B<object!>.IOut<string>!*/; o = (new[] { z3, y3 })[0]/*T:B<object?>.IOut<string?>!*/; o = (new[] { z3, z3 })[0]/*T:B<object>.IOut<string>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (9,26): warning CS8619: Nullability of reference types in value of type 'B<object?>.INone' doesn't match target type 'B<object>.INone'. // o = (new[] { x0, y0 })[0]/*T:B<object!>.INone!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y0").WithArguments("B<object?>.INone", "B<object>.INone").WithLocation(9, 26), // (11,22): warning CS8619: Nullability of reference types in value of type 'B<object?>.INone' doesn't match target type 'B<object>.INone'. // o = (new[] { y0, x0 })[0]/*T:B<object!>.INone!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y0").WithArguments("B<object?>.INone", "B<object>.INone").WithLocation(11, 22), // (23,26): warning CS8619: Nullability of reference types in value of type 'B<object?>.I<string?>' doesn't match target type 'B<object>.I<string>'. // o = (new[] { x1, y1 })[0]/*T:B<object!>.I<string!>!*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("B<object?>.I<string?>", "B<object>.I<string>").WithLocation(23, 26), // (25,22): warning CS8619: Nullability of reference types in value of type 'B<object?>.I<string?>' doesn't match target type 'B<object>.I<string>'. // o = (new[] { y1, x1 })[0]/*T:B<object!>.I<string!>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("B<object?>.I<string?>", "B<object>.I<string>").WithLocation(25, 22), // (37,26): warning CS8619: Nullability of reference types in value of type 'B<object?>.IIn<string?>' doesn't match target type 'B<object>.IIn<string>'. // o = (new[] { x2, y2 })[0]/*T:B<object!>.IIn<string!>!*/; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y2").WithArguments("B<object?>.IIn<string?>", "B<object>.IIn<string>").WithLocation(37, 26), // (39,22): warning CS8619: Nullability of reference types in value of type 'B<object?>.IIn<string?>' doesn't match target type 'B<object>.IIn<string>'. // o = (new[] { y2, x2 })[0]/*T:B<object!>.IIn<string!>!*/; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y2").WithArguments("B<object?>.IIn<string?>", "B<object>.IIn<string>").WithLocation(39, 22), // (51,26): warning CS8619: Nullability of reference types in value of type 'B<object?>.IOut<string?>' doesn't match target type 'B<object>.IOut<string?>'. // o = (new[] { x3, y3 })[0]/*T:B<object!>.IOut<string?>!*/; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y3").WithArguments("B<object?>.IOut<string?>", "B<object>.IOut<string?>").WithLocation(51, 26), // (53,22): warning CS8619: Nullability of reference types in value of type 'B<object?>.IOut<string?>' doesn't match target type 'B<object>.IOut<string?>'. // o = (new[] { y3, x3 })[0]/*T:B<object!>.IOut<string?>!*/; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y3").WithArguments("B<object?>.IOut<string?>", "B<object>.IOut<string?>").WithLocation(53, 22)); comp.VerifyTypes(); } [Fact] public void ImplicitlyTypedArrayCreation_NestedNullability_Tuples() { var source0 = @"public class A { public static object F; public static I<object> IF; } public interface I<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F1(bool b, object x1, object? y1) { var z1 = A.F/*T:object!*/; object o; o = (new[] { (x1, x1), (x1, y1) })[0]/*T:(object!, object?)*/; o = (new[] { (z1, x1), (x1, x1) })[0]/*T:(object!, object!)*/; o = (new[] { (y1, y1), (y1, z1) })[0]/*T:(object?, object?)*/; o = (new[] { (x1, y1), (y1, y1) })[0]/*T:(object?, object?)*/; o = (new[] { (z1, z1), (z1, x1) })[0]/*T:(object!, object!)*/; o = (new[] { (y1, z1), (z1, z1) })[0]/*T:(object?, object!)*/; } static void F2(bool b, I<object> x2, I<object?> y2) { var z2 = A.IF/*T:I<object>!*/; object o; o = (new[] { (x2, x2), (x2, y2) })[0]/*T:(I<object!>!, I<object!>!)*/; // 1 o = (new[] { (z2, x2), (x2, x2) })[0]/*T:(I<object!>!, I<object!>!)*/; o = (new[] { (y2, y2), (y2, z2) })[0]/*T:(I<object?>!, I<object?>!)*/; o = (new[] { (x2, y2), (y2, y2) })[0]/*T:(I<object!>!, I<object?>!)*/; // 2 o = (new[] { (z2, z2), (z2, x2) })[0]/*T:(I<object>!, I<object!>!)*/; o = (new[] { (y2, z2), (z2, z2) })[0]/*T:(I<object?>!, I<object>!)*/; o = (new[] { (x2, x2)!, (x2, y2) })[0]/*T:(I<object!>!, I<object!>!)*/; // 3 o = (new[] { (x2, y2), (y2, y2)! })[0]/*T:(I<object!>!, I<object?>!)*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (18,32): warning CS8619: Nullability of reference types in value of type '(I<object> x2, I<object?> y2)' doesn't match target type '(I<object>, I<object>)'. // o = (new[] { (x2, x2), (x2, y2) })[0]/*T:(I<object!>!, I<object!>!)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x2, y2)").WithArguments("(I<object> x2, I<object?> y2)", "(I<object>, I<object>)").WithLocation(18, 32), // (21,32): warning CS8619: Nullability of reference types in value of type '(I<object?>, I<object?>)' doesn't match target type '(I<object>, I<object?>)'. // o = (new[] { (x2, y2), (y2, y2) })[0]/*T:(I<object!>!, I<object?>!)*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(y2, y2)").WithArguments("(I<object?>, I<object?>)", "(I<object>, I<object?>)").WithLocation(21, 32), // (25,33): warning CS8619: Nullability of reference types in value of type '(I<object> x2, I<object?> y2)' doesn't match target type '(I<object>, I<object>)'. // o = (new[] { (x2, x2)!, (x2, y2) })[0]/*T:(I<object!>!, I<object!>!)*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x2, y2)").WithArguments("(I<object> x2, I<object?> y2)", "(I<object>, I<object>)").WithLocation(25, 33)); comp.VerifyTypes(); } [Fact] public void ImplicitlyTypedArrayCreation_Empty() { var source = @"class Program { static void Main() { var a = new[] { }; var b = new[] { null }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS0826: No best type found for implicitly-typed array // var a = new[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { }").WithLocation(5, 17), // (6,17): error CS0826: No best type found for implicitly-typed array // var b = new[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { null }").WithLocation(6, 17)); } [Fact, WorkItem(36132, "https://github.com/dotnet/roslyn/issues/36132")] public void ImplicitlyTypedArrayCreation_UsesNullabilitiesOfConvertedTypes() { var source = @" class A { } class B { public static implicit operator A(B? b) => new A(); } class C { public static implicit operator A?(C c) => new A(); } class D { void Test(A a, B? b, C c) { _ = (new A[] { a, b }) /*T:A![]!*/; _ = (new A?[] { a, b }) /*T:A?[]!*/; _ = (new[] { a, b }) /*T:A![]!*/; _ = (new[] { b, a }) /*T:A![]!*/; _ = (new A[] { a, c }) /*T:A![]!*/; // 1 _ = (new A?[] { a, c }) /*T:A?[]!*/; _ = (new[] { a, c }) /*T:A?[]!*/; _ = (new[] { c, a }) /*T:A?[]!*/; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (15,27): warning CS8601: Possible null reference assignment. // _ = (new A[] { a, c }) /*T:A![]!*/; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c").WithLocation(15, 27) ); comp.VerifyTypes(); } [Fact, WorkItem(36132, "https://github.com/dotnet/roslyn/issues/36132")] public void Ternary_UsesNullabilitiesOfConvertedTypes() { var source = @" class A { } class B { public static implicit operator A(B? b) => new A(); } class C { public static implicit operator A?(C c) => new A(); } class D { void Test(A a, B? b, C c, bool cond) { _ = (cond ? a : b) /*T:A!*/; _ = (cond ? b : a) /*T:A!*/; _ = (cond ? a : c) /*T:A?*/; _ = (cond ? c : a) /*T:A?*/; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact, WorkItem(36132, "https://github.com/dotnet/roslyn/issues/36132")] public void ReturnTypeInference_UsesNullabilitiesOfConvertedTypes() { var source = @" using System; class A { } class B { public static implicit operator A(B? b) => new A(); } class C { public static implicit operator A?(C c) => new A(); } class D { void Test(A a, B? b, C c, bool cond) { Func<A> x1 = () => { if (cond) return a; else return b; }; Func<A> x2 = () => { if (cond) return b; else return a; }; Func<A?> x3 = () => { if (cond) return a; else return c; }; Func<A?> x4 = () => { if (cond) return c; else return a; }; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void ExplicitlyTypedArrayCreation() { var source = @"class C { static void F(object x, object? y) { var a = new object[] { x, y }; a[0].ToString(); var b = new object?[] { x, y }; b[0].ToString(); var c = new object[] { x, y! }; c[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,35): warning CS8601: Possible null reference assignment. // var a = new object[] { x, y }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(5, 35), // (8,9): warning CS8602: Dereference of a possibly null reference. // b[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0]").WithLocation(8, 9)); } [Fact] public void IdentityConversion_ArrayInitializer_02() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(I<object> x, I<object?> y, I<object>? z, I<object?>? w) { (new[] { x, y })[0].ToString(); // A1 (new[] { x, z })[0].ToString(); // A2 (new[] { x, w })[0].ToString(); // A3 (new[] { y, z })[0].ToString(); // A4 (new[] { y, w })[0].ToString(); // A5 (new[] { w, z })[0].ToString(); // A6 } static void F(IIn<object> x, IIn<object?> y, IIn<object>? z, IIn<object?>? w) { (new[] { x, y })[0].ToString(); // B1 (new[] { x, z })[0].ToString(); // B2 (new[] { x, w })[0].ToString(); // B3 (new[] { y, z })[0].ToString(); // B4 (new[] { y, w })[0].ToString(); // B5 (new[] { w, z })[0].ToString(); // B6 } static void F(IOut<object> x, IOut<object?> y, IOut<object>? z, IOut<object?>? w) { (new[] { x, y })[0].ToString(); // C1 (new[] { x, z })[0].ToString(); // C2 (new[] { x, w })[0].ToString(); // C3 (new[] { y, z })[0].ToString(); // C4 (new[] { y, w })[0].ToString(); // C5 (new[] { w, z })[0].ToString(); // C6 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,21): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // (new[] { x, y })[0].ToString(); // A1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(8, 21), // (9,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, z })[0].ToString(); // A2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, z })[0]").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, w })[0].ToString(); // A3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, w })[0]").WithLocation(10, 9), // (10,21): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // (new[] { x, w })[0].ToString(); // A3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("I<object?>", "I<object>").WithLocation(10, 21), // (11,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, z })[0].ToString(); // A4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, z })[0]").WithLocation(11, 9), // (11,18): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // (new[] { y, z })[0].ToString(); // A4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(11, 18), // (12,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, w })[0].ToString(); // A5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, w })[0]").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // (new[] { w, z })[0].ToString(); // A6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { w, z })[0]").WithLocation(13, 9), // (13,18): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // (new[] { w, z })[0].ToString(); // A6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("I<object?>", "I<object>").WithLocation(13, 18), // (18,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, z })[0].ToString(); // B2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, z })[0]").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, w })[0].ToString(); // B3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, w })[0]").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, z })[0].ToString(); // B4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, z })[0]").WithLocation(20, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, w })[0].ToString(); // B5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, w })[0]").WithLocation(21, 9), // (22,9): warning CS8602: Dereference of a possibly null reference. // (new[] { w, z })[0].ToString(); // B6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { w, z })[0]").WithLocation(22, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, z })[0].ToString(); // C2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, z })[0]").WithLocation(27, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, w })[0].ToString(); // C3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, w })[0]").WithLocation(28, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, z })[0].ToString(); // C4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, z })[0]").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, w })[0].ToString(); // C5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, w })[0]").WithLocation(30, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // (new[] { w, z })[0].ToString(); // C6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { w, z })[0]").WithLocation(31, 9) ); } [Fact] public void IdentityConversion_ArrayInitializer_IsNullableNull() { var source0 = @"#pragma warning disable 8618 public class A<T> { public T F; } public class B : A<object> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F(object? x, B b) { var y = b.F/*T:object!*/; (new[] { x, x! })[0].ToString(); // 1 (new[] { x!, x })[0].ToString(); // 2 (new[] { x!, x! })[0].ToString(); (new[] { y, y! })[0].ToString(); (new[] { y!, y })[0].ToString(); (new[] { x, y })[0].ToString(); // 3 (new[] { x, y! })[0].ToString(); // 4 (new[] { x!, y })[0].ToString(); (new[] { x!, y! })[0].ToString(); } static void F(A<object?> z, B w) { (new[] { z, z! })[0].F.ToString(); // 5 (new[] { z!, z })[0].F.ToString(); // 6 (new[] { z!, z! })[0].F.ToString(); // 7 (new[] { w, w! })[0].F.ToString(); (new[] { w!, w })[0].F.ToString(); (new[] { z, w })[0].F.ToString(); // 8 (new[] { z, w! })[0].F.ToString(); // 9 (new[] { z!, w })[0].F.ToString(); // 10 (new[] { z!, w! })[0].F.ToString(); // 11 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); // https://github.com/dotnet/roslyn/issues/30376: `!` should suppress conversion warnings. comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, x! })[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, x! })[0]").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x!, x })[0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x!, x })[0]").WithLocation(7, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, y })[0].ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, y })[0]").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, y! })[0].ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, y! })[0]").WithLocation(12, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z, z! })[0].F.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z, z! })[0].F").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z!, z })[0].F.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z!, z })[0].F").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z!, z! })[0].F.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z!, z! })[0].F").WithLocation(20, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z, w })[0].F.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z, w })[0].F").WithLocation(23, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z, w! })[0].F.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z, w! })[0].F").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z!, w })[0].F.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z!, w })[0].F").WithLocation(25, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z!, w! })[0].F.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z!, w! })[0].F").WithLocation(26, 9)); } [Fact] public void IdentityConversion_ArrayInitializer_ExplicitType() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(I<object>? x, I<object?>? y) { I<object?>?[] a = new[] { x }; I<object?>[] b = new[] { y }; I<object>?[] c = new[] { y }; I<object>[] d = new[] { x }; } static void F(IIn<object>? x, IIn<object?>? y) { IIn<object?>?[] a = new[] { x }; IIn<object?>[] b = new[] { y }; IIn<object>?[] c = new[] { y }; IIn<object>[] d = new[] { x }; } static void F(IOut<object>? x, IOut<object?>? y) { IOut<object?>?[] a = new[] { x }; IOut<object?>[] b = new[] { y }; IOut<object>?[] c = new[] { y }; IOut<object>[] d = new[] { x }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,27): warning CS8619: Nullability of reference types in value of type 'I<object>?[]' doesn't match target type 'I<object?>?[]'. // I<object?>?[] a = new[] { x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { x }").WithArguments("I<object>?[]", "I<object?>?[]").WithLocation(8, 27), // (9,26): warning CS8619: Nullability of reference types in value of type 'I<object?>?[]' doesn't match target type 'I<object?>[]'. // I<object?>[] b = new[] { y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { y }").WithArguments("I<object?>?[]", "I<object?>[]").WithLocation(9, 26), // (10,26): warning CS8619: Nullability of reference types in value of type 'I<object?>?[]' doesn't match target type 'I<object>?[]'. // I<object>?[] c = new[] { y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { y }").WithArguments("I<object?>?[]", "I<object>?[]").WithLocation(10, 26), // (11,25): warning CS8619: Nullability of reference types in value of type 'I<object>?[]' doesn't match target type 'I<object>[]'. // I<object>[] d = new[] { x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { x }").WithArguments("I<object>?[]", "I<object>[]").WithLocation(11, 25), // (15,29): warning CS8619: Nullability of reference types in value of type 'IIn<object>?[]' doesn't match target type 'IIn<object?>?[]'. // IIn<object?>?[] a = new[] { x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { x }").WithArguments("IIn<object>?[]", "IIn<object?>?[]").WithLocation(15, 29), // (16,28): warning CS8619: Nullability of reference types in value of type 'IIn<object?>?[]' doesn't match target type 'IIn<object?>[]'. // IIn<object?>[] b = new[] { y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { y }").WithArguments("IIn<object?>?[]", "IIn<object?>[]").WithLocation(16, 28), // (18,27): warning CS8619: Nullability of reference types in value of type 'IIn<object>?[]' doesn't match target type 'IIn<object>[]'. // IIn<object>[] d = new[] { x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { x }").WithArguments("IIn<object>?[]", "IIn<object>[]").WithLocation(18, 27), // (23,29): warning CS8619: Nullability of reference types in value of type 'IOut<object?>?[]' doesn't match target type 'IOut<object?>[]'. // IOut<object?>[] b = new[] { y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { y }").WithArguments("IOut<object?>?[]", "IOut<object?>[]").WithLocation(23, 29), // (24,29): warning CS8619: Nullability of reference types in value of type 'IOut<object?>?[]' doesn't match target type 'IOut<object>?[]'. // IOut<object>?[] c = new[] { y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { y }").WithArguments("IOut<object?>?[]", "IOut<object>?[]").WithLocation(24, 29), // (25,28): warning CS8619: Nullability of reference types in value of type 'IOut<object>?[]' doesn't match target type 'IOut<object>[]'. // IOut<object>[] d = new[] { x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { x }").WithArguments("IOut<object>?[]", "IOut<object>[]").WithLocation(25, 28)); } [Fact] public void ImplicitConversion_ArrayInitializer_ExplicitType_01() { var source = @"class A<T> { } class B<T> : A<T> { } class C { static void F(A<object> x, B<object?> y) { var z = new A<object>[] { x, y }; var w = new A<object?>[] { x, y }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,38): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'A<object>'. // var z = new A<object>[] { x, y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("B<object?>", "A<object>").WithLocation(7, 38), // (8,36): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'A<object?>'. // var w = new A<object?>[] { x, y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "A<object?>").WithLocation(8, 36)); } [Fact] public void ImplicitConversion_ArrayInitializer_ExplicitType_02() { var source = @"interface IIn<in T> { } interface IOut<out T> { } class C { static void F(IIn<object> x, IIn<object?> y) { var a = new IIn<string?>[] { x }; var b = new IIn<string>[] { y }; } static void F(IOut<string> x, IOut<string?> y) { var a = new IOut<object?>[] { x }; var b = new IOut<object>[] { y }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,38): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<string?>'. // var a = new IIn<string?>[] { x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object>", "IIn<string?>").WithLocation(7, 38), // (13,38): warning CS8619: Nullability of reference types in value of type 'IOut<string?>' doesn't match target type 'IOut<object>'. // var b = new IOut<object>[] { y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("IOut<string?>", "IOut<object>").WithLocation(13, 38)); } [Fact] public void MultipleConversions_ArrayInitializer() { var source = @"class A { public static implicit operator C(A a) => new C(); } class B : A { } class C { static void F(B x, C? y) { (new[] { x, y })[0].ToString(); (new[] { y, x })[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, y })[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, y })[0]").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, x })[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, x })[0]").WithLocation(13, 9)); } [Fact] public void MultipleConversions_ArrayInitializer_ConversionWithNullableOutput() { var source = @"class A { public static implicit operator C?(A a) => new C(); } class B : A { } class C { static void F(B x, C y) { (new[] { x, y })[0].ToString(); (new[] { y, x })[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, y })[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, y })[0]").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, x })[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, x })[0]").WithLocation(13, 9)); } [Fact] public void MultipleConversions_ArrayInitializer_ConversionWithNullableInput() { var source = @"class A { public static implicit operator C(A? a) => new C(); } class B : A { } class C { static void F(B? x, C y) { (new[] { x, y })[0].ToString(); (new[] { y, x })[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ObjectInitializer_01() { CSharpCompilation c = CreateCompilation( new[] { @"#pragma warning disable 8618 class C { static void Main() {} void Test1(CL1? x1, CL1? y1) { var z1 = new CL1() { F1 = x1, F2 = y1 }; } void Test2(CL1? x2, CL1? y2) { var z2 = new CL1() { P1 = x2, P2 = y2 }; } void Test3(CL1 x3, CL1 y3) { var z31 = new CL1() { F1 = x3, F2 = y3 }; var z32 = new CL1() { P1 = x3, P2 = y3 }; } } class CL1 { public CL1 F1; public CL1? F2; public CL1 P1 {get; set;} public CL1? P2 {get; set;} } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,35): warning CS8601: Possible null reference assignment. // var z1 = new CL1() { F1 = x1, F2 = y1 }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x1").WithLocation(9, 35), // (14,35): warning CS8601: Possible null reference assignment. // var z2 = new CL1() { P1 = x2, P2 = y2 }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x2").WithLocation(14, 35) ); } [Fact] public void ObjectInitializer_02() { var source = @"class C { C(object o) { } static void F(object? x) { var y = new C(x); if (x != null) y = new C(x); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,23): warning CS8604: Possible null reference argument for parameter 'o' in 'C.C(object o)'. // var y = new C(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("o", "C.C(object o)").WithLocation(6, 23)); } [Fact] public void ObjectInitializer_03() { var source = @"class A { internal B F = new B(); } class B { internal object? G; } class C { static void Main() { var o = new A() { F = { G = new object() } }; o.F.G.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ObjectInitializer_ParameterlessStructConstructor() { var src = @" #nullable enable var s1 = new S1() { }; s1.field.ToString(); var s2 = new S2() { }; s2.field.ToString(); // 1 var s3 = new S3() { }; s3.field.ToString(); public struct S1 { public string field; public S1() { field = string.Empty; } } public struct S2 { public string field; } public struct S3 { public string field = string.Empty; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,1): warning CS8602: Dereference of a possibly null reference. // s2.field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2.field").WithLocation(8, 1) ); } [Fact] public void IdentityConversion_ObjectElementInitializerArgumentsOrder() { var source = @"interface I<T> { } class C { static C F(I<string> x, I<object> y) { return new C() { [ y: y, // warn 1 x: x] = 1 }; } static object G(C c, I<string?> x, I<object?> y) { return new C() { [ y: y, x: x] // warn 2 = 2 }; } int this[I<string> x, I<object?> y] { get { return 0; } set { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,16): warning CS8620: Nullability of reference types in argument of type 'I<object>' doesn't match target type 'I<object?>' for parameter 'y' in 'int C.this[I<string> x, I<object?> y]'. // y: y, // warn 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object>", "I<object?>", "y", "int C.this[I<string> x, I<object?> y]").WithLocation(7, 16), // (15,16): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'x' in 'int C.this[I<string> x, I<object?> y]'. // x: x] // warn 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<string?>", "I<string>", "x", "int C.this[I<string> x, I<object?> y]").WithLocation(15, 16)); } [Fact] public void ImplicitConversion_CollectionInitializer() { var source = @"using System.Collections.Generic; class A<T> { } class B<T> : A<T> { } class C { static void M(B<object>? x, B<object?> y) { var c = new List<A<object>> { x, // 1 y, // 2 }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8604: Possible null reference argument for parameter 'item' in 'void List<A<object>>.Add(A<object> item)'. // x, // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("item", "void List<A<object>>.Add(A<object> item)").WithLocation(10, 13), // (11,13): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'A<object>' for parameter 'item' in 'void List<A<object>>.Add(A<object> item)'. // y, // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("B<object?>", "A<object>", "item", "void List<A<object>>.Add(A<object> item)").WithLocation(11, 13)); } [Fact] public void Structs_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL1 x1) { S1 y1 = new S1(); y1.F1 = x1; y1 = new S1(); x1 = y1.F1; } void M1(ref S1 x) {} void Test2(CL1 x2) { S1 y2 = new S1(); y2.F1 = x2; M1(ref y2); x2 = y2.F1; } void Test3(CL1 x3) { S1 y3 = new S1() { F1 = x3 }; x3 = y3.F1; } void Test4(CL1 x4, CL1? z4) { var y4 = new S2() { F2 = new S1() { F1 = x4, F3 = z4 } }; x4 = y4.F2.F1 ?? x4; x4 = y4.F2.F3; } void Test5(CL1 x5, CL1? z5) { var y5 = new S2() { F2 = new S1() { F1 = x5, F3 = z5 } }; var u5 = y5.F2; x5 = u5.F1 ?? x5; x5 = u5.F3; } } class CL1 { } struct S1 { public CL1? F1; public CL1? F3; } struct S2 { public S1 F2; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = y1.F1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1.F1").WithLocation(12, 14), // (22,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = y2.F1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2.F1").WithLocation(22, 14), // (35,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = y4.F2.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y4.F2.F3").WithLocation(35, 14), // (43,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x5 = u5.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u5.F3").WithLocation(43, 14) ); } [Fact] public void Structs_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL1 x1) { S1 y1; y1.F1 = x1; S1 z1 = y1; x1 = z1.F3; x1 = z1.F3 ?? x1; z1.F3 = null; } struct Test2 { S1 z2 {get;} public Test2(CL1 x2) { S1 y2; y2.F1 = x2; z2 = y2; x2 = z2.F3; x2 = z2.F3 ?? x2; } } void Test3(CL1 x3) { S1 y3; CL1? z3 = y3.F3; x3 = z3; x3 = z3 ?? x3; } void Test4(CL1 x4, CL1? z4) { S1 y4; z4 = y4.F3; x4 = z4; x4 = z4 ?? x4; } void Test5(CL1 x5) { S1 y5; var z5 = new { F3 = y5.F3 }; x5 = z5.F3; x5 = z5.F3 ?? x5; } void Test6(CL1 x6, S1 z6) { S1 y6; y6.F1 = x6; z6 = y6; x6 = z6.F3; x6 = z6.F3 ?? x6; } void Test7(CL1 x7) { S1 y7; y7.F1 = x7; var z7 = new { F3 = y7 }; x7 = z7.F3.F3; x7 = z7.F3.F3 ?? x7; } struct Test8 { CL1? z8 {get;} public Test8(CL1 x8) { S1 y8; y8.F1 = x8; z8 = y8.F3; x8 = z8; x8 = z8 ?? x8; } } } class CL1 { } struct S1 { public CL1? F1; public CL1? F3; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,17): error CS0165: Use of unassigned local variable 'y1' // S1 z1 = y1; Diagnostic(ErrorCode.ERR_UseDefViolation, "y1").WithArguments("y1").WithLocation(11, 17), // (12,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = z1.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z1.F3").WithLocation(12, 14), // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = z1.F3 ?? x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z1.F3 ?? x1").WithLocation(13, 14), // (25,18): error CS0165: Use of unassigned local variable 'y2' // z2 = y2; Diagnostic(ErrorCode.ERR_UseDefViolation, "y2").WithArguments("y2").WithLocation(25, 18), // (26,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = z2.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z2.F3").WithLocation(26, 18), // (27,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = z2.F3 ?? x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z2.F3 ?? x2").WithLocation(27, 18), // (34,19): error CS0170: Use of possibly unassigned field 'F3' // CL1? z3 = y3.F3; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y3.F3").WithArguments("F3").WithLocation(34, 19), // (35,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = z3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z3").WithLocation(35, 14), // (36,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = z3 ?? x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z3 ?? x3").WithLocation(36, 14), // (42,14): error CS0170: Use of possibly unassigned field 'F3' // z4 = y4.F3; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y4.F3").WithArguments("F3").WithLocation(42, 14), // (43,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = z4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z4").WithLocation(43, 14), // (44,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = z4 ?? x4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z4 ?? x4").WithLocation(44, 14), // (50,29): error CS0170: Use of possibly unassigned field 'F3' // var z5 = new { F3 = y5.F3 }; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y5.F3").WithArguments("F3").WithLocation(50, 29), // (51,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x5 = z5.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z5.F3").WithLocation(51, 14), // (52,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x5 = z5.F3 ?? x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z5.F3 ?? x5").WithLocation(52, 14), // (59,14): error CS0165: Use of unassigned local variable 'y6' // z6 = y6; Diagnostic(ErrorCode.ERR_UseDefViolation, "y6").WithArguments("y6").WithLocation(59, 14), // (60,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x6 = z6.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z6.F3").WithLocation(60, 14), // (61,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x6 = z6.F3 ?? x6; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z6.F3 ?? x6").WithLocation(61, 14), // (68,29): error CS0165: Use of unassigned local variable 'y7' // var z7 = new { F3 = y7 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "y7").WithArguments("y7").WithLocation(68, 29), // (69,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x7 = z7.F3.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z7.F3.F3").WithLocation(69, 14), // (70,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x7 = z7.F3.F3 ?? x7; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z7.F3.F3 ?? x7").WithLocation(70, 14), // (81,18): error CS0170: Use of possibly unassigned field 'F3' // z8 = y8.F3; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y8.F3").WithArguments("F3").WithLocation(81, 18), // (82,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x8 = z8; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z8").WithLocation(82, 18), // (83,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x8 = z8 ?? x8; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z8 ?? x8").WithLocation(83, 18) ); } [Fact] public void Structs_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL1 x1) { x1 = new S1().F1; } void Test2(CL1 x2) { x2 = new S1() {F1 = x2}.F1; } void Test3(CL1 x3) { x3 = new S1() {F1 = x3}.F1 ?? x3; } void Test4(CL1 x4) { x4 = new S2().F2; } void Test5(CL1 x5) { x5 = new S2().F2 ?? x5; } } class CL1 { } struct S1 { public CL1? F1; } struct S2 { public CL1 F2; S2(CL1 x) { F2 = x; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = new S1().F1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "new S1().F1").WithLocation(9, 14), // (24,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = new S2().F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "new S2().F2").WithLocation(24, 14) ); } [Fact] public void Structs_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} } struct TS2 { System.Action? E2; TS2(System.Action x2) { this = new TS2(); System.Action z2 = E2; System.Action y2 = E2 ?? x2; } void Dummy() { E2 = null; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action z2 = E2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(15, 28) ); } [Fact] [WorkItem(29889, "https://github.com/dotnet/roslyn/issues/29889")] public void AnonymousTypes_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL1 x1, CL1? z1) { var y1 = new { p1 = x1, p2 = z1 }; x1 = y1.p1 ?? x1; x1 = y1.p2; // 1 } void Test2(CL1 x2, CL1? z2) { var u2 = new { p1 = x2, p2 = z2 }; var v2 = new { p1 = z2, p2 = x2 }; u2 = v2; // 2 x2 = u2.p2 ?? x2; x2 = u2.p1; // 3 x2 = v2.p2 ?? x2; // 4 x2 = v2.p1; // 5 } void Test3(CL1 x3, CL1? z3) { var u3 = new { p1 = x3, p2 = z3 }; var v3 = u3; x3 = v3.p1 ?? x3; x3 = v3.p2; // 6 } void Test4(CL1 x4, CL1? z4) { var u4 = new { p0 = new { p1 = x4, p2 = z4 } }; var v4 = new { p0 = new { p1 = z4, p2 = x4 } }; u4 = v4; // 7 x4 = u4.p0.p2 ?? x4; x4 = u4.p0.p1; // 8 x4 = v4.p0.p2 ?? x4; // 9 x4 = v4.p0.p1; // 10 } void Test5(CL1 x5, CL1? z5) { var u5 = new { p0 = new { p1 = x5, p2 = z5 } }; var v5 = u5; x5 = v5.p0.p1 ?? x5; x5 = v5.p0.p2; // 11 } void Test6(CL1 x6, CL1? z6) { var u6 = new { p0 = new { p1 = x6, p2 = z6 } }; var v6 = u6.p0; x6 = v6.p1 ?? x6; x6 = v6.p2; // 12 } void Test7(CL1 x7, CL1? z7) { var u7 = new { p0 = new S1() { p1 = x7, p2 = z7 } }; var v7 = new { p0 = new S1() { p1 = z7, p2 = x7 } }; u7 = v7; x7 = u7.p0.p2 ?? x7; x7 = u7.p0.p1; // 13 x7 = v7.p0.p2 ?? x7; // 14 x7 = v7.p0.p1; // 15 } void Test8(CL1 x8, CL1? z8) { var u8 = new { p0 = new S1() { p1 = x8, p2 = z8 } }; var v8 = u8; x8 = v8.p0.p1 ?? x8; x8 = v8.p0.p2; // 16 } void Test9(CL1 x9, CL1? z9) { var u9 = new { p0 = new S1() { p1 = x9, p2 = z9 } }; var v9 = u9.p0; x9 = v9.p1 ?? x9; x9 = v9.p2; // 17 } void M1<T>(ref T x) {} void Test10(CL1 x10) { var u10 = new { a0 = x10, a1 = new { p1 = x10 }, a2 = new S1() { p2 = x10 } }; x10 = u10.a0; x10 = u10.a1.p1; x10 = u10.a2.p2; M1(ref u10); x10 = u10.a0; x10 = u10.a1.p1; x10 = u10.a2.p2; // 18 } } class CL1 { } struct S1 { public CL1? p1; public CL1? p2; }" }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = y1.p2; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1.p2").WithLocation(11, 14), // (18,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: CL1? p1, CL1 p2>' doesn't match target type '<anonymous type: CL1 p1, CL1? p2>'. // u2 = v2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "v2").WithArguments("<anonymous type: CL1? p1, CL1 p2>", "<anonymous type: CL1 p1, CL1? p2>").WithLocation(18, 14), // (20,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = u2.p1; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u2.p1").WithLocation(20, 14), // (21,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = v2.p2 ?? x2; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v2.p2 ?? x2").WithLocation(21, 14), // (22,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = v2.p1; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v2.p1").WithLocation(22, 14), // (30,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = v3.p2; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v3.p2").WithLocation(30, 14), // (37,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: <anonymous type: CL1? p1, CL1 p2> p0>' doesn't match target type '<anonymous type: <anonymous type: CL1 p1, CL1? p2> p0>'. // u4 = v4; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "v4").WithArguments("<anonymous type: <anonymous type: CL1? p1, CL1 p2> p0>", "<anonymous type: <anonymous type: CL1 p1, CL1? p2> p0>").WithLocation(37, 14), // (39,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = u4.p0.p1; // 8 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u4.p0.p1").WithLocation(39, 14), // (40,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = v4.p0.p2 ?? x4; // 9 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v4.p0.p2 ?? x4").WithLocation(40, 14), // (41,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = v4.p0.p1; // 10 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v4.p0.p1").WithLocation(41, 14), // (49,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x5 = v5.p0.p2; // 11 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v5.p0.p2").WithLocation(49, 14), // (57,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x6 = v6.p2; // 12 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v6.p2").WithLocation(57, 14), // (66,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x7 = u7.p0.p1; // 13 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u7.p0.p1").WithLocation(66, 14), // (67,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x7 = v7.p0.p2 ?? x7; // 14 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v7.p0.p2 ?? x7").WithLocation(67, 14), // (68,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x7 = v7.p0.p1; // 15 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v7.p0.p1").WithLocation(68, 14), // (76,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x8 = v8.p0.p2; // 16 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v8.p0.p2").WithLocation(76, 14), // (84,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x9 = v9.p2; // 17 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v9.p2").WithLocation(84, 14), // (100,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // x10 = u10.a2.p2; // 18 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u10.a2.p2").WithLocation(100, 15)); } [Fact] public void AnonymousTypes_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL1? x1) { var y1 = new { p1 = x1 }; y1.p1?. M1(y1.p1); } void Test2(CL1? x2) { var y2 = new { p1 = x2 }; if (y2.p1 != null) { y2.p1.M1(y2.p1); } } void Test3(out CL1? x3, CL1 z3) { var y3 = new { p1 = x3 }; x3 = y3.p1 ?? z3.M1(y3.p1); CL1 v3 = y3.p1; } } class CL1 { public CL1? M1(CL1 x) { return null; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (25,29): error CS0269: Use of unassigned out parameter 'x3' // var y3 = new { p1 = x3 }; Diagnostic(ErrorCode.ERR_UseDefViolationOut, "x3").WithArguments("x3").WithLocation(25, 29), // (27,29): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1? CL1.M1(CL1 x)'. // z3.M1(y3.p1); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y3.p1").WithArguments("x", "CL1? CL1.M1(CL1 x)").WithLocation(27, 29)); } [Fact] public void AnonymousTypes_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test2(CL1 x2) { x2 = new {F1 = x2}.F1; } void Test3(CL1 x3) { x3 = new {F1 = x3}.F1 ?? x3; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void AnonymousTypes_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL1<string> x1, CL1<string?> y1) { var u1 = new { F1 = x1 }; var v1 = new { F1 = y1 }; u1 = v1; v1 = u1; } } class CL1<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: CL1<string?> F1>' doesn't match target type '<anonymous type: CL1<string> F1>'. // u1 = v1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "v1").WithArguments("<anonymous type: CL1<string?> F1>", "<anonymous type: CL1<string> F1>").WithLocation(12, 14), // (13,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: CL1<string> F1>' doesn't match target type '<anonymous type: CL1<string?> F1>'. // v1 = u1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "u1").WithArguments("<anonymous type: CL1<string> F1>", "<anonymous type: CL1<string?> F1>").WithLocation(13, 14) ); } [Fact] [WorkItem(29889, "https://github.com/dotnet/roslyn/issues/29889")] [WorkItem(33577, "https://github.com/dotnet/roslyn/issues/33577")] public void AnonymousTypes_05() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F0(string x0, string? y0) { var a0 = new { F = x0 }; var b0 = new { F = y0 }; a0 = b0; // 1 b0 = a0; // 2 } static void F1(I<string> x1, I<string?> y1) { var a1 = new { F = x1 }; var b1 = new { F = y1 }; a1 = b1; // 3 b1 = a1; // 4 } static void F2(IIn<string> x2, IIn<string?> y2) { var a2 = new { F = x2 }; var b2 = new { F = y2 }; a2 = b2; b2 = a2; // 5 } static void F3(IOut<string> x3, IOut<string?> y3) { var a3 = new { F = x3 }; var b3 = new { F = y3 }; a3 = b3; // 6 b3 = a3; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/33577: Should not report a warning for `a2 = b2` or `b3 = a3`. comp.VerifyDiagnostics( // (10,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: string? F>' doesn't match target type '<anonymous type: string F>'. // a0 = b0; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b0").WithArguments("<anonymous type: string? F>", "<anonymous type: string F>").WithLocation(10, 14), // (11,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: string F>' doesn't match target type '<anonymous type: string? F>'. // b0 = a0; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a0").WithArguments("<anonymous type: string F>", "<anonymous type: string? F>").WithLocation(11, 14), // (17,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: I<string?> F>' doesn't match target type '<anonymous type: I<string> F>'. // a1 = b1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b1").WithArguments("<anonymous type: I<string?> F>", "<anonymous type: I<string> F>").WithLocation(17, 14), // (18,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: I<string> F>' doesn't match target type '<anonymous type: I<string?> F>'. // b1 = a1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1").WithArguments("<anonymous type: I<string> F>", "<anonymous type: I<string?> F>").WithLocation(18, 14), // (24,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: IIn<string?> F>' doesn't match target type '<anonymous type: IIn<string> F>'. // a2 = b2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b2").WithArguments("<anonymous type: IIn<string?> F>", "<anonymous type: IIn<string> F>").WithLocation(24, 14), // (25,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: IIn<string> F>' doesn't match target type '<anonymous type: IIn<string?> F>'. // b2 = a2; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("<anonymous type: IIn<string> F>", "<anonymous type: IIn<string?> F>").WithLocation(25, 14), // (31,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: IOut<string?> F>' doesn't match target type '<anonymous type: IOut<string> F>'. // a3 = b3; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b3").WithArguments("<anonymous type: IOut<string?> F>", "<anonymous type: IOut<string> F>").WithLocation(31, 14), // (32,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: IOut<string> F>' doesn't match target type '<anonymous type: IOut<string?> F>'. // b3 = a3; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a3").WithArguments("<anonymous type: IOut<string> F>", "<anonymous type: IOut<string?> F>").WithLocation(32, 14)); } [Fact] [WorkItem(29890, "https://github.com/dotnet/roslyn/issues/29890")] public void AnonymousTypes_06() { var source = @"class C { static void F(string x, string y) { x = new { x, y }.x ?? x; y = new { x, y = y }.y ?? y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void AnonymousTypes_07() { var source = @"class Program { static T F<T>(T t) => t; static void G() { var a = new { }; a = new { }; a = F(a); a = F(new { }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] public void AnonymousTypes_08() { var source = @"class Program { static void F<T>(T x, T? y) where T : class { new { x, y }.x.ToString(); new { x, y }.y.ToString(); // 1 new { y, x }.x.ToString(); new { y, x }.y.ToString(); // 2 new { x = x, y = y }.x.ToString(); new { x = x, y = y }.y.ToString(); // 3 new { x = y, y = x }.x.ToString(); // 4 new { x = y, y = x }.y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // new { x, y }.y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new { x, y }.y").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // new { y, x }.y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new { y, x }.y").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // new { x = x, y = y }.y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new { x = x, y = y }.y").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // new { x = y, y = x }.x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new { x = y, y = x }.x").WithLocation(11, 9)); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] public void AnonymousTypes_09() { var source = @"class Program { static void F<T>(T? x, T? y) where T : struct { if (y == null) return; _ = new { x = x, y = y }.x.Value; // 1 _ = new { x = x, y = y }.y.Value; _ = new { x = y, y = x }.x.Value; _ = new { x = y, y = x }.y.Value; // 2 _ = new { x, y }.x.Value; // 3 _ = new { x, y }.y.Value; _ = new { y, x }.x.Value; // 4 _ = new { y, x }.y.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8629: Nullable value type may be null. // _ = new { x = x, y = y }.x.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new { x = x, y = y }.x").WithLocation(6, 13), // (9,13): warning CS8629: Nullable value type may be null. // _ = new { x = y, y = x }.y.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new { x = y, y = x }.y").WithLocation(9, 13), // (10,13): warning CS8629: Nullable value type may be null. // _ = new { x, y }.x.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new { x, y }.x").WithLocation(10, 13), // (12,13): warning CS8629: Nullable value type may be null. // _ = new { y, x }.x.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new { y, x }.x").WithLocation(12, 13)); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] public void AnonymousTypes_10() { var source = @"class Program { static void F<T>(T x, T? y) where T : class { var a = new { x, y }; a.x/*T:T!*/.ToString(); a.y/*T:T?*/.ToString(); // 1 a = new { x = y, y = x }; // 2 a.x/*T:T?*/.ToString(); // 3 a.y/*T:T!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // a.y/*T:T?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.y").WithLocation(7, 9), // (8,13): warning CS8619: Nullability of reference types in value of type '<anonymous type: T? x, T y>' doesn't match target type '<anonymous type: T x, T? y>'. // a = new { x = y, y = x }; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new { x = y, y = x }").WithArguments("<anonymous type: T? x, T y>", "<anonymous type: T x, T? y>").WithLocation(8, 13), // (9,9): warning CS8602: Dereference of a possibly null reference. // a.x/*T:T?*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.x").WithLocation(9, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] [WorkItem(33577, "https://github.com/dotnet/roslyn/issues/33577")] public void AnonymousTypes_11() { var source = @"class Program { static void F<T>() where T : struct { T? x = new T(); T? y = null; var a = new { x, y }; _ = a.x.Value; _ = a.y.Value; // 1 x = null; y = new T(); a = new { x, y }; _ = a.x.Value; // 2 _ = a.y.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8629: Nullable value type may be null. // _ = a.y.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "a.y").WithLocation(9, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = a.x.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "a.x").WithLocation(13, 13)); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] public void AnonymousTypes_12() { var source = @"class Program { static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var a = new { x, y }; a.x/*T:T?*/.ToString(); // 2 a.y/*T:T!*/.ToString(); x = new T(); y = null; a = new { x, y }; // 3 a.x/*T:T!*/.ToString(); a.y/*T:T?*/.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 15), // (8,9): warning CS8602: Dereference of a possibly null reference. // a.x/*T:T?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.x").WithLocation(8, 9), // (12,13): warning CS8619: Nullability of reference types in value of type '<anonymous type: T x, T? y>' doesn't match target type '<anonymous type: T? x, T y>'. // a = new { x, y }; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new { x, y }").WithArguments("<anonymous type: T x, T? y>", "<anonymous type: T? x, T y>").WithLocation(12, 13), // (14,9): warning CS8602: Dereference of a possibly null reference. // a.y/*T:T?*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.y").WithLocation(14, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] public void AnonymousTypes_13() { var source = @"class Program { static void F<T>(T x, T y) { } static void G<T>(T x, T? y) where T : class { F(new { x, y }, new { x = x, y = y }); F(new { x, y }, new { x = y, y = x }); // 1 F(new { x = x, y = y }, new { x = x, y = y }); F(new { x = x, y = y }, new { x = y, y = x }); // 2 F(new { x = x, y = y }, new { x, y }); F(new { x = y, y = x }, new { x, y }); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,25): warning CS8620: Argument of type '<anonymous type: T? x, T y>' cannot be used for parameter 'y' of type '<anonymous type: T x, T? y>' in 'void Program.F<<anonymous type: T x, T? y>>(<anonymous type: T x, T? y> x, <anonymous type: T x, T? y> y)' due to differences in the nullability of reference types. // F(new { x, y }, new { x = y, y = x }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new { x = y, y = x }").WithArguments("<anonymous type: T? x, T y>", "<anonymous type: T x, T? y>", "y", "void Program.F<<anonymous type: T x, T? y>>(<anonymous type: T x, T? y> x, <anonymous type: T x, T? y> y)").WithLocation(9, 25), // (11,33): warning CS8620: Argument of type '<anonymous type: T? x, T y>' cannot be used for parameter 'y' of type '<anonymous type: T x, T? y>' in 'void Program.F<<anonymous type: T x, T? y>>(<anonymous type: T x, T? y> x, <anonymous type: T x, T? y> y)' due to differences in the nullability of reference types. // F(new { x = x, y = y }, new { x = y, y = x }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new { x = y, y = x }").WithArguments("<anonymous type: T? x, T y>", "<anonymous type: T x, T? y>", "y", "void Program.F<<anonymous type: T x, T? y>>(<anonymous type: T x, T? y> x, <anonymous type: T x, T? y> y)").WithLocation(11, 33), // (13,33): warning CS8620: Argument of type '<anonymous type: T x, T? y>' cannot be used for parameter 'y' of type '<anonymous type: T? x, T y>' in 'void Program.F<<anonymous type: T? x, T y>>(<anonymous type: T? x, T y> x, <anonymous type: T? x, T y> y)' due to differences in the nullability of reference types. // F(new { x = y, y = x }, new { x, y }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new { x, y }").WithArguments("<anonymous type: T x, T? y>", "<anonymous type: T? x, T y>", "y", "void Program.F<<anonymous type: T? x, T y>>(<anonymous type: T? x, T y> x, <anonymous type: T? x, T y> y)").WithLocation(13, 33)); } [Fact] [WorkItem(33007, "https://github.com/dotnet/roslyn/issues/33007")] public void AnonymousTypes_14() { var source = @"class Program { static T F<T>(T t) => t; static void F1<T>(T t1) where T : class { var a1 = F(new { t = t1 }); a1.t.ToString(); } static void F2<T>(T? t2) where T : class { var a2 = F(new { t = t2 }); a2.t.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // a2.t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2.t").WithLocation(12, 9)); } [Fact] [WorkItem(33007, "https://github.com/dotnet/roslyn/issues/33007")] public void AnonymousTypes_15() { var source = @"using System; class Program { static U F<T, U>(Func<T, U> f, T t) => f(t); static void F1<T>(T t1) where T : class { var a1 = F(t => new { t }, t1); a1.t.ToString(); } static void F2<T>(T? t2) where T : class { var a2 = F(t => new { t }, t2); a2.t.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // a2.t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2.t").WithLocation(13, 9)); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] public void AnonymousTypes_16() { var source = @"class Program { static void F<T>(T? t) where T : class { new { }.Missing(); if (t == null) return; new { t }.Missing(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,17): error CS1061: '<empty anonymous type>' does not contain a definition for 'Missing' and no accessible extension method 'Missing' accepting a first argument of type '<empty anonymous type>' could be found (are you missing a using directive or an assembly reference?) // new { }.Missing(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Missing").WithArguments("<empty anonymous type>", "Missing").WithLocation(5, 17), // (7,19): error CS1061: '<anonymous type: T t>' does not contain a definition for 'Missing' and no accessible extension method 'Missing' accepting a first argument of type '<anonymous type: T t>' could be found (are you missing a using directive or an assembly reference?) // new { t }.Missing(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Missing").WithArguments("<anonymous type: T t>", "Missing").WithLocation(7, 19)); } [Fact] [WorkItem(35044, "https://github.com/dotnet/roslyn/issues/35044")] public void AnonymousTypes_17() { var source = @" class Program { static void M(object o1, object? o2) { new { O1/*T:object!*/ = o1, O1/*T:object?*/ = o2 }.O1.ToString();; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,37): error CS0833: An anonymous type cannot have multiple properties with the same name // new { O1/*T:object!*/ = o1, O1/*T:object?*/ = o2 }.O1.ToString();; Diagnostic(ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, "O1/*T:object?*/ = o2").WithLocation(6, 37)); comp.VerifyTypes(); } [Fact] public void AnonymousObjectCreation_01() { var source = @"class C { static void F(object? o) { (new { P = o }).P.ToString(); if (o == null) return; (new { Q = o }).Q.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // (new { P = o }).P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new { P = o }).P").WithLocation(5, 9)); } [Fact] [WorkItem(29891, "https://github.com/dotnet/roslyn/issues/29891")] public void AnonymousObjectCreation_02() { var source = @"class C { static void F(object? o) { (new { P = new[] { o }}).P[0].ToString(); if (o == null) return; (new { Q = new[] { o }}).Q[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // (new { P = new[] { o }}).P[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new { P = new[] { o }}).P[0]").WithLocation(5, 9)); } [Fact] public void This() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1() { this.Test2(); } void Test2() { this?.Test1(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void ReadonlyAutoProperties_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C1 { static void Main() { } C1 P1 {get;} public C1(C1? x1) // 1 { P1 = x1; // 2 } } class C2 { C2? P2 {get;} public C2(C2 x2) { x2 = P2; // 3 } } class C3 { C3? P3 {get;} public C3(C3 x3, C3? y3) { P3 = y3; x3 = P3; // 4 } } class C4 { C4? P4 {get;} public C4(C4 x4) { P4 = x4; x4 = P4; } } class C5 { S1 P5 {get;} public C5(C0 x5) { P5 = new S1() { F1 = x5 }; x5 = P5.F1; } } class C0 {} struct S1 { public C0? F1; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,14): warning CS8601: Possible null reference assignment. // P1 = x1; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x1").WithLocation(12, 14), // (10,12): warning CS8618: Non-nullable property 'P1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C1(C1? x1) // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C1").WithArguments("property", "P1").WithLocation(10, 12), // (22,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = P2; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P2").WithLocation(22, 14), // (33,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = P3; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P3").WithLocation(33, 14) ); } [Fact] public void ReadonlyAutoProperties_02() { CSharpCompilation c = CreateCompilation(new[] { @" struct C1 { static void Main() { } C0 P1 {get;} public C1(C0? x1) // 1 { P1 = x1; // 2 } } struct C2 { C0? P2 {get;} public C2(C0 x2) { x2 = P2; // 3, 4 P2 = null; } } struct C3 { C0? P3 {get;} public C3(C0 x3, C0? y3) { P3 = y3; x3 = P3; // 5 } } struct C4 { C0? P4 {get;} public C4(C0 x4) { P4 = x4; x4 = P4; } } struct C5 { S1 P5 {get;} public C5(C0 x5) { P5 = new S1() { F1 = x5 }; x5 = P5.F1 ?? x5; } } class C0 {} struct S1 { public C0? F1; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,14): warning CS8601: Possible null reference assignment. // P1 = x1; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x1").WithLocation(12, 14), // (10,12): warning CS8618: Non-nullable property 'P1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C1(C0? x1) // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C1").WithArguments("property", "P1").WithLocation(10, 12), // (34,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = P3; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P3").WithLocation(34, 14), // (22,14): error CS8079: Use of possibly unassigned auto-implemented property 'P2' // x2 = P2; // 3, 4 Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "P2").WithArguments("P2").WithLocation(22, 14), // (22,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = P2; // 3, 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P2").WithLocation(22, 14) ); } [Fact] public void NotAssigned() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(object? x1) { CL1? y1; if (x1 == null) { y1 = null; return; } CL1 z1 = y1; } void Test2(object? x2, out CL1? y2) { if (x2 == null) { y2 = null; return; } CL1 z2 = y2; y2 = null; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (17,18): error CS0165: Use of unassigned local variable 'y1' // CL1 z1 = y1; Diagnostic(ErrorCode.ERR_UseDefViolation, "y1").WithArguments("y1").WithLocation(17, 18), // (17,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(17, 18), // (28,18): error CS0269: Use of unassigned out parameter 'y2' // CL1 z2 = y2; Diagnostic(ErrorCode.ERR_UseDefViolationOut, "y2").WithArguments("y2").WithLocation(28, 18), // (28,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2").WithLocation(28, 18)); } [Fact] public void Lambda_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Func<CL1?> x1 = () => M1(); } void Test2() { System.Func<CL1?> x2 = delegate { return M1(); }; } delegate CL1? D1(); void Test3() { D1 x3 = () => M1(); } void Test4() { D1 x4 = delegate { return M1(); }; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Lambda_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Action<CL1?> x1 = (p1) => p1 = M1(); } delegate void D1(CL1? p); void Test3() { D1 x3 = (p3) => p3 = M1(); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Lambda_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Func<CL1> x1 = () => M1(); } void Test2() { System.Func<CL1> x2 = delegate { return M1(); }; } delegate CL1 D1(); void Test3() { D1 x3 = () => M1(); } void Test4() { D1 x4 = delegate { return M1(); }; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,37): warning CS8603: Possible null reference return. // System.Func<CL1> x1 = () => M1(); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(12, 37), // (17,49): warning CS8603: Possible null reference return. // System.Func<CL1> x2 = delegate { return M1(); }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(17, 49), // (24,23): warning CS8603: Possible null reference return. // D1 x3 = () => M1(); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(24, 23), // (29,35): warning CS8603: Possible null reference return. // D1 x4 = delegate { return M1(); }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(29, 35) ); } [Fact] public void Lambda_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Action<CL1> x1 = (p1) => p1 = M1(); } delegate void D1(CL1 p); void Test3() { D1 x3 = (p3) => p3 = M1(); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action<CL1> x1 = (p1) => p1 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(12, 46), // (19,30): warning CS8600: Converting null literal or possible null value to non-nullable type. // D1 x3 = (p3) => p3 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(19, 30) ); } [Fact] public void Lambda_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } delegate CL1 D1(); delegate CL1? D2(); void M2(int x, D1 y) {} void M2(long x, D2 y) {} void M3(long x, D2 y) {} void M3(int x, D1 y) {} void Test1(int x1) { M2(x1, () => M1()); } void Test2(int x2) { M3(x2, () => M1()); } void Test3(int x3) { M2(x3, delegate { return M1(); }); } void Test4(int x4) { M3(x4, delegate { return M1(); }); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (20,22): warning CS8603: Possible null reference return. // M2(x1, () => M1()); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(20, 22), // (25,22): warning CS8603: Possible null reference return. // M3(x2, () => M1()); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(25, 22), // (30,34): warning CS8603: Possible null reference return. // M2(x3, delegate { return M1(); }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(30, 34), // (35,34): warning CS8603: Possible null reference return. // M3(x4, delegate { return M1(); }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(35, 34) ); } [Fact] public void Lambda_06() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } delegate CL1 D1(); delegate CL1? D2(); void M2(int x, D2 y) {} void M2(long x, D1 y) {} void M3(long x, D1 y) {} void M3(int x, D2 y) {} void Test1(int x1) { M2(x1, () => M1()); } void Test2(int x2) { M3(x2, () => M1()); } void Test3(int x3) { M2(x3, delegate { return M1(); }); } void Test4(int x4) { M3(x4, delegate { return M1(); }); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Lambda_07() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } delegate T D<T>(); void M2(int x, D<CL1> y) {} void M2<T>(int x, D<T> y) {} void M3<T>(int x, D<T> y) {} void M3(int x, D<CL1> y) {} void Test1(int x1) { M2(x1, () => M1()); } void Test2(int x2) { M3(x2, () => M1()); } void Test3(int x3) { M2(x3, delegate { return M1(); }); } void Test4(int x4) { M3(x4, delegate { return M1(); }); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (19,22): warning CS8603: Possible null reference return. // M2(x1, () => M1()); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(19, 22), // (24,22): warning CS8603: Possible null reference return. // M3(x2, () => M1()); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(24, 22), // (29,34): warning CS8603: Possible null reference return. // M2(x3, delegate { return M1(); }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(29, 34), // (34,34): warning CS8603: Possible null reference return. // M3(x4, delegate { return M1(); }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(34, 34) ); } [Fact] public void Lambda_08() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } delegate T D<T>(); void M2(int x, D<CL1?> y) {} void M2<T>(int x, D<T> y) {} void M3<T>(int x, D<T> y) {} void M3(int x, D<CL1?> y) {} void Test1(int x1) { M2(x1, () => M1()); } void Test2(int x2) { M3(x2, () => M1()); } void Test3(int x3) { M2(x3, delegate { return M1(); }); } void Test4(int x4) { M3(x4, delegate { return M1(); }); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Lambda_09() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } delegate T1 D<T1, T2>(T2 y); void M2(int x, D<CL1, CL1> y) {} void M2<T>(int x, D<T, CL1> y) {} void M3<T>(int x, D<T, CL1> y) {} void M3(int x, D<CL1, CL1> y) {} void Test1(int x1) { M2(x1, (y1) => { y1 = M1(); return y1; }); } void Test2(int x2) { M3(x2, (y2) => { y2 = M1(); return y2; }); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (21,26): warning CS8600: Converting null literal or possible null value to non-nullable type. // y1 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(21, 26), // (22,28): warning CS8603: Possible null reference return. // return y1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y1").WithLocation(22, 28), // (30,26): warning CS8600: Converting null literal or possible null value to non-nullable type. // y2 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(30, 26), // (31,28): warning CS8603: Possible null reference return. // return y2; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y2").WithLocation(31, 28) ); } [Fact] public void Lambda_10() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } delegate T1 D<T1, T2>(T2 y); void M2(int x, D<CL1, CL1?> y) {} void M2<T>(int x, D<T, CL1> y) {} void M3<T>(int x, D<T, CL1> y) {} void M3(int x, D<CL1, CL1?> y) {} void Test1(int x1) { M2(x1, (y1) => { y1 = M1(); return y1; }); } void Test2(int x2) { M3(x2, (y2) => { y2 = M1(); return y2; }); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (22,28): warning CS8603: Possible null reference return. // return y1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y1").WithLocation(22, 28), // (31,28): warning CS8603: Possible null reference return. // return y2; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y2").WithLocation(31, 28) ); } [Fact] public void Lambda_11() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Action<CL1> x1 = (CL1 p1) => p1 = M1(); } void Test2() { System.Action<CL1> x2 = delegate (CL1 p2) { p2 = M1(); }; } delegate void D1(CL1 p); void Test3() { D1 x3 = (CL1 p3) => p3 = M1(); } void Test4() { D1 x4 = delegate (CL1 p4) { p4 = M1(); }; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action<CL1> x1 = (CL1 p1) => p1 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(12, 50), // (17,58): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action<CL1> x2 = delegate (CL1 p2) { p2 = M1(); }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(17, 58), // (24,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // D1 x3 = (CL1 p3) => p3 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(24, 34), // (29,42): warning CS8600: Converting null literal or possible null value to non-nullable type. // D1 x4 = delegate (CL1 p4) { p4 = M1(); }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(29, 42) ); } [Fact] public void Lambda_12() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Action<CL1?> x1 = (CL1 p1) => p1 = M1(); } void Test2() { System.Action<CL1?> x2 = delegate (CL1 p2) { p2 = M1(); }; } delegate void D1(CL1? p); void Test3() { D1 x3 = (CL1 p3) => p3 = M1(); } void Test4() { D1 x4 = delegate (CL1 p4) { p4 = M1(); }; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action<CL1?> x1 = (CL1 p1) => p1 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(12, 51), // (12,34): warning CS8622: Nullability of reference types in type of parameter 'p1' of 'lambda expression' doesn't match the target delegate 'Action<CL1?>'. // System.Action<CL1?> x1 = (CL1 p1) => p1 = M1(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1 p1) => p1 = M1()").WithArguments("p1", "lambda expression", "System.Action<CL1?>").WithLocation(12, 34), // (17,59): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action<CL1?> x2 = delegate (CL1 p2) { p2 = M1(); }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(17, 59), // (17,34): warning CS8622: Nullability of reference types in type of parameter 'p2' of 'anonymous method' doesn't match the target delegate 'Action<CL1?>'. // System.Action<CL1?> x2 = delegate (CL1 p2) { p2 = M1(); }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "delegate (CL1 p2) { p2 = M1(); }").WithArguments("p2", "anonymous method", "System.Action<CL1?>").WithLocation(17, 34), // (24,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // D1 x3 = (CL1 p3) => p3 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(24, 34), // (24,17): warning CS8622: Nullability of reference types in type of parameter 'p3' of 'lambda expression' doesn't match the target delegate 'C.D1'. // D1 x3 = (CL1 p3) => p3 = M1(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1 p3) => p3 = M1()").WithArguments("p3", "lambda expression", "C.D1").WithLocation(24, 17), // (29,42): warning CS8600: Converting null literal or possible null value to non-nullable type. // D1 x4 = delegate (CL1 p4) { p4 = M1(); }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(29, 42), // (29,17): warning CS8622: Nullability of reference types in type of parameter 'p4' of 'anonymous method' doesn't match the target delegate 'C.D1'. // D1 x4 = delegate (CL1 p4) { p4 = M1(); }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "delegate (CL1 p4) { p4 = M1(); }").WithArguments("p4", "anonymous method", "C.D1").WithLocation(29, 17) ); } [Fact] public void Lambda_13() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Action<CL1> x1 = (CL1? p1) => p1 = M1(); } void Test2() { System.Action<CL1> x2 = delegate (CL1? p2) { p2 = M1(); }; } delegate void D1(CL1 p); void Test3() { D1 x3 = (CL1? p3) => p3 = M1(); } void Test4() { D1 x4 = delegate (CL1? p4) { p4 = M1(); }; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,33): warning CS8622: Nullability of reference types in type of parameter 'p1' of 'lambda expression' doesn't match the target delegate 'Action<CL1>'. // System.Action<CL1> x1 = (CL1? p1) => p1 = M1(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1? p1) => p1 = M1()").WithArguments("p1", "lambda expression", "System.Action<CL1>").WithLocation(12, 33), // (17,33): warning CS8622: Nullability of reference types in type of parameter 'p2' of 'anonymous method' doesn't match the target delegate 'Action<CL1>'. // System.Action<CL1> x2 = delegate (CL1? p2) { p2 = M1(); }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "delegate (CL1? p2) { p2 = M1(); }").WithArguments("p2", "anonymous method", "System.Action<CL1>").WithLocation(17, 33), // (24,17): warning CS8622: Nullability of reference types in type of parameter 'p3' of 'lambda expression' doesn't match the target delegate 'C.D1'. // D1 x3 = (CL1? p3) => p3 = M1(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1? p3) => p3 = M1()").WithArguments("p3", "lambda expression", "C.D1").WithLocation(24, 17), // (29,17): warning CS8622: Nullability of reference types in type of parameter 'p4' of 'anonymous method' doesn't match the target delegate 'C.D1'. // D1 x4 = delegate (CL1? p4) { p4 = M1(); }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "delegate (CL1? p4) { p4 = M1(); }").WithArguments("p4", "anonymous method", "C.D1").WithLocation(29, 17) ); } [Fact] public void Lambda_14() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Action<CL1?> x1 = (CL1? p1) => p1 = M1(); } void Test2() { System.Action<CL1?> x2 = delegate (CL1? p2) { p2 = M1(); }; } delegate void D1(CL1? p); void Test3() { D1 x3 = (CL1? p3) => p3 = M1(); } void Test4() { D1 x4 = delegate (CL1? p4) { p4 = M1(); }; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Lambda_15() { CSharpCompilation notAnnotated = CreateCompilation(@" public class CL0 { public static void M1(System.Func<CL1<CL0>, CL0> x) {} } public class CL1<T> { public T F1; public CL1() { F1 = default(T); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} static void Test1() { CL0.M1(p1 => { p1.F1 = null; p1 = null; return null; }); } static void Test2() { System.Func<CL1<CL0>, CL0> l2 = p2 => { p2.F1 = null; // 1 p2 = null; // 2 return null; // 3 }; } } " }, options: WithNullableEnable(), references: new[] { notAnnotated.EmitToImageReference() }); c.VerifyDiagnostics( // (20,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // p2.F1 = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 29), // (21,26): warning CS8600: Converting null literal or possible null value to non-nullable type. // p2 = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(21, 26), // (22,28): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(22, 28) ); } [Fact] public void Lambda_16() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1() { System.Action<CL1<string?>> x1 = (CL1<string> p1) => System.Console.WriteLine(); } void Test2() { System.Action<CL1<string>> x2 = (CL1<string?> p2) => System.Console.WriteLine(); } } class CL1<T> {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,42): warning CS8622: Nullability of reference types in type of parameter 'p1' of 'lambda expression' doesn't match the target delegate 'Action<CL1<string?>>'. // System.Action<CL1<string?>> x1 = (CL1<string> p1) => System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1<string> p1) => System.Console.WriteLine()").WithArguments("p1", "lambda expression", "System.Action<CL1<string?>>").WithLocation(10, 42), // (15,41): warning CS8622: Nullability of reference types in type of parameter 'p2' of 'lambda expression' doesn't match the target delegate 'Action<CL1<string>>'. // System.Action<CL1<string>> x2 = (CL1<string?> p2) => System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1<string?> p2) => System.Console.WriteLine()").WithArguments("p2", "lambda expression", "System.Action<CL1<string>>").WithLocation(15, 41) ); } [Fact] public void Lambda_17() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Linq.Expressions; class C { static void Main() { } void Test1() { Expression<System.Action<CL1<string?>>> x1 = (CL1<string> p1) => System.Console.WriteLine(); } void Test2() { Expression<System.Action<CL1<string>>> x2 = (CL1<string?> p2) => System.Console.WriteLine(); } } class CL1<T> {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,54): warning CS8622: Nullability of reference types in type of parameter 'p1' of 'lambda expression' doesn't match the target delegate 'Action<CL1<string?>>'. // Expression<System.Action<CL1<string?>>> x1 = (CL1<string> p1) => System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1<string> p1) => System.Console.WriteLine()").WithArguments("p1", "lambda expression", "System.Action<CL1<string?>>").WithLocation(12, 54), // (17,53): warning CS8622: Nullability of reference types in type of parameter 'p2' of 'lambda expression' doesn't match the target delegate 'Action<CL1<string>>'. // Expression<System.Action<CL1<string>>> x2 = (CL1<string?> p2) => System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1<string?> p2) => System.Console.WriteLine()").WithArguments("p2", "lambda expression", "System.Action<CL1<string>>").WithLocation(17, 53) ); } [Fact] public void Lambda_18() { var source = @"delegate T D<T>(T t) where T : class; class C { static void F() { var d1 = (D<string?>)((string s1) => { s1 = null; return s1; }); var d2 = (D<string>)((string? s2) => { s2.ToString(); return s2; }); // suppressed var d3 = (D<string?>)((string s1) => { s1 = null; return s1; }!); var d4 = (D<string>)((string? s2) => { s2.ToString(); return s2; }!); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): warning CS8622: Nullability of reference types in type of parameter 's1' of 'lambda expression' doesn't match the target delegate 'D<string?>'. // var d1 = (D<string?>)((string s1) => { s1 = null; return s1; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(D<string?>)((string s1) => { s1 = null; return s1; })").WithArguments("s1", "lambda expression", "D<string?>").WithLocation(6, 18), // (6,21): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'D<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var d1 = (D<string?>)((string s1) => { s1 = null; return s1; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("D<T>", "T", "string?").WithLocation(6, 21), // (6,53): warning CS8600: Converting null literal or possible null value to non-nullable type. // var d1 = (D<string?>)((string s1) => { s1 = null; return s1; }); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 53), // (7,18): warning CS8622: Nullability of reference types in type of parameter 's2' of 'lambda expression' doesn't match the target delegate 'D<string>'. // var d2 = (D<string>)((string? s2) => { s2.ToString(); return s2; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(D<string>)((string? s2) => { s2.ToString(); return s2; })").WithArguments("s2", "lambda expression", "D<string>").WithLocation(7, 18), // (7,48): warning CS8602: Dereference of a possibly null reference. // var d2 = (D<string>)((string? s2) => { s2.ToString(); return s2; }); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(7, 48), // (10,21): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'D<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var d3 = (D<string?>)((string s1) => { s1 = null; return s1; }!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("D<T>", "T", "string?").WithLocation(10, 21), // (10,53): warning CS8600: Converting null literal or possible null value to non-nullable type. // var d3 = (D<string?>)((string s1) => { s1 = null; return s1; }!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(10, 53), // (11,48): warning CS8602: Dereference of a possibly null reference. // var d4 = (D<string>)((string? s2) => { s2.ToString(); return s2; }!); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(11, 48) ); } /// <summary> /// To track nullability of captured variables inside and outside a lambda, /// the lambda should be considered executed at the location the lambda /// is converted to a delegate. /// </summary> [Fact] [WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void Lambda_19() { var source = @"using System; class C { static void F1(object? x1, object y1) { object z1 = y1; Action f = () => { z1 = x1; // warning }; f(); z1.ToString(); } static void F2(object? x2, object y2) { object z2 = x2; // warning Action f = () => { z2 = y2; }; f(); z2.ToString(); // warning } static void F3(object? x3, object y3) { object z3 = y3; if (x3 == null) return; Action f = () => { z3 = x3; }; f(); z3.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z1 = x1; // warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(9, 18), // (16,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object z2 = x2; // warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(16, 21), // (22,9): warning CS8602: Dereference of a possibly null reference. // z2.ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2").WithLocation(22, 9)); } [Fact] public void Lambda_20() { var source = @"#nullable enable #pragma warning disable 649 using System; class Program { static Action? F; static Action M(Action a) { if (F == null) return a; return () => F(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [ConditionalFact(typeof(IsRelease))] [WorkItem(48174, "https://github.com/dotnet/roslyn/issues/48174")] public void Lambda_Nesting_Large_01() { const int depth = 30; var builder = new StringBuilder(); for (int i = 1; i < depth; i++) { builder.AppendLine($" M0(c{i} =>"); } builder.Append($" M0(c{depth} => {{ }}"); for (int i = 0; i < depth; i++) { builder.Append(")"); } builder.Append(";"); var source = @" using System; class C { void M0(Action<C> action) { } void M1() { " + builder.ToString() + @" } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void Lambda_21() { var comp = CreateCompilation(@" class C { static void M() { string? s = null; C c = new C(() => s.ToString()); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,19): error CS1729: 'C' does not contain a constructor that takes 1 arguments // C c = new C(() => s.ToString()); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "1").WithLocation(7, 19), // (7,27): warning CS8602: Dereference of a possibly null reference. // C c = new C(() => s.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 27) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void Lambda_22() { var comp = CreateCompilation(@" class C { static void M() { string? s = null; M(() => s.ToString()); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): error CS1501: No overload for method 'M' takes 1 arguments // M(() => s.ToString()); Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "1").WithLocation(7, 9), // (7,17): warning CS8602: Dereference of a possibly null reference. // M(() => s.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 17) ); } [ConditionalFact(typeof(IsRelease))] [WorkItem(48174, "https://github.com/dotnet/roslyn/issues/48174")] public void Lambda_Nesting_Large_02() { const int depth = 30; var builder = new StringBuilder(); for (int i = 0; i < depth; i++) { builder.AppendLine($" Action<C> a{i} = c{i} => {{"); } for (int i = 0; i < depth; i++) { builder.AppendLine(" };"); } var source = @" using System; class C { void M1() { " + builder.ToString() + @" } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [ConditionalFact(typeof(IsRelease))] [WorkItem(48174, "https://github.com/dotnet/roslyn/issues/48174")] public void Lambda_Nesting_Large_03() { var source = #region large source @"using System; namespace nullable_repro { public class Recursive { public void Method(Action<Recursive> next) { } public void Initial(Recursive recurse) { recurse.Method(((recurse2) => { recurse2.Method(((recurse3) => { recurse3.Method(((recurse4) => { recurse4.Method(((recurse5) => { recurse5.Method(((recurse6) => { recurse6.Method(((recurse7) => { recurse7.Method(((recurse8) => { recurse8.Method(((recurse9) => { recurse9.Method(((recurse10) => { recurse10.Method(((recurse11) => { recurse11.Method(((recurse12) => { recurse12.Method(((recurse13) => { recurse13.Method(((recurse14) => { recurse14.Method(((recurse15) => { recurse15.Method(((recurse16) => { recurse16.Method(((recurse17) => { recurse17.Method(((recurse18) => { recurse18.Method(((recurse19) => { recurse19.Method(((recurse20) => { recurse20.Method(((recurse21) => { } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } } }"; #endregion var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [ConditionalFact(typeof(IsRelease))] [WorkItem(48174, "https://github.com/dotnet/roslyn/issues/48174")] public void Lambda_Nesting_ErrorType() { var source = @" public class Program { public static void M(string? x) { ERROR error1 = () => // 1 { ERROR(() => { x.ToString(); // 2 }); x.ToString(); // 3 }; x.ToString(); // 4 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'ERROR' could not be found (are you missing a using directive or an assembly reference?) // ERROR error1 = () => // 1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ERROR").WithArguments("ERROR").WithLocation(6, 9), // (10,17): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 17), // (12,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 13), // (14,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 9) ); } [Fact] public void LambdaReturnValue_01() { var source = @"using System; class C { static void F(Func<object> f) { } static void G(string x, object? y) { F(() => { if ((object)x == y) return x; return y; }); F(() => { if (y == null) return x; return y; }); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,56): warning CS8603: Possible null reference return. // F(() => { if ((object)x == y) return x; return y; }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y").WithLocation(9, 56)); } [Fact] public void LambdaReturnValue_02() { var source = @"using System; class C { static void F(Func<object> f) { } static void G(bool b, object x, string? y) { F(() => { if (b) return x; return y; }); F(() => { if (b) return y; return x; }); } static void H(bool b, object? x, string y) { F(() => { if (b) return x; return y; }); F(() => { if (b) return y; return x; }); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,43): warning CS8603: Possible null reference return. // F(() => { if (b) return x; return y; }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y").WithLocation(9, 43), // (10,33): warning CS8603: Possible null reference return. // F(() => { if (b) return y; return x; }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y").WithLocation(10, 33), // (14,33): warning CS8603: Possible null reference return. // F(() => { if (b) return x; return y; }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x").WithLocation(14, 33), // (15,43): warning CS8603: Possible null reference return. // F(() => { if (b) return y; return x; }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x").WithLocation(15, 43)); } [Fact] public void LambdaReturnValue_03() { var source = @"using System; class C { static T F<T>(Func<T> f) { throw null!; } static void G(bool b, object x, string? y) { F(() => { if (b) return x; return y; }).ToString(); } static void H(bool b, object? x, string y) { F(() => { if (b) return x; return y; }).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(() => { if (b) return x; return y; }).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => { if (b) return x; return y; })").WithLocation(10, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F(() => { if (b) return x; return y; }).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => { if (b) return x; return y; })").WithLocation(14, 9)); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void LambdaReturnValue_04() { var source = @"using System; class C { static T F<T>(Func<T> f) { throw null!; } static void G(object? o) { F(() => o).ToString(); // 1 if (o != null) F(() => o).ToString(); F(() => { return o; }).ToString(); // 2 if (o != null) F(() => { return o; }).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(() => o).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => o)").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F(() => { return o; }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => { return o; })").WithLocation(12, 9)); } [Fact] public void LambdaReturnValue_05() { var source = @"using System; class C { static T F<T>(Func<object?, T> f) { throw null!; } static void G() { F(o => o).ToString(); // 1 F(o => { if (o == null) throw new ArgumentException(); return o; }).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(o => o).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(o => o)").WithLocation(10, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void LambdaReturnValue_05_WithSuppression() { var source = @"using System; class C { static T F<T>(Func<object?, T> f) { throw null!; } static void G() { F(o => { if (o == null) throw new ArgumentException(); return o; }!).ToString(); } }"; // covers suppression case in InferReturnType var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void LambdaReturnValue_06() { var source = @"using System; class C { static U F<T, U>(Func<T, U> f, T t) { return f(t); } static void M(object? x) { F(y => F(z => z, y), x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(y => F(z => z, y), x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y => F(z => z, y), x)").WithLocation(10, 9)); } [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] [WorkItem(30480, "https://github.com/dotnet/roslyn/issues/30480")] [Fact] public void LambdaReturnValue_NestedNullability_Invariant() { var source0 = @"public class A { public static B<object> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"using System; class C { static T F<T>(Func<int, T> f) => throw null!; static void F(B<object?> x, B<object> y) { var z = A.F/*T:B<object>!*/; F(i => { switch (i) { case 0: return x; default: return x; }})/*T:B<object?>!*/; F(i => { switch (i) { case 0: return x; default: return y; }})/*T:B<object!>!*/; // 1 F(i => { switch (i) { case 0: return x; default: return z; }})/*T:B<object?>!*/; F(i => { switch (i) { case 0: return y; default: return x; }})/*T:B<object!>!*/; // 2 F(i => { switch (i) { case 0: return y; default: return y; }})/*T:B<object!>!*/; F(i => { switch (i) { case 0: return y; default: return z; }})/*T:B<object!>!*/; F(i => { switch (i) { case 0: return z; default: return x; }})/*T:B<object?>!*/; F(i => { switch (i) { case 0: return z; default: return y; }})/*T:B<object!>!*/; F(i => { switch (i) { case 0: return z; default: return z; }})/*T:B<object>!*/; F(i => { switch (i) { case 0: return x; case 1: return y; default: return z; }})/*T:B<object!>!*/; // 3 F(i => { switch (i) { case 0: return z; case 1: return y; default: return x; }})/*T:B<object!>!*/; // 4 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (9,46): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // F(i => { switch (i) { case 0: return x; default: return y; }})/*T:B<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(9, 46), // (11,65): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // F(i => { switch (i) { case 0: return y; default: return x; }})/*T:B<object!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(11, 65), // (17,46): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // F(i => { switch (i) { case 0: return x; case 1: return y; default: return z; }})/*T:B<object!>*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(17, 46), // (18,83): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // F(i => { switch (i) { case 0: return z; case 1: return y; default: return x; }})/*T:B<object!>*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(18, 83) ); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void LambdaReturnValue_NestedNullability_Variant_01() { var source0 = @"public class A { public static I<object> F; public static IIn<object> FIn; public static IOut<object> FOut; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"using System; class C { static T F<T>(Func<bool, T> f) => throw null!; static void F1(I<object> x, I<object?> y) { var z = A.F/*T:I<object>!*/; F(b => { if (b) return x; else return x; })/*T:I<object!>!*/; F(b => { if (b) return x; else return y; })/*T:I<object!>!*/; // 1 F(b => { if (b) return x; else return z; })/*T:I<object!>!*/; F(b => { if (b) return y; else return x; })/*T:I<object!>!*/; // 2 F(b => { if (b) return y; else return y; })/*T:I<object?>!*/; F(b => { if (b) return y; else return z; })/*T:I<object?>!*/; F(b => { if (b) return z; else return x; })/*T:I<object!>!*/; F(b => { if (b) return z; else return y; })/*T:I<object?>!*/; F(b => { if (b) return z; else return z; })/*T:I<object>!*/; } static void F2(IIn<object> x, IIn<object?> y) { var z = A.FIn/*T:IIn<object>!*/; F(b => { if (b) return x; else return x; })/*T:IIn<object!>!*/; F(b => { if (b) return x; else return y; })/*T:IIn<object!>!*/; F(b => { if (b) return x; else return z; })/*T:IIn<object!>!*/; F(b => { if (b) return y; else return x; })/*T:IIn<object!>!*/; F(b => { if (b) return y; else return y; })/*T:IIn<object?>!*/; F(b => { if (b) return y; else return z; })/*T:IIn<object>!*/; F(b => { if (b) return z; else return x; })/*T:IIn<object!>!*/; F(b => { if (b) return z; else return y; })/*T:IIn<object>!*/; F(b => { if (b) return z; else return z; })/*T:IIn<object>!*/; } static void F3(IOut<object> x, IOut<object?> y) { var z = A.FOut/*T:IOut<object>!*/; F(b => { if (b) return x; else return x; })/*T:IOut<object!>!*/; F(b => { if (b) return x; else return y; })/*T:IOut<object?>!*/; F(b => { if (b) return x; else return z; })/*T:IOut<object>!*/; F(b => { if (b) return y; else return x; })/*T:IOut<object?>!*/; F(b => { if (b) return y; else return y; })/*T:IOut<object?>!*/; F(b => { if (b) return y; else return z; })/*T:IOut<object?>!*/; F(b => { if (b) return z; else return x; })/*T:IOut<object>!*/; F(b => { if (b) return z; else return y; })/*T:IOut<object?>!*/; F(b => { if (b) return z; else return z; })/*T:IOut<object>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (9,47): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // F(b => { if (b) return x; else return y; })/*T:I<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(9, 47), // (11,32): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // F(b => { if (b) return y; else return x; })/*T:I<object!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(11, 32) ); } [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] [Fact] public void LambdaReturnValue_NestedNullability_Variant_02() { var source0 = @"public class A { public static B<object> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"using System; class C { static Func<int, T> CreateFunc<T>(T t) => throw null!; static void F(B<object?> x, B<object> y) { var f = CreateFunc(y)/*Func<int, B<object!>!>!*/; var z = A.F/*T:B<object>!*/; f = i => { switch (i) { case 0: return x; default: return x; }}; // 1 2 f = i => { switch (i) { case 0: return x; default: return y; }}; // 3 f = i => { switch (i) { case 0: return x; default: return z; }}; // 4 f = i => { switch (i) { case 0: return y; default: return x; }}; // 5 f = i => { switch (i) { case 0: return y; default: return y; }}; f = i => { switch (i) { case 0: return y; default: return z; }}; f = i => { switch (i) { case 0: return z; default: return x; }}; // 6 f = i => { switch (i) { case 0: return z; default: return y; }}; f = i => { switch (i) { case 0: return z; default: return z; }}; f = i => { switch (i) { case 0: return x; case 1: return y; default: return z; }}; // 7 f = i => { switch (i) { case 0: return z; case 1: return y; default: return x; }}; // 8 var g = CreateFunc(z)/*Func<int, B<object>!>!*/; g = i => { switch (i) { case 0: return x; default: return x; }}; g = i => { switch (i) { case 0: return x; default: return y; }}; g = i => { switch (i) { case 0: return x; default: return z; }}; g = i => { switch (i) { case 0: return y; default: return x; }}; g = i => { switch (i) { case 0: return y; default: return y; }}; g = i => { switch (i) { case 0: return y; default: return z; }}; g = i => { switch (i) { case 0: return z; default: return x; }}; g = i => { switch (i) { case 0: return z; default: return y; }}; g = i => { switch (i) { case 0: return z; default: return z; }}; g = i => { switch (i) { case 0: return x; case 1: return y; default: return z; }}; g = i => { switch (i) { case 0: return z; case 1: return y; default: return x; }}; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (9,48): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return x; default: return x; }}; // 1 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(9, 48), // (9,67): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return x; default: return x; }}; // 1 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(9, 67), // (10,48): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return x; default: return y; }}; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(10, 48), // (11,48): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return x; default: return z; }}; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(11, 48), // (12,67): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return y; default: return x; }}; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(12, 67), // (15,67): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return z; default: return x; }}; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(15, 67), // (18,48): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return x; case 1: return y; default: return z; }}; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(18, 48), // (19,85): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return z; case 1: return y; default: return x; }}; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(19, 85) ); comp.VerifyTypes(); } [WorkItem(30432, "https://github.com/dotnet/roslyn/issues/30432")] [Fact] public void LambdaReturnValue_TopLevelNullability_Ref() { var source = @"delegate ref V D<T, U, V>(ref T t, ref U u); class C { static V F<T, U, V>(D<T, U, V> d) => throw null!; static void G(bool b) { F((ref object? x1, ref object? y1) => { if (b) return ref x1; return ref y1; }); F((ref object? x2, ref object y2) => { if (b) return ref x2; return ref y2; }); F((ref object x3, ref object? y3) => { if (b) return ref x3; return ref y3; }); F((ref object x4, ref object y4) => { if (b) return ref x4; return ref y4; }); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,81): warning CS8619: Nullability of reference types in value of type 'object' doesn't match target type 'object?'. // F((ref object? x2, ref object y2) => { if (b) return ref x2; return ref y2; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y2").WithArguments("object", "object?").WithLocation(8, 81), // (9,66): warning CS8619: Nullability of reference types in value of type 'object' doesn't match target type 'object?'. // F((ref object x3, ref object? y3) => { if (b) return ref x3; return ref y3; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("object", "object?").WithLocation(9, 66) ); } [WorkItem(30432, "https://github.com/dotnet/roslyn/issues/30432")] [WorkItem(30964, "https://github.com/dotnet/roslyn/issues/30964")] [Fact] public void LambdaReturnValue_NestedNullability_Ref() { var source = @"delegate ref V D<T, U, V>(ref T t, ref U u); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static V F<T, U, V>(D<T, U, V> d) => throw null!; static void G(bool b) { // I<object> F((ref I<object?> a1, ref I<object?> b1) => { if (b) return ref a1; return ref b1; }); F((ref I<object?> a2, ref I<object> b2) => { if (b) return ref a2; return ref b2; }); // 1 F((ref I<object> a3, ref I<object?> b3) => { if (b) return ref a3; return ref b3; }); // 2 F((ref I<object> a4, ref I<object> b4) => { if (b) return ref a4; return ref b4; }); // IIn<object> F((ref IIn<object?> c1, ref IIn<object?> d1) => { if (b) return ref c1; return ref d1; }); F((ref IIn<object?> c2, ref IIn<object> d2) => { if (b) return ref c2; return ref d2; }); // 3 F((ref IIn<object> c3, ref IIn<object?> d3) => { if (b) return ref c3; return ref d3; }); // 4 F((ref IIn<object> c4, ref IIn<object> d4) => { if (b) return ref c4; return ref d4; }); // IOut<object> F((ref IOut<object?> e1, ref IOut<object?> f1) => { if (b) return ref e1; return ref f1; }); F((ref IOut<object?> e2, ref IOut<object> f2) => { if (b) return ref e2; return ref f2; }); // 5 F((ref IOut<object> e3, ref IOut<object?> f3) => { if (b) return ref e3; return ref f3; }); // 6 F((ref IOut<object> e4, ref IOut<object> f4) => { if (b) return ref e4; return ref f4; }); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,72): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // F((ref I<object?> a2, ref I<object> b2) => { if (b) return ref a2; return ref b2; }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("I<object?>", "I<object>").WithLocation(12, 72), // (13,87): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // F((ref I<object> a3, ref I<object?> b3) => { if (b) return ref a3; return ref b3; }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b3").WithArguments("I<object?>", "I<object>").WithLocation(13, 87), // (17,76): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'IIn<object>'. // F((ref IIn<object?> c2, ref IIn<object> d2) => { if (b) return ref c2; return ref d2; }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c2").WithArguments("IIn<object?>", "IIn<object>").WithLocation(17, 76), // (18,91): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'IIn<object>'. // F((ref IIn<object> c3, ref IIn<object?> d3) => { if (b) return ref c3; return ref d3; }); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "d3").WithArguments("IIn<object?>", "IIn<object>").WithLocation(18, 91), // (22,93): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'IOut<object?>'. // F((ref IOut<object?> e2, ref IOut<object> f2) => { if (b) return ref e2; return ref f2; }); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "f2").WithArguments("IOut<object>", "IOut<object?>").WithLocation(22, 93), // (23,78): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'IOut<object?>'. // F((ref IOut<object> e3, ref IOut<object?> f3) => { if (b) return ref e3; return ref f3; }); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "e3").WithArguments("IOut<object>", "IOut<object?>").WithLocation(23, 78) ); } [Fact] public void LambdaParameterValue() { var source = @"using System; class C { static void F<T>(T t, Action<T> f) { } static void G(object? x) { F(x, y => F(y, z => { y.ToString(); z.ToString(); })); if (x != null) F(x, y => F(y, z => { y.ToString(); z.ToString(); })); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,31): warning CS8602: Dereference of a possibly null reference. // F(x, y => F(y, z => { y.ToString(); z.ToString(); })); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 31), // (9,45): warning CS8602: Dereference of a possibly null reference. // F(x, y => F(y, z => { y.ToString(); z.ToString(); })); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(9, 45)); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LocalFunction_OnlyCalledInLambda_01() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main(string[] args) { var x = M1(); Task.Run(() => Bar()); Task.Run(() => Baz()); void Bar() => M2(x); void Baz() => Console.WriteLine(x.ToString()); } private static object M1() => new object(); private static bool M2(object instance) => instance != null; } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LocalFunction_OnlyCalledInLambda_02() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main(string[] args) { var x = M1(); void Bar() => M2(x); void Baz() => Console.WriteLine(x.ToString()); Task.Run(() => Bar()); Task.Run(() => Baz()); } private static object M1() => new object(); private static bool M2(object instance) => instance != null; } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LambdaWritesDoNotUpdateContainingMethodState() { var source = @" using System; class Program { static void M1() { string? x = ""hello""; M2(() => { x = null; }); x.ToString(); x = null; x.ToString(); // 1 } static void M2(Action a) { } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (16,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 9)); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LambdaWritesDoNotUpdateContainingMethodState_02() { var source = @" using System; class Program { static void M1() { M2(() => { string? y = ""world""; M2(() => { y = null; }); y.ToString(); y = null; y.ToString(); // 1 }); } static void M2(Action a) { } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (18,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(18, 13)); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void AnonymousMethodWritesDoNotUpdateContainingMethodState() { var source = @" using System; class Program { static void M1() { string? x = ""hello""; M2(delegate() { x = null; }); x.ToString(); x = null; x.ToString(); // 1 } static void M2(Action a) { } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (16,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 9)); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LocalFunctionWritesDoNotUpdateContainingMethodState_01() { var source = @" using System; class Program { static void M1() { string? x = ""hello""; x.ToString(); M2(local); x.ToString(); local(); x.ToString(); void local() { x = null; } } static void M2(Action a) { } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LocalFunctionWritesDoNotUpdateContainingMethodState_02() { var source = @" using System; class Program { static void M1() { string? x = ""hello""; void local() { x = null; } x.ToString(); M2(local); x.ToString(); local(); x.ToString(); } static void M2(Action a) { } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LocalFunctionStateConsidersAllUsages_01() { var source = @" class Program { static void M1() { string? x = ""hello""; local1(); local2(); x = null; local1(); void local1() { _ = x.ToString(); // 1 } void local2() { _ = x.ToString(); } } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 17)); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LocalFunctionStateConsidersAllUsages_02() { var source = @" using System; class Program { static void M1() { string? x = ""hello""; M2(local1); M2(local2); x = null; M2(local1); void local1() { _ = x.ToString(); // 1 } void local2() { _ = x.ToString(); } } static void M2(Action a) { } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (17,17): warning CS8602: Dereference of a possibly null reference. // _ = x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 17)); } [Fact] [WorkItem(33645, "https://github.com/dotnet/roslyn/issues/33645")] public void ReinferLambdaReturnType() { var source = @"using System; class C { static T F<T>(Func<T> f) => f(); static void G(object? x) { F(() => x)/*T:object?*/; if (x == null) return; F(() => x)/*T:object!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void ReinferLambdaReturnType_IgnoreInnerLocalFunction() { var source = @" using System; class C { static T F<T>(Func<T> f) => f(); void M() { F(() => new object()).ToString(); F(() => { _ = local1(); return new object(); object? local1() { return null; } }).ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ReinferLambdaReturnType_IgnoreInnerLambda() { var source = @" using System; class C { static T F<T>(Func<T> f) => f(); void M() { F(() => new object()).ToString(); F(() => { Func<object?> fn1 = () => { return null; }; _ = fn1(); return new object(); }).ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void IdentityConversion_LambdaReturnType() { var source = @"delegate T D<T>(); interface I<T> { } class C { static void F(object x, object? y) { D<object?> a = () => x; D<object> b = () => y; // 1 if (y == null) return; a = () => y; b = () => y; a = (D<object?>)(() => y); b = (D<object>)(() => y); } static void F(I<object> x, I<object?> y) { D<I<object?>> a = () => x; // 2 D<I<object>> b = () => y; // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,29): warning CS8603: Possible null reference return. // D<object> b = () => y; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y").WithLocation(8, 29), // (17,33): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // D<I<object?>> a = () => x; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object>", "I<object?>").WithLocation(17, 33), // (18,32): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // D<I<object>> b = () => y; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(18, 32)); } [Fact] public void IdentityConversion_LambdaParameter() { var source = @"delegate void D<T>(T t); interface I<T> { } class C { static void F() { D<object?> a = (object o) => { }; D<object> b = (object? o) => { }; D<I<object?>> c = (I<object> o) => { }; D<I<object>> d = (I<object?> o) => { }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,24): warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'D<object?>'. // D<object?> a = (object o) => { }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(object o) => { }").WithArguments("o", "lambda expression", "D<object?>").WithLocation(7, 24), // (8,23): warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'D<object>'. // D<object> b = (object? o) => { }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(object? o) => { }").WithArguments("o", "lambda expression", "D<object>").WithLocation(8, 23), // (9,27): warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'D<I<object?>>'. // D<I<object?>> c = (I<object> o) => { }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(I<object> o) => { }").WithArguments("o", "lambda expression", "D<I<object?>>").WithLocation(9, 27), // (10,26): warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'D<I<object>>'. // D<I<object>> d = (I<object?> o) => { }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(I<object?> o) => { }").WithArguments("o", "lambda expression", "D<I<object>>").WithLocation(10, 26)); } [Fact, WorkItem(40561, "https://github.com/dotnet/roslyn/issues/40561")] public void ReturnLambda_InsideConditionalExpr() { var source = @" using System; class C { static void M0(string s) { } static Action? M1(string? s) => s != null ? () => M0(s) : (Action?)null; static Action? M2(string? s) => s != null ? (Action)(() => M0(s)) : null; static Action? M3(string? s) => s != null ? () => { M0(s); s = null; } : (Action?)null; static Action? M4(string? s) { return s != null ? local(() => M0(s), s = null) : (Action?)null; Action local(Action a1, string? s) { return a1; } } static Action? M5(string? s) { return s != null ? local(s = null, () => M0(s)) // 1 : (Action?)null; Action local(string? s, Action a1) { return a1; } } static Action? M6(string? s) { return s != null ? local(() => M0(s)) : (Action?)null; Action local(Action a1) { s = null; return a1; } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (38,40): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M0(string s)'. // ? local(s = null, () => M0(s)) // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s").WithArguments("s", "void C.M0(string s)").WithLocation(38, 40)); } [Fact] [WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void ReturnTypeInference_01() { var source = @"class C { static T F<T>(System.Func<T> f) { return f(); } static void G(string x, string? y) { F(() => x).ToString(); F(() => y).ToString(); // 1 if (y != null) F(() => y).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(() => y).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => y)").WithLocation(10, 9)); } [Fact] public void ReturnTypeInference_DelegateTypes() { var source = @" class C { System.Func<bool, T> D1<T>(T t) => k => t; void M1(bool b, string? s, string s2) { M2(k => s, D1(s)) /*T:System.Func<bool, string?>!*/; M2(D1(s), k => s) /*T:System.Func<bool, string?>!*/; M2(k => s2, D1(s2)) /*T:System.Func<bool, string!>!*/; M2(D1(s2), k => s2) /*T:System.Func<bool, string!>!*/; _ = (new[] { k => s, D1(s) }) /*T:System.Func<bool, string?>![]!*/; _ = (new[] { D1(s), k => s }) /*T:System.Func<bool, string?>![]!*/; _ = (new[] { k => s2, D1(s2) }) /*T:System.Func<bool, string>![]!*/; // wrong _ = (new[] { D1(s2), k => s2 }) /*T:System.Func<bool, string>![]!*/; // wrong } T M2<T>(T x, T y) => throw null!; }"; // See https://github.com/dotnet/roslyn/issues/34392 // Best type inference involving lambda conversion should agree with method type inference var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } // Multiple returns, one of which is null. [Fact] public void ReturnTypeInference_02() { var source = @"class C { static T F<T>(System.Func<T> f) { return f(); } static void G(string x) { F(() => { if (x.Length > 0) return x; return null; }).ToString(); F(() => { if (x.Length == 0) return null; return x; }).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F(() => { if (x.Length > 0) return x; return null; }).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => { if (x.Length > 0) return x; return null; })").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F(() => { if (x.Length == 0) return null; return x; }).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => { if (x.Length == 0) return null; return x; })").WithLocation(10, 9)); } [Fact] public void ReturnTypeInference_CSharp7() { var source = @"using System; class C { static void Main(string[] args) { args.F(arg => arg.Length); } } static class E { internal static U[] F<T, U>(this T[] a, Func<T, U> f) => throw new Exception(); }"; var comp = CreateCompilationWithMscorlib45( new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); } [Fact] public void UnboundLambda_01() { var source = @"class C { static void F() { var y = x => x; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,17): error CS8917: The delegate type could not be inferred. // var y = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(5, 17)); } [Fact] public void UnboundLambda_02() { var source = @"class C { static void F(object? x) { var z = y => y ?? x.ToString(); System.Func<object?, object> z2 = y => y ?? x.ToString(); System.Func<object?, object> z3 = y => null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,17): error CS8917: The delegate type could not be inferred. // var z = y => y ?? x.ToString(); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "y => y ?? x.ToString()").WithLocation(5, 17), // (5,27): warning CS8602: Dereference of a possibly null reference. // var z = y => y ?? x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(5, 27), // (6,53): warning CS8602: Dereference of a possibly null reference. // System.Func<object?, object> z2 = y => y ?? x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 53), // (7,48): warning CS8603: Possible null reference return. // System.Func<object?, object> z3 = y => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(7, 48)); } /// <summary> /// Inferred nullability of captured variables should be tracked across /// local function invocations, as if the local function was inlined. /// </summary> [Fact] [WorkItem(29892, "https://github.com/dotnet/roslyn/issues/29892")] public void LocalFunction_01() { var source = @"class C { static void F1(object? x1, object y1) { object z1 = y1; f(); z1.ToString(); // warning void f() { z1 = x1; // warning } } static void F2(object? x2, object y2) { object z2 = x2; // warning f(); z2.ToString(); void f() { z2 = y2; } } static void F3(object? x3, object y3) { object z3 = y3; void f() { z3 = x3; } if (x3 == null) return; f(); z3.ToString(); } static void F4(object? x4) { f().ToString(); // warning if (x4 != null) f().ToString(); object? f() => x4; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29892: Should report warnings as indicated in source above. comp.VerifyDiagnostics( // (10,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z1 = x1; // warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(10, 18), // (15,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object z2 = x2; // warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(15, 21), // (17,9): warning CS8602: Dereference of a possibly null reference. // z2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2").WithLocation(17, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // f().ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "f()").WithLocation(36, 9), // (37,25): warning CS8602: Dereference of a possibly null reference. // if (x4 != null) f().ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "f()").WithLocation(37, 25)); } [Fact] [WorkItem(29892, "https://github.com/dotnet/roslyn/issues/29892")] public void LocalFunction_02() { var source = @"class C { static void F1() { string? x = """"; f(); x = """"; g(); void f() { x.ToString(); // warn x = null; f(); } void g() { x.ToString(); x = null; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 13) ); } [Fact] [WorkItem(29892, "https://github.com/dotnet/roslyn/issues/29892")] public void LocalFunction_03() { var source = @"class C { static void F1() { string? x = """"; f(); h(); void f() { x.ToString(); } void g() { x.ToString(); // warn } void h() { x = null; g(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 13) ); } [Fact] [WorkItem(29892, "https://github.com/dotnet/roslyn/issues/29892")] public void LocalFunction_04() { var source = @"class C { static void F1() { string? x = """"; f(); void f() { x.ToString(); // warn if (string.Empty == """") // non-constant { x = null; f(); } } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 13) ); } [Fact] [WorkItem(42396, "https://github.com/dotnet/roslyn/issues/42396")] public void LocalFunction_05() { var source = @" using System; using System.Collections.Generic; class C { void M<T>() where T : class { Func<IEnumerable<List<T>>> f = () => { IEnumerable<T> Enumerate(IEnumerable<T> xs) { foreach (T x in xs) yield return x; } Enumerate(new List<T>()); return new List<T>[0]; }; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(42396, "https://github.com/dotnet/roslyn/issues/42396")] public void LocalFunction_06() { var source = @" using System; using System.Collections.Generic; class C { void M<T>() where T : class { Func<IEnumerable<List<T>>> f = () => { IEnumerable<T> Enumerate(IEnumerable<T> xs) { return xs; } Enumerate(new List<T>()); return new List<T>[0]; }; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } /// <summary> /// Should report warnings within unused local functions. /// </summary> [Fact] [WorkItem(29892, "https://github.com/dotnet/roslyn/issues/29892")] public void LocalFunction_NoCallers() { var source = @"#pragma warning disable 8321 class C { static void F1(object? x1) { void f1() { x1.ToString(); // 1 } } static void F2(object? x2) { if (x2 == null) return; void f2() { x2.ToString(); // 2 } } static void F3(object? x3) { object? y3 = x3; void f3() { y3.ToString(); // 3 } if (y3 == null) return; void g3() { y3.ToString(); // 4 } } static void F4() { void f4(object? x4) { x4.ToString(); // 5 } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(8, 13), // (16,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(16, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // y3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y3").WithLocation(24, 13), // (29,13): warning CS8602: Dereference of a possibly null reference. // y3.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y3").WithLocation(29, 13), // (36,13): warning CS8602: Dereference of a possibly null reference. // x4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(36, 13)); } [Fact] public void New_01() { var source = @"class C { static void F1() { object? x1; x1 = new object?(); // error 1 x1 = new object? { }; // error 2 x1 = (new object?[1])[0]; x1 = new object[]? {}; // error 3 } static void F2<T2>() { object? x2; x2 = new T2?(); // error 4 x2 = new T2? { }; // error 5 x2 = (new T2?[1])[0]; } static void F3<T3>() where T3 : class, new() { object? x3; x3 = new T3?(); // error 6 x3 = new T3? { }; // error 7 x3 = (new T3?[1])[0]; } static void F4<T4>() where T4 : new() { object? x4; x4 = new T4?(); // error 8 x4 = new T4? { }; // error 9 x4 = (new T4?[1])[0]; x4 = new System.Nullable<int>? { }; // error 11 } static void F5<T5>() where T5 : class { object? x5; x5 = new T5?(); // error 10 x5 = new T5? { }; // error 11 x5 = (new T5?[1])[0]; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,14): error CS8628: Cannot use a nullable reference type in object creation. // x1 = new object?(); // error 1 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new object?()").WithArguments("object").WithLocation(6, 14), // (7,14): error CS8628: Cannot use a nullable reference type in object creation. // x1 = new object? { }; // error 2 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new object? { }").WithArguments("object").WithLocation(7, 14), // (9,14): error CS8628: Cannot use a nullable reference type in object creation. // x1 = new object[]? {}; // error 3 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new object[]? {}").WithArguments("object[]").WithLocation(9, 14), // (9,18): error CS8386: Invalid object creation // x1 = new object[]? {}; // error 3 Diagnostic(ErrorCode.ERR_InvalidObjectCreation, "object[]?").WithArguments("object[]").WithLocation(9, 18), // (14,18): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // x2 = new T2?(); // error 4 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(14, 18), // (14,14): error CS8628: Cannot use a nullable reference type in object creation. // x2 = new T2?(); // error 4 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T2?()").WithArguments("T2").WithLocation(14, 14), // (14,14): error CS0304: Cannot create an instance of the variable type 'T2' because it does not have the new() constraint // x2 = new T2?(); // error 4 Diagnostic(ErrorCode.ERR_NoNewTyvar, "new T2?()").WithArguments("T2").WithLocation(14, 14), // (15,18): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // x2 = new T2? { }; // error 5 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(15, 18), // (15,14): error CS8628: Cannot use a nullable reference type in object creation. // x2 = new T2? { }; // error 5 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T2? { }").WithArguments("T2").WithLocation(15, 14), // (15,14): error CS0304: Cannot create an instance of the variable type 'T2' because it does not have the new() constraint // x2 = new T2? { }; // error 5 Diagnostic(ErrorCode.ERR_NoNewTyvar, "new T2? { }").WithArguments("T2").WithLocation(15, 14), // (16,19): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // x2 = (new T2?[1])[0]; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(16, 19), // (21,14): error CS8628: Cannot use a nullable reference type in object creation. // x3 = new T3?(); // error 6 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T3?()").WithArguments("T3").WithLocation(21, 14), // (22,14): error CS8628: Cannot use a nullable reference type in object creation. // x3 = new T3? { }; // error 7 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T3? { }").WithArguments("T3").WithLocation(22, 14), // (28,18): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // x4 = new T4?(); // error 8 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T4?").WithArguments("9.0").WithLocation(28, 18), // (28,14): error CS8628: Cannot use a nullable reference type in object creation. // x4 = new T4?(); // error 8 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T4?()").WithArguments("T4").WithLocation(28, 14), // (29,18): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // x4 = new T4? { }; // error 9 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T4?").WithArguments("9.0").WithLocation(29, 18), // (29,14): error CS8628: Cannot use a nullable reference type in object creation. // x4 = new T4? { }; // error 9 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T4? { }").WithArguments("T4").WithLocation(29, 14), // (30,19): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // x4 = (new T4?[1])[0]; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T4?").WithArguments("9.0").WithLocation(30, 19), // (31,18): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // x4 = new System.Nullable<int>? { }; // error 11 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "System.Nullable<int>?").WithArguments("System.Nullable<T>", "T", "int?").WithLocation(31, 18), // (36,14): error CS8628: Cannot use a nullable reference type in object creation. // x5 = new T5?(); // error 10 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T5?()").WithArguments("T5").WithLocation(36, 14), // (36,14): error CS0304: Cannot create an instance of the variable type 'T5' because it does not have the new() constraint // x5 = new T5?(); // error 10 Diagnostic(ErrorCode.ERR_NoNewTyvar, "new T5?()").WithArguments("T5").WithLocation(36, 14), // (37,14): error CS8628: Cannot use a nullable reference type in object creation. // x5 = new T5? { }; // error 11 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T5? { }").WithArguments("T5").WithLocation(37, 14), // (37,14): error CS0304: Cannot create an instance of the variable type 'T5' because it does not have the new() constraint // x5 = new T5? { }; // error 11 Diagnostic(ErrorCode.ERR_NoNewTyvar, "new T5? { }").WithArguments("T5").WithLocation(37, 14) ); } [Fact] public void New_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1<T1>(T1 x1) where T1 : class, new() { x1 = new T1(); } void Test2<T2>(T2 x2) where T2 : class, new() { x2 = new T2() ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } // `where T : new()` does not imply T is non-nullable. [Fact] public void New_03() { var source = @"class C { static void F1<T>() where T : new() { } static void F2<T>(T t) where T : new() { } static void G<U>() where U : class, new() { object? x = null; F1<object?>(); F2(x); U? y = null; F1<U?>(); F2(y); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void New_04() { var source = @"class C { internal object? F; internal object P { get; set; } = null!; } class Program { static void F<T>() where T : C, new() { T x = new T() { F = 1, P = null }; // 1 x.F.ToString(); x.P.ToString(); // 2 C y = new T() { F = 2, P = null }; // 3 y.F.ToString(); y.P.ToString(); // 4 C z = (C)new T() { F = 3, P = null }; // 5 z.F.ToString(); z.P.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // T x = new T() { F = 1, P = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 36), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.P").WithLocation(12, 9), // (13,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // C y = new T() { F = 2, P = null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 36), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.P").WithLocation(15, 9), // (16,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // C z = (C)new T() { F = 3, P = null }; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 39), // (18,9): warning CS8602: Dereference of a possibly null reference. // z.P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.P").WithLocation(18, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void New_05() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F<T>() where T : I, new() { T x = new T() { P = 1, Q = null }; // 1 x.P.ToString(); x.Q.ToString(); // 2 I y = new T() { P = 2, Q = null }; // 3 y.P.ToString(); y.Q.ToString(); // 4 I z = (I)new T() { P = 3, Q = null }; // 5 z.P.ToString(); z.Q.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // T x = new T() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 36), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Q").WithLocation(12, 9), // (13,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // I y = new T() { P = 2, Q = null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 36), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.Q.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Q").WithLocation(15, 9), // (16,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // I z = (I)new T() { P = 3, Q = null }; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 39), // (18,9): warning CS8602: Dereference of a possibly null reference. // z.Q.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.Q").WithLocation(18, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void New_06() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F<T>() where T : class, I, new() { T x = new T() { P = 1, Q = null }; // 1 x.P.ToString(); x.Q.ToString(); // 2 I y = new T() { P = 2, Q = null }; // 3 y.P.ToString(); y.Q.ToString(); // 4 I z = (I)new T() { P = 3, Q = null }; // 5 z.P.ToString(); z.Q.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // T x = new T() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 36), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Q").WithLocation(12, 9), // (13,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // I y = new T() { P = 2, Q = null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 36), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.Q.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Q").WithLocation(15, 9), // (16,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // I z = (I)new T() { P = 3, Q = null }; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 39), // (18,9): warning CS8602: Dereference of a possibly null reference. // z.Q.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.Q").WithLocation(18, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void New_07() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F<T>() where T : struct, I { T x = new T() { P = 1, Q = null }; // 1 x.P.ToString(); x.Q.ToString(); // 2 I y = new T() { P = 2, Q = null }; // 3 y.P.ToString(); y.Q.ToString(); // 4 I z = (I)new T() { P = 3, Q = null }; // 5 z.P.ToString(); z.Q.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // T x = new T() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 36), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Q").WithLocation(12, 9), // (13,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // I y = new T() { P = 2, Q = null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 36), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.Q.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Q").WithLocation(15, 9), // (16,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // I z = (I)new T() { P = 3, Q = null }; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 39), // (18,9): warning CS8602: Dereference of a possibly null reference. // z.Q.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.Q").WithLocation(18, 9)); } [Fact] public void DynamicObjectCreation_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = new CL0((dynamic)0); } void Test2(CL0 x2) { x2 = new CL0((dynamic)0) ?? x2; } } class CL0 { public CL0(int x) {} public CL0(long x) {} } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicObjectCreation_02() { var source = @"class C { C(object x, object y) { } static void G(object? x, dynamic y) { var o = new C(x, y); if (x != null) o = new C(y, x); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29893: We should be able to report warnings // when all applicable methods agree on the nullability of particular parameters. // (For instance, x in F(x, y) above.) comp.VerifyDiagnostics(); } [Fact] public void DynamicObjectCreation_03() { var source = @"class C { C(object f) { F = f; } object? F; object? G; static void M(dynamic d) { var o = new C(d) { G = new object() }; o.G.ToString(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void DynamicIndexerAccess_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = x1[(dynamic)0]; } void Test2(CL0 x2) { x2 = x2[(dynamic)0] ?? x2; } } class CL0 { public CL0 this[int x] { get { return new CL0(); } set { } } public CL0 this[long x] { get { return new CL0(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicIndexerAccess_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { dynamic y1 = x1[(dynamic)0]; } void Test2(CL0 x2) { dynamic y2 = x2[(dynamic)0] ?? x2; } } class CL0 { public CL0? this[int x] { get { return new CL0(); } set { } } public CL0 this[long x] { get { return new CL0(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicIndexerAccess_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { dynamic y1 = x1[(dynamic)0]; } void Test2(CL0 x2) { dynamic y2 = x2[(dynamic)0] ?? x2; } } class CL0 { public CL0 this[int x] { get { return new CL0(); } set { } } public CL0? this[long x] { get { return new CL0(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicIndexerAccess_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { dynamic y1 = x1[(dynamic)0]; } void Test2(CL0 x2) { dynamic y2 = x2[(dynamic)0] ?? x2; } } class CL0 { public CL0? this[int x] { get { return new CL0(); } set { } } public CL0? this[long x] { get { return new CL0(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicIndexerAccess_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = x1[(dynamic)0]; } void Test2(CL0 x2) { x2 = x2[(dynamic)0] ?? x2; } } class CL0 { public int this[int x] { get { return x; } set { } } public int this[long x] { get { return (int)x; } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicIndexerAccess_06() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = x1[(dynamic)0]; } void Test2(CL0 x2) { x2 = x2[(dynamic)0] ?? x2; } } class CL0 { public int this[int x] { get { return x; } set { } } public long this[long x] { get { return x; } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicIndexerAccess_07() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(dynamic x1) { x1 = x1[0]; } void Test2(dynamic x2) { x2 = x2[0] ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicIndexerAccess_08() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1<T>(CL0<T> x1) { x1 = x1[(dynamic)0]; } void Test2<T>(CL0<T> x2) { x2 = x2[(dynamic)0] ?? x2; } } class CL0<T> { public T this[int x] { get { return default(T); } set { } } public long this[long x] { get { return x; } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (22,22): warning CS8603: Possible null reference return. // get { return default(T); } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(22, 22)); } [Fact] public void DynamicIndexerAccess_09() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1, dynamic y1) { x1[(dynamic)0] = y1; } void Test2(CL0 x2, dynamic? y2, CL1 z2) { x2[(dynamic)0] = y2; z2[0] = y2; } } class CL0 { public CL0 this[int x] { get { return new CL0(); } set { } } public CL0 this[long x] { get { return new CL0(); } set { } } } class CL1 { public dynamic this[int x] { get { return new CL0(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,17): warning CS8601: Possible null reference assignment. // z2[0] = y2; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y2").WithLocation(15, 17) ); } [Fact] public void DynamicIndexerAccess_10() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0? x1) { x1 = x1[(dynamic)0]; } void Test2(CL0? x2) { x2 = x2[0]; } } class CL0 { public CL0 this[int x] { get { return new CL0(); } set { } } public CL0 this[long x] { get { return new CL0(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,14): warning CS8602: Dereference of a possibly null reference. // x1 = x1[(dynamic)0]; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(9, 14), // (14,14): warning CS8602: Dereference of a possibly null reference. // x2 = x2[0]; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(14, 14) ); } [Fact] public void DynamicInvocation_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = x1.M1((dynamic)0); } void Test2(CL0 x2) { x2 = x2.M1((dynamic)0) ?? x2; } } class CL0 { public CL0 M1(int x) { return new CL0(); } public CL0 M1(long x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicInvocation_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { dynamic y1 = x1.M1((dynamic)0); } void Test2(CL0 x2) { dynamic y2 = x2.M1((dynamic)0) ?? x2; } } class CL0 { public CL0? M1(int x) { return new CL0(); } public CL0 M1(long x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicInvocation_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { dynamic y1 = x1.M1((dynamic)0); } void Test2(CL0 x2) { dynamic y2 = x2.M1((dynamic)0) ?? x2; } } class CL0 { public CL0 M1(int x) { return new CL0(); } public CL0? M1(long x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicInvocation_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { dynamic y1 = x1.M1((dynamic)0); } void Test2(CL0 x2) { dynamic y2 = x2.M1((dynamic)0) ?? x2; } } class CL0 { public CL0? M1(int x) { return new CL0(); } public CL0? M1(long x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicInvocation_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = x1.M1((dynamic)0); } void Test2(CL0 x2) { x2 = x2.M1((dynamic)0) ?? x2; } } class CL0 { public int M1(int x) { return x; } public int M1(long x) { return (int)x; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicInvocation_06() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = x1.M1((dynamic)0); } void Test2(CL0 x2) { x2 = x2.M1((dynamic)0) ?? x2; } } class CL0 { public int M1(int x) { return x; } public long M1(long x) { return x; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicInvocation_07() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(dynamic x1) { x1 = x1.M1(0); } void Test2(dynamic x2) { x2 = x2.M1(0) ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicInvocation_08() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1<T>(CL0<T> x1) { x1 = x1.M1((dynamic)0); } void Test2<T>(CL0<T> x2) { x2 = x2.M1((dynamic)0) ?? x2; } } class CL0<T> { public T M1(int x) { return default(T); } public long M1(long x) { return x; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (22,16): warning CS8603: Possible null reference return. // return default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(22, 16)); } [Fact] public void DynamicInvocation_09() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0? x1) { x1 = x1.M1((dynamic)0); } void Test2(CL0? x2) { x2 = x2.M1(0); } } class CL0 { public CL0 M1(int x) { return new CL0(); } public CL0 M1(long x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,14): warning CS8602: Dereference of a possibly null reference. // x1 = x1.M1((dynamic)0); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(9, 14), // (14,14): warning CS8602: Dereference of a possibly null reference. // x2 = x2.M1(0); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(14, 14) ); } [Fact] public void DynamicMemberAccess_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(dynamic x1) { x1 = x1.M1; } void Test2(dynamic x2) { x2 = x2.M1 ?? x2; } void Test3(dynamic? x3) { dynamic y3 = x3.M1; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (19,22): warning CS8602: Dereference of a possibly null reference. // dynamic y3 = x3.M1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(19, 22) ); } [Fact] public void DynamicMemberAccess_02() { var source = @"class C { static void M(dynamic x) { x.F/*T:dynamic!*/.ToString(); var y = x.F; y/*T:dynamic!*/.ToString(); y = null; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void DynamicObjectCreationExpression_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1() { dynamic? x1 = null; CL0 y1 = new CL0(x1); } void Test2(CL0 y2) { dynamic? x2 = null; CL0 z2 = new CL0(x2) ?? y2; } } class CL0 { public CL0(int x) { } public CL0(long x) { } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicInvocation() { var source = @"class C { static void F(object x, object y) { } static void G(object? x, dynamic y) { F(x, y); if (x != null) F(y, x); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29893: We should be able to report warnings // when all applicable methods agree on the nullability of particular parameters. // (For instance, x in F(x, y) above.) comp.VerifyDiagnostics(); } [Fact] public void NameOf_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(string x1, string? y1) { x1 = nameof(y1); } void Test2(string x2, string? y2) { string? z2 = nameof(y2); x2 = z2 ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void StringInterpolation_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(string x1, string? y1) { x1 = $""{y1}""; } void Test2(string x2, string? y2) { x2 = $""{y2}"" ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Theory] [CombinatorialData] public void StringInterpolation_02(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{s = """"}{s.ToString()}""", @"$""{s = """"}"" + $""{s.ToString()}""")] string expression) { CSharpCompilation c = CreateCompilation(new[] { @" #nullable enable string? s = null; M(" + expression + @", s); void M(CustomHandler c, string s) {} ", GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns, includeTrailingOutConstructorParameter: validityParameter) }, parseOptions: TestOptions.RegularPreview); if (validityParameter) { c.VerifyDiagnostics( // (5,30): warning CS8604: Possible null reference argument for parameter 's' in 'void M(CustomHandler c, string s)'. // M($"{s = ""}{s.ToString()}", s); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s").WithArguments("s", "void M(CustomHandler c, string s)").WithLocation(5, 19 + expression.IndexOf("s.ToString")) ); } else { c.VerifyDiagnostics(); } } [Theory] [CombinatorialData] public void StringInterpolation_03(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; #nullable enable string? s = """"; M( #line 1000 ref s, #line 2000 " + expression + @", #line 3000 s.ToString()); void M<T>(ref T t1, [InterpolatedStringHandlerArgument(""t1"")] CustomHandler<T> c, T t2) {} public partial struct CustomHandler<T> { public CustomHandler(int literalLength, int formattedCount, [MaybeNull] ref T t " + (validityParameter ? ", out bool success" : "") + @") : this() { " + (validityParameter ? "success = true;" : "") + @" } } ", GetInterpolatedStringCustomHandlerType("CustomHandler<T>", "partial struct", useBoolReturns, includeTrailingOutConstructorParameter: validityParameter), InterpolatedStringHandlerArgumentAttribute, MaybeNullAttributeDefinition }, parseOptions: TestOptions.RegularPreview); // https://github.com/dotnet/roslyn/issues/54583 // Should be a warning on `s.ToString()` c.VerifyDiagnostics( // (1000,9): warning CS8601: Possible null reference assignment. // ref s, Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(1000, 9) ); } [Theory] [CombinatorialData] public void StringInterpolation_04(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s = null; M(s, " + expression + @"); void M(string? s1, [InterpolatedStringHandlerArgument(""s1"")] CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s" + (validityParameter ? ", out bool success" : "") + @") : this() { " + (validityParameter ? "success = true;" : "") + @" } } ", GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns, includeTrailingOutConstructorParameter: validityParameter), InterpolatedStringHandlerArgumentAttribute }, parseOptions: TestOptions.RegularPreview); // https://github.com/dotnet/roslyn/issues/54583 // Should be a warning for the constructor parameter c.VerifyDiagnostics( ); } [Theory] [CombinatorialData] public void StringInterpolation_05(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{s}""", @"$""{s}"" + $""""")] string expression) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s = null; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + (validityParameter ? ", out bool success" : "") + @") : this() { " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted(object o) { return " + (useBoolReturns ? "true" : "") + @"; } } ", InterpolatedStringHandlerAttribute }, parseOptions: TestOptions.RegularPreview); c.VerifyDiagnostics( // (6,6): warning CS8604: Possible null reference argument for parameter 'o' in 'void CustomHandler.AppendFormatted(object o)'. // M($"{s}"); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s").WithArguments("o", (useBoolReturns ? "bool" : "void") + " CustomHandler.AppendFormatted(object o)").WithLocation(6, 6) ); } [Theory] [CombinatorialData] public void StringInterpolation_06(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{s = null}{s = """"}""", @"$""{s = null}"" + $""{s = """"}""")] string expression) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s = """"; M(" + expression + @"); _ = s.ToString(); void M(CustomHandler c) {} [InterpolatedStringHandler] public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + (validityParameter ? ", out bool success" : "") + @") : this() { " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted(object? o) { return " + (useBoolReturns ? "true" : "") + @"; } } ", InterpolatedStringHandlerAttribute }, parseOptions: TestOptions.RegularPreview); if (useBoolReturns) { c.VerifyDiagnostics( // (7,5): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 5) ); } else { c.VerifyDiagnostics( ); } } [Theory] [CombinatorialData] public void StringInterpolation_07(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{s1 = null}{s2 = null}{s3 = null}{s1 = """"}{s2 = """"}{s3 = """"}""", @"$""{s1 = null}"" + $""{s2 = null}"" + $""{s3 = null}"" + $""{s1 = """"}"" + $""{s2 = """"}"" + $""{s3 = """"}""")] string expression) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s1 = """"; string? s2 = """"; string? s3 = """"; M(" + expression + @"); _ = s1.ToString(); _ = s2.ToString(); _ = s3.ToString(); void M(CustomHandler c) {} [InterpolatedStringHandler] public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + (validityParameter ? ", out bool success" : "") + @") : this() { " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted(object? o) { return " + (useBoolReturns ? "true" : "") + @"; } } ", InterpolatedStringHandlerAttribute }, parseOptions: TestOptions.RegularPreview); if (useBoolReturns) { c.VerifyDiagnostics( // (9,5): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 5), // (10,5): warning CS8602: Dereference of a possibly null reference. // _ = s2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 5), // (11,5): warning CS8602: Dereference of a possibly null reference. // _ = s3.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(11, 5) ); } else { c.VerifyDiagnostics(); } } [Fact] public void DelegateCreation_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(System.Action x1) { x1 = new System.Action(Main); } void Test2(System.Action x2) { x2 = new System.Action(Main) ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DelegateCreation_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL0<string?> M1(CL0<string> x) { throw new System.Exception(); } CL0<string> M2(CL0<string> x) { throw new System.Exception(); } delegate CL0<string> D1(CL0<string?> x); void Test1() { D1 x1 = new D1(M1); D1 x2 = new D1(M2); } CL0<string> M3(CL0<string?> x) { throw new System.Exception(); } CL0<string?> M4(CL0<string?> x) { throw new System.Exception(); } delegate CL0<string?> D2(CL0<string> x); void Test2() { D2 x1 = new D2(M3); D2 x2 = new D2(M4); } } class CL0<T>{} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (14,24): warning CS8621: Nullability of reference types in return type of 'CL0<string?> C.M1(CL0<string> x)' doesn't match the target delegate 'C.D1' (possibly because of nullability attributes). // D1 x1 = new D1(M1); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M1").WithArguments("CL0<string?> C.M1(CL0<string> x)", "C.D1").WithLocation(14, 24), // (15,24): warning CS8622: Nullability of reference types in type of parameter 'x' of 'CL0<string> C.M2(CL0<string> x)' doesn't match the target delegate 'C.D1' (possibly because of nullability attributes). // D1 x2 = new D1(M2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M2").WithArguments("x", "CL0<string> C.M2(CL0<string> x)", "C.D1").WithLocation(15, 24), // (24,24): warning CS8621: Nullability of reference types in return type of 'CL0<string> C.M3(CL0<string?> x)' doesn't match the target delegate 'C.D2' (possibly because of nullability attributes). // D2 x1 = new D2(M3); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M3").WithArguments("CL0<string> C.M3(CL0<string?> x)", "C.D2").WithLocation(24, 24), // (25,24): warning CS8622: Nullability of reference types in type of parameter 'x' of 'CL0<string?> C.M4(CL0<string?> x)' doesn't match the target delegate 'C.D2' (possibly because of nullability attributes). // D2 x2 = new D2(M4); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M4").WithArguments("x", "CL0<string?> C.M4(CL0<string?> x)", "C.D2").WithLocation(25, 24) ); } [Fact] public void DelegateCreation_03() { var source = @"delegate void D(object x, object? y); class Program { static void Main() { _ = new D((object x1, object? y1) => { x1 = null; // 1 y1.ToString(); // 2 }); _ = new D((x2, y2) => { x2 = null; // 3 y2.ToString(); // 4 }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 22), // (9,17): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(9, 17), // (13,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = null; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 22), // (14,17): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(14, 17)); } [Fact] public void DelegateCreation_04() { var source = @"delegate object D1(); delegate object? D2(); class Program { static void F(object x, object? y) { x = null; // 1 y = 2; _ = new D1(() => x); // 2 _ = new D2(() => x); _ = new D1(() => y); _ = new D2(() => y); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 13), // (9,26): warning CS8603: Possible null reference return. // _ = new D1(() => x); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x").WithLocation(9, 26)); } [Fact] [WorkItem(35549, "https://github.com/dotnet/roslyn/issues/35549")] public void DelegateCreation_05() { var source = @"delegate T D<T>(); class Program { static T F<T>() => throw null!; static void G<T>() where T : class { _ = new D<T?>(F<T>)!; _ = new D<T?>(F<T>!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,25): error CS0119: 'T' is a type, which is not valid in the given context // _ = new D<T?>(F<T>!); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(8, 25), // (8,28): error CS1525: Invalid expression term ')' // _ = new D<T?>(F<T>!); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(8, 28)); } [Fact] public void DelegateCreation_06() { var source = @"delegate T D<T>(); class Program { static T F<T>() => throw null!; static void G<T>() where T : class { _ = new D<T>(F<T?>)!; // 1 _ = new D<T>(F<T?>!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,22): warning CS8621: Nullability of reference types in return type of 'T? Program.F<T?>()' doesn't match the target delegate 'D<T>'. // _ = new D<T>(F<T?>)!; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<T?>").WithArguments("T? Program.F<T?>()", "D<T>").WithLocation(7, 22)); } [Fact] public void DelegateCreation_07() { var source = @"delegate T D<T>(); class Program { static T F<T>() => throw null!; static void G<T>() where T : class { _ = new D<T?>(() => F<T>())!; _ = new D<T?>(() => F<T>()!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void DelegateCreation_08() { var source = @"delegate T D<T>(); class Program { static T F<T>() => throw null!; static void G<T>() where T : class { _ = new D<T>(() => F<T?>())!; // 1 _ = new D<T>(() => F<T?>()!); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,28): warning CS8603: Possible null reference return. // _ = new D<T>(() => F<T?>())!; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "F<T?>()").WithLocation(7, 28)); } [Fact] public void DelegateCreation_09() { var source = @"delegate void D(); class C { void F() { } static void M() { D d = default(C).F; // 1 _ = new D(default(C).F); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // D d = default(C).F; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(C)").WithLocation(7, 15), // (8,19): warning CS8602: Dereference of a possibly null reference. // _ = new D(default(C).F); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(C)").WithLocation(8, 19)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_ReturnType_01() { var source = @"delegate T D<T>(); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>() => throw null!; static void Main() { _ = new D<object>(() => F<object?>()); // 1 _ = new D<object?>(() => F<object>()); _ = new D<I<object>>(() => F<I<object?>>()); // 2 _ = new D<I<object?>>(() => F<I<object>>()); // 3 _ = new D<IIn<object>>(() => F<IIn<object?>>()); _ = new D<IIn<object?>>(() => F<IIn<object>>()); // 4 _ = new D<IOut<object>>(() => F<IOut<object?>>()); // 5 _ = new D<IOut<object?>>(() => F<IOut<object>>()); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,33): warning CS8603: Possible null reference return. // _ = new D<object>(() => F<object?>()); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "F<object?>()").WithLocation(10, 33), // (12,36): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // _ = new D<I<object>>(() => F<I<object?>>()); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "F<I<object?>>()").WithArguments("I<object?>", "I<object>").WithLocation(12, 36), // (13,37): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // _ = new D<I<object?>>(() => F<I<object>>()); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "F<I<object>>()").WithArguments("I<object>", "I<object?>").WithLocation(13, 37), // (15,39): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // _ = new D<IIn<object?>>(() => F<IIn<object>>()); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "F<IIn<object>>()").WithArguments("IIn<object>", "IIn<object?>").WithLocation(15, 39), // (16,39): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // _ = new D<IOut<object>>(() => F<IOut<object?>>()); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "F<IOut<object?>>()").WithArguments("IOut<object?>", "IOut<object>").WithLocation(16, 39)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_ReturnType_02() { var source = @"delegate T D<T>(); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>() => throw null!; static void Main() { _ = new D<object>(F<object?>); // 1 _ = new D<object?>(F<object>); _ = new D<I<object>>(F<I<object?>>); // 2 _ = new D<I<object?>>(F<I<object>>); // 3 _ = new D<IIn<object>>(F<IIn<object?>>); _ = new D<IIn<object?>>(F<IIn<object>>); // 4 _ = new D<IOut<object>>(F<IOut<object?>>); // 5 _ = new D<IOut<object?>>(F<IOut<object>>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,27): warning CS8621: Nullability of reference types in return type of 'object? C.F<object?>()' doesn't match the target delegate 'D<object>'. // _ = new D<object>(F<object?>); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<object?>").WithArguments("object? C.F<object?>()", "D<object>").WithLocation(10, 27), // (12,30): warning CS8621: Nullability of reference types in return type of 'I<object?> C.F<I<object?>>()' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>(F<I<object?>>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<I<object?>>").WithArguments("I<object?> C.F<I<object?>>()", "D<I<object>>").WithLocation(12, 30), // (13,31): warning CS8621: Nullability of reference types in return type of 'I<object> C.F<I<object>>()' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>(F<I<object>>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<I<object>>").WithArguments("I<object> C.F<I<object>>()", "D<I<object?>>").WithLocation(13, 31), // (15,33): warning CS8621: Nullability of reference types in return type of 'IIn<object> C.F<IIn<object>>()' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>(F<IIn<object>>); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<IIn<object>>").WithArguments("IIn<object> C.F<IIn<object>>()", "D<IIn<object?>>").WithLocation(15, 33), // (16,33): warning CS8621: Nullability of reference types in return type of 'IOut<object?> C.F<IOut<object?>>()' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>(F<IOut<object?>>); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<IOut<object?>>").WithArguments("IOut<object?> C.F<IOut<object?>>()", "D<IOut<object>>").WithLocation(16, 33)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_Parameter_01() { var source = @"delegate void D<T>(T t1); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void Main() { // parameter name is different than delegate to ensure that diagnostics refer to the correct names _ = new D<object>((object? t2) => { }); // 1 _ = new D<object?>((object t2) => { }); // 2 _ = new D<I<object>>((I<object?> t2) => { }); // 3 _ = new D<I<object?>>((I<object> t2) => { }); // 4 _ = new D<IIn<object>>((IIn<object?> t2) => { }); // 5 _ = new D<IIn<object?>>((IIn<object> t2) => { }); // 6 _ = new D<IOut<object>>((IOut<object?> t2) => { }); // 7 _ = new D<IOut<object?>>((IOut<object> t2) => { }); // 8 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,40): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<object>'. // _ = new D<object>((object? t2) => { }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<object>").WithLocation(10, 40), // (11,40): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>((object t2) => { }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<object?>").WithLocation(11, 40), // (12,46): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>((I<object?> t2) => { }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<I<object>>").WithLocation(12, 46), // (13,46): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>((I<object> t2) => { }); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<I<object?>>").WithLocation(13, 46), // (14,50): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>((IIn<object?> t2) => { }); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IIn<object>>").WithLocation(14, 50), // (15,50): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>((IIn<object> t2) => { }); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IIn<object?>>").WithLocation(15, 50), // (16,52): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>((IOut<object?> t2) => { }); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IOut<object>>").WithLocation(16, 52), // (17,52): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>((IOut<object> t2) => { }); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IOut<object?>>").WithLocation(17, 52)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_Parameter_02() { var source = @"delegate void D<T>(T t1); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { // parameter name is different than delegate to ensure that diagnostics refer to the correct names static void F<T>(T t2) { } static void Main() { _ = new D<object>(F<object?>); _ = new D<object?>(F<object>); // 1 _ = new D<I<object>>(F<I<object?>>); // 2 _ = new D<I<object?>>(F<I<object>>); // 3 _ = new D<IIn<object>>(F<IIn<object?>>); // 4 _ = new D<IIn<object?>>(F<IIn<object>>); _ = new D<IOut<object>>(F<IOut<object?>>); _ = new D<IOut<object?>>(F<IOut<object>>); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,28): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<object>(object t2)' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>(F<object>); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object>").WithArguments("t2", "void C.F<object>(object t2)", "D<object?>").WithLocation(12, 28), // (13,30): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<I<object?>>(I<object?> t2)' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>(F<I<object?>>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t2", "void C.F<I<object?>>(I<object?> t2)", "D<I<object>>").WithLocation(13, 30), // (14,31): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<I<object>>(I<object> t2)' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>(F<I<object>>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t2", "void C.F<I<object>>(I<object> t2)", "D<I<object?>>").WithLocation(14, 31), // (15,32): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<IIn<object?>>(IIn<object?> t2)' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>(F<IIn<object?>>); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object?>>").WithArguments("t2", "void C.F<IIn<object?>>(IIn<object?> t2)", "D<IIn<object>>").WithLocation(15, 32), // (18,34): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<IOut<object>>(IOut<object> t2)' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>(F<IOut<object>>); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object>>").WithArguments("t2", "void C.F<IOut<object>>(IOut<object> t2)", "D<IOut<object?>>").WithLocation(18, 34)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_OutParameter_01() { var source = @"delegate void D<T>(out T t1); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void Main() { // parameter name is different than delegate to ensure that diagnostics refer to the correct names _ = new D<object>((out object? t2) => t2 = default!); // 1 _ = new D<object?>((out object t2) => t2 = default!); // 2 _ = new D<I<object>>((out I<object?> t2) => t2 = default!); // 3 _ = new D<I<object?>>((out I<object> t2) => t2 = default!); // 4 _ = new D<IIn<object>>((out IIn<object?> t2) => t2 = default!); // 5 _ = new D<IIn<object?>>((out IIn<object> t2) => t2 = default!); // 6 _ = new D<IOut<object>>((out IOut<object?> t2) => t2 = default!); // 7 _ = new D<IOut<object?>>((out IOut<object> t2) => t2 = default!); // 8 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,44): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<object>'. // _ = new D<object>((out object? t2) => t2 = default!); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<object>").WithLocation(10, 44), // (11,44): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>((out object t2) => t2 = default!); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<object?>").WithLocation(11, 44), // (12,50): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>((out I<object?> t2) => t2 = default!); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<I<object>>").WithLocation(12, 50), // (13,50): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>((out I<object> t2) => t2 = default!); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<I<object?>>").WithLocation(13, 50), // (14,54): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>((out IIn<object?> t2) => t2 = default!); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IIn<object>>").WithLocation(14, 54), // (15,54): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>((out IIn<object> t2) => t2 = default!); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IIn<object?>>").WithLocation(15, 54), // (16,56): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>((out IOut<object?> t2) => t2 = default!); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IOut<object>>").WithLocation(16, 56), // (17,56): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>((out IOut<object> t2) => t2 = default!); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IOut<object?>>").WithLocation(17, 56)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_OutParameter_02() { var source = @"delegate void D<T>(out T t1); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { // parameter name is different than delegate to ensure that diagnostics refer to the correct names static void F<T>(out T t2) { t2 = default!; } static void Main() { _ = new D<object>(F<object?>); // 1 _ = new D<object?>(F<object>); _ = new D<I<object>>(F<I<object?>>); // 2 _ = new D<I<object?>>(F<I<object>>); // 3 _ = new D<IIn<object>>(F<IIn<object?>>); _ = new D<IIn<object?>>(F<IIn<object>>); // 4 _ = new D<IOut<object>>(F<IOut<object?>>); // 5 _ = new D<IOut<object?>>(F<IOut<object>>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,27): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<object?>(out object? t2)' doesn't match the target delegate 'D<object>'. // _ = new D<object>(F<object?>); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object?>").WithArguments("t2", "void C.F<object?>(out object? t2)", "D<object>").WithLocation(11, 27), // (13,30): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<I<object?>>(out I<object?> t2)' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>(F<I<object?>>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t2", "void C.F<I<object?>>(out I<object?> t2)", "D<I<object>>").WithLocation(13, 30), // (14,31): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<I<object>>(out I<object> t2)' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>(F<I<object>>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t2", "void C.F<I<object>>(out I<object> t2)", "D<I<object?>>").WithLocation(14, 31), // (16,33): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<IIn<object>>(out IIn<object> t2)' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>(F<IIn<object>>); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object>>").WithArguments("t2", "void C.F<IIn<object>>(out IIn<object> t2)", "D<IIn<object?>>").WithLocation(16, 33), // (17,33): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<IOut<object?>>(out IOut<object?> t2)' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>(F<IOut<object?>>); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object?>>").WithArguments("t2", "void C.F<IOut<object?>>(out IOut<object?> t2)", "D<IOut<object>>").WithLocation(17, 33)); } [Fact] [WorkItem(32563, "https://github.com/dotnet/roslyn/issues/32563")] public void DelegateCreation_InParameter_01() { var source = @"delegate void D<T>(in T t1); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void Main() { // parameter name is different than delegate to ensure that diagnostics refer to the correct names _ = new D<object>((in object? t2) => { }); // 1 _ = new D<object?>((in object t2) => { }); // 2 _ = new D<I<object>>((in I<object?> t2) => { }); // 3 _ = new D<I<object?>>((in I<object> t2) => { }); // 4 _ = new D<IIn<object>>((in IIn<object?> t2) => { }); // 5 _ = new D<IIn<object?>>((in IIn<object> t2) => { }); // 6 _ = new D<IOut<object>>((in IOut<object?> t2) => { }); // 7 _ = new D<IOut<object?>>((in IOut<object> t2) => { }); // 8 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,43): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<object>'. // _ = new D<object>((in object? t2) => { }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<object>").WithLocation(10, 43), // (11,43): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>((in object t2) => { }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<object?>").WithLocation(11, 43), // (12,49): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>((in I<object?> t2) => { }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<I<object>>").WithLocation(12, 49), // (13,49): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>((in I<object> t2) => { }); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<I<object?>>").WithLocation(13, 49), // (14,53): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>((in IIn<object?> t2) => { }); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IIn<object>>").WithLocation(14, 53), // (15,53): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>((in IIn<object> t2) => { }); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IIn<object?>>").WithLocation(15, 53), // (16,55): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>((in IOut<object?> t2) => { }); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IOut<object>>").WithLocation(16, 55), // (17,55): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>((in IOut<object> t2) => { }); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IOut<object?>>").WithLocation(17, 55)); } [Fact] [WorkItem(32563, "https://github.com/dotnet/roslyn/issues/32563")] public void DelegateCreation_InParameter_02() { var source = @"delegate void D<T>(in T t1); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { // parameter name is different than delegate to ensure that diagnostics refer to the correct names static void F<T>(in T t2) { } static void Main() { _ = new D<object>(F<object?>); _ = new D<object?>(F<object>); // 1 _ = new D<I<object>>(F<I<object?>>); // 2 _ = new D<I<object?>>(F<I<object>>); // 3 _ = new D<IIn<object>>(F<IIn<object?>>); // 4 _ = new D<IIn<object?>>(F<IIn<object>>); _ = new D<IOut<object>>(F<IOut<object?>>); _ = new D<IOut<object?>>(F<IOut<object>>); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,28): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<object>(in object t2)' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>(F<object>); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object>").WithArguments("t2", "void C.F<object>(in object t2)", "D<object?>").WithLocation(12, 28), // (13,30): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<I<object?>>(in I<object?> t2)' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>(F<I<object?>>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t2", "void C.F<I<object?>>(in I<object?> t2)", "D<I<object>>").WithLocation(13, 30), // (14,31): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<I<object>>(in I<object> t2)' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>(F<I<object>>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t2", "void C.F<I<object>>(in I<object> t2)", "D<I<object?>>").WithLocation(14, 31), // (15,32): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<IIn<object?>>(in IIn<object?> t2)' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>(F<IIn<object?>>); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object?>>").WithArguments("t2", "void C.F<IIn<object?>>(in IIn<object?> t2)", "D<IIn<object>>").WithLocation(15, 32), // (18,34): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<IOut<object>>(in IOut<object> t2)' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>(F<IOut<object>>); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object>>").WithArguments("t2", "void C.F<IOut<object>>(in IOut<object> t2)", "D<IOut<object?>>").WithLocation(18, 34)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_RefParameter_01() { var source = @"delegate void D<T>(ref T t); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void Main() { _ = new D<object>((ref object? t) => { }); // 1 _ = new D<object?>((ref object t) => { }); // 2 _ = new D<I<object>>((ref I<object?> t) => { }); // 3 _ = new D<I<object?>>((ref I<object> t) => { }); // 4 _ = new D<IIn<object>>((ref IIn<object?> t) => { }); // 5 _ = new D<IIn<object?>>((ref IIn<object> t) => { }); // 6 _ = new D<IOut<object>>((ref IOut<object?> t) => { }); // 7 _ = new D<IOut<object?>>((ref IOut<object> t) => { }); // 8 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,43): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<object>'. // _ = new D<object>((ref object? t) => { }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<object>").WithLocation(9, 43), // (10,43): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>((ref object t) => { }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<object?>").WithLocation(10, 43), // (11,49): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>((ref I<object?> t) => { }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<I<object>>").WithLocation(11, 49), // (12,49): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>((ref I<object> t) => { }); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<I<object?>>").WithLocation(12, 49), // (13,53): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>((ref IIn<object?> t) => { }); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<IIn<object>>").WithLocation(13, 53), // (14,53): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>((ref IIn<object> t) => { }); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<IIn<object?>>").WithLocation(14, 53), // (15,55): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>((ref IOut<object?> t) => { }); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<IOut<object>>").WithLocation(15, 55), // (16,55): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>((ref IOut<object> t) => { }); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<IOut<object?>>").WithLocation(16, 55)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_RefParameter_02() { var source = @"delegate void D<T>(ref T t); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F<T>(ref T t) { } static void Main() { _ = new D<object>(F<object?>); // 1 _ = new D<object?>(F<object>); // 2 _ = new D<I<object>>(F<I<object?>>); // 3 _ = new D<I<object?>>(F<I<object>>); // 4 _ = new D<IIn<object>>(F<IIn<object?>>); // 5 _ = new D<IIn<object?>>(F<IIn<object>>); // 6 _ = new D<IOut<object>>(F<IOut<object?>>); // 7 _ = new D<IOut<object?>>(F<IOut<object>>); // 8 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,27): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object?>(ref object? t)' doesn't match the target delegate 'D<object>'. // _ = new D<object>(F<object?>); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object?>").WithArguments("t", "void C.F<object?>(ref object? t)", "D<object>").WithLocation(10, 27), // (11,28): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object>(ref object t)' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>(F<object>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object>").WithArguments("t", "void C.F<object>(ref object t)", "D<object?>").WithLocation(11, 28), // (12,30): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object?>>(ref I<object?> t)' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>(F<I<object?>>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t", "void C.F<I<object?>>(ref I<object?> t)", "D<I<object>>").WithLocation(12, 30), // (13,31): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object>>(ref I<object> t)' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>(F<I<object>>); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t", "void C.F<I<object>>(ref I<object> t)", "D<I<object?>>").WithLocation(13, 31), // (14,32): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object?>>(ref IIn<object?> t)' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>(F<IIn<object?>>); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object?>>").WithArguments("t", "void C.F<IIn<object?>>(ref IIn<object?> t)", "D<IIn<object>>").WithLocation(14, 32), // (15,33): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object>>(ref IIn<object> t)' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>(F<IIn<object>>); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object>>").WithArguments("t", "void C.F<IIn<object>>(ref IIn<object> t)", "D<IIn<object?>>").WithLocation(15, 33), // (16,33): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object?>>(ref IOut<object?> t)' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>(F<IOut<object?>>); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object?>>").WithArguments("t", "void C.F<IOut<object?>>(ref IOut<object?> t)", "D<IOut<object>>").WithLocation(16, 33), // (17,34): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object>>(ref IOut<object> t)' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>(F<IOut<object>>); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object>>").WithArguments("t", "void C.F<IOut<object>>(ref IOut<object> t)", "D<IOut<object?>>").WithLocation(17, 34)); } [Fact] [WorkItem(37984, "https://github.com/dotnet/roslyn/issues/37984")] public void DelegateCreation_FromCompatibleDelegate() { var source = @" using System; delegate void D(); class C { void M(Action a1, Action? a2, D d1, D? d2) { _ = new D(a1); _ = new D(a2); // 1 _ = new D(a2!); _ = new Action(d1); _ = new Action(d2); // 2 _ = new Action(d2!); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,19): warning CS8601: Possible null reference assignment. // _ = new D(a2); // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "a2").WithLocation(11, 19), // (14,24): warning CS8601: Possible null reference assignment. // _ = new Action(d2); // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "d2").WithLocation(14, 24)); } [Fact] [WorkItem(37984, "https://github.com/dotnet/roslyn/issues/37984")] public void DelegateCreation_FromNullableMismatchedDelegate() { var source = @" using System; delegate void D1(string s); delegate void D2(string? s); class C { void M(Action<string> a1, Action<string?> a2, D1 d1, D2 d2) { _ = new D1(a1); _ = new D1(a2); _ = new D2(a1); // 1 _ = new D2(a1!); _ = new D2(a2); _ = new D1(d1); _ = new D1(d2); _ = new D2(d1); // 2 _ = new D2(d1!); _ = new D2(d2); _ = new Action<string>(d1); _ = new Action<string>(d2); _ = new Action<string?>(d1); // 3 _ = new Action<string?>(d1!); _ = new Action<string?>(d2); _ = new Action<string>(a1); _ = new Action<string>(a2); _ = new Action<string?>(a1); // 4 _ = new Action<string?>(a1!); _ = new Action<string?>(a2); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (13,20): warning CS8622: Nullability of reference types in type of parameter 'obj' of 'void Action<string>.Invoke(string obj)' doesn't match the target delegate 'D2'. // _ = new D2(a1); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "a1").WithArguments("obj", "void Action<string>.Invoke(string obj)", "D2").WithLocation(13, 20), // (19,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'void D1.Invoke(string s)' doesn't match the target delegate 'D2'. // _ = new D2(d1); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "d1").WithArguments("s", "void D1.Invoke(string s)", "D2").WithLocation(19, 20), // (25,33): warning CS8622: Nullability of reference types in type of parameter 's' of 'void D1.Invoke(string s)' doesn't match the target delegate 'Action<string?>'. // _ = new Action<string?>(d1); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "d1").WithArguments("s", "void D1.Invoke(string s)", "System.Action<string?>").WithLocation(25, 33), // (31,33): warning CS8622: Nullability of reference types in type of parameter 'obj' of 'void Action<string>.Invoke(string obj)' doesn't match the target delegate 'Action<string?>'. // _ = new Action<string?>(a1); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "a1").WithArguments("obj", "void Action<string>.Invoke(string obj)", "System.Action<string?>").WithLocation(31, 33)); } [Fact] [WorkItem(37984, "https://github.com/dotnet/roslyn/issues/37984")] public void DelegateCreation_Oblivious() { var source = @" using System; class C { void M(Action<string>? a1) { // even though the delegate is declared in a disabled context, the delegate creation still requires a not-null delegate argument _ = new D1(a1); // 1 _ = new D1(a1!); } } #nullable disable delegate void D1(string s); "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,20): warning CS8601: Possible null reference assignment. // _ = new D1(a1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "a1").WithLocation(9, 20)); } [Fact] [WorkItem(37984, "https://github.com/dotnet/roslyn/issues/37984")] public void DelegateCreation_Errors() { var source = @" using System; delegate void D1(string s); delegate void D2(string? s); class C { void M() { _ = new D1(null); // 1 _ = new D1((Action<string>?)null); // 2 _ = new D1((Action<string>)null!); _ = new D1(default(D1)); // 3 _ = new D1(default(D1)!); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,20): error CS0149: Method name expected // _ = new D1(null); // 1 Diagnostic(ErrorCode.ERR_MethodNameExpected, "null").WithLocation(11, 20), // (12,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // _ = new D1((Action<string>?)null); // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(Action<string>?)null").WithLocation(12, 20), // (14,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // _ = new D1(default(D1)); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default(D1)").WithLocation(14, 20)); } [Fact] [WorkItem(37984, "https://github.com/dotnet/roslyn/issues/37984")] public void DelegateCreation_UpdateArgumentFlowState() { var source = @" using System; delegate void D1(); class C { void M(Action? a) { _ = new D1(a); // 1 a(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (10,20): warning CS8601: Possible null reference assignment. // _ = new D1(a); // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "a").WithLocation(10, 20)); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44129")] public void DelegateCreation_FromMethodGroup_NullabilityAttributes_01() { var source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [return: MaybeNull] public string M1() => null; public void M2([DisallowNull] string? s2) { } } static class Program { static void M3(this C c, [DisallowNull] string? s2) { } static void M() { var c = new C(); _ = new Func<string>(c.M1); // 1 _ = new Action<string?>(c.M2); // 2 _ = new Action<string?>(c.M3); // 3 } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (19,30): warning CS8621: Nullability of reference types in return type of 'string C.M1()' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes). // _ = new Func<string>(c.M1); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "c.M1").WithArguments("string C.M1()", "System.Func<string>").WithLocation(19, 30), // (20,33): warning CS8622: Nullability of reference types in type of parameter 's2' of 'void C.M2(string? s2)' doesn't match the target delegate 'Action<string?>' (possibly because of nullability attributes). // _ = new Action<string?>(c.M2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M2").WithArguments("s2", "void C.M2(string? s2)", "System.Action<string?>").WithLocation(20, 33), // (21,33): warning CS8622: Nullability of reference types in type of parameter 's2' of 'void Program.M3(C c, string? s2)' doesn't match the target delegate 'Action<string?>' (possibly because of nullability attributes). // _ = new Action<string?>(c.M3); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M3").WithArguments("s2", "void Program.M3(C c, string? s2)", "System.Action<string?>").WithLocation(21, 33) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44129")] public void DelegateCreation_FromMethodGroup_NullabilityAttributes_02() { var source = @" using System.Diagnostics.CodeAnalysis; delegate void D1(out string s); delegate bool D2(out string s); delegate void D3(ref string s); class C { public void M1(out string s) => throw null!; public void M2(out string? s) => throw null!; public void M3([MaybeNull] out string s) => throw null!; public bool M4([MaybeNullWhen(false)] out string s) => throw null!; public void M5(ref string s) => throw null!; public void M6([MaybeNull] ref string s) => throw null!; static void M() { var c = new C(); _ = new D1(c.M1); _ = new D1(c.M2); // 1 _ = new D1(c.M3); // 2 _ = new D2(c.M4); // 3 _ = new D3(c.M5); _ = new D3(c.M6); // 4 } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (22,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'void C.M2(out string? s)' doesn't match the target delegate 'D1' (possibly because of nullability attributes). // _ = new D1(c.M2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M2").WithArguments("s", "void C.M2(out string? s)", "D1").WithLocation(22, 20), // (23,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'void C.M3(out string s)' doesn't match the target delegate 'D1' (possibly because of nullability attributes). // _ = new D1(c.M3); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M3").WithArguments("s", "void C.M3(out string s)", "D1").WithLocation(23, 20), // (24,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'bool C.M4(out string s)' doesn't match the target delegate 'D2' (possibly because of nullability attributes). // _ = new D2(c.M4); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M4").WithArguments("s", "bool C.M4(out string s)", "D2").WithLocation(24, 20), // (26,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'void C.M6(ref string s)' doesn't match the target delegate 'D3' (possibly because of nullability attributes). // _ = new D3(c.M6); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M6").WithArguments("s", "void C.M6(ref string s)", "D3").WithLocation(26, 20) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44129")] public void DelegateCreation_FromMethodGroup_NullabilityAttributes_03() { var source = @" using System.Diagnostics.CodeAnalysis; delegate void D1([AllowNull] string s); [return: NotNull] delegate string? D2(); class C { public void M1(string s) => throw null!; public void M2(string? s) => throw null!; public string M3() => throw null!; public string? M4() => throw null!; static void M() { var c = new C(); _ = new D1(c.M1); // 1 _ = new D1(c.M2); _ = new D2(c.M3); _ = new D2(c.M4); // 2 } } "; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (17,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'void C.M1(string s)' doesn't match the target delegate 'D1' (possibly because of nullability attributes). // _ = new D1(c.M1); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M1").WithArguments("s", "void C.M1(string s)", "D1").WithLocation(17, 20), // (20,20): warning CS8621: Nullability of reference types in return type of 'string? C.M4()' doesn't match the target delegate 'D2' (possibly because of nullability attributes). // _ = new D2(c.M4); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "c.M4").WithArguments("string? C.M4()", "D2").WithLocation(20, 20) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44129")] public void DelegateCreation_FromMethodGroup_NullabilityAttributes_04() { var source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [return: MaybeNull] public string M1() => null; public string M2() => """"; public void M3([DisallowNull] object? s2) { } public void M4(object? s2) { } } static class Program { [return: MaybeNull] static string M5(this C c) => null; static string M6(this C c) => """"; static void M7(this C c, [DisallowNull] object? s2) { } static void M8(this C c, object? s2) { } static void M() { var c = new C(); _ = new Func<object>(c.M1); // 1 _ = new Func<object?>(c.M1); _ = new Func<object>(c.M2); _ = new Func<object?>(c.M2); _ = new Action<string>(c.M3); _ = new Action<string?>(c.M3); // 2 _ = new Action<string>(c.M4); _ = new Action<string?>(c.M4); _ = new Func<object>(c.M5); // 3 _ = new Func<object?>(c.M5); _ = new Func<object>(c.M6); _ = new Func<object?>(c.M6); _ = new Action<string>(c.M7); _ = new Action<string?>(c.M7); // 4 _ = new Action<string>(c.M8); _ = new Action<string?>(c.M8); } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (27,30): warning CS8621: Nullability of reference types in return type of 'string C.M1()' doesn't match the target delegate 'Func<object>' (possibly because of nullability attributes). // _ = new Func<object>(c.M1); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "c.M1").WithArguments("string C.M1()", "System.Func<object>").WithLocation(27, 30), // (33,33): warning CS8622: Nullability of reference types in type of parameter 's2' of 'void C.M3(object? s2)' doesn't match the target delegate 'Action<string?>' (possibly because of nullability attributes). // _ = new Action<string?>(c.M3); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M3").WithArguments("s2", "void C.M3(object? s2)", "System.Action<string?>").WithLocation(33, 33), // (37,30): warning CS8621: Nullability of reference types in return type of 'string Program.M5(C c)' doesn't match the target delegate 'Func<object>' (possibly because of nullability attributes). // _ = new Func<object>(c.M5); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "c.M5").WithArguments("string Program.M5(C c)", "System.Func<object>").WithLocation(37, 30), // (43,33): warning CS8622: Nullability of reference types in type of parameter 's2' of 'void Program.M7(C c, object? s2)' doesn't match the target delegate 'Action<string?>' (possibly because of nullability attributes). // _ = new Action<string?>(c.M7); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M7").WithArguments("s2", "void Program.M7(C c, object? s2)", "System.Action<string?>").WithLocation(43, 33) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44129")] public void DelegateCreation_FromExtensionMethodGroup_BadParameterCount() { var source = @" using System; using System.Diagnostics.CodeAnalysis; class C { } static class Program { static void M3(this C c, [DisallowNull] string? s2) { } static void M() { var c = new C(); _ = new Action<string?, string>(c.M3); // 1 _ = new Action(c.M3); // 2 } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,13): error CS0123: No overload for 'M3' matches delegate 'Action<string?, string>' // _ = new Action<string?, string>(c.M3); // 1 Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Action<string?, string>(c.M3)").WithArguments("M3", "System.Action<string?, string>").WithLocation(15, 13), // (16,13): error CS0123: No overload for 'M3' matches delegate 'Action' // _ = new Action(c.M3); // 2 Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Action(c.M3)").WithArguments("M3", "System.Action").WithLocation(16, 13) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44129")] public void DelegateCreation_FromMethodGroup_MaybeNullReturn() { var source = @" using System; using System.Diagnostics.CodeAnalysis; public static class D { [return: MaybeNull] public static string FirstOrDefault(this string[] e) => e.Length > 0 ? e[0] : null; public static void Main() { var e = new string[0]; Func<string> f = e.FirstOrDefault; // 1 f().ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,26): warning CS8621: Nullability of reference types in return type of 'string D.FirstOrDefault(string[] e)' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes). // Func<string> f = e.FirstOrDefault; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "e.FirstOrDefault").WithArguments("string D.FirstOrDefault(string[] e)", "System.Func<string>").WithLocation(13, 26) ); } [Fact] [WorkItem(46977, "https://github.com/dotnet/roslyn/issues/46977")] public void DelegateCreation_FromMethodGroup_ReadonlyRefCovariance_01() { var source = @" delegate ref readonly T D<T>(); class C { void M() { D<string> d1 = M1; D<string?> d2 = M1; D<string> d3 = M2; // 1 D<string?> d4 = M2; _ = new D<string>(d1); _ = new D<string?>(d1); _ = new D<string>(d2); // 2 _ = new D<string?>(d2); D<string> d5 = d1; D<string?> d6 = d1; // 3 D<string> d7 = d2; // 4 D<string?> d8 = d2; } ref readonly string M1() => throw null!; ref readonly string? M2() => throw null!; }"; // Note: strictly speaking we don't need to warn on 3, but it would require a // change to nullable reference conversion analysis which special cases delegates. var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (10,24): warning CS8621: Nullability of reference types in return type of 'ref readonly string? C.M2()' doesn't match the target delegate 'D<string>' (possibly because of nullability attributes). // D<string> d3 = M2; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M2").WithArguments("ref readonly string? C.M2()", "D<string>").WithLocation(10, 24), // (15,27): warning CS8621: Nullability of reference types in return type of 'ref readonly string? D<string?>.Invoke()' doesn't match the target delegate 'D<string>' (possibly because of nullability attributes). // _ = new D<string>(d2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "d2").WithArguments("ref readonly string? D<string?>.Invoke()", "D<string>").WithLocation(15, 27), // (19,25): warning CS8619: Nullability of reference types in value of type 'D<string>' doesn't match target type 'D<string?>'. // D<string?> d6 = d1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "d1").WithArguments("D<string>", "D<string?>").WithLocation(19, 25), // (20,24): warning CS8619: Nullability of reference types in value of type 'D<string?>' doesn't match target type 'D<string>'. // D<string> d7 = d2; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "d2").WithArguments("D<string?>", "D<string>").WithLocation(20, 24) ); } [Fact] [WorkItem(46977, "https://github.com/dotnet/roslyn/issues/46977")] public void DelegateCreation_FromMethodGroup_ReadonlyRefCovariance_02() { var source = @" delegate ref readonly string D1(); delegate ref readonly string? D2(); class C { void M() { D1 d1 = M1; D2 d2 = M1; D1 d3 = M2; // 1 D2 d4 = M2; _ = new D1(d1); _ = new D2(d1); _ = new D1(d2); // 2 _ = new D2(d2); } ref readonly string M1() => throw null!; ref readonly string? M2() => throw null!; }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8621: Nullability of reference types in return type of 'ref readonly string? C.M2()' doesn't match the target delegate 'D1' (possibly because of nullability attributes). // D1 d3 = M2; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M2").WithArguments("ref readonly string? C.M2()", "D1").WithLocation(11, 17), // (16,20): warning CS8621: Nullability of reference types in return type of 'ref readonly string? D2.Invoke()' doesn't match the target delegate 'D1' (possibly because of nullability attributes). // _ = new D1(d2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "d2").WithArguments("ref readonly string? D2.Invoke()", "D1").WithLocation(16, 20) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44174")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_01() { var source = @" using System; using System.Diagnostics.CodeAnalysis; public class C { public Func<string?, string?> M1() { return Helper.Method; } public Func<string, string> M2() { return Helper.Method; } public Func<string, string?> M3() { return Helper.Method; } public Func<string?, string> M4() { return Helper.Method; // 1 } public Func< #nullable disable string, #nullable enable string> M5() { return Helper.Method; } } static class Helper { [return: NotNullIfNotNull(""arg"")] public static string? Method(string? arg) => arg; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (24,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method(string? arg)' doesn't match the target delegate 'Func<string?, string>' (possibly because of nullability attributes). // return Helper.Method; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method").WithArguments("string? Helper.Method(string? arg)", "System.Func<string?, string>").WithLocation(24, 16) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44174")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_02() { var source = @" using System.Diagnostics.CodeAnalysis; public delegate void D1(string? x, out string? y); public delegate void D2(string x, out string y); public delegate void D3(string x, out string? y); public delegate void D4(string? x, out string y); public delegate void D5( #nullable disable string x, #nullable enable out string y); public delegate void D6(string? x, out string? y, out string? z); public delegate void D7(string x, out string? y, out string z); public delegate void D8(string x, out string y, out string z); public delegate void D9(string? x, out string y, out string z); public class C { public D1 M1() { return Helper.Method1; } public D2 M2() { return Helper.Method1; } public D3 M3() { return Helper.Method1; } public D4 M4() { return Helper.Method1; // 1 } public D5 M5() { return Helper.Method1; } public D6 M6() { return Helper.Method2; } public D7 M7() { return Helper.Method2; // 2 } public D8 M8() { return Helper.Method3; } public D9 M9() { return Helper.Method3; // 3, 4 } } static class Helper { public static void Method1(string? x, [NotNullIfNotNull(""x"")] out string? y) { y = x; } public static void Method2(string? x, [NotNullIfNotNull(""x"")] out string? y, [NotNullIfNotNull(""y"")] out string? z) { z = y = x; } public static void Method3(string? x, [NotNullIfNotNull(""x"")] out string? y, [NotNullIfNotNull(""x"")] out string? z) { z = y = x; } } "; // Diagnostic 2 is verifying something a bit esoteric: non-nullability of 'x' does not propagate to 'z'. var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (34,16): warning CS8622: Nullability of reference types in type of parameter 'y' of 'void Helper.Method1(string? x, out string? y)' doesn't match the target delegate 'D4' (possibly because of nullability attributes). // return Helper.Method1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Helper.Method1").WithArguments("y", "void Helper.Method1(string? x, out string? y)", "D4").WithLocation(34, 16), // (46,16): warning CS8622: Nullability of reference types in type of parameter 'z' of 'void Helper.Method2(string? x, out string? y, out string? z)' doesn't match the target delegate 'D7' (possibly because of nullability attributes). // return Helper.Method2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Helper.Method2").WithArguments("z", "void Helper.Method2(string? x, out string? y, out string? z)", "D7").WithLocation(46, 16), // (54,16): warning CS8622: Nullability of reference types in type of parameter 'y' of 'void Helper.Method3(string? x, out string? y, out string? z)' doesn't match the target delegate 'D9' (possibly because of nullability attributes). // return Helper.Method3; // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Helper.Method3").WithArguments("y", "void Helper.Method3(string? x, out string? y, out string? z)", "D9").WithLocation(54, 16), // (54,16): warning CS8622: Nullability of reference types in type of parameter 'z' of 'void Helper.Method3(string? x, out string? y, out string? z)' doesn't match the target delegate 'D9' (possibly because of nullability attributes). // return Helper.Method3; // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Helper.Method3").WithArguments("z", "void Helper.Method3(string? x, out string? y, out string? z)", "D9").WithLocation(54, 16) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44174")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_03() { var source = @" using System; using System.Diagnostics.CodeAnalysis; public class C { public Func<string, string> M1() { return Helper.Method1<string?>; } public Func<string, string?> M2() { return Helper.Method1<string?>; } public Func<string?, string> M3() { return Helper.Method1<string?>; // 1 } public Func<string?, string?> M4() { return Helper.Method1<string?>; } public Func<T, T> M5<T>() { return Helper.Method1<T?>; // 2 } public Func<T, T?> M6<T>() { return Helper.Method1<T?>; } public Func<T?, T> M7<T>() { return Helper.Method1<T?>; // 3 } public Func<T?, T?> M8<T>() { return Helper.Method1<T?>; } } static class Helper { [return: NotNullIfNotNull(""t"")] public static T Method1<T>(T t) => t; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1<string?>(string? t)' doesn't match the target delegate 'Func<string?, string>' (possibly because of nullability attributes). // return Helper.Method1<string?>; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1<string?>").WithArguments("string? Helper.Method1<string?>(string? t)", "System.Func<string?, string>").WithLocation(15, 16), // (23,16): warning CS8621: Nullability of reference types in return type of 'T? Helper.Method1<T?>(T? t)' doesn't match the target delegate 'Func<T, T>' (possibly because of nullability attributes). // return Helper.Method1<T?>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1<T?>").WithArguments("T? Helper.Method1<T?>(T? t)", "System.Func<T, T>").WithLocation(23, 16), // (31,16): warning CS8621: Nullability of reference types in return type of 'T? Helper.Method1<T?>(T? t)' doesn't match the target delegate 'Func<T?, T>' (possibly because of nullability attributes). // return Helper.Method1<T?>; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1<T?>").WithArguments("T? Helper.Method1<T?>(T? t)", "System.Func<T?, T>").WithLocation(31, 16) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44174")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_04() { var source = @" using System.Diagnostics.CodeAnalysis; public delegate void Del<T1, T2, T3>(T1 x, T2 y, out T3 z); public class C { public Del<string, string, string> M1() { return Helper.Method1; } public Del<string, string, string?> M2() { return Helper.Method1; } public Del<string, string?, string> M3() { return Helper.Method1; } public Del<string?, string, string> M4() { return Helper.Method1; } public Del<string?, string?, string> M5() { return Helper.Method1; // 1 } public Del<string?, string?, string?> M6() { return Helper.Method1; } } static class Helper { public static void Method1(string? x, string? y, [NotNullIfNotNull(""x""), NotNullIfNotNull(""y"")] out string? z) { z = x ?? y; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (24,16): warning CS8622: Nullability of reference types in type of parameter 'z' of 'void Helper.Method1(string? x, string? y, out string? z)' doesn't match the target delegate 'Del<string?, string?, string>' (possibly because of nullability attributes). // return Helper.Method1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Helper.Method1").WithArguments("z", "void Helper.Method1(string? x, string? y, out string? z)", "Del<string?, string?, string>").WithLocation(24, 16) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44174")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_05() { var source = @" using System; using System.Diagnostics.CodeAnalysis; public class C { public Func<string, string, string> M1() { return Helper.Method1; } public Func<string, string, string?> M2() { return Helper.Method1; } public Func<string, string?, string> M3() { return Helper.Method1; } public Func<string?, string, string> M4() { return Helper.Method1; } public Func<string?, string?, string> M5() { return Helper.Method1; // 1 } public Func<string?, string?, string?> M6() { return Helper.Method1; } } static class Helper { [return: NotNullIfNotNull(""x""), NotNullIfNotNull(""y"")] public static string? Method1(string? x, string? y) { return x ?? y; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (23,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1(string? x, string? y)' doesn't match the target delegate 'Func<string?, string?, string>' (possibly because of nullability attributes). // return Helper.Method1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1").WithArguments("string? Helper.Method1(string? x, string? y)", "System.Func<string?, string?, string>").WithLocation(23, 16) ); } [Fact] [WorkItem(49865, "https://github.com/dotnet/roslyn/issues/49865")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_06() { var source = @" using System; using System.Diagnostics.CodeAnalysis; public class C { public Func<T, string> M1<T>() { return Helper.Method1; // 1 } public Func<T, string> M2<T>() where T : notnull { return Helper.Method1; } public Func<T, string> M3<T>() where T : class { return Helper.Method1; } public Func<T, string> M4<T>() where T : class? { return Helper.Method1; // 2 } public Func<T, string> M5<T>() where T : struct { return Helper.Method1; } public Func<T?, string> M6<T>() { return Helper.Method1; // 3 } } static class Helper { [return: NotNullIfNotNull(""t"")] public static string? Method1<T>(T t) { return t?.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (7,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1<T>(T t)' doesn't match the target delegate 'Func<T, string>' (possibly because of nullability attributes). // return Helper.Method1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1").WithArguments("string? Helper.Method1<T>(T t)", "System.Func<T, string>").WithLocation(7, 16), // (19,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1<T>(T t)' doesn't match the target delegate 'Func<T, string>' (possibly because of nullability attributes). // return Helper.Method1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1").WithArguments("string? Helper.Method1<T>(T t)", "System.Func<T, string>").WithLocation(19, 16), // (28,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1<T?>(T? t)' doesn't match the target delegate 'Func<T?, string>' (possibly because of nullability attributes). // return Helper.Method1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1").WithArguments("string? Helper.Method1<T?>(T? t)", "System.Func<T?, string>").WithLocation(28, 16)); } [Fact] [WorkItem(49865, "https://github.com/dotnet/roslyn/issues/49865")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_07() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public D1<T> M1<T>() { return Helper.Method1; // 1 } public D2<T> M2<T>() { return Helper.Method1; // 2 } public D3<T> M3<T>() { return Helper.Method1; } } public delegate string D1<T>(T t); public delegate string D2<T>(T? t); public delegate string D3<T>([DisallowNull] T t); static class Helper { [return: NotNullIfNotNull(""t"")] public static string? Method1<T>(T t) { return t?.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (6,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1<T>(T t)' doesn't match the target delegate 'D1<T>' (possibly because of nullability attributes). // return Helper.Method1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1").WithArguments("string? Helper.Method1<T>(T t)", "D1<T>").WithLocation(6, 16), // (10,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1<T?>(T? t)' doesn't match the target delegate 'D2<T>' (possibly because of nullability attributes). // return Helper.Method1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1").WithArguments("string? Helper.Method1<T?>(T? t)", "D2<T>").WithLocation(10, 16)); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44174")] public void NotNullIfNotNull_Override() { var source = @" using System.Diagnostics.CodeAnalysis; abstract class Base1 { public abstract string? Method(string? arg); } class Derived1 : Base1 { [return: NotNullIfNotNull(""arg"")] public override string? Method(string? arg) => arg; } abstract class Base2 { public abstract string Method(string arg); } class Derived2 : Base2 { [return: NotNullIfNotNull(""arg"")] public override string? Method(string? arg) => arg; } abstract class Base3 { public abstract string? Method(string arg); } class Derived3 : Base3 { [return: NotNullIfNotNull(""arg"")] public override string? Method(string? arg) => arg; } abstract class Base4 { public abstract string Method(string? arg); } class Derived4 : Base4 { [return: NotNullIfNotNull(""arg"")] public override string? Method(string? arg) => arg; // 1 } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (37,29): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override string? Method(string? arg) => arg; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "Method").WithLocation(37, 29) ); } [Fact] public void IdentityConversion_DelegateReturnType() { var source = @"delegate T D<T>(); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>() => throw new System.Exception(); static void G() { D<object> a = F<object?>; D<object?> b = F<object>; D<I<object>> c = F<I<object?>>; D<I<object?>> d = F<I<object>>; D<IIn<object>> e = F<IIn<object?>>; D<IIn<object?>> f = F<IIn<object>>; D<IOut<object>> g = F<IOut<object?>>; D<IOut<object?>> h = F<IOut<object>>; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,23): warning CS8621: Nullability of reference types in return type of 'object? C.F<object?>()' doesn't match the target delegate 'D<object>'. // D<object> a = F<object?>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<object?>").WithArguments("object? C.F<object?>()", "D<object>").WithLocation(10, 23), // (12,26): warning CS8621: Nullability of reference types in return type of 'I<object?> C.F<I<object?>>()' doesn't match the target delegate 'D<I<object>>'. // D<I<object>> c = F<I<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<I<object?>>").WithArguments("I<object?> C.F<I<object?>>()", "D<I<object>>").WithLocation(12, 26), // (13,27): warning CS8621: Nullability of reference types in return type of 'I<object> C.F<I<object>>()' doesn't match the target delegate 'D<I<object?>>'. // D<I<object?>> d = F<I<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<I<object>>").WithArguments("I<object> C.F<I<object>>()", "D<I<object?>>").WithLocation(13, 27), // (15,29): warning CS8621: Nullability of reference types in return type of 'IIn<object> C.F<IIn<object>>()' doesn't match the target delegate 'D<IIn<object?>>'. // D<IIn<object?>> f = F<IIn<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<IIn<object>>").WithArguments("IIn<object> C.F<IIn<object>>()", "D<IIn<object?>>").WithLocation(15, 29), // (16,29): warning CS8621: Nullability of reference types in return type of 'IOut<object?> C.F<IOut<object?>>()' doesn't match the target delegate 'D<IOut<object>>'. // D<IOut<object>> g = F<IOut<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<IOut<object?>>").WithArguments("IOut<object?> C.F<IOut<object?>>()", "D<IOut<object>>").WithLocation(16, 29)); } [Fact] public void IdentityConversion_DelegateParameter_01() { var source = @"delegate void D<T>(T t); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F<T>(T t) { } static void G() { D<object> a = F<object?>; D<object?> b = F<object>; D<I<object>> c = F<I<object?>>; D<I<object?>> d = F<I<object>>; D<IIn<object>> e = F<IIn<object?>>; D<IIn<object?>> f = F<IIn<object>>; D<IOut<object>> g = F<IOut<object?>>; D<IOut<object?>> h = F<IOut<object>>; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,24): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object>(object t)' doesn't match the target delegate 'D<object?>'. // D<object?> b = F<object>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object>").WithArguments("t", "void C.F<object>(object t)", "D<object?>").WithLocation(11, 24), // (12,26): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object?>>(I<object?> t)' doesn't match the target delegate 'D<I<object>>'. // D<I<object>> c = F<I<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t", "void C.F<I<object?>>(I<object?> t)", "D<I<object>>").WithLocation(12, 26), // (13,27): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object>>(I<object> t)' doesn't match the target delegate 'D<I<object?>>'. // D<I<object?>> d = F<I<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t", "void C.F<I<object>>(I<object> t)", "D<I<object?>>").WithLocation(13, 27), // (14,28): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object?>>(IIn<object?> t)' doesn't match the target delegate 'D<IIn<object>>'. // D<IIn<object>> e = F<IIn<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object?>>").WithArguments("t", "void C.F<IIn<object?>>(IIn<object?> t)", "D<IIn<object>>").WithLocation(14, 28), // (17,30): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object>>(IOut<object> t)' doesn't match the target delegate 'D<IOut<object?>>'. // D<IOut<object?>> h = F<IOut<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object>>").WithArguments("t", "void C.F<IOut<object>>(IOut<object> t)", "D<IOut<object?>>").WithLocation(17, 30)); } [Fact] [WorkItem(29844, "https://github.com/dotnet/roslyn/issues/29844")] public void IdentityConversion_DelegateParameter_02() { var source = @"delegate T D<T>(); class A<T> { internal T M() => throw new System.NotImplementedException(); } class B { static A<T> F<T>(T t) => throw null!; static void G(object? o) { var x = F(o); D<object?> d = x.M; D<object> e = x.M; // 1 if (o == null) return; var y = F(o); d = y.M; e = y.M; d = (D<object?>)y.M; e = (D<object>)y.M; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,23): warning CS8621: Nullability of reference types in return type of 'object? A<object?>.M()' doesn't match the target delegate 'D<object>'. // D<object> e = x.M; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.M").WithArguments("object? A<object?>.M()", "D<object>").WithLocation(13, 23)); } [Fact] [WorkItem(29844, "https://github.com/dotnet/roslyn/issues/29844")] public void IdentityConversion_DelegateOutParameter() { var source = @"delegate void D<T>(out T t); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F<T>(out T t) { t = default!; } static void G() { D<object> a = F<object?>; D<object?> b = F<object>; D<I<object>> c = F<I<object?>>; D<I<object?>> d = F<I<object>>; D<IIn<object>> e = F<IIn<object?>>; D<IIn<object?>> f = F<IIn<object>>; D<IOut<object>> g = F<IOut<object?>>; D<IOut<object?>> h = F<IOut<object>>; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,23): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object?>(out object? t)' doesn't match the target delegate 'D<object>'. // D<object> a = F<object?>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object?>").WithArguments("t", "void C.F<object?>(out object? t)", "D<object>").WithLocation(10, 23), // (12,26): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object?>>(out I<object?> t)' doesn't match the target delegate 'D<I<object>>'. // D<I<object>> c = F<I<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t", "void C.F<I<object?>>(out I<object?> t)", "D<I<object>>").WithLocation(12, 26), // (13,27): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object>>(out I<object> t)' doesn't match the target delegate 'D<I<object?>>'. // D<I<object?>> d = F<I<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t", "void C.F<I<object>>(out I<object> t)", "D<I<object?>>").WithLocation(13, 27), // (15,29): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object>>(out IIn<object> t)' doesn't match the target delegate 'D<IIn<object?>>'. // D<IIn<object?>> f = F<IIn<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object>>").WithArguments("t", "void C.F<IIn<object>>(out IIn<object> t)", "D<IIn<object?>>").WithLocation(15, 29), // (16,29): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object?>>(out IOut<object?> t)' doesn't match the target delegate 'D<IOut<object>>'. // D<IOut<object>> g = F<IOut<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object?>>").WithArguments("t", "void C.F<IOut<object?>>(out IOut<object?> t)", "D<IOut<object>>").WithLocation(16, 29) ); } [Fact] [WorkItem(32563, "https://github.com/dotnet/roslyn/issues/32563")] public void IdentityConversion_DelegateInParameter() { var source = @"delegate void D<T>(in T t); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F<T>(in T t) { } static void G() { D<object> a = F<object?>; D<object?> b = F<object>; D<I<object>> c = F<I<object?>>; D<I<object?>> d = F<I<object>>; D<IIn<object>> e = F<IIn<object?>>; D<IIn<object?>> f = F<IIn<object>>; D<IOut<object>> g = F<IOut<object?>>; D<IOut<object?>> h = F<IOut<object>>; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,24): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object>(in object t)' doesn't match the target delegate 'D<object?>'. // D<object?> b = F<object>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object>").WithArguments("t", "void C.F<object>(in object t)", "D<object?>").WithLocation(11, 24), // (12,26): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object?>>(in I<object?> t)' doesn't match the target delegate 'D<I<object>>'. // D<I<object>> c = F<I<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t", "void C.F<I<object?>>(in I<object?> t)", "D<I<object>>").WithLocation(12, 26), // (13,27): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object>>(in I<object> t)' doesn't match the target delegate 'D<I<object?>>'. // D<I<object?>> d = F<I<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t", "void C.F<I<object>>(in I<object> t)", "D<I<object?>>").WithLocation(13, 27), // (14,28): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object?>>(in IIn<object?> t)' doesn't match the target delegate 'D<IIn<object>>'. // D<IIn<object>> e = F<IIn<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object?>>").WithArguments("t", "void C.F<IIn<object?>>(in IIn<object?> t)", "D<IIn<object>>").WithLocation(14, 28), // (17,30): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object>>(in IOut<object> t)' doesn't match the target delegate 'D<IOut<object?>>'. // D<IOut<object?>> h = F<IOut<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object>>").WithArguments("t", "void C.F<IOut<object>>(in IOut<object> t)", "D<IOut<object?>>").WithLocation(17, 30) ); } [Fact] public void IdentityConversion_DelegateRefParameter() { var source = @"delegate void D<T>(ref T t); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F<T>(ref T t) { } static void G() { D<object> a = F<object?>; D<object?> b = F<object>; D<I<object>> c = F<I<object?>>; D<I<object?>> d = F<I<object>>; D<IIn<object>> e = F<IIn<object?>>; D<IIn<object?>> f = F<IIn<object>>; D<IOut<object>> g = F<IOut<object?>>; D<IOut<object?>> h = F<IOut<object>>; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,23): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object?>(ref object? t)' doesn't match the target delegate 'D<object>'. // D<object> a = F<object?>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object?>").WithArguments("t", "void C.F<object?>(ref object? t)", "D<object>").WithLocation(10, 23), // (11,24): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object>(ref object t)' doesn't match the target delegate 'D<object?>'. // D<object?> b = F<object>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object>").WithArguments("t", "void C.F<object>(ref object t)", "D<object?>").WithLocation(11, 24), // (12,26): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object?>>(ref I<object?> t)' doesn't match the target delegate 'D<I<object>>'. // D<I<object>> c = F<I<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t", "void C.F<I<object?>>(ref I<object?> t)", "D<I<object>>").WithLocation(12, 26), // (13,27): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object>>(ref I<object> t)' doesn't match the target delegate 'D<I<object?>>'. // D<I<object?>> d = F<I<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t", "void C.F<I<object>>(ref I<object> t)", "D<I<object?>>").WithLocation(13, 27), // (14,28): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object?>>(ref IIn<object?> t)' doesn't match the target delegate 'D<IIn<object>>'. // D<IIn<object>> e = F<IIn<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object?>>").WithArguments("t", "void C.F<IIn<object?>>(ref IIn<object?> t)", "D<IIn<object>>").WithLocation(14, 28), // (15,29): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object>>(ref IIn<object> t)' doesn't match the target delegate 'D<IIn<object?>>'. // D<IIn<object?>> f = F<IIn<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object>>").WithArguments("t", "void C.F<IIn<object>>(ref IIn<object> t)", "D<IIn<object?>>").WithLocation(15, 29), // (16,29): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object?>>(ref IOut<object?> t)' doesn't match the target delegate 'D<IOut<object>>'. // D<IOut<object>> g = F<IOut<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object?>>").WithArguments("t", "void C.F<IOut<object?>>(ref IOut<object?> t)", "D<IOut<object>>").WithLocation(16, 29), // (17,30): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object>>(ref IOut<object> t)' doesn't match the target delegate 'D<IOut<object?>>'. // D<IOut<object?>> h = F<IOut<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object>>").WithArguments("t", "void C.F<IOut<object>>(ref IOut<object> t)", "D<IOut<object?>>").WithLocation(17, 30)); } [Fact] public void Base_01() { CSharpCompilation c = CreateCompilation(new[] { @" class Base { public virtual void Test() {} } class C : Base { static void Main() { } public override void Test() { base.Test(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Base_02() { var source0 = @"public abstract class A<T> { } public class B<T> : A<T?> where T : B<T> { }"; var comp0 = CreateCompilation(source0, options: WithNullableEnable()); comp0.VerifyDiagnostics(); CompileAndVerify(comp0, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var b = m.GlobalNamespace.GetTypeMember("B"); Assert.Equal("A<T?>", b.BaseTypeNoUseSiteDiagnostics.ToTestDisplayString(true)); } } [Fact] public void Base_03() { var source0 = @"public abstract class A<T> { } public class B<T> : A<T> where T : B<T> { }"; var comp0 = CreateCompilation(source0, options: WithNullableEnable()); comp0.VerifyDiagnostics(); CompileAndVerify(comp0, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var b = m.GlobalNamespace.GetTypeMember("B"); Assert.Equal("A<T!>", b.BaseTypeNoUseSiteDiagnostics.ToTestDisplayString(true)); } } [Fact] public void TypeOf_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(System.Type x1) { x1 = typeof(C); } void Test2(System.Type x2) { x2 = typeof(C) ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] [WorkItem(29894, "https://github.com/dotnet/roslyn/issues/29894")] public void TypeOf_02() { CSharpCompilation c = CreateCompilation(new[] { @" class List<T> { } class C<T, TClass, TStruct> where TClass : class where TStruct : struct { void M() { _ = typeof(C<int, object, int>?); _ = typeof(T?); _ = typeof(TClass?); _ = typeof(TStruct?); _ = typeof(List<T?>); _ = typeof(List<TClass?>); _ = typeof(List<TStruct?>); } } " }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (9,13): error CS8639: The typeof operator cannot be used on a nullable reference type // _ = typeof(C<int, object, int>?); Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(C<int, object, int>?)").WithLocation(9, 13), // (10,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // _ = typeof(T?); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(10, 20), // (11,13): error CS8639: The typeof operator cannot be used on a nullable reference type // _ = typeof(TClass?); Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(TClass?)").WithLocation(11, 13), // (13,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // _ = typeof(List<T?>); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(13, 25)); } [Fact] public void Default_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(C x1) { x1 = default(C); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = default(C); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(C)").WithLocation(10, 14) ); } [Fact] public void Default_NonNullable() { var source = @"class C { static void Main() { var s = default(string); s.ToString(); var i = default(int); i.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("System.Int32", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.NotAnnotated, symbol.TypeWithAnnotations.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, symbol.GetPublicSymbol().NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, symbol.GetPublicSymbol().Type.NullableAnnotation); } [Fact] public void Default_Nullable() { var source = @"class C { static void Main() { var s = default(string?); s.ToString(); var i = default(int?); i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("System.Int32?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Default_TUnconstrained() { var source = @"class C { static void F<T>() { var s = default(T); s.ToString(); var t = default(T?); t.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9), // (7,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // var t = default(T?); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 25), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(8, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("T?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("T?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Default_TClass() { var source = @"class C { static void F<T>() where T : class { var s = default(T); s.ToString(); var t = default(T?); t.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(8, 9)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("T?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("T?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void DefaultInferred_NonNullable() { var source = @"class C { static void Main() { string s = default; s.ToString(); int i = default; i.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // string s = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(5, 20), // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String!", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.NotAnnotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("System.Int32", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.NotAnnotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void DefaultInferred_Nullable() { var source = @"class C { static void Main() { string? s = default; s.ToString(); int? i = default; i.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("System.Int32?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void DefaultInferred_TUnconstrained() { var source = @"class C { static void F<T>() { T s = default; s.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("T", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.NotAnnotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void DefaultInferred_TClass() { var source = @"class C { static void F<T>() where T : class { T s = default; s.ToString(); T? t = default; t.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T s = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(5, 15), // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(8, 9)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("T!", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.NotAnnotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("T?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] [WorkItem(29896, "https://github.com/dotnet/roslyn/issues/29618")] public void DeconstructionTypeInference() { var source = @"class C { static void F((object? a, object? b) t) { if (t.b == null) return; object? x; object? y; (x, y) = t; x.ToString(); y.ToString(); } static void F(object? a, object? b) { if (b == null) return; object? x; object? y; (x, y) = (a, b); x.ToString(); y.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(18, 9)); } [Fact] public void IdentityConversion_DeconstructionAssignment() { var source = @"interface IIn<in T> { } interface IOut<out T> { } class C<T> { void Deconstruct(out IIn<T> x, out IOut<T> y) { throw new System.NotImplementedException(); } static void F(C<object> c) { IIn<object?> x; IOut<object?> y; (x, y) = c; } static void G(C<object?> c) { IIn<object> x; IOut<object> y; (x, y) = c; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,10): warning CS8624: Argument of type 'IIn<object?>' cannot be used as an output of type 'IIn<object>' for parameter 'x' in 'void C<object>.Deconstruct(out IIn<object> x, out IOut<object> y)' due to differences in the nullability of reference types. // (x, y) = c; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "x").WithArguments("IIn<object?>", "IIn<object>", "x", "void C<object>.Deconstruct(out IIn<object> x, out IOut<object> y)").WithLocation(13, 10), // (19,13): warning CS8624: Argument of type 'IOut<object>' cannot be used as an output of type 'IOut<object?>' for parameter 'y' in 'void C<object?>.Deconstruct(out IIn<object?> x, out IOut<object?> y)' due to differences in the nullability of reference types. // (x, y) = c; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "y").WithArguments("IOut<object>", "IOut<object?>", "y", "void C<object?>.Deconstruct(out IIn<object?> x, out IOut<object?> y)").WithLocation(19, 13) ); } [Fact] [WorkItem(29618, "https://github.com/dotnet/roslyn/issues/29618")] public void DeconstructionTypeInference_01() { var source = @"class C { static void M() { (var x, var y) = ((string?)null, string.Empty); x.ToString(); // 1 y.ToString(); x = null; y = null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9) ); } [Fact] [WorkItem(29618, "https://github.com/dotnet/roslyn/issues/29618")] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void DeconstructionTypeInference_02() { var source = @"class C { static (string?, string) F() => (string.Empty, string.Empty); static void G() { (var x, var y) = F(); x.ToString(); // 1 y.ToString(); x = null; y = null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] [WorkItem(29618, "https://github.com/dotnet/roslyn/issues/29618")] public void DeconstructionTypeInference_03() { var source = @"class C { void Deconstruct(out string? x, out string y) { x = string.Empty; y = string.Empty; } static void M() { (var x, var y) = new C(); x.ToString(); y.ToString(); x = null; y = null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 9)); } [Fact] public void DeconstructionTypeInference_04() { var source = @"class C { static (string?, string) F() => (null, string.Empty); static void G() { string x; string? y; var t = ((x, y) = F()); _ = t/*T:(string x, string y)*/; t.x.ToString(); // 1 t.y.ToString(); t.x = null; t.y = null; // 2 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/33011: Deconstruction should infer string? for x, // string! for y, and (string?, string!) for t. comp.VerifyDiagnostics( // (8,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // var t = ((x, y) = F()); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F()").WithLocation(8, 27) ); comp.VerifyTypes(); } [Fact] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void DeconstructionTypeInference_05() { var source = @"using System; using System.Collections.Generic; class C { static IEnumerable<(string, string?)> F() => throw new Exception(); static void G() { foreach ((var x, var y) in F()) { x.ToString(); y.ToString(); // 1 x = null; // 2 y = null; // 3 } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 13), // (12,13): error CS1656: Cannot assign to 'x' because it is a 'foreach iteration variable' // x = null; // 2 Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x").WithArguments("x", "foreach iteration variable").WithLocation(12, 13), // (13,13): error CS1656: Cannot assign to 'y' because it is a 'foreach iteration variable' // y = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "y").WithArguments("y", "foreach iteration variable").WithLocation(13, 13) ); } [Fact] public void Discard_01() { var source = @"class C { static void F((object, object?) t) { object? x; ((_, x) = t).Item1.ToString(); ((x, _) = t).Item2.ToString(); } }"; // https://github.com/dotnet/roslyn/issues/33011: Should report WRN_NullReferenceReceiver. var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); //// (7,9): warning CS8602: Dereference of a possibly null reference. //// ((x, _) = t).Item2.ToString(); //Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((x, _) = t).Item2").WithLocation(7, 9)); } [Fact, WorkItem(29635, "https://github.com/dotnet/roslyn/issues/29635")] public void Discard_02() { var source = @"#nullable disable class C<T> { #nullable enable void F(object? o1, object? o2, C<object> o3, C<object?> o4) { if (o1 is null) throw null!; _ /*T:object!*/ = o1; _ /*T:object?*/ = o2; _ /*T:C<object!>!*/ = o3; _ /*T:C<object?>!*/ = o4; } #nullable disable void F(C<object> o) { _ /*T:C<object>!*/ = o; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); var tree = comp.SyntaxTrees.Single(); var discards = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Select(a => a.Left).ToArray(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var discard1 = model.GetSymbolInfo(discards[0]).Symbol; Assert.Equal(SymbolKind.Discard, discard1.Kind); Assert.Equal("object _", discard1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var discard2 = model.GetSymbolInfo(discards[1]).Symbol; Assert.Equal(SymbolKind.Discard, discard2.Kind); Assert.Equal("object? _", discard2.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var discard3 = model.GetSymbolInfo(discards[2]).Symbol; Assert.Equal(SymbolKind.Discard, discard3.Kind); Assert.Equal("C<object> _", discard3.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var discard4 = model.GetSymbolInfo(discards[3]).Symbol; Assert.Equal(SymbolKind.Discard, discard4.Kind); Assert.Equal("C<object?> _", discard4.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var discard5 = model.GetSymbolInfo(discards[4]).Symbol; Assert.Equal(SymbolKind.Discard, discard5.Kind); Assert.Equal("C<object> _", discard5.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); } [Fact, WorkItem(36503, "https://github.com/dotnet/roslyn/issues/36503")] public void Discard_Reinferred() { var source = @" #nullable enable interface I<in T> {} class C { void M(I<string?> i1, I<string> i2) { var x = i2 ?? i1; _ = x /*T:I<string!>!*/; _ /*T:I<string!>!*/ = i2 ?? i1; var y = (_ = i2 ?? i1); _ = y /*T:I<string!>!*/; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact, WorkItem(36503, "https://github.com/dotnet/roslyn/issues/36503")] public void Discard_Reinferred_Nested() { var source = @" #nullable enable interface I<in T> {} class C { void M(I<I<string?>> i1, I<I<string>?> i2) { var x = i2 ?? i1; _ = x /*T:I<I<string?>!>!*/; _ /*T:I<I<string?>!>!*/ = i2 ?? i1; var y = (_ = i2 ?? i1); _ = y /*T:I<I<string?>!>!*/; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact, WorkItem(36503, "https://github.com/dotnet/roslyn/issues/36503")] public void Discard_OutDiscard() { var source = @" class C { void M<T>(out T t) => throw null!; void M2() { M<string?>(out var _); M<object?>(out _); M<string>(out var _); #nullable disable annotations M<object>(out _); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var arguments = tree.GetRoot().DescendantNodes().OfType<ArgumentSyntax>(); var discard1 = arguments.First().Expression; Assert.Equal("var _", discard1.ToString()); Assert.Equal("System.String?", model.GetTypeInfoAndVerifyIOperation(discard1).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, model.GetTypeInfo(discard1).Nullability.Annotation); var discard2 = arguments.Skip(1).First().Expression; Assert.Equal("_", discard2.ToString()); Assert.Equal("System.Object?", model.GetTypeInfoAndVerifyIOperation(discard2).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, model.GetTypeInfo(discard2).Nullability.Annotation); var discard3 = arguments.Skip(2).First().Expression; Assert.Equal("var _", discard3.ToString()); Assert.Equal("System.String", model.GetTypeInfoAndVerifyIOperation(discard3).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, model.GetTypeInfo(discard3).Nullability.Annotation); var discard4 = arguments.Skip(3).First().Expression; Assert.Equal("_", discard4.ToString()); Assert.Equal("System.Object", model.GetTypeInfoAndVerifyIOperation(discard4).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, model.GetTypeInfo(discard4).Nullability.Annotation); } [Fact, WorkItem(36503, "https://github.com/dotnet/roslyn/issues/35010")] public void Discard_Deconstruction() { var source = @" class C { void M(string x, object y) { x = null; // 1 y = null; // 2 (var _, _) = (x, y); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var arguments = tree.GetRoot().DescendantNodes().OfType<ArgumentSyntax>(); // https://github.com/dotnet/roslyn/issues/35010: handle GetTypeInfo for deconstruction variables, discards, foreach deconstructions and nested deconstructions var discard1 = (DeclarationExpressionSyntax)arguments.First().Expression; Assert.Equal("var _", discard1.ToString()); Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfoAndVerifyIOperation(discard1.Designation).Nullability.Annotation); Assert.Equal("System.String", model.GetTypeInfo(discard1).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfo(discard1).Nullability.Annotation); Assert.Null(model.GetSymbolInfo(discard1).Symbol); Assert.Null(model.GetSymbolInfo(discard1.Designation).Symbol); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetDeclaredSymbol(discard1.Designation)); var discard2 = arguments.Skip(1).First().Expression; Assert.Equal("_", discard2.ToString()); Assert.Equal("System.Object", model.GetTypeInfoAndVerifyIOperation(discard2).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfo(discard2).Nullability.Annotation); Assert.Equal("object _", model.GetSymbolInfo(discard2).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Null(model.GetDeclaredSymbol(discard2)); } [Fact, WorkItem(35032, "https://github.com/dotnet/roslyn/issues/35032")] public void Discard_Pattern() { var source = @" public class C { public object? Property { get; } public void Deconstruct(out object? x, out object y) => throw null!; void M(C c) { _ = c is C { Property: _ }; _ = c is C (_, _); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discardPatterns = tree.GetRoot().DescendantNodes().OfType<DiscardPatternSyntax>().ToArray(); var discardPattern1 = discardPatterns[0]; Assert.Equal("_", discardPattern1.ToString()); Assert.Equal("System.Object", model.GetTypeInfo(discardPattern1).Type.ToTestDisplayString()); // Nullability in patterns are not yet supported: https://github.com/dotnet/roslyn/issues/35032 Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfo(discardPattern1).Nullability.Annotation); Assert.Null(model.GetSymbolInfo(discardPattern1).Symbol); var discardPattern2 = discardPatterns[1]; Assert.Equal("_", discardPattern2.ToString()); Assert.Equal("System.Object", model.GetTypeInfo(discardPattern2).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfo(discardPattern2).Nullability.Annotation); Assert.Null(model.GetSymbolInfo(discardPattern2).Symbol); } [Fact] public void Discard_03() { var source = @"#nullable disable class C<T> { #nullable enable void F(bool b, object o1, object? o2, C<object> o3, C<object?> o4) { _ /*T:object?*/ = (b ? o1 : o2); _ /*T:C<object!>!*/ = (b ? o3 : o4); // 1 var x = (b ? o3 : o4); // 2 _ /*T:C<object!>!*/ = (b ? o4 : o3); // 3 var y = (b ? o4 : o3); // 4 _ /*T:C<object!>!*/ = (b ? o3 : o5); _ /*T:C<object?>!*/ = (b ? o4 : o5); } #nullable disable static C<object> o5 = null; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,41): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // _ /*T:C<object!>!*/ = (b ? o3 : o4); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "o4").WithArguments("C<object?>", "C<object>").WithLocation(8, 41), // (9,27): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var x = (b ? o3 : o4); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "o4").WithArguments("C<object?>", "C<object>").WithLocation(9, 27), // (11,36): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // _ /*T:C<object!>!*/ = (b ? o4 : o3); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "o4").WithArguments("C<object?>", "C<object>").WithLocation(11, 36), // (12,22): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var y = (b ? o4 : o3); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "o4").WithArguments("C<object?>", "C<object>").WithLocation(12, 22) ); comp.VerifyTypes(); } [Fact, WorkItem(29635, "https://github.com/dotnet/roslyn/issues/29635")] public void Discard_04() { var source = @"#nullable disable class C<T> { #nullable enable void F(bool b, object o1) { (_ /*T:object!*/ = o1) /*T:object!*/.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void BinaryOperator_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(string? x1, string? y1) { string z1 = x1 + y1; } void Test2(string? x2, string? y2) { string z2 = x2 + y2 ?? """"; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void BinaryOperator_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(dynamic? x1, dynamic? y1) { dynamic z1 = x1 + y1; } void Test2(dynamic? x2, dynamic? y2) { dynamic z2 = x2 + y2 ?? """"; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void BinaryOperator_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(string? x1, CL0? y1) { CL0? z1 = x1 + y1; CL0 u1 = z1 ?? new CL0(); } void Test2(string? x2, CL1? y2) { CL1 z2 = x2 + y2; } void Test3(string x3, CL0? y3, CL2 z3) { CL2 u3 = x3 + y3 + z3; } void Test4(string x4, CL1 y4, CL2 z4) { CL2 u4 = x4 + y4 + z4; } } class CL0 { public static CL0 operator + (string? x, CL0 y) { return y; } } class CL1 { public static CL1? operator + (string x, CL1? y) { return y; } } class CL2 { public static CL2 operator + (CL0 x, CL2 y) { return y; } public static CL2 operator + (CL1 x, CL2 y) { return y; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,24): warning CS8604: Possible null reference argument for parameter 'y' in 'CL0 CL0.operator +(string? x, CL0 y)'. // CL0? z1 = x1 + y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y1").WithArguments("y", "CL0 CL0.operator +(string? x, CL0 y)").WithLocation(10, 24), // (16,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1? CL1.operator +(string x, CL1? y)'. // CL1 z2 = x2 + y2; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("x", "CL1? CL1.operator +(string x, CL1? y)").WithLocation(16, 18), // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = x2 + y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2 + y2").WithLocation(16, 18), // (21,23): warning CS8604: Possible null reference argument for parameter 'y' in 'CL0 CL0.operator +(string? x, CL0 y)'. // CL2 u3 = x3 + y3 + z3; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y3").WithArguments("y", "CL0 CL0.operator +(string? x, CL0 y)").WithLocation(21, 23), // (26,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL2 CL2.operator +(CL1 x, CL2 y)'. // CL2 u4 = x4 + y4 + z4; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x4 + y4").WithArguments("x", "CL2 CL2.operator +(CL1 x, CL2 y)").WithLocation(26, 18) ); } [Fact] public void BinaryOperator_03_WithDisallowAndAllowNull() { CSharpCompilation c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class CL0 { void Test1(string? x1, CL0? y1) { CL0? z1 = x1 + y1; CL0 u1 = z1 ?? new CL0(); } public static CL0 operator + (string? x, [AllowNull] CL0 y) => throw null!; } class CL1 { void Test2(string? x2, CL1? y2) { CL1 z2 = x2 + y2; // 1, 2 } public static CL1? operator + ([AllowNull] string x, [DisallowNull] CL1? y) => throw null!; } class CL2 { void Test3(string x3, CL0? y3, CL2 z3) { CL2 u3 = x3 + y3 + z3; } void Test4(string x4, CL1 y4, CL2 z4) { CL2 u4 = x4 + y4 + z4; } public static CL2 operator + ([AllowNull] CL0 x, CL2 y) => throw null!; public static CL2 operator + ([AllowNull] CL1 x, CL2 y) => throw null!; } ", AllowNullAttributeDefinition, DisallowNullAttributeDefinition }); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 c.VerifyDiagnostics( // (8,24): warning CS8604: Possible null reference argument for parameter 'y' in 'CL0 CL0.operator +(string? x, CL0 y)'. // CL0? z1 = x1 + y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y1").WithArguments("y", "CL0 CL0.operator +(string? x, CL0 y)").WithLocation(8, 24), // (19,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1? CL1.operator +(string x, CL1? y)'. // CL1 z2 = x2 + y2; // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("x", "CL1? CL1.operator +(string x, CL1? y)").WithLocation(19, 18), // (19,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = x2 + y2; // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2 + y2").WithLocation(19, 18), // (29,23): warning CS8604: Possible null reference argument for parameter 'y' in 'CL0 CL0.operator +(string? x, CL0 y)'. // CL2 u3 = x3 + y3 + z3; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y3").WithArguments("y", "CL0 CL0.operator +(string? x, CL0 y)").WithLocation(29, 23), // (34,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL2 CL2.operator +(CL1 x, CL2 y)'. // CL2 u4 = x4 + y4 + z4; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x4 + y4").WithArguments("x", "CL2 CL2.operator +(CL1 x, CL2 y)").WithLocation(34, 18) ); } [Fact] public void BinaryOperator_03_WithMaybeAndNotNull() { CSharpCompilation c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class CL0 { void Test1(string x1, CL0 y1) { CL0 z1 = x1 + y1; // 1 } [return: MaybeNull] public static CL0 operator + (string x, CL0 y) => throw null!; } class CL1 { void Test2(string x2, CL1 y2) { CL1 z2 = x2 + y2; } [return: NotNull] public static CL1? operator + (string x, CL1 y) => throw null!; } class CL2 { void Test3(string x3, CL0 y3, CL2 z3) { CL2 u3 = x3 + y3 + z3; // 2, 3 } void Test4(string x4, CL1 y4, CL2 z4) { CL2 u4 = x4 + y4 + z4; } [return: MaybeNull] public static CL2 operator + (CL0 x, CL2 y) => throw null!; [return: NotNull] public static CL2? operator + (CL1 x, CL2 y) => throw null!; } ", MaybeNullAttributeDefinition, NotNullAttributeDefinition }); c.VerifyDiagnostics( // (8,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 z1 = x1 + y1; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1 + y1").WithLocation(8, 18), // (28,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL2 CL2.operator +(CL0 x, CL2 y)'. // CL2 u3 = x3 + y3 + z3; // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x3 + y3").WithArguments("x", "CL2 CL2.operator +(CL0 x, CL2 y)").WithLocation(28, 18), // (28,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL2 u3 = x3 + y3 + z3; // 2, 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3 + y3 + z3").WithLocation(28, 18) ); } [Fact] public void BinaryOperator_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1, CL0? y1) { CL0? z1 = x1 && y1; CL0 u1 = z1; } void Test2(CL0 x2, CL0? y2) { CL0? z2 = x2 && y2; CL0 u2 = z2 ?? new CL0(); } } class CL0 { public static CL0 operator &(CL0 x, CL0? y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0 x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'bool CL0.operator false(CL0 x)'. // CL0? z1 = x1 && y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "bool CL0.operator false(CL0 x)").WithLocation(10, 19), // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator &(CL0 x, CL0? y)'. // CL0? z1 = x1 && y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL0 CL0.operator &(CL0 x, CL0? y)").WithLocation(10, 19) ); } [Fact] public void BinaryOperator_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1, CL0? y1) { CL0? z1 = x1 && y1; } } class CL0 { public static CL0 operator &(CL0? x, CL0 y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0 x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'bool CL0.operator false(CL0 x)'. // CL0? z1 = x1 && y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "bool CL0.operator false(CL0 x)").WithLocation(10, 19), // (10,25): warning CS8604: Possible null reference argument for parameter 'y' in 'CL0 CL0.operator &(CL0? x, CL0 y)'. // CL0? z1 = x1 && y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y1").WithArguments("y", "CL0 CL0.operator &(CL0? x, CL0 y)").WithLocation(10, 25) ); } [Fact] public void BinaryOperator_06() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1, CL0? y1) { CL0? z1 = x1 && y1; } } class CL0 { public static CL0 operator &(CL0? x, CL0? y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0? x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void BinaryOperator_07() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1, CL0? y1) { CL0? z1 = x1 || y1; } } class CL0 { public static CL0 operator |(CL0? x, CL0? y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0? x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'bool CL0.operator true(CL0 x)'. // CL0? z1 = x1 || y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "bool CL0.operator true(CL0 x)").WithLocation(10, 19) ); } [Fact] public void BinaryOperator_08() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1, CL0? y1) { CL0? z1 = x1 || y1; } } class CL0 { public static CL0 operator |(CL0? x, CL0? y) { return new CL0(); } public static bool operator true(CL0? x) { return false; } public static bool operator false(CL0 x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void BinaryOperator_09() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0 x1, CL0 y1, CL0 z1) { CL0? u1 = x1 && y1 || z1; } } class CL0 { public static CL0? operator &(CL0 x, CL0 y) { return new CL0(); } public static CL0 operator |(CL0 x, CL0 y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0 x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'bool CL0.operator true(CL0 x)'. // CL0? u1 = x1 && y1 || z1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1 && y1").WithArguments("x", "bool CL0.operator true(CL0 x)").WithLocation(10, 19), // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator |(CL0 x, CL0 y)'. // CL0? u1 = x1 && y1 || z1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1 && y1").WithArguments("x", "CL0 CL0.operator |(CL0 x, CL0 y)").WithLocation(10, 19) ); } [Fact] public void BinaryOperator_10() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1, CL0? y1, CL0? z1) { CL0? u1 = x1 && y1 || z1; } void Test2(CL0 x2, CL0? y2, CL0? z2) { CL0? u1 = x2 && y2 || z2; } } class CL0 { public static CL0 operator &(CL0? x, CL0? y) { return new CL0(); } public static CL0 operator |(CL0 x, CL0? y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0? x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void BinaryOperator_11() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(System.Action x1, System.Action y1) { System.Action u1 = x1 + y1; } void Test2(System.Action x2, System.Action y2) { System.Action u2 = x2 + y2 ?? x2; } void Test3(System.Action? x3, System.Action y3) { System.Action u3 = x3 + y3; } void Test4(System.Action? x4, System.Action y4) { System.Action u4 = x4 + y4 ?? y4; } void Test5(System.Action x5, System.Action? y5) { System.Action u5 = x5 + y5; } void Test6(System.Action x6, System.Action? y6) { System.Action u6 = x6 + y6 ?? x6; } void Test7(System.Action? x7, System.Action? y7) { System.Action u7 = x7 + y7; } void Test8(System.Action x8, System.Action y8) { System.Action u8 = x8 - y8; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (40,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action u7 = x7 + y7; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x7 + y7").WithLocation(40, 28), // (45,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action u8 = x8 - y8; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x8 - y8").WithLocation(45, 28) ); } [Fact] public void BinaryOperator_12() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0 x1, CL0 y1) { CL0? u1 = x1 && !y1; } void Test2(bool x2, bool y2) { bool u2 = x2 && !y2; } } class CL0 { public static CL0 operator &(CL0? x, CL0 y) { return new CL0(); } public static bool operator true(CL0? x) { return false; } public static bool operator false(CL0? x) { return false; } public static CL0? operator !(CL0 x) { return null; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,25): warning CS8604: Possible null reference argument for parameter 'y' in 'CL0 CL0.operator &(CL0? x, CL0 y)'. // CL0? u1 = x1 && !y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "!y1").WithArguments("y", "CL0 CL0.operator &(CL0? x, CL0 y)").WithLocation(10, 25) ); } [Fact] public void BinaryOperator_13() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0 x1, CL0 y1) { CL0 z1 = x1 && y1; } } class CL0 { public static CL0? operator &(CL0 x, CL0 y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0? x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 z1 = x1 && y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1 && y1").WithLocation(10, 18) ); } [Fact] public void BinaryOperator_14() { var source = @"struct S { public static S operator&(S a, S b) => a; public static S operator|(S a, S b) => b; public static bool operator true(S? s) => true; public static bool operator false(S? s) => false; static void And(S x, S? y) { if (x && x) { } if (x && y) { } if (y && x) { } if (y && y) { } } static void Or(S x, S? y) { if (x || x) { } if (x || y) { } if (y || x) { } if (y || y) { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void BinaryOperator_15() { var source = @"struct S { public static S operator+(S a, S b) => a; static void F(S x, S? y) { S? s; s = x + x; s = x + y; s = y + x; s = y + y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void BinaryOperator_15_WithDisallowNull() { var source = @" using System.Diagnostics.CodeAnalysis; struct S { public static S? operator+(S? a, [DisallowNull] S? b) => throw null!; static void F(S? x, S? y) { if (x == null) throw null!; S? s; s = x + x; s = x + y; // 1 s = y + x; s = y + y; // 2 } }"; // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var comp = CreateCompilation(new[] { source, DisallowNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void BinaryOperator_16() { var source = @"struct S { public static bool operator<(S a, S b) => true; public static bool operator<=(S a, S b) => true; public static bool operator>(S a, S b) => true; public static bool operator>=(S a, S b) => true; public static bool operator==(S a, S b) => true; public static bool operator!=(S a, S b) => true; public override bool Equals(object other) => true; public override int GetHashCode() => 0; static void F(S x, S? y) { if (x < y) { } if (x <= y) { } if (x > y) { } if (x >= y) { } if (x == y) { } if (x != y) { } if (y < x) { } if (y <= x) { } if (y > x) { } if (y >= x) { } if (y == x) { } if (y != x) { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversion_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1) { System.Action u1 = x1.M1; } void Test2(CL0 x2) { System.Action u2 = x2.M1; } } class CL0 { public void M1() {} } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,28): warning CS8602: Dereference of a possibly null reference. // System.Action u1 = x1.M1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(10, 28) ); } [Fact] public void MethodGroupConversion_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void M1<T>(T x){} void Test1() { System.Action<string?> u1 = M1<string>; } void Test2() { System.Action<string> u2 = M1<string?>; } void Test3() { System.Action<CL0<string?>> u3 = M1<CL0<string>>; } void Test4() { System.Action<CL0<string>> u4 = M1<CL0<string?>>; } } class CL0<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,37): warning CS8622: Nullability of reference types in type of parameter 'x' of 'void C.M1<string>(string x)' doesn't match the target delegate 'Action<string?>'. // System.Action<string?> u1 = M1<string>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M1<string>").WithArguments("x", "void C.M1<string>(string x)", "System.Action<string?>").WithLocation(12, 37), // (22,42): warning CS8622: Nullability of reference types in type of parameter 'x' of 'void C.M1<CL0<string>>(CL0<string> x)' doesn't match the target delegate 'Action<CL0<string?>>'. // System.Action<CL0<string?>> u3 = M1<CL0<string>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M1<CL0<string>>").WithArguments("x", "void C.M1<CL0<string>>(CL0<string> x)", "System.Action<CL0<string?>>").WithLocation(22, 42), // (27,41): warning CS8622: Nullability of reference types in type of parameter 'x' of 'void C.M1<CL0<string?>>(CL0<string?> x)' doesn't match the target delegate 'Action<CL0<string>>'. // System.Action<CL0<string>> u4 = M1<CL0<string?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M1<CL0<string?>>").WithArguments("x", "void C.M1<CL0<string?>>(CL0<string?> x)", "System.Action<CL0<string>>").WithLocation(27, 41) ); } [Fact] public void MethodGroupConversion_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void M1<T>(T x){} void Test1() { System.Action<string?> u1 = (System.Action<string?>)M1<string>; // 1 System.Action<string> u2 = (System.Action<string>)M1<string?>; System.Action<CL0<string?>> u3 = (System.Action<CL0<string?>>)M1<CL0<string>>; // 2 System.Action<CL0<string>> u4 = (System.Action<CL0<string>>)M1<CL0<string?>>; //3 } } class CL0<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,37): warning CS8622: Nullability of reference types in type of parameter 'x' of 'void C.M1<string>(string x)' doesn't match the target delegate 'Action<string?>'. // System.Action<string?> u1 = (System.Action<string?>)M1<string>; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(System.Action<string?>)M1<string>").WithArguments("x", "void C.M1<string>(string x)", "System.Action<string?>").WithLocation(8, 37), // (10,42): warning CS8622: Nullability of reference types in type of parameter 'x' of 'void C.M1<CL0<string>>(CL0<string> x)' doesn't match the target delegate 'Action<CL0<string?>>'. // System.Action<CL0<string?>> u3 = (System.Action<CL0<string?>>)M1<CL0<string>>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(System.Action<CL0<string?>>)M1<CL0<string>>").WithArguments("x", "void C.M1<CL0<string>>(CL0<string> x)", "System.Action<CL0<string?>>").WithLocation(10, 42), // (11,41): warning CS8622: Nullability of reference types in type of parameter 'x' of 'void C.M1<CL0<string?>>(CL0<string?> x)' doesn't match the target delegate 'Action<CL0<string>>'. // System.Action<CL0<string>> u4 = (System.Action<CL0<string>>)M1<CL0<string?>>; //3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(System.Action<CL0<string>>)M1<CL0<string?>>").WithArguments("x", "void C.M1<CL0<string?>>(CL0<string?> x)", "System.Action<CL0<string>>").WithLocation(11, 41) ); } [Fact] public void MethodGroupConversion_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } T M1<T>(){throw new System.Exception();} void Test1() { System.Func<string?> u1 = M1<string>; } void Test2() { System.Func<string> u2 = M1<string?>; } void Test3() { System.Func<CL0<string?>> u3 = M1<CL0<string>>; } void Test4() { System.Func<CL0<string>> u4 = M1<CL0<string?>>; } } class CL0<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (17,34): warning CS8621: Nullability of reference types in return type of 'string? C.M1<string?>()' doesn't match the target delegate 'Func<string>'. // System.Func<string> u2 = M1<string?>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M1<string?>").WithArguments("string? C.M1<string?>()", "System.Func<string>").WithLocation(17, 34), // (22,40): warning CS8621: Nullability of reference types in return type of 'CL0<string> C.M1<CL0<string>>()' doesn't match the target delegate 'Func<CL0<string?>>'. // System.Func<CL0<string?>> u3 = M1<CL0<string>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M1<CL0<string>>").WithArguments("CL0<string> C.M1<CL0<string>>()", "System.Func<CL0<string?>>").WithLocation(22, 40), // (27,39): warning CS8621: Nullability of reference types in return type of 'CL0<string?> C.M1<CL0<string?>>()' doesn't match the target delegate 'Func<CL0<string>>'. // System.Func<CL0<string>> u4 = M1<CL0<string?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M1<CL0<string?>>").WithArguments("CL0<string?> C.M1<CL0<string?>>()", "System.Func<CL0<string>>").WithLocation(27, 39) ); } [Fact] public void MethodGroupConversion_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } T M1<T>(){throw new System.Exception();} void Test1() { System.Func<string?> u1 = (System.Func<string?>)M1<string>; System.Func<string> u2 = (System.Func<string>)M1<string?>; // 1 System.Func<CL0<string?>> u3 = (System.Func<CL0<string?>>)M1<CL0<string>>; // 2 System.Func<CL0<string>> u4 = (System.Func<CL0<string>>)M1<CL0<string?>>; // 3 } } class CL0<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,34): warning CS8621: Nullability of reference types in return type of 'string? C.M1<string?>()' doesn't match the target delegate 'Func<string>'. // System.Func<string> u2 = (System.Func<string>)M1<string?>; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "(System.Func<string>)M1<string?>").WithArguments("string? C.M1<string?>()", "System.Func<string>").WithLocation(13, 34), // (14,40): warning CS8621: Nullability of reference types in return type of 'CL0<string> C.M1<CL0<string>>()' doesn't match the target delegate 'Func<CL0<string?>>'. // System.Func<CL0<string?>> u3 = (System.Func<CL0<string?>>)M1<CL0<string>>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "(System.Func<CL0<string?>>)M1<CL0<string>>").WithArguments("CL0<string> C.M1<CL0<string>>()", "System.Func<CL0<string?>>").WithLocation(14, 40), // (15,39): warning CS8621: Nullability of reference types in return type of 'CL0<string?> C.M1<CL0<string?>>()' doesn't match the target delegate 'Func<CL0<string>>'. // System.Func<CL0<string>> u4 = (System.Func<CL0<string>>)M1<CL0<string?>>; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "(System.Func<CL0<string>>)M1<CL0<string?>>").WithArguments("CL0<string?> C.M1<CL0<string?>>()", "System.Func<CL0<string>>").WithLocation(15, 39) ); } [Fact] public void MethodGroupConversion_06() { var source = @"delegate void D<T>(T t); class A { } class B<T> { internal void F(T t) { } } class C { static B<T> Create<T>(T t) => new B<T>(); static void F1(A x, A? y) { D<A> d1; d1 = Create(x).F; d1 = Create(y).F; x = y; // 1 d1 = Create(x).F; } static void F2(A x, A? y) { D<A?> d2; d2 = Create(x).F; // 2 d2 = Create(y).F; x = y; // 3 d2 = Create(x).F; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = y; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(15, 13), // (21,14): warning CS8622: Nullability of reference types in type of parameter 't' of 'void B<A>.F(A t)' doesn't match the target delegate 'D<A?>'. // d2 = Create(x).F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Create(x).F").WithArguments("t", "void B<A>.F(A t)", "D<A?>").WithLocation(21, 14), // (23,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = y; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(23, 13)); } [Fact] public void UnaryOperator_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1) { CL0 u1 = !x1; } void Test2(CL1 x2) { CL1 u2 = !x2; } void Test3(CL2? x3) { CL2 u3 = !x3; } void Test4(CL1 x4) { dynamic y4 = x4; CL1 u4 = !y4; dynamic v4 = !y4 ?? y4; } void Test5(bool x5) { bool u5 = !x5; } } class CL0 { public static CL0 operator !(CL0 x) { return new CL0(); } } class CL1 { public static CL1? operator !(CL1 x) { return new CL1(); } } class CL2 { public static CL2 operator !(CL2? x) { return new CL2(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator !(CL0 x)'. // CL0 u1 = !x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL0 CL0.operator !(CL0 x)").WithLocation(10, 19), // (15,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u2 = !x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "!x2").WithLocation(15, 18) ); } [Fact] public void UnaryOperator_02() { var source = @"struct S { public static S operator~(S s) => s; static void F(S? s) { s = ~s; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Conversion_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1) { CL1 u1 = x1; } void Test2(CL0? x2, CL0 y2) { int u2 = x2; long v2 = x2; int w2 = y2; } void Test3(CL0 x3) { CL2 u3 = x3; } void Test4(CL0 x4) { CL3? u4 = x4; CL3 v4 = u4 ?? new CL3(); } void Test5(dynamic? x5) { CL3 u5 = x5; } void Test6(dynamic? x6) { CL3? u6 = x6; CL3 v6 = u6 ?? new CL3(); } void Test7(CL0? x7) { dynamic u7 = x7; } void Test8(CL0 x8) { dynamic? u8 = x8; dynamic v8 = u8 ?? x8; } void Test9(dynamic? x9) { object u9 = x9; } void Test10(object? x10) { dynamic u10 = x10; } void Test11(CL4? x11) { CL3 u11 = x11; } void Test12(CL3? x12) { CL4 u12 = (CL4)x12; } void Test13(int x13) { object? u13 = x13; object v13 = u13 ?? new object(); } void Test14<T>(T x14) { object u14 = x14; object v14 = ((object)x14) ?? new object(); } void Test15(int? x15) { object u15 = x15; } void Test16() { System.IFormattable? u16 = $""{3}""; object v16 = u16 ?? new object(); } } class CL0 { public static implicit operator CL1(CL0 x) { return new CL1(); } public static implicit operator int(CL0 x) { return 0; } public static implicit operator long(CL0? x) { return 0; } public static implicit operator CL2?(CL0 x) { return new CL2(); } public static implicit operator CL3(CL0? x) { return new CL3(); } } class CL1 {} class CL2 {} class CL3 {} class CL4 : CL3 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0.implicit operator CL1(CL0 x)'. // CL1 u1 = x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL0.implicit operator CL1(CL0 x)").WithLocation(10, 18), // (15,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0.implicit operator int(CL0 x)'. // int u2 = x2; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("x", "CL0.implicit operator int(CL0 x)").WithLocation(15, 18), // (22,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL2 u3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(22, 18), // (33,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL3 u5 = x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5").WithLocation(33, 18), // (44,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // dynamic u7 = x7; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x7").WithLocation(44, 22), // (55,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object u9 = x9; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x9").WithLocation(55, 21), // (60,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // dynamic u10 = x10; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x10").WithLocation(60, 23), // (65,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL3 u11 = x11; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x11").WithLocation(65, 19), // (70,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL4 u12 = (CL4)x12; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(CL4)x12").WithLocation(70, 19), // (81,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object u14 = x14; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x14").WithLocation(81, 22), // (82,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // object v14 = ((object)x14) ?? new object(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)x14").WithLocation(82, 23), // (87,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object u15 = x15; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x15").WithLocation(87, 22)); } [Fact] public void Conversion_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0<string?> x1) { CL0<string> u1 = x1; CL0<string> v1 = (CL0<string>)x1; } } class CL0<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,26): warning CS8619: Nullability of reference types in value of type 'CL0<string?>' doesn't match target type 'CL0<string>'. // CL0<string> u1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("CL0<string?>", "CL0<string>").WithLocation(10, 26), // (11,26): warning CS8619: Nullability of reference types in value of type 'CL0<string?>' doesn't match target type 'CL0<string>'. // CL0<string> v1 = (CL0<string>)x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(CL0<string>)x1").WithArguments("CL0<string?>", "CL0<string>").WithLocation(11, 26) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void ImplicitConversions_01() { var source = @"class A<T> { } class B<T> : A<T> { } class C { static void F1(B<object> x1) { A<object?> y1 = x1; y1 = x1; y1 = x1!; } static void F2(B<object?> x2) { A<object> y2 = x2; y2 = x2; y2 = x2!; } static void F3(B<object>? x3) { A<object?> y3 = x3; y3 = x3; y3 = x3!; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,25): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // A<object?> y1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("B<object>", "A<object?>").WithLocation(7, 25), // (8,14): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // y1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("B<object>", "A<object?>").WithLocation(8, 14), // (13,24): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'A<object>'. // A<object> y2 = x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("B<object?>", "A<object>").WithLocation(13, 24), // (14,14): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'A<object>'. // y2 = x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("B<object?>", "A<object>").WithLocation(14, 14), // (19,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // A<object?> y3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(19, 25), // (19,25): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // A<object?> y3 = x3; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("B<object>", "A<object?>").WithLocation(19, 25), // (20,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(20, 14), // (20,14): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // y3 = x3; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("B<object>", "A<object?>").WithLocation(20, 14) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void ImplicitConversions_02() { var source = @"interface IA<T> { } interface IB<T> : IA<T> { } class C { static void F1(IB<object> x1) { IA<object?> y1 = x1; y1 = x1; y1 = x1!; } static void F2(IB<object?> x2) { IA<object> y2 = x2; y2 = x2; y2 = x2!; } static void F3(IB<object>? x3) { IA<object?> y3 = x3; y3 = x3; y3 = x3!; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,26): warning CS8619: Nullability of reference types in value of type 'IB<object>' doesn't match target type 'IA<object?>'. // IA<object?> y1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("IB<object>", "IA<object?>").WithLocation(7, 26), // (8,14): warning CS8619: Nullability of reference types in value of type 'IB<object>' doesn't match target type 'IA<object?>'. // y1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("IB<object>", "IA<object?>").WithLocation(8, 14), // (13,25): warning CS8619: Nullability of reference types in value of type 'IB<object?>' doesn't match target type 'IA<object>'. // IA<object> y2 = x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("IB<object?>", "IA<object>").WithLocation(13, 25), // (14,14): warning CS8619: Nullability of reference types in value of type 'IB<object?>' doesn't match target type 'IA<object>'. // y2 = x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("IB<object?>", "IA<object>").WithLocation(14, 14), // (19,26): warning CS8600: Converting null literal or possible null value to non-nullable type. // IA<object?> y3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(19, 26), // (19,26): warning CS8619: Nullability of reference types in value of type 'IB<object>' doesn't match target type 'IA<object?>'. // IA<object?> y3 = x3; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("IB<object>", "IA<object?>").WithLocation(19, 26), // (20,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(20, 14), // (20,14): warning CS8619: Nullability of reference types in value of type 'IB<object>' doesn't match target type 'IA<object?>'. // y3 = x3; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("IB<object>", "IA<object?>").WithLocation(20, 14)); } [Fact] public void ImplicitConversions_03() { var source = @"interface IOut<out T> { } class C { static void F(IOut<object> x) { IOut<object?> y = x; } static void G(IOut<object?> x) { IOut<object> y = x; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,26): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // IOut<object> y = x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IOut<object?>", "IOut<object>").WithLocation(10, 26)); } [Fact] public void ImplicitConversions_04() { var source = @"interface IIn<in T> { } class C { static void F(IIn<object> x) { IIn<object?> y = x; } static void G(IIn<object?> x) { IIn<object> y = x; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,26): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // IIn<object?> y = x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object>", "IIn<object?>").WithLocation(6, 26)); } [Fact] public void ImplicitConversions_05() { var source = @"interface IOut<out T> { } class A<T> : IOut<T> { } class C { static void F(A<string> x) { IOut<object?> y = x; } static void G(A<string?> x) { IOut<object> y = x; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,26): warning CS8619: Nullability of reference types in value of type 'A<string?>' doesn't match target type 'IOut<object>'. // IOut<object> y = x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<string?>", "IOut<object>").WithLocation(11, 26)); } [Fact] public void ImplicitConversions_06() { var source = @"interface IIn<in T> { } interface IOut<out T> { } class A<T> : IIn<object>, IOut<object?> { } class B : IIn<object>, IOut<object?> { } class C { static void F(A<string> a1, B b1) { IIn<object?> y = a1; y = b1; IOut<object?> z = a1; z = b1; } static void G(A<string> a2, B b2) { IIn<object> y = a2; y = b2; IOut<object> z = a2; z = b2; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29897: Report the base types that did not match // rather than the derived or implementing type. For instance, report `'IIn<object>' // doesn't match ... 'IIn<object?>'` rather than `'A<string>' doesn't match ...`. comp.VerifyDiagnostics( // (9,26): warning CS8619: Nullability of reference types in value of type 'A<string>' doesn't match target type 'IIn<object?>'. // IIn<object?> y = a1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1").WithArguments("A<string>", "IIn<object?>").WithLocation(9, 26), // (10,13): warning CS8619: Nullability of reference types in value of type 'B' doesn't match target type 'IIn<object?>'. // y = b1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b1").WithArguments("B", "IIn<object?>").WithLocation(10, 13), // (18,26): warning CS8619: Nullability of reference types in value of type 'A<string>' doesn't match target type 'IOut<object>'. // IOut<object> z = a2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("A<string>", "IOut<object>").WithLocation(18, 26), // (19,13): warning CS8619: Nullability of reference types in value of type 'B' doesn't match target type 'IOut<object>'. // z = b2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b2").WithArguments("B", "IOut<object>").WithLocation(19, 13)); } [Fact, WorkItem(29898, "https://github.com/dotnet/roslyn/issues/29898")] public void ImplicitConversions_07() { var source = @"class A<T> { } class B<T> { public static implicit operator A<T>(B<T> b) => throw null!; } class C { static B<T> F<T>(T t) => throw null!; static void G(A<object?> a) => throw null!; static void Main(object? x) { var y = F(x); G(y); if (x == null) return; var z = F(x); G(z); // warning var z2 = F(x); G(z2!); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,11): warning CS8620: Argument of type 'B<object>' cannot be used for parameter 'a' of type 'A<object?>' in 'void C.G(A<object?> a)' due to differences in the nullability of reference types. // G(z); // warning Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("B<object>", "A<object?>", "a", "void C.G(A<object?> a)").WithLocation(18, 11) ); } [Fact] public void ImplicitConversion_Params() { var source = @"class A<T> { } class B<T> { public static implicit operator A<T>(B<T> b) => throw null!; } class C { static B<T> F<T>(T t) => throw null!; static void G(params A<object>[] a) => throw null!; static void Main(object? x) { var y = F(x); G(y); // 1 if (x == null) return; var z = F(x); G(z); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,11): warning CS8620: Argument of type 'B<object?>' cannot be used for parameter 'a' of type 'A<object>' in 'void C.G(params A<object>[] a)' due to differences in the nullability of reference types. // G(y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("B<object?>", "A<object>", "a", "void C.G(params A<object>[] a)").WithLocation(16, 11) ); } [Fact] public void ImplicitConversion_Typeless() { var source = @" public struct Optional<T> { public static implicit operator Optional<T>(T value) => throw null!; } class C { static void G1(Optional<object> a) => throw null!; static void G2(Optional<object?> a) => throw null!; static void M() { G1(null); // 1 G2(null); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,12): warning CS8625: Cannot convert null literal to non-nullable reference type. // G1(null); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 12) ); } [Fact] public void ImplicitConversion_Typeless_WithConstraint() { var source = @" public struct Optional<T> where T : class { public static implicit operator Optional<T>(T value) => throw null!; } class C { static void G(Optional<object> a) => throw null!; static void M() { G(null); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // G(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 11) ); } [Fact, WorkItem(41763, "https://github.com/dotnet/roslyn/issues/41763")] public void Conversions_EnumToUnderlyingType_SemanticModel() { var source = @" enum E { A = 1, B = (int)A }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); comp.VerifyDiagnostics(); var node = tree.GetRoot().DescendantNodes().OfType<EnumMemberDeclarationSyntax>().ElementAt(1); model.GetSymbolInfo(node.EqualsValue.Value); } [Fact] public void IdentityConversion_LocalDeclaration() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } interface IBoth<in T, out U> { } class C { static void F1(I<object> x1, IIn<object> y1, IOut<object> z1, IBoth<object, object> w1) { I<object?> a1 = x1; IIn<object?> b1 = y1; IOut<object?> c1 = z1; IBoth<object?, object?> d1 = w1; } static void F2(I<object?> x2, IIn<object?> y2, IOut<object?> z2, IBoth<object?, object?> w2) { I<object> a2 = x2; IIn<object> b2 = y2; IOut<object> c2 = z2; IBoth<object, object> d2 = w2; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,25): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // I<object?> a1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("I<object>", "I<object?>").WithLocation(9, 25), // (10,27): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // IIn<object?> b1 = y1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("IIn<object>", "IIn<object?>").WithLocation(10, 27), // (12,38): warning CS8619: Nullability of reference types in value of type 'IBoth<object, object>' doesn't match target type 'IBoth<object?, object?>'. // IBoth<object?, object?> d1 = w1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w1").WithArguments("IBoth<object, object>", "IBoth<object?, object?>").WithLocation(12, 38), // (16,24): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // I<object> a2 = x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("I<object?>", "I<object>").WithLocation(16, 24), // (18,27): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // IOut<object> c2 = z2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "z2").WithArguments("IOut<object?>", "IOut<object>").WithLocation(18, 27), // (19,36): warning CS8619: Nullability of reference types in value of type 'IBoth<object?, object?>' doesn't match target type 'IBoth<object, object>'. // IBoth<object, object> d2 = w2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w2").WithArguments("IBoth<object?, object?>", "IBoth<object, object>").WithLocation(19, 36)); } [Fact] public void IdentityConversion_Assignment() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } interface IBoth<in T, out U> { } class C { static void F1(I<object> x1, IIn<object> y1, IOut<object> z1, IBoth<object, object> w1) { I<object?> a1; a1 = x1; IIn<object?> b1; b1 = y1; IOut<object?> c1; c1 = z1; IBoth<object?, object?> d1; d1 = w1; } static void F2(I<object?> x2, IIn<object?> y2, IOut<object?> z2, IBoth<object?, object?> w2) { I<object> a2; a2 = x2; IIn<object> b2; b2 = y2; IOut<object> c2; c2 = z2; IBoth<object, object> d2; d2 = w2; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,14): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // a1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("I<object>", "I<object?>").WithLocation(10, 14), // (12,14): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // b1 = y1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("IIn<object>", "IIn<object?>").WithLocation(12, 14), // (16,14): warning CS8619: Nullability of reference types in value of type 'IBoth<object, object>' doesn't match target type 'IBoth<object?, object?>'. // d1 = w1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w1").WithArguments("IBoth<object, object>", "IBoth<object?, object?>").WithLocation(16, 14), // (21,14): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // a2 = x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("I<object?>", "I<object>").WithLocation(21, 14), // (25,14): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // c2 = z2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "z2").WithArguments("IOut<object?>", "IOut<object>").WithLocation(25, 14), // (27,14): warning CS8619: Nullability of reference types in value of type 'IBoth<object?, object?>' doesn't match target type 'IBoth<object, object>'. // d2 = w2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w2").WithArguments("IBoth<object?, object?>", "IBoth<object, object>").WithLocation(27, 14)); } [Fact] public void IdentityConversion_Argument() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(I<object> x, IIn<object> y, IOut<object> z) { G(x, y, z); } static void G(I<object?> x, IIn<object?> y, IOut<object?> z) { F(x, y, z); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,11): warning CS8620: Nullability of reference types in argument of type 'I<object>' doesn't match target type 'I<object?>' for parameter 'x' in 'void C.G(I<object?> x, IIn<object?> y, IOut<object?> z)'. // G(x, y, z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "x", "void C.G(I<object?> x, IIn<object?> y, IOut<object?> z)").WithLocation(8, 11), // (8,14): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'y' in 'void C.G(I<object?> x, IIn<object?> y, IOut<object?> z)'. // G(x, y, z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IIn<object>", "IIn<object?>", "y", "void C.G(I<object?> x, IIn<object?> y, IOut<object?> z)").WithLocation(8, 14), // (12,11): warning CS8620: Nullability of reference types in argument of type 'I<object?>' doesn't match target type 'I<object>' for parameter 'x' in 'void C.F(I<object> x, IIn<object> y, IOut<object> z)'. // F(x, y, z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object?>", "I<object>", "x", "void C.F(I<object> x, IIn<object> y, IOut<object> z)").WithLocation(12, 11), // (12,17): warning CS8620: Nullability of reference types in argument of type 'IOut<object?>' doesn't match target type 'IOut<object>' for parameter 'z' in 'void C.F(I<object> x, IIn<object> y, IOut<object> z)'. // F(x, y, z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IOut<object?>", "IOut<object>", "z", "void C.F(I<object> x, IIn<object> y, IOut<object> z)").WithLocation(12, 17)); } [Fact] public void IdentityConversion_OutArgument() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(out I<object> x, out IIn<object> y, out IOut<object> z) { G(out x, out y, out z); } static void G(out I<object?> x, out IIn<object?> y, out IOut<object?> z) { F(out x, out y, out z); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,15): warning CS8624: Argument of type 'I<object>' cannot be used as an output of type 'I<object?>' for parameter 'x' in 'void C.G(out I<object?> x, out IIn<object?> y, out IOut<object?> z)' due to differences in the nullability of reference types. // G(out x, out y, out z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "x").WithArguments("I<object>", "I<object?>", "x", "void C.G(out I<object?> x, out IIn<object?> y, out IOut<object?> z)").WithLocation(8, 15), // (8,29): warning CS8624: Argument of type 'IOut<object>' cannot be used as an output of type 'IOut<object?>' for parameter 'z' in 'void C.G(out I<object?> x, out IIn<object?> y, out IOut<object?> z)' due to differences in the nullability of reference types. // G(out x, out y, out z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "z").WithArguments("IOut<object>", "IOut<object?>", "z", "void C.G(out I<object?> x, out IIn<object?> y, out IOut<object?> z)").WithLocation(8, 29), // (12,15): warning CS8624: Argument of type 'I<object?>' cannot be used as an output of type 'I<object>' for parameter 'x' in 'void C.F(out I<object> x, out IIn<object> y, out IOut<object> z)' due to differences in the nullability of reference types. // F(out x, out y, out z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "x").WithArguments("I<object?>", "I<object>", "x", "void C.F(out I<object> x, out IIn<object> y, out IOut<object> z)").WithLocation(12, 15), // (12,22): warning CS8624: Argument of type 'IIn<object?>' cannot be used as an output of type 'IIn<object>' for parameter 'y' in 'void C.F(out I<object> x, out IIn<object> y, out IOut<object> z)' due to differences in the nullability of reference types. // F(out x, out y, out z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "y").WithArguments("IIn<object?>", "IIn<object>", "y", "void C.F(out I<object> x, out IIn<object> y, out IOut<object> z)").WithLocation(12, 22) ); } [Fact] public void IdentityConversion_RefArgument() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(ref I<object> x, ref IIn<object> y, ref IOut<object> z) { G(ref x, ref y, ref z); } static void G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z) { F(ref x, ref y, ref z); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,15): warning CS8620: Argument of type 'I<object>' cannot be used as an input of type 'I<object?>' for parameter 'x' in 'void C.G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z)' due to differences in the nullability of reference types. // G(ref x, ref y, ref z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "x", "void C.G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z)").WithLocation(8, 15), // (8,22): warning CS8620: Argument of type 'IIn<object>' cannot be used as an input of type 'IIn<object?>' for parameter 'y' in 'void C.G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z)' due to differences in the nullability of reference types. // G(ref x, ref y, ref z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IIn<object>", "IIn<object?>", "y", "void C.G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z)").WithLocation(8, 22), // (8,29): warning CS8620: Argument of type 'IOut<object>' cannot be used as an input of type 'IOut<object?>' for parameter 'z' in 'void C.G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z)' due to differences in the nullability of reference types. // G(ref x, ref y, ref z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IOut<object>", "IOut<object?>", "z", "void C.G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z)").WithLocation(8, 29), // (12,15): warning CS8620: Argument of type 'I<object?>' cannot be used as an input of type 'I<object>' for parameter 'x' in 'void C.F(ref I<object> x, ref IIn<object> y, ref IOut<object> z)' due to differences in the nullability of reference types. // F(ref x, ref y, ref z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object?>", "I<object>", "x", "void C.F(ref I<object> x, ref IIn<object> y, ref IOut<object> z)").WithLocation(12, 15), // (12,22): warning CS8620: Argument of type 'IIn<object?>' cannot be used as an input of type 'IIn<object>' for parameter 'y' in 'void C.F(ref I<object> x, ref IIn<object> y, ref IOut<object> z)' due to differences in the nullability of reference types. // F(ref x, ref y, ref z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IIn<object?>", "IIn<object>", "y", "void C.F(ref I<object> x, ref IIn<object> y, ref IOut<object> z)").WithLocation(12, 22), // (12,29): warning CS8620: Argument of type 'IOut<object?>' cannot be used as an input of type 'IOut<object>' for parameter 'z' in 'void C.F(ref I<object> x, ref IIn<object> y, ref IOut<object> z)' due to differences in the nullability of reference types. // F(ref x, ref y, ref z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IOut<object?>", "IOut<object>", "z", "void C.F(ref I<object> x, ref IIn<object> y, ref IOut<object> z)").WithLocation(12, 29)); } [Fact] public void IdentityConversion_InArgument() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(in I<object> x, in IIn<object> y, in IOut<object> z) { G(in x, in y, in z); } static void G(in I<object?> x, in IIn<object?> y, in IOut<object?> z) { F(in x, in y, in z); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8620: Nullability of reference types in argument of type 'I<object>' doesn't match target type 'I<object?>' for parameter 'x' in 'void C.G(in I<object?> x, in IIn<object?> y, in IOut<object?> z)'. // G(in x, in y, in z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "x", "void C.G(in I<object?> x, in IIn<object?> y, in IOut<object?> z)").WithLocation(8, 14), // (8,20): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'y' in 'void C.G(in I<object?> x, in IIn<object?> y, in IOut<object?> z)'. // G(in x, in y, in z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IIn<object>", "IIn<object?>", "y", "void C.G(in I<object?> x, in IIn<object?> y, in IOut<object?> z)").WithLocation(8, 20), // (12,14): warning CS8620: Nullability of reference types in argument of type 'I<object?>' doesn't match target type 'I<object>' for parameter 'x' in 'void C.F(in I<object> x, in IIn<object> y, in IOut<object> z)'. // F(in x, in y, in z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object?>", "I<object>", "x", "void C.F(in I<object> x, in IIn<object> y, in IOut<object> z)").WithLocation(12, 14), // (12,26): warning CS8620: Nullability of reference types in argument of type 'IOut<object?>' doesn't match target type 'IOut<object>' for parameter 'z' in 'void C.F(in I<object> x, in IIn<object> y, in IOut<object> z)'. // F(in x, in y, in z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IOut<object?>", "IOut<object>", "z", "void C.F(in I<object> x, in IIn<object> y, in IOut<object> z)").WithLocation(12, 26)); } [Fact] public void IdentityConversion_ExtensionThis() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } static class E { static void F1(object x, object? y) { x.F1A(); y.F1A(); x.F1B(); y.F1B(); // 1 } static void F1A(this object? o) { } static void F1B(this object o) { } static void F2(I<object> x, I<object?> y) { x.F2A(); // 2 y.F2A(); x.F2B(); y.F2B(); // 3 } static void F2A(this I<object?> o) { } static void F2B(this I<object> o) { } static void F3(IIn<object> x, IIn<object?> y) { x.F3A(); // 4 y.F3A(); x.F3B(); y.F3B(); } static void F3A(this IIn<object?> o) { } static void F3B(this IIn<object> o) { } static void F4(IOut<object> x, IOut<object?> y) { x.F4A(); y.F4A(); x.F4B(); y.F4B(); // 5 } static void F4A(this IOut<object?> o) { } static void F4B(this IOut<object> o) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8604: Possible null reference argument for parameter 'o' in 'void E.F1B(object o)'. // y.F1B(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("o", "void E.F1B(object o)").WithLocation(11, 9), // (17,9): warning CS8620: Nullability of reference types in argument of type 'I<object>' doesn't match target type 'I<object?>' for parameter 'o' in 'void E.F2A(I<object?> o)'. // x.F2A(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "o", "void E.F2A(I<object?> o)").WithLocation(17, 9), // (20,9): warning CS8620: Nullability of reference types in argument of type 'I<object?>' doesn't match target type 'I<object>' for parameter 'o' in 'void E.F2B(I<object> o)'. // y.F2B(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object?>", "I<object>", "o", "void E.F2B(I<object> o)").WithLocation(20, 9), // (26,9): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'o' in 'void E.F3A(IIn<object?> o)'. // x.F3A(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("IIn<object>", "IIn<object?>", "o", "void E.F3A(IIn<object?> o)").WithLocation(26, 9), // (38,9): warning CS8620: Nullability of reference types in argument of type 'IOut<object?>' doesn't match target type 'IOut<object>' for parameter 'o' in 'void E.F4B(IOut<object> o)'. // y.F4B(); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IOut<object?>", "IOut<object>", "o", "void E.F4B(IOut<object> o)").WithLocation(38, 9)); } // https://github.com/dotnet/roslyn/issues/29899: Clone this method using types from unannotated assemblies // rather than `x!`, particularly because `x!` results in IsNullable=false rather than IsNullable=null. [Fact] public void IdentityConversion_TypeInference_IsNullableNull() { var source = @"class A<T> { } class B { static T F1<T>(T x, T y) { return x; } static void G1(object? x, object y) { F1(x, x!).ToString(); F1(x!, x).ToString(); F1(y, y!).ToString(); F1(y!, y).ToString(); } static T F2<T>(A<T> x, A<T> y) { throw new System.Exception(); } static void G(A<object?> z, A<object> w) { F2(z, z!).ToString(); F2(z!, z).ToString(); F2(w, w!).ToString(); F2(w!, w).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // F1(x, x!).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x, x!)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F1(x!, x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x!, x)").WithLocation(13, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // F2(z, z!).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(z, z!)").WithLocation(23, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // F2(z!, z).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(z!, z)").WithLocation(24, 9)); } [Fact] public void IdentityConversion_IndexerArgumentsOrder() { var source = @"interface I<T> { } class C { static object F(C c, I<string> x, I<object> y) { return c[ y: y, // warn 1 x: x]; } static object G(C c, I<string?> x, I<object?> y) { return c[ y: y, x: x]; // warn 2 } object this[I<string> x, I<object?> y] => new object(); }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,16): warning CS8620: Nullability of reference types in argument of type 'I<object>' doesn't match target type 'I<object?>' for parameter 'y' in 'object C.this[I<string> x, I<object?> y]'. // y: y, // warn 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object>", "I<object?>", "y", "object C.this[I<string> x, I<object?> y]").WithLocation(7, 16), // (14,16): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'x' in 'object C.this[I<string> x, I<object?> y]'. // x: x]; // warn 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<string?>", "I<string>", "x", "object C.this[I<string> x, I<object?> y]").WithLocation(14, 16)); } [Fact] public void IncrementOperator_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1) { CL0? u1 = ++x1; CL0 v1 = u1 ?? new CL0(); CL0 w1 = x1 ?? new CL0(); } void Test2(CL0? x2) { CL0 u2 = x2++; CL0 v2 = x2 ?? new CL0(); } void Test3(CL1? x3) { CL1 u3 = --x3; CL1 v3 = x3; } void Test4(CL1 x4) { CL1? u4 = x4--; // Result of increment is nullable, storing it in not nullable parameter. CL1 v4 = u4 ?? new CL1(); CL1 w4 = x4 ?? new CL1(); } void Test5(CL1 x5) { CL1 u5 = --x5; } void Test6(CL1 x6) { x6--; } void Test7() { CL1 x7; x7--; } } class CL0 { public static CL0 operator ++(CL0 x) { return new CL0(); } } class CL1 { public static CL1? operator --(CL1? x) { return new CL1(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,21): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator ++(CL0 x)'. // CL0? u1 = ++x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL0 CL0.operator ++(CL0 x)").WithLocation(10, 21), // (16,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator ++(CL0 x)'. // CL0 u2 = x2++; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("x", "CL0 CL0.operator ++(CL0 x)").WithLocation(16, 18), // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 u2 = x2++; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2++").WithLocation(16, 18), // (21,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u3 = --x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x3").WithLocation(21, 18), // (22,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 v3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(22, 18), // (26,19): warning CS8601: Possible null reference assignment. // CL1? u4 = x4--; // Result of increment is nullable, storing it in not nullable parameter. Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x4--").WithLocation(26, 19), // (32,18): warning CS8601: Possible null reference assignment. // CL1 u5 = --x5; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "--x5").WithLocation(32, 18), // (32,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u5 = --x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x5").WithLocation(32, 18), // (37,9): warning CS8601: Possible null reference assignment. // x6--; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x6--").WithLocation(37, 9), // (43,9): error CS0165: Use of unassigned local variable 'x7' // x7--; Diagnostic(ErrorCode.ERR_UseDefViolation, "x7").WithArguments("x7").WithLocation(43, 9), // (43,9): warning CS8601: Possible null reference assignment. // x7--; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x7--").WithLocation(43, 9) ); } [Fact] public void IncrementOperator_02() { CSharpCompilation c = CreateCompilation( new[] { @"#pragma warning disable 8618 class C { static void Main() { } void Test1() { CL0? u1 = ++x1; CL0 v1 = u1 ?? new CL0(); } void Test2() { CL0 u2 = x2++; } void Test3() { CL1 u3 = --x3; } void Test4() { CL1? u4 = x4--; // Result of increment is nullable, storing it in not nullable property. CL1 v4 = u4 ?? new CL1(); } void Test5(CL1 x5) { CL1 u5 = --x5; } CL0? x1 {get; set;} CL0? x2 {get; set;} CL1? x3 {get; set;} CL1 x4 {get; set;} CL1 x5 {get; set;} } class CL0 { public static CL0 operator ++(CL0 x) { return new CL0(); } } class CL1 { public static CL1? operator --(CL1? x) { return new CL1(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,21): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator ++(CL0 x)'. // CL0? u1 = ++x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL0 CL0.operator ++(CL0 x)").WithLocation(10, 21), // (16,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator ++(CL0 x)'. // CL0 u2 = x2++; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("x", "CL0 CL0.operator ++(CL0 x)").WithLocation(16, 18), // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 u2 = x2++; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2++").WithLocation(16, 18), // (21,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u3 = --x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x3").WithLocation(21, 18), // (26,19): warning CS8601: Possible null reference assignment. // CL1? u4 = x4--; // Result of increment is nullable, storing it in not nullable property. Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x4--").WithLocation(26, 19), // (32,18): warning CS8601: Possible null reference assignment. // CL1 u5 = --x5; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "--x5").WithLocation(32, 18), // (32,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u5 = --x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x5").WithLocation(32, 18) ); } [Fact] public void IncrementOperator_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(X1 x1) { CL0? u1 = ++x1[0]; CL0 v1 = u1 ?? new CL0(); } void Test2(X1 x2) { CL0 u2 = x2[0]++; } void Test3(X3 x3) { CL1 u3 = --x3[0]; } void Test4(X4 x4) { CL1? u4 = x4[0]--; // Result of increment is nullable, storing it in not nullable parameter. CL1 v4 = u4 ?? new CL1(); } void Test5(X4 x5) { CL1 u5 = --x5[0]; } } class CL0 { public static CL0 operator ++(CL0 x) { return new CL0(); } } class CL1 { public static CL1? operator --(CL1? x) { return new CL1(); } } class X1 { public CL0? this[int x] { get { return null; } set { } } } class X3 { public CL1? this[int x] { get { return null; } set { } } } class X4 { public CL1 this[int x] { get { return new CL1(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,21): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator ++(CL0 x)'. // CL0? u1 = ++x1[0]; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1[0]").WithArguments("x", "CL0 CL0.operator ++(CL0 x)").WithLocation(10, 21), // (16,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator ++(CL0 x)'. // CL0 u2 = x2[0]++; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2[0]").WithArguments("x", "CL0 CL0.operator ++(CL0 x)").WithLocation(16, 18), // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 u2 = x2[0]++; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2[0]++").WithLocation(16, 18), // (21,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u3 = --x3[0]; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x3[0]").WithLocation(21, 18), // (26,19): warning CS8601: Possible null reference assignment. // CL1? u4 = x4[0]--; // Result of increment is nullable, storing it in not nullable parameter. Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x4[0]--").WithLocation(26, 19), // (32,18): warning CS8601: Possible null reference assignment. // CL1 u5 = --x5[0]; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "--x5[0]").WithLocation(32, 18), // (32,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u5 = --x5[0]; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x5[0]").WithLocation(32, 18) ); } [Fact] public void IncrementOperator_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(dynamic? x1) { dynamic? u1 = ++x1; dynamic v1 = u1 ?? new object(); } void Test2(dynamic? x2) { dynamic u2 = x2++; } void Test3(dynamic? x3) { dynamic u3 = --x3; } void Test4(dynamic x4) { dynamic? u4 = x4--; dynamic v4 = u4 ?? new object(); } void Test5(dynamic x5) { dynamic u5 = --x5; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (16,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // dynamic u2 = x2++; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2++").WithLocation(16, 22), // (21,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // dynamic u3 = --x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x3").WithLocation(21, 22) ); } [Fact] public void IncrementOperator_05() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(B? x1) { B? u1 = ++x1; B v1 = u1 ?? new B(); } } class A { public static C? operator ++(A x) { return new C(); } } class C : A { public static implicit operator B(C x) { return new B(); } } class B : A { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'C? A.operator ++(A x)'. // B? u1 = ++x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "C? A.operator ++(A x)").WithLocation(10, 19), // (10,17): warning CS8604: Possible null reference argument for parameter 'x' in 'C.implicit operator B(C x)'. // B? u1 = ++x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "++x1").WithArguments("x", "C.implicit operator B(C x)").WithLocation(10, 17) ); } [Fact] public void IncrementOperator_06() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(B x1) { B u1 = ++x1; } } class A { public static C operator ++(A x) { return new C(); } } class C : A { public static implicit operator B?(C x) { return new B(); } } class B : A { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,16): warning CS8601: Possible null reference assignment. // B u1 = ++x1; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "++x1").WithLocation(10, 16), // (10,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // B u1 = ++x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "++x1").WithLocation(10, 16) ); } [Fact] public void IncrementOperator_07() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(Convertible? x1) { Convertible? u1 = ++x1; Convertible v1 = u1 ?? new Convertible(); } void Test2(int? x2) { var u2 = ++x2; } void Test3(byte x3) { var u3 = ++x3; } } class Convertible { public static implicit operator int(Convertible c) { return 0; } public static implicit operator Convertible(int i) { return new Convertible(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,29): warning CS8604: Possible null reference argument for parameter 'c' in 'Convertible.implicit operator int(Convertible c)'. // Convertible? u1 = ++x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("c", "Convertible.implicit operator int(Convertible c)").WithLocation(10, 29) ); } [Fact] public void CompoundAssignment_01() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL1? x1, CL0 y1) { CL1? u1 = x1 += y1; // 1, 2 CL1 v1 = u1 ?? new CL1(); CL1 w1 = x1 ?? new CL1(); } } class CL0 { public static CL1 operator +(CL0 x, CL0 y) { return new CL1(); } } class CL1 { public static implicit operator CL0(CL1 x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1.implicit operator CL0(CL1 x)'. // CL1? u1 = x1 += y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL1.implicit operator CL0(CL1 x)").WithLocation(10, 19) ); } [Fact] public void CompoundAssignment_02() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL1? x1, CL0? y1) { CL1? u1 = x1 += y1; // 1, 2 CL1 v1 = u1 ?? new CL1(); CL1 w1 = x1 ?? new CL1(); } } class CL0 { public static CL1 operator +(CL0 x, CL0 y) { return new CL1(); } } class CL1 { public static implicit operator CL0(CL1? x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1 CL0.operator +(CL0 x, CL0 y)'. // CL1? u1 = x1 += y1; // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL1 CL0.operator +(CL0 x, CL0 y)").WithLocation(10, 19), // (10,25): warning CS8604: Possible null reference argument for parameter 'y' in 'CL1 CL0.operator +(CL0 x, CL0 y)'. // CL1? u1 = x1 += y1; // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y1").WithArguments("y", "CL1 CL0.operator +(CL0 x, CL0 y)").WithLocation(10, 25) ); } [Fact] public void CompoundAssignment_03() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL1? x1, CL0? y1) { CL1? u1 = x1 += y1; CL1 v1 = u1 ?? new CL1(); CL1 w1 = x1 ?? new CL1(); } void Test2(CL0? x2, CL0 y2) { CL0 u2 = x2 += y2; CL0 w2 = x2; } void Test3(CL0? x3, CL0 y3) { x3 = new CL0(); CL0 u3 = x3 += y3; CL0 w3 = x3; } void Test4(CL0? x4, CL0 y4) { x4 = new CL0(); x4 += y4; CL0 w4 = x4; } } class CL0 { public static CL1 operator +(CL0 x, CL0? y) { return new CL1(); } } class CL1 { public static implicit operator CL0?(CL1? x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1 CL0.operator +(CL0 x, CL0? y)'. // CL1? u1 = x1 += y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL1 CL0.operator +(CL0 x, CL0? y)").WithLocation(10, 19), // (17,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1 CL0.operator +(CL0 x, CL0? y)'. // CL0 u2 = x2 += y2; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("x", "CL1 CL0.operator +(CL0 x, CL0? y)").WithLocation(17, 18), // (17,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 u2 = x2 += y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2 += y2").WithLocation(17, 18), // (18,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 w2 = x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(18, 18), // (24,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 u3 = x3 += y3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3 += y3").WithLocation(24, 18), // (25,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 w3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(25, 18), // (32,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 w4 = x4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x4").WithLocation(32, 18) ); } [Fact] public void CompoundAssignment_04() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL1? x1, CL0? y1) { x1 = new CL1(); CL1? u1 = x1 += y1; CL1 w1 = x1; w1 = u1; } void Test2(CL1 x2, CL0 y2) { CL1 u2 = x2 += y2; CL1 w2 = x2; } void Test3(CL1 x3, CL0 y3) { x3 += y3; } void Test4(CL0? x4, CL0 y4) { CL0? u4 = x4 += y4; CL0 v4 = u4 ?? new CL0(); CL0 w4 = x4 ?? new CL0(); } void Test5(CL0 x5, CL0 y5) { x5 += y5; } void Test6(CL0 y6) { CL1 x6; x6 += y6; } } class CL0 { public static CL1? operator +(CL0 x, CL0? y) { return new CL1(); } } class CL1 { public static implicit operator CL0(CL1 x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 w1 = x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(12, 18), // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // w1 = u1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u1").WithLocation(13, 14), // (18,18): warning CS8601: Possible null reference assignment. // CL1 u2 = x2 += y2; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x2 += y2").WithLocation(18, 18), // (18,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u2 = x2 += y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2 += y2").WithLocation(18, 18), // (19,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 w2 = x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(19, 18), // (24,9): warning CS8601: Possible null reference assignment. // x3 += y3; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x3 += y3").WithLocation(24, 9), // (29,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1? CL0.operator +(CL0 x, CL0? y)'. // CL0? u4 = x4 += y4; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x4").WithArguments("x", "CL1? CL0.operator +(CL0 x, CL0? y)").WithLocation(29, 19), // (29,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1.implicit operator CL0(CL1 x)'. // CL0? u4 = x4 += y4; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x4 += y4").WithArguments("x", "CL1.implicit operator CL0(CL1 x)").WithLocation(29, 19), // (36,9): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1.implicit operator CL0(CL1 x)'. // x5 += y5; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x5 += y5").WithArguments("x", "CL1.implicit operator CL0(CL1 x)").WithLocation(36, 9), // (42,9): error CS0165: Use of unassigned local variable 'x6' // x6 += y6; Diagnostic(ErrorCode.ERR_UseDefViolation, "x6").WithArguments("x6").WithLocation(42, 9), // (42,9): warning CS8601: Possible null reference assignment. // x6 += y6; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x6 += y6").WithLocation(42, 9)); } [Fact] public void CompoundAssignment_05() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(int x1, int y1) { var u1 = x1 += y1; } void Test2(int? x2, int y2) { var u2 = x2 += y2; } void Test3(dynamic? x3, dynamic? y3) { dynamic? u3 = x3 += y3; dynamic v3 = u3; dynamic w3 = u3 ?? v3; } void Test4(dynamic? x4, dynamic? y4) { dynamic u4 = x4 += y4; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void CompoundAssignment_06() { CSharpCompilation c = CreateCompilation( new[] { @"#pragma warning disable 8618 class Test { static void Main() { } void Test1(CL0 y1) { CL1? u1 = x1 += y1; // 1 CL1 v1 = u1 ?? new CL1(); CL1 w1 = x1 ?? new CL1(); } void Test2(CL0 y2) { CL1? u2 = x2 += y2; CL1 v2 = u2 ?? new CL1(); CL1 w2 = x2 ?? new CL1(); } CL1? x1 {get; set;} CL1 x2 {get; set;} } class CL0 { public static CL1 operator +(CL0 x, CL0 y) { return new CL1(); } } class CL1 { public static implicit operator CL0(CL1 x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1.implicit operator CL0(CL1 x)'. // CL1? u1 = x1 += y1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL1.implicit operator CL0(CL1 x)").WithLocation(10, 19) ); } [Fact] public void CompoundAssignment_07() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL2 x1, CL0 y1) { CL1? u1 = x1[0] += y1; // 1, 2 CL1 v1 = u1 ?? new CL1(); CL1 w1 = x1[0] ?? new CL1(); } void Test2(CL3 x2, CL0 y2) { CL1? u2 = x2[0] += y2; CL1 v2 = u2 ?? new CL1(); CL1 w2 = x2[0] ?? new CL1(); } } class CL0 { public static CL1 operator +(CL0 x, CL0 y) { return new CL1(); } } class CL1 { public static implicit operator CL0(CL1 x) { return new CL0(); } } class CL2 { public CL1? this[int x] { get { return new CL1(); } set { } } } class CL3 { public CL1 this[int x] { get { return new CL1(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1.implicit operator CL0(CL1 x)'. // CL1? u1 = x1[0] += y1; // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1[0]").WithArguments("x", "CL1.implicit operator CL0(CL1 x)").WithLocation(10, 19), // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1 CL0.operator +(CL0 x, CL0 y)'. // CL1? u1 = x1[0] += y1; // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1[0]").WithArguments("x", "CL1 CL0.operator +(CL0 x, CL0 y)").WithLocation(10, 19) ); } [Fact] public void IdentityConversion_CompoundAssignment() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { public static I<object> operator+(I<object> x, C y) => x; public static IIn<object> operator+(IIn<object> x, C y) => x; public static IOut<object> operator+(IOut<object> x, C y) => x; static void F(C c, I<object> x, I<object?> y) { x += c; y += c; // 1, 2, 3 } static void F(C c, IIn<object> x, IIn<object?> y) { x += c; y += c; // 4 } static void F(C c, IOut<object> x, IOut<object?> y) { x += c; y += c; // 5, 6 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // y += c; // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(12, 9), // (12,9): warning CS8620: Argument of type 'I<object?>' cannot be used for parameter 'x' of type 'I<object>' in 'I<object> C.operator +(I<object> x, C y)' due to differences in the nullability of reference types. // y += c; // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object?>", "I<object>", "x", "I<object> C.operator +(I<object> x, C y)").WithLocation(12, 9), // (12,9): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // y += c; // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y += c").WithArguments("I<object>", "I<object?>").WithLocation(12, 9), // (17,9): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // y += c; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y += c").WithArguments("IIn<object>", "IIn<object?>").WithLocation(17, 9), // (22,9): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // y += c; // 5, 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("IOut<object?>", "IOut<object>").WithLocation(22, 9), // (22,9): warning CS8620: Argument of type 'IOut<object?>' cannot be used for parameter 'x' of type 'IOut<object>' in 'IOut<object> C.operator +(IOut<object> x, C y)' due to differences in the nullability of reference types. // y += c; // 5, 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IOut<object?>", "IOut<object>", "x", "IOut<object> C.operator +(IOut<object> x, C y)").WithLocation(22, 9) ); } [Fact] public void Events_01() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } event System.Action? E1; void Test1() { E1(); } delegate void D2 (object x); event D2 E2; void Test2() { E2(null); } delegate object? D3 (); event D3 E3; void Test3() { object x3 = E3(); } void Test4() { //E1?(); System.Action? x4 = E1; //x4?(); } void Test5() { System.Action x5 = E1; } void Test6(D2? x6) { E2 = x6; } void Test7(D2? x7) { E2 += x7; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // E1(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(12, 9), // (16,14): warning CS8618: Non-nullable event 'E2' is uninitialized. Consider declaring the event as nullable. // event D2 E2; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E2").WithArguments("event", "E2").WithLocation(16, 14), // (20,12): warning CS8625: Cannot convert null literal to non-nullable reference type. // E2(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 12), // (24,14): warning CS8618: Non-nullable event 'E3' is uninitialized. Consider declaring the event as nullable. // event D3 E3; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E3").WithArguments("event", "E3").WithLocation(24, 14), // (28,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x3 = E3(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E3()").WithLocation(28, 21), // (40,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action x5 = E1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E1").WithLocation(40, 28), // (45,14): warning CS8601: Possible null reference assignment. // E2 = x6; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x6").WithLocation(45, 14) ); } // https://github.com/dotnet/roslyn/issues/29901: Events are not tracked for structs. // (This should be fixed if/when struct member state is populated lazily.) [Fact(Skip = "https://github.com/dotnet/roslyn/issues/29901")] [WorkItem(29901, "https://github.com/dotnet/roslyn/issues/29901")] public void Events_02() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } } struct TS1 { event System.Action? E1; TS1(System.Action x1) { E1 = x1; System.Action y1 = E1 ?? x1; E1 = x1; TS1 z1 = this; y1 = z1.E1 ?? x1; } void Test3(System.Action x3) { TS1 s3; s3.E1 = x3; System.Action y3 = s3.E1 ?? x3; s3.E1 = x3; TS1 z3 = s3; y3 = z3.E1 ?? x3; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } // https://github.com/dotnet/roslyn/issues/29901: Events are not tracked for structs. // (This should be fixed if/when struct member state is populated lazily.) [Fact(Skip = "https://github.com/dotnet/roslyn/issues/29901")] [WorkItem(29901, "https://github.com/dotnet/roslyn/issues/29901")] public void Events_03() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } } struct TS2 { event System.Action? E2; TS2(System.Action x2) { this = new TS2(); System.Action z2 = E2; System.Action y2 = E2 ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (16,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action z2 = E2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(16, 28) ); } [Fact] public void Events_04() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL0? x1, System.Action? y1) { System.Action v1 = x1.E1 += y1; } void Test2(CL0? x2, System.Action? y2) { System.Action v2 = x2.E1 -= y2; } } class CL0 { public event System.Action? E1; void Dummy() { var x = E1; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,28): error CS0029: Cannot implicitly convert type 'void' to 'System.Action' // System.Action v1 = x1.E1 += y1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1.E1 += y1").WithArguments("void", "System.Action").WithLocation(10, 28), // (10,28): warning CS8602: Dereference of a possibly null reference. // System.Action v1 = x1.E1 += y1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(10, 28), // (15,28): error CS0029: Cannot implicitly convert type 'void' to 'System.Action' // System.Action v2 = x2.E1 -= y2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2.E1 -= y2").WithArguments("void", "System.Action").WithLocation(15, 28), // (15,28): warning CS8602: Dereference of a possibly null reference. // System.Action v2 = x2.E1 -= y2; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(15, 28) ); } [Fact] public void Events_05() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } public event System.Action E1; void Test1(Test? x1) { System.Action v1 = x1.E1; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,32): warning CS8618: Non-nullable event 'E1' is uninitialized. Consider declaring the event as nullable. // public event System.Action E1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(8, 32), // (12,28): warning CS8602: Dereference of a possibly null reference. // System.Action v1 = x1.E1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(12, 28) ); } [Theory] [InlineData("")] [InlineData("static ")] [WorkItem(42557, "https://github.com/dotnet/roslyn/issues/42557")] public void EventAccessor_NonNullableEvent(string modifiers) { var source = @" class C { " + modifiers + @"event System.Action E1 = null!; " + modifiers + @"void M0(System.Action e2) { E1 += e2; E1.Invoke(); } " + modifiers + @"void M1() { E1 += () => { }; E1.Invoke(); } " + modifiers + @"void M2(System.Action? e2) { E1 += e2; E1.Invoke(); } " + modifiers + @"void M3() { E1 += null; E1.Invoke(); } " + modifiers + @"void M4() { E1 -= () => { }; E1.Invoke(); // 1 } " + modifiers + @"void M5(System.Action? e2) { E1 -= e2; E1.Invoke(); // 2 } " + modifiers + @"void M6() { E1 -= null; E1.Invoke(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (33,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(33, 9), // (39,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(39, 9) ); } [Theory] [InlineData("")] [InlineData("static ")] [WorkItem(42557, "https://github.com/dotnet/roslyn/issues/42557")] public void EventAccessor_NullableEvent(string modifiers) { var source = @" class C { " + modifiers + @"event System.Action? E1; " + modifiers + @"void M0(System.Action e2) { E1 += e2; E1.Invoke(); } " + modifiers + @"void M1() { E1 += () => { }; E1.Invoke(); } " + modifiers + @"void M2(System.Action? e2) { E1 += e2; E1.Invoke(); // 1 } " + modifiers + @"void M3() { E1 += null; E1.Invoke(); // 2 } " + modifiers + @"void M4() { E1 -= () => { }; E1.Invoke(); // 3 } " + modifiers + @"void M(System.Action? e2) { E1 -= e2; E1.Invoke(); // 4 } " + modifiers + @"void M() { E1 -= null; E1.Invoke(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (21,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(21, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(27, 9), // (33,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(33, 9), // (39,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(39, 9), // (45,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(45, 9) ); } [Fact] [WorkItem(42557, "https://github.com/dotnet/roslyn/issues/42557")] public void InvalidEventAssignment_01() { var source = @" using System; class C { event Action? E1; static void M1() { E1 += () => { }; E1.Invoke(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.E1' // E1 += () => { }; Diagnostic(ErrorCode.ERR_ObjectRequired, "E1").WithArguments("C.E1").WithLocation(10, 9), // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.E1' // E1.Invoke(); Diagnostic(ErrorCode.ERR_ObjectRequired, "E1").WithArguments("C.E1").WithLocation(11, 9) ); } [Fact] [WorkItem(42557, "https://github.com/dotnet/roslyn/issues/42557")] public void InvalidEventAssignment_02() { var source = @" using System; class C { public event Action? E1; } class Program { void M1(bool b) { var c = new C(); if (b) c.E1.Invoke(); c.E1 += () => { }; c.E1.Invoke(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (14,18): error CS0070: The event 'C.E1' can only appear on the left hand side of += or -= (except when used from within the type 'C') // if (b) c.E1.Invoke(); Diagnostic(ErrorCode.ERR_BadEventUsage, "E1").WithArguments("C.E1", "C").WithLocation(14, 18), // (16,11): error CS0070: The event 'C.E1' can only appear on the left hand side of += or -= (except when used from within the type 'C') // c.E1.Invoke(); Diagnostic(ErrorCode.ERR_BadEventUsage, "E1").WithArguments("C.E1", "C").WithLocation(16, 11) ); } [Fact] [WorkItem(42557, "https://github.com/dotnet/roslyn/issues/42557")] public void EventAssignment_NoMemberSlot() { var source = @" using System; class C { public event Action? E1; } class Program { C M0() => new C(); void M1() { M0().E1 += () => { }; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (6,26): warning CS0067: The event 'C.E1' is never used // public event Action? E1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("C.E1").WithLocation(6, 26) ); } [WorkItem(31018, "https://github.com/dotnet/roslyn/issues/31018")] [Fact] public void EventAssignment() { var source = @"#pragma warning disable 0067 using System; class A<T> { } class B { event Action<A<object?>> E; static void M1() { var b1 = new B(); b1.E += F1; // 1 b1.E += F2; // 2 b1.E += F3; b1.E += F4; } static void M2(Action<A<object>> f1, Action<A<object>?> f2, Action<A<object?>> f3, Action<A<object?>?> f4) { var b2 = new B(); b2.E += f1; // 3 b2.E += f2; // 4 b2.E += f3; b2.E += f4; } static void M3() { var b3 = new B(); b3.E += (A<object> a) => { }; // 5 b3.E += (A<object>? a) => { }; // 6 b3.E += (A<object?> a) => { }; b3.E += (A<object?>? a) => { }; // 7 } static void F1(A<object> a) { } static void F2(A<object>? a) { } static void F3(A<object?> a) { } static void F4(A<object?>? a) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/31018: Report warnings for // 3 and // 4. comp.VerifyDiagnostics( // (6,30): warning CS8618: Non-nullable event 'E' is uninitialized. Consider declaring the event as nullable. // event Action<A<object?>> E; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E").WithArguments("event", "E").WithLocation(6, 30), // (10,17): warning CS8622: Nullability of reference types in type of parameter 'a' of 'void B.F1(A<object> a)' doesn't match the target delegate 'Action<A<object?>>'. // b1.E += F1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F1").WithArguments("a", "void B.F1(A<object> a)", "System.Action<A<object?>>").WithLocation(10, 17), // (11,17): warning CS8622: Nullability of reference types in type of parameter 'a' of 'void B.F2(A<object>? a)' doesn't match the target delegate 'Action<A<object?>>'. // b1.E += F2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F2").WithArguments("a", "void B.F2(A<object>? a)", "System.Action<A<object?>>").WithLocation(11, 17), // (26,17): warning CS8622: Nullability of reference types in type of parameter 'a' of 'lambda expression' doesn't match the target delegate 'Action<A<object?>>'. // b3.E += (A<object> a) => { }; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(A<object> a) => { }").WithArguments("a", "lambda expression", "System.Action<A<object?>>").WithLocation(26, 17), // (27,17): warning CS8622: Nullability of reference types in type of parameter 'a' of 'lambda expression' doesn't match the target delegate 'Action<A<object?>>'. // b3.E += (A<object>? a) => { }; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(A<object>? a) => { }").WithArguments("a", "lambda expression", "System.Action<A<object?>>").WithLocation(27, 17), // (29,17): warning CS8622: Nullability of reference types in type of parameter 'a' of 'lambda expression' doesn't match the target delegate 'Action<A<object?>>'. // b3.E += (A<object?>? a) => { }; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(A<object?>? a) => { }").WithArguments("a", "lambda expression", "System.Action<A<object?>>").WithLocation(29, 17)); } [Fact] public void AsOperator_01() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL1 x1) { object y1 = x1 as object ?? new object(); } void Test2(int x2) { object y2 = x2 as object ?? new object(); } void Test3(CL1? x3) { object y3 = x3 as object; } void Test4(int? x4) { object y4 = x4 as object; } void Test5(object x5) { CL1 y5 = x5 as CL1; } void Test6() { CL1 y6 = null as CL1; } void Test7<T>(T x7) { CL1 y7 = x7 as CL1; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (20,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y3 = x3 as object; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3 as object").WithLocation(20, 21), // (25,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y4 = x4 as object; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x4 as object").WithLocation(25, 21), // (30,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 y5 = x5 as CL1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5 as CL1").WithLocation(30, 18), // (35,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 y6 = null as CL1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null as CL1").WithLocation(35, 18), // (40,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 y7 = x7 as CL1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x7 as CL1").WithLocation(40, 18) ); } [Fact] public void ReturningValues_IEnumerableT() { var source = @" public class C { System.Collections.Generic.IEnumerable<string> M() { return null; // 1 } public System.Collections.Generic.IEnumerable<string>? M2() { return null; } System.Collections.Generic.IEnumerable<string> M3() => null; // 2 System.Collections.Generic.IEnumerable<string>? M4() => null; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,16): warning CS8603: Possible null reference return. // return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 16), // (12,60): warning CS8603: Possible null reference return. // System.Collections.Generic.IEnumerable<string> M3() => null; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(12, 60) ); var source2 = @" class D { void M(C c) { c.M2() /*T:System.Collections.Generic.IEnumerable<string!>?*/ ; } } "; var comp2 = CreateCompilation(source2, references: new[] { comp.EmitToImageReference() }, options: WithNullableEnable()); comp2.VerifyTypes(); } [Fact] public void Yield_IEnumerableT() { var source = @" public class C { public System.Collections.Generic.IEnumerable<string> M() { yield return null; // 1 yield return """"; yield return null; // 2 yield break; } public System.Collections.Generic.IEnumerable<string?> M2() { yield return null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,22): warning CS8603: Possible null reference return. // yield return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 22), // (8,22): warning CS8603: Possible null reference return. // yield return null; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 22) ); var source2 = @" class D { void M(C c) { c.M() /*T:System.Collections.Generic.IEnumerable<string!>!*/ ; c.M2() /*T:System.Collections.Generic.IEnumerable<string?>!*/ ; } } "; var comp2 = CreateCompilation(source2, references: new[] { comp.EmitToImageReference() }, options: WithNullableEnable()); comp2.VerifyTypes(); } [Fact] public void Yield_IEnumerableT_LocalFunction() { var source = @" class C { void Method() { _ = M(); _ = M2(); System.Collections.Generic.IEnumerable<string> M() { yield return null; // 1 yield return """"; yield return null; // 2 yield break; } System.Collections.Generic.IEnumerable<string?> M2() { yield return null; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,26): warning CS8603: Possible null reference return. // yield return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(11, 26), // (13,26): warning CS8603: Possible null reference return. // yield return null; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(13, 26) ); } [Fact] public void Yield_IEnumerableT_GenericT() { var source = @" class C { System.Collections.Generic.IEnumerable<T> M<T>() { yield return default; // 1 } System.Collections.Generic.IEnumerable<T> M1<T>() where T : class { yield return default; // 2 } System.Collections.Generic.IEnumerable<T> M2<T>() where T : class? { yield return default; // 3 } System.Collections.Generic.IEnumerable<T?> M3<T>() where T : class { yield return default; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (6,22): warning CS8603: Possible null reference return. // yield return default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(6, 22), // (10,22): warning CS8603: Possible null reference return. // yield return default; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(10, 22), // (14,22): warning CS8603: Possible null reference return. // yield return default; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(14, 22) ); } [Fact] public void Yield_IEnumerableT_ErrorValue() { var source = @" class C { System.Collections.Generic.IEnumerable<string> M() { yield return bad; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (6,22): error CS0103: The name 'bad' does not exist in the current context // yield return bad; Diagnostic(ErrorCode.ERR_NameNotInContext, "bad").WithArguments("bad").WithLocation(6, 22) ); } [Fact] public void Yield_IEnumerableT_ErrorValue2() { var source = @" static class C { static System.Collections.Generic.IEnumerable<object> M(object? x) { yield return (C)x; } static System.Collections.Generic.IEnumerable<object?> M(object? y) { yield return (C?)y; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (6,22): error CS0716: Cannot convert to static type 'C' // yield return (C)x; Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)x").WithArguments("C").WithLocation(6, 22), // (6,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // yield return (C)x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)x").WithLocation(6, 22), // (8,60): error CS0111: Type 'C' already defines a member called 'M' with the same parameter types // static System.Collections.Generic.IEnumerable<object?> M(object? y) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "C").WithLocation(8, 60), // (10,22): error CS0716: Cannot convert to static type 'C' // yield return (C?)y; Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C?)y").WithArguments("C").WithLocation(10, 22) ); } [Fact] public void Yield_IEnumerableT_NoValue() { var source = @" class C { System.Collections.Generic.IEnumerable<string> M() { yield return; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (6,15): error CS1627: Expression expected after yield return // yield return; Diagnostic(ErrorCode.ERR_EmptyYield, "return").WithLocation(6, 15) ); } [Fact] public void Yield_IEnumeratorT() { var source = @" class C { System.Collections.Generic.IEnumerator<string> M() { yield return null; // 1 yield return """"; } System.Collections.Generic.IEnumerator<string?> M2() { yield return null; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (6,22): warning CS8603: Possible null reference return. // yield return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 22) ); } [Fact] public void Yield_IEnumeratorT_LocalFunction() { var source = @" class C { void Method() { _ = M(); _ = M2(); System.Collections.Generic.IEnumerator<string> M() { yield return null; // 1 yield return """"; } System.Collections.Generic.IEnumerator<string?> M2() { yield return null; } } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (11,26): warning CS8603: Possible null reference return. // yield return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(11, 26) ); } [Fact] public void Yield_IEnumerable() { var source = @" class C { System.Collections.IEnumerable M() { yield return null; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void Yield_IEnumerator() { var source = @" class C { System.Collections.IEnumerator M() { yield return null; yield return null; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact, CompilerTrait(CompilerFeature.AsyncStreams)] public void Yield_IAsyncEnumerable() { var source = @" using System.Collections.Generic; using System.Threading.Tasks; class C { public static async IAsyncEnumerable<string> M() { yield return null; // 1 yield return null; // 2 await Task.Delay(1); yield break; } public static async IAsyncEnumerable<string?> M2() { yield return null; yield return null; await Task.Delay(1); } void Method() { _ = local(); _ = local2(); async IAsyncEnumerable<string> local() { yield return null; // 3 await Task.Delay(1); yield break; } async IAsyncEnumerable<string?> local2() { yield return null; await Task.Delay(1); } } }"; CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, options: WithNullableEnable()).VerifyDiagnostics( // (8,22): warning CS8603: Possible null reference return. // yield return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 22), // (9,22): warning CS8603: Possible null reference return. // yield return null; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(9, 22), // (26,26): warning CS8603: Possible null reference return. // yield return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(26, 26) ); } [Fact, CompilerTrait(CompilerFeature.AsyncStreams)] public void Yield_IAsyncEnumerator() { var source = @" using System.Collections.Generic; using System.Threading.Tasks; class C { async IAsyncEnumerator<string> M() { yield return null; // 1 yield return null; // 2 await Task.Delay(1); yield break; } async IAsyncEnumerator<string?> M2() { yield return null; yield return null; await Task.Delay(1); } void Method() { _ = local(); _ = local2(); async IAsyncEnumerator<string> local() { yield return null; // 3 await Task.Delay(1); } async IAsyncEnumerator<string?> local2() { yield return null; await Task.Delay(1); yield break; } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,22): warning CS8603: Possible null reference return. // yield return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 22), // (9,22): warning CS8603: Possible null reference return. // yield return null; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(9, 22), // (26,26): warning CS8603: Possible null reference return. // yield return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(26, 26) ); } [Fact] public void Await_01() { var source = @" using System; static class Program { static void Main() { } static async void f() { object x = await new D() ?? new object(); } } class D { public Awaiter GetAwaiter() { return new Awaiter(); } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public object GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void Await_02() { var source = @" using System; static class Program { static void Main() { } static async void f() { object x = await new D(); } } class D { public Awaiter GetAwaiter() { return new Awaiter(); } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public object? GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (10,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = await new D(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "await new D()").WithLocation(10, 20) ); } [Fact] public void Await_03() { var source = @"using System.Threading.Tasks; class Program { async void M(Task? x, Task? y) { if (y == null) return; await x; // 1 await y; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // await x; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 15)); } [Fact] public void Await_ProduceResultTypeFromTask() { var source = @" class C { async void M() { var x = await Async(); x.ToString(); } System.Threading.Tasks.Task<string?> Async() => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void Await_CheckNullReceiver() { var source = @" class C { async void M() { await Async(); } System.Threading.Tasks.Task<string>? Async() => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,15): warning CS8602: Dereference of a possibly null reference. // await Async(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Async()").WithLocation(6, 15) ); } [Fact] public void Await_ExtensionGetAwaiter() { var source = @" public class Awaitable { async void M() { await Async(); } Awaitable? Async() => throw null!; } public static class Extensions { public static System.Runtime.CompilerServices.TaskAwaiter GetAwaiter(this Awaitable? x) => throw null!; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Await_UpdateExpression() { var source = @" class C { async void M(System.Threading.Tasks.Task<string>? task) { await task; // warn await task; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,15): warning CS8602: Dereference of a possibly null reference. // await task; // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "task").WithLocation(6, 15) ); } [Fact] public void Await_LearnFromNullTest() { var source = @" class C { System.Threading.Tasks.Task<string>? M() => throw null!; async System.Threading.Tasks.Task M2(C? c) { await c?.M(); // warn c.ToString(); // no cascade } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // await c?.M(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c?.M()").WithLocation(7, 15) ); } [Fact, WorkItem(40452, "https://github.com/dotnet/roslyn/issues/40452")] public void Await_CallInferredTypeArgs_01() { var source = @" using System.Threading.Tasks; class C { Task<T> M1<T>(T item) => throw null!; async Task M2(object? obj) { var task = M1(obj); task.Result.ToString(); // 1 (await task).ToString(); // 2 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // task.Result.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "task.Result").WithLocation(11, 9), // (12,10): warning CS8602: Dereference of a possibly null reference. // (await task).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "await task").WithLocation(12, 10)); } [Fact, WorkItem(40452, "https://github.com/dotnet/roslyn/issues/40452")] public void Await_CallInferredTypeArgs_02() { var source = @" using System.Threading.Tasks; class C { static async Task Main() { object? thisIsNull = await Task.Run(GetNull); thisIsNull.ToString(); // 1 } static object? GetNull() => null; } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // thisIsNull.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "thisIsNull").WithLocation(9, 9)); } [Fact] public void ArrayAccess_LearnFromNullTest() { var source = @" class C { string[] field = null!; void M2(C? c) { _ = (c?.field)[0]; // warn c.ToString(); // no cascade } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,14): warning CS8602: Dereference of a possibly null reference. // _ = (c?.field)[0]; // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c?.field").WithLocation(7, 14) ); } [Fact] public void Call_LambdaConsidersNonFinalState() { var source = @" using System; class C { void M(string? maybeNull1, string? maybeNull2, string? maybeNull3) { M1(() => maybeNull1.Length); // 1 M2(() => maybeNull2.Length, maybeNull2 = """"); // 2 M3(maybeNull3 = """", () => maybeNull3.Length); } void M1<T>(Func<T> lambda) => throw null!; void M1(Func<string> lambda) => throw null!; void M2<T>(Func<T> lambda, object o) => throw null!; void M3<T>(object o, Func<T> lambda) => throw null!; }"; var comp = CreateNullableCompilation(new[] { source }); comp.VerifyDiagnostics( // (7,18): warning CS8602: Dereference of a possibly null reference. // M1(() => maybeNull1.Length); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "maybeNull1").WithLocation(7, 18), // (8,18): warning CS8602: Dereference of a possibly null reference. // M2(() => maybeNull2.Length, maybeNull2 = ""); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "maybeNull2").WithLocation(8, 18) ); } [Fact] public void Call_LearnFromNullTest() { var source = @" class C { string M() => throw null!; C field = null!; void M2(C? c) { _ = (c?.field).M(); // warn c.ToString(); // no cascade } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8602: Dereference of a possibly null reference. // _ = (c?.field).M(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c?.field").WithLocation(8, 14) ); } [Fact, WorkItem(36132, "https://github.com/dotnet/roslyn/issues/36132")] public void Call_MethodTypeInferenceUsesNullabilitiesOfConvertedTypes() { var source = @" class A { } class B { public static implicit operator A(B? b) => new A(); } class C { void Test1(A a, B? b) { A t1 = M<A>(a, b); } void Test2(A a, B? b) { A t2 = M(a, b); // unexpected } T M<T>(T t1, T t2) => t2; }"; var comp = CreateNullableCompilation(source); // There should be no diagnostic. See https://github.com/dotnet/roslyn/issues/36132 comp.VerifyDiagnostics( // (14,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // A t2 = M(a, b); // unexpected Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M(a, b)").WithLocation(14, 16) ); } [Fact] public void Indexer_LearnFromNullTest() { var source = @" class C { string this[int i] => throw null!; C field = null!; void M(C? c) { _ = (c?.field)[0]; // warn c.ToString(); // no cascade } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8602: Dereference of a possibly null reference. // _ = (c?.field)[0]; // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c?.field").WithLocation(8, 14) ); } [Fact] public void MemberAccess_LearnFromNullTest() { var source = @" class C { string this[int i] => throw null!; C field = null!; void M(C? c) { _ = (c?.field).field; // warn c.ToString(); // no cascade } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8602: Dereference of a possibly null reference. // _ = (c?.field).field; // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c?.field").WithLocation(8, 14) ); } [Theory, WorkItem(31906, "https://github.com/dotnet/roslyn/issues/31906")] [InlineData("==")] [InlineData(">")] [InlineData("<")] [InlineData(">=")] [InlineData("<=")] public void LearnFromNullTest_FromOperatorOnConstant(string op) { var source = @" class C { static void F(string? s, string? s2) { if (s?.Length OPERATOR 1) s.ToString(); else s.ToString(); // 1 if (1 OPERATOR s2?.Length) s2.ToString(); else s2.ToString(); // 2 } }"; var comp = CreateCompilation(source.Replace("OPERATOR", op), options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(14, 13) ); } [Fact] public void LearnFromNullTest_IncludingConstants() { var source = @" class C { void F() { const string s1 = """"; if (s1 == null) s1.ToString(); // 1 if (null == s1) s1.ToString(); // 2 if (s1 != null) s1.ToString(); else s1.ToString(); // 3 if (null != s1) s1.ToString(); else s1.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS0162: Unreachable code detected // s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_UnreachableCode, "s1").WithLocation(8, 13), // (11,13): warning CS0162: Unreachable code detected // s1.ToString(); // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "s1").WithLocation(11, 13), // (16,13): warning CS0162: Unreachable code detected // s1.ToString(); // 3 Diagnostic(ErrorCode.WRN_UnreachableCode, "s1").WithLocation(16, 13), // (21,13): warning CS0162: Unreachable code detected // s1.ToString(); // 4 Diagnostic(ErrorCode.WRN_UnreachableCode, "s1").WithLocation(21, 13) ); } [Fact, WorkItem(31906, "https://github.com/dotnet/roslyn/issues/31906")] public void LearnFromNullTest_NotEqualsConstant() { var source = @" class C { static void F(string? s, string? s2) { if (s?.Length != 1) s.ToString(); // 1 else s.ToString(); if (1 != s2?.Length) s2.ToString(); // 2 else s2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 13) ); } [Fact, WorkItem(31906, "https://github.com/dotnet/roslyn/issues/31906")] public void LearnFromNullTest_FromIsConstant() { var source = @" class C { static void F(string? s) { if (s?.Length is 1) s.ToString(); else s.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NoPiaObjectCreation_01() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(ClassITest28))] public interface ITest28 { } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest28 //: ITest28 { public ClassITest28(int x){} } "; var piaCompilation = CreateCompilationWithMscorlib45(pia, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CompileAndVerify(piaCompilation); string source = @" class UsePia { public static void Main() { } void Test1(ITest28 x1) { x1 = new ITest28(); } void Test2(ITest28 x2) { x2 = new ITest28() ?? x2; } }"; var compilation = CreateCompilationWithMscorlib45(new[] { source }, new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) }, options: WithNullableEnable(TestOptions.DebugExe)); compilation.VerifyDiagnostics( ); } [Fact] public void SymbolDisplay_01() { var source = @" abstract class B { string? F1; event System.Action? E1; string? P1 {get; set;} string?[][,] P2 {get; set;} System.Action<string?> M1(string? x) {return null;} string[]?[,] M2(string[][,]? x) {return null;} void M3(string?* x) {} public abstract string? this[System.Action? x] {get; set;} public static implicit operator B?(int x) { return null; } } delegate string? D1(); delegate string D2(); interface I1<T>{} interface I2<T>{} class C<T> {} class F : C<F?>, I1<C<B?>>, I2<C<B>?> {} "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); var b = compilation.GetTypeByMetadataName("B"); Assert.Equal("System.String? B.F1", b.GetMember("F1").ToTestDisplayString()); Assert.Equal("event System.Action? B.E1", b.GetMember("E1").ToTestDisplayString()); Assert.Equal("System.String? B.P1 { get; set; }", b.GetMember("P1").ToTestDisplayString()); Assert.Equal("System.String?[][,] B.P2 { get; set; }", b.GetMember("P2").ToTestDisplayString()); Assert.Equal("System.Action<System.String?> B.M1(System.String? x)", b.GetMember("M1").ToTestDisplayString()); Assert.Equal("System.String[]?[,] B.M2(System.String[][,]? x)", b.GetMember("M2").ToTestDisplayString()); Assert.Equal("void B.M3(System.String?* x)", b.GetMember("M3").ToTestDisplayString()); Assert.Equal("System.String? B.this[System.Action? x] { get; set; }", b.GetMember("this[]").ToTestDisplayString()); Assert.Equal("B.implicit operator B?(int)", b.GetMember("op_Implicit").ToDisplayString()); Assert.Equal("String? D1()", compilation.GetTypeByMetadataName("D1") .ToDisplayString(new SymbolDisplayFormat(delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier))); Assert.Equal("String D1()", compilation.GetTypeByMetadataName("D1") .ToDisplayString(new SymbolDisplayFormat(delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); Assert.Equal("String! D2()", compilation.GetTypeByMetadataName("D2") .ToDisplayString(new SymbolDisplayFormat(delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); var f = compilation.GetTypeByMetadataName("F"); Assert.Equal("C<F?>", f.BaseType().ToTestDisplayString()); Assert.Equal("I1<C<B?>>", f.Interfaces()[0].ToTestDisplayString()); Assert.Equal("I2<C<B>?>", f.Interfaces()[1].ToTestDisplayString()); } [Fact] public void NullableAttribute_01() { var source = @"#pragma warning disable 8618 public abstract class B { public string? F1; public event System.Action? E1; public string? P1 {get; set;} public string?[][,] P2 {get; set;} public System.Action<string?> M1(string? x) {throw new System.NotImplementedException();} public string[]?[,] M2(string[][,]? x) {throw new System.NotImplementedException();} public abstract string? this[System.Action? x] {get; set;} public static implicit operator B?(int x) {throw new System.NotImplementedException();} public event System.Action? E2 { add { } remove { } } } public delegate string? D1(); public interface I1<T>{} public interface I2<T>{} public class C<T> {} public class F : C<F?>, I1<C<B?>>, I2<C<B>?> {} "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (5,33): warning CS0067: The event 'B.E1' is never used // public event System.Action? E1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("B.E1").WithLocation(5, 33) ); CompileAndVerify(compilation, symbolValidator: m => { var b = ((PEModuleSymbol)m).GlobalNamespace.GetTypeMember("B"); Assert.Equal("System.String? B.F1", b.GetMember("F1").ToTestDisplayString()); Assert.Equal("event System.Action? B.E1", b.GetMember("E1").ToTestDisplayString()); Assert.Equal("System.String? B.P1 { get; set; }", b.GetMember("P1").ToTestDisplayString()); Assert.Equal("System.String?[][,] B.P2 { get; set; }", b.GetMember("P2").ToTestDisplayString()); Assert.Equal("System.Action<System.String?> B.M1(System.String? x)", b.GetMember("M1").ToTestDisplayString()); Assert.Equal("System.String[]?[,] B.M2(System.String[][,]? x)", b.GetMember("M2").ToTestDisplayString()); Assert.Equal("System.String? B.this[System.Action? x] { get; set; }", b.GetMember("this[]").ToTestDisplayString()); Assert.Equal("B.implicit operator B?(int)", b.GetMember("op_Implicit").ToDisplayString()); Assert.Equal("event System.Action? B.E2", b.GetMember("E2").ToTestDisplayString()); Assert.Equal("String? D1()", compilation.GetTypeByMetadataName("D1") .ToDisplayString(new SymbolDisplayFormat(delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier))); var f = ((PEModuleSymbol)m).GlobalNamespace.GetTypeMember("F"); Assert.Equal("C<F?>", f.BaseType().ToTestDisplayString()); Assert.Equal("I1<C<B?>>", f.Interfaces()[0].ToTestDisplayString()); Assert.Equal("I2<C<B>?>", f.Interfaces()[1].ToTestDisplayString()); }); } [Fact] public void NullableAttribute_02() { CSharpCompilation c0 = CreateCompilation(new[] { @" public class CL0 { public object F1; public object? P1 { get; set;} } " }, options: WithNullableEnable(TestOptions.DebugDll)); string source = @" class C { static void Main() { } void Test1(CL0 x1, object? y1) { x1.F1 = y1; } void Test2(CL0 x2, object y2) { y2 = x2.P1; } } "; var expected = new[] { // (10,17): warning CS8601: Possible null reference assignment. // x1.F1 = y1; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y1").WithLocation(10, 17), // (15,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y2 = x2.P1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2.P1").WithLocation(15, 14) }; CSharpCompilation c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics(expected); c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { c0.ToMetadataReference() }); c.VerifyDiagnostics(expected); } [Fact] public void NullableAttribute_03() { CSharpCompilation c0 = CreateCompilation(new[] { @" public class CL0 { public object F1; } " }, options: WithNullableEnable(TestOptions.DebugDll)); string source = @" class C { static void Main() { } void Test1(CL0 x1, object? y1) { x1.F1 = y1; } } "; var expected = new[] { // (10,17): warning CS8601: Possible null reference assignment. // x1.F1 = y1; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y1").WithLocation(10, 17) }; CSharpCompilation c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics(expected); c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { c0.ToMetadataReference() }); c.VerifyDiagnostics(expected); } [Fact] public void NullableAttribute_04() { var source = @"#pragma warning disable 8618 using System.Runtime.CompilerServices; public abstract class B { [Nullable(0)] public string F1; [Nullable(1)] public event System.Action E1; [Nullable(2)] public string[][,] P2 {get; set;} [return:Nullable(0)] public System.Action<string?> M1(string? x) {throw new System.NotImplementedException();} public string[][,] M2([Nullable(new byte[] {0})] string[][,] x) {throw new System.NotImplementedException();} } public class C<T> {} [Nullable(2)] public class F : C<F> {} "; var compilation = CreateCompilation(new[] { source, NullableAttributeDefinition }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (7,6): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // [Nullable(1)] public event System.Action E1; Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(1)").WithLocation(7, 6), // (8,6): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // [Nullable(2)] public string[][,] P2 {get; set;} Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(2)").WithLocation(8, 6), // (9,13): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // [return:Nullable(0)] public System.Action<string?> M1(string? x) Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(0)").WithLocation(9, 13), // (11,28): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // public string[][,] M2([Nullable(new byte[] {0})] string[][,] x) Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(new byte[] {0})").WithLocation(11, 28), // (6,6): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // [Nullable(0)] public string F1; Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(0)").WithLocation(6, 6), // (17,2): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // [Nullable(2)] public class F : C<F> Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(2)").WithLocation(17, 2), // (7,46): warning CS0067: The event 'B.E1' is never used // [Nullable(1)] public event System.Action E1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("B.E1").WithLocation(7, 46) ); } [Fact] public void NonNullTypes_02() { string lib = @" using System; #nullable disable public class CL0 { #nullable disable public class CL1 { #nullable enable #pragma warning disable 8618 public Action F1; #nullable enable #pragma warning disable 8618 public Action? F2; #nullable enable #pragma warning disable 8618 public Action P1 { get; set; } #nullable enable public Action? P2 { get; set; } #nullable enable public Action M1() { throw new System.NotImplementedException(); } #nullable enable public Action? M2() { return null; } #nullable enable public void M3(Action x3) {} } } "; string source1 = @"#pragma warning disable 8618 using System; partial class C { partial class B { #nullable enable public event Action E1; #nullable enable public event Action? E2; #nullable enable void Test11(Action? x11) { E1 = x11; } #nullable enable void Test12(Action x12) { x12 = E1 ?? x12; } #nullable enable void Test13(Action x13) { x13 = E2; } } } "; string source2 = @"#pragma warning disable 8618 using System; #nullable disable partial class C { #nullable disable partial class B { #nullable enable void Test21(CL0.CL1 c, Action? x21) { c.F1 = x21; c.P1 = x21; c.M3(x21); } #nullable enable void Test22(CL0.CL1 c, Action x22) { x22 = c.F1 ?? x22; x22 = c.P1 ?? x22; x22 = c.M1() ?? x22; } #nullable enable void Test23(CL0.CL1 c, Action x23) { x23 = c.F2; x23 = c.P2; x23 = c.M2(); } } } "; CSharpCompilation c = CreateCompilation(new[] { lib, source1, source2 }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c.VerifyDiagnostics( // (18,18): warning CS8601: Possible null reference assignment. // E1 = x11; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x11").WithLocation(18, 18), // (30,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x13 = E2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(30, 19), // (13,20): warning CS8601: Possible null reference assignment. // c.F1 = x21; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(13, 20), // (14,20): warning CS8601: Possible null reference assignment. // c.P1 = x21; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(14, 20), // (15,18): warning CS8604: Possible null reference argument for parameter 'x3' in 'void CL1.M3(Action x3)'. // c.M3(x21); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x21").WithArguments("x3", "void CL1.M3(Action x3)").WithLocation(15, 18), // (29,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F2").WithLocation(29, 19), // (30,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.P2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P2").WithLocation(30, 19), // (31,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M2()").WithLocation(31, 19) ); CSharpCompilation c1 = CreateCompilation(new[] { lib }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c1.VerifyDiagnostics(); var expected = new[] { // (13,20): warning CS8601: Possible null reference assignment. // c.F1 = x21; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(13, 20), // (14,20): warning CS8601: Possible null reference assignment. // c.P1 = x21; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(14, 20), // (15,18): warning CS8604: Possible null reference argument for parameter 'x3' in 'void CL1.M3(Action x3)'. // c.M3(x21); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x21").WithArguments("x3", "void CL1.M3(Action x3)").WithLocation(15, 18), // (29,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F2").WithLocation(29, 19), // (30,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.P2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P2").WithLocation(30, 19), // (31,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M2()").WithLocation(31, 19) }; c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c.VerifyDiagnostics(expected); c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c.VerifyDiagnostics(expected); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypes_03() { string lib = @" using System; public class CL0 { public class CL1 { #nullable enable public Action F1 = null!; #nullable enable public Action? F2; #nullable enable public Action P1 { get; set; } = null!; #nullable enable public Action? P2 { get; set; } #nullable enable public Action M1() { throw new System.NotImplementedException(); } #nullable enable public Action? M2() { return null; } #nullable enable public void M3(Action x3) {} } } "; string source1 = @" using System; partial class C { partial class B { #nullable enable public event Action E1; #nullable enable public event Action? E2; #nullable disable void Test11(Action? x11) // 1 { E1 = x11; // 2 } void Test12(Action x12) { x12 = E1 ?? x12; // 3 } void Test13(Action x13) { x13 = E2; } } } "; string source2 = @" using System; partial class C { partial class B { void Test21(CL0.CL1 c, Action? x21) // 4 { c.F1 = x21; // 5 c.P1 = x21; // 6 c.M3(x21); // 7 } void Test22(CL0.CL1 c, Action x22) { x22 = c.F1 ?? x22; // 8 x22 = c.P1 ?? x22; // 9 x22 = c.M1() ?? x22; // 10 } void Test23(CL0.CL1 c, Action x23) { x23 = c.F2; x23 = c.P2; x23 = c.M2(); } } } "; CSharpCompilation c = CreateCompilation(new[] { lib, source1, source2 }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c.VerifyDiagnostics( // (15,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void Test11(Action? x11) // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(15, 27), // (8,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void Test21(CL0.CL1 c, Action? x21) // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 38), // (11,29): warning CS8618: Non-nullable event 'E1' is uninitialized. Consider declaring the event as nullable. // public event Action E1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(11, 29) ); CSharpCompilation c1 = CreateCompilation(new[] { lib }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c1.VerifyDiagnostics(); var expectedDiagnostics = new[] { // (8,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Test21(CL0.CL1 c, Action? x21) // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 38) }; c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c.VerifyDiagnostics(expectedDiagnostics); c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c.VerifyDiagnostics(expectedDiagnostics); expectedDiagnostics = new[] { // (10,20): warning CS8601: Possible null reference assignment. // c.F1 = x21; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(10, 20), // (11,20): warning CS8601: Possible null reference assignment. // c.P1 = x21; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(11, 20), // (12,18): warning CS8604: Possible null reference argument for parameter 'x3' in 'void CL1.M3(Action x3)'. // c.M3(x21); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x21").WithArguments("x3", "void CL1.M3(Action x3)").WithLocation(12, 18), // (24,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F2").WithLocation(24, 19), // (25,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.P2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P2").WithLocation(25, 19), // (26,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M2()").WithLocation(26, 19) }; c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics(expectedDiagnostics); c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypes_04() { string lib = @" using System; #nullable disable public class CL0 { public class CL1 { #nullable enable public Action F1 = null!; #nullable enable public Action? F2; #nullable enable public Action P1 { get; set; } = null!; #nullable enable public Action? P2 { get; set; } #nullable enable public Action M1() { throw new System.NotImplementedException(); } #nullable enable public Action? M2() { return null; } #nullable enable public void M3(Action x3) {} } } "; string source1 = @" using System; partial class C { partial class B { #nullable enable public event Action E1; #nullable enable public event Action? E2; void Test11(Action? x11) // 1 { E1 = x11; // 2 } void Test12(Action x12) { x12 = E1 ?? x12; // 3 } void Test13(Action x13) { x13 = E2; } } } "; string source2 = @" using System; #nullable disable partial class C { partial class B { void Test21(CL0.CL1 c, Action? x21) // 4 { c.F1 = x21; // 5 c.P1 = x21; // 6 c.M3(x21); // 7 } void Test22(CL0.CL1 c, Action x22) { x22 = c.F1 ?? x22; // 8 x22 = c.P1 ?? x22; // 9 x22 = c.M1() ?? x22; // 10 } void Test23(CL0.CL1 c, Action x23) { x23 = c.F2; x23 = c.P2; x23 = c.M2(); } } } "; CSharpCompilation c = CreateCompilation(new[] { lib, source1, source2 }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,29): warning CS8618: Non-nullable event 'E1' is uninitialized. Consider declaring the event as nullable. // public event Action E1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(9, 29), // (9,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void Test21(CL0.CL1 c, Action? x21) // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 38), // (15,18): warning CS8601: Possible null reference assignment. // E1 = x11; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x11").WithLocation(15, 18), // (25,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x13 = E2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(25, 19) ); CSharpCompilation c1 = CreateCompilation(new[] { lib }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c1.VerifyDiagnostics(); var expected = new[] { // (9,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Test21(CL0.CL1 c, Action? x21) // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 38) }; c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics(expected); c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics(expected); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypes_05() { string lib = @" using System; #nullable enable public class CL0 { #nullable disable public class CL1 { #nullable enable public Action F1 = null!; #nullable enable public Action? F2; #nullable enable public Action P1 { get; set; } = null!; #nullable enable public Action? P2 { get; set; } #nullable enable public Action M1() { throw new System.NotImplementedException(); } #nullable enable public Action? M2() { return null; } #nullable enable public void M3(Action x3) {} } } "; string source1 = @" using System; partial class C { partial class B { #nullable enable public event Action E1; #nullable enable public event Action? E2; void Test11(Action? x11) // 1 { E1 = x11; // 2 } void Test12(Action x12) { x12 = E1 ?? x12; // 3 } void Test13(Action x13) { x13 = E2; } } } "; string source2 = @" using System; #nullable enable partial class C { #nullable disable partial class B { void Test21(CL0.CL1 c, Action? x21) // 4 { c.F1 = x21; // 5 c.P1 = x21; // 6 c.M3(x21); // 7 } void Test22(CL0.CL1 c, Action x22) { x22 = c.F1 ?? x22; // 8 x22 = c.P1 ?? x22; // 9 x22 = c.M1() ?? x22; // 10 } void Test23(CL0.CL1 c, Action x23) { x23 = c.F2; x23 = c.P2; x23 = c.M2(); } } } "; CSharpCompilation c = CreateCompilation(new[] { lib, source1, source2 }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,29): warning CS8618: Non-nullable event 'E1' is uninitialized. Consider declaring the event as nullable. // public event Action E1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(9, 29), // (10,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void Test21(CL0.CL1 c, Action? x21) // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 38), // (15,18): warning CS8601: Possible null reference assignment. // E1 = x11; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x11").WithLocation(15, 18), // (25,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x13 = E2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(25, 19) ); CSharpCompilation c1 = CreateCompilation(new[] { lib }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c1.VerifyDiagnostics(); var expected = new[] { // (10,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Test21(CL0.CL1 c, Action? x21) // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 38) }; c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics(expected); c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics(expected); } [Fact] public void NonNullTypes_06() { string lib = @" using System; #nullable enable public class CL0 { #nullable enable public class CL1 { #nullable disable public Action F1 = null!; #nullable disable public Action? F2; #nullable disable public Action P1 { get; set; } = null!; #nullable disable public Action? P2 { get; set; } #nullable disable public Action M1() { throw new System.NotImplementedException(); } #nullable disable public Action? M2() { return null; } #nullable disable public void M3(Action x3) {} } } "; string source1 = @" using System; #nullable enable partial class C { #nullable enable partial class B { #nullable disable public event Action E1; #nullable disable public event Action? E2; #nullable enable void Test11(Action? x11) { E1 = x11; } #nullable enable void Test12(Action x12) { x12 = E1 ?? x12; } #nullable enable void Test13(Action x13) { x13 = E2; // warn 1 } } } "; string source2 = @" using System; partial class C { partial class B { #nullable enable void Test21(CL0.CL1 c, Action? x21) { c.F1 = x21; c.P1 = x21; c.M3(x21); } #nullable enable void Test22(CL0.CL1 c, Action x22) { x22 = c.F1 ?? x22; x22 = c.P1 ?? x22; x22 = c.M1() ?? x22; } #nullable enable void Test23(CL0.CL1 c, Action x23) { x23 = c.F2; // warn 2 x23 = c.P2; // warn 3 x23 = c.M2(); // warn 4 } } } "; CSharpCompilation c = CreateCompilation(new[] { lib, source1, source2 }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public Action? F2; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 22), // (18,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public Action? P2 { get; set; } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 22), // (23,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public Action? M2() { return null; } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(23, 22), // (13,28): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public event Action? E2; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 28), // (30,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x13 = E2; // warn 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(30, 19), // (27,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.F2; // warn 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F2").WithLocation(27, 19), // (28,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.P2; // warn 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P2").WithLocation(28, 19), // (29,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.M2(); // warn 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M2()").WithLocation(29, 19) ); CSharpCompilation c1 = CreateCompilation(new[] { lib }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c1.VerifyDiagnostics( // (13,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public Action? F2; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 22), // (18,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public Action? P2 { get; set; } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 22), // (23,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public Action? M2() { return null; } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(23, 22) ); c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (27,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.F2; // warn 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F2").WithLocation(27, 19), // (28,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.P2; // warn 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P2").WithLocation(28, 19), // (29,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.M2(); // warn 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M2()").WithLocation(29, 19) ); c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (27,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.F2; // warn 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F2").WithLocation(27, 19), // (28,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.P2; // warn 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P2").WithLocation(28, 19), // (29,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.M2(); // warn 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M2()").WithLocation(29, 19) ); } [Fact] public void Covariance_Interface() { var source = @"interface I<out T> { } class C { static I<string?> F1(I<string> i) => i; static I<object?> F2(I<string> i) => i; static I<string> F3(I<string?> i) => i; static I<object> F4(I<string?> i) => i; }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,42): warning CS8619: Nullability of reference types in value of type 'I<string?>' doesn't match target type 'I<string>'. // static I<string> F3(I<string?> i) => i; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i").WithArguments("I<string?>", "I<string>").WithLocation(6, 42), // (7,42): warning CS8619: Nullability of reference types in value of type 'I<string?>' doesn't match target type 'I<object>'. // static I<object> F4(I<string?> i) => i; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i").WithArguments("I<string?>", "I<object>").WithLocation(7, 42)); } [Fact] public void Contravariance_Interface() { var source = @"interface I<in T> { } class C { static I<string?> F1(I<string> i) => i; static I<string?> F2(I<object> i) => i; static I<string> F3(I<string?> i) => i; static I<string> F4(I<object?> i) => i; }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,42): warning CS8619: Nullability of reference types in value of type 'I<string>' doesn't match target type 'I<string?>'. // static I<string?> F1(I<string> i) => i; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i").WithArguments("I<string>", "I<string?>").WithLocation(4, 42), // (5,42): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<string?>'. // static I<string?> F2(I<object> i) => i; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i").WithArguments("I<object>", "I<string?>").WithLocation(5, 42)); } [Fact] public void Covariance_Delegate() { var source = @"delegate void D<in T>(T t); class C { static void F1(string s) { } static void F2(string? s) { } static void F3(object o) { } static void F4(object? o) { } static void F<T>(D<T> d) { } static void Main() { F<string>(F1); F<string>(F2); F<string>(F3); F<string>(F4); F<string?>(F1); // warning F<string?>(F2); F<string?>(F3); // warning F<string?>(F4); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (15,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'void C.F1(string s)' doesn't match the target delegate 'D<string?>'. // F<string?>(F1); // warning Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F1").WithArguments("s", "void C.F1(string s)", "D<string?>").WithLocation(15, 20), // (17,20): warning CS8622: Nullability of reference types in type of parameter 'o' of 'void C.F3(object o)' doesn't match the target delegate 'D<string?>'. // F<string?>(F3); // warning Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F3").WithArguments("o", "void C.F3(object o)", "D<string?>").WithLocation(17, 20)); } [Fact] public void Contravariance_Delegate() { var source = @"delegate T D<out T>(); class C { static string F1() => string.Empty; static string? F2() => string.Empty; static object F3() => string.Empty; static object? F4() => string.Empty; static T F<T>(D<T> d) => d(); static void Main() { F<object>(F1); F<object>(F2); // warning F<object>(F3); F<object>(F4); // warning F<object?>(F1); F<object?>(F2); F<object?>(F3); F<object?>(F4); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,19): warning CS8621: Nullability of reference types in return type of 'string? C.F2()' doesn't match the target delegate 'D<object>'. // F<object>(F2); // warning Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F2").WithArguments("string? C.F2()", "D<object>").WithLocation(12, 19), // (14,19): warning CS8621: Nullability of reference types in return type of 'object? C.F4()' doesn't match the target delegate 'D<object>'. // F<object>(F4); // warning Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F4").WithArguments("object? C.F4()", "D<object>").WithLocation(14, 19)); } [Fact] public void TypeArgumentInference_01() { string source = @" class C { void Main() {} T M1<T>(T? x) where T: class {throw new System.NotImplementedException();} void Test1(string? x1) { M1(x1).ToString(); } void Test2(string?[] x2) { M1(x2)[0].ToString(); } void Test3(CL0<string?>? x3) { M1(x3).P1.ToString(); } void Test11(string? x11) { M1<string?>(x11).ToString(); } void Test12(string?[] x12) { M1<string?[]>(x12)[0].ToString(); } void Test13(CL0<string?>? x13) { M1<CL0<string?>?>(x13).P1.ToString(); } } class CL0<T> { public T P1 {get;set;} } "; CSharpCompilation c = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // M1(x2)[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x2)[0]").WithLocation(15, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // M1(x3).P1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x3).P1").WithLocation(20, 9), // (25,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.M1<T>(T?)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // M1<string?>(x11).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<string?>").WithArguments("C.M1<T>(T?)", "T", "string?").WithLocation(25, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // M1<string?>(x11).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1<string?>(x11)").WithLocation(25, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // M1<string?[]>(x12)[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1<string?[]>(x12)[0]").WithLocation(30, 9), // (35,9): warning CS8634: The type 'CL0<string?>?' cannot be used as type parameter 'T' in the generic type or method 'C.M1<T>(T?)'. Nullability of type argument 'CL0<string?>?' doesn't match 'class' constraint. // M1<CL0<string?>?>(x13).P1.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<CL0<string?>?>").WithArguments("C.M1<T>(T?)", "T", "CL0<string?>?").WithLocation(35, 9), // (35,9): warning CS8602: Dereference of a possibly null reference. // M1<CL0<string?>?>(x13).P1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1<CL0<string?>?>(x13)").WithLocation(35, 9), // (35,9): warning CS8602: Dereference of a possibly null reference. // M1<CL0<string?>?>(x13).P1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1<CL0<string?>?>(x13).P1").WithLocation(35, 9), // (41,14): warning CS8618: Non-nullable property 'P1' is uninitialized. Consider declaring the property as nullable. // public T P1 {get;set;} Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "P1").WithArguments("property", "P1").WithLocation(41, 14) ); } [Fact] public void ExplicitImplementations_LazyMethodChecks() { var source = @"interface I { void M<T>(T? x) where T : class; } class C : I { void I.M<T>(T? x) { } }"; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (5,11): error CS0535: 'C' does not implement interface member 'I.M<T>(T?)' // class C : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C", "I.M<T>(T?)").WithLocation(5, 11), // (7,12): error CS0539: 'C.M<T>(T?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I.M<T>(T? x) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M").WithArguments("C.M<T>(T?)").WithLocation(7, 12), // (7,20): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I.M<T>(T? x) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(7, 20)); var method = compilation.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); var implementations = method.ExplicitInterfaceImplementations; Assert.Empty(implementations); } [Fact] public void ExplicitImplementations_LazyMethodChecks_01() { var source = @"interface I { void M<T>(T? x) where T : class; } class C : I { void I.M<T>(T? x) where T : class{ } }"; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); var method = compilation.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); var implementations = method.ExplicitInterfaceImplementations; Assert.Equal(new[] { "void I.M<T>(T? x)" }, implementations.SelectAsArray(m => m.ToTestDisplayString())); } [Fact] public void EmptyStructDifferentAssembly() { var sourceA = @"using System.Collections; public struct S { public S(string f, IEnumerable g) { F = f; G = g; } private string F { get; } private IEnumerable G { get; } }"; var compA = CreateCompilation(sourceA, parseOptions: TestOptions.Regular7); var sourceB = @"using System.Collections.Generic; class C { static void Main() { var c = new List<object>(); c.Add(new S(string.Empty, new object[0])); } }"; var compB = CreateCompilation( sourceB, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular8, references: new[] { compA.EmitToImageReference() }); CompileAndVerify(compB, expectedOutput: ""); } [Fact] public void EmptyStructField() { var source = @"#pragma warning disable 8618 class A { } struct B { } struct S { public readonly A A; public readonly B B; public S(B b) : this(null, b) { } public S(A a, B b) { this.A = a; this.B = b; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,26): warning CS8625: Cannot convert null literal to non-nullable reference type. // public S(B b) : this(null, b) Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 26)); } [Fact] public void WarningOnConversion_Assignment() { var source = @"#pragma warning disable 8618 class Person { internal string FirstName { get; set; } internal string LastName { get; set; } internal string? MiddleName { get; set; } } class Program { static void F(Person p) { p.LastName = null; p.LastName = (string)null; p.LastName = (string?)null; p.LastName = null as string; p.LastName = null as string?; p.LastName = default(string); p.LastName = default; p.FirstName = p.MiddleName; p.LastName = p.MiddleName ?? null; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // p.LastName = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 22), // (13,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // p.LastName = (string)null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(13, 22), // (13,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // p.LastName = (string)null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string)null").WithLocation(13, 22), // (14,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // p.LastName = (string?)null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string?)null").WithLocation(14, 22), // (15,22): warning CS8601: Possible null reference assignment. // p.LastName = null as string; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "null as string").WithLocation(15, 22), // (16,30): error CS8651: It is not legal to use nullable reference type 'string?' in an as expression; use the underlying type 'string' instead. // p.LastName = null as string?; Diagnostic(ErrorCode.ERR_AsNullableType, "string?").WithArguments("string").WithLocation(16, 30), // (17,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // p.LastName = default(string); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default(string)").WithLocation(17, 22), // (18,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // p.LastName = default; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(18, 22), // (19,23): warning CS8601: Possible null reference assignment. // p.FirstName = p.MiddleName; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "p.MiddleName").WithLocation(19, 23), // (20,22): warning CS8601: Possible null reference assignment. // p.LastName = p.MiddleName ?? null; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "p.MiddleName ?? null").WithLocation(20, 22) ); } [Fact] public void WarningOnConversion_Receiver() { var source = @"#pragma warning disable 8618 class Person { internal string FirstName { get; set; } internal string LastName { get; set; } internal string? MiddleName { get; set; } } class Program { static void F(Person p) { ((string)null).F(); ((string?)null).F(); (null as string).F(); (null as string?).F(); default(string).F(); ((p != null) ? p.MiddleName : null).F(); (p.MiddleName ?? null).F(); } } static class Extensions { internal static void F(this string s) { } }"; var comp = CreateCompilationWithMscorlib45(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,18): error CS8651: It is not legal to use nullable reference type 'string?' in an as expression; use the underlying type 'string' instead. // (null as string?).F(); Diagnostic(ErrorCode.ERR_AsNullableType, "string?").WithArguments("string").WithLocation(15, 18), // (12,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((string)null).F(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(12, 10), // (12,10): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((string)null).F(); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string)null").WithLocation(12, 10), // (13,10): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((string?)null).F(); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string?)null").WithLocation(13, 10), // (14,10): warning CS8604: Possible null reference argument for parameter 's' in 'void Extensions.F(string s)'. // (null as string).F(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "null as string").WithArguments("s", "void Extensions.F(string s)").WithLocation(14, 10), // (16,9): warning CS8625: Cannot convert null literal to non-nullable reference type. // default(string).F(); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default(string)").WithLocation(16, 9), // (17,10): warning CS8604: Possible null reference argument for parameter 's' in 'void Extensions.F(string s)'. // ((p != null) ? p.MiddleName : null).F(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(p != null) ? p.MiddleName : null").WithArguments("s", "void Extensions.F(string s)").WithLocation(17, 10), // (18,10): warning CS8602: Dereference of a possibly null reference. // (p.MiddleName ?? null).F(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p").WithLocation(18, 10), // (18,10): warning CS8604: Possible null reference argument for parameter 's' in 'void Extensions.F(string s)'. // (p.MiddleName ?? null).F(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "p.MiddleName ?? null").WithArguments("s", "void Extensions.F(string s)").WithLocation(18, 10) ); } [Fact] public void WarningOnConversion_Argument() { var source = @"#pragma warning disable 8618 class Person { internal string FirstName { get; set; } internal string LastName { get; set; } internal string? MiddleName { get; set; } } class Program { static void F(Person p) { G(null); G((string)null); G((string?)null); G(null as string); G(null as string?); G(default(string)); G(default); G((p != null) ? p.MiddleName : null); G(p.MiddleName ?? null); } static void G(string name) { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (16,19): error CS8651: It is not legal to use nullable reference type 'string?' in an as expression; use the underlying type 'string' instead. // G(null as string?); Diagnostic(ErrorCode.ERR_AsNullableType, "string?").WithArguments("string").WithLocation(16, 19), // (12,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // G(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 11), // (13,11): warning CS8600: Converting null literal or possible null value to non-nullable type. // G((string)null); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(13, 11), // (13,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // G((string)null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string)null").WithLocation(13, 11), // (14,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // G((string?)null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string?)null").WithLocation(14, 11), // (15,11): warning CS8604: Possible null reference argument for parameter 'name' in 'void Program.G(string name)'. // G(null as string); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "null as string").WithArguments("name", "void Program.G(string name)").WithLocation(15, 11), // (17,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // G(default(string)); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default(string)").WithLocation(17, 11), // (18,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // G(default); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(18, 11), // (19,11): warning CS8604: Possible null reference argument for parameter 'name' in 'void Program.G(string name)'. // G((p != null) ? p.MiddleName : null); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(p != null) ? p.MiddleName : null").WithArguments("name", "void Program.G(string name)").WithLocation(19, 11), // (20,11): warning CS8602: Dereference of a possibly null reference. // G(p.MiddleName ?? null); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p").WithLocation(20, 11), // (20,11): warning CS8604: Possible null reference argument for parameter 'name' in 'void Program.G(string name)'. // G(p.MiddleName ?? null); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "p.MiddleName ?? null").WithArguments("name", "void Program.G(string name)").WithLocation(20, 11) ); } [Fact] public void WarningOnConversion_Return() { var source = @"#pragma warning disable 8618 class Person { internal string FirstName { get; set; } internal string LastName { get; set; } internal string? MiddleName { get; set; } } class Program { static string F1() => null; static string F2() => (string)null; static string F3() => (string?)null; static string F4() => null as string; static string F5() => null as string?; static string F6() => default(string); static string F7() => default; static string F8(Person p) => (p != null) ? p.MiddleName : null; static string F9(Person p) => p.MiddleName ?? null; }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,27): warning CS8603: Possible null reference return. // static string F1() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(10, 27), // (11,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // static string F2() => (string)null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(11, 27), // (11,27): warning CS8603: Possible null reference return. // static string F2() => (string)null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(string)null").WithLocation(11, 27), // (12,27): warning CS8603: Possible null reference return. // static string F3() => (string?)null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(string?)null").WithLocation(12, 27), // (13,27): warning CS8603: Possible null reference return. // static string F4() => null as string; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null as string").WithLocation(13, 27), // (14,35): error CS8651: It is not legal to use nullable reference type 'string?' in an as expression; use the underlying type 'string' instead. // static string F5() => null as string?; Diagnostic(ErrorCode.ERR_AsNullableType, "string?").WithArguments("string").WithLocation(14, 35), // (15,27): warning CS8603: Possible null reference return. // static string F6() => default(string); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(string)").WithLocation(15, 27), // (16,27): warning CS8603: Possible null reference return. // static string F7() => default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(16, 27), // (17,35): warning CS8603: Possible null reference return. // static string F8(Person p) => (p != null) ? p.MiddleName : null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(p != null) ? p.MiddleName : null").WithLocation(17, 35), // (18,35): warning CS8603: Possible null reference return. // static string F9(Person p) => p.MiddleName ?? null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "p.MiddleName ?? null").WithLocation(18, 35) ); } [Fact] public void SuppressNullableWarning() { var source = @"class C { static void F(string? s) // 1 { G(null!); // 2, 3 G((null as string)!); // 4, 5 G(default(string)!); // 6, 7 G(default!); // 8, 9, 10 G(s!); // 11, 12 } static void G(string s) { } }"; var comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular7, skipUsesIsNullable: true); comp.VerifyDiagnostics( // (5,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(null!); // 2, 3 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "null!").WithArguments("nullable reference types", "8.0").WithLocation(5, 11), // (6,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G((null as string)!); // 4, 5 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "(null as string)!").WithArguments("nullable reference types", "8.0").WithLocation(6, 11), // (7,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(default(string)!); // 6, 7 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "default(string)!").WithArguments("nullable reference types", "8.0").WithLocation(7, 11), // (8,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(default!); // 8, 9, 10 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "default!").WithArguments("nullable reference types", "8.0").WithLocation(8, 11), // (8,11): error CS8107: Feature 'default literal' is not available in C# 7.0. Please use language version 7.1 or greater. // G(default!); // 8, 9, 10 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "default").WithArguments("default literal", "7.1").WithLocation(8, 11), // (9,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(s!); // 11, 12 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "s!").WithArguments("nullable reference types", "8.0").WithLocation(9, 11), // (3,25): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // static void F(string? s) // 1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(3, 25) ); comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void SuppressNullableWarning_ReferenceType() { var source = @"class C { static C F(C? o) { C other; other = o!; o = other; o!.F(); G(o!); return o!; } void F() { } static void G(C o) { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_Array() { var source = @"class C { static object[] F(object?[] o) { object[] other; other = o!; o = other!; o!.F(); G(o!); return o!; } static void G(object[] o) { } } static class E { internal static void F(this object[] o) { } }"; var comp = CreateCompilationWithMscorlib45( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_ConstructedType() { var source = @"class C { static C<object> F(C<object?> o) { C<object> other; other = o!; // 1 o = other!; // 2 o!.F(); G(o!); // 3 return o!; // 4 } static void G(C<object> o) { } } class C<T> { internal void F() { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29902, "https://github.com/dotnet/roslyn/issues/29902")] public void SuppressNullableWarning_Multiple() { var source = @"class C { static void F(string? s) { G(default!!); G(s!!); G((s!)!); G(((s!)!)!); G(s!!!!!!!); G(s! ! ! ! ! ! !); } static void G(string s) { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,11): error CS8715: Duplicate null suppression operator ('!') // G(default!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "default").WithLocation(5, 11), // (6,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(6, 11), // (7,12): error CS8715: Duplicate null suppression operator ('!') // G((s!)!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(7, 12), // (8,13): error CS8715: Duplicate null suppression operator ('!') // G(((s!)!)!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(8, 13), // (8,13): error CS8715: Duplicate null suppression operator ('!') // G(((s!)!)!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(8, 13), // (9,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!!!!!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(9, 11), // (9,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!!!!!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(9, 11), // (9,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!!!!!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(9, 11), // (9,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!!!!!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(9, 11), // (9,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!!!!!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(9, 11), // (9,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!!!!!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(9, 11), // (10,11): error CS8715: Duplicate null suppression operator ('!') // G(s! ! ! ! ! ! !); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(10, 11), // (10,11): error CS8715: Duplicate null suppression operator ('!') // G(s! ! ! ! ! ! !); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(10, 11), // (10,11): error CS8715: Duplicate null suppression operator ('!') // G(s! ! ! ! ! ! !); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(10, 11), // (10,11): error CS8715: Duplicate null suppression operator ('!') // G(s! ! ! ! ! ! !); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(10, 11), // (10,11): error CS8715: Duplicate null suppression operator ('!') // G(s! ! ! ! ! ! !); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(10, 11), // (10,11): error CS8715: Duplicate null suppression operator ('!') // G(s! ! ! ! ! ! !); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(10, 11) ); } [Fact] [WorkItem(43659, "https://github.com/dotnet/roslyn/issues/43659")] public void SuppressNullableWarning_ConditionalAccess_01() { var source = @" #nullable enable using System; using System.Linq; class Program { static void Main() { int[]? a = null; string? s1 = a?.First().ToString(); Console.Write(s1 == null); string? s2 = a?.First()!.ToString(); Console.Write(s2 == null); string s3 = a?.First().ToString()!; Console.Write(s3 == null); string? s4 = (a?.First()).ToString(); Console.Write(s4 == null); string? s5 = (a?.First())!.ToString(); Console.Write(s5 == null); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueTrueTrueFalseFalse"); } [Fact] [WorkItem(43659, "https://github.com/dotnet/roslyn/issues/43659")] public void SuppressNullableWarning_ConditionalAccess_02() { var source = @" #nullable enable using System.Linq; class Program { static void Main() { int[]? a = null; string? s1 = a?.First()!!.ToString(); // 1 string? s2 = a?.First()!!!!.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (12,24): error CS8715: Duplicate null suppression operator ('!') // string? s1 = a?.First()!!.ToString(); // 1 Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, ".First()", isSuppressed: false).WithLocation(12, 24), // (13,24): error CS8715: Duplicate null suppression operator ('!') // string? s2 = a?.First()!!!!.ToString(); // 2 Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, ".First()", isSuppressed: false).WithLocation(13, 24), // (13,24): error CS8715: Duplicate null suppression operator ('!') // string? s2 = a?.First()!!!!.ToString(); // 2 Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, ".First()", isSuppressed: false).WithLocation(13, 24), // (13,24): error CS8715: Duplicate null suppression operator ('!') // string? s2 = a?.First()!!!!.ToString(); // 2 Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, ".First()", isSuppressed: false).WithLocation(13, 24)); } [Fact] [WorkItem(43659, "https://github.com/dotnet/roslyn/issues/43659")] public void SuppressNullableWarning_ConditionalAccess_03() { var source = @" #nullable enable using System; public class D { } public class C { public D d = null!; } public class B { public C? c; } public class A { public B? b; } class Program { static void Main() { M(new A()); } static void M(A a) { var str = a.b?.c!.d.ToString(); Console.Write(str == null); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] [WorkItem(43659, "https://github.com/dotnet/roslyn/issues/43659")] public void SuppressNullableWarning_ConditionalAccess_04() { var source = @" #nullable enable public class D { } public class C { public D? d; } public class B { public C? c; } public class A { public B? b; } class Program { static void M(A a) { string str1 = a.b?.c!.d.ToString(); // 1, 2 string str2 = a.b?.c!.d!.ToString(); // 3 string str3 = a.b?.c!.d!.ToString()!; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // string str1 = a.b?.c!.d.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "a.b?.c!.d.ToString()", isSuppressed: false).WithLocation(13, 23), // (13,27): warning CS8602: Dereference of a possibly null reference. // string str1 = a.b?.c!.d.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, ".c!.d", isSuppressed: false).WithLocation(13, 27), // (14,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // string str2 = a.b?.c!.d!.ToString(); // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "a.b?.c!.d!.ToString()", isSuppressed: false).WithLocation(14, 23)); } [Fact] public void SuppressNullableWarning_Nested() { var source = @"class C<T> where T : class { static T? F(T t) => t; static T? G(T t) => t; static void M(T? t) { F(G(t!)); F(G(t)!); F(G(t!)!); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,11): warning CS8604: Possible null reference argument for parameter 't' in 'T? C<T>.F(T t)'. // F(G(t!)); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "G(t!)").WithArguments("t", "T? C<T>.F(T t)").WithLocation(7, 11), // (8,13): warning CS8604: Possible null reference argument for parameter 't' in 'T? C<T>.G(T t)'. // F(G(t)!); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("t", "T? C<T>.G(T t)").WithLocation(8, 13)); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_Conditional() { var source = @"class C<T> { } class C { static void F(C<object>? x, C<object?> y, bool c) { C<object> a; a = c ? x : y; // 1 a = c ? y : x; // 2 a = c ? x : y!; // 3 a = c ? x! : y; // 4 a = c ? x! : y!; C<object?> b; b = c ? x : y; // 5 b = c ? x : y!; // 6 b = c ? x! : y; // 7 b = c ? x! : y!; // 8 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // a = c ? x : y; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ? x : y").WithLocation(7, 13), // (7,21): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // a = c ? x : y; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(7, 21), // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // a = c ? y : x; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ? y : x").WithLocation(8, 13), // (8,17): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // a = c ? y : x; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(8, 17), // (9,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // a = c ? x : y!; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ? x : y!").WithLocation(9, 13), // (10,22): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // a = c ? x! : y; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(10, 22), // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // b = c ? x : y; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ? x : y").WithLocation(13, 13), // (13,13): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // b = c ? x : y; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x : y").WithArguments("C<object>", "C<object?>").WithLocation(13, 13), // (13,21): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // b = c ? x : y; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(13, 21), // (14,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // b = c ? x : y!; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ? x : y!").WithLocation(14, 13), // (14,13): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // b = c ? x : y!; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x : y!").WithArguments("C<object>", "C<object?>").WithLocation(14, 13), // (15,13): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // b = c ? x! : y; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x! : y").WithArguments("C<object>", "C<object?>").WithLocation(15, 13), // (15,22): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // b = c ? x! : y; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(15, 22), // (16,13): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // b = c ? x! : y!; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x! : y!").WithArguments("C<object>", "C<object?>").WithLocation(16, 13) ); } [Fact] public void SuppressNullableWarning_NullCoalescing() { var source = @" class C<T> { static void F(C<object>? x, C<object?> y) { var t1 = x ?? y; // 1 var t2 = y ?? x; // 2 var t3 = x! ?? y; // 3 var t4 = y! ?? x; // 4 var t5 = x ?? y!; var t6 = y ?? x!; var t7 = x! ?? y!; var t8 = y! ?? x!; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,23): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var t1 = x ?? y; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(6, 23), // (7,23): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // var t2 = y ?? x; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<object>", "C<object?>").WithLocation(7, 23), // (8,24): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var t3 = x! ?? y; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(8, 24), // (9,24): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // var t4 = y! ?? x; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<object>", "C<object?>").WithLocation(9, 24)); } [Fact] [WorkItem(30151, "https://github.com/dotnet/roslyn/issues/30151")] [WorkItem(33346, "https://github.com/dotnet/roslyn/issues/33346")] public void SuppressNullableWarning_ArrayInitializer() { var source = @" class C<T> { static void F(C<object>? x, C<object?> y) { var a1 = new[] { x, y }; // 1 _ = a1 /*T:C<object!>?[]!*/; var a2 = new[] { x!, y }; // 2 _ = a2 /*T:C<object!>![]!*/; var a3 = new[] { x, y! }; _ = a3 /*T:C<object!>?[]!*/; var a4 = new[] { x!, y! }; _ = a4 /*T:C<object!>![]!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,29): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var a1 = new[] { x, y }; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(6, 29), // (8,30): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var a2 = new[] { x!, y }; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(8, 30)); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_LocalDeclaration() { var source = @" class C<T> { static void F(C<object>? x, C<object?> y) { C<object>? c1 = y; // 1 C<object?> c2 = x; // 2 and 3 C<object>? c3 = y!; // 4 C<object?> c4 = x!; // 5 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,25): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // C<object>? c1 = y; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(6, 25), // (7,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // C<object?> c2 = x; // 2 and 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(7, 25), // (7,25): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // C<object?> c2 = x; // 2 and 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<object>", "C<object?>").WithLocation(7, 25) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_Cast() { var source = @" class C<T> { static void F(C<object>? x, C<object?> y) { var c1 = (C<object>?)y; var c2 = (C<object?>)x; // warn var c3 = (C<object>?)y!; var c4 = (C<object?>)x!; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var c1 = (C<object>?)y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(C<object>?)y").WithArguments("C<object?>", "C<object>").WithLocation(6, 18), // (7,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // var c2 = (C<object?>)x; // warn Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C<object?>)x").WithLocation(7, 18), // (7,18): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // var c2 = (C<object?>)x; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(C<object?>)x").WithArguments("C<object>", "C<object?>").WithLocation(7, 18) ); } [Fact] public void SuppressNullableWarning_ObjectInitializer() { var source = @" class C<T> { public C<object>? X = null!; public C<object?> Y = null!; static void F(C<object>? x, C<object?> y) { _ = new C<int>() { X = y, Y = x }; _ = new C<int>() { X = y!, Y = x! }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,32): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // _ = new C<int>() { X = y, Y = x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(8, 32), // (8,39): warning CS8601: Possible null reference assignment. // _ = new C<int>() { X = y, Y = x }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(8, 39), // (8,39): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // _ = new C<int>() { X = y, Y = x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<object>", "C<object?>").WithLocation(8, 39) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_CollectionInitializer() { var source = @" using System.Collections; class C<T> : IEnumerable { IEnumerator IEnumerable.GetEnumerator() => throw null!; void Add(C<object?> key, params C<object?>[] value) => throw null!; static void F(C<object>? x) { _ = new C<int>() { x, x }; // warn 1 and 2 _ = new C<int>() { x!, x! }; // warn 3 and 4 } } class D<T> : IEnumerable { IEnumerator IEnumerable.GetEnumerator() => throw null!; void Add(D<object>? key, params D<object>?[] value) => throw null!; static void F(D<object?> y) { _ = new D<int>() { y, y }; // warn 5 and 6 _ = new D<int>() { y!, y! }; // warn 7 and 8 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,28): warning CS8620: Argument of type 'D<object?>' cannot be used for parameter 'key' of type 'D<object>' in 'void D<int>.Add(D<object>? key, params D<object>?[] value)' due to differences in the nullability of reference types. // _ = new D<int>() { y, y }; // warn 5 and 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("D<object?>", "D<object>", "key", "void D<int>.Add(D<object>? key, params D<object>?[] value)").WithLocation(19, 28), // (19,32): warning CS8620: Argument of type 'D<object?>' cannot be used for parameter 'key' of type 'D<object>' in 'void D<int>.Add(D<object>? key, params D<object>?[] value)' due to differences in the nullability of reference types. // _ = new D<int>() { y, y }; // warn 5 and 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("D<object?>", "D<object>", "key", "void D<int>.Add(D<object>? key, params D<object>?[] value)").WithLocation(19, 32), // (9,28): warning CS8604: Possible null reference argument for parameter 'key' in 'void C<int>.Add(C<object?> key, params C<object?>[] value)'. // _ = new C<int>() { x, x }; // warn 1 and 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("key", "void C<int>.Add(C<object?> key, params C<object?>[] value)").WithLocation(9, 28), // (9,28): warning CS8620: Argument of type 'C<object>' cannot be used for parameter 'key' of type 'C<object?>' in 'void C<int>.Add(C<object?> key, params C<object?>[] value)' due to differences in the nullability of reference types. // _ = new C<int>() { x, x }; // warn 1 and 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("C<object>", "C<object?>", "key", "void C<int>.Add(C<object?> key, params C<object?>[] value)").WithLocation(9, 28), // (9,31): warning CS8620: Argument of type 'C<object>' cannot be used for parameter 'key' of type 'C<object?>' in 'void C<int>.Add(C<object?> key, params C<object?>[] value)' due to differences in the nullability of reference types. // _ = new C<int>() { x, x }; // warn 1 and 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("C<object>", "C<object?>", "key", "void C<int>.Add(C<object?> key, params C<object?>[] value)").WithLocation(9, 31) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_IdentityConversion() { var source = @"class C<T> { } class C { static void F(C<object?> x, C<object> y) { C<object> a; a = x; // 1 a = x!; // 2 C<object?> b; b = y; // 3 b = y!; // 4 } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,13): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // a = x; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<object?>", "C<object>").WithLocation(7, 13), // (10,13): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // b = y; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object>", "C<object?>").WithLocation(10, 13) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_ImplicitConversion() { var source = @"interface I<T> { } class C<T> : I<T> { } class C { static void F(C<object?> x, C<object> y) { I<object> a; a = x; a = x!; I<object?> b; b = y; b = y!; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,13): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'I<object>'. // a = x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<object?>", "I<object>").WithLocation(8, 13), // (11,13): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'I<object?>'. // b = y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object>", "I<object?>").WithLocation(11, 13) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_ImplicitExtensionMethodThisConversion() { var source = @"interface I<T> { } class C<T> : I<T> { } class C { static void F(C<object?> x, C<object> y) { x.F1(); x!.F1(); y.F2(); y!.F2(); } } static class E { internal static void F1(this I<object> o) { } internal static void F2(this I<object?> o) { } }"; var comp = CreateCompilationWithMscorlib45( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,9): warning CS8620: Nullability of reference types in argument of type 'C<object?>' doesn't match target type 'I<object>' for parameter 'o' in 'void E.F1(I<object> o)'. // x.F1(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("C<object?>", "I<object>", "o", "void E.F1(I<object> o)").WithLocation(7, 9), // (9,9): warning CS8620: Nullability of reference types in argument of type 'C<object>' doesn't match target type 'I<object?>' for parameter 'o' in 'void E.F2(I<object?> o)'. // y.F2(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<object>", "I<object?>", "o", "void E.F2(I<object?> o)").WithLocation(9, 9) ); } [Fact] public void SuppressNullableWarning_ImplicitUserDefinedConversion() { var source = @"class A<T> { } class B<T> { public static implicit operator A<T>(B<T> b) => new A<T>(); } class C { static void F(B<object?> b1, B<object> b2) { A<object> a1; a1 = b1; // 1 a1 = b1!; // 2 A<object?> a2; a2 = b2; // 3 a2 = b2!; // 4 } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,14): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'A<object>'. // a1 = b1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b1").WithArguments("A<object?>", "A<object>").WithLocation(11, 14), // (14,14): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'A<object?>'. // a2 = b2; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b2").WithArguments("A<object>", "A<object?>").WithLocation(14, 14) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_ExplicitConversion() { var source = @"interface I<T> { } class C<T> { } class C { static void F(C<object?> x, C<object> y) { I<object> a; a = (I<object?>)x; // 1 a = ((I<object?>)x)!; // 2 I<object?> b; b = (I<object>)y; // 3 b = ((I<object>)y)!; // 4 } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,13): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // a = (I<object?>)x; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(I<object?>)x").WithArguments("I<object?>", "I<object>").WithLocation(8, 13), // (11,13): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // b = (I<object>)y; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(I<object>)y").WithArguments("I<object>", "I<object?>").WithLocation(11, 13) ); } [Fact] public void SuppressNullableWarning_Ref() { var source = @"class C { static void F(ref string s, ref string? t) { } static void Main() { string? s = null; string t = """"; F(ref s, ref t); F(ref s!, ref t!); } }"; var comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (10,15): warning CS8601: Possible null reference assignment. // F(ref s, ref t); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(10, 15), // (10,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(ref s, ref t); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(10, 22)); } [Fact] public void SuppressNullableWarning_Ref_WithNestedDifferences() { var source = @" class List<T> { } class C { static void F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d) { } static void F1(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d) { F(ref b, ref c, ref d, ref a); // warnings } static void F2(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d) { F(ref b!, ref c!, ref d!, ref a!); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,15): warning CS8601: Possible null reference assignment. // F(ref b, ref c, ref d, ref a); // warnings Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "b").WithLocation(10, 15), // (10,22): warning CS8620: Argument of type 'List<string?>' cannot be used for parameter 'b' of type 'List<string>' in 'void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)' due to differences in the nullability of reference types. // F(ref b, ref c, ref d, ref a); // warnings Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "c").WithArguments("List<string?>", "List<string>", "b", "void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)").WithLocation(10, 22), // (10,22): warning CS8601: Possible null reference assignment. // F(ref b, ref c, ref d, ref a); // warnings Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c").WithLocation(10, 22), // (10,29): warning CS8601: Possible null reference assignment. // F(ref b, ref c, ref d, ref a); // warnings Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "d").WithLocation(10, 29), // (10,36): warning CS8620: Argument of type 'List<string>' cannot be used for parameter 'd' of type 'List<string?>' in 'void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)' due to differences in the nullability of reference types. // F(ref b, ref c, ref d, ref a); // warnings Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "a").WithArguments("List<string>", "List<string?>", "d", "void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)").WithLocation(10, 36), // (10,36): warning CS8601: Possible null reference assignment. // F(ref b, ref c, ref d, ref a); // warnings Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "a").WithLocation(10, 36)); } [Fact] public void SuppressNullableWarning_Ref_WithUnassignedLocals() { var source = @" class List<T> { } class C { static void F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d) { throw null!; } static void F1() { List<string> a; List<string>? b; List<string?> c; List<string?>? d; F(ref b, ref c, ref d, ref a); } static void F2() { List<string> a; List<string>? b; List<string?> c; List<string?>? d; F(ref b!, ref c!, ref d!, ref a!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,15): error CS0165: Use of unassigned local variable 'b' // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(15, 15), // (15,15): warning CS8601: Possible null reference assignment. // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "b").WithLocation(15, 15), // (15,22): error CS0165: Use of unassigned local variable 'c' // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c").WithLocation(15, 22), // (15,22): warning CS8620: Argument of type 'List<string?>' cannot be used for parameter 'b' of type 'List<string>' in 'void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)' due to differences in the nullability of reference types. // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "c").WithArguments("List<string?>", "List<string>", "b", "void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)").WithLocation(15, 22), // (15,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c").WithLocation(15, 22), // (15,29): error CS0165: Use of unassigned local variable 'd' // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.ERR_UseDefViolation, "d").WithArguments("d").WithLocation(15, 29), // (15,29): warning CS8601: Possible null reference assignment. // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "d").WithLocation(15, 29), // (15,36): error CS0165: Use of unassigned local variable 'a' // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.ERR_UseDefViolation, "a").WithArguments("a").WithLocation(15, 36), // (15,36): warning CS8620: Argument of type 'List<string>' cannot be used for parameter 'd' of type 'List<string?>' in 'void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)' due to differences in the nullability of reference types. // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "a").WithArguments("List<string>", "List<string?>", "d", "void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)").WithLocation(15, 36), // (15,36): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "a").WithLocation(15, 36), // (23,15): error CS0165: Use of unassigned local variable 'b' // F(ref b!, ref c!, ref d!, ref a!); Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(23, 15), // (23,23): error CS0165: Use of unassigned local variable 'c' // F(ref b!, ref c!, ref d!, ref a!); Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c").WithLocation(23, 23), // (23,31): error CS0165: Use of unassigned local variable 'd' // F(ref b!, ref c!, ref d!, ref a!); Diagnostic(ErrorCode.ERR_UseDefViolation, "d").WithArguments("d").WithLocation(23, 31), // (23,39): error CS0165: Use of unassigned local variable 'a' // F(ref b!, ref c!, ref d!, ref a!); Diagnostic(ErrorCode.ERR_UseDefViolation, "a").WithArguments("a").WithLocation(23, 39)); } [Fact] public void SuppressNullableWarning_Out_WithNestedDifferences() { var source = @" class List<T> { } class C { static void F(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d) { throw null!; } static void F1(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d) { F(out b, out c, out d, out a); // warn on `c` and `a` } static void F2(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d) { F(out b!, out c!, out d!, out a!); // warn on `c!` and `a!` } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,22): warning CS8601: Possible null reference assignment. // F(out b, out c, out d, out a); // warn on `c` and `a` Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c").WithLocation(11, 22), // (11,22): warning CS8624: Argument of type 'List<string?>' cannot be used as an output of type 'List<string>' for parameter 'b' in 'void C.F(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d)' due to differences in the nullability of reference types. // F(out b, out c, out d, out a); // warn on `c` and `a` Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "c").WithArguments("List<string?>", "List<string>", "b", "void C.F(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d)").WithLocation(11, 22), // (11,36): warning CS8601: Possible null reference assignment. // F(out b, out c, out d, out a); // warn on `c` and `a` Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "a").WithLocation(11, 36), // (11,36): warning CS8624: Argument of type 'List<string>' cannot be used as an output of type 'List<string?>' for parameter 'd' in 'void C.F(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d)' due to differences in the nullability of reference types. // F(out b, out c, out d, out a); // warn on `c` and `a` Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "a").WithArguments("List<string>", "List<string?>", "d", "void C.F(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d)").WithLocation(11, 36) ); } [Fact] [WorkItem(27522, "https://github.com/dotnet/roslyn/issues/27522")] public void SuppressNullableWarning_Out() { var source = @"class C { static void F(out string s, out string? t) { s = string.Empty; t = string.Empty; } static ref string RefReturn() => ref (new string[1])[0]; static void Main() { string? s; string t; F(out s, out t); // warn F(out s!, out t!); // ok F(out RefReturn(), out RefReturn()); // warn F(out RefReturn()!, out RefReturn()!); // ok F(out (s!), out (t!)); // errors F(out (s)!, out (t)!); // errors } }"; var comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (18,19): error CS1525: Invalid expression term ',' // F(out (s)!, out (t)!); // errors Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(18, 19), // (18,29): error CS1525: Invalid expression term ')' // F(out (s)!, out (t)!); // errors Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(18, 29), // (18,16): error CS0118: 's' is a variable but is used like a type // F(out (s)!, out (t)!); // errors Diagnostic(ErrorCode.ERR_BadSKknown, "s").WithArguments("s", "variable", "type").WithLocation(18, 16), // (18,26): error CS0118: 't' is a variable but is used like a type // F(out (s)!, out (t)!); // errors Diagnostic(ErrorCode.ERR_BadSKknown, "t").WithArguments("t", "variable", "type").WithLocation(18, 26), // (13,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(out s, out t); // warn Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(13, 22), // (15,32): warning CS8601: Possible null reference assignment. // F(out RefReturn(), out RefReturn()); // warn Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "RefReturn()").WithLocation(15, 32)); } [Fact] [WorkItem(27317, "https://github.com/dotnet/roslyn/pull/27317")] public void RefOutSuppressionInference() { var src = @" class C { void M<T>(ref T t) { } void M2<T>(out T t) => throw null!; void M3<T>(in T t) { } T M4<T>(in T t) => t; void M3() { string? s1 = null; M(ref s1!); s1.ToString(); string? s2 = null; M2(out s2!); s2.ToString(); string? s3 = null; M3(s3!); s3.ToString(); // warn string? s4 = null; M3(in s4!); s4.ToString(); // warn string? s5 = null; s5 = M4(s5!); s5.ToString(); string? s6 = null; s6 = M4(in s6!); s6.ToString(); } }"; var comp = CreateCompilation(src, options: WithNullableEnable(TestOptions.DebugDll)); comp.VerifyDiagnostics( // (21,9): warning CS8602: Dereference of a possibly null reference. // s3.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(21, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(25, 9)); } [Fact] [WorkItem(27522, "https://github.com/dotnet/roslyn/issues/27522")] [WorkItem(29903, "https://github.com/dotnet/roslyn/issues/29903")] public void SuppressNullableWarning_Assignment() { var source = @"class C { static void Main() { string? s = null; string t = string.Empty; t! = s; t! += s; (t!) = s; } }"; var comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (7,9): error CS8598: The suppression operator is not allowed in this context // t! = s; Diagnostic(ErrorCode.ERR_IllegalSuppression, "t").WithLocation(7, 9), // (7,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t! = s; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(7, 14), // (8,9): error CS8598: The suppression operator is not allowed in this context // t! += s; Diagnostic(ErrorCode.ERR_IllegalSuppression, "t").WithLocation(8, 9), // (9,10): error CS8598: The suppression operator is not allowed in this context // (t!) = s; Diagnostic(ErrorCode.ERR_IllegalSuppression, "t").WithLocation(9, 10), // (9,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // (t!) = s; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(9, 16) ); } [Fact] public void SuppressNullableWarning_Conversion() { var source = @"class A { public static implicit operator B(A a) => new B(); } class B { } class C { static void F(A? a) { G((B)a); G((B)a!); } static void G(B b) { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,14): warning CS8604: Possible null reference argument for parameter 'a' in 'A.implicit operator B(A a)'. // G((B)a); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("a", "A.implicit operator B(A a)").WithLocation(12, 14)); } [Fact] [WorkItem(29906, "https://github.com/dotnet/roslyn/issues/29906")] public void SuppressNullableWarning_Condition() { var source = @"class C { static object? F(bool b) { return (b && G(out var o))! ? o : null; } static bool G(out object o) { o = new object(); return true; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Deconstruction() { var source = @" class C<T> { } class C2 { void M(C<string?> c) { // line 1 (string d1, (C<string> d2, string d3)) = (null, (c, null)); // line 2 (string e1, (C<string> e2, string e3)) = (null, (c, null))!; // line 3 (string f1, (C<string> f2, string f3)) = (null, (c, null)!); // line 4 (string g1, (C<string> g2, string g3)) = (null!, (c, null)!); // line 5 (string h1, (C<string> h2, string h3)) = (null!, (c!, null!)); // no warnings // line 6 (string i1, (C<string> i2, string i3)) = default((string, (C<string>, string)))!; // line 7 (string j1, (C<string> j2, string j3)) = (null, default((C<string>, string))!); // line 8 (string k1, (C<string> k2, string k3)) = (null!, default((C<string>, string))!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // line 1 // (10,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string d1, (C<string> d2, string d3)) = (null, (c, null)); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(10, 51), // (10,58): warning CS8619: Nullability of reference types in value of type 'C<string?>' doesn't match target type 'C<string>'. // (string d1, (C<string> d2, string d3)) = (null, (c, null)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c").WithArguments("C<string?>", "C<string>").WithLocation(10, 58), // (10,61): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string d1, (C<string> d2, string d3)) = (null, (c, null)); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(10, 61), // line 2 // (13,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string e1, (C<string> e2, string e3)) = (null, (c, null))!; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 51), // (13,58): warning CS8619: Nullability of reference types in value of type 'C<string?>' doesn't match target type 'C<string>'. // (string e1, (C<string> e2, string e3)) = (null, (c, null))!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c").WithArguments("C<string?>", "C<string>").WithLocation(13, 58), // (13,61): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string e1, (C<string> e2, string e3)) = (null, (c, null))!; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 61), // line 3 // (16,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string f1, (C<string> f2, string f3)) = (null, (c, null)!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 51), // (16,58): warning CS8619: Nullability of reference types in value of type 'C<string?>' doesn't match target type 'C<string>'. // (string f1, (C<string> f2, string f3)) = (null, (c, null)!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c").WithArguments("C<string?>", "C<string>").WithLocation(16, 58), // (16,61): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string f1, (C<string> f2, string f3)) = (null, (c, null)!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 61), // line 4 // (19,59): warning CS8619: Nullability of reference types in value of type 'C<string?>' doesn't match target type 'C<string>'. // (string g1, (C<string> g2, string g3)) = (null!, (c, null)!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c").WithArguments("C<string?>", "C<string>").WithLocation(19, 59), // (19,62): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string g1, (C<string> g2, string g3)) = (null!, (c, null)!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 62), // line 6 // (25,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string i1, (C<string> i2, string i3)) = default((string, (C<string>, string)))!; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((string, (C<string>, string)))").WithLocation(25, 50), // (25,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string i1, (C<string> i2, string i3)) = default((string, (C<string>, string)))!; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((string, (C<string>, string)))").WithLocation(25, 50), // (25,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string i1, (C<string> i2, string i3)) = default((string, (C<string>, string)))!; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((string, (C<string>, string)))").WithLocation(25, 50), // line 7 // (28,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string j1, (C<string> j2, string j3)) = (null, default((C<string>, string))!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(28, 51), // (28,57): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string j1, (C<string> j2, string j3)) = (null, default((C<string>, string))!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((C<string>, string))").WithLocation(28, 57), // (28,57): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string j1, (C<string> j2, string j3)) = (null, default((C<string>, string))!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((C<string>, string))").WithLocation(28, 57), // line 8 // (31,58): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string k1, (C<string> k2, string k3)) = (null!, default((C<string>, string))!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((C<string>, string))").WithLocation(31, 58), // (31,58): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string k1, (C<string> k2, string k3)) = (null!, default((C<string>, string))!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((C<string>, string))").WithLocation(31, 58) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Tuple() { var source = @" class C<T> { } class C2 { static T Id<T>(T t) => t; void M(C<string?> c) { // line 1 (string, (C<string>, string)) t1 = (null, (c, null)); t1.Item1.ToString(); // warn Id(t1).Item1.ToString(); // no warn // line 2 (string, (C<string>, string)) t2 = (null, (c, null))!; t2.Item1.ToString(); // warn Id(t2).Item1.ToString(); // no warn // line 3 (string, (C<string>, string)) t3 = (null, (c, null)!); t3.Item1.ToString(); // warn Id(t3).Item1.ToString(); // no warn // line 4 (string, (C<string>, string)) t4 = (null, (c, null)!)!; // no warn t4.Item1.ToString(); // warn Id(t4).Item1.ToString(); // no warn // line 5 (string, (C<string>, string)) t5 = (null!, (c, null)!); // no warn t5.Item1.ToString(); // no warn Id(t5).Item1.ToString(); // no warn // line 6 (string, (C<string>, string)) t6 = (null!, (c!, null!)); // warn t6.Item1.ToString(); // no warn Id(t6).Item1.ToString(); // no warn // line 7 (string, (C<string>, string)) t7 = (null!, (c!, null!)!); // no warn t7.Item1.ToString(); // no warn Id(t7).Item1.ToString(); // no warn // line 8 (string, (C<string>, string)) t8 = (null, (c, null))!; // warn t8.Item1.ToString(); // warn Id(t8).Item1.ToString(); // no warn } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // line 1 // (9,51): warning CS8619: Nullability of reference types in value of type '(C<string?> c, string?)' doesn't match target type '(C<string>, string)'. // (string, (C<string>, string)) t1 = (null, (c, null)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(c, null)").WithArguments("(C<string?> c, string?)", "(C<string>, string)").WithLocation(9, 51), // (9,44): warning CS8619: Nullability of reference types in value of type '(string?, (C<string>, string))' doesn't match target type '(string, (C<string>, string))'. // (string, (C<string>, string)) t1 = (null, (c, null)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, (c, null))").WithArguments("(string?, (C<string>, string))", "(string, (C<string>, string))").WithLocation(9, 44), // (10,9): warning CS8602: Dereference of a possibly null reference. // t1.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1.Item1").WithLocation(10, 9), // line 2 // (14,51): warning CS8619: Nullability of reference types in value of type '(C<string?> c, string?)' doesn't match target type '(C<string>, string)'. // (string, (C<string>, string)) t2 = (null, (c, null))!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(c, null)").WithArguments("(C<string?> c, string?)", "(C<string>, string)").WithLocation(14, 51), // (15,9): warning CS8602: Dereference of a possibly null reference. // t2.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2.Item1").WithLocation(15, 9), // line 3 // (19,44): warning CS8619: Nullability of reference types in value of type '(string?, (C<string>, string))' doesn't match target type '(string, (C<string>, string))'. // (string, (C<string>, string)) t3 = (null, (c, null)!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, (c, null)!)").WithArguments("(string?, (C<string>, string))", "(string, (C<string>, string))").WithLocation(19, 44), // (20,9): warning CS8602: Dereference of a possibly null reference. // t3.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3.Item1").WithLocation(20, 9), // line 4 // (25,9): warning CS8602: Dereference of a possibly null reference. // t4.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t4.Item1").WithLocation(25, 9), // line 6 // (34,52): warning CS8619: Nullability of reference types in value of type '(C<string?>, string)' doesn't match target type '(C<string>, string)'. // (string, (C<string>, string)) t6 = (null!, (c!, null!)); // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(c!, null!)").WithArguments("(C<string?>, string)", "(C<string>, string)").WithLocation(34, 52), // line 8 // (44,51): warning CS8619: Nullability of reference types in value of type '(C<string?> c, string?)' doesn't match target type '(C<string>, string)'. // (string, (C<string>, string)) t8 = (null, (c, null))!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(c, null)").WithArguments("(C<string?> c, string?)", "(C<string>, string)").WithLocation(44, 51), // (45,9): warning CS8602: Dereference of a possibly null reference. // t8.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t8.Item1").WithLocation(45, 9)); CompileAndVerify(comp); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_TupleEquality() { var source = @"class C<T> { static void M((string, C<string>) t, C<string?> c) { _ = t == (null, c); _ = t == (null, c)!; _ = (1, t) == (1, (null, c)); _ = (1, t) == (1, (null, c)!); _ = (1, t) == (1, (null!, c!)); _ = (1, t!) == (1, (null, c)); _ = (t, (null, c)!) == ((null, c)!, t); _ = (t, (null!, c!)) == ((null!, c!), t); _ = (t!, (null, c)) == ((null, c), t!); _ = (t, (null, c))! == ((null, c), t); _ = (t, (null, c)) == ((null, c), t)!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); CompileAndVerify(comp); } [Fact] public void SuppressNullableWarning_ValueType_01() { var source = @"struct S { static void F() { G(1!); G(((int?)null)!); G(default(S)!); _ = new S2<object>()!; } static void G(object o) { } static void G<T>(T? t) where T : struct { } } struct S2<T> { }"; // Feature enabled. var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); // Feature disabled. comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); // Feature disabled (C# 7). comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (5,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(1!); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "1!").WithArguments("nullable reference types", "8.0").WithLocation(5, 11), // (6,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(((int?)null)!); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "((int?)null)!").WithArguments("nullable reference types", "8.0").WithLocation(6, 11), // (7,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(default(S)!); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "default(S)!").WithArguments("nullable reference types", "8.0").WithLocation(7, 11), // (8,13): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = new S2<object>()!; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "new S2<object>()!").WithArguments("nullable reference types", "8.0").WithLocation(8, 13)); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_ValueType_02() { var source = @"struct S<T> where T : class? { static S<object> F(S<object?> s) => s /*T:S<object?>*/ !; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_UserDefinedConversion() { var source = @" struct S { public static implicit operator C?(S s) => new C(); } class C { void M() { C c = new S()!; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_UserDefinedConversion_InArrayInitializer() { var source = @" struct S { public static implicit operator C?(S s) => new C(); } class C { void M(C c) { var a = new[] { c, new S()! }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void SuppressNullableWarning_GenericType() { var source = @"struct S { static void F<TStruct, TRef, TUnconstrained>(TStruct tStruct, TRef tRef, TUnconstrained tUnconstrained) where TStruct : struct where TRef : class { _ = tStruct!; _ = tRef!; _ = tUnconstrained!; } }"; // Feature enabled. var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); // Feature disabled. comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); // Feature disabled (C# 7). comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (6,13): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = tStruct!; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "tStruct!").WithArguments("nullable reference types", "8.0").WithLocation(6, 13), // (7,13): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = tRef!; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "tRef!").WithArguments("nullable reference types", "8.0").WithLocation(7, 13), // (8,13): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = tUnconstrained!; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "tUnconstrained!").WithArguments("nullable reference types", "8.0").WithLocation(8, 13) ); } [Fact] public void SuppressNullableWarning_TypeParameters_01() { var source = @"class C { static void F1<T1>(T1 t1) { default(T1).ToString(); // 1 default(T1)!.ToString(); t1.ToString(); // 2 t1!.ToString(); } static void F2<T2>(T2 t2) where T2 : class { default(T2).ToString(); // 3 default(T2)!.ToString(); // 4 t2.ToString(); t2!.ToString(); } static void F3<T3>(T3 t3) where T3 : struct { default(T3).ToString(); default(T3)!.ToString(); t3.ToString(); t3!.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // default(T1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T1)").WithLocation(5, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(7, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // default(T2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T2)").WithLocation(12, 9) ); } [Fact] public void SuppressNullableWarning_TypeParameters_02() { var source = @"abstract class A<T> { internal abstract void F<U>(out T t, out U u) where U : T; } class B1<T> : A<T> where T : class { internal override void F<U>(out T t1, out U u1) { t1 = default(T)!; t1 = default!; u1 = default(U)!; u1 = default!; } } class B2<T> : A<T> where T : struct { internal override void F<U>(out T t2, out U u2) { t2 = default(T)!; // 1 t2 = default!; // 2 u2 = default(U)!; // 3 u2 = default!; // 4 } } class B3<T> : A<T> { internal override void F<U>(out T t3, out U u3) { t3 = default(T)!; t3 = default!; u3 = default(U)!; u3 = default!; } } class B4 : A<object> { internal override void F<U>(out object t4, out U u4) { t4 = default(object)!; t4 = default!; u4 = default(U)!; u4 = default!; } } class B5 : A<int> { internal override void F<U>(out int t5, out U u5) { t5 = default(int)!; // 5 t5 = default!; // 6 u5 = default(U)!; // 7 u5 = default!; // 8 } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); // https://github.com/dotnet/roslyn/issues/29907: Report error for `default!`. comp.VerifyDiagnostics(); } [Fact] public void SuppressNullableWarning_NonNullOperand() { var source = @"class C { static void F(string? s) { G(""""!); G((new string('a', 1))!); G((s ?? """")!); } static void G(string s) { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void SuppressNullableWarning_InvalidOperand() { var source = @"class C { static void F(C c) { G(F!); G(c.P!); } static void G(object o) { } object P { set { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,11): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor // G(c.P!); Diagnostic(ErrorCode.ERR_PropertyLacksGet, "c.P").WithArguments("C.P").WithLocation(6, 11) ); } [Fact] public void SuppressNullableWarning_InvalidArrayInitializer() { var source = @"class C { static void F() { var a = new object[] { new object(), F! }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_IndexedProperty() { var source0 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Class A Public ReadOnly Property P(i As Integer) As Object Get Return Nothing End Get End Property Public ReadOnly Property Q(Optional i As Integer = 0) As Object Get Return Nothing End Get End Property End Class"; var ref0 = BasicCompilationUtils.CompileToMetadata(source0); var source = @"class B { static object F(A a, int i) { if (i > 0) { return a.P!; } return a.Q!; } }"; var comp = CreateCompilation( new[] { source }, new[] { ref0 }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,20): error CS0856: Indexed property 'A.P' has non-optional arguments which must be provided // return a.P!; Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, "a.P").WithArguments("A.P").WithLocation(7, 20)); } [Fact] public void LocalTypeInference() { var source = @"class C { static void F(string? s, string? t) { if (s != null) { var x = s; G(x); // no warning x = t; } else { var y = s; G(y); // warning y = t; } } static void G(string s) { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (14,15): warning CS8604: Possible null reference argument for parameter 's' in 'void C.G(string s)'. // G(y); // warning Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("s", "void C.G(string s)").WithLocation(14, 15)); } [Fact] public void AssignmentInCondition_01() { var source = @"class C { object P => null; static void F(object o) { C? c; while ((c = o as C) != null) { o = c.P; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,17): warning CS8603: Possible null reference return. // object P => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(3, 17)); } [Fact] public void AssignmentInCondition_02() { var source = @"class C { object? P => null; static void F(object? o) { C? c; while ((c = o as C) != null) { o = c.P; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void StructAsNullableInterface() { var source = @"interface I { void F(); } struct S : I { void I.F() { } } class C { static void F(I? i) { i.F(); } static void Main() { F(new S()); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // i.F(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "i").WithLocation(15, 9)); } [Fact] public void IsNull() { var source = @"class C { static void F1(object o) { } static void F2(object o) { } static void G(object? o) { if (o is null) { F1(o); } else { F2(o); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,16): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F1(object o)'. // F1(o); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.F1(object o)").WithLocation(9, 16)); } [Fact] public void IsInvalidConstant() { var source = @"class C { static void F(object o) { } static void G(object? o) { if (o is F) { F(o); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): error CS0150: A constant value is expected // if (o is F) Diagnostic(ErrorCode.ERR_ConstantExpected, "F").WithLocation(6, 18), // (8,15): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // F(o); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.F(object o)").WithLocation(8, 15)); } [Fact] public void Feature() { var source = @"class C { static object F() => null; static object F(object? o) => o; }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8.WithFeature("staticNullChecking")); comp.VerifyDiagnostics( // (3,26): warning CS8603: Possible null reference return. // static object F() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(3, 26), // (4,35): warning CS8603: Possible null reference return. // static object F(object? o) => o; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(4, 35)); comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8.WithFeature("staticNullChecking", "0")); comp.VerifyDiagnostics( // (3,26): warning CS8603: Possible null reference return. // static object F() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(3, 26), // (4,35): warning CS8603: Possible null reference return. // static object F(object? o) => o; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(4, 35)); comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8.WithFeature("staticNullChecking", "1")); comp.VerifyDiagnostics( // (3,26): warning CS8603: Possible null reference return. // static object F() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(3, 26), // (4,35): warning CS8603: Possible null reference return. // static object F(object? o) => o; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(4, 35)); } [Fact] public void AllowMemberOptOut() { var source1 = @"partial class C { #nullable disable static void F(object o) { } }"; var source2 = @"partial class C { static void G(object o) { } static void M(object? o) { F(o); G(o); } }"; var comp = CreateCompilation( new[] { source1, source2 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static void M(object? o) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 25) ); comp = CreateCompilation( new[] { source1, source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,11): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.G(object o)'. // G(o); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.G(object o)").WithLocation(9, 11)); } [Fact] public void InferLocalNullability() { var source = @"class C { static string? F(string s) => s; static void G(string s) { string x; x = F(s); F(x); string? y = s; y = F(y); F(y); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = F(s); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F(s)").WithLocation(7, 13), // (8,11): warning CS8604: Possible null reference argument for parameter 's' in 'string? C.F(string s)'. // F(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("s", "string? C.F(string s)").WithLocation(8, 11), // (11,11): warning CS8604: Possible null reference argument for parameter 's' in 'string? C.F(string s)'. // F(y); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("s", "string? C.F(string s)").WithLocation(11, 11)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String!", symbol.TypeWithAnnotations.ToTestDisplayString(true)); } [Fact] public void InferLocalType_UsedInDeclaration() { var source = @"using System; using System.Collections.Generic; class C { static T F<T>(IEnumerable<T> e) { throw new NotImplementedException(); } static void G() { var a = new[] { F(a) }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,27): error CS0841: Cannot use local variable 'a' before it is declared // var a = new[] { F(a) }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "a").WithArguments("a").WithLocation(11, 27)); } [Fact] public void InferLocalType_UsedInDeclaration_Script() { var source = @"using System; using System.Collections.Generic; static T F<T>(IEnumerable<T> e) { throw new NotImplementedException(); } var a = new[] { F(a) };"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp8)); comp.VerifyDiagnostics( // (7,5): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition. // var a = new[] { F(a) }; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(7, 5)); } [Fact] public void InferLocalType_UsedBeforeDeclaration() { var source = @"using System; using System.Collections.Generic; class C { static T F<T>(IEnumerable<T> e) { throw new NotImplementedException(); } static void G() { var a = new[] { F(b) }; var b = a; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,27): error CS0841: Cannot use local variable 'b' before it is declared // var a = new[] { F(b) }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "b").WithArguments("b").WithLocation(11, 27)); } [Fact] public void InferLocalType_OutVarError() { var source = @"using System; using System.Collections.Generic; class C { static T F<T>(IEnumerable<T> e) { throw new NotImplementedException(); } static void G() { dynamic d = null!; d.F(out var v); F(v).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,21): error CS8197: Cannot infer the type of implicitly-typed out variable 'v'. // d.F(out var v); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "v").WithArguments("v").WithLocation(12, 21)); } [Fact] public void InferLocalType_OutVarError_Script() { var source = @"using System; using System.Collections.Generic; static T F<T>(IEnumerable<T> e) { throw new NotImplementedException(); } dynamic d = null!; d.F(out var v); F(v).ToString();"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, parseOptions: TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp8)); comp.VerifyDiagnostics( // (8,13): error CS8197: Cannot infer the type of implicitly-typed out variable 'v'. // d.F(out var v); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "v").WithArguments("v").WithLocation(8, 13) ); } /// <summary> /// Default value for non-nullable parameter /// should not result in a warning at the call site. /// </summary> [WorkItem(26626, "https://github.com/dotnet/roslyn/issues/26626")] [Fact] public void ParameterDefaultValue_FromMetadata() { var source0 = @"public class C { public static void F(object o = null) { } }"; var comp0 = CreateCompilation( new[] { source0 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp0.VerifyDiagnostics( // (3,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // public static void F(object o = null) Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(3, 37) ); var ref0 = comp0.EmitToImageReference(); var source1 = @"class Program { static void Main() { C.F(); C.F(null); } }"; var comp1 = CreateCompilation( new[] { source1 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { ref0 }); comp1.VerifyDiagnostics( // (6,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // C.F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 13)); } [Fact] public void ParameterDefaultValue_WithSuppression() { var source0 = @"class C { void F(object o = null!) { } }"; var comp = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [WorkItem(26626, "https://github.com/dotnet/roslyn/issues/26626")] [Fact] public void ParameterDefaultValue_01() { var source = @"class C { const string? S0 = null; const string? S1 = """"; static string? F() => string.Empty; static void F0(string s = null) { } // 1 static void F1(string s = default) { } // 2 static void F2(string s = default(string)) { } // 3 static void F3( string x = (string)null, // 4, 5 string y = (string?)null) { } // 6 static void F4(string s = S0) { } // 7 static void F5(string s = S1) { } // 8 static void F6(string s = F()) { } // 9 static void M() { F0(); F1(); F2(); F3(); F4(); F5(); F6(); F0(null); // 10 F0(string.Empty); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F0(string s = null) { } // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 31), // (7,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F1(string s = default) { } // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(7, 31), // (8,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F2(string s = default(string)) { } // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default(string)").WithLocation(8, 31), // (10,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // string x = (string)null, // 4, 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(10, 20), // (10,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // string x = (string)null, // 4, 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string)null").WithLocation(10, 20), // (11,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // string y = (string?)null) { } // 6 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string?)null").WithLocation(11, 20), // (12,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F4(string s = S0) { } // 7 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "S0").WithLocation(12, 31), // (13,31): warning CS8601: Possible null reference assignment. // static void F5(string s = S1) { } // 8 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "S1").WithLocation(13, 31), // (14,31): error CS1736: Default parameter value for 's' must be a compile-time constant // static void F6(string s = F()) { } // 9 Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("s").WithLocation(14, 31), // (14,31): warning CS8601: Possible null reference assignment. // static void F6(string s = F()) { } // 9 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "F()").WithLocation(14, 31), // (24,12): warning CS8625: Cannot convert null literal to non-nullable reference type. // F0(null); // 10 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(24, 12) ); } [WorkItem(26626, "https://github.com/dotnet/roslyn/issues/26626")] [Fact] public void ParameterDefaultValue_02() { var source = @"class C { const string? S0 = null; static void F0(string s = null!) { } static void F1( string x = (string)null!, string y = ((string)null)!) { } // 1 static void F2( string x = default!, string y = default(string)!) { } static void F3(string s = S0!) { } static void F4(string x = (string)null) { } // 2, 3 static void F5(string? y = (string)null) { } // 4 static void M() { F0(); F1(); F2(); F3(); F1(x: null); // 5 F1(y: null); // 6 F2(null!, null); // 7 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string y = ((string)null)!) { } // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(7, 21), // (12,31): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F4(string x = (string)null) { } // 2, 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(12, 31), // (12,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F4(string x = (string)null) { } // 2, 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string)null").WithLocation(12, 31), // (13,32): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F5(string? y = (string)null) { } // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(13, 32), // (20,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F1(x: null); // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 15), // (21,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F1(y: null); // 6 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 15), // (22,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // F2(null!, null); // 7 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(22, 19) ); } [WorkItem(26626, "https://github.com/dotnet/roslyn/issues/26626")] [WorkItem(29910, "https://github.com/dotnet/roslyn/issues/29910")] [Fact] public void ParameterDefaultValue_03() { var source = @"interface I { } class C : I { } class P { static void F0<T>(T t = default) { } // 1 static void F1<T>(T t = null) where T : class { } // 2 static void F2<T>(T t = default) where T : struct { } static void F3<T>(T t = default) where T : new() { } // 3 static void F4<T>(T t = null) where T : C { } // 4 static void F5<T>(T t = default) where T : I { } // 5 static void F6<T, U>(T t = default) where T : U { } // 6 static void G0() { F0<object>(); F0<object>(default); // 7 F0(new object()); F1<object>(); F1<object>(default); // 8 F1(new object()); F2<int>(); F2<int>(default); F2(2); F3<object>(); F3<object>(default); // 9 F3(new object()); F4<C>(); F4<C>(default); // 10 F4(new C()); F5<I>(); F5<I>(default); // 11 F5(new C()); F6<object, object>(); F6<object, object>(default); // 12 F6<object, object>(new object()); } static void G0<T>() { F0<T>(); F0<T>(default); // 13 F6<T, T>(); F6<T, T>(default); // 14 } static void G1<T>() where T : class { F0<T>(); F0<T>(default); // 15 F1<T>(); F1<T>(default); // 16 F6<T, T>(); F6<T, T>(default); // 17 } static void G2<T>() where T : struct { F0<T>(); F0<T>(default); F2<T>(); F2<T>(default); F3<T>(); F3<T>(default); F6<T, T>(); F6<T, T>(default); } static void G3<T>() where T : new() { F0<T>(); F0<T>(default); // 18 F0<T>(new T()); F3<T>(); F3<T>(default); // 19 F3<T>(new T()); F6<T, T>(); F6<T, T>(default); // 20 F6<T, T>(new T()); } static void G4<T>() where T : C { F0<T>(); F0<T>(default); // 21 F1<T>(); F1<T>(default); // 22 F4<T>(); F4<T>(default); // 23 F5<T>(); F5<T>(default); // 24 F6<T, T>(); F6<T, T>(default); // 25 } static void G5<T>() where T : I { F0<T>(); F0<T>(default); // 26 F5<T>(); F5<T>(default); // 27 F6<T, T>(); F6<T, T>(default); // 28 } static void G6<T, U>() where T : U { F0<T>(); F0<T>(default); // 29 F6<T, U>(); F6<T, U>(default); // 30 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,29): warning CS8601: Possible null reference assignment. // static void F0<T>(T t = default) { } // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(5, 29), // (6,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F1<T>(T t = null) where T : class { } // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 29), // (8,29): warning CS8601: Possible null reference assignment. // static void F3<T>(T t = default) where T : new() { } // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(8, 29), // (9,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F4<T>(T t = null) where T : C { } // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 29), // (10,29): warning CS8601: Possible null reference assignment. // static void F5<T>(T t = default) where T : I { } // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(10, 29), // (11,32): warning CS8601: Possible null reference assignment. // static void F6<T, U>(T t = default) where T : U { } // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(11, 32), // (15,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // F0<object>(default); // 7 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(15, 20), // (18,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // F1<object>(default); // 8 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(18, 20), // (24,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // F3<object>(default); // 9 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(24, 20), // (27,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F4<C>(default); // 10 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(27, 15), // (30,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F5<I>(default); // 11 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(30, 15), // (33,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // F6<object, object>(default); // 12 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(33, 28), // (39,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F0<T>(T t = default(T))'. // F0<T>(default); // 13 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F0<T>(T t = default(T))").WithLocation(39, 15), // (41,18): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F6<T, T>(T t = default(T))'. // F6<T, T>(default); // 14 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F6<T, T>(T t = default(T))").WithLocation(41, 18), // (46,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F0<T>(default); // 15 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(46, 15), // (48,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F1<T>(default); // 16 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(48, 15), // (50,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // F6<T, T>(default); // 17 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(50, 18), // (66,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F0<T>(T t = default(T))'. // F0<T>(default); // 18 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F0<T>(T t = default(T))").WithLocation(66, 15), // (69,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F3<T>(T t = default(T))'. // F3<T>(default); // 19 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F3<T>(T t = default(T))").WithLocation(69, 15), // (72,18): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F6<T, T>(T t = default(T))'. // F6<T, T>(default); // 20 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F6<T, T>(T t = default(T))").WithLocation(72, 18), // (78,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F0<T>(default); // 21 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(78, 15), // (80,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F1<T>(default); // 22 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(80, 15), // (82,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F4<T>(default); // 23 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(82, 15), // (84,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F5<T>(default); // 24 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(84, 15), // (86,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // F6<T, T>(default); // 25 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(86, 18), // (91,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F0<T>(T t = default(T))'. // F0<T>(default); // 26 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F0<T>(T t = default(T))").WithLocation(91, 15), // (93,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F5<T>(T t = default(T))'. // F5<T>(default); // 27 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F5<T>(T t = default(T))").WithLocation(93, 15), // (95,18): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F6<T, T>(T t = default(T))'. // F6<T, T>(default); // 28 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F6<T, T>(T t = default(T))").WithLocation(95, 18), // (100,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F0<T>(T t = default(T))'. // F0<T>(default); // 29 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F0<T>(T t = default(T))").WithLocation(100, 15), // (102,18): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F6<T, U>(T t = default(T))'. // F6<T, U>(default); // 30 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F6<T, U>(T t = default(T))").WithLocation(102, 18) ); // No warnings with C#7.3. comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); comp.VerifyDiagnostics( // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.3", "8.0").WithLocation(1, 1) ); } [Fact] public void NonNullTypesInCSharp7_InSource() { var source = @" #nullable enable public class C { public static string field; } public class D { #nullable enable public static string field; #nullable enable public static string Method(string s) => throw null; #nullable enable public static string Property { get; set; } #nullable enable public static event System.Action Event; #nullable disable void M() { C.field = null; D.field = null; D.Method(null); D.Property = null; D.Event(); } } "; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7, skipUsesIsNullable: true); comp.VerifyDiagnostics( // (2,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(2, 2), // (9,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(9, 2), // (12,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(12, 2), // (15,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(15, 2), // (18,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(18, 2), // (20,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // #nullable disable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(20, 2) ); } [Fact] public void NonNullTypesInCSharp7_FromMetadata() { var libSource = @"#nullable enable #pragma warning disable 8618 public class C { public static string field; } public class D { #nullable enable public static string field; #nullable enable public static string Method(string s) => throw null!; #nullable enable public static string Property { get; set; } #nullable enable public static event System.Action Event; } "; var libComp = CreateCompilation(new[] { libSource }); libComp.VerifyDiagnostics( // (19,39): warning CS0067: The event 'D.Event' is never used // public static event System.Action Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("D.Event").WithLocation(19, 39) ); var source = @" class Client { void M() { C.field = null; D.field = null; D.Method(null); D.Property = null; D.Event(); } } "; var comp = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (10,11): error CS0079: The event 'D.Event' can only appear on the left hand side of += or -= // D.Event(); Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "Event").WithArguments("D.Event").WithLocation(10, 11) ); var comp2 = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() }); comp2.VerifyDiagnostics( // (10,11): error CS0079: The event 'D.Event' can only appear on the left hand side of += or -= // D.Event(); Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "Event").WithArguments("D.Event").WithLocation(10, 11) ); } [WorkItem(26626, "https://github.com/dotnet/roslyn/issues/26626")] [Fact] public void ParameterDefaultValue_04() { var source = @"partial class C { static partial void F(object? x = null, object y = null); static partial void F(object? x, object y) { } static partial void G(object x, object? y); static partial void G(object x = null, object? y = null) { } static void M() { F(); G(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,34): warning CS1066: The default value specified for parameter 'x' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // static partial void G(object x = null, object? y = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "x").WithArguments("x").WithLocation(6, 34), // (6,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // static partial void G(object x = null, object? y = null) { } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 38), // (6,52): warning CS1066: The default value specified for parameter 'y' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // static partial void G(object x = null, object? y = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "y").WithArguments("y").WithLocation(6, 52), // (3,56): warning CS8625: Cannot convert null literal to non-nullable reference type. // static partial void F(object? x = null, object y = null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(3, 56), // (10,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.G(object, object?)' // G(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "G").WithArguments("x", "C.G(object, object?)").WithLocation(10, 9) ); } [WorkItem(40818, "https://github.com/dotnet/roslyn/issues/40818")] [Fact] public void ParameterDefaultValue_05() { var source = @" class C { T M1<T>(T t = default) // 1 => t; T M2<T>(T t = default) where T : class? // 2 => t; T M3<T>(T t = default) where T : class // 3 => t; T M4<T>(T t = default) where T : notnull // 4 => t; T M5<T>(T? t = default) where T : struct => t.Value; // 5 T M6<T>(T? t = default(T)) where T : struct // 6 => t.Value; // 7 }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); var expected = new[] { // (4,19): warning CS8601: Possible null reference assignment. // T M1<T>(T t = default) // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(4, 19), // (7,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // T M2<T>(T t = default) where T : class? // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(7, 19), // (10,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // T M3<T>(T t = default) where T : class // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(10, 19), // (13,19): warning CS8601: Possible null reference assignment. // T M4<T>(T t = default) where T : notnull // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(13, 19), // (17,12): warning CS8629: Nullable value type may be null. // => t.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(17, 12), // (19,16): error CS1770: A value of type 'T' cannot be used as default parameter for nullable parameter 't' because 'T' is not a simple type // T M6<T>(T? t = default(T)) where T : struct // 6 Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "t").WithArguments("T", "t").WithLocation(19, 16), // (20,12): warning CS8629: Nullable value type may be null. // => t.Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(20, 12) }; comp.VerifyDiagnostics(expected); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(expected); } [WorkItem(40818, "https://github.com/dotnet/roslyn/issues/40818")] [WorkItem(40975, "https://github.com/dotnet/roslyn/issues/40975")] [Fact] public void ParameterDefaultValue_06() { var source = @" using System.Diagnostics.CodeAnalysis; class C { string M1(string? s = null) => s; // 1 string M2(string? s = ""a"") => s; // 2 int M3(int? i = null) => i.Value; // 3 int M4(int? i = 1) => i.Value; // 4 string M5([AllowNull] string s = null) => s; // 5 string M6([AllowNull] string s = ""a"") => s; // 6 int M7([DisallowNull] int? i = null) // 7 => i.Value; int M8([DisallowNull] int? i = 1) => i.Value; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,12): warning CS8603: Possible null reference return. // => s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(7, 12), // (10,12): warning CS8603: Possible null reference return. // => s; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(10, 12), // (13,12): warning CS8629: Nullable value type may be null. // => i.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(13, 12), // (16,12): warning CS8629: Nullable value type may be null. // => i.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(16, 12), // (19,12): warning CS8603: Possible null reference return. // => s; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(19, 12), // (22,12): warning CS8603: Possible null reference return. // => s; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(22, 12), // (24,36): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // int M7([DisallowNull] int? i = null) // 7 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "null").WithLocation(24, 36) ); } [Fact, WorkItem(47344, "https://github.com/dotnet/roslyn/issues/47344")] public void ParameterDefaultValue_07() { var source = @" record Rec1<T>(T t = default) // 1, 2 { } record Rec2<T>(T t = default) // 2 { T t { get; } = t; } record Rec3<T>(T t = default) // 3, 4 { T t { get; } = default!; } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (2,22): warning CS8601: Possible null reference assignment. // record Rec1<T>(T t = default) // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(2, 22), // (6,22): warning CS8601: Possible null reference assignment. // record Rec2<T>(T t = default) // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(6, 22), // (11,18): warning CS8907: Parameter 't' is unread. Did you forget to use it to initialize the property with that name? // record Rec3<T>(T t = default) // 3, 4 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "t").WithArguments("t").WithLocation(11, 18), // (11,22): warning CS8601: Possible null reference assignment. // record Rec3<T>(T t = default) // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(11, 22) ); } [Fact, WorkItem(43399, "https://github.com/dotnet/roslyn/issues/43399")] public void ParameterDefaultValue_08() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; public class C { public void M1([Optional, DefaultParameterValue(null)] object obj) // 1 { obj.ToString(); } public void M2([Optional, DefaultParameterValue(default(object))] object obj) // 2 { obj.ToString(); } public void M3([Optional, DefaultParameterValue(""a"")] object obj) { obj.ToString(); } public void M4([AllowNull, Optional, DefaultParameterValue(null)] object obj) { obj.ToString(); // 3 } public void M5([Optional, DefaultParameterValue((object)null)] object obj) // 4, 5 { obj.ToString(); } } "; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // public void M1([Optional, DefaultParameterValue(null)] object obj) // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "[Optional, DefaultParameterValue(null)] object obj").WithLocation(7, 20), // (11,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // public void M2([Optional, DefaultParameterValue(default(object))] object obj) // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "[Optional, DefaultParameterValue(default(object))] object obj").WithLocation(11, 20), // (21,9): warning CS8602: Dereference of a possibly null reference. // obj.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(21, 9), // (23,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // public void M5([Optional, DefaultParameterValue((object)null)] object obj) // 3, 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "[Optional, DefaultParameterValue((object)null)] object obj").WithLocation(23, 20), // (23,53): warning CS8600: Converting null literal or possible null value to non-nullable type. // public void M5([Optional, DefaultParameterValue((object)null)] object obj) // 3, 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)null").WithLocation(23, 53) ); } [Fact, WorkItem(43399, "https://github.com/dotnet/roslyn/issues/43399")] public void ParameterDefaultValue_09() { var source = @" using System.Runtime.InteropServices; public class C { public void M1([Optional, DefaultParameterValue(null!)] object obj) { obj.ToString(); } public void M2([Optional, DefaultParameterValue(default)] object obj) { obj.ToString(); } public void M3([Optional, DefaultParameterValue(null)] object obj = null) { obj.ToString(); } } "; // 'M1' doesn't seem like a scenario where an error or warning should be given. // However, we can't round trip the concept that the parameter default value was suppressed. // Therefore even if we fixed this, this usage could result in strange corner case behaviors when // emitting the method to metadata and calling it in source. var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,31): error CS8017: The parameter has multiple distinct default values. // public void M1([Optional, DefaultParameterValue(null!)] object obj) Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "DefaultParameterValue(null!)").WithLocation(5, 31), // (9,31): error CS8017: The parameter has multiple distinct default values. // public void M2([Optional, DefaultParameterValue(default)] object obj) Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "DefaultParameterValue(default)").WithLocation(9, 31), // (13,21): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute // public void M3([Optional, DefaultParameterValue(null)] object obj = null) Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "Optional").WithLocation(13, 21), // (13,31): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute // public void M3([Optional, DefaultParameterValue(null)] object obj = null) Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "DefaultParameterValue").WithLocation(13, 31), // (13,73): warning CS8625: Cannot convert null literal to non-nullable reference type. // public void M3([Optional, DefaultParameterValue(null)] object obj = null) Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 73), // (13,73): error CS8017: The parameter has multiple distinct default values. // public void M3([Optional, DefaultParameterValue(null)] object obj = null) Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "null").WithLocation(13, 73) ); } [Fact, WorkItem(48847, "https://github.com/dotnet/roslyn/issues/48847")] public void ParameterDefaultValue_10() { var source = @" public abstract class C1 { public abstract void M1(string s = null); // 1 public abstract void M2(string? s = null); } public interface I1 { void M1(string s = null); // 2 void M2(string? s = null); } public delegate void D1(string s = null); // 3 public delegate void D2(string? s = null); "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,40): warning CS8625: Cannot convert null literal to non-nullable reference type. // public abstract void M1(string s = null); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 40), // (10,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // void M1(string s = null); // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 24), // (14,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // public delegate void D1(string s = null); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 36) ); } [Fact, WorkItem(48844, "https://github.com/dotnet/roslyn/issues/48844")] public void ParameterDefaultValue_11() { var source = @" delegate void D1<T>(T t = default); // 1 delegate void D2<T>(T? t = default); class C { void M() { D1<string> d1 = str => str.ToString(); d1(); D2<string> d2 = str => str.ToString(); // 2 d2(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (2,27): warning CS8601: Possible null reference assignment. // delegate void D1<T>(T t = default); // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(2, 27), // (12,32): warning CS8602: Dereference of a possibly null reference. // D2<string> d2 = str => str.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "str").WithLocation(12, 32) ); } [Fact, WorkItem(48848, "https://github.com/dotnet/roslyn/issues/48848")] public void ParameterDefaultValue_12() { var source = @" public class Base1<T> { public virtual void M(T t = default) { } // 1 } public class Override1 : Base1<string> { public override void M(string s) { } } public class Base2<T> { public virtual void M(T? t = default) { } } public class Override2 : Base2<string> { public override void M(string s) { } // 2 } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,33): warning CS8601: Possible null reference assignment. // public virtual void M(T t = default) { } // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(4, 33), // (19,26): warning CS8765: Nullability of type of parameter 's' doesn't match overridden member (possibly because of nullability attributes). // public override void M(string s) { } // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("s").WithLocation(19, 26) ); } [Fact] public void InvalidThrowTerm() { var source = @"class C { static string F(string s) => s + throw new System.Exception(); }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (3,38): error CS1525: Invalid expression term 'throw' // static string F(string s) => s + throw new System.Exception(); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new System.Exception()").WithArguments("throw").WithLocation(3, 38)); } [Fact] public void UnboxingConversion_01() { var source = @"using System.Collections.Generic; class Program { static IEnumerator<T> M<T>() => default(T); }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,37): error CS0266: Cannot implicitly convert type 'T' to 'System.Collections.Generic.IEnumerator<T>'. An explicit conversion exists (are you missing a cast?) // static IEnumerator<T> M<T>() => default(T); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "default(T)").WithArguments("T", "System.Collections.Generic.IEnumerator<T>").WithLocation(4, 37), // (4,37): warning CS8603: Possible null reference return. // static IEnumerator<T> M<T>() => default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(4, 37) ); } [Fact] [WorkItem(33359, "https://github.com/dotnet/roslyn/issues/33359")] public void UnboxingConversion_02() { var source = @"class C { interface I { } struct S : I { } static void Main() { M<S, I?>(null); } static void M<T, V>(V v) where T : struct, V { var t = ((T) v); // 1 } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (13,18): warning CS8605: Unboxing a possibly null value. // var t = ((T) v); // 1 Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(T) v").WithLocation(13, 18)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_03() { var source = @"public interface I { } public struct S : I { static void M1(I? i) { S s = (S)i; // 1 _ = i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8605: Unboxing a possibly null value. // S s = (S)i; // 1 Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(S)i").WithLocation(7, 15)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_04() { var source = @"public interface I { } public struct S : I { static void M1(I? i) { S s = (S)i!; _ = i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_05() { var source = @"public interface I { } public class C { public I? i = new S(); } public struct S : I { static void M1(C? c) { S s = (S)c?.i; // 1 _ = c.ToString(); _ = c.i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,15): warning CS8605: Unboxing a possibly null value. // S s = (S)c?.i; // 1 Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(S)c?.i").WithLocation(12, 15)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_06() { var source = @"public interface I { } public class C { public I? i = new S(); } public struct S : I { static void M1(C? c) { S? s = (S?)c?.i; _ = c.ToString(); // 1 _ = c.i.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(13, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = c.i.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.i").WithLocation(14, 13)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_07() { var source = @"public interface I { } public struct S : I { static void M1(I? i) { S s = (S)i; // 1 _ = i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8605: Unboxing a possibly null value. // S s = (S)i; // 1 Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(S)i").WithLocation(7, 15)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_08() { var source = @"public interface I { } public class C { static void M1<T>(I? i) { T t = (T)i; _ = i.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t = (T)i; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)i").WithLocation(7, 15), // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = i.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "i").WithLocation(8, 13)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_09() { var source = @"public interface I { } public class C { static void M1<T>(I? i) where T : struct { T t = (T)i; // 1 _ = i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8605: Unboxing a possibly null value. // T t = (T)i; // 1 Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(T)i").WithLocation(7, 15)); } [Fact] public void DeconstructionConversion_NoDeconstructMethod() { var source = @"class C { static void F(C c) { var (x, y) = c; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,22): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // var (x, y) = c; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "c").WithArguments("C", "Deconstruct").WithLocation(5, 22), // (5,22): error CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type. // var (x, y) = c; Diagnostic(ErrorCode.ERR_MissingDeconstruct, "c").WithArguments("C", "2").WithLocation(5, 22), // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = c; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(5, 14), // (5,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = c; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void ConditionalAccessDelegateInvoke() { var source = @"using System; class C<T> { static T F(Func<T>? f) { return f?.Invoke(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,17): error CS0023: Operator '?' cannot be applied to operand of type 'T' // return f?.Invoke(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(6, 17) ); } [Fact] public void NonNullTypes_DecodeAttributeCycle_01() { var source = @"using System.Runtime.InteropServices; interface I { int P { get; } } [StructLayout(LayoutKind.Auto)] struct S : I { int I.P => 0; }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void NonNullTypes_DecodeAttributeCycle_01_WithEvent() { var source = @"using System; using System.Runtime.InteropServices; interface I { event Func<int> E; } [StructLayout(LayoutKind.Auto)] struct S : I { event Func<int> I.E { add => throw null!; remove => throw null!; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void NonNullTypes_DecodeAttributeCycle_02() { var source = @"[A(P)] class A : System.Attribute { string P => null; }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (1,4): error CS0120: An object reference is required for the non-static field, method, or property 'A.P' // [A(P)] Diagnostic(ErrorCode.ERR_ObjectRequired, "P").WithArguments("A.P").WithLocation(1, 4), // (1,2): error CS1729: 'A' does not contain a constructor that takes 1 arguments // [A(P)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "A(P)").WithArguments("A", "1").WithLocation(1, 2), // (4,17): warning CS8603: Possible null reference return. // string P => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(4, 17)); } [Fact] [WorkItem(29954, "https://github.com/dotnet/roslyn/issues/29954")] public void UnassignedOutParameterClass() { var source = @"class C { static void G(out C? c) { c.ToString(); // 1 c = null; c.ToString(); // 2 c = new C(); c.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS0269: Use of unassigned out parameter 'c' // c.ToString(); // 1 Diagnostic(ErrorCode.ERR_UseDefViolationOut, "c").WithArguments("c").WithLocation(5, 9), // (5,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(5, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(7, 9)); } [Fact] public void UnassignedOutParameterClassField() { var source = @"class C { #pragma warning disable 0649 object? F; static void G(out C c) { object o = c.F; c.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,20): error CS0269: Use of unassigned out parameter 'c' // object o = c.F; Diagnostic(ErrorCode.ERR_UseDefViolationOut, "c").WithArguments("c").WithLocation(7, 20), // (5,17): error CS0177: The out parameter 'c' must be assigned to before control leaves the current method // static void G(out C c) Diagnostic(ErrorCode.ERR_ParamUnassigned, "G").WithArguments("c").WithLocation(5, 17), // (7,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object o = c.F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F").WithLocation(7, 20), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F").WithLocation(8, 9)); } [Fact] public void UnassignedOutParameterStructField() { var source = @"struct S { #pragma warning disable 0649 object? F; static void G(out S s) { object o = s.F; s.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,20): error CS0170: Use of possibly unassigned field 'F' // object o = s.F; Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.F").WithArguments("F").WithLocation(7, 20), // (5,17): error CS0177: The out parameter 's' must be assigned to before control leaves the current method // static void G(out S s) Diagnostic(ErrorCode.ERR_ParamUnassigned, "G").WithArguments("s").WithLocation(5, 17), // (7,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object o = s.F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s.F").WithLocation(7, 20), // (8,9): warning CS8602: Dereference of a possibly null reference. // s.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.F").WithLocation(8, 9) ); } [Fact] public void UnassignedLocalField() { var source = @"class C { static void F() { S s; C c; c = s.F; s.F.ToString(); } } struct S { internal C? F; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): error CS0170: Use of possibly unassigned field 'F' // c = s.F; Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.F").WithArguments("F").WithLocation(7, 13), // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = s.F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s.F").WithLocation(7, 13), // (8,9): warning CS8602: Dereference of a possibly null reference. // s.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.F").WithLocation(8, 9), // (13,17): warning CS0649: Field 'S.F' is never assigned to, and will always have its default value null // internal C? F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("S.F", "null").WithLocation(13, 17) ); } [Fact] public void UnassignedLocalField_Conditional() { var source = @"class C { static void F(bool b) { S s; object o; if (b) { s.F = new object(); s.G = new object(); } else { o = s.F; } o = s.G; } } struct S { internal object? F; internal object? G; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): error CS0170: Use of possibly unassigned field 'F' // o = s.F; Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.F").WithArguments("F").WithLocation(14, 17), // (14,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = s.F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s.F").WithLocation(14, 17), // (16,13): error CS0170: Use of possibly unassigned field 'G' // o = s.G; Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.G").WithArguments("G").WithLocation(16, 13), // (16,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = s.G; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s.G").WithLocation(16, 13) ); } [Fact] public void UnassignedLocalProperty() { var source = @"class C { static void F() { S s; C c; c = s.P; s.P.ToString(); } } struct S { internal C? P { get => null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = s.P; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s.P").WithLocation(7, 13), // (8,9): warning CS8602: Dereference of a possibly null reference. // s.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.P").WithLocation(8, 9)); } [Fact] public void UnassignedClassAutoProperty() { var source = @"class C { object? P { get; } void M(out object o) { o = P; P.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8601: Possible null reference assignment. // o = P; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "P").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "P").WithLocation(7, 9)); } [Fact] public void UnassignedClassAutoProperty_Constructor() { var source = @"class C { object? P { get; } C(out object o) { o = P; P.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8601: Possible null reference assignment. // o = P; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "P").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "P").WithLocation(7, 9)); } [Fact] public void UnassignedStructAutoProperty() { var source = @"struct S { object? P { get; } void M(out object o) { o = P; P.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8601: Possible null reference assignment. // o = P; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "P").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "P").WithLocation(7, 9)); } [Fact] public void UnassignedStructAutoProperty_Constructor() { var source = @"struct S { object? P { get; } S(out object o) { o = P; P.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): error CS8079: Use of possibly unassigned auto-implemented property 'P' // o = P; Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "P").WithArguments("P").WithLocation(6, 13), // (4,5): error CS0843: Auto-implemented property 'S.P' must be fully assigned before control is returned to the caller. // S(out object o) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "S").WithArguments("S.P").WithLocation(4, 5), // (6,13): warning CS8601: Possible null reference assignment. // o = P; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "P").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "P").WithLocation(7, 9) ); } [Fact] public void ParameterField_Class() { var source = @"class C { #pragma warning disable 0649 object? F; static void M(C x) { C y = x; object z = y.F; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object z = y.F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y.F").WithLocation(8, 20)); } [Fact] public void ParameterField_Struct() { var source = @"struct S { #pragma warning disable 0649 object? F; static void M(S x) { S y = x; object z = y.F; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object z = y.F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y.F").WithLocation(8, 20)); } [Fact] public void InstanceFieldStructTypeExpressionReceiver() { var source = @"struct S { #pragma warning disable 0649 object? F; void M() { S.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): error CS0120: An object reference is required for the non-static field, method, or property 'S.F' // S.F.ToString(); Diagnostic(ErrorCode.ERR_ObjectRequired, "S.F").WithArguments("S.F").WithLocation(7, 9)); } [Fact] public void InstanceFieldPrimitiveRecursiveStruct() { var source = @"#pragma warning disable 0649 namespace System { public class Object { public int GetHashCode() => 0; } public abstract class ValueType { } public struct Void { } public struct Int32 { Int32 _value; object? _f; void M() { _value = _f.GetHashCode(); } } public class String { } public struct Boolean { } public struct Enum { } public class Exception { } public class Attribute { } public class AttributeUsageAttribute : Attribute { public AttributeUsageAttribute(AttributeTargets validOn) => throw null!; public bool AllowMultiple { get; set; } } public enum AttributeTargets { Assembly = 1, Module = 2, Class = 4, Struct = 8, Enum = 16, Constructor = 32, Method = 64, Property = 128, Field = 256, Event = 512, Interface = 1024, Parameter = 2048, Delegate = 4096, ReturnValue = 8192, GenericParameter = 16384, All = 32767 } public class ObsoleteAttribute : Attribute { public ObsoleteAttribute(string message) => throw null!; } }"; var comp = CreateEmptyCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,22): warning CS8602: Dereference of a possibly null reference. // _value = _f.GetHashCode(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "_f").WithLocation(16, 22) ); } [Fact] public void Pointer() { var source = @"class C { static unsafe void F(int* p) { *p = 0; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(TestOptions.UnsafeReleaseDll)); comp.VerifyDiagnostics(); } [Fact] public void TaskMethodReturningNull() { var source = @"using System.Threading.Tasks; class C { static Task F0() => null; static Task<string> F1() => null; static Task<string?> F2() { return null; } static Task<T> F3<T>() { return default; } static Task<T> F4<T>() { return default(Task<T>); } static Task<T> F5<T>() where T : class { return null; } static Task<T?> F6<T>() where T : class => null; static Task? G0() => null; static Task<string>? G1() => null; static Task<T>? G3<T>() { return default; } static Task<T?>? G6<T>() where T : class => null; }"; var comp = CreateCompilationWithMscorlib46(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,25): warning CS8603: Possible null reference return. // static Task F0() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(4, 25), // (5,33): warning CS8603: Possible null reference return. // static Task<string> F1() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(5, 33), // (6,40): warning CS8603: Possible null reference return. // static Task<string?> F2() { return null; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 40), // (7,37): warning CS8603: Possible null reference return. // static Task<T> F3<T>() { return default; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(7, 37), // (8,37): warning CS8603: Possible null reference return. // static Task<T> F4<T>() { return default(Task<T>); } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(Task<T>)").WithLocation(8, 37), // (9,53): warning CS8603: Possible null reference return. // static Task<T> F5<T>() where T : class { return null; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(9, 53), // (10,48): warning CS8603: Possible null reference return. // static Task<T?> F6<T>() where T : class => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(10, 48)); } // https://github.com/dotnet/roslyn/issues/29957: Should not report WRN_NullReferenceReturn for F0. [WorkItem(23275, "https://github.com/dotnet/roslyn/issues/23275")] [WorkItem(29957, "https://github.com/dotnet/roslyn/issues/29957")] [Fact] public void AsyncTaskMethodReturningNull() { var source = @"#pragma warning disable 1998 using System.Threading.Tasks; class C { static async Task F0() { return null; } static async Task<string> F1() => null; static async Task<string?> F2() { return null; } static async Task<T> F3<T>() { return default; } static async Task<T> F4<T>() { return default(T); } static async Task<T> F5<T>() where T : class { return null; } static async Task<T?> F6<T>() where T : class => null; static async Task? G0() { return null; } static async Task<string>? G1() => null; static async Task<T>? G3<T>() { return default; } static async Task<T?>? G6<T>() where T : class => null; }"; var comp = CreateCompilationWithMscorlib46(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,30): error CS1997: Since 'C.F0()' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'? // static async Task F0() { return null; } Diagnostic(ErrorCode.ERR_TaskRetNoObjectRequired, "return").WithArguments("C.F0()").WithLocation(5, 30), // (6,39): warning CS8603: Possible null reference return. // static async Task<string> F1() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 39), // (8,43): warning CS8603: Possible null reference return. // static async Task<T> F3<T>() { return default; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(8, 43), // (9,43): warning CS8603: Possible null reference return. // static async Task<T> F4<T>() { return default(T); } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(9, 43), // (10,59): warning CS8603: Possible null reference return. // static async Task<T> F5<T>() where T : class { return null; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(10, 59), // (12,31): error CS1997: Since 'C.G0()' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'? // static async Task? G0() { return null; } Diagnostic(ErrorCode.ERR_TaskRetNoObjectRequired, "return").WithArguments("C.G0()").WithLocation(12, 31), // (13,40): warning CS8603: Possible null reference return. // static async Task<string>? G1() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(13, 40), // (14,44): warning CS8603: Possible null reference return. // static async Task<T>? G3<T>() { return default; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(14, 44)); } [Fact] public void IncrementWithErrors() { var source = @"using System.Threading.Tasks; class C { static async Task<int> F(ref int i) { return await Task.Run(() => i++); } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (4,38): error CS1988: Async methods cannot have ref or out parameters // static async Task<int> F(ref int i) Diagnostic(ErrorCode.ERR_BadAsyncArgType, "i").WithLocation(4, 38), // (6,37): error CS1628: Cannot use ref or out parameter 'i' inside an anonymous method, lambda expression, or query expression // return await Task.Run(() => i++); Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "i").WithArguments("i").WithLocation(6, 37)); } [Fact] public void NullCastToValueType() { var source = @"struct S { } class C { static void M() { S s = (S)null; s.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,15): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type // S s = (S)null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(S)null").WithArguments("S").WithLocation(6, 15)); } [Fact] public void NullCastToUnannotatableReferenceTypedTypeParameter() { var source = @"struct S { } class C { static T M1<T>() where T: class? { return (T)null; // 1 } static T M2<T>() where T: C? { return (T)null; // 2 } static T M3<T>() where T: class? { return null; // 3 } static T M4<T>() where T: C? { return null; // 4 } static T M5<T>() where T: class? { return (T)null!; } static T M6<T>() where T: C? { return (T)null!; } static T M7<T>() where T: class? { return null!; } static T M8<T>() where T: C? { return null!; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,16): warning CS8603: Possible null reference return. // return (T)null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)null").WithLocation(6, 16), // (10,16): warning CS8603: Possible null reference return. // return (T)null; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)null").WithLocation(10, 16), // (14,16): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(14, 16), // (18,16): warning CS8603: Possible null reference return. // return null; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(18, 16)); } [Fact] public void LiftedUserDefinedConversion() { var source = @"#pragma warning disable 0649 struct A<T> { public static implicit operator B<T>(A<T> a) => new B<T>(); } struct B<T> { internal T F; } class C { static void F(A<object>? x, A<object?>? y) { B<object>? z = x; z?.F.ToString(); B<object?>? w = y; w?.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,11): warning CS8602: Dereference of a possibly null reference. // w?.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, ".F").WithLocation(17, 11)); } [Fact] public void LiftedBinaryOperator() { var source = @"struct A<T> { public static A<T> operator +(A<T> a1, A<T> a2) => throw null!; } class C2 { static void F(A<object>? x, A<object>? y) { var sum1 = (x + y)/*T:A<object!>?*/; sum1.ToString(); if (x == null || y == null) return; var sum2 = (x + y)/*T:A<object!>?*/; sum2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void GroupBy() { var source = @"using System.Linq; class Program { static void Main() { var items = from i in Enumerable.Range(0, 3) group (long)i by i; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } // Tests for NullableWalker.HasImplicitTypeArguments. [Fact] public void ExplicitTypeArguments() { var source = @"interface I<T> { } class C { C P => throw new System.Exception(); I<T> F<T>(T t) { throw new System.Exception(); } static void M(C c) { c.P.F<object>(string.Empty); (new[]{ c })[0].F<object>(string.Empty); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void MultipleConversions_01() { var source = @"class A { public static implicit operator C(A a) => new C(); } class B : A { } class C { static void F(B? x, B y) { C c; c = x; // (ImplicitUserDefined)(ImplicitReference) c = y; // (ImplicitUserDefined)(ImplicitReference) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8604: Possible null reference argument for parameter 'a' in 'A.implicit operator C(A a)'. // c = x; // (ImplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("a", "A.implicit operator C(A a)").WithLocation(13, 13)); } [Fact] public void MultipleConversions_02() { var source = @"class A { } class B : A { } class C { public static implicit operator B?(C c) => null; static void F(C c) { A a = c; // (ImplicitReference)(ImplicitUserDefined) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // A a = c; // (ImplicitReference)(ImplicitUserDefined) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c").WithLocation(12, 15)); } [Fact] public void MultipleConversions_03() { var source = @"struct S<T> { public static implicit operator S<T>(T t) => default; static void M() { S<object> s = true; // (ImplicitUserDefined)(Boxing) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void MultipleConversions_04() { var source = @"struct S<T> { public static implicit operator T(S<T> s) => throw new System.Exception(); static void M() { bool b = new S<object>(); // (Unboxing)(ExplicitUserDefined) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): error CS0266: Cannot implicitly convert type 'S<object>' to 'bool'. An explicit conversion exists (are you missing a cast?) // bool b = new S<object>(); // (Unboxing)(ExplicitUserDefined) Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "new S<object>()").WithArguments("S<object>", "bool").WithLocation(6, 18)); } [Fact] public void MultipleConversions_Explicit_01() { var source = @"class A { public static explicit operator C(A a) => new C(); } class B : A { } class C { static void F1(B b1) { C? c; c = (C)b1; // (ExplicitUserDefined)(ImplicitReference) c = (C?)b1; // (ExplicitUserDefined)(ImplicitReference) } static void F2(bool flag, B? b2) { C? c; if (flag) c = (C)b2; // (ExplicitUserDefined)(ImplicitReference) if (flag) c = (C?)b2; // (ExplicitUserDefined)(ImplicitReference) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,26): warning CS8604: Possible null reference argument for parameter 'a' in 'A.explicit operator C(A a)'. // if (flag) c = (C)b2; // (ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b2").WithArguments("a", "A.explicit operator C(A a)").WithLocation(19, 26), // (20,27): warning CS8604: Possible null reference argument for parameter 'a' in 'A.explicit operator C(A a)'. // if (flag) c = (C?)b2; // (ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b2").WithArguments("a", "A.explicit operator C(A a)").WithLocation(20, 27)); } [Fact] public void MultipleConversions_Explicit_02() { var source = @"class A { public static explicit operator C?(A? a) => new D(); } class B : A { } class C { } class D : C { } class P { static void F1(A a1, B b1) { C? c; c = (C)a1; // (ExplicitUserDefined) c = (C?)a1; // (ExplicitUserDefined) c = (C)b1; // (ExplicitUserDefined)(ImplicitReference) c = (C?)b1; // (ExplicitUserDefined)(ImplicitReference) c = (C)(B)a1; c = (C)(B?)a1; c = (C?)(B)a1; c = (C?)(B?)a1; D? d; d = (D)a1; // (ExplicitReference)(ExplicitUserDefined) d = (D?)a1; // (ExplicitReference)(ExplicitUserDefined) d = (D)b1; // (ExplicitReference)(ExplicitUserDefined)(ImplicitReference) d = (D?)b1; // (ExplicitReference)(ExplicitUserDefined)(ImplicitReference) } static void F2(A? a2, B? b2) { C? c; c = (C)a2; // (ExplicitUserDefined) c = (C?)a2; // (ExplicitUserDefined) c = (C)b2; // (ExplicitUserDefined)(ImplicitReference) c = (C?)b2; // (ExplicitUserDefined)(ImplicitReference) D? d; d = (D)a2; // (ExplicitReference)(ExplicitUserDefined) d = (D?)a2; // (ExplicitReference)(ExplicitUserDefined) d = (D)b2; // (ExplicitReference)(ExplicitUserDefined)(ImplicitReference) d = (D?)b2; // (ExplicitReference)(ExplicitUserDefined)(ImplicitReference) d = (D)(A)b2; d = (D)(A?)b2; d = (D?)(A)b2; d = (D?)(A?)b2; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = (C)a1; // (ExplicitUserDefined) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)a1").WithLocation(13, 13), // (15,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = (C)b1; // (ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)b1").WithLocation(15, 13), // (17,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = (C)(B)a1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)(B)a1").WithLocation(17, 13), // (18,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = (C)(B?)a1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)(B?)a1").WithLocation(18, 13), // (22,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)a1; // (ExplicitReference)(ExplicitUserDefined) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(D)a1").WithLocation(22, 13), // (24,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)b1; // (ExplicitReference)(ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(D)b1").WithLocation(24, 13), // (30,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = (C)a2; // (ExplicitUserDefined) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)a2").WithLocation(30, 13), // (32,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = (C)b2; // (ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)b2").WithLocation(32, 13), // (35,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)a2; // (ExplicitReference)(ExplicitUserDefined) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(D)a2").WithLocation(35, 13), // (37,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)b2; // (ExplicitReference)(ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(D)b2").WithLocation(37, 13), // (39,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)(A)b2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(A)b2").WithLocation(39, 16), // (39,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)(A)b2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(D)(A)b2").WithLocation(39, 13), // (40,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)(A?)b2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(D)(A?)b2").WithLocation(40, 13), // (41,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D?)(A)b2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(A)b2").WithLocation(41, 17)); } [Fact] public void MultipleConversions_Explicit_03() { var source = @"class A { public static explicit operator S(A a) => new S(); } class B : A { } struct S { } class C { static void F(bool flag, B? b) { S? s; if (flag) s = (S)b; // (ExplicitUserDefined)(ImplicitReference) if (flag) s = (S?)b; // (ImplicitNullable)(ExplicitUserDefined)(ImplicitReference) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,26): warning CS8604: Possible null reference argument for parameter 'a' in 'A.explicit operator S(A a)'. // if (flag) s = (S)b; // (ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b").WithArguments("a", "A.explicit operator S(A a)").WithLocation(12, 26), // (13,27): warning CS8604: Possible null reference argument for parameter 'a' in 'A.explicit operator S(A a)'. // if (flag) s = (S?)b; // (ImplicitNullable)(ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b").WithArguments("a", "A.explicit operator S(A a)").WithLocation(13, 27)); } [Fact] [WorkItem(29960, "https://github.com/dotnet/roslyn/issues/29960")] public void MultipleConversions_Explicit_04() { var source = @"struct S { public static explicit operator A?(S s) => throw null!; } class A { internal void F() { } } class B : A { } class C { static void F(S s) { var b1 = (B)s; b1.F(); B b2 = (B)s; b2.F(); A a = (B)s; a.F(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29960: Should only report one WRN_ConvertingNullableToNonNullable // warning for `B b2 = (B)s;` and `A a = (B)s;`. comp.VerifyDiagnostics( // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // var b1 = (B)s; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)s").WithLocation(16, 18), // (17,9): warning CS8602: Dereference of a possibly null reference. // b1.F(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1").WithLocation(17, 9), // (18,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // B b2 = (B)s; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)s").WithLocation(18, 16), // (19,9): warning CS8602: Dereference of a possibly null reference. // b2.F(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b2").WithLocation(19, 9), // (20,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // A a = (B)s; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)s").WithLocation(20, 15), // (20,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // A a = (B)s; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)s").WithLocation(20, 15), // (21,9): warning CS8602: Dereference of a possibly null reference. // a.F(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(21, 9)); } [Fact] [WorkItem(29699, "https://github.com/dotnet/roslyn/issues/29699")] public void MultipleTupleConversions_01() { var source = @"class A { public static implicit operator C(A a) => new C(); } class B : A { } class C { static void F((B?, B) x, (B, B?) y, (B, B) z) { (C, C?) c; c = x; // (ImplicitTuple)(ImplicitUserDefined)(ImplicitReference) c = y; // (ImplicitTuple)(ImplicitUserDefined)(ImplicitReference) c = z; // (ImplicitTuple)(ImplicitUserDefined)(ImplicitReference) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8604: Possible null reference argument for parameter 'a' in 'A.implicit operator C(A a)'. // c = x; // (ImplicitTuple)(ImplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("a", "A.implicit operator C(A a)").WithLocation(13, 13), // (13,13): warning CS8619: Nullability of reference types in value of type '(B?, B)' doesn't match target type '(C, C?)'. // c = x; // (ImplicitTuple)(ImplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("(B?, B)", "(C, C?)").WithLocation(13, 13), // (14,13): warning CS8604: Possible null reference argument for parameter 'a' in 'A.implicit operator C(A a)'. // c = y; // (ImplicitTuple)(ImplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("a", "A.implicit operator C(A a)").WithLocation(14, 13)); } [Fact] public void MultipleTupleConversions_02() { var source = @"class A { } class B : A { } class C { public static implicit operator B(C c) => new C(); static void F(C? x, C y) { (A, A?) t = (x, y); // (ImplicitTuple)(ImplicitReference)(ImplicitUserDefined) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,17): warning CS0219: The variable 't' is assigned but its value is never used // (A, A?) t = (x, y); // (ImplicitTuple)(ImplicitReference)(ImplicitUserDefined) Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t").WithArguments("t").WithLocation(12, 17), // (12,22): warning CS8604: Possible null reference argument for parameter 'c' in 'C.implicit operator B(C c)'. // (A, A?) t = (x, y); // (ImplicitTuple)(ImplicitReference)(ImplicitUserDefined) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("c", "C.implicit operator B(C c)").WithLocation(12, 22)); } [Fact] [WorkItem(29966, "https://github.com/dotnet/roslyn/issues/29966")] public void Conversions_ImplicitTupleLiteral_01() { var source = @"#pragma warning disable 0219 interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class A<T> : I<T> { } class B<T> : IIn<T> { } class C<T> : IOut<T> { } static class E { static void F1(string x, string? y) { (string, string) t1 = (x, y); // 1 (string?, string?) u1 = (x, y); (object, object) v1 = (x, y); // 2 (object?, object?) w1 = (x, y); F1A((x, y)); // 3 F1B((x, y)); F1C((x, y)); // 4 F1D((x, y)); } static void F1A((string, string) t) { } static void F1B((string?, string?) t) { } static void F1C((object, object) t) { } static void F1D((object?, object?) t) { } static void F2(A<object> x, A<object?> y) { (A<object>, A<object>) t2 = (x, y); // 5 (A<object?>, A<object?>) u2 = (x, y); // 6 (I<object>, I<object>) v2 = (x, y); // 7 (I<object?>, I<object?>) w2 = (x, y); // 8 F2A((x, y)); // 9 F2B((x, y)); // 10 F2C((x, y)); // 11 F2D((x, y)); // 12 } static void F2A((A<object>, A<object>) t) { } static void F2B((A<object?>, A<object?>) t) { } static void F2C((I<object>, I<object>) t) { } static void F2D((I<object?>, I<object?>) t) { } static void F3(B<object> x, B<object?> y) { (B<object>, B<object>) t3 = (x, y); // 13 (B<object?>, B<object?>) u3 = (x, y); // 14 (IIn<object>, IIn<object>) v3 = (x, y); (IIn<object?>, IIn<object?>) w3 = (x, y); // 15 F3A((x, y)); F3B((x, y)); // 16 } static void F3A((IIn<object>, IIn<object>) t) { } static void F3B((IIn<object?>, IIn<object?>) t) { } static void F4(C<object> x, C<object?> y) { (C<object>, C<object>) t4 = (x, y); // 17 (C<object?>, C<object?>) u4 = (x, y); // 18 (IOut<object>, IOut<object>) v4 = (x, y); // 19 (IOut<object?>, IOut<object?>) w4 = (x, y); F4A((x, y)); // 20 F4B((x, y)); } static void F4A((IOut<object>, IOut<object>) t) { } static void F4B((IOut<object?>, IOut<object?>) t) { } static void F5<T, U>(U u) where U : T { (T, T) t5 = (u, default(T)); // 21 (object, object) v5 = (default(T), u); // 22 (object?, object?) w5 = (default(T), u); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29966: Report WRN_NullabilityMismatchInArgument rather than ...Assignment. comp.VerifyDiagnostics( // (12,31): warning CS8619: Nullability of reference types in value of type '(string x, string? y)' doesn't match target type '(string, string)'. // (string, string) t1 = (x, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(string x, string? y)", "(string, string)").WithLocation(12, 31), // (14,31): warning CS8619: Nullability of reference types in value of type '(object x, object? y)' doesn't match target type '(object, object)'. // (object, object) v1 = (x, y); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(object x, object? y)", "(object, object)").WithLocation(14, 31), // (16,13): warning CS8620: Argument of type '(string x, string? y)' cannot be used for parameter 't' of type '(string, string)' in 'void E.F1A((string, string) t)' due to differences in the nullability of reference types. // F1A((x, y)); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(string x, string? y)", "(string, string)", "t", "void E.F1A((string, string) t)").WithLocation(16, 13), // (18,13): warning CS8620: Argument of type '(object x, object? y)' cannot be used for parameter 't' of type '(object, object)' in 'void E.F1C((object, object) t)' due to differences in the nullability of reference types. // F1C((x, y)); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(object x, object? y)", "(object, object)", "t", "void E.F1C((object, object) t)").WithLocation(18, 13), // (27,37): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?> y)' doesn't match target type '(A<object>, A<object>)'. // (A<object>, A<object>) t2 = (x, y); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object>, A<object>)").WithLocation(27, 37), // (28,39): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?> y)' doesn't match target type '(A<object?>, A<object?>)'. // (A<object?>, A<object?>) u2 = (x, y); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object?>, A<object?>)").WithLocation(28, 39), // (29,41): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'I<object>'. // (I<object>, I<object>) v2 = (x, y); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object?>", "I<object>").WithLocation(29, 41), // (30,40): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'I<object?>'. // (I<object?>, I<object?>) w2 = (x, y); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "I<object?>").WithLocation(30, 40), // (31,13): warning CS8620: Argument of type '(A<object> x, A<object?> y)' cannot be used for parameter 't' of type '(A<object>, A<object>)' in 'void E.F2A((A<object>, A<object>) t)' due to differences in the nullability of reference types. // F2A((x, y)); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object>, A<object>)", "t", "void E.F2A((A<object>, A<object>) t)").WithLocation(31, 13), // (32,13): warning CS8620: Argument of type '(A<object> x, A<object?> y)' cannot be used for parameter 't' of type '(A<object?>, A<object?>)' in 'void E.F2B((A<object?>, A<object?>) t)' due to differences in the nullability of reference types. // F2B((x, y)); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object?>, A<object?>)", "t", "void E.F2B((A<object?>, A<object?>) t)").WithLocation(32, 13), // (33,17): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'I<object>'. // F2C((x, y)); // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object?>", "I<object>").WithLocation(33, 17), // (34,14): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'I<object?>'. // F2D((x, y)); // 12 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "I<object?>").WithLocation(34, 14), // (42,37): warning CS8619: Nullability of reference types in value of type '(B<object> x, B<object?> y)' doesn't match target type '(B<object>, B<object>)'. // (B<object>, B<object>) t3 = (x, y); // 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(B<object> x, B<object?> y)", "(B<object>, B<object>)").WithLocation(42, 37), // (43,39): warning CS8619: Nullability of reference types in value of type '(B<object> x, B<object?> y)' doesn't match target type '(B<object?>, B<object?>)'. // (B<object?>, B<object?>) u3 = (x, y); // 14 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(B<object> x, B<object?> y)", "(B<object?>, B<object?>)").WithLocation(43, 39), // (45,44): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'IIn<object?>'. // (IIn<object?>, IIn<object?>) w3 = (x, y); // 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object>", "IIn<object?>").WithLocation(45, 44), // (47,14): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'IIn<object?>'. // F3B((x, y)); // 16 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object>", "IIn<object?>").WithLocation(47, 14), // (53,37): warning CS8619: Nullability of reference types in value of type '(C<object> x, C<object?> y)' doesn't match target type '(C<object>, C<object>)'. // (C<object>, C<object>) t4 = (x, y); // 17 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(C<object> x, C<object?> y)", "(C<object>, C<object>)").WithLocation(53, 37), // (54,39): warning CS8619: Nullability of reference types in value of type '(C<object> x, C<object?> y)' doesn't match target type '(C<object?>, C<object?>)'. // (C<object?>, C<object?>) u4 = (x, y); // 18 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(C<object> x, C<object?> y)", "(C<object?>, C<object?>)").WithLocation(54, 39), // (55,47): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'IOut<object>'. // (IOut<object>, IOut<object>) v4 = (x, y); // 19 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "IOut<object>").WithLocation(55, 47), // (57,17): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'IOut<object>'. // F4A((x, y)); // 20 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "IOut<object>").WithLocation(57, 17), // (64,22): warning CS8619: Nullability of reference types in value of type '(T u, T?)' doesn't match target type '(T, T)'. // (T, T) t5 = (u, default(T)); // 21 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(u, default(T))").WithArguments("(T u, T?)", "(T, T)").WithLocation(64, 22), // (65,31): warning CS8619: Nullability of reference types in value of type '(object?, object? u)' doesn't match target type '(object, object)'. // (object, object) v5 = (default(T), u); // 22 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default(T), u)").WithArguments("(object?, object? u)", "(object, object)").WithLocation(65, 31)); } [Fact] public void Conversions_ImplicitTupleLiteral_02() { var source = @"#pragma warning disable 0219 interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class A<T> : I<T> { } class B<T> : IIn<T> { } class C<T> : IOut<T> { } static class E { static void F1(string x, string? y) { (string, string)? t1 = (x, y); // 1 (string?, string?)? u1 = (x, y); (object, object)? v1 = (x, y); // 2 (object?, object?)? w1 = (x, y); } static void F2(A<object> x, A<object?> y) { (A<object>, A<object>)? t2 = (x, y); // 3 (A<object?>, A<object?>)? u2 = (x, y); // 4 (I<object>, I<object>)? v2 = (x, y); // 5 (I<object?>, I<object?>)? w2 = (x, y); // 6 } static void F3(B<object> x, B<object?> y) { (IIn<object>, IIn<object>)? v3 = (x, y); (IIn<object?>, IIn<object?>)? w3 = (x, y); // 7 } static void F4(C<object> x, C<object?> y) { (IOut<object>, IOut<object>)? v4 = (x, y); // 8 (IOut<object?>, IOut<object?>)? w4 = (x, y); } static void F5<T, U>(U u) where U : T { (T, T)? t5 = (u, default(T)); // 9 (object, object)? v5 = (default(T), u); // 10 (object?, object?)? w5 = (default(T), u); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,32): warning CS8619: Nullability of reference types in value of type '(string x, string? y)' doesn't match target type '(string, string)?'. // (string, string)? t1 = (x, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(string x, string? y)", "(string, string)?").WithLocation(12, 32), // (14,32): warning CS8619: Nullability of reference types in value of type '(object x, object? y)' doesn't match target type '(object, object)?'. // (object, object)? v1 = (x, y); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(object x, object? y)", "(object, object)?").WithLocation(14, 32), // (19,38): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?> y)' doesn't match target type '(A<object>, A<object>)?'. // (A<object>, A<object>)? t2 = (x, y); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object>, A<object>)?").WithLocation(19, 38), // (20,40): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?> y)' doesn't match target type '(A<object?>, A<object?>)?'. // (A<object?>, A<object?>)? u2 = (x, y); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object?>, A<object?>)?").WithLocation(20, 40), // (21,42): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'I<object>'. // (I<object>, I<object>)? v2 = (x, y); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object?>", "I<object>").WithLocation(21, 42), // (22,41): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'I<object?>'. // (I<object?>, I<object?>)? w2 = (x, y); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "I<object?>").WithLocation(22, 41), // (27,45): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'IIn<object?>'. // (IIn<object?>, IIn<object?>)? w3 = (x, y); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object>", "IIn<object?>").WithLocation(27, 45), // (31,48): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'IOut<object>'. // (IOut<object>, IOut<object>)? v4 = (x, y); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "IOut<object>").WithLocation(31, 48), // (36,23): warning CS8619: Nullability of reference types in value of type '(T u, T?)' doesn't match target type '(T, T)?'. // (T, T)? t5 = (u, default(T)); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(u, default(T))").WithArguments("(T u, T?)", "(T, T)?").WithLocation(36, 23), // (37,32): warning CS8619: Nullability of reference types in value of type '(object?, object? u)' doesn't match target type '(object, object)?'. // (object, object)? v5 = (default(T), u); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default(T), u)").WithArguments("(object?, object? u)", "(object, object)?").WithLocation(37, 32)); } [Fact] public void Conversions_ImplicitTuple() { var source = @"#pragma warning disable 0219 interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class A<T> : I<T> { } class B<T> : IIn<T> { } class C<T> : IOut<T> { } class D { static void F1((string x, string?) a1) { (string, string) t1 = a1; // 1 (string?, string?) u1 = a1; (object, object) v1 = a1; // 2 (object?, object?) w1 = a1; } static void F2((A<object> x, A<object?>) a2) { (A<object>, A<object>) t2 = a2; // 3 (A<object?>, A<object?>) u2 = a2; // 4 (I<object>, I<object>) v2 = a2; // 5 (I<object?>, I<object?>) w2 = a2; // 6 } static void F3((B<object> x, B<object?>) a3) { (IIn<object>, IIn<object>) v3 = a3; (IIn<object?>, IIn<object?>) w3 = a3; // 7 } static void F4((C<object> x, C<object?>) a4) { (IOut<object>, IOut<object>) v4 = a4; // 8 (IOut<object?>, IOut<object?>) w4 = a4; } static void F5<T, U>((U, U) a5) where U : T { (U, T) t5 = a5; (object, object) v5 = a5; // 9 (object?, object?) w5 = a5; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,31): warning CS8619: Nullability of reference types in value of type '(string x, string?)' doesn't match target type '(string, string)'. // (string, string) t1 = a1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1").WithArguments("(string x, string?)", "(string, string)").WithLocation(12, 31), // (14,31): warning CS8619: Nullability of reference types in value of type '(string x, string?)' doesn't match target type '(object, object)'. // (object, object) v1 = a1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1").WithArguments("(string x, string?)", "(object, object)").WithLocation(14, 31), // (19,37): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(A<object>, A<object>)'. // (A<object>, A<object>) t2 = a2; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("(A<object> x, A<object?>)", "(A<object>, A<object>)").WithLocation(19, 37), // (20,39): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(A<object?>, A<object?>)'. // (A<object?>, A<object?>) u2 = a2; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("(A<object> x, A<object?>)", "(A<object?>, A<object?>)").WithLocation(20, 39), // (21,37): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(I<object>, I<object>)'. // (I<object>, I<object>) v2 = a2; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("(A<object> x, A<object?>)", "(I<object>, I<object>)").WithLocation(21, 37), // (22,39): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(I<object?>, I<object?>)'. // (I<object?>, I<object?>) w2 = a2; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("(A<object> x, A<object?>)", "(I<object?>, I<object?>)").WithLocation(22, 39), // (27,43): warning CS8619: Nullability of reference types in value of type '(B<object> x, B<object?>)' doesn't match target type '(IIn<object?>, IIn<object?>)'. // (IIn<object?>, IIn<object?>) w3 = a3; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a3").WithArguments("(B<object> x, B<object?>)", "(IIn<object?>, IIn<object?>)").WithLocation(27, 43), // (31,43): warning CS8619: Nullability of reference types in value of type '(C<object> x, C<object?>)' doesn't match target type '(IOut<object>, IOut<object>)'. // (IOut<object>, IOut<object>) v4 = a4; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a4").WithArguments("(C<object> x, C<object?>)", "(IOut<object>, IOut<object>)").WithLocation(31, 43), // (37,31): warning CS8619: Nullability of reference types in value of type '(U, U)' doesn't match target type '(object, object)'. // (object, object) v5 = a5; // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a5").WithArguments("(U, U)", "(object, object)").WithLocation(37, 31)); } [Fact] public void Conversions_ExplicitTupleLiteral_01() { var source = @"#pragma warning disable 0219 interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } sealed class A<T> : I<T> { } sealed class B<T> : IIn<T> { } sealed class C<T> : IOut<T> { } class D { static void F1(string x, string? y) { var t1 = ((string, string))(x, y); // 1 var u1 = ((string?, string?))(x, y); var v1 = ((object, object))(x, y); // 2 var w1 = ((object?, object?))(x, y); } static void F2(A<object> x, A<object?> y) { var t2 = ((A<object>, A<object>))(x, y); // 3 var u2 = ((A<object?>, A<object?>))(x, y); // 4 var v2 = ((I<object>, I<object>))(x, y); // 5 var w2 = ((I<object?>, I<object?>))(x, y); // 6 } static void F3(B<object> x, B<object?> y) { var v3 = ((IIn<object>, IIn<object>))(x, y); var w3 = ((IIn<object?>, IIn<object?>))(x, y); // 7 } static void F4(C<object> x, C<object?> y) { var v4 = ((IOut<object>, IOut<object>))(x, y); // 8 var w4 = ((IOut<object?>, IOut<object?>))(x, y); } static void F5<T, U>(T t) where U : T { var t5 = ((U, U))(t, default(T)); // 9 var v5 = ((object, object))(default(T), t); // 10 var w5 = ((object?, object?))(default(T), t); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,18): warning CS8619: Nullability of reference types in value of type '(string x, string? y)' doesn't match target type '(string, string)'. // var t1 = ((string, string))(x, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((string, string))(x, y)").WithArguments("(string x, string? y)", "(string, string)").WithLocation(12, 18), // (14,18): warning CS8619: Nullability of reference types in value of type '(object x, object? y)' doesn't match target type '(object, object)'. // var v1 = ((object, object))(x, y); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, object))(x, y)").WithArguments("(object x, object? y)", "(object, object)").WithLocation(14, 18), // (14,40): warning CS8600: Converting null literal or possible null value to non-nullable type. // var v1 = ((object, object))(x, y); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(14, 40), // (19,18): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?> y)' doesn't match target type '(A<object>, A<object>)'. // var t2 = ((A<object>, A<object>))(x, y); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((A<object>, A<object>))(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object>, A<object>)").WithLocation(19, 18), // (20,18): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?> y)' doesn't match target type '(A<object?>, A<object?>)'. // var u2 = ((A<object?>, A<object?>))(x, y); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((A<object?>, A<object?>))(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object?>, A<object?>)").WithLocation(20, 18), // (21,46): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'I<object>'. // var v2 = ((I<object>, I<object>))(x, y); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object?>", "I<object>").WithLocation(21, 46), // (22,45): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'I<object?>'. // var w2 = ((I<object?>, I<object?>))(x, y); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "I<object?>").WithLocation(22, 45), // (27,49): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'IIn<object?>'. // var w3 = ((IIn<object?>, IIn<object?>))(x, y); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object>", "IIn<object?>").WithLocation(27, 49), // (31,52): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'IOut<object>'. // var v4 = ((IOut<object>, IOut<object>))(x, y); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "IOut<object>").WithLocation(31, 52), // (36,18): warning CS8619: Nullability of reference types in value of type '(U? t, U?)' doesn't match target type '(U, U)'. // var t5 = ((U, U))(t, default(T)); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((U, U))(t, default(T))").WithArguments("(U? t, U?)", "(U, U)").WithLocation(36, 18), // (37,18): warning CS8619: Nullability of reference types in value of type '(object?, object? t)' doesn't match target type '(object, object)'. // var v5 = ((object, object))(default(T), t); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, object))(default(T), t)").WithArguments("(object?, object? t)", "(object, object)").WithLocation(37, 18), // (37,37): warning CS8600: Converting null literal or possible null value to non-nullable type. // var v5 = ((object, object))(default(T), t); // 10 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(T)").WithLocation(37, 37), // (37,49): warning CS8600: Converting null literal or possible null value to non-nullable type. // var v5 = ((object, object))(default(T), t); // 10 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(37, 49)); } [Fact] public void Conversions_ExplicitTupleLiteral_02() { var source = @"#pragma warning disable 0219 interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } sealed class A<T> : I<T> { } sealed class B<T> : IIn<T> { } sealed class C<T> : IOut<T> { } class D { static void F1(string x, string? y) { var t1 = ((string, string)?)(x, y); // 1 var u1 = ((string?, string?)?)(x, y); var v1 = ((object, object)?)(x, y); // 2 var w1 = ((object?, object?)?)(x, y); } static void F2(A<object> x, A<object?> y) { var t2 = ((A<object>, A<object>)?)(x, y); // 3 var u2 = ((A<object?>, A<object?>)?)(x, y); // 4 var v2 = ((I<object>, I<object>)?)(x, y); // 5 var w2 = ((I<object?>, I<object?>)?)(x, y); // 6 } static void F3(B<object> x, B<object?> y) { var v3 = ((IIn<object>, IIn<object>)?)(x, y); var w3 = ((IIn<object?>, IIn<object?>)?)(x, y); // 7 } static void F4(C<object> x, C<object?> y) { var v4 = ((IOut<object>, IOut<object>)?)(x, y); // 8 var w4 = ((IOut<object?>, IOut<object?>)?)(x, y); } static void F5<T, U>(T t) where U : T { var t5 = ((U, U)?)(t, default(T)); // 9 var v5 = ((object, object)?)(default(T), t); // 10 var w5 = ((object?, object?)?)(default(T), t); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,18): warning CS8619: Nullability of reference types in value of type '(string x, string? y)' doesn't match target type '(string, string)?'. // var t1 = ((string, string)?)(x, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((string, string)?)(x, y)").WithArguments("(string x, string? y)", "(string, string)?").WithLocation(12, 18), // (12,41): warning CS8600: Converting null literal or possible null value to non-nullable type. // var t1 = ((string, string)?)(x, y); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(12, 41), // (14,18): warning CS8619: Nullability of reference types in value of type '(object x, object? y)' doesn't match target type '(object, object)?'. // var v1 = ((object, object)?)(x, y); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, object)?)(x, y)").WithArguments("(object x, object? y)", "(object, object)?").WithLocation(14, 18), // (14,41): warning CS8600: Converting null literal or possible null value to non-nullable type. // var v1 = ((object, object)?)(x, y); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(14, 41), // (19,47): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'A<object>'. // var t2 = ((A<object>, A<object>)?)(x, y); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object?>", "A<object>").WithLocation(19, 47), // (20,46): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'A<object?>'. // var u2 = ((A<object?>, A<object?>)?)(x, y); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "A<object?>").WithLocation(20, 46), // (21,47): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'I<object>'. // var v2 = ((I<object>, I<object>)?)(x, y); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object?>", "I<object>").WithLocation(21, 47), // (22,46): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'I<object?>'. // var w2 = ((I<object?>, I<object?>)?)(x, y); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "I<object?>").WithLocation(22, 46), // (27,50): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'IIn<object?>'. // var w3 = ((IIn<object?>, IIn<object?>)?)(x, y); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object>", "IIn<object?>").WithLocation(27, 50), // (31,53): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'IOut<object>'. // var v4 = ((IOut<object>, IOut<object>)?)(x, y); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "IOut<object>").WithLocation(31, 53), // (36,18): warning CS8619: Nullability of reference types in value of type '(U? t, U?)' doesn't match target type '(U, U)?'. // var t5 = ((U, U)?)(t, default(T)); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((U, U)?)(t, default(T))").WithArguments("(U? t, U?)", "(U, U)?").WithLocation(36, 18), // (37,18): warning CS8619: Nullability of reference types in value of type '(object?, object? t)' doesn't match target type '(object, object)?'. // var v5 = ((object, object)?)(default(T), t); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, object)?)(default(T), t)").WithArguments("(object?, object? t)", "(object, object)?").WithLocation(37, 18), // (37,38): warning CS8600: Converting null literal or possible null value to non-nullable type. // var v5 = ((object, object)?)(default(T), t); // 10 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(T)").WithLocation(37, 38), // (37,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // var v5 = ((object, object)?)(default(T), t); // 10 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(37, 50)); } [Fact] public void Conversions_ExplicitTuple() { var source = @"#pragma warning disable 0219 interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } sealed class A<T> : I<T> { } sealed class B<T> : IIn<T> { } sealed class C<T> : IOut<T> { } class D { static void F1((string x, string?) a1) { var t1 = ((string, string))a1; // 1 var u1 = ((string?, string?))a1; var v1 = ((object, object))a1; // 2 var w1 = ((object?, object?))a1; } static void F2((A<object> x, A<object?>) a2) { var t2 = ((A<object>, A<object>))a2; // 3 var u2 = ((A<object?>, A<object?>))a2; // 4 var v2 = ((I<object>, I<object>))a2; // 5 var w2 = ((I<object?>, I<object?>))a2; // 6 } static void F3((B<object> x, B<object?>) a3) { var v3 = ((IIn<object>, IIn<object>))a3; var w3 = ((IIn<object?>, IIn<object?>))a3; // 7 } static void F4((C<object> x, C<object?>) a4) { var v4 = ((IOut<object>, IOut<object>))a4; // 8 var w4 = ((IOut<object?>, IOut<object?>))a4; } static void F5<T, U>((T, T) a5) where U : T { var t5 = ((U, U))a5; var v5 = ((object, object))default((T, T)); // 9 var w5 = ((object?, object?))default((T, T)); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,18): warning CS8619: Nullability of reference types in value of type '(string x, string?)' doesn't match target type '(string, string)'. // var t1 = ((string, string))a1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((string, string))a1").WithArguments("(string x, string?)", "(string, string)").WithLocation(12, 18), // (14,18): warning CS8619: Nullability of reference types in value of type '(string x, string?)' doesn't match target type '(object, object)'. // var v1 = ((object, object))a1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, object))a1").WithArguments("(string x, string?)", "(object, object)").WithLocation(14, 18), // (19,18): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(A<object>, A<object>)'. // var t2 = ((A<object>, A<object>))a2; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((A<object>, A<object>))a2").WithArguments("(A<object> x, A<object?>)", "(A<object>, A<object>)").WithLocation(19, 18), // (20,18): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(A<object?>, A<object?>)'. // var u2 = ((A<object?>, A<object?>))a2; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((A<object?>, A<object?>))a2").WithArguments("(A<object> x, A<object?>)", "(A<object?>, A<object?>)").WithLocation(20, 18), // (21,18): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(I<object>, I<object>)'. // var v2 = ((I<object>, I<object>))a2; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((I<object>, I<object>))a2").WithArguments("(A<object> x, A<object?>)", "(I<object>, I<object>)").WithLocation(21, 18), // (22,18): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(I<object?>, I<object?>)'. // var w2 = ((I<object?>, I<object?>))a2; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((I<object?>, I<object?>))a2").WithArguments("(A<object> x, A<object?>)", "(I<object?>, I<object?>)").WithLocation(22, 18), // (27,18): warning CS8619: Nullability of reference types in value of type '(B<object> x, B<object?>)' doesn't match target type '(IIn<object?>, IIn<object?>)'. // var w3 = ((IIn<object?>, IIn<object?>))a3; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((IIn<object?>, IIn<object?>))a3").WithArguments("(B<object> x, B<object?>)", "(IIn<object?>, IIn<object?>)").WithLocation(27, 18), // (31,18): warning CS8619: Nullability of reference types in value of type '(C<object> x, C<object?>)' doesn't match target type '(IOut<object>, IOut<object>)'. // var v4 = ((IOut<object>, IOut<object>))a4; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((IOut<object>, IOut<object>))a4").WithArguments("(C<object> x, C<object?>)", "(IOut<object>, IOut<object>)").WithLocation(31, 18), // (37,18): warning CS8619: Nullability of reference types in value of type '(T, T)' doesn't match target type '(object, object)'. // var v5 = ((object, object))default((T, T)); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, object))default((T, T))").WithArguments("(T, T)", "(object, object)").WithLocation(37, 18)); } [Fact] [WorkItem(29966, "https://github.com/dotnet/roslyn/issues/29966")] public void Conversions_ImplicitTupleLiteral_ExtensionThis() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class A<T> : I<T> { } class B<T> : IIn<T> { } class C<T> : IOut<T> { } static class E { static void F1(string x, string? y) { (x, y).F1A(); // 1 (x, y).F1B(); } static void F1A(this (object, object) t) { } static void F1B(this (object?, object?) t) { } static void F2(A<object> x, A<object?> y) { (x, y).F2A(); // 2 (x, y).F2B(); // 3 } static void F2A(this (I<object>, I<object>) t) { } static void F2B(this (I<object?>, I<object?>) t) { } static void F3(B<object> x, B<object?> y) { (x, y).F3A(); (x, y).F3B(); // 4 } static void F3A(this (IIn<object>, IIn<object>) t) { } static void F3B(this (IIn<object?>, IIn<object?>) t) { } static void F4(C<object> x, C<object?> y) { (x, y).F4A(); // 5 (x, y).F4B(); } static void F4A(this (IOut<object>, IOut<object>) t) { } static void F4B(this (IOut<object?>, IOut<object?>) t) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8620: Argument of type '(string x, string? y)' cannot be used for parameter 't' of type '(object, object)' in 'void E.F1A((object, object) t)' due to differences in the nullability of reference types. // (x, y).F1A(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(string x, string? y)", "(object, object)", "t", "void E.F1A((object, object) t)").WithLocation(11, 9), // (18,9): warning CS8620: Argument of type '(A<object> x, A<object?> y)' cannot be used for parameter 't' of type '(I<object>, I<object>)' in 'void E.F2A((I<object>, I<object>) t)' due to differences in the nullability of reference types. // (x, y).F2A(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(I<object>, I<object>)", "t", "void E.F2A((I<object>, I<object>) t)").WithLocation(18, 9), // (19,9): warning CS8620: Argument of type '(A<object> x, A<object?> y)' cannot be used for parameter 't' of type '(I<object?>, I<object?>)' in 'void E.F2B((I<object?>, I<object?>) t)' due to differences in the nullability of reference types. // (x, y).F2B(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(I<object?>, I<object?>)", "t", "void E.F2B((I<object?>, I<object?>) t)").WithLocation(19, 9), // (26,9): warning CS8620: Argument of type '(B<object> x, B<object?> y)' cannot be used for parameter 't' of type '(IIn<object?>, IIn<object?>)' in 'void E.F3B((IIn<object?>, IIn<object?>) t)' due to differences in the nullability of reference types. // (x, y).F3B(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(B<object> x, B<object?> y)", "(IIn<object?>, IIn<object?>)", "t", "void E.F3B((IIn<object?>, IIn<object?>) t)").WithLocation(26, 9), // (32,9): warning CS8620: Argument of type '(C<object> x, C<object?> y)' cannot be used for parameter 't' of type '(IOut<object>, IOut<object>)' in 'void E.F4A((IOut<object>, IOut<object>) t)' due to differences in the nullability of reference types. // (x, y).F4A(); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(C<object> x, C<object?> y)", "(IOut<object>, IOut<object>)", "t", "void E.F4A((IOut<object>, IOut<object>) t)").WithLocation(32, 9)); } [Fact] public void Conversions_ImplicitTuple_ExtensionThis_01() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class A<T> : I<T> { } class B<T> : IIn<T> { } class C<T> : IOut<T> { } static class E { static void F1((string x, string?) t1) { t1.F1A(); // 1 t1.F1B(); } static void F1A(this (object, object) t) { } static void F1B(this (object?, object?) t) { } static void F2((A<object>, A<object?>) t2) { t2.F2A(); // 2 t2.F2B(); // 3 } static void F2A(this (I<object>, I<object>) t) { } static void F2B(this (I<object?>, I<object?>) t) { } static void F3((B<object>, B<object?>) t3) { t3.F3A(); t3.F3B(); // 4 } static void F3A(this (IIn<object>, IIn<object>) t) { } static void F3B(this (IIn<object?>, IIn<object?>) t) { } static void F4((C<object>, C<object?>) t4) { t4.F4A(); // 5 t4.F4B(); } static void F4A(this (IOut<object>, IOut<object>) t) { } static void F4B(this (IOut<object?>, IOut<object?>) t) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8620: Nullability of reference types in argument of type '(string x, string?)' doesn't match target type '(object, object)' for parameter 't' in 'void E.F1A((object, object) t)'. // t1.F1A(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t1").WithArguments("(string x, string?)", "(object, object)", "t", "void E.F1A((object, object) t)").WithLocation(11, 9), // (18,9): warning CS8620: Nullability of reference types in argument of type '(A<object>, A<object?>)' doesn't match target type '(I<object>, I<object>)' for parameter 't' in 'void E.F2A((I<object>, I<object>) t)'. // t2.F2A(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t2").WithArguments("(A<object>, A<object?>)", "(I<object>, I<object>)", "t", "void E.F2A((I<object>, I<object>) t)").WithLocation(18, 9), // (19,9): warning CS8620: Nullability of reference types in argument of type '(A<object>, A<object?>)' doesn't match target type '(I<object?>, I<object?>)' for parameter 't' in 'void E.F2B((I<object?>, I<object?>) t)'. // t2.F2B(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t2").WithArguments("(A<object>, A<object?>)", "(I<object?>, I<object?>)", "t", "void E.F2B((I<object?>, I<object?>) t)").WithLocation(19, 9), // (26,9): warning CS8620: Nullability of reference types in argument of type '(B<object>, B<object?>)' doesn't match target type '(IIn<object?>, IIn<object?>)' for parameter 't' in 'void E.F3B((IIn<object?>, IIn<object?>) t)'. // t3.F3B(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t3").WithArguments("(B<object>, B<object?>)", "(IIn<object?>, IIn<object?>)", "t", "void E.F3B((IIn<object?>, IIn<object?>) t)").WithLocation(26, 9), // (32,9): warning CS8620: Nullability of reference types in argument of type '(C<object>, C<object?>)' doesn't match target type '(IOut<object>, IOut<object>)' for parameter 't' in 'void E.F4A((IOut<object>, IOut<object>) t)'. // t4.F4A(); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t4").WithArguments("(C<object>, C<object?>)", "(IOut<object>, IOut<object>)", "t", "void E.F4A((IOut<object>, IOut<object>) t)").WithLocation(32, 9)); } [Fact] public void Conversions_ImplicitTuple_ExtensionThis_02() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } static class E { static void F1((string, string)? t1) { t1.F1A(); // 1 t1.F1B(); } static void F1A(this (string?, string?)? t) { } static void F1B(this (string, string)? t) { } static void F2((I<object?>, I<object?>)? t2) { t2.F2A(); t2.F2B(); // 2 } static void F2A(this (I<object?>, I<object?>)? t) { } static void F2B(this (I<object>, I<object>)? t) { } static void F3((IIn<object?>, IIn<object?>)? t3) { t3.F3A(); t3.F3B(); // 3 } static void F3A(this (IIn<object?>, IIn<object?>)? t) { } static void F3B(this (IIn<object>, IIn<object>)? t) { } static void F4((IOut<object?>, IOut<object?>)? t4) { t4.F4A(); t4.F4B(); // 4 } static void F4A(this (IOut<object?>, IOut<object?>)? t) { } static void F4B(this (IOut<object>, IOut<object>)? t) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8620: Nullability of reference types in argument of type '(string, string)?' doesn't match target type '(string?, string?)?' for parameter 't' in 'void E.F1A((string?, string?)? t)'. // t1.F1A(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t1").WithArguments("(string, string)?", "(string?, string?)?", "t", "void E.F1A((string?, string?)? t)").WithLocation(8, 9), // (16,9): warning CS8620: Nullability of reference types in argument of type '(I<object?>, I<object?>)?' doesn't match target type '(I<object>, I<object>)?' for parameter 't' in 'void E.F2B((I<object>, I<object>)? t)'. // t2.F2B(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t2").WithArguments("(I<object?>, I<object?>)?", "(I<object>, I<object>)?", "t", "void E.F2B((I<object>, I<object>)? t)").WithLocation(16, 9), // (23,9): warning CS8620: Nullability of reference types in argument of type '(IIn<object?>, IIn<object?>)?' doesn't match target type '(IIn<object>, IIn<object>)?' for parameter 't' in 'void E.F3B((IIn<object>, IIn<object>)? t)'. // t3.F3B(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t3").WithArguments("(IIn<object?>, IIn<object?>)?", "(IIn<object>, IIn<object>)?", "t", "void E.F3B((IIn<object>, IIn<object>)? t)").WithLocation(23, 9), // (30,9): warning CS8620: Nullability of reference types in argument of type '(IOut<object?>, IOut<object?>)?' doesn't match target type '(IOut<object>, IOut<object>)?' for parameter 't' in 'void E.F4B((IOut<object>, IOut<object>)? t)'. // t4.F4B(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t4").WithArguments("(IOut<object?>, IOut<object?>)?", "(IOut<object>, IOut<object>)?", "t", "void E.F4B((IOut<object>, IOut<object>)? t)").WithLocation(30, 9)); } [Fact] public void Conversions_ImplicitTuple_ExtensionThis_03() { var source = @"static class E { static void F((string, (string, string)?) t) { t.FA(); // 1 t.FB(); FA(t); FB(t); } static void FA(this (object, (string?, string?)?) t) { } static void FB(this (object, (string, string)?) t) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8620: Nullability of reference types in argument of type '(string, (string, string)?)' doesn't match target type '(object, (string?, string?)?)' for parameter 't' in 'void E.FA((object, (string?, string?)?) t)'. // t.FA(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t").WithArguments("(string, (string, string)?)", "(object, (string?, string?)?)", "t", "void E.FA((object, (string?, string?)?) t)").WithLocation(5, 9)); } [Fact] public void TupleTypeInference_01() { var source = @"class C { static (T, T) F<T>((T, T) t) => t; static void G(string x, string? y) { F((x, x)).Item2.ToString(); F((x, y)).Item2.ToString(); F((y, x)).Item2.ToString(); F((y, y)).Item2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F((x, y)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F((x, y)).Item2").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F((y, x)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F((y, x)).Item2").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F((y, y)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F((y, y)).Item2").WithLocation(9, 9)); } [Fact] public void TupleTypeInference_02() { var source = @"class C { static (T, T) F<T>((T, T?) t) where T : class => (t.Item1, t.Item1); static void G(string x, string? y) { F((x, x)).Item2.ToString(); F((x, y)).Item2.ToString(); F((y, x)).Item2.ToString(); F((y, y)).Item2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>((T, T?))'. Nullability of type argument 'string?' doesn't match 'class' constraint. // F((y, x)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>((T, T?))", "T", "string?").WithLocation(8, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F((y, x)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F((y, x)).Item2").WithLocation(8, 9), // (9,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>((T, T?))'. Nullability of type argument 'string?' doesn't match 'class' constraint. // F((y, y)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>((T, T?))", "T", "string?").WithLocation(9, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F((y, y)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F((y, y)).Item2").WithLocation(9, 9)); } [Fact] public void TupleTypeInference_03() { var source = @"class C { static T F<T>((T, T?) t) where T : class => t.Item1; static void G((string, string) x, (string, string?) y, (string?, string) z, (string?, string?) w) { F(x).ToString(); F(y).ToString(); F(z).ToString(); F(w).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>((T, T?))'. Nullability of type argument 'string?' doesn't match 'class' constraint. // F(z).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>((T, T?))", "T", "string?").WithLocation(8, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F(z).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(z)").WithLocation(8, 9), // (9,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>((T, T?))'. Nullability of type argument 'string?' doesn't match 'class' constraint. // F(w).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>((T, T?))", "T", "string?").WithLocation(9, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F(w).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(w)").WithLocation(9, 9)); } [Fact] public void TupleTypeInference_04_Ref() { var source = @"class C { static T F<T>(ref (T, T?) t) where T : class => throw new System.Exception(); static void G(string x, string? y) { (string, string) t1 = (x, x); F(ref t1).ToString(); (string, string?) t2 = (x, y); F(ref t2).ToString(); (string?, string) t3 = (y, x); F(ref t3).ToString(); (string?, string?) t4 = (y, y); F(ref t4).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8620: Argument of type '(string, string)' cannot be used as an input of type '(string, string?)' for parameter 't' in 'string C.F<string>(ref (string, string?) t)' due to differences in the nullability of reference types. // F(ref t1).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t1").WithArguments("(string, string)", "(string, string?)", "t", "string C.F<string>(ref (string, string?) t)").WithLocation(7, 15), // (11,15): warning CS8620: Argument of type '(string?, string)' cannot be used as an input of type '(string, string?)' for parameter 't' in 'string C.F<string>(ref (string, string?) t)' due to differences in the nullability of reference types. // F(ref t3).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t3").WithArguments("(string?, string)", "(string, string?)", "t", "string C.F<string>(ref (string, string?) t)").WithLocation(11, 15), // (13,15): warning CS8620: Argument of type '(string?, string?)' cannot be used as an input of type '(string, string?)' for parameter 't' in 'string C.F<string>(ref (string, string?) t)' due to differences in the nullability of reference types. // F(ref t4).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t4").WithArguments("(string?, string?)", "(string, string?)", "t", "string C.F<string>(ref (string, string?) t)").WithLocation(13, 15)); } [Fact] public void TupleTypeInference_04_Out() { var source = @"class C { static T F<T>(out (T, T?) t) where T : class => throw new System.Exception(); static void G() { F(out (string, string) t1).ToString(); F(out (string, string?) t2).ToString(); F(out (string?, string) t3).ToString(); F(out (string?, string?) t4).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,15): warning CS8624: Argument of type '(string, string)' cannot be used as an output of type '(string, string?)' for parameter 't' in 'string C.F<string>(out (string, string?) t)' due to differences in the nullability of reference types. // F(out (string, string) t1).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "(string, string) t1").WithArguments("(string, string)", "(string, string?)", "t", "string C.F<string>(out (string, string?) t)").WithLocation(6, 15), // (8,15): warning CS8624: Argument of type '(string?, string)' cannot be used as an output of type '(string, string?)' for parameter 't' in 'string C.F<string>(out (string, string?) t)' due to differences in the nullability of reference types. // F(out (string?, string) t3).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "(string?, string) t3").WithArguments("(string?, string)", "(string, string?)", "t", "string C.F<string>(out (string, string?) t)").WithLocation(8, 15), // (9,15): warning CS8624: Argument of type '(string?, string?)' cannot be used as an output of type '(string, string?)' for parameter 't' in 'string C.F<string>(out (string, string?) t)' due to differences in the nullability of reference types. // F(out (string?, string?) t4).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "(string?, string?) t4").WithArguments("(string?, string?)", "(string, string?)", "t", "string C.F<string>(out (string, string?) t)").WithLocation(9, 15)); } [Fact] public void TupleTypeInference_05() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>(I<(T, T?)> t) where T : class => throw new System.Exception(); static void G(I<(string, string)> x, I<(string, string?)> y, I<(string?, string)> z, I<(string?, string?)> w) { F(x).ToString(); F(y).ToString(); F(z).ToString(); F(w).ToString(); } static T F<T>(IIn<(T, T?)> t) where T : class => throw new System.Exception(); static void G(IIn<(string, string)> x, IIn<(string, string?)> y, IIn<(string?, string)> z, IIn<(string?, string?)> w) { F(x).ToString(); F(y).ToString(); F(z).ToString(); F(w).ToString(); } static T F<T>(IOut<(T, T?)> t) where T : class => throw new System.Exception(); static void G(IOut<(string, string)> x, IOut<(string, string?)> y, IOut<(string?, string)> z, IOut<(string?, string?)> w) { F(x).ToString(); F(y).ToString(); F(z).ToString(); F(w).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): warning CS8620: Nullability of reference types in argument of type 'I<(string, string)>' doesn't match target type 'I<(string, string?)>' for parameter 't' in 'string C.F<string>(I<(string, string?)> t)'. // F(x).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<(string, string)>", "I<(string, string?)>", "t", "string C.F<string>(I<(string, string?)> t)").WithLocation(9, 11), // (11,11): warning CS8620: Nullability of reference types in argument of type 'I<(string?, string)>' doesn't match target type 'I<(string, string?)>' for parameter 't' in 'string C.F<string>(I<(string, string?)> t)'. // F(z).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("I<(string?, string)>", "I<(string, string?)>", "t", "string C.F<string>(I<(string, string?)> t)").WithLocation(11, 11), // (12,11): warning CS8620: Nullability of reference types in argument of type 'I<(string?, string?)>' doesn't match target type 'I<(string, string?)>' for parameter 't' in 'string C.F<string>(I<(string, string?)> t)'. // F(w).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "w").WithArguments("I<(string?, string?)>", "I<(string, string?)>", "t", "string C.F<string>(I<(string, string?)> t)").WithLocation(12, 11), // (17,11): warning CS8620: Nullability of reference types in argument of type 'IIn<(string, string)>' doesn't match target type 'IIn<(string, string?)>' for parameter 't' in 'string C.F<string>(IIn<(string, string?)> t)'. // F(x).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("IIn<(string, string)>", "IIn<(string, string?)>", "t", "string C.F<string>(IIn<(string, string?)> t)").WithLocation(17, 11), // (19,11): warning CS8620: Nullability of reference types in argument of type 'IIn<(string?, string)>' doesn't match target type 'IIn<(string, string?)>' for parameter 't' in 'string C.F<string>(IIn<(string, string?)> t)'. // F(z).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IIn<(string?, string)>", "IIn<(string, string?)>", "t", "string C.F<string>(IIn<(string, string?)> t)").WithLocation(19, 11), // (20,11): warning CS8620: Nullability of reference types in argument of type 'IIn<(string?, string?)>' doesn't match target type 'IIn<(string, string?)>' for parameter 't' in 'string C.F<string>(IIn<(string, string?)> t)'. // F(w).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "w").WithArguments("IIn<(string?, string?)>", "IIn<(string, string?)>", "t", "string C.F<string>(IIn<(string, string?)> t)").WithLocation(20, 11), // (25,11): warning CS8620: Nullability of reference types in argument of type 'IOut<(string, string)>' doesn't match target type 'IOut<(string, string?)>' for parameter 't' in 'string C.F<string>(IOut<(string, string?)> t)'. // F(x).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("IOut<(string, string)>", "IOut<(string, string?)>", "t", "string C.F<string>(IOut<(string, string?)> t)").WithLocation(25, 11), // (27,11): warning CS8620: Nullability of reference types in argument of type 'IOut<(string?, string)>' doesn't match target type 'IOut<(string, string?)>' for parameter 't' in 'string C.F<string>(IOut<(string, string?)> t)'. // F(z).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IOut<(string?, string)>", "IOut<(string, string?)>", "t", "string C.F<string>(IOut<(string, string?)> t)").WithLocation(27, 11), // (28,11): warning CS8620: Nullability of reference types in argument of type 'IOut<(string?, string?)>' doesn't match target type 'IOut<(string, string?)>' for parameter 't' in 'string C.F<string>(IOut<(string, string?)> t)'. // F(w).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "w").WithArguments("IOut<(string?, string?)>", "IOut<(string, string?)>", "t", "string C.F<string>(IOut<(string, string?)> t)").WithLocation(28, 11) ); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void TupleTypeInference_06() { var source = @"class C { static void F(object? x, object? y) { if (y != null) { ((object? x, object? y), object? z) t = ((x, y), y); t.Item1.Item1.ToString(); t.Item1.Item2.ToString(); t.Item2.ToString(); t.Item1.x.ToString(); // warning already reported for t.Item1.Item1 t.Item1.y.ToString(); // warning already reported for t.Item1.Item2 t.z.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // t.Item1.Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1.Item1").WithLocation(8, 13)); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void TupleTypeInference_07() { var source = @"class C { static void F(object? x, object? y) { if (y != null) { (object? _1, object? _2, object? _3, object? _4, object? _5, object? _6, object? _7, object? _8, object? _9, object? _10) t = (null, null, null, null, null, null, null, x, null, y); t._7.ToString(); t._8.ToString(); t.Rest.Item1.ToString(); // warning already reported for t._8 t.Rest.Item2.ToString(); t._9.ToString(); // warning already reported for t.Rest.Item2 t._10.ToString(); t.Rest.Item3.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // t._7.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t._7").WithLocation(8, 13), // (9,13): warning CS8602: Dereference of a possibly null reference. // t._8.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t._8").WithLocation(9, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(11, 13)); } [Fact] [WorkItem(35157, "https://github.com/dotnet/roslyn/issues/35157")] public void TupleTypeInference_08() { var source = @" class C { void M() { _ = (null, 2); _ = (null, (2, 3)); _ = (null, (null, (2, 3))); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = (null, 2); Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(6, 9), // (7,9): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = (null, (2, 3)); Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(7, 9), // (8,9): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = (null, (null, (2, 3))); Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(8, 9) ); } [Fact] public void TupleTypeInference_09() { var source = @" using System; class C { C(long arg) {} void M() { int i = 0; Func<(C, C)> action = () => (new(i), new(i)); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_01() { var source = @"class Program { static void F() { (object? a, string) t = (default(object), default(string)) /*T:(object?, string?)*/; // 1 (object, string? b) u = t; // 2 _ = t/*T:(object? a, string!)*/; _ = u/*T:(object!, string? b)*/; t.Item1.ToString(); // 3 t.Item2.ToString(); // 4 u.Item1.ToString(); // 5 u.Item2.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,33): warning CS8619: Nullability of reference types in value of type '(object?, string?)' doesn't match target type '(object? a, string)'. // (object? a, string) t = (default(object), default(string)) /*T:(object?, string?)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default(object), default(string))").WithArguments("(object?, string?)", "(object? a, string)").WithLocation(5, 33), // (6,33): warning CS8619: Nullability of reference types in value of type '(object? a, string)' doesn't match target type '(object, string? b)'. // (object, string? b) u = t; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("(object? a, string)", "(object, string? b)").WithLocation(6, 33), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2").WithLocation(12, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_02() { var source = @"class Program { static void F(object? x, object y) { (object x, object? y, object? z) t = (null, x, y); // 1 _ = t/*T:(object! x, object? y, object? z)*/; t.x.ToString(); // 2 t.y.ToString(); // 3 t.z.ToString(); if (x == null) return; (object x, object y) u = (x, default(object))/*T:(object! x, object?)*/; // 4 _ = u/*T:(object! x, object! y)*/; u.x.ToString(); u.y.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (5,46): warning CS8619: Nullability of reference types in value of type '(object?, object? x, object y)' doesn't match target type '(object x, object? y, object? z)'. // (object x, object? y, object? z) t = (null, x, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, x, y)").WithArguments("(object?, object? x, object y)", "(object x, object? y, object? z)").WithLocation(5, 46), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.x").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.y").WithLocation(8, 9), // (11,34): warning CS8619: Nullability of reference types in value of type '(object x, object?)' doesn't match target type '(object x, object y)'. // (object x, object y) u = (x, default(object))/*T:(object! x, object?)*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, default(object))").WithArguments("(object x, object?)", "(object x, object y)").WithLocation(11, 34), // (14,9): warning CS8602: Dereference of a possibly null reference. // u.y.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.y").WithLocation(14, 9)); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_03() { var source = @"class A { internal object? F; } class B : A { } class Program { static void F1() { (A, A?) t1 = (null, new A() { F = 1 }); // 1 (A x, A? y) u1 = t1; u1.x.ToString(); // 2 u1.y.ToString(); u1.y.F.ToString(); } static void F2() { (A, A?) t2 = (null, new B() { F = 2 }); // 3 (A x, A? y) u2 = t2; u2.x.ToString(); // 4 u2.y.ToString(); u2.y.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,22): warning CS8619: Nullability of reference types in value of type '(A?, A)' doesn't match target type '(A, A?)'. // (A, A?) t1 = (null, new A() { F = 1 }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, new A() { F = 1 })").WithArguments("(A?, A)", "(A, A?)").WithLocation(12, 22), // (14,9): warning CS8602: Dereference of a possibly null reference. // u1.x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u1.x").WithLocation(14, 9), // (20,22): warning CS8619: Nullability of reference types in value of type '(A?, A)' doesn't match target type '(A, A?)'. // (A, A?) t2 = (null, new B() { F = 2 }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, new B() { F = 2 })").WithArguments("(A?, A)", "(A, A?)").WithLocation(20, 22), // (22,9): warning CS8602: Dereference of a possibly null reference. // u2.x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.x").WithLocation(22, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_04() { var source = @"class Program { static void F(object? x, string? y) { (object?, string) t = (x, y)/*T:(object? x, string? y)*/; // 1 (object, string?) u = t; // 2 t.Item1.ToString(); // 3 t.Item2.ToString(); // 4 u.Item1.ToString(); // 5 u.Item2.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,31): warning CS8619: Nullability of reference types in value of type '(object? x, string? y)' doesn't match target type '(object?, string)'. // (object?, string) t = (x, y)/*T:(object? x, string? y)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(object? x, string? y)", "(object?, string)").WithLocation(5, 31), // (6,31): warning CS8619: Nullability of reference types in value of type '(object?, string)' doesn't match target type '(object, string?)'. // (object, string?) u = t; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("(object?, string)", "(object, string?)").WithLocation(6, 31), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2").WithLocation(10, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_05() { var source = @"class Program { static void F(object x, string? y) { (object?, string) t = (x, y)/*T:(object! x, string? y)*/; // 1 (object a, string? b) u = t; // 2 t.Item1.ToString(); t.Item2.ToString(); // 3 u.Item1.ToString(); u.Item2.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,31): warning CS8619: Nullability of reference types in value of type '(object x, string? y)' doesn't match target type '(object?, string)'. // (object?, string) t = (x, y)/*T:(object! x, string? y)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(object x, string? y)", "(object?, string)").WithLocation(5, 31), // (6,35): warning CS8619: Nullability of reference types in value of type '(object?, string)' doesn't match target type '(object a, string? b)'. // (object a, string? b) u = t; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("(object?, string)", "(object a, string? b)").WithLocation(6, 35), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2").WithLocation(10, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_06() { var source = @"class Program { static void F(string x, string? y) { (object, string) t = ((object, string))(x, y)/*T:(string! x, string? y)*/; // 1 (object a, string?) u = ((string, string?))t; (object?, object b) v = ((object?, object))t; t.Item1.ToString(); t.Item2.ToString(); u.Item1.ToString(); u.Item2.ToString(); // 2 v.Item1.ToString(); // 3 v.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,30): warning CS8619: Nullability of reference types in value of type '(object x, string? y)' doesn't match target type '(object, string)'. // (object, string) t = ((object, string))(x, y)/*T:(string! x, string? y)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, string))(x, y)").WithArguments("(object x, string? y)", "(object, string)").WithLocation(5, 30), // (5,52): warning CS8600: Converting null literal or possible null value to non-nullable type. // (object, string) t = ((object, string))(x, y)/*T:(string! x, string? y)*/; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(5, 52), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // v.Item1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v.Item1").WithLocation(12, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_07() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C<T> { internal T F; } class Program { static void F<T>(C<T> x, C<T> y) { if (y.F == null) return; var t = (x, y); var u = t; t.Item1.F.ToString(); // 1 t.Item2.F.ToString(); u.Item1.F.ToString(); // 2 u.Item2.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1.F").WithLocation(14, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1.F").WithLocation(16, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_08() { var source = @"class Program { static void F(bool b, object x, object? y) { (object?, object, object?, object, object?, (object, object?), object, object, object?, object) t = (x, x, x, y, y, (y, x), x, x, y, y)/*T:(object!, object!, object!, object?, object?, (object? y, object! x), object!, object!, object?, object?)*/; // 1 t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 2 t.Item5.ToString(); // 3 t.Item6.Item1.ToString(); // 4 t.Item6.Item2.ToString(); t.Item7.ToString(); if (b) { t.Item8.ToString(); t.Item9.ToString(); // 5 t.Item10.ToString(); // 6 } else { t.Rest.Item1.ToString(); t.Rest.Item2.ToString(); // 7 t.Rest.Item3.ToString(); // 8 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8619: Nullability of reference types in value of type '(object, object, object, object?, object?, (object? y, object x), object, object, object?, object?)' doesn't match target type '(object?, object, object?, object, object?, (object, object?), object, object, object?, object)'. // (x, x, x, y, y, (y, x), x, x, y, y)/*T:(object!, object!, object!, object?, object?, (object? y, object! x), object!, object!, object?, object?)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, x, x, y, y, (y, x), x, x, y, y)").WithArguments("(object, object, object, object?, object?, (object? y, object x), object, object, object?, object?)", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object)").WithLocation(6, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(12, 9), // (18,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(18, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(19, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(24, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(25, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_09() { var source = @"class Program { static void F(bool b, object x) { (object?, object, object?, object, object?, (object, object?), object, object, object?, object) t = (x, x, x, default(object), default(object), default((object, object?)), x, x, default(object), default(object))/*T:(object!, object!, object!, object?, object?, (object!, object?), object!, object!, object?, object?)*/; // 1 t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 2 t.Item5.ToString(); // 3 t.Item6.Item1.ToString(); // 4 t.Item6.Item2.ToString(); // 5 t.Item7.ToString(); if (b) { t.Item8.ToString(); t.Item9.ToString(); // 6 t.Item10.ToString(); // 7 } else { t.Rest.Item1.ToString(); t.Rest.Item2.ToString(); // 8 t.Rest.Item3.ToString(); // 9 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8619: Nullability of reference types in value of type '(object, object, object, object?, object?, (object, object?), object, object, object?, object?)' doesn't match target type '(object?, object, object?, object, object?, (object, object?), object, object, object?, object)'. // (x, x, x, default(object), default(object), default((object, object?)), x, x, default(object), default(object))/*T:(object!, object!, object!, object?, object?, (object!, object?), object!, object!, object?, object?)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, x, x, default(object), default(object), default((object, object?)), x, x, default(object), default(object))").WithArguments("(object, object, object, object?, object?, (object, object?), object, object, object?, object?)", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object)").WithLocation(6, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item2").WithLocation(13, 9), // (18,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(18, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(19, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(24, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(25, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_10() { // https://github.com/dotnet/roslyn/issues/35010: LValueType.TypeSymbol and RValueType.Type do not agree for the null literal var source = @"using System; class Program { static void F(object x, string y) { (object, string?) t = new ValueTuple<object?, string>(null, """") { Item1 = x }; // 1 (object?, string) u = new ValueTuple<object?, string>() { Item2 = y }; t.Item1.ToString(); t.Item2.ToString(); u.Item1.ToString(); // 2 u.Item1.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,31): warning CS8619: Nullability of reference types in value of type '(object?, string)' doesn't match target type '(object, string?)'. // (object, string?) t = new ValueTuple<object?, string>(null, "") { Item1 = x }; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new ValueTuple<object?, string>(null, """") { Item1 = x }").WithArguments("(object?, string)", "(object, string?)").WithLocation(6, 31), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(10, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_11() { var source = @"using System; class Program { static void F(bool b, object x, object? y) { var t = new ValueTuple<object?, object, object?, object, object?, ValueTuple<object, object?>, object, ValueTuple<object, object?, object>>( x, x, x, b ? y : null!, // 1 y, new ValueTuple<object, object?>(b ? y : null!, x), // 2 x, new ValueTuple<object, object?, object>(x, b ? y : null!, b ? y : null!))/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; // 3 t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 4 t.Item5.ToString(); // 5 t.Item6.Item1.ToString(); // 6 t.Item6.Item2.ToString(); t.Item7.ToString(); if (b) { t.Item8.ToString(); t.Item9.ToString(); // 7 t.Item10.ToString(); // 8 } else { t.Rest.Item1.ToString(); t.Rest.Item2.ToString(); // 9 t.Rest.Item3.ToString(); // 10 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8604: Possible null reference argument for parameter 'item4' in '(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)'. // b ? y : null!, // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? y : null!").WithArguments("item4", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)").WithLocation(10, 13), // (12,45): warning CS8604: Possible null reference argument for parameter 'item1' in '(object, object?).ValueTuple(object item1, object? item2)'. // new ValueTuple<object, object?>(b ? y : null!, x), // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? y : null!").WithArguments("item1", "(object, object?).ValueTuple(object item1, object? item2)").WithLocation(12, 45), // (14,71): warning CS8604: Possible null reference argument for parameter 'item3' in '(object, object?, object).ValueTuple(object item1, object? item2, object item3)'. // new ValueTuple<object, object?, object>(x, b ? y : null!, b ? y : null!))/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? y : null!").WithArguments("item3", "(object, object?, object).ValueTuple(object item1, object? item2, object item3)").WithLocation(14, 71), // (18,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(20, 9), // (26,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(26, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(27, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(32, 13), // (33,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(33, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_12() { var source = @"using System; class Program { static void F(bool b, object x) { var t = new ValueTuple<object?, object, object?, object, object?, ValueTuple<object, object?>, object, ValueTuple<object, object?, object>>( x, x, x, default, // 1 default, default, x, default)/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 2 t.Item5.ToString(); // 3 t.Item6.Item1.ToString(); // 4 t.Item6.Item2.ToString(); // 5 t.Item7.ToString(); if (b) { t.Item8.ToString(); // 6 t.Item9.ToString(); // 7 t.Item10.ToString(); // 8 } else { t.Rest.Item1.ToString(); // 9 t.Rest.Item2.ToString(); // 10 t.Rest.Item3.ToString(); // 11 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // default, // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(10, 13), // (18,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(20, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item2").WithLocation(21, 9), // (25,13): warning CS8602: Dereference of a possibly null reference. // t.Item8.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item8").WithLocation(25, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(26, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(27, 13), // (31,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item1.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item1").WithLocation(31, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(32, 13), // (33,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(33, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_13() { var source = @"using System; class Program { static void F(bool b, object x, object? y) { var t = new ValueTuple<object?, object, object?, object, object?, (object, object?), object, (object, object?, object)>( x, x, x, y, // 1 y, (y, x), // 2 x, (x, y, y))/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; // 3 t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 4 t.Item5.ToString(); // 5 t.Item6.Item1.ToString(); // 6 t.Item6.Item2.ToString(); t.Item7.ToString(); if (b) { t.Item8.ToString(); t.Item9.ToString(); // 7 t.Item10.ToString(); // 8 } else { t.Rest.Item1.ToString(); t.Rest.Item2.ToString(); // 9 t.Rest.Item3.ToString(); // 10 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8604: Possible null reference argument for parameter 'item4' in '(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)'. // y, // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("item4", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)").WithLocation(10, 13), // (12,13): warning CS8620: Argument of type '(object? y, object x)' cannot be used for parameter 'item6' of type '(object, object?)' in '(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)' due to differences in the nullability of reference types. // (y, x), // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, x)").WithArguments("(object? y, object x)", "(object, object?)", "item6", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)").WithLocation(12, 13), // (14,13): warning CS8620: Argument of type '(object x, object?, object?)' cannot be used for parameter 'rest' of type '(object, object?, object)' in '(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)' due to differences in the nullability of reference types. // (x, y, y))/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y, y)").WithArguments("(object x, object?, object?)", "(object, object?, object)", "rest", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)").WithLocation(14, 13), // (18,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(20, 9), // (26,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(26, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(27, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(32, 13), // (33,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(33, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_14() { var source = @"using System; class Program { static void F(bool b, object x) { var t = new ValueTuple<object?, object, object?, object, object?, (object, object?), object, (object, object?, object)>( x, x, x, default, // 1 default, default, x, default)/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 2 t.Item5.ToString(); // 3 t.Item6.Item1.ToString(); // 4 t.Item6.Item2.ToString(); // 5 t.Item7.ToString(); if (b) { t.Item8.ToString(); // 6 t.Item9.ToString(); // 7 t.Item10.ToString(); // 8 } else { t.Rest.Item1.ToString(); // 9 t.Rest.Item2.ToString(); // 10 t.Rest.Item3.ToString(); // 11 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // default, // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(10, 13), // (18,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(20, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item2").WithLocation(21, 9), // (25,13): warning CS8602: Dereference of a possibly null reference. // t.Item8.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item8").WithLocation(25, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(26, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(27, 13), // (31,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item1.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item1").WithLocation(31, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(32, 13), // (33,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(33, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_15() { var source = @"using System; class Program { static void F(object x, string? y) { var t = new ValueTuple<object?, string>(1); var u = new ValueTuple<object?, string>(null, null, 3); t.Item1.ToString(); // 1 t.Item2.ToString(); u.Item1.ToString(); // 2 u.Item1.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,21): error CS7036: There is no argument given that corresponds to the required formal parameter 'item2' of '(object?, string).ValueTuple(object?, string)' // var t = new ValueTuple<object?, string>(1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "ValueTuple<object?, string>").WithArguments("item2", "(object?, string).ValueTuple(object?, string)").WithLocation(6, 21), // (7,21): error CS1729: '(object?, string)' does not contain a constructor that takes 3 arguments // var u = new ValueTuple<object?, string>(null, null, 3); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ValueTuple<object?, string>").WithArguments("(object?, string)", "3").WithLocation(7, 21), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(10, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_16() { var source = @"class Program { static object F(object? x, object y, string z, string w) { throw null!; } static void G(bool b, string s, (string?, string?) t) { (string? x, string? y) u; (string? x, string? y) v; _ = b ? F( t.Item1 = s, u = t, u.x.ToString(), u.y.ToString()) : // 1 F( t.Item2 = s, v = t, v.x.ToString(), // 2 v.y.ToString()); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,17): warning CS8602: Dereference of a possibly null reference. // u.y.ToString()) : // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.y").WithLocation(16, 17), // (20,17): warning CS8602: Dereference of a possibly null reference. // v.x.ToString(), // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v.x").WithLocation(20, 17)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_17() { var source = @"class C { (object x, (string? z, object w) y) F; static void M(C c, (object? x, (string z, object? w) y) t) { c.F = t; // 1 (object, (string?, object)) u = c.F/*T:(object! x, (string? z, object! w) y)*/; c.F.x.ToString(); // 2 c.F.y.z.ToString(); c.F.y.w.ToString(); // 3 u.Item1.ToString(); // 4 u.Item2.Item1.ToString(); u.Item2.Item2.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,15): warning CS8619: Nullability of reference types in value of type '(object? x, (string z, object? w) y)' doesn't match target type '(object x, (string? z, object w) y)'. // c.F = t; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("(object? x, (string z, object? w) y)", "(object x, (string? z, object w) y)").WithLocation(6, 15), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.F.x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F.x").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.F.y.w.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F.y.w").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(11, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.Item2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2.Item2").WithLocation(13, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Tuple_Assignment_18() { var source = @"class Program { static void F(string s) { (object, object?)? t = (null, s); // 1 (object?, object?) u = t.Value; t.Value.Item1.ToString(); // 2 t.Value.Item2.ToString(); u.Item1.ToString(); // 3 u.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,32): warning CS8619: Nullability of reference types in value of type '(object?, object s)' doesn't match target type '(object, object?)?'. // (object, object?)? t = (null, s); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, s)").WithArguments("(object?, object s)", "(object, object?)?").WithLocation(5, 32), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.Value.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Value.Item1").WithLocation(7, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(9, 9)); } [Fact] public void Tuple_Assignment_19() { var source = @"class C { static void F() { (string, string?) t = t; t.Item1.ToString(); t.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,31): error CS0165: Use of unassigned local variable 't' // (string, string?) t = t; Diagnostic(ErrorCode.ERR_UseDefViolation, "t").WithArguments("t").WithLocation(5, 31), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(7, 9)); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_20() { var source = @"class C { static void G(object? x, object? y) { F = (x, y); } static (object?, object?) G() { return ((object?, object?))F; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS0103: The name 'F' does not exist in the current context // F = (x, y); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(5, 9), // (9,36): error CS0103: The name 'F' does not exist in the current context // return ((object?, object?))F; Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(9, 36)); } [Fact] [WorkItem(35010, "https://github.com/dotnet/roslyn/issues/35010")] public void Tuple_Assignment_21() { var source = @" #pragma warning disable CS0219 class C { static void F(string? x, string? y) { (object a, long b) t = (x, 0)/*T:(string? x, int)*/; // 1 (object a, (long b, object c)) t2 = (x, (0, y)/*T:(int, string? y)*/)/*T:(string? x, (int, string? y))*/; // 2, 3 (object a, (long b, object c)) t3 = (x!, (0, y!)/*T:(int, string!)*/)/*T:(string!, (int, string!))*/; (int b, string? c)? t4 = null; (object? a, (long b, object? c)?) t5 = (x, t4)/*T:(string? x, (int b, string? c)? t4)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,32): warning CS8619: Nullability of reference types in value of type '(object? x, long)' doesn't match target type '(object a, long b)'. // (object a, long b) t = (x, 0)/*T:(string? x, int)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, 0)").WithArguments("(object? x, long)", "(object a, long b)").WithLocation(7, 32), // (8,45): warning CS8619: Nullability of reference types in value of type '(object? x, (long b, object c))' doesn't match target type '(object a, (long b, object c))'. // (object a, (long b, object c)) t2 = (x, (0, y)/*T:(int, string? y)*/)/*T:(string? x, (int, string! y))*/; // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, (0, y)/*T:(int, string? y)*/)").WithArguments("(object? x, (long b, object c))", "(object a, (long b, object c))").WithLocation(8, 45), // (8,49): warning CS8619: Nullability of reference types in value of type '(long, object? y)' doesn't match target type '(long b, object c)'. // (object a, (long b, object c)) t2 = (x, (0, y)/*T:(int, string? y)*/)/*T:(string? x, (int, string! y))*/; // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(0, y)").WithArguments("(long, object? y)", "(long b, object c)").WithLocation(8, 49) ); comp.VerifyTypes(); } [Fact] [WorkItem(35010, "https://github.com/dotnet/roslyn/issues/35010")] public void Tuple_Assignment_22() { var source = @" #pragma warning disable CS0219 class C { static void F(string? x) { (C, C)/*T:(C!, C!)*/ b = (x, x)/*T:(string?, string?)*/; } public static implicit operator C(string? a) { return new C(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_23() { var source = @"class Program { static void F() { (object? a, string) t = (default, default) /*T:<null>!*/; // 1 (object, string? b) u = t; // 2 _ = t/*T:(object? a, string!)*/; _ = u/*T:(object!, string? b)*/; t.Item1.ToString(); // 3 t.Item2.ToString(); // 4 u.Item1.ToString(); // 5 u.Item2.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,33): warning CS8619: Nullability of reference types in value of type '(object?, string?)' doesn't match target type '(object? a, string)'. // (object? a, string) t = (default, default) /*T:<null>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default, default)").WithArguments("(object?, string?)", "(object? a, string)").WithLocation(5, 33), // (6,33): warning CS8619: Nullability of reference types in value of type '(object? a, string)' doesn't match target type '(object, string? b)'. // (object, string? b) u = t; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("(object? a, string)", "(object, string? b)").WithLocation(6, 33), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2").WithLocation(12, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_24() { var source = @"class Program { static void F(object? x, object y) { (object x, object? y, object? z) t = (null, x, y); // 1 _ = t/*T:(object! x, object? y, object? z)*/; t.x.ToString(); // 2 t.y.ToString(); // 3 t.z.ToString(); if (x == null) return; (object x, object y) u = (x, default)/*T:<null>!*/; // 4 _ = u/*T:(object! x, object! y)*/; u.x.ToString(); u.y.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (5,46): warning CS8619: Nullability of reference types in value of type '(object?, object? x, object y)' doesn't match target type '(object x, object? y, object? z)'. // (object x, object? y, object? z) t = (null, x, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, x, y)").WithArguments("(object?, object? x, object y)", "(object x, object? y, object? z)").WithLocation(5, 46), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.x").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.y").WithLocation(8, 9), // (11,34): warning CS8619: Nullability of reference types in value of type '(object x, object?)' doesn't match target type '(object x, object y)'. // (object x, object y) u = (x, default)/*T:<null>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, default)").WithArguments("(object x, object?)", "(object x, object y)").WithLocation(11, 34), // (14,9): warning CS8602: Dereference of a possibly null reference. // u.y.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.y").WithLocation(14, 9)); } [Fact] [WorkItem(46206, "https://github.com/dotnet/roslyn/issues/46206")] public void Tuple_Assignment_25() { var source = @"using System; class Program { static void F(object x, string y) { (object, string?) t = new ValueTuple<object?, string>(item2: """", item1: null) { Item1 = x }; t.Item1.ToString(); t.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,31): warning CS8619: Nullability of reference types in value of type '(object?, string)' doesn't match target type '(object, string?)'. // (object, string?) t = new ValueTuple<object?, string>(item2: "", item1: null) { Item1 = x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new ValueTuple<object?, string>(item2: """", item1: null) { Item1 = x }").WithArguments("(object?, string)", "(object, string?)").WithLocation(6, 31)); } [Fact] [WorkItem(46206, "https://github.com/dotnet/roslyn/issues/46206")] public void Tuple_Assignment_26() { var source = @"using System; class Program { static void F(bool b, object x, object? y) { var t = new ValueTuple<object?, object, object?, object, object?, ValueTuple<object, object?>, object, ValueTuple<object, object?, object>>( x, x, x, b ? y : x, // 1 y, new ValueTuple<object, object?>(b ? y : x, x), // 2, rest: new ValueTuple<object, object?, object>(x, b ? y : x, b ? y : x), // 3 item7: y)/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; // 4 t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 5 t.Item5.ToString(); // 6 t.Item6.Item1.ToString(); // 7 t.Item6.Item2.ToString(); t.Item7.ToString(); // 8 if (b) { t.Item8.ToString(); t.Item9.ToString(); // 9 t.Item10.ToString(); // 10 } else { t.Rest.Item1.ToString(); t.Rest.Item2.ToString(); // 11 t.Rest.Item3.ToString(); // 12 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8604: Possible null reference argument for parameter 'item4' in '(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)'. // b ? y : x, // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? y : x").WithArguments("item4", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)").WithLocation(10, 13), // (12,45): warning CS8604: Possible null reference argument for parameter 'item1' in '(object, object?).ValueTuple(object item1, object? item2)'. // new ValueTuple<object, object?>(b ? y : x, x), // 2, Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? y : x").WithArguments("item1", "(object, object?).ValueTuple(object item1, object? item2)").WithLocation(12, 45), // (13,73): warning CS8604: Possible null reference argument for parameter 'item3' in '(object, object?, object).ValueTuple(object item1, object? item2, object item3)'. // rest: new ValueTuple<object, object?, object>(x, b ? y : x, b ? y : x), // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? y : x").WithArguments("item3", "(object, object?, object).ValueTuple(object item1, object? item2, object item3)").WithLocation(13, 73), // (14,20): warning CS8604: Possible null reference argument for parameter 'item7' in '(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)'. // item7: y)/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("item7", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)").WithLocation(14, 20), // (18,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(20, 9), // (22,9): warning CS8602: Dereference of a possibly null reference. // t.Item7.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item7").WithLocation(22, 9), // (26,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(26, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(27, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(32, 13), // (33,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(33, 13)); } [Fact] [WorkItem(32338, "https://github.com/dotnet/roslyn/issues/32338")] public void CopyStructUnconstrainedFieldNullability_01() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void M<T>(T t) { var x = new S<T>() { F = t }; var y = x; y.F.ToString(); // 1 if (t == null) return; x = new S<T>() { F = t }; var z = x; z.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(12, 9)); } [Fact] [WorkItem(32338, "https://github.com/dotnet/roslyn/issues/32338")] public void CopyStructUnconstrainedFieldNullability_02() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void M<T>(S<T> x) { var y = x; y.F.ToString(); // 1 if (x.F == null) return; var z = x; z.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(11, 9)); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] [WorkItem(32338, "https://github.com/dotnet/roslyn/issues/32338")] public void CopyTupleUnconstrainedElementNullability_01() { var source = @"class Program { static void M<T, U>(T t, U u) { var x = (t, u); var y = x; y.Item1.ToString(); // 1 if (t == null) return; x = (t, u); var z = x; z.Item1.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // y.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Item1").WithLocation(7, 9)); } [Fact] [WorkItem(32338, "https://github.com/dotnet/roslyn/issues/32338")] public void CopyTupleUnconstrainedElementNullability_02() { var source = @"class Program { static void M<T, U>((T, U) x) { var y = x; y.Item1.ToString(); // 1 if (x.Item1 == null) return; var z = x; z.Item1.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // y.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Item1").WithLocation(6, 9)); } [Fact] [WorkItem(32703, "https://github.com/dotnet/roslyn/issues/32703")] [WorkItem(31395, "https://github.com/dotnet/roslyn/issues/31395")] public void CopyClassFields() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C { internal object? F; internal object G; } class Program { static void F(C x) { if (x.F == null) return; if (x.G != null) return; C y = x; x.F.ToString(); x.G.ToString(); // 1 y.F.ToString(); y.G.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,9): warning CS8602: Dereference of a possibly null reference. // x.G.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.G").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // y.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.G").WithLocation(18, 9)); } [Fact] [WorkItem(32703, "https://github.com/dotnet/roslyn/issues/32703")] public void CopyStructFields() { var source = @"#pragma warning disable 0649 struct S { internal object? F; internal object G; } class Program { static void F(S x) { if (x.F == null) return; if (x.G != null) return; S y = x; x.F.ToString(); x.G.ToString(); // 1 y.F.ToString(); y.G.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // x.G.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.G").WithLocation(15, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // y.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.G").WithLocation(17, 9) ); } [Fact] [WorkItem(32703, "https://github.com/dotnet/roslyn/issues/32703")] public void CopyNullableStructFields() { var source = @"#pragma warning disable 0649 struct S { internal object? F; internal object G; } class Program { static void F(S? x) { if (x == null) return; if (x.Value.F == null) return; if (x.Value.G != null) return; S? y = x; x.Value.F.ToString(); x.Value.G.ToString(); // 1 y.Value.F.ToString(); y.Value.G.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,9): warning CS8602: Dereference of a possibly null reference. // x.Value.G.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.G").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // y.Value.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.G").WithLocation(18, 9) ); } [Fact] [WorkItem(31395, "https://github.com/dotnet/roslyn/issues/31395")] public void NestedAssignment() { var source = @"class C { internal C? F; internal C G = null!; } class Program { static void F1() { var x1 = new C() { F = new C(), G = null }; // 1 var y1 = new C() { F = x1, G = (x1 = new C()) }; y1.F.F.ToString(); y1.F.G.ToString(); // 2 y1.G.F.ToString(); // 3 y1.G.G.ToString(); } static void F2() { var x2 = new C() { F = new C(), G = null }; // 4 var y2 = new C() { G = x2, F = (x2 = new C()) }; y2.F.F.ToString(); // 5 y2.F.G.ToString(); y2.G.F.ToString(); y2.G.G.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,45): warning CS8625: Cannot convert null literal to non-nullable reference type. // var x1 = new C() { F = new C(), G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 45), // (13,9): warning CS8602: Dereference of a possibly null reference. // y1.F.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1.F.G").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // y1.G.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1.G.F").WithLocation(14, 9), // (19,45): warning CS8625: Cannot convert null literal to non-nullable reference type. // var x2 = new C() { F = new C(), G = null }; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 45), // (21,9): warning CS8602: Dereference of a possibly null reference. // y2.F.F.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2.F.F").WithLocation(21, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // y2.G.G.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2.G.G").WithLocation(24, 9)); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void ConditionalAccessIsAPureTest() { var source = @" class C { void F(object o) { if (o?.ToString() != null) o.ToString(); else o.ToString(); // 1 o.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(9, 13) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void ConditionalAccessIsAPureTest_Generic() { var source = @" class C { void F<T>(T t) { if (t is null) return; if (t?.ToString() != null) t.ToString(); else t.ToString(); // 1 t.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(11, 13) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void ConditionalAccessIsAPureTest_Indexer() { var source = @" class C { void F(C c) { if (c?[0] == true) c.ToString(); else c.ToString(); // 1 c.ToString(); } bool this[int i] => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(9, 13) ); } [Fact] [WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] [WorkItem(34018, "https://github.com/dotnet/roslyn/issues/34018")] public void ConditionalAccessIsAPureTest_InFinally_01() { var source = @" class C { void F(object o) { try { } finally { if (o?.ToString() != null) o.ToString(); } o.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(34018, "https://github.com/dotnet/roslyn/issues/34018")] public void ConditionalAccessIsAPureTest_InFinally_02() { var source = @" class C { void F() { C? c = null; try { c = new C(); } finally { if (c != null) c.Cleanup(); } c.Operation(); // ok } void Cleanup() {} void Operation() {} }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void NullCoalescingIsAPureTest() { var source = @" class C { void F(string s, string s2) { _ = s ?? s.ToString(); // 1 _ = s2 ?? null; s2.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): warning CS8602: Dereference of a possibly null reference. // _ = s ?? s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 18), // (9,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(9, 9) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void NullCoalescingAssignmentIsAPureTest() { var source = @" class C { void F(string s, string s2) { s ??= s.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,15): warning CS8602: Dereference of a possibly null reference. // s ??= s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 15) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void NullComparisonIsAPureTest() { var source = @" class C { void F(C x, C y) { if (x == null) x.ToString(); // 1 else x.ToString(); if (null != y) y.ToString(); else y.ToString(); // 2 } public static bool operator==(C? one, C? two) => throw null!; public static bool operator!=(C? one, C? two) => throw null!; public override bool Equals(object o) => throw null!; public override int GetHashCode() => throw null!; }"; // `x == null` is a "pure test" even when it binds to a user-defined operator, // so affects both branches var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(14, 13) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void NullComparisonIsAPureTest_IntroducesMaybeNull() { var source = @" class C { void F(C x, C y) { if (x == null) { } x.ToString(); // 1 if (null != y) { } y.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(10, 9) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void NullComparisonIsAPureTest_WithCast() { var source = @" class C { void F(object x, object y) { if ((string)x == null) x.ToString(); // 1 else x.ToString(); if (null != (string)y) y.ToString(); else y.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(14, 13) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void IsNullIsAPureTest() { var source = @" class C { void F(C x) { if (x is null) x.ToString(); // 1 else x.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 13) ); } // https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-12-18.md [Fact] public void OtherComparisonsAsPureNullTests_01() { var source = @"#nullable enable using System; using System_Object = System.Object; class E { } class Program { static void F1(E e) { if (e is object) return; e.ToString(); // 1 } static void F2(E e) { if (e is Object) return; e.ToString(); // 2 } static void F3(E e) { if (e is System.Object) return; e.ToString(); // 3 } static void F4(E e) { if (e is System_Object) return; e.ToString(); // 4 } static void F5(E e) { if (e is object _) return; e.ToString(); } static void F6(E e) { if (e is object x) return; e.ToString(); } static void F7(E e) { if (e is dynamic) return; e.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // e.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(10, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // e.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(15, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // e.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(20, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // e.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(25, 9), // (39,13): warning CS1981: Using 'is' to test compatibility with 'dynamic' is essentially identical to testing compatibility with 'Object' and will succeed for all non-null values // if (e is dynamic) return; Diagnostic(ErrorCode.WRN_IsDynamicIsConfusing, "e is dynamic").WithArguments("is", "dynamic", "Object").WithLocation(39, 13)); } [Fact] public void OtherComparisonsAsPureNullTests_02() { var source = @"#nullable enable class Program { static void F1(string s) { if (s is string) return; s.ToString(); } static void F2(string s) { if (s is string _) return; s.ToString(); } static void F3(string s) { if (s is string x) return; s.ToString(); } static void F4(object o) { if (o is string x) return; o.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } // https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-12-18.md [Fact] public void OtherComparisonsAsPureNullTests_03() { var source = @"#nullable enable #pragma warning disable 649 class E { public void Deconstruct() => throw null!; internal Pair? F; } class Pair { public void Deconstruct(out int x, out int y) => throw null!; } class Program { static void F1(E e) { if (e is { }) return; e.ToString(); // 1 } static void F2(E e) { if (e is { } _) return; e.ToString(); } static void F3(E e) { if (e is { } x) return; e.ToString(); } static void F4(E e) { if (e is E { }) return; e.ToString(); } static void F5(E e) { if (e is object { }) return; e.ToString(); } static void F6(E e) { if (e is { F: null }) return; e.ToString(); } static void F7(E e) { if (e is ( )) return; e.ToString(); } static void F8(E e) { if (e is ( ) { }) return; e.ToString(); } static void F9(E e) { if (e is { F: (1, 2) }) return; e.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,9): warning CS8602: Dereference of a possibly null reference. // e.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(17, 9)); } [Fact] public void OtherComparisonsAsPureNullTests_04() { var source = @"#nullable enable #pragma warning disable 649 class E { internal object F; } class Program { static void F0(E e) { e.F.ToString(); } static void F1(E e) { if (e is { F: null }) return; e.F.ToString(); } static void F2(E e) { if (e is E { F: 2 }) return; e.F.ToString(); } static void F3(E e) { if (e is { F: { } }) return; e.F.ToString(); // 1 } static void F4(E e) { if (e is { F: { } } _) return; e.F.ToString(); // 2 } static void F5(E e) { if (e is { F: { } } x) return; e.F.ToString(); // 3 } static void F6(E e) { if (e is E { F: { } }) return; e.F.ToString(); // 4 } static void F7(E e) { if (e is { F: object _ }) return; e.F.ToString(); } static void F8(E e) { if (e is { F: object x }) { x.ToString(); return; } e.F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,21): warning CS8618: Non-nullable field 'F' is uninitialized. Consider declaring the field as nullable. // internal object F; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "F").WithArguments("field", "F").WithLocation(5, 21), // (26,9): warning CS8602: Dereference of a possibly null reference. // e.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.F").WithLocation(26, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // e.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.F").WithLocation(31, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // e.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.F").WithLocation(36, 9), // (41,9): warning CS8602: Dereference of a possibly null reference. // e.F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.F").WithLocation(41, 9)); } [Fact] public void OtherComparisonsAsPureNullTests_05() { var source = @"#nullable enable class E { } class Program { static void F(E e) { switch (e) { case { }: return; } e.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // e.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(13, 9)); } [Fact] public void OtherComparisonsAsPureNullTests_06() { var source = @"#nullable enable class E { } class Program { static void F(E e) { switch (e) { case var x when e.ToString() == null: // 1 break; case { }: break; } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,29): warning CS8602: Dereference of a possibly null reference. // case var x when e.ToString() == null: // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(11, 29)); } [Theory] [InlineData("null")] [InlineData("not null")] [InlineData("{}")] public void OtherComparisonsAsPureNullTests_ExtendedProperties_PureNullTest(string pureTest) { var source = $@"#nullable enable class E {{ public E Property1 {{ get; set; }} = null!; public object Property2 {{ get; set; }} = null!; }} class Program {{ static void F(E e) {{ switch (e) {{ case var x when e.Property1.Property2.ToString() == null: // 1 break; case {{ Property1.Property2: {pureTest} }}: break; }} }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics( // (13,29): warning CS8602: Dereference of a possibly null reference. // case var x when e.Property1.Property2.ToString() == null: // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.Property1.Property2").WithLocation(13, 29)); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void OtherComparisonsAreNotPureTest() { var source = @" class C { void F(C x) { if (x is D) { } x.ToString(); } } class D : C { } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ImplicitNullable_01() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { S? x = new S() { F = 1, G = null }; // 1 S? y = x; x.Value.F.ToString(); x.Value.G.ToString(); // 2 y.Value.F.ToString(); y.Value.G.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S? x = new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 37), // (13,9): warning CS8602: Dereference of a possibly null reference. // x.Value.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.G").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.Value.G.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.G").WithLocation(15, 9)); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ImplicitNullable_02() { var source = @"class Program { static void F(int? x) { long? y = x; if (x == null) return; long? z = x; x.Value.ToString(); y.Value.ToString(); // 1 z.Value.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8629: Nullable value type may be null. // y.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(9, 9) ); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ImplicitNullable_03() { var source = @"class Program { static void F(int x) { int? y = x; long? z = x; y.Value.ToString(); z.Value.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ImplicitNullable_04() { var source = @"class Program { static void F1(long x1) { int? y1 = x1; // 1 y1.Value.ToString(); } static void F2(long? x2) { int? y2 = x2; // 2 y2.Value.ToString(); // 3 } static void F3(long? x3) { if (x3 == null) return; int? y3 = x3; // 4 y3.Value.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,19): error CS0266: Cannot implicitly convert type 'long' to 'int?'. An explicit conversion exists (are you missing a cast?) // int? y1 = x1; // 1 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x1").WithArguments("long", "int?").WithLocation(5, 19), // (10,19): error CS0266: Cannot implicitly convert type 'long?' to 'int?'. An explicit conversion exists (are you missing a cast?) // int? y2 = x2; // 2 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x2").WithArguments("long?", "int?").WithLocation(10, 19), // (11,9): warning CS8629: Nullable value type may be null. // y2.Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y2").WithLocation(11, 9), // (16,19): error CS0266: Cannot implicitly convert type 'long?' to 'int?'. An explicit conversion exists (are you missing a cast?) // int? y3 = x3; // 4 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x3").WithArguments("long?", "int?").WithLocation(16, 19) ); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ImplicitNullable_05() { var source = @"#pragma warning disable 0649 struct A { internal object? F; } struct B { internal object? F; } class Program { static void F1() { A a1 = new A(); B? b1 = a1; // 1 _ = b1.Value; b1.Value.F.ToString(); // 2 } static void F2() { A? a2 = new A() { F = 2 }; B? b2 = a2; // 3 _ = b2.Value; b2.Value.F.ToString(); // 4 } static void F3(A? a3) { B? b3 = a3; // 5 _ = b3.Value; // 6 b3.Value.F.ToString(); // 7 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,17): error CS0029: Cannot implicitly convert type 'A' to 'B?' // B? b1 = a1; // 1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "a1").WithArguments("A", "B?").WithLocation(15, 17), // (17,9): warning CS8602: Dereference of a possibly null reference. // b1.Value.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.Value.F").WithLocation(17, 9), // (22,17): error CS0029: Cannot implicitly convert type 'A?' to 'B?' // B? b2 = a2; // 3 Diagnostic(ErrorCode.ERR_NoImplicitConv, "a2").WithArguments("A?", "B?").WithLocation(22, 17), // (24,9): warning CS8602: Dereference of a possibly null reference. // b2.Value.F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b2.Value.F").WithLocation(24, 9), // (28,17): error CS0029: Cannot implicitly convert type 'A?' to 'B?' // B? b3 = a3; // 5 Diagnostic(ErrorCode.ERR_NoImplicitConv, "a3").WithArguments("A?", "B?").WithLocation(28, 17), // (29,13): warning CS8629: Nullable value type may be null. // _ = b3.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "b3").WithLocation(29, 13), // (30,9): warning CS8602: Dereference of a possibly null reference. // b3.Value.F.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b3.Value.F").WithLocation(30, 9) ); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ExplicitNullable_01() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { S x = new S() { F = 1, G = null }; // 1 var y = (S?)x; y.Value.F.ToString(); y.Value.G.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // S x = new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 36), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.Value.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.G").WithLocation(13, 9)); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ExplicitNullable_02() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { S? x = new S() { F = 1, G = null }; // 1 S y = (S)x; y.F.ToString(); y.G.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S? x = new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 37), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.G").WithLocation(13, 9)); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ExplicitNullable_03() { var source = @"class Program { static void F(int? x) { long? y = (long?)x; if (x == null) return; long? z = (long?)x; x.Value.ToString(); y.Value.ToString(); // 1 z.Value.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8629: Nullable value type may be null. // y.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(9, 9) ); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ExplicitNullable_04() { var source = @"class Program { static void F(long? x) { int? y = (int?)x; if (x == null) return; int? z = (int?)x; x.Value.ToString(); y.Value.ToString(); // 1 z.Value.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8629: Nullable value type may be null. // y.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(9, 9) ); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ExplicitNullable_05() { var source = @"class Program { static void F1(int? x1) { int y1 = (int)x1; // 1 } static void F2(int? x2) { if (x2 == null) return; int y2 = (int)x2; } static void F3(int? x3) { long y3 = (long)x3; // 2 } static void F4(int? x4) { if (x4 == null) return; long y4 = (long)x4; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,18): warning CS8629: Nullable value type may be null. // int y1 = (int)x1; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int)x1").WithLocation(5, 18), // (14,19): warning CS8629: Nullable value type may be null. // long y3 = (long)x3; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(long)x3").WithLocation(14, 19)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void Conversions_ExplicitNullable_06() { var source = @"class C { int? i = null; static void F1(C? c) { int i1 = (int)c?.i; // 1 _ = c.ToString(); _ = c.i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,18): warning CS8629: Nullable value type may be null. // int i1 = (int)c?.i; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int)c?.i").WithLocation(7, 18)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void Conversions_ExplicitNullable_07() { var source = @"class C { int? i = null; static void F1(C? c) { int? i1 = (int?)c?.i; _ = c.ToString(); // 1 _ = c.i.Value.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 13), // (9,13): warning CS8629: Nullable value type may be null. // _ = c.i.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.i").WithLocation(9, 13)); } [Fact] [WorkItem(35334, "https://github.com/dotnet/roslyn/issues/35334")] public void Conversions_ExplicitNullable_UserDefinedIntroducingNullability() { var source = @" class A { public static explicit operator B(A a) => throw null!; } class B { void M(A a) { var b = ((B?)a)/*T:B?*/; b.ToString(); // 1 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(8, 9)); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Tuple_Conversions_ImplicitNullable_01() { var source = @"struct S { internal object? F; } class Program { static void F() { S x = new S(); S y = new S() { F = 1 }; (S, S) t = (x, y); (S? x, S? y) u = t; (S?, S?) v = (x, y); t.Item1.F.ToString(); // 1 t.Item2.F.ToString(); u.x.Value.F.ToString(); // 2 u.y.Value.F.ToString(); v.Item1.Value.F.ToString(); // 3 v.Item2.Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1.F").WithLocation(14, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // u.x.Value.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.x.Value.F").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // v.Item1.Value.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v.Item1.Value.F").WithLocation(18, 9) ); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Tuple_Conversions_ImplicitNullable_02() { var source = @"struct S { internal object? F; } class Program { static void F() { S x = new S(); S y = new S() { F = 1 }; (S, S) t = (x, y); (S a, S b)? u = t; t.Item1.F.ToString(); // 1 t.Item2.F.ToString(); u.Value.a.F.ToString(); // 2 u.Value.b.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1.F").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // u.Value.a.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Value.a.F").WithLocation(15, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Tuple_Conversions_ImplicitReference() { var source = @"class Program { static void F(string x, string? y) { (object?, string?) t = (x, y); (object? a, object? b) u = t; t.Item1.ToString(); t.Item2.ToString(); // 1 u.a.ToString(); // 2 u.b.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // u.a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.a").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.b.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.b").WithLocation(10, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Tuple_Conversions_ImplicitDynamic() { var source = @"class Program { static void F(object x, object? y) { (object?, dynamic?) t = (x, y); (dynamic? a, object? b) u = t; t.Item1.ToString(); t.Item2.ToString(); // 1 u.a.ToString(); u.b.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.b.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.b").WithLocation(10, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Tuple_Conversions_Boxing() { var source = @"class Program { static void F<T, U, V>(T x, U y, V? z) where U : struct where V : struct { (object, object, object) t = (x, y, z); // 1 t.Item1.ToString(); // 2 t.Item2.ToString(); t.Item3.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,38): warning CS8619: Nullability of reference types in value of type '(object? x, object y, object? z)' doesn't match target type '(object, object, object)'. // (object, object, object) t = (x, y, z); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y, z)").WithArguments("(object? x, object y, object? z)", "(object, object, object)").WithLocation(7, 38), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // t.Item3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item3").WithLocation(10, 9)); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_Default_01() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F<T, U, V>() where U : class where V : struct { default(S<T>).F/*T:T*/.ToString(); // 1 default(S<U>).F/*T:U?*/.ToString(); // 2 _ = default(S<V?>).F/*T:V?*/.Value; // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // default(S<T>).F/*T:T*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(S<T>).F").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // default(S<U>).F/*T:U?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(S<U>).F").WithLocation(13, 9), // (14,13): warning CS8629: Nullable value type may be null. // _ = default(S<V?>).F/*T:V?*/.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "default(S<V?>).F").WithLocation(14, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_Default_02() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F<T, U, V>() where U : class where V : struct { new S<T>().F/*T:T*/.ToString(); // 1 new S<U>().F/*T:U?*/.ToString(); // 2 _ = new S<V?>().F/*T:V?*/.Value; // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // new S<T>().F/*T:T*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new S<T>().F").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // new S<U>().F/*T:U?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new S<U>().F").WithLocation(13, 9), // (14,13): warning CS8629: Nullable value type may be null. // _ = new S<V?>().F/*T:V?*/.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new S<V?>().F").WithLocation(14, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_Default_03() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F() { S<object> x = default; S<object> y = x; x.F/*T:object?*/.ToString(); // 1 y.F/*T:object?*/.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.F/*T:object?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(13, 9)); comp.VerifyTypes(); } [Fact] public void StructField_Default_04() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F() { S<int?> x = default; S<int?> y = x; _ = x.F.Value; // 1 _ = y.F.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,13): warning CS8629: Nullable value type may be null. // _ = x.F.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x.F").WithLocation(12, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = y.F.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y.F").WithLocation(13, 13) ); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_Default_05() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F() { var x = new S<object>(); var y = x; x.F/*T:object?*/.ToString(); // 1 y.F/*T:object?*/.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.F/*T:object?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(13, 9)); comp.VerifyTypes(); } [Fact] public void StructField_Default_06() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F() { var x = new S<int?>(); var y = x; _ = x.F.Value; // 1 _ = y.F.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,13): warning CS8629: Nullable value type may be null. // _ = x.F.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x.F").WithLocation(12, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = y.F.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y.F").WithLocation(13, 13) ); } [Fact] public void StructField_Default_07() { var source = @"#pragma warning disable 649 struct S<T, U> { internal T F; internal U G; } class Program { static void F(object a, string b) { var x = new S<object, string>() { F = a }; x.F/*T:object!*/.ToString(); x.G/*T:string?*/.ToString(); // 1 var y = new S<object, string>() { G = b }; y.F/*T:object?*/.ToString(); // 2 y.G/*T:string!*/.ToString(); var z = new S<object, string>() { F = default, G = default }; // 3, 4 z.F/*T:object?*/.ToString(); // 5 z.G/*T:string?*/.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // x.G/*T:string?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.G").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.F/*T:object?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(15, 9), // (17,47): warning CS8625: Cannot convert null literal to non-nullable reference type. // var z = new S<object, string>() { F = default, G = default }; // 3, 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(17, 47), // (17,60): warning CS8625: Cannot convert null literal to non-nullable reference type. // var z = new S<object, string>() { F = default, G = default }; // 3, 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(17, 60), // (18,9): warning CS8602: Dereference of a possibly null reference. // z.F/*T:object?*/.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.F").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // z.G/*T:string?*/.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.G").WithLocation(19, 9)); comp.VerifyTypes(); } [Fact] public void StructField_Default_ParameterlessConstructor() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; internal S() { F = default!; } internal S(T t) { F = t; } } class Program { static void F() { var x = default(S<object>); x.F/*T:object?*/.ToString(); // 1 var y = new S<object>(); y.F/*T:object!*/.ToString(); var z = new S<object>(1); z.F/*T:object!*/.ToString(); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,14): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // internal S() { F = default!; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S").WithArguments("parameterless struct constructors", "10.0").WithLocation(5, 14), // (5,14): error CS8938: The parameterless struct constructor must be 'public'. // internal S() { F = default!; } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S").WithLocation(5, 14), // (13,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(13, 9)); comp.VerifyTypes(); } [Fact] public void StructField_Default_NoType() { var source = @"class Program { static void F() { _ = default/*T:!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,13): error CS8716: There is no target type for the default literal. // _ = default/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(5, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_ParameterDefaultValue_01() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F1<T1>(S<T1> x1 = default) { var y1 = x1; x1.F/*T:T1*/.ToString(); // 1 y1.F/*T:T1*/.ToString(); // 2 } static void F2<T2>(S<T2> x2 = default) where T2 : class { var y2 = x2; x2.F/*T:T2?*/.ToString(); // 3 y2.F/*T:T2?*/.ToString(); // 4 } static void F3<T3>(S<T3?> x3 = default) where T3 : struct { var y3 = x3; _ = x3.F/*T:T3?*/.Value; // 5 _ = y3.F/*T:T3?*/.Value; // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // x1.F/*T:T1*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1.F").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // y1.F/*T:T1*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1.F").WithLocation(12, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // x2.F/*T:T2?*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2.F").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // y2.F/*T:T2?*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2.F").WithLocation(18, 9), // (23,13): warning CS8629: Nullable value type may be null. // _ = x3.F/*T:T3?*/.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x3.F").WithLocation(23, 13), // (24,13): warning CS8629: Nullable value type may be null. // _ = y3.F/*T:T3?*/.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y3.F").WithLocation(24, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_ParameterDefaultValue_02() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; internal S(T t) { F = t; } } class Program { static void F<T>(S<T> x = new S<T>(), S<T> y = null, S<T> z = new S<T>(default)) where T : class { x.F/*T:T?*/.ToString(); // 1 y.F/*T:T!*/.ToString(); z.F/*T:T!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,48): error CS1750: A value of type '<null>' cannot be used as a default parameter because there are no standard conversions to type 'S<T>' // static void F<T>(S<T> x = new S<T>(), S<T> y = null, S<T> z = new S<T>(default)) where T : class Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "y").WithArguments("<null>", "S<T>").WithLocation(9, 48), // (9,67): error CS1736: Default parameter value for 'z' must be a compile-time constant // static void F<T>(S<T> x = new S<T>(), S<T> y = null, S<T> z = new S<T>(default)) where T : class Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new S<T>(default)").WithArguments("z").WithLocation(9, 67), // (9,76): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F<T>(S<T> x = new S<T>(), S<T> y = null, S<T> z = new S<T>(default)) where T : class Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(9, 76), // (11,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:T?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(11, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_ParameterDefaultValue_03() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F<T>(S<T> x = /*missing*/, S<T> y = default) where T : class { x.F/*T:T!*/.ToString(); y.F/*T:T?*/.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,42): error CS1525: Invalid expression term ',' // static void F<T>(S<T> x = /*missing*/, S<T> y = default) where T : class Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(8, 42), // (11,9): warning CS8602: Dereference of a possibly null reference. // y.F/*T:T?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(11, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_ParameterDefaultValue_04() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F<T>(S<T>? x = default(S<T>)) where T : class { if (x == null) return; var y = x.Value; y.F/*T:T!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,28): error CS1770: A value of type 'S<T>' cannot be used as default parameter for nullable parameter 'x' because 'S<T>' is not a simple type // static void F<T>(S<T>? x = default(S<T>)) where T : class Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "x").WithArguments("S<T>", "x").WithLocation(8, 28)); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_Default_Nested() { var source = @"#pragma warning disable 649 struct S { internal S(int i) { S1 = null!; T = default; } internal object S1; internal T T; } struct T { internal object T1; } class Program { static void F1() { // default S s1 = default; s1.S1.ToString(); // 1 s1.T.T1.ToString(); // 2 } static void F2() { // default constructor S s2 = new S(); s2.S1.ToString(); // 3 s2.T.T1.ToString(); // 4 } static void F3() { // explicit constructor S s3 = new S(0); s3.S1.ToString(); s3.T.T1.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (22,9): warning CS8602: Dereference of a possibly null reference. // s1.S1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1.S1").WithLocation(22, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // s1.T.T1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1.T.T1").WithLocation(23, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // s2.S1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2.S1").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // s2.T.T1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2.T.T1").WithLocation(30, 9)); } [Fact] public void StructField_Cycle_Default() { // Nullability of F is treated as object!, even for default instances, because a struct with cycles // is not a "trackable" struct type (see EmptyStructTypeCache.IsTrackableStructType). var source = @"#pragma warning disable 649 struct S { internal S Next; internal object F; } class Program { static void F() { default(S).F/*T:object!*/.ToString(); S x = default; S y = x; x.F/*T:object!*/.ToString(); x.Next.F/*T:object!*/.ToString(); y.F/*T:object!*/.ToString(); y.Next.F/*T:object!*/.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,16): error CS0523: Struct member 'S.Next' of type 'S' causes a cycle in the struct layout // internal S Next; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "Next").WithArguments("S.Next", "S").WithLocation(4, 16)); comp.VerifyTypes(); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructProperty_Cycle_Default() { var source = @"#pragma warning disable 649 struct S { internal S Next { get => throw null!; set { } } internal object F; } class Program { static void F() { S x = default; S y = x; x.F/*T:object?*/.ToString(); // 1 x.Next.F/*T:object!*/.ToString(); y.F/*T:object?*/.ToString(); // 2 y.Next.F/*T:object!*/.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(17, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // y.F/*T:object?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(19, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructProperty_Cycle() { var source = @"struct S { internal object? F; internal S P { get { return this; } set { this = value; } } } class Program { static void M(S s) { s.F = 2; for (int i = 0; i < 3; i++) { s.P = s; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructField_Cycle_01() { var source = @"#pragma warning disable 649 struct S { internal S F; internal object? P => null; } class Program { static void F(S x, S y) { if (y.P == null) return; x.P.ToString(); // 1 y.P.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,16): error CS0523: Struct member 'S.F' of type 'S' causes a cycle in the struct layout // internal S F; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("S.F", "S").WithLocation(4, 16), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.P").WithLocation(12, 9)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructField_Cycle_02() { var source0 = @".class public sealed S extends [mscorlib]System.ValueType { .field public valuetype [mscorlib]System.Nullable`1<valuetype S> F }"; var ref0 = CompileIL(source0); var source = @"class Program { static void F(S x, S y) { if (y.F == null) return; _ = x.F.Value; // 1 _ = y.F.Value; } }"; var comp = CreateCompilation(new[] { source }, new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8629: Nullable value type may be null. // _ = x.F.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x.F").WithLocation(6, 13)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructField_Cycle_03() { var source0 = @".class public sealed S extends [mscorlib]System.ValueType { .field public valuetype S F .field public object G }"; var ref0 = CompileIL(source0); var source = @"class Program { static void F(S s) { s.G = null; s.G.ToString(); // 1 } }"; var comp = CreateCompilation(new[] { source }, new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.G.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.G").WithLocation(6, 9)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructField_Cycle_04() { var source0 = @".class public sealed S extends [mscorlib]System.ValueType { .field public valuetype S F .method public instance object get_P() { ldnull ret } .method public instance void set_P(object 'value') { ret } .property instance object P() { .get instance object S::get_P() .set instance void S::set_P(object) } }"; var ref0 = CompileIL(source0); var source = @"class Program { static void F(S s) { s.P = null; s.P.ToString(); // 1 } }"; var comp = CreateCompilation(new[] { source }, new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructPropertyNoBackingField() { var source0 = @".class public sealed S extends [mscorlib]System.ValueType { .method public instance object get_P() { ldnull ret } .method public instance void set_P(object 'value') { ret } .property instance object P() { .get instance object S::get_P() .set instance void S::set_P(object) } }"; var ref0 = CompileIL(source0); var source = @"class Program { static void F(S s) { s.P = null; s.P.ToString(); // 1 } }"; var comp = CreateCompilation(new[] { source }, new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.P").WithLocation(6, 9)); } // `default` expression in a split state. [Fact] public void IsPattern_DefaultTrackableStruct() { var source = @"#pragma warning disable 649 struct S { internal object F; } class Program { static void F() { if (default(S) is default) { } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (default(S) is default) { } Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(10, 27)); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_Default_01() { var source = @"class Program { static void F() { default((object?, string))/*T:(object?, string!)*/.Item2.ToString(); // 1 _ = default((int, int?))/*T:(int, int?)*/.Item2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // default((object?, string))/*T:(object?, string!)*/.Item2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default((object?, string))/*T:(object?, string!)*/.Item2").WithLocation(5, 9), // (6,13): warning CS8629: Nullable value type may be null. // _ = default((int, int?))/*T:(int, int?)*/.Item2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "default((int, int?))/*T:(int, int?)*/.Item2").WithLocation(6, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_Default_02() { var source = @"using System; class Program { static void F1() { new ValueTuple<object?, string>()/*T:(object?, string!)*/.Item2.ToString(); // 1 _ = new ValueTuple<int, int?>()/*T:(int, int?)*/.Item2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // new ValueTuple<object?, string>()/*T:(object?, string!)*/.Item2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new ValueTuple<object?, string>()/*T:(object?, string!)*/.Item2").WithLocation(6, 9), // (7,13): warning CS8629: Nullable value type may be null. // _ = new ValueTuple<int, int?>()/*T:(int, int?)*/.Item2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new ValueTuple<int, int?>()/*T:(int, int?)*/.Item2").WithLocation(7, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_Default_03() { var source = @"class Program { static void F() { (object, (object?, string)) t = default/*CT:(object!, (object?, string!))*/; (object, (object?, string)) u = t; t.Item1/*T:object?*/.ToString(); // 1 t.Item2.Item2/*T:string?*/.ToString(); // 2 u.Item1/*T:object?*/.ToString(); // 3 u.Item2.Item2/*T:string?*/.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // t.Item1/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.Item2/*T:string?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2.Item2").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // u.Item1/*T:object?*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.Item2/*T:string?*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2.Item2").WithLocation(10, 9)); comp.VerifyTypes(); } [Fact] public void Tuple_Default_04() { var source = @"class Program { static void F() { (int, int?) t = default/*CT:(int, int?)*/; (int, int?) u = t; _ = t.Item2.Value; // 1 _ = u.Item2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8629: Nullable value type may be null. // _ = t.Item2.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t.Item2").WithLocation(7, 13), // (8,13): warning CS8629: Nullable value type may be null. // _ = u.Item2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "u.Item2").WithLocation(8, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_Default_05() { var source = @"using System; class Program { static void F1() { var t = new ValueTuple<object, ValueTuple<object?, string>>()/*T:(object!, (object?, string!))*/; var u = t; t.Item1/*T:object?*/.ToString(); // 1 t.Item2.Item2/*T:string?*/.ToString(); // 2 u.Item1/*T:object?*/.ToString(); // 3 u.Item2.Item2/*T:string?*/.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item1/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.Item2/*T:string?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2.Item2").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.Item1/*T:object?*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.Item2/*T:string?*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2.Item2").WithLocation(11, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_Default_06() { var source = @"using System; class Program { static void F1() { var t = new ValueTuple<int, int?>()/*T:(int, int?)*/; var u = t; _ = t.Item2.Value; // 1 _ = u.Item2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8629: Nullable value type may be null. // _ = t.Item2.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t.Item2").WithLocation(8, 13), // (9,13): warning CS8629: Nullable value type may be null. // _ = u.Item2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "u.Item2").WithLocation(9, 13) ); comp.VerifyTypes(); } [Fact, WorkItem(33344, "https://github.com/dotnet/roslyn/issues/33344")] public void Tuple_Default_07() { var source = @" #nullable enable class C { void M() { (object?, string?) tuple = default/*CT:(object?, string?)*/; tuple.Item1.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // tuple.Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "tuple.Item1").WithLocation(8, 9)); comp.VerifyTypes(); } [Fact] public void Tuple_Default_NoType() { var source = @"class Program { static void F(object? x, bool b) { _ = (default, default)/*T:<null>!*/.Item1.ToString(); _ = (x, default)/*T:<null>!*/.Item2.ToString(); (b switch { _ => null }).ToString(); (b ? null : null).ToString(); (new()).ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,14): error CS8716: There is no target type for the default literal. // _ = (default, default)/*T:<null>!*/.Item1.ToString(); Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(5, 14), // (5,23): error CS8716: There is no target type for the default literal. // _ = (default, default)/*T:<null>!*/.Item1.ToString(); Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(5, 23), // (6,17): error CS8716: There is no target type for the default literal. // _ = (x, default)/*T:<null>!*/.Item2.ToString(); Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(6, 17), // (7,12): error CS8506: No best type was found for the switch expression. // (b switch { _ => null }).ToString(); Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(7, 12), // (8,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and '<null>' // (b ? null : null).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? null : null").WithArguments("<null>", "<null>").WithLocation(8, 10), // (9,10): error CS8754: There is no target type for 'new()' // (new()).ToString(); Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(9, 10) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_ParameterDefaultValue_01() { var source = @"class Program { static void F<T, U, V>((T x, U y, V? z) t = default) where U : class where V : struct { var u = t/*T:(T x, U! y, V? z)*/; t.x/*T:T*/.ToString(); // 1 t.y/*T:U?*/.ToString(); // 2 _ = t.z/*T:V?*/.Value; // 3 u.x/*T:T*/.ToString(); // 4 u.y/*T:U?*/.ToString(); // 5 _ = u.z/*T:V?*/.Value; // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.x/*T:T*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.x").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.y/*T:U?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.y").WithLocation(9, 9), // (10,13): warning CS8629: Nullable value type may be null. // _ = t.z/*T:V?*/.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t.z").WithLocation(10, 13), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.x/*T:T*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.x").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // u.y/*T:U?*/.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.y").WithLocation(12, 9), // (13,13): warning CS8629: Nullable value type may be null. // _ = u.z/*T:V?*/.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "u.z").WithLocation(13, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_ParameterDefaultValue_02() { var source = @"class Program { static void F<T, U, V>( (T, U, V?) x = new System.ValueTuple<T, U, V?>(), (T, U, V?) y = null, (T, U, V?) z = (default(T), new U(), new V())) where U : class, new() where V : struct { x.Item1/*T:T*/.ToString(); // 1 x.Item2/*T:U?*/.ToString(); // 2 _ = x.Item3/*T:V?*/.Value; // 3 y.Item1/*T:T*/.ToString(); // 4 y.Item2/*T:U!*/.ToString(); _ = y.Item3/*T:V?*/.Value; // 5 z.Item1/*T:T*/.ToString(); // 6 z.Item2/*T:U!*/.ToString(); _ = z.Item3/*T:V?*/.Value; // 7 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): error CS1750: A value of type '<null>' cannot be used as a default parameter because there are no standard conversions to type '(T, U, V?)' // (T, U, V?) y = null, Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "y").WithArguments("<null>", "(T, U, V?)").WithLocation(5, 20), // (6,24): error CS1736: Default parameter value for 'z' must be a compile-time constant // (T, U, V?) z = (default(T), new U(), new V())) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "(default(T), new U(), new V())").WithArguments("z").WithLocation(6, 24), // (6,24): warning CS8619: Nullability of reference types in value of type '(T?, U, V?)' doesn't match target type '(T, U, V?)'. // (T, U, V?) z = (default(T), new U(), new V())) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default(T), new U(), new V())").WithArguments("(T?, U, V?)", "(T, U, V?)").WithLocation(6, 24), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.Item1/*T:T*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Item1").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // x.Item2/*T:U?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Item2").WithLocation(11, 9), // (12,13): warning CS8629: Nullable value type may be null. // _ = x.Item3/*T:V?*/.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x.Item3").WithLocation(12, 13), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.Item1/*T:T*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Item1").WithLocation(13, 9), // (15,13): warning CS8629: Nullable value type may be null. // _ = y.Item3/*T:V?*/.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y.Item3").WithLocation(15, 13), // (16,9): warning CS8602: Dereference of a possibly null reference. // z.Item1/*T:T*/.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.Item1").WithLocation(16, 9), // (18,13): warning CS8629: Nullable value type may be null. // _ = z.Item3/*T:V?*/.Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "z.Item3").WithLocation(18, 13) ); comp.VerifyTypes(); } [Fact] public void Tuple_Constructor() { var source = @"class C { C((string x, string? y) t) { } static void M(string x, string? y) { C c; c = new C((x, x)); c = new C((x, y)); c = new C((y, x)); // 1 c = new C((y, y)); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,19): warning CS8620: Nullability of reference types in argument of type '(string? y, string x)' doesn't match target type '(string x, string? y)' for parameter 't' in 'C.C((string x, string? y) t)'. // c = new C((y, x)); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, x)").WithArguments("(string? y, string x)", "(string x, string? y)", "t", "C.C((string x, string? y) t)").WithLocation(9, 19), // (10,19): warning CS8620: Nullability of reference types in argument of type '(string?, string?)' doesn't match target type '(string x, string? y)' for parameter 't' in 'C.C((string x, string? y) t)'. // c = new C((y, y)); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, y)").WithArguments("(string?, string?)", "(string x, string? y)", "t", "C.C((string x, string? y) t)").WithLocation(10, 19)); } [Fact] public void Tuple_Indexer() { var source = @"class C { object? this[(string x, string? y) t] => null; static void M(string x, string? y) { var c = new C(); object? o; o = c[(x, x)]; o = c[(x, y)]; o = c[(y, x)]; // 1 o = c[(y, y)]; // 2 var t = (y, x); o = c[t]; // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,15): warning CS8620: Nullability of reference types in argument of type '(string? y, string x)' doesn't match target type '(string x, string? y)' for parameter 't' in 'object? C.this[(string x, string? y) t]'. // o = c[(y, x)]; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, x)").WithArguments("(string? y, string x)", "(string x, string? y)", "t", "object? C.this[(string x, string? y) t]").WithLocation(10, 15), // (11,15): warning CS8620: Nullability of reference types in argument of type '(string?, string?)' doesn't match target type '(string x, string? y)' for parameter 't' in 'object? C.this[(string x, string? y) t]'. // o = c[(y, y)]; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, y)").WithArguments("(string?, string?)", "(string x, string? y)", "t", "object? C.this[(string x, string? y) t]").WithLocation(11, 15), // (13,15): warning CS8620: Nullability of reference types in argument of type '(string? y, string x)' doesn't match target type '(string x, string? y)' for parameter 't' in 'object? C.this[(string x, string? y) t]'. // o = c[t]; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t").WithArguments("(string? y, string x)", "(string x, string? y)", "t", "object? C.this[(string x, string? y) t]").WithLocation(13, 15)); } [Fact] public void Tuple_CollectionInitializer() { var source = @"using System.Collections.Generic; class C { static void M(string x, string? y) { var c = new List<(string, string?)> { (x, x), (x, y), (y, x), // 1 (y, y), // 2 }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8620: Nullability of reference types in argument of type '(string? y, string x)' doesn't match target type '(string, string?)' for parameter 'item' in 'void List<(string, string?)>.Add((string, string?) item)'. // (y, x), // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, x)").WithArguments("(string? y, string x)", "(string, string?)", "item", "void List<(string, string?)>.Add((string, string?) item)").WithLocation(10, 13), // (11,13): warning CS8620: Nullability of reference types in argument of type '(string?, string?)' doesn't match target type '(string, string?)' for parameter 'item' in 'void List<(string, string?)>.Add((string, string?) item)'. // (y, y), // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, y)").WithArguments("(string?, string?)", "(string, string?)", "item", "void List<(string, string?)>.Add((string, string?) item)").WithLocation(11, 13)); } [Fact] public void Tuple_Method() { var source = @"class C { static void F(object? x, object? y) { if (x == null) return; (x, y).ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Tuple_OtherMembers_01() { var source = @"internal delegate T D<T>(); namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; F1 = item1; E2 = null; } public T1 Item1; public T2 Item2; internal T1 F1; internal T1 P1 => Item1; internal event D<T2>? E2; } } class C { static void F(object? x) { var y = (x, x); y.F1.ToString(); // 1 y.P1.ToString(); // 2 y.E2?.Invoke().ToString(); // 3 if (x == null) return; var z = (x, x); z.F1.ToString(); z.P1.ToString(); z.E2?.Invoke().ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), targetFramework: TargetFramework.Mscorlib46); comp.VerifyDiagnostics( // (27,11): error CS0070: The event '(object, object).E2' can only appear on the left hand side of += or -= (except when used from within the type '(object, object)') // y.E2?.Invoke().ToString(); // 3 Diagnostic(ErrorCode.ERR_BadEventUsage, "E2").WithArguments("(object, object).E2", "(object, object)").WithLocation(27, 11), // (32,11): error CS0070: The event '(object, object).E2' can only appear on the left hand side of += or -= (except when used from within the type '(object, object)') // z.E2?.Invoke().ToString(); Diagnostic(ErrorCode.ERR_BadEventUsage, "E2").WithArguments("(object, object).E2", "(object, object)").WithLocation(32, 11), // (25,9): warning CS8602: Dereference of a possibly null reference. // y.F1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F1").WithLocation(25, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // y.P1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.P1").WithLocation(26, 9)); } [Fact] public void Tuple_OtherMembers_02() { // https://github.com/dotnet/roslyn/issues/33578 // Cannot test Derived<T> since tuple types are considered sealed and the base type // is dropped: "error CS0509: 'Derived<T>': cannot derive from sealed type '(T, T)'". var source = @"namespace System { public class Base<T> { public Base(T t) { F = t; } public T F; } public class ValueTuple<T1, T2> : Base<T1> { public ValueTuple(T1 item1, T2 item2) : base(item1) { Item1 = item1; Item2 = item2; } public T1 Item1; public T2 Item2; } //public class Derived<T> : ValueTuple<T, T> //{ // public Derived(T t) : base(t, t) { } // public T P { get; set; } //} } class C { static void F(object? x) { var y = (x, x); y.F.ToString(); // 1 y.Item2.ToString(); // 2 if (x == null) return; var z = (x, x); z.F.ToString(); z.Item2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), targetFramework: TargetFramework.Mscorlib46); comp.VerifyDiagnostics( // (29,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // y.Item2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Item2").WithLocation(30, 9)); } [Fact] public void Tuple_OtherMembers_03() { var source = @"namespace System { public class Object { public string ToString() => throw null!; public object? F; } public class String { } public abstract class ValueType { public object? P { get; set; } } public struct Void { } public struct Boolean { } public struct Enum { } public class Attribute { } public struct Int32 { } public class Exception { } public class AttributeUsageAttribute : Attribute { public AttributeUsageAttribute(AttributeTargets validOn) => throw null!; public bool AllowMultiple { get; set; } } public enum AttributeTargets { Assembly = 1, Module = 2, Class = 4, Struct = 8, Enum = 16, Constructor = 32, Method = 64, Property = 128, Field = 256, Event = 512, Interface = 1024, Parameter = 2048, Delegate = 4096, ReturnValue = 8192, GenericParameter = 16384, All = 32767 } public class ObsoleteAttribute : Attribute { public ObsoleteAttribute(string message) => throw null!; } public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; } } class C { static void M(object x) { var y = (x, x); y.F.ToString(); y.P.ToString(); } }"; var comp = CreateEmptyCompilation(source); comp.VerifyDiagnostics( // (6,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public object? F; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 22), // (11,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public object? P { get; set; } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 22) ); var comp2 = CreateEmptyCompilation(new[] { source }, options: WithNullableEnable()); comp2.VerifyDiagnostics( // (36,22): warning CS8597: Thrown value may be null. // => throw null; Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "null").WithLocation(36, 22), // (45,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(45, 9), // (46,9): warning CS8602: Dereference of a possibly null reference. // y.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.P").WithLocation(46, 9)); } [Fact] public void TypeInference_TupleNameDifferences_01() { var source = @"class C<T> { } static class E { public static T F<T>(this C<T> c, T t) => t; } class C { static void F(object o) { var c = new C<(object x, int y)>(); c.F((o, -1)).x.ToString(); } }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (13,22): error CS1061: '(object, int)' does not contain a definition for 'x' and no extension method 'x' accepting a first argument of type '(object, int)' could be found (are you missing a using directive or an assembly reference?) // c.F((o, -1)).x.ToString(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "x").WithArguments("(object, int)", "x").WithLocation(13, 22)); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,22): error CS1061: '(object, int)' does not contain a definition for 'x' and no extension method 'x' accepting a first argument of type '(object, int)' could be found (are you missing a using directive or an assembly reference?) // c.F((o, -1)).x.ToString(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "x").WithArguments("(object, int)", "x").WithLocation(13, 22)); } [Fact] public void TypeInference_TupleNameDifferences_02() { var source = @"class C<T> { } static class E { public static T F<T>(this C<T> c, T t) => t; } class C { static void F(object o) { var c = new C<(object? x, int y)>(); c.F((o, -1))/*T:(object?, int)*/.x.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,42): error CS1061: '(object, int)' does not contain a definition for 'x' and no accessible extension method 'x' accepting a first argument of type '(object, int)' could be found (are you missing a using directive or an assembly reference?) // c.F((o, -1))/*T:(object?, int)*/.x.ToString(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "x").WithArguments("(object, int)", "x").WithLocation(13, 42)); comp.VerifyTypes(); } [Fact] public void TypeInference_DynamicDifferences_01() { var source = @"class C<T> { } static class E { public static T F<T>(this C<T> c, T t) => t; } class C { static void F(dynamic x, object y) { var c = new C<(object, object)>(); c.F((x, y))/*T:(dynamic!, object!)*/.Item1.G(); } }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void TypeInference_DynamicDifferences_02() { var source = @"class C<T> { } static class E { public static T F<T>(this C<T> c, T t) => t; } class C { static void F(dynamic x, object y) { var c = new C<(object, object?)>(); c.F((x, y))/*T:(dynamic!, object?)*/.Item1.G(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } // Assert failure in ConversionsBase.IsValidExtensionMethodThisArgConversion. [WorkItem(22317, "https://github.com/dotnet/roslyn/issues/22317")] [Fact(Skip = "22317")] public void TypeInference_DynamicDifferences_03() { var source = @"interface I<T> { } static class E { public static T F<T>(this I<T> i, T t) => t; } class C { static void F(I<object> i, dynamic? d) { i.F(d).G(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): error CS1929: 'I<object>' does not contain a definition for 'F' and the best extension method overload 'E.F<T>(I<T>, T)' requires a receiver of type 'I<T>' // i.F(d).G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "i").WithArguments("I<object>", "F", "E.F<T>(I<T>, T)", "I<T>").WithLocation(12, 9)); } [Fact] public void NullableConversionAndNullCoalescingOperator_01() { var source = @"#pragma warning disable 0649 struct S { short F; static ushort G(S? s) { return (ushort)(s?.F ?? 0); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableConversionAndNullCoalescingOperator_02() { var source = @"struct S { public static implicit operator int(S s) => 0; } class P { static int F(S? x, int y) => x ?? y; static int G(S x, int? y) => y ?? x; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ConstrainedToTypeParameter_01() { var source = @"class C<T, U> where U : T { }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ConstrainedToTypeParameter_02() { var source = @"class C<T> where T : C<T> { }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ArrayElementConversion() { var source = @"class C { static object F() => new sbyte[] { -1 }; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void TrackNonNullableLocals() { var source = @"class C { static void F(object x) { object y = x; x.ToString(); // 1 y.ToString(); // 2 x = null; y = x; x.ToString(); // 3 y.ToString(); // 4 x = null; y = x; if (x == null) return; if (y == null) return; x.ToString(); // 5 y.ToString(); // 6 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 13), // (9,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(9, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 9), // (12,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 13), // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(13, 13)); } [Fact] public void TrackNonNullableFieldsAndProperties() { var source = @"#pragma warning disable 8618 class C { object F; object P { get; set; } static void M(C c) { c.F.ToString(); // 1 c.P.ToString(); // 2 c.F = null; c.P = null; c.F.ToString(); // 3 c.P.ToString(); // 4 if (c.F == null) return; if (c.P == null) return; c.F.ToString(); // 5 c.P.ToString(); // 6 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.F = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 15), // (11,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.P = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 15), // (12,9): warning CS8602: Dereference of a possibly null reference. // c.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(13, 9)); } [Fact] public void TrackNonNullableFields_ObjectInitializer() { var source = @"class C<T> { internal T F = default!; } class Program { static void F1(object? x1) { C<object> c1; c1 = new C<object>() { F = x1 }; // 1 c1 = new C<object>() { F = c1.F }; // 2 c1.F.ToString(); // 3 } static void F2<T>() { C<T> c2; c2 = new C<T>() { F = default }; // 4 c2 = new C<T>() { F = c2.F }; // 5 c2.F.ToString(); // 6 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,36): warning CS8601: Possible null reference assignment. // c1 = new C<object>() { F = x1 }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x1").WithLocation(10, 36), // (11,36): warning CS8601: Possible null reference assignment. // c1 = new C<object>() { F = c1.F }; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c1.F").WithLocation(11, 36), // (12,9): warning CS8602: Dereference of a possibly null reference. // c1.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.F").WithLocation(12, 9), // (17,31): warning CS8601: Possible null reference assignment. // c2 = new C<T>() { F = default }; // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(17, 31), // (18,31): warning CS8601: Possible null reference assignment. // c2 = new C<T>() { F = c2.F }; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c2.F").WithLocation(18, 31), // (19,9): warning CS8602: Dereference of a possibly null reference. // c2.F.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2.F").WithLocation(19, 9)); } [Fact] public void TrackUnannotatedFieldsAndProperties() { var source0 = @"public class C { public object F; public object P { get; set; } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var source1 = @"class P { static void M(C c, object? o) { c.F.ToString(); c.P.ToString(); c.F = o; c.P = o; c.F.ToString(); // 1 c.P.ToString(); // 2 c.F = o; c.P = o; if (c.F == null) return; if (c.P == null) return; c.F.ToString(); c.P.ToString(); } }"; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { comp0.EmitToImageReference() }); comp1.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(10, 9)); } /// <summary> /// Assignment warnings for local and parameters should be distinct from /// fields and properties because the former may be warnings from legacy /// method bodies and it should be possible to disable those warnings separately. /// </summary> [Fact] public void AssignmentWarningsDistinctForLocalsAndParameters() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C { internal object F; internal object P { get; set; } } class P { static void F(out object? x) { x = null; } static void Local() { object? y = null; object x1 = null; x1 = y; F(out x1); } static void Parameter(object x2) { object? y = null; x2 = null; x2 = y; F(out x2); } static void OutParameter(out object x3) { object? y = null; x3 = null; x3 = y; F(out x3); } static void RefParameter(ref object x4) { object? y = null; x4 = null; x4 = y; F(out x4); } static void Field() { var c = new C(); object? y = null; c.F = null; c.F = y; F(out c.F); } static void Property() { var c = new C(); object? y = null; c.P = null; c.P = y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x1 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(17, 21), // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = y; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(18, 14), // (19,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(out x1); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(19, 15), // (24,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(24, 14), // (25,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = y; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(25, 14), // (26,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(out x2); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(26, 15), // (31,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // x3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(31, 14), // (32,14): warning CS8601: Possible null reference assignment. // x3 = y; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(32, 14), // (33,15): warning CS8601: Possible null reference assignment. // F(out x3); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x3").WithLocation(33, 15), // (38,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // x4 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(38, 14), // (39,14): warning CS8601: Possible null reference assignment. // x4 = y; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(39, 14), // (40,15): warning CS8601: Possible null reference assignment. // F(out x4); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x4").WithLocation(40, 15), // (46,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.F = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(46, 15), // (47,15): warning CS8601: Possible null reference assignment. // c.F = y; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(47, 15), // (48,15): warning CS8601: Possible null reference assignment. // F(out c.F); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c.F").WithLocation(48, 15), // (54,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.P = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(54, 15), // (55,15): warning CS8601: Possible null reference assignment. // c.P = y; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(55, 15)); } /// <summary> /// Explicit cast does not cast away top-level nullability. /// </summary> [Fact] public void ExplicitCast() { var source = @"#pragma warning disable 0649 class A<T> { internal T F; } class B1 : A<string> { } class B2 : A<string?> { } class C { static void F0() { ((A<string>)null).F.ToString(); ((A<string>?)null).F.ToString(); ((A<string?>)default).F.ToString(); ((A<string?>?)default).F.ToString(); } static void F1(A<string> x1, A<string>? y1) { ((B2?)x1).F.ToString(); ((B2)y1).F.ToString(); } static void F2(B1 x2, B1? y2) { ((A<string?>?)x2).F.ToString(); ((A<string?>)y2).F.ToString(); } static void F3(A<string?> x3, A<string?>? y3) { ((B2?)x3).F.ToString(); ((B2)y3).F.ToString(); } static void F4(B2 x4, B2? y4) { ((A<string>?)x4).F.ToString(); ((A<string>)y4).F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,16): warning CS8618: Non-nullable field 'F' is uninitialized. Consider declaring the field as nullable. // internal T F; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "F").WithArguments("field", "F").WithLocation(4, 16), // (12,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((A<string>)null).F.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(A<string>)null").WithLocation(12, 10), // (12,10): warning CS8602: Dereference of a possibly null reference. // ((A<string>)null).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string>)null").WithLocation(12, 10), // (13,10): warning CS8602: Dereference of a possibly null reference. // ((A<string>?)null).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string>?)null").WithLocation(13, 10), // (14,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((A<string?>)default).F.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(A<string?>)default").WithLocation(14, 10), // (14,10): warning CS8602: Dereference of a possibly null reference. // ((A<string?>)default).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string?>)default").WithLocation(14, 10), // (14,9): warning CS8602: Dereference of a possibly null reference. // ((A<string?>)default).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((A<string?>)default).F").WithLocation(14, 9), // (15,10): warning CS8602: Dereference of a possibly null reference. // ((A<string?>?)default).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string?>?)default").WithLocation(15, 10), // (15,9): warning CS8602: Dereference of a possibly null reference. // ((A<string?>?)default).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((A<string?>?)default).F").WithLocation(15, 9), // (19,10): warning CS8619: Nullability of reference types in value of type 'A<string>' doesn't match target type 'B2'. // ((B2?)x1).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B2?)x1").WithArguments("A<string>", "B2").WithLocation(19, 10), // (19,10): warning CS8602: Dereference of a possibly null reference. // ((B2?)x1).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(B2?)x1").WithLocation(19, 10), // (19,9): warning CS8602: Dereference of a possibly null reference. // ((B2?)x1).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((B2?)x1).F").WithLocation(19, 9), // (20,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((B2)y1).F.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B2)y1").WithLocation(20, 10), // (20,10): warning CS8619: Nullability of reference types in value of type 'A<string>' doesn't match target type 'B2'. // ((B2)y1).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B2)y1").WithArguments("A<string>", "B2").WithLocation(20, 10), // (20,10): warning CS8602: Dereference of a possibly null reference. // ((B2)y1).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(B2)y1").WithLocation(20, 10), // (20,9): warning CS8602: Dereference of a possibly null reference. // ((B2)y1).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((B2)y1).F").WithLocation(20, 9), // (24,10): warning CS8619: Nullability of reference types in value of type 'B1' doesn't match target type 'A<string?>'. // ((A<string?>?)x2).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<string?>?)x2").WithArguments("B1", "A<string?>").WithLocation(24, 10), // (24,10): warning CS8602: Dereference of a possibly null reference. // ((A<string?>?)x2).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string?>?)x2").WithLocation(24, 10), // (24,9): warning CS8602: Dereference of a possibly null reference. // ((A<string?>?)x2).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((A<string?>?)x2).F").WithLocation(24, 9), // (25,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((A<string?>)y2).F.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(A<string?>)y2").WithLocation(25, 10), // (25,10): warning CS8619: Nullability of reference types in value of type 'B1' doesn't match target type 'A<string?>'. // ((A<string?>)y2).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<string?>)y2").WithArguments("B1", "A<string?>").WithLocation(25, 10), // (25,10): warning CS8602: Dereference of a possibly null reference. // ((A<string?>)y2).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string?>)y2").WithLocation(25, 10), // (25,9): warning CS8602: Dereference of a possibly null reference. // ((A<string?>)y2).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((A<string?>)y2).F").WithLocation(25, 9), // (29,10): warning CS8602: Dereference of a possibly null reference. // ((B2?)x3).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(B2?)x3").WithLocation(29, 10), // (29,9): warning CS8602: Dereference of a possibly null reference. // ((B2?)x3).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((B2?)x3).F").WithLocation(29, 9), // (30,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((B2)y3).F.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B2)y3").WithLocation(30, 10), // (30,10): warning CS8602: Dereference of a possibly null reference. // ((B2)y3).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(B2)y3").WithLocation(30, 10), // (30,9): warning CS8602: Dereference of a possibly null reference. // ((B2)y3).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((B2)y3).F").WithLocation(30, 9), // (34,10): warning CS8619: Nullability of reference types in value of type 'B2' doesn't match target type 'A<string>'. // ((A<string>?)x4).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<string>?)x4").WithArguments("B2", "A<string>").WithLocation(34, 10), // (34,10): warning CS8602: Dereference of a possibly null reference. // ((A<string>?)x4).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string>?)x4").WithLocation(34, 10), // (35,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((A<string>)y4).F.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(A<string>)y4").WithLocation(35, 10), // (35,10): warning CS8619: Nullability of reference types in value of type 'B2' doesn't match target type 'A<string>'. // ((A<string>)y4).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<string>)y4").WithArguments("B2", "A<string>").WithLocation(35, 10), // (35,10): warning CS8602: Dereference of a possibly null reference. // ((A<string>)y4).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string>)y4").WithLocation(35, 10) ); } [Fact] public void ExplicitCast_NestedNullability_01() { var source = @"class A<T> { } class B<T> : A<T> { } class C { static void F1(A<object> x1, A<object?> y1) { object o; o = (B<object>)x1; o = (B<object?>)x1; // 1 o = (B<object>)y1; // 2 o = (B<object?>)y1; } static void F2(B<object> x2, B<object?> y2) { object o; o = (A<object>)x2; o = (A<object?>)x2; // 3 o = (A<object>)y2; // 4 o = (A<object?>)y2; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'B<object?>'. // o = (B<object?>)x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<object?>)x1").WithArguments("A<object>", "B<object?>").WithLocation(9, 13), // (10,13): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'B<object>'. // o = (B<object>)y1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<object>)y1").WithArguments("A<object?>", "B<object>").WithLocation(10, 13), // (17,13): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // o = (A<object?>)x2; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<object?>)x2").WithArguments("B<object>", "A<object?>").WithLocation(17, 13), // (18,13): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'A<object>'. // o = (A<object>)y2; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<object>)y2").WithArguments("B<object?>", "A<object>").WithLocation(18, 13)); } [Fact] public void ExplicitCast_NestedNullability_02() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class A<T> : I<T> { } class B<T> : IIn<T> { } class C<T> : IOut<T> { } class D { static void F1(A<object> x1, A<object?> y1) { object o; o = (I<object>)x1; o = (I<object?>)x1; o = (I<object>)y1; o = (I<object?>)y1; } static void F2(I<object> x2, I<object?> y2) { object o; o = (A<object>)x2; o = (A<object?>)x2; o = (A<object>)y2; o = (A<object?>)y2; } static void F3(B<object> x3, B<object?> y3) { object o; o = (IIn<object>)x3; o = (IIn<object?>)x3; o = (IIn<object>)y3; o = (IIn<object?>)y3; } static void F4(IIn<object> x4, IIn<object?> y4) { object o; o = (B<object>)x4; o = (B<object?>)x4; o = (B<object>)y4; o = (B<object?>)y4; } static void F5(C<object> x5, C<object?> y5) { object o; o = (IOut<object>)x5; o = (IOut<object?>)x5; o = (IOut<object>)y5; o = (IOut<object?>)y5; } static void F6(IOut<object> x6, IOut<object?> y6) { object o; o = (C<object>)x6; o = (C<object?>)x6; o = (C<object>)y6; o = (C<object?>)y6; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ExplicitCast_NestedNullability_03() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } sealed class A<T> : I<T> { } sealed class B<T> : IIn<T> { } sealed class C<T> : IOut<T> { } class D { static void F1(A<object> x1, A<object?> y1) { object o; o = (I<object>)x1; o = (I<object?>)x1; // 1 o = (I<object>)y1; // 2 o = (I<object?>)y1; } static void F2(I<object> x2, I<object?> y2) { object o; o = (A<object>)x2; o = (A<object?>)x2; // 3 o = (A<object>)y2; // 4 o = (A<object?>)y2; } static void F3(B<object> x3, B<object?> y3) { object o; o = (IIn<object>)x3; o = (IIn<object?>)x3; // 5 o = (IIn<object>)y3; o = (IIn<object?>)y3; } static void F4(IIn<object> x4, IIn<object?> y4) { object o; o = (B<object>)x4; o = (B<object?>)x4; o = (B<object>)y4; // 6 o = (B<object?>)y4; } static void F5(C<object> x5, C<object?> y5) { object o; o = (IOut<object>)x5; o = (IOut<object?>)x5; o = (IOut<object>)y5; // 7 o = (IOut<object?>)y5; } static void F6(IOut<object> x6, IOut<object?> y6) { object o; o = (C<object>)x6; o = (C<object?>)x6; // 8 o = (C<object>)y6; o = (C<object?>)y6; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'I<object?>'. // o = (I<object?>)x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(I<object?>)x1").WithArguments("A<object>", "I<object?>").WithLocation(13, 13), // (14,13): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'I<object>'. // o = (I<object>)y1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(I<object>)y1").WithArguments("A<object?>", "I<object>").WithLocation(14, 13), // (21,13): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'A<object?>'. // o = (A<object?>)x2; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<object?>)x2").WithArguments("I<object>", "A<object?>").WithLocation(21, 13), // (22,13): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'A<object>'. // o = (A<object>)y2; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<object>)y2").WithArguments("I<object?>", "A<object>").WithLocation(22, 13), // (29,13): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'IIn<object?>'. // o = (IIn<object?>)x3; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(IIn<object?>)x3").WithArguments("B<object>", "IIn<object?>").WithLocation(29, 13), // (38,13): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'B<object>'. // o = (B<object>)y4; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<object>)y4").WithArguments("IIn<object?>", "B<object>").WithLocation(38, 13), // (46,13): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'IOut<object>'. // o = (IOut<object>)y5; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(IOut<object>)y5").WithArguments("C<object?>", "IOut<object>").WithLocation(46, 13), // (53,13): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'C<object?>'. // o = (C<object?>)x6; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(C<object?>)x6").WithArguments("IOut<object>", "C<object?>").WithLocation(53, 13)); } [Fact] [WorkItem(35334, "https://github.com/dotnet/roslyn/issues/35334")] public void ExplicitCast_UserDefined_01() { var source = @"class A1 { public static implicit operator B?(A1? a) => new B(); } class A2 { public static implicit operator B?(A2 a) => new B(); } class A3 { public static implicit operator B(A3? a) => new B(); } class A4 { public static implicit operator B(A4 a) => new B(); } class B { } class C { static bool flag; static void F1(A1? x1, A1 y1) { B? b; if (flag) b = ((B)x1)/*T:B?*/; if (flag) b = ((B?)x1)/*T:B?*/; if (flag) b = ((B)y1)/*T:B?*/; if (flag) b = ((B?)y1)/*T:B?*/; } static void F2(A2? x2, A2 y2) { B? b; if (flag) b = ((B)x2)/*T:B?*/; if (flag) b = ((B?)x2)/*T:B?*/; if (flag) b = ((B)y2)/*T:B?*/; if (flag) b = ((B?)y2)/*T:B?*/; } static void F3(A3? x3, A3 y3) { B? b; if (flag) b = ((B)x3)/*T:B!*/; if (flag) b = ((B?)x3)/*T:B?*/; if (flag) b = ((B)y3)/*T:B!*/; if (flag) b = ((B?)y3)/*T:B?*/; } static void F4(A4? x4, A4 y4) { B? b; if (flag) b = ((B)x4)/*T:B!*/; if (flag) b = ((B?)x4)/*T:B?*/; if (flag) b = ((B)y4)/*T:B!*/; if (flag) b = ((B?)y4)/*T:B?*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (24,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (flag) b = ((B)x1)/*T:B?*/; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)x1").WithLocation(24, 24), // (26,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (flag) b = ((B)y1)/*T:B?*/; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)y1").WithLocation(26, 24), // (32,27): warning CS8604: Possible null reference argument for parameter 'a' in 'A2.implicit operator B?(A2 a)'. // if (flag) b = ((B)x2)/*T:B?*/; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("a", "A2.implicit operator B?(A2 a)").WithLocation(32, 27), // (32,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (flag) b = ((B)x2)/*T:B?*/; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)x2").WithLocation(32, 24), // (33,28): warning CS8604: Possible null reference argument for parameter 'a' in 'A2.implicit operator B?(A2 a)'. // if (flag) b = ((B?)x2)/*T:B?*/; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("a", "A2.implicit operator B?(A2 a)").WithLocation(33, 28), // (34,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (flag) b = ((B)y2)/*T:B?*/; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)y2").WithLocation(34, 24), // (48,27): warning CS8604: Possible null reference argument for parameter 'a' in 'A4.implicit operator B(A4 a)'. // if (flag) b = ((B)x4)/*T:B!*/; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x4").WithArguments("a", "A4.implicit operator B(A4 a)").WithLocation(48, 27), // (49,28): warning CS8604: Possible null reference argument for parameter 'a' in 'A4.implicit operator B(A4 a)'. // if (flag) b = ((B?)x4)/*T:B?*/; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x4").WithArguments("a", "A4.implicit operator B(A4 a)").WithLocation(49, 28), // (20,17): warning CS0649: Field 'C.flag' is never assigned to, and will always have its default value false // static bool flag; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "flag").WithArguments("C.flag", "false").WithLocation(20, 17)); comp.VerifyTypes(); } [Fact] public void ExplicitCast_UserDefined_02() { var source = @"class A<T> where T : class? { } class B { public static implicit operator A<string?>(B b) => throw null!; } class C { public static implicit operator A<string>(C c) => throw null!; static void F1(B x1) { var y1 = (A<string?>)x1; var z1 = (A<string>)x1; // 1 } static void F2(C x2) { var y2 = (A<string?>)x2; // 2 var z2 = (A<string>)x2; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,18): warning CS8619: Nullability of reference types in value of type 'A<string?>' doesn't match target type 'A<string>'. // var z1 = (A<string>)x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<string>)x1").WithArguments("A<string?>", "A<string>").WithLocation(14, 18), // (18,18): warning CS8619: Nullability of reference types in value of type 'A<string>' doesn't match target type 'A<string?>'. // var y2 = (A<string?>)x2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<string?>)x2").WithArguments("A<string>", "A<string?>").WithLocation(18, 18)); } [Fact] public void ExplicitCast_UserDefined_03() { var source = @"class A1<T> where T : class { public static implicit operator B<T?>(A1<T> a) => throw null!; } class A2<T> where T : class { public static implicit operator B<T>(A2<T> a) => throw null!; } class B<T> { } class C<T> where T : class { static void F1(A1<T?> x1, A1<T> y1) { B<T?> x; B<T> y; x = ((B<T?>)x1)/*T:B<T?>!*/; y = ((B<T>)x1)/*T:B<T!>!*/; x = ((B<T?>)y1)/*T:B<T?>!*/; y = ((B<T>)y1)/*T:B<T!>!*/; } static void F2(A2<T?> x2, A2<T> y2) { B<T?> x; B<T> y; x = ((B<T?>)x2)/*T:B<T?>!*/; y = ((B<T>)x2)/*T:B<T!>!*/; x = ((B<T?>)y2)/*T:B<T?>!*/; y = ((B<T>)y2)/*T:B<T!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,27): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'A1<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // static void F1(A1<T?> x1, A1<T> y1) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "x1").WithArguments("A1<T>", "T", "T?").WithLocation(12, 27), // (17,14): warning CS8619: Nullability of reference types in value of type 'B<T?>' doesn't match target type 'B<T>'. // y = ((B<T>)x1)/*T:B<T!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<T>)x1").WithArguments("B<T?>", "B<T>").WithLocation(17, 14), // (19,14): warning CS8619: Nullability of reference types in value of type 'B<T?>' doesn't match target type 'B<T>'. // y = ((B<T>)y1)/*T:B<T!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<T>)y1").WithArguments("B<T?>", "B<T>").WithLocation(19, 14), // (21,27): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'A2<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // static void F2(A2<T?> x2, A2<T> y2) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "x2").WithArguments("A2<T>", "T", "T?").WithLocation(21, 27), // (26,14): warning CS8619: Nullability of reference types in value of type 'B<T?>' doesn't match target type 'B<T>'. // y = ((B<T>)x2)/*T:B<T!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<T>)x2").WithArguments("B<T?>", "B<T>").WithLocation(26, 14), // (27,14): warning CS8619: Nullability of reference types in value of type 'B<T>' doesn't match target type 'B<T?>'. // x = ((B<T?>)y2)/*T:B<T?>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<T?>)y2").WithArguments("B<T>", "B<T?>").WithLocation(27, 14)); comp.VerifyTypes(); } [Fact] public void ExplicitCast_StaticType() { var source = @"static class C { static object F(object? x) => (C)x; static object? G(object? y) => (C?)y; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,35): error CS0716: Cannot convert to static type 'C' // static object F(object? x) => (C)x; Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)x").WithArguments("C").WithLocation(3, 35), // (3,35): warning CS8600: Converting null literal or possible null value to non-nullable type. // static object F(object? x) => (C)x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)x").WithLocation(3, 35), // (4,36): error CS0716: Cannot convert to static type 'C' // static object? G(object? y) => (C?)y; Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C?)y").WithArguments("C").WithLocation(4, 36) ); } [Fact] public void ForEach_01() { var source = @"class Enumerable { public Enumerator GetEnumerator() => new Enumerator(); } class Enumerator { public object Current => throw null!; public bool MoveNext() => false; } class C { static void F(Enumerable e) { foreach (var x in e) x.ToString(); foreach (string y in e) y.ToString(); foreach (string? z in e) z.ToString(); // 1 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,13): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(19, 13)); } [Fact, WorkItem(40164, "https://github.com/dotnet/roslyn/issues/40164")] public void ForEach_02() { var source = @"class Enumerable { public Enumerator GetEnumerator() => new Enumerator(); } class Enumerator { public object? Current => throw null!; public bool MoveNext() => false; } class C { static void F(Enumerable e) { foreach (var x in e) x.ToString(); foreach (object y in e) y.ToString(); foreach (object? z in e) z.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 13), // (16,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (object y in e) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(16, 25), // (17,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(17, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(19, 13)); } [Fact, WorkItem(40164, "https://github.com/dotnet/roslyn/issues/40164")] public void ForEach_03() { var source = @"using System.Collections; namespace System { public class Object { public string ToString() => throw null!; } public abstract class ValueType { } public struct Void { } public struct Boolean { } public class String { } public struct Enum { } public class Attribute { } public struct Int32 { } public class AttributeUsageAttribute : Attribute { public AttributeUsageAttribute(AttributeTargets validOn) => throw null!; public bool AllowMultiple { get; set; } } public enum AttributeTargets { Assembly = 1, Module = 2, Class = 4, Struct = 8, Enum = 16, Constructor = 32, Method = 64, Property = 128, Field = 256, Event = 512, Interface = 1024, Parameter = 2048, Delegate = 4096, ReturnValue = 8192, GenericParameter = 16384, All = 32767 } public class ObsoleteAttribute : Attribute { public ObsoleteAttribute(string message) => throw null!; } public class Exception { } } namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { object? Current { get; } bool MoveNext(); } } class Enumerable : IEnumerable { IEnumerator IEnumerable.GetEnumerator() => throw null!; } class C { static void F(Enumerable e) { foreach (var x in e) x.ToString(); foreach (object y in e) y.ToString(); } static void G(IEnumerable e) { foreach (var z in e) z.ToString(); foreach (object w in e) w.ToString(); } }"; var comp = CreateEmptyCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (51,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(51, 13), // (52,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (object y in e) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(52, 25), // (53,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(53, 13), // (58,13): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(58, 13), // (59,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (object w in e) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "w").WithLocation(59, 25), // (60,13): warning CS8602: Dereference of a possibly null reference. // w.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w").WithLocation(60, 13)); } // z.ToString() should warn if IEnumerator.Current is annotated as `object?`. [Fact] public void ForEach_04() { var source = @"using System.Collections; using System.Collections.Generic; class C { static void F(IEnumerable<object?> cx, object?[] cy) { foreach (var x in cx) x.ToString(); foreach (object? y in cy) y.ToString(); foreach (object? z in (IEnumerable)cx) z.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13), // (10,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(10, 13)); } [Fact] public void ForEach_05() { var source = @"class C { static void F1(dynamic c) { foreach (var x in c) x.ToString(); foreach (object? y in c) y.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ForEach_06() { var source = @"using System.Collections; using System.Collections.Generic; class C<T> : IEnumerable<T> where T : class { IEnumerator<T> IEnumerable<T>.GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } class P { static void F<T>(C<T?> c) where T : class { foreach (var x in c) x.ToString(); foreach (T? y in c) y.ToString(); foreach (T z in c) z.ToString(); foreach (object w in c) w.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,28): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // static void F<T>(C<T?> c) where T : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "c").WithArguments("C<T>", "T", "T?").WithLocation(10, 28), // (13,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(15, 13), // (16,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (T z in c) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z").WithLocation(16, 20), // (17,13): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(17, 13), // (18,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (object w in c) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "w").WithLocation(18, 25), // (19,13): warning CS8602: Dereference of a possibly null reference. // w.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w").WithLocation(19, 13)); } [Fact] public void ForEach_07() { var source = @"struct S<T> where T : class { public E<T> GetEnumerator() => new E<T>(); } struct E<T> where T : class { public T Current => throw null!; public bool MoveNext() => false; } class P { static void F1<T>() where T : class { foreach (var x1 in new S<T>()) x1.ToString(); foreach (T y1 in new S<T>()) y1.ToString(); foreach (T? z1 in new S<T>()) z1.ToString(); foreach (object? w1 in new S<T>()) w1.ToString(); } static void F2<T>() where T : class { foreach (var x2 in new S<T?>()) x2.ToString(); foreach (T y2 in new S<T?>()) y2.ToString(); foreach (T? z2 in new S<T?>()) z2.ToString(); foreach (object? w2 in new S<T?>()) w2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (25,34): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'S<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // foreach (var x2 in new S<T?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "T?").WithArguments("S<T>", "T", "T?").WithLocation(25, 34), // (26,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(26, 13), // (27,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (T y2 in new S<T?>()) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2").WithLocation(27, 20), // (27,32): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'S<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // foreach (T y2 in new S<T?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "T?").WithArguments("S<T>", "T", "T?").WithLocation(27, 32), // (28,13): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(28, 13), // (29,33): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'S<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // foreach (T? z2 in new S<T?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "T?").WithArguments("S<T>", "T", "T?").WithLocation(29, 33), // (30,13): warning CS8602: Dereference of a possibly null reference. // z2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2").WithLocation(30, 13), // (31,38): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'S<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // foreach (object? w2 in new S<T?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "T?").WithArguments("S<T>", "T", "T?").WithLocation(31, 38), // (32,13): warning CS8602: Dereference of a possibly null reference. // w2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w2").WithLocation(32, 13)); } [Fact] public void ForEach_08() { var source = @"using System.Collections.Generic; interface I<T> { T P { get; } } interface IIn<in T> { } interface IOut<out T> { T P { get; } } static class C { static void F1(IEnumerable<I<object>> x1, IEnumerable<I<object?>> y1) { foreach (I<object?> a1 in x1) a1.P.ToString(); foreach (I<object> b1 in y1) b1.P.ToString(); } static void F2(IEnumerable<IIn<object>> x2, IEnumerable<IIn<object?>> y2) { foreach (IIn<object?> a2 in x2) ; foreach (IIn<object> b2 in y2) ; } static void F3(IEnumerable<IOut<object>> x3, IEnumerable<IOut<object?>> y3) { foreach (IOut<object?> a3 in x3) a3.P.ToString(); foreach (IOut<object> b3 in y3) b3.P.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,29): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // foreach (I<object?> a1 in x1) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1").WithArguments("I<object>", "I<object?>").WithLocation(9, 29), // (10,13): warning CS8602: Dereference of a possibly null reference. // a1.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a1.P").WithLocation(10, 13), // (11,28): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // foreach (I<object> b1 in y1) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b1").WithArguments("I<object?>", "I<object>").WithLocation(11, 28), // (16,31): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // foreach (IIn<object?> a2 in x2) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("IIn<object>", "IIn<object?>").WithLocation(16, 31), // (24,13): warning CS8602: Dereference of a possibly null reference. // a3.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a3.P").WithLocation(24, 13), // (25,31): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // foreach (IOut<object> b3 in y3) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b3").WithArguments("IOut<object?>", "IOut<object>").WithLocation(25, 31)); } [Fact] public void ForEach_09() { var source = @"class A { } class B : A { } class C { static void F(A?[] c) { foreach (var a1 in c) a1.ToString(); foreach (A? a2 in c) a2.ToString(); foreach (A a3 in c) a3.ToString(); foreach (B? b1 in c) b1.ToString(); foreach (B b2 in c) b2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // a1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a1").WithLocation(8, 13), // (10,13): warning CS8602: Dereference of a possibly null reference. // a2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2").WithLocation(10, 13), // (11,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (A a3 in c) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "a3").WithLocation(11, 20), // (12,13): warning CS8602: Dereference of a possibly null reference. // a3.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a3").WithLocation(12, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // b1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1").WithLocation(14, 13), // (15,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (B b2 in c) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b2").WithLocation(15, 20), // (16,13): warning CS8602: Dereference of a possibly null reference. // b2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b2").WithLocation(16, 13)); } [Fact] [WorkItem(29971, "https://github.com/dotnet/roslyn/issues/29971")] public void ForEach_10() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class A<T> { internal T F; } class B : A<object> { } class C { static void F(A<object?>[] c) { foreach (var a1 in c) a1.F.ToString(); foreach (A<object?> a2 in c) a2.F.ToString(); foreach (A<object> a3 in c) a3.F.ToString(); foreach (B b1 in c) b1.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // a1.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a1.F").WithLocation(13, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // a2.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2.F").WithLocation(15, 13), // (16,28): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'A<object>'. // foreach (A<object> a3 in c) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a3").WithArguments("A<object?>", "A<object>").WithLocation(16, 28), // (18,20): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'B'. // foreach (B b1 in c) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b1").WithArguments("A<object?>", "B").WithLocation(18, 20)); } [Fact] [WorkItem(29971, "https://github.com/dotnet/roslyn/issues/29971")] public void ForEach_11() { var source = @"using System.Collections.Generic; class A { public static implicit operator B?(A a) => null; } class B { } class C { static void F(IEnumerable<A> e) { foreach (var x in e) x.ToString(); foreach (B y in e) y.ToString(); foreach (B? z in e) { z.ToString(); if (z != null) z.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (B y in e) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(15, 20), // (16,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(16, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(19, 13)); } [WorkItem(23493, "https://github.com/dotnet/roslyn/issues/23493")] [Fact] public void ForEach_12() { var source = @"using System.Collections; using System.Collections.Generic; class C { static void F() { foreach (var x in (IEnumerable?)null) // 1 { } foreach (var y in (IEnumerable<object>)default) // 2 { } foreach (var z in default(IEnumerable)) // 3 { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,27): error CS0186: Use of null is not valid in this context // foreach (var x in (IEnumerable?)null) // 1 Diagnostic(ErrorCode.ERR_NullNotValid, "(IEnumerable?)null").WithLocation(7, 27), // (10,27): error CS0186: Use of null is not valid in this context // foreach (var y in (IEnumerable<object>)default) // 2 Diagnostic(ErrorCode.ERR_NullNotValid, "(IEnumerable<object>)default").WithLocation(10, 27), // (13,27): error CS0186: Use of null is not valid in this context // foreach (var z in default(IEnumerable)) // 3 Diagnostic(ErrorCode.ERR_NullNotValid, "default(IEnumerable)").WithLocation(13, 27), // (7,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in (IEnumerable?)null) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable?)null").WithLocation(7, 27), // (10,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var y in (IEnumerable<object>)default) // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IEnumerable<object>)default").WithLocation(10, 27), // (10,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in (IEnumerable<object>)default) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable<object>)default").WithLocation(10, 27)); } [WorkItem(23493, "https://github.com/dotnet/roslyn/issues/23493")] [Fact] public void ForEach_13() { var source = @"using System.Collections; using System.Collections.Generic; class C { static void F1(object[]? c1) { foreach (var x in c1) // 1 { } foreach (var z in c1) // no cascade { } } static void F2(object[]? c1) { foreach (var y in (IEnumerable)c1) // 2 { } } static void F3(object[]? c1) { if (c1 == null) return; foreach (var z in c1) { } } static void F4(IList<object>? c2) { foreach (var x in c2) // 3 { } } static void F5(IList<object>? c2) { foreach (var y in (IEnumerable?)c2) // 4 { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in c1) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(7, 27), // (16,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var y in (IEnumerable)c1) // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IEnumerable)c1").WithLocation(16, 27), // (16,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in (IEnumerable)c1) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable)c1").WithLocation(16, 27), // (29,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in c2) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(29, 27), // (35,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in (IEnumerable?)c2) // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable?)c2").WithLocation(35, 27)); } [WorkItem(23493, "https://github.com/dotnet/roslyn/issues/23493")] [Fact] public void ForEach_14() { var source = @"using System.Collections; using System.Collections.Generic; class C { static void F1<T>(T t1) where T : class?, IEnumerable<object>? { foreach (var x in t1) // 1 { } } static void F2<T>(T t1) where T : class?, IEnumerable<object>? { foreach (var y in (IEnumerable<object>?)t1) // 2 { } } static void F3<T>(T t1) where T : class?, IEnumerable<object>? { foreach (var z in (IEnumerable<object>)t1) // 3 { } } static void F4<T>(T t2) where T : class? { foreach (var w in (IEnumerable?)t2) // 4 { } } static void F5<T>(T t2) where T : class? { foreach (var v in (IEnumerable)t2) // 5 { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in t1) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(7, 27), // (13,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in (IEnumerable<object>?)t1) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable<object>?)t1").WithLocation(13, 27), // (19,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var z in (IEnumerable<object>)t1) // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IEnumerable<object>)t1").WithLocation(19, 27), // (19,27): warning CS8602: Dereference of a possibly null reference. // foreach (var z in (IEnumerable<object>)t1) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable<object>)t1").WithLocation(19, 27), // (25,27): warning CS8602: Dereference of a possibly null reference. // foreach (var w in (IEnumerable?)t2) // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable?)t2").WithLocation(25, 27), // (31,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var v in (IEnumerable)t2) // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IEnumerable)t2").WithLocation(31, 27), // (31,27): warning CS8602: Dereference of a possibly null reference. // foreach (var v in (IEnumerable)t2) // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable)t2").WithLocation(31, 27)); } [WorkItem(23493, "https://github.com/dotnet/roslyn/issues/23493")] [Fact] public void ForEach_15() { var source = @"using System.Collections; using System.Collections.Generic; class C { static void F1<T>(T t1) where T : IEnumerable? { foreach (var x in t1) // 1 { } foreach (var x in t1) // no cascade { } } static void F2<T>(T t1) where T : IEnumerable? { foreach (var w in (IEnumerable?)t1) // 2 { } } static void F3<T>(T t1) where T : IEnumerable? { foreach (var v in (IEnumerable)t1) // 3 { } } static void F4<T>(T t2) { foreach (var y in (IEnumerable<object>?)t2) // 4 { } } static void F5<T>(T t2) { foreach (var z in (IEnumerable<object>)t2) // 5 { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in t1) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(7, 27), // (16,27): warning CS8602: Dereference of a possibly null reference. // foreach (var w in (IEnumerable?)t1) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable?)t1").WithLocation(16, 27), // (22,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var v in (IEnumerable)t1) // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IEnumerable)t1").WithLocation(22, 27), // (22,27): warning CS8602: Dereference of a possibly null reference. // foreach (var v in (IEnumerable)t1) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable)t1").WithLocation(22, 27), // (28,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in (IEnumerable<object>?)t2) // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable<object>?)t2").WithLocation(28, 27), // (34,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var z in (IEnumerable<object>)t2) // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IEnumerable<object>)t2").WithLocation(34, 27), // (34,27): warning CS8602: Dereference of a possibly null reference. // foreach (var z in (IEnumerable<object>)t2) // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable<object>)t2").WithLocation(34, 27)); } [Fact] [WorkItem(29972, "https://github.com/dotnet/roslyn/issues/29972")] public void ForEach_16() { var source = @"using System.Collections; class Enumerable : IEnumerable { public IEnumerator? GetEnumerator() => null; } class C { static void F1(Enumerable e) { foreach (var x in e) // 1 { } foreach (var y in (IEnumerable?)e) // 2 { } foreach (var z in (IEnumerable)e) { } } static void F2(Enumerable? e) { foreach (var x in e) // 3 { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in e) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(10, 27), // (13,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in (IEnumerable?)e) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable?)e").WithLocation(13, 27), // (22,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in e) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(22, 27)); } [Fact] [WorkItem(29972, "https://github.com/dotnet/roslyn/issues/29972")] public void ForEach_17() { var source = @" class C { void M1<EnumerableType, EnumeratorType, T>(EnumerableType e) where EnumerableType : Enumerable<EnumeratorType, T> where EnumeratorType : I<T>? { foreach (var t in e) // 1 { t.ToString(); // 2 } } void M2<EnumerableType, EnumeratorType, T>(EnumerableType e) where EnumerableType : Enumerable<EnumeratorType, T> where EnumeratorType : I<T> { foreach (var t in e) { t.ToString(); // 3 } } } interface Enumerable<E, T> where E : I<T>? { E GetEnumerator(); } interface I<T> { T Current { get; } bool MoveNext(); } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,27): warning CS8602: Dereference of a possibly null reference. // foreach (var t in e) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(8, 27), // (10,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(10, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(19, 13)); } [Fact] [WorkItem(34667, "https://github.com/dotnet/roslyn/issues/34667")] public void ForEach_18() { var source = @" using System.Collections.Generic; class Program { static void Main() { } static void F(IEnumerable<object[]?[]> source) { foreach (object[][] item in source) { } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,29): warning CS8619: Nullability of reference types in value of type 'object[]?[]' doesn't match target type 'object[][]'. // foreach (object[][] item in source) { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "item").WithArguments("object[]?[]", "object[][]").WithLocation(10, 29)); } [Fact] [WorkItem(35151, "https://github.com/dotnet/roslyn/issues/35151")] public void ForEach_19() { var source = @" using System.Collections; class C { void M1(IEnumerator e) { var enumerable1 = Create(e); foreach (var i in enumerable1) { } e = null; // 1 var enumerable2 = Create(e); foreach (var i in enumerable2) // 2 { } } void M2(IEnumerator? e) { var enumerable1 = Create(e); foreach (var i in enumerable1) // 3 { } if (e == null) return; var enumerable2 = Create(e); foreach (var i in enumerable2) { } } void M3<TEnumerator>(TEnumerator e) where TEnumerator : IEnumerator { var enumerable1 = Create(e); foreach (var i in enumerable1) { } e = default; var enumerable2 = Create(e); foreach (var i in enumerable2) // 4 { } } void M4<TEnumerator>(TEnumerator e) where TEnumerator : IEnumerator? { var enumerable1 = Create(e); foreach (var i in enumerable1) // 5 { } if (e == null) return; var enumerable2 = Create(e); foreach (var i in enumerable2) // 6 { } } static Enumerable<T> Create<T>(T t) where T : IEnumerator? => throw null!; } class Enumerable<T> where T : IEnumerator? { public T GetEnumerator() => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // e = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 13), // (14,27): warning CS8602: Dereference of a possibly null reference. // foreach (var i in enumerable2) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "enumerable2").WithLocation(14, 27), // (22,27): warning CS8602: Dereference of a possibly null reference. // foreach (var i in enumerable1) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "enumerable1").WithLocation(22, 27), // (42,27): warning CS8602: Dereference of a possibly null reference. // foreach (var i in enumerable2) // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "enumerable2").WithLocation(42, 27), // (50,27): warning CS8602: Dereference of a possibly null reference. // foreach (var i in enumerable1) // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "enumerable1").WithLocation(50, 27), // (56,27): warning CS8602: Dereference of a possibly null reference. // foreach (var i in enumerable2) // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "enumerable2").WithLocation(56, 27)); } [Fact] [WorkItem(35151, "https://github.com/dotnet/roslyn/issues/35151")] public void ForEach_20() { var source = @" using System.Collections.Generic; class C { void M1(string e) { var enumerable1 = Create(e); foreach (var s in enumerable1) { s.ToString(); } e = null; // 1 var enumerable2 = Create(e); foreach (var s in enumerable2) { s.ToString(); // 2 } } void M2(string? e) { var enumerable1 = Create(e); foreach (var s in enumerable1) { s.ToString(); // 3 } if (e == null) return; var enumerable2 = Create(e); foreach (var s in enumerable2) { s.ToString(); } } static Enumerable<IEnumerator<U>, U> Create<U>(U u) => throw null!; } class Enumerable<T, U> where T : IEnumerator<U>? { public T GetEnumerator() => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // e = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(26, 13)); } [Fact] [WorkItem(35151, "https://github.com/dotnet/roslyn/issues/35151")] public void ForEach_21() { var source = @" using System.Collections; using System.Collections.Generic; class C { void M1(string e) { var enumerable1 = Create(e); foreach (var s in enumerable1) { s.ToString(); } e = null; // 1 var enumerable2 = Create(e); foreach (var s in enumerable2) { s.ToString(); // 2 } } void M2(string? e) { var enumerable1 = Create(e); foreach (var s in enumerable1) { s.ToString(); // 3 } if (e == null) return; var enumerable2 = Create(e); foreach (var s in enumerable2) { s.ToString(); } } static Enumerable<T> Create<T>(T t) => throw null!; } class Enumerable<T> : IEnumerable<T> { public IEnumerator<T> GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // e = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(15, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(19, 13), // (28,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(28, 13)); } [Fact] [WorkItem(35151, "https://github.com/dotnet/roslyn/issues/35151")] public void ForEach_22() { var source = @" using System.Collections; using System.Collections.Generic; class C { void M1(string e) { var enumerable1 = Create(e); foreach (var s in enumerable1) { s.ToString(); } e = null; // 1 var enumerable2 = Create(e); foreach (var s in enumerable2) { s.ToString(); // 2 } } void M2(string? e) { var enumerable1 = Create(e); foreach (var s in enumerable1) { s.ToString(); // 3 } if (e == null) return; var enumerable2 = Create(e); foreach (var s in enumerable2) { s.ToString(); } } static Enumerable<T> Create<T>(T t) => throw null!; } class Enumerable<T> : IEnumerable<T> { IEnumerator<T> IEnumerable<T>.GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // e = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(15, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(19, 13), // (28,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(28, 13)); } [Fact] [WorkItem(33257, "https://github.com/dotnet/roslyn/issues/33257")] [WorkItem(35151, "https://github.com/dotnet/roslyn/issues/35151")] public void ForEach_23() { var source = @" class C { void M(string? s) { var l1 = new[] { s }; foreach (var x in l1) { x.ToString(); // 1 } if (s == null) return; var l2 = new[] { s }; foreach (var x in l2) { x.ToString(); } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 13)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_24() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; struct S<T> { public E<T> GetEnumerator() => new E<T>(); } struct E<T> { [MaybeNull]public T Current => default; public bool MoveNext() => false; } class Program { static T F1<T>() { foreach (var t1 in new S<T>()) return t1; // 1 foreach (T t2 in new S<T>()) return t2; // 2 throw null!; } static object F2<T>() { foreach (object o1 in new S<T>()) // 3 return o1; // 4 foreach (object? o2 in new S<T>()) return o2; // 5 throw null!; } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (17,20): warning CS8603: Possible null reference return. // return t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(17, 20), // (18,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (T t2 in new S<T>()) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t2").WithLocation(18, 20), // (19,20): warning CS8603: Possible null reference return. // return t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(19, 20), // (24,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (object o1 in new S<T>()) // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "o1").WithLocation(24, 25), // (25,20): warning CS8603: Possible null reference return. // return o1; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o1").WithLocation(25, 20), // (27,20): warning CS8603: Possible null reference return. // return o2; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o2").WithLocation(27, 20)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_25() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; struct S<T> { public E<T> GetAsyncEnumerator() => new E<T>(); } class E<T> { [MaybeNull]public T Current => default; public ValueTask<bool> MoveNextAsync() => default; public ValueTask DisposeAsync() => default; } class Program { static async Task<T> F1<T>() { await foreach (var t1 in new S<T>()) return t1; // 1 await foreach (T t2 in new S<T>()) return t2; // 2 throw null!; } static async Task<object> F2<T>() { await foreach (object o1 in new S<T>()) // 3 return o1; // 4 await foreach (object? o2 in new S<T>()) return o2; // 5 throw null!; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (19,20): warning CS8603: Possible null reference return. // return t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(19, 20), // (20,26): warning CS8600: Converting null literal or possible null value to non-nullable type. // await foreach (T t2 in new S<T>()) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t2").WithLocation(20, 26), // (21,20): warning CS8603: Possible null reference return. // return t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(21, 20), // (26,31): warning CS8600: Converting null literal or possible null value to non-nullable type. // await foreach (object o1 in new S<T>()) // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "o1").WithLocation(26, 31), // (27,20): warning CS8603: Possible null reference return. // return o1; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o1").WithLocation(27, 20), // (29,20): warning CS8603: Possible null reference return. // return o2; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o2").WithLocation(29, 20)); } [Fact, WorkItem(39736, "https://github.com/dotnet/roslyn/issues/39736")] public void Foreach_TuplesThroughFunction() { var source = @" using System.Collections.Generic; class Alpha { public string Value { get; set; } = """"; public override string ToString() => Value; } class C { void M() { var items3 = new List<(int? Index, Alpha? Alpha)>() { (0, new Alpha { Value = ""A"" }), (1, new Alpha { Value = ""B"" }), (2, new Alpha { Value = ""C"" }) }; foreach (var indexAndAlpha in Identity(items3)) { var (index, alpha) = indexAndAlpha; index/*T:int?*/.ToString(); alpha/*T:Alpha?*/.ToString(); // 1 } foreach (var (index, alpha) in Identity(items3)) { index/*T:int?*/.ToString(); alpha/*T:Alpha!*/.ToString(); // Should warn, be Alpha? } } IEnumerable<T> Identity<T>(IEnumerable<T> ie) => ie; } "; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/39736, missing the warning on the alpha dereference // from the deconstruction case comp.VerifyDiagnostics( // (23,13): warning CS8602: Dereference of a possibly null reference. // alpha.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "alpha").WithLocation(23, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(33257, "https://github.com/dotnet/roslyn/issues/33257")] public void ForEach_Span() { var source = @" using System; class C { void M1(Span<string> s1, Span<string?> s2) { foreach (var s in s1) { s.ToString(); } foreach (var s in s2) { s.ToString(); // 1 } } } "; var comp = CreateCompilationWithMscorlibAndSpan(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13)); } [Fact] [WorkItem(35151, "https://github.com/dotnet/roslyn/issues/35151")] public void ForEach_StringNotIEnumerable() { // In some frameworks, System.String doesn't implement IEnumerable, but for compat reasons the compiler // will still allow foreach'ing over these strings. var systemSource = @" namespace System { public class Object { } public struct Void { } public class ValueType { } public struct Boolean { } public struct Int32 { } public class Exception { } public struct Char { public string ToString() => throw null!; } public class String { public int Length { get; } [System.Runtime.CompilerServices.IndexerName(""Chars"")] public char this[int i] => throw null!; } public interface IDisposable { void Dispose(); } public abstract class Attribute { protected Attribute() { } } } namespace System.Runtime.CompilerServices { using System; public sealed class IndexerNameAttribute: Attribute { public IndexerNameAttribute(String indexerName) {} } } namespace System.Reflection { using System; public sealed class DefaultMemberAttribute : Attribute { public DefaultMemberAttribute(String memberName) {} } } namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { object Current { get; } bool MoveNext(); } }"; var source = @" class C { void M(string s, string? s2) { foreach (var c in s) { c.ToString(); } s = null; // 1 foreach (var c in s) // 2 { c.ToString(); } foreach (var c in s2) // 3 { c.ToString(); } foreach (var c in (string)null) // 4 { } } }"; var comp = CreateEmptyCompilation(new[] { source, systemSource }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 13), // (12,27): warning CS8602: Dereference of a possibly null reference. // foreach (var c in s) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 27), // (17,27): warning CS8602: Dereference of a possibly null reference. // foreach (var c in s2) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(17, 27), // (22,27): error CS0186: Use of null is not valid in this context // foreach (var c in (string)null) // 4 Diagnostic(ErrorCode.ERR_NullNotValid, "(string)null").WithLocation(22, 27), // (22,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var c in (string)null) // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(22, 27), // (22,27): warning CS8602: Dereference of a possibly null reference. // foreach (var c in (string)null) // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(string)null").WithLocation(22, 27)); } [Fact] public void ForEach_UnconstrainedTypeParameter() { var source = @"class C<T> { void M(T parameter) { foreach (T local in new[] { parameter }) { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Theory] [InlineData("System.Collections.IEnumerator?")] [InlineData("System.Collections.Generic.IEnumerator<object>?")] [WorkItem(38233, "https://github.com/dotnet/roslyn/issues/38233")] public void ForEach_NullableGetEnumerator_01(string enumeratorType) { var source = $@" class C {{ public {enumeratorType} GetEnumerator() => throw null!; static void M1(C c) {{ foreach (var obj in c) // 1 {{ }} }} static void M2(C c) {{ foreach (var obj in c!) {{ }} }} }}"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,29): warning CS8602: Dereference of a possibly null reference. // foreach (var obj in c) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 29)); } [Theory] [InlineData("System.Collections.IEnumerator?")] [InlineData("System.Collections.Generic.IEnumerator<object>?")] [WorkItem(38233, "https://github.com/dotnet/roslyn/issues/38233")] public void ForEach_NullableGetEnumerator_02(string enumeratorType) { var source = $@" class C {{ public {enumeratorType} GetEnumerator() => throw null!; static void M1(C? c) {{ foreach (var obj in c) // 1 {{ }} }} static void M2(C? c) {{ C c2 = c!; foreach (var obj in c2) // 2 {{ }} }} static void M3(C? c) {{ foreach (var obj in c!) {{ }} }} }}"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,29): warning CS8602: Dereference of a possibly null reference. // foreach (var obj in c) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 29), // (16,29): warning CS8602: Dereference of a possibly null reference. // foreach (var obj in c2) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(16, 29)); } [Fact] [WorkItem(38233, "https://github.com/dotnet/roslyn/issues/38233")] public void ForEach_NullableGetEnumerator_03() { var source = @" class Enumerator { public object Current => null!; public bool MoveNext() => false; } class Enumerable { public Enumerator? GetEnumerator() => null; static void M1(Enumerable e) { foreach (var obj in e) // 1 { } } static void M2(Enumerable e) { foreach (var obj in e!) { } } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,29): warning CS8602: Dereference of a possibly null reference. // foreach (var obj in e) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(13, 29)); } [Fact] [WorkItem(38233, "https://github.com/dotnet/roslyn/issues/38233")] public void ForEach_NullableGetEnumerator_04() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { foreach(var s in new A()) { _ = s.ToString(); } } [return: MaybeNull] public IEnumerator<string> GetEnumerator() => throw null!; }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,26): warning CS8602: Dereference of a possibly null reference. // foreach(var s in new A()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A()").WithLocation(8, 26) ); } [Fact] [WorkItem(38233, "https://github.com/dotnet/roslyn/issues/38233")] public void ForEach_NullableGetEnumerator_05() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { foreach(var s in new A()) { _ = s.ToString(); } } [return: NotNull] public IEnumerator<string>? GetEnumerator() => throw null!; }"; var comp = CreateCompilation(new[] { source, NotNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator1() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<string?>()) { _ = s.ToString(); } } } static class Extensions { public static IEnumerator<T> GetEnumerator<T>(this A<T> a) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator2() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<string>()) { _ = s.ToString(); } } } static class Extensions { public static IEnumerator<T> GetEnumerator<T>(this A<T> a) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator3() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<string>()) { _ = s.ToString(); // 1 } foreach(var s in new A<string?>()) { _ = s.ToString(); // 2 } } } static class Extensions { public static IEnumerator<T?> GetEnumerator<T>(this A<T> a) where T : class => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17), // (12,26): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'Extensions.GetEnumerator<T>(A<T>)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // foreach(var s in new A<string?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "new A<string?>()").WithArguments("Extensions.GetEnumerator<T>(A<T>)", "T", "string?").WithLocation(12, 26), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator4() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<string>()) { _ = s.ToString(); // 1 } foreach(var s in new A<string?>()) { _ = s.ToString(); // 2 } } } static class Extensions { public static IEnumerator<T> GetEnumerator<T>(this A<T> a) where T : notnull => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,26): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'Extensions.GetEnumerator<T>(A<T>)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // foreach(var s in new A<string?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "new A<string?>()").WithArguments("Extensions.GetEnumerator<T>(A<T>)", "T", "string?").WithLocation(12, 26), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator5() { var source = @" using System.Collections.Generic; class A { public static void M() { A? a = null; foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IEnumerator<string> GetEnumerator(this A a) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,26): warning CS8604: Possible null reference argument for parameter 'a' in 'IEnumerator<string> Extensions.GetEnumerator(A a)'. // foreach(var s in a) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("a", "IEnumerator<string> Extensions.GetEnumerator(A a)").WithLocation(8, 26)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator6() { var source = @" using System.Collections.Generic; class A { public static void M() { A? a = null; foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IEnumerator<string> GetEnumerator(this A? a) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): warning CS8602: Dereference of a possibly null reference. // _ = a.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(11, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator7() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { A? a = null; foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IEnumerator<string> GetEnumerator([NotNull] this A? a) => throw null!; }"; var comp = CreateCompilation(new[] { source, NotNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator8() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { A a = new A(); foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IEnumerator<string> GetEnumerator([MaybeNull] this A a) => throw null!; }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,17): warning CS8602: Dereference of a possibly null reference. // _ = a.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(12, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator9() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { A? a = null; foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); // 1 } } } static class Extensions { public static IEnumerator<string> GetEnumerator([AllowNull] this A a) => throw null!; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,17): warning CS8602: Dereference of a possibly null reference. // _ = a.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(12, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator10() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { A? a = null; foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IEnumerator<string> GetEnumerator([DisallowNull] this A? a) => throw null!; }"; var comp = CreateCompilation(new[] { source, DisallowNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,26): warning CS8604: Possible null reference argument for parameter 'a' in 'IEnumerator<string> Extensions.GetEnumerator(A? a)'. // foreach(var s in a) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("a", "IEnumerator<string> Extensions.GetEnumerator(A? a)").WithLocation(9, 26)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator11() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<IEnumerator<string>?>()) { _ = s.ToString(); } } } static class Extensions { public static T GetEnumerator<T>(this A<T> a) where T : IEnumerator<string>? => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,26): warning CS8602: Dereference of a possibly null reference. // foreach(var s in new A<IEnumerator<string>?>()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A<IEnumerator<string>?>()").WithLocation(7, 26)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator12() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<IEnumerator<string>?>()) { _ = s.ToString(); // 1 } foreach(var s in new A<IEnumerator<string?>?>()) { _ = s.ToString(); // 2 } } } static class Extensions { public static T GetEnumerator<T>(this A<T?> a) where T : class, IEnumerator<string?> => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator13() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<IEnumerator<string>?>()) { _ = s.ToString(); } } } static class Extensions { public static T GetEnumerator<T>(this A<T> a) where T : IEnumerator<string> => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,26): warning CS8631: The type 'System.Collections.Generic.IEnumerator<string>?' cannot be used as type parameter 'T' in the generic type or method 'Extensions.GetEnumerator<T>(A<T>)'. Nullability of type argument 'System.Collections.Generic.IEnumerator<string>?' doesn't match constraint type 'System.Collections.Generic.IEnumerator<string>'. // foreach(var s in new A<IEnumerator<string>?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "new A<IEnumerator<string>?>()").WithArguments("Extensions.GetEnumerator<T>(A<T>)", "System.Collections.Generic.IEnumerator<string>", "T", "System.Collections.Generic.IEnumerator<string>?").WithLocation(7, 26), // (7,26): warning CS8602: Dereference of a possibly null reference. // foreach(var s in new A<IEnumerator<string>?>()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A<IEnumerator<string>?>()").WithLocation(7, 26) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator14() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { foreach(var s in new A()) { _ = s.ToString(); } } } static class Extensions { [return: MaybeNull] public static IEnumerator<string> GetEnumerator(this A a) => throw null!; }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,26): warning CS8602: Dereference of a possibly null reference. // foreach(var s in new A()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A()").WithLocation(8, 26) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator15() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { foreach(var s in new A()) { _ = s.ToString(); } } } static class Extensions { [return: NotNull] public static IEnumerator<string>? GetEnumerator(this A a) => throw null!; }"; var comp = CreateCompilation(new[] { source, NotNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void ForEach_ExtensionGetEnumerator16() { var source = @" using System.Collections.Generic; #nullable enable public class C<T> { static void M(C<string> c) { foreach (var i in c) { } } } #nullable disable public static class CExt { public static IEnumerator<int> GetEnumerator<T>(this C<T> c, T t = default) => throw null; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,27): warning CS8620: Argument of type 'C<string>' cannot be used for parameter 'c' of type 'C<string?>' in 'IEnumerator<int> CExt.GetEnumerator<string?>(C<string?> c, string? t = null)' due to differences in the nullability of reference types. // foreach (var i in c) Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "c").WithArguments("C<string>", "C<string?>", "c", "IEnumerator<int> CExt.GetEnumerator<string?>(C<string?> c, string? t = null)").WithLocation(8, 27) ); } [Fact] public void ForEach_ExtensionGetEnumerator17() { var source = @" using System.Collections.Generic; #nullable enable public class C { static void M(C c) { foreach (var i in c) { } } } public static class CExt { public static IEnumerator<int> GetEnumerator(this C c, string t = default) => throw null!; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,71): warning CS8625: Cannot convert null literal to non-nullable reference type. // public static IEnumerator<int> GetEnumerator(this C c, string t = default) => throw null!; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(15, 71) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator1() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<string?>()) { _ = s.ToString(); } } } static class Extensions { public static IAsyncEnumerator<T> GetAsyncEnumerator<T>(this A<T> a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator2() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<string>()) { _ = s.ToString(); } } } static class Extensions { public static IAsyncEnumerator<T> GetAsyncEnumerator<T>(this A<T> a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator3() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<string>()) { _ = s.ToString(); // 1 } await foreach(var s in new A<string?>()) { _ = s.ToString(); // 2 } } } static class Extensions { public static IAsyncEnumerator<T?> GetAsyncEnumerator<T>(this A<T> a) where T : class => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17), // (12,32): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'Extensions.GetAsyncEnumerator<T>(A<T>)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // await foreach(var s in new A<string?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "new A<string?>()").WithArguments("Extensions.GetAsyncEnumerator<T>(A<T>)", "T", "string?").WithLocation(12, 32), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator4() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<string>()) { _ = s.ToString(); // 1 } await foreach(var s in new A<string?>()) { _ = s.ToString(); // 2 } } } static class Extensions { public static IAsyncEnumerator<T> GetAsyncEnumerator<T>(this A<T> a) where T : notnull => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,32): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'Extensions.GetAsyncEnumerator<T>(A<T>)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // await foreach(var s in new A<string?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "new A<string?>()").WithArguments("Extensions.GetAsyncEnumerator<T>(A<T>)", "T", "string?").WithLocation(12, 32), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator5() { var source = @" using System.Collections.Generic; class A { public static async void M() { A? a = null; await foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IAsyncEnumerator<string> GetAsyncEnumerator(this A a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,32): warning CS8604: Possible null reference argument for parameter 'a' in 'IAsyncEnumerator<string> Extensions.GetAsyncEnumerator(A a)'. // await foreach(var s in a) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("a", "IAsyncEnumerator<string> Extensions.GetAsyncEnumerator(A a)").WithLocation(8, 32) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator6() { var source = @" using System.Collections.Generic; class A { public static async void M() { A? a = null; await foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IAsyncEnumerator<string> GetAsyncEnumerator(this A? a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): warning CS8602: Dereference of a possibly null reference. // _ = a.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(11, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator7() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static async void M() { A? a = null; await foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IAsyncEnumerator<string> GetAsyncEnumerator([NotNull] this A? a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable, NotNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator8() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static async void M() { A a = new A(); await foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IAsyncEnumerator<string> GetAsyncEnumerator([MaybeNull] this A a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable, MaybeNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,17): warning CS8602: Dereference of a possibly null reference. // _ = a.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(12, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator9() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static async void M() { A? a = null; await foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); // 1 } } } static class Extensions { public static IAsyncEnumerator<string> GetAsyncEnumerator([AllowNull] this A a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable, AllowNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,17): warning CS8602: Dereference of a possibly null reference. // _ = a.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(12, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator10() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static async void M() { A? a = null; await foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IAsyncEnumerator<string> GetAsyncEnumerator([DisallowNull] this A? a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable, DisallowNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,32): warning CS8604: Possible null reference argument for parameter 'a' in 'IAsyncEnumerator<string> Extensions.GetAsyncEnumerator(A? a)'. // await foreach(var s in a) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("a", "IAsyncEnumerator<string> Extensions.GetAsyncEnumerator(A? a)").WithLocation(9, 32) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator11() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<IAsyncEnumerator<string>?>()) { _ = s.ToString(); } } } static class Extensions { public static T GetAsyncEnumerator<T>(this A<T> a) where T : IAsyncEnumerator<string>? => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,32): warning CS8602: Dereference of a possibly null reference. // await foreach(var s in new A<IAsyncEnumerator<string>?>()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A<IAsyncEnumerator<string>?>()").WithLocation(7, 32) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator12() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<IAsyncEnumerator<string>?>()) { _ = s.ToString(); // 1 } await foreach(var s in new A<IAsyncEnumerator<string?>?>()) { _ = s.ToString(); // 2 } } } static class Extensions { public static T GetAsyncEnumerator<T>(this A<T?> a) where T : class, IAsyncEnumerator<string?> => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator13() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<IAsyncEnumerator<string>?>()) { _ = s.ToString(); } } } static class Extensions { public static T GetAsyncEnumerator<T>(this A<T> a) where T : IAsyncEnumerator<string> => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,32): warning CS8631: The type 'System.Collections.Generic.IAsyncEnumerator<string>?' cannot be used as type parameter 'T' in the generic type or method 'Extensions.GetAsyncEnumerator<T>(A<T>)'. Nullability of type argument 'System.Collections.Generic.IAsyncEnumerator<string>?' doesn't match constraint type 'System.Collections.Generic.IAsyncEnumerator<string>'. // await foreach(var s in new A<IAsyncEnumerator<string>?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "new A<IAsyncEnumerator<string>?>()").WithArguments("Extensions.GetAsyncEnumerator<T>(A<T>)", "System.Collections.Generic.IAsyncEnumerator<string>", "T", "System.Collections.Generic.IAsyncEnumerator<string>?").WithLocation(7, 32), // (7,32): warning CS8602: Dereference of a possibly null reference. // await foreach(var s in new A<IAsyncEnumerator<string>?>()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A<IAsyncEnumerator<string>?>()").WithLocation(7, 32) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator14() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static async void M() { await foreach(var s in new A()) { _ = s.ToString(); } } } static class Extensions { [return: MaybeNull] public static IAsyncEnumerator<string> GetAsyncEnumerator(this A a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable, MaybeNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,32): warning CS8602: Dereference of a possibly null reference. // await foreach(var s in new A()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A()").WithLocation(8, 32) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator15() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static async void M() { await foreach(var s in new A()) { _ = s.ToString(); } } } static class Extensions { [return: NotNull] public static IAsyncEnumerator<string>? GetAsyncEnumerator(this A a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable, NotNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator_Suppressions1() { var source = @" using System.Collections.Generic; class A { public static void M() { foreach(var s in new A()!) { _ = s.ToString(); } } } static class Extensions { public static IEnumerator<string>? GetEnumerator(this A a) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator_Suppressions2() { var source = @" using System.Collections.Generic; class A { public static void M() { var a = default(A); foreach(var s in a!) { _ = s.ToString(); } } } static class Extensions { public static IEnumerator<string> GetEnumerator(this A a) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_01() { var source = @"class A { } class B { } class C { static void F<T>(T? t) where T : A { } static void G(B? b) { F(b); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,9): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>(T?)'. There is no implicit reference conversion from 'B' to 'A'. // F(b); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "F").WithArguments("C.F<T>(T?)", "A", "T", "B").WithLocation(8, 9)); } [Fact] public void TypeInference_02() { var source = @"interface I<T> { } class C { static T F<T>(I<T> t) { throw new System.Exception(); } static void G(I<string> x, I<string?> y) { F(x).ToString(); F(y).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // F(y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y)").WithLocation(11, 9)); } [Fact] public void TypeInference_03() { var source = @"interface I<T> { } class C { static T F1<T>(I<T?> t) { throw new System.Exception(); } static void G1(I<string> x1, I<string?> y1) { F1(x1).ToString(); // 1 F1(y1).ToString(); } static T F2<T>(I<T?> t) where T : class { throw new System.Exception(); } static void G2(I<string> x2, I<string?> y2) { F2(x2).ToString(); // 2 F2(y2).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static T F1<T>(I<T?> t) Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 22), // (10,12): warning CS8620: Argument of type 'I<string>' cannot be used for parameter 't' of type 'I<string?>' in 'string C.F1<string>(I<string?> t)' due to differences in the nullability of reference types. // F1(x1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1").WithArguments("I<string>", "I<string?>", "t", "string C.F1<string>(I<string?> t)").WithLocation(10, 12), // (19,12): warning CS8620: Argument of type 'I<string>' cannot be used for parameter 't' of type 'I<string?>' in 'string C.F2<string>(I<string?> t)' due to differences in the nullability of reference types. // F2(x2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x2").WithArguments("I<string>", "I<string?>", "t", "string C.F2<string>(I<string?> t)").WithLocation(19, 12)); } [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] [Fact] public void TypeInference_LowerBounds_TopLevelNullability_01() { var source0 = @"public class A { public static A F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static void G(A? x, A y) { var z = A.F; F(x, x)/*T:A?*/; F(x, y)/*T:A?*/; F(x, z)/*T:A?*/; F(y, x)/*T:A?*/; F(y, y)/*T:A!*/; F(y, z)/*T:A!*/; F(z, x)/*T:A?*/; F(z, y)/*T:A!*/; F(z, z)/*T:A!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_LowerBounds_TopLevelNullability_02() { var source = @"class C { static T F<T>(T x, T y) => throw null!; static void G<T, U>(T t, U u) where T : class? where U : class, T { F(t, t)/*T:T*/; F(t, u)/*T:T*/; F(u, t)/*T:T*/; F(u, u)/*T:U!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] [Fact] public void TypeInference_ExactBounds_TopLevelNullability_01() { var source0 = @"public class A { public static A F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(out T x, out T y) => throw null!; static void G(A? x, A y) { var z = A.F; F(out x, out x)/*T:A?*/; F(out x, out y)/*T:A!*/; F(out x, out z)/*T:A?*/; F(out y, out x)/*T:A!*/; F(out y, out y)/*T:A!*/; F(out y, out z)/*T:A!*/; F(out z, out x)/*T:A?*/; F(out z, out y)/*T:A!*/; F(out z, out z)/*T:A?*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void TypeInference_LowerBounds_NestedNullability_Variant_01() { var source0 = @"public class A { public static I<string> F; public static IIn<string> FIn; public static IOut<string> FOut; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static void G1(I<string> x1, I<string?> y1) { var z1 = A.F/*T:I<string>!*/; F(x1, x1)/*T:I<string!>!*/; F(x1, y1)/*T:I<string!>!*/; // 1 F(x1, z1)/*T:I<string!>!*/; F(y1, x1)/*T:I<string!>!*/; // 2 F(y1, y1)/*T:I<string?>!*/; F(y1, z1)/*T:I<string?>!*/; F(z1, x1)/*T:I<string!>!*/; F(z1, y1)/*T:I<string?>!*/; F(z1, z1)/*T:I<string>!*/; } static void G2(IIn<string> x2, IIn<string?> y2) { var z2 = A.FIn/*T:IIn<string>!*/; F(x2, x2)/*T:IIn<string!>!*/; F(x2, y2)/*T:IIn<string!>!*/; F(x2, z2)/*T:IIn<string!>!*/; F(y2, x2)/*T:IIn<string!>!*/; F(y2, y2)/*T:IIn<string?>!*/; F(y2, z2)/*T:IIn<string>!*/; F(z2, x2)/*T:IIn<string!>!*/; F(z2, y2)/*T:IIn<string>!*/; F(z2, z2)/*T:IIn<string>!*/; } static void G3(IOut<string> x3, IOut<string?> y3) { var z3 = A.FOut/*T:IOut<string>!*/; F(x3, x3)/*T:IOut<string!>!*/; F(x3, y3)/*T:IOut<string?>!*/; F(x3, z3)/*T:IOut<string>!*/; F(y3, x3)/*T:IOut<string?>!*/; F(y3, y3)/*T:IOut<string?>!*/; F(y3, z3)/*T:IOut<string?>!*/; F(z3, x3)/*T:IOut<string>!*/; F(z3, y3)/*T:IOut<string?>!*/; F(z3, z3)/*T:IOut<string>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (8,15): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'y' in 'I<string> C.F<I<string>>(I<string> x, I<string> y)'. // F(x1, y1)/*T:I<string!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<string?>", "I<string>", "y", "I<string> C.F<I<string>>(I<string> x, I<string> y)").WithLocation(8, 15), // (10,11): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'x' in 'I<string> C.F<I<string>>(I<string> x, I<string> y)'. // F(y1, x1)/*T:I<string!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<string?>", "I<string>", "x", "I<string> C.F<I<string>>(I<string> x, I<string> y)").WithLocation(10, 11) ); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void TypeInference_LowerBounds_NestedNullability_Variant_02() { var source0 = @"public class A { public static B<string> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"public interface IOut<out T, out U> { } class C { static T F<T>(T x, T y) => throw null!; static T F<T>(T x, T y, T z) => throw null!; static IOut<T, U> CreateIOut<T, U>(B<T> t, B<U> u) => throw null!; static void G(B<string> x, B<string?> y) { var z = A.F/*T:B<string>!*/; var xx = CreateIOut(x, x)/*T:IOut<string!, string!>!*/; var xy = CreateIOut(x, y)/*T:IOut<string!, string?>!*/; var xz = CreateIOut(x, z)/*T:IOut<string!, string>!*/; F(xx, xy)/*T:IOut<string!, string?>!*/; F(xx, xz)/*T:IOut<string!, string>!*/; F(CreateIOut(y, x), xx)/*T:IOut<string?, string!>!*/; F(CreateIOut(y, z), CreateIOut(z, x))/*T:IOut<string?, string>!*/; F(xx, xy, xz)/*T:IOut<string!, string?>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void TypeInference_LowerBounds_NestedNullability_Variant_03() { var source0 = @"public class A { public static I<string> F; public static IIn<string> FIn; public static IOut<string> FOut; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static I<T> Create1<T>(T t) => throw null!; static void G1(I<IOut<string?>> x1, I<IOut<string>> y1) { var z1 = Create1(A.FOut)/*T:I<IOut<string>!>!*/; F(x1, x1)/*T:I<IOut<string?>!>!*/; F(x1, y1)/*T:I<IOut<string!>!>!*/; // 1 F(x1, z1)/*T:I<IOut<string?>!>!*/; F(y1, x1)/*T:I<IOut<string!>!>!*/; // 2 F(y1, y1)/*T:I<IOut<string!>!>!*/; F(y1, z1)/*T:I<IOut<string!>!>!*/; F(z1, x1)/*T:I<IOut<string?>!>!*/; F(z1, y1)/*T:I<IOut<string!>!>!*/; F(z1, z1)/*T:I<IOut<string>!>!*/; } static IOut<T> Create2<T>(T t) => throw null!; static void G2(IOut<IIn<string?>> x2, IOut<IIn<string>> y2) { var z2 = Create2(A.FIn)/*T:IOut<IIn<string>!>!*/; F(x2, x2)/*T:IOut<IIn<string?>!>!*/; F(x2, y2)/*T:IOut<IIn<string!>!>!*/; F(x2, z2)/*T:IOut<IIn<string>!>!*/; F(y2, x2)/*T:IOut<IIn<string!>!>!*/; F(y2, y2)/*T:IOut<IIn<string!>!>!*/; F(y2, z2)/*T:IOut<IIn<string!>!>!*/; F(z2, x2)/*T:IOut<IIn<string>!>!*/; F(z2, y2)/*T:IOut<IIn<string!>!>!*/; F(z2, z2)/*T:IOut<IIn<string>!>!*/; } static IIn<T> Create3<T>(T t) => throw null!; static void G3(IIn<IOut<string?>> x3, IIn<IOut<string>> y3) { var z3 = Create3(A.FOut)/*T:IIn<IOut<string>!>!*/; F(x3, x3)/*T:IIn<IOut<string?>!>!*/; F(x3, y3)/*T:IIn<IOut<string!>!>!*/; F(x3, z3)/*T:IIn<IOut<string>!>!*/; F(y3, x3)/*T:IIn<IOut<string!>!>!*/; F(y3, y3)/*T:IIn<IOut<string!>!>!*/; F(y3, z3)/*T:IIn<IOut<string!>!>!*/; F(z3, x3)/*T:IIn<IOut<string>!>!*/; F(z3, y3)/*T:IIn<IOut<string!>!>!*/; F(z3, z3)/*T:IIn<IOut<string>!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (9,11): warning CS8620: Nullability of reference types in argument of type 'I<IOut<string?>>' doesn't match target type 'I<IOut<string>>' for parameter 'x' in 'I<IOut<string>> C.F<I<IOut<string>>>(I<IOut<string>> x, I<IOut<string>> y)'. // F(x1, y1)/*T:I<IOut<string!>!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1").WithArguments("I<IOut<string?>>", "I<IOut<string>>", "x", "I<IOut<string>> C.F<I<IOut<string>>>(I<IOut<string>> x, I<IOut<string>> y)").WithLocation(9, 11), // (11,15): warning CS8620: Nullability of reference types in argument of type 'I<IOut<string?>>' doesn't match target type 'I<IOut<string>>' for parameter 'y' in 'I<IOut<string>> C.F<I<IOut<string>>>(I<IOut<string>> x, I<IOut<string>> y)'. // F(y1, x1)/*T:I<IOut<string!>!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1").WithArguments("I<IOut<string?>>", "I<IOut<string>>", "y", "I<IOut<string>> C.F<I<IOut<string>>>(I<IOut<string>> x, I<IOut<string>> y)").WithLocation(11, 15) ); } [Fact] public void TypeInference_ExactBounds_TopLevelNullability_02() { var source0 = @"public class A { public static B<string> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(B<T> x, B<T> y) => throw null!; static void G(B<string?> x, B<string> y) { var z = A.F/*T:B<string>!*/; F(x, x)/*T:string?*/; F(x, y)/*T:string!*/; // 1 F(x, z)/*T:string?*/; F(y, x)/*T:string!*/; // 2 F(y, y)/*T:string!*/; F(y, z)/*T:string!*/; F(z, x)/*T:string?*/; F(z, y)/*T:string!*/; F(z, z)/*T:string!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (8,11): warning CS8620: Nullability of reference types in argument of type 'B<string?>' doesn't match target type 'B<string>' for parameter 'x' in 'string C.F<string>(B<string> x, B<string> y)'. // F(x, y)/*T:string!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<string?>", "B<string>", "x", "string C.F<string>(B<string> x, B<string> y)").WithLocation(8, 11), // (10,14): warning CS8620: Nullability of reference types in argument of type 'B<string?>' doesn't match target type 'B<string>' for parameter 'y' in 'string C.F<string>(B<string> x, B<string> y)'. // F(y, x)/*T:string!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<string?>", "B<string>", "y", "string C.F<string>(B<string> x, B<string> y)").WithLocation(10, 14) ); } [Fact] public void TypeInference_ExactBounds_NestedNullability() { var source0 = @"public class A { public static B<object> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class Program { static T F<T>(T x, T y, T z) => throw null!; static void G(B<object?> x, B<object> y) { var z = A.F/*T:B<object>!*/; F(x, x, x)/*T:B<object?>!*/; F(x, x, y)/*T:B<object!>!*/; // 1 2 F(x, x, z)/*T:B<object?>!*/; F(x, y, x)/*T:B<object!>!*/; // 3 4 F(x, y, y)/*T:B<object!>!*/; // 5 F(x, y, z)/*T:B<object!>!*/; // 6 F(x, z, x)/*T:B<object?>!*/; F(x, z, y)/*T:B<object!>!*/; // 7 F(x, z, z)/*T:B<object?>!*/; F(y, x, x)/*T:B<object!>!*/; // 8 9 F(y, x, y)/*T:B<object!>!*/; // 10 F(y, x, z)/*T:B<object!>!*/; // 11 F(y, y, x)/*T:B<object!>!*/; // 12 F(y, y, y)/*T:B<object!>!*/; F(y, y, z)/*T:B<object!>!*/; F(y, z, x)/*T:B<object!>!*/; // 13 F(y, z, y)/*T:B<object!>!*/; F(y, z, z)/*T:B<object!>!*/; F(z, x, x)/*T:B<object?>!*/; F(z, x, y)/*T:B<object!>!*/; // 14 F(z, x, z)/*T:B<object?>!*/; F(z, y, x)/*T:B<object!>!*/; // 15 F(z, y, y)/*T:B<object!>!*/; F(z, y, z)/*T:B<object!>!*/; F(z, z, x)/*T:B<object?>!*/; F(z, z, y)/*T:B<object!>!*/; F(z, z, z)/*T:B<object>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,11): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'x' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, x, y)/*T:B<object!>!*/; // 1 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "x", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(8, 11), // (8,14): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'y' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, x, y)/*T:B<object!>!*/; // 1 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "y", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(8, 14), // (10,11): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'x' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, y, x)/*T:B<object!>!*/; // 3 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "x", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(10, 11), // (10,17): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'z' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, y, x)/*T:B<object!>!*/; // 3 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "z", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(10, 17), // (11,11): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'x' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, y, y)/*T:B<object!>!*/; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "x", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(11, 11), // (12,11): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'x' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, y, z)/*T:B<object!>!*/; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "x", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(12, 11), // (14,11): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'x' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, z, y)/*T:B<object!>!*/; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "x", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(14, 11), // (16,14): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'y' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(y, x, x)/*T:B<object!>!*/; // 8 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "y", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(16, 14), // (16,17): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'z' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(y, x, x)/*T:B<object!>!*/; // 8 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "z", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(16, 17), // (17,14): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'y' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(y, x, y)/*T:B<object!>!*/; // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "y", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(17, 14), // (18,14): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'y' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(y, x, z)/*T:B<object!>!*/; // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "y", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(18, 14), // (19,17): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'z' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(y, y, x)/*T:B<object!>!*/; // 12 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "z", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(19, 17), // (22,17): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'z' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(y, z, x)/*T:B<object!>!*/; // 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "z", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(22, 17), // (26,14): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'y' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(z, x, y)/*T:B<object!>!*/; // 14 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "y", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(26, 14), // (28,17): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'z' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(z, y, x)/*T:B<object!>!*/; // 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "z", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(28, 17) ); comp.VerifyTypes(); } [Fact] public void TypeInference_ExactAndLowerBounds_TopLevelNullability() { var source0 = @"public class A { public static B<string> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, B<T> y) => throw null!; static B<T> CreateB<T>(T t) => throw null!; static void G(string? x, string y) { var z = A.F /*T:B<string>!*/; F(x, CreateB(x))/*T:string?*/; F(x, CreateB(y))/*T:string?*/; // 1 F(x, z)/*T:string?*/; F(y, CreateB(x))/*T:string?*/; F(y, CreateB(y))/*T:string!*/; F(y, z)/*T:string!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (9,14): warning CS8620: Nullability of reference types in argument of type 'B<string>' doesn't match target type 'B<string?>' for parameter 'y' in 'string? C.F<string?>(string? x, B<string?> y)'. // F(x, CreateB(y))/*T:string?*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "CreateB(y)").WithArguments("B<string>", "B<string?>", "y", "string? C.F<string?>(string? x, B<string?> y)").WithLocation(9, 14) ); } [Fact] public void TypeInference_ExactAndUpperBounds_TopLevelNullability() { var source0 = @"public class A { public static IIn<string> FIn; public static B<string> FB; } public interface IIn<in T> { } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(IIn<T> x, B<T> y) => throw null!; static IIn<T> CreateIIn<T>(T t) => throw null!; static B<T> CreateB<T>(T t) => throw null!; static void G(string? x, string y) { var zin = A.FIn/*T:IIn<string>!*/; var zb = A.FB/*T:B<string>!*/; F(CreateIIn(x), CreateB(x))/*T:string?*/; F(CreateIIn(x), CreateB(y))/*T:string!*/; F(CreateIIn(x), zb)/*T:string!*/; F(CreateIIn(y), CreateB(x))/*T:string!*/; // 1 F(CreateIIn(y), CreateB(y))/*T:string!*/; F(CreateIIn(y), zb)/*T:string!*/; F(zin, CreateB(x))/*T:string!*/; F(zin, CreateB(y))/*T:string!*/; F(zin, zb)/*T:string!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (13,25): warning CS8620: Nullability of reference types in argument of type 'B<string?>' doesn't match target type 'B<string>' for parameter 'y' in 'string C.F<string>(IIn<string> x, B<string> y)'. // F(CreateIIn(y), CreateB(x))/*T:string!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "CreateB(x)").WithArguments("B<string?>", "B<string>", "y", "string C.F<string>(IIn<string> x, B<string> y)").WithLocation(13, 25) ); comp.VerifyTypes(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void TypeInference_MixedBounds_NestedNullability() { var source0 = @"public class A { public static IIn<object, string> F1; public static IOut<object, string> F2; } public interface IIn<in T, U> { } public interface IOut<T, out U> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static void F1(bool b, IIn<object, string> x1, IIn<object?, string?> y1) { var z1 = A.F1/*T:IIn<object, string>!*/; F(x1, x1)/*T:IIn<object!, string!>!*/; F(x1, y1)/*T:IIn<object!, string!>!*/; // 1 F(x1, z1)/*T:IIn<object!, string!>!*/; F(y1, x1)/*T:IIn<object!, string!>!*/; // 2 F(y1, y1)/*T:IIn<object?, string?>!*/; F(y1, z1)/*T:IIn<object, string?>!*/; F(z1, x1)/*T:IIn<object!, string!>!*/; F(z1, y1)/*T:IIn<object, string?>!*/; F(z1, z1)/*T:IIn<object, string>!*/; } static void F2(bool b, IOut<object, string> x2, IOut<object?, string?> y2) { var z2 = A.F2/*T:IOut<object, string>!*/; F(x2, x2)/*T:IOut<object!, string!>!*/; F(x2, y2)/*T:IOut<object!, string?>!*/; // 3 F(x2, z2)/*T:IOut<object!, string>!*/; F(y2, x2)/*T:IOut<object!, string?>!*/; // 4 F(y2, y2)/*T:IOut<object?, string?>!*/; F(y2, z2)/*T:IOut<object?, string?>!*/; F(z2, x2)/*T:IOut<object!, string>!*/; F(z2, y2)/*T:IOut<object?, string?>!*/; F(z2, z2)/*T:IOut<object, string>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (8,15): warning CS8620: Nullability of reference types in argument of type 'IIn<object?, string?>' doesn't match target type 'IIn<object, string>' for parameter 'y' in 'IIn<object, string> C.F<IIn<object, string>>(IIn<object, string> x, IIn<object, string> y)'. // F(x1, y1)/*T:IIn<object!, string!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("IIn<object?, string?>", "IIn<object, string>", "y", "IIn<object, string> C.F<IIn<object, string>>(IIn<object, string> x, IIn<object, string> y)").WithLocation(8, 15), // (10,11): warning CS8620: Nullability of reference types in argument of type 'IIn<object?, string?>' doesn't match target type 'IIn<object, string>' for parameter 'x' in 'IIn<object, string> C.F<IIn<object, string>>(IIn<object, string> x, IIn<object, string> y)'. // F(y1, x1)/*T:IIn<object!, string!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("IIn<object?, string?>", "IIn<object, string>", "x", "IIn<object, string> C.F<IIn<object, string>>(IIn<object, string> x, IIn<object, string> y)").WithLocation(10, 11), // (21,15): warning CS8620: Nullability of reference types in argument of type 'IOut<object?, string?>' doesn't match target type 'IOut<object, string?>' for parameter 'y' in 'IOut<object, string?> C.F<IOut<object, string?>>(IOut<object, string?> x, IOut<object, string?> y)'. // F(x2, y2)/*T:IOut<object!, string?>!*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y2").WithArguments("IOut<object?, string?>", "IOut<object, string?>", "y", "IOut<object, string?> C.F<IOut<object, string?>>(IOut<object, string?> x, IOut<object, string?> y)").WithLocation(21, 15), // (23,11): warning CS8620: Nullability of reference types in argument of type 'IOut<object?, string?>' doesn't match target type 'IOut<object, string?>' for parameter 'x' in 'IOut<object, string?> C.F<IOut<object, string?>>(IOut<object, string?> x, IOut<object, string?> y)'. // F(y2, x2)/*T:IOut<object!, string?>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y2").WithArguments("IOut<object?, string?>", "IOut<object, string?>", "x", "IOut<object, string?> C.F<IOut<object, string?>>(IOut<object, string?> x, IOut<object, string?> y)").WithLocation(23, 11) ); } [Fact] public void TypeInference_LowerBounds_NestedNullability_MismatchedTypes() { var source = @"interface IOut<out T> { } class Program { static T F<T>(T x, T y) => throw null!; static void G(IOut<object> x, IOut<string?> y) { F(x, y)/*T:IOut<object!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // Ideally we'd infer IOut<object?> but the spec doesn't require merging nullability // across distinct types (in this case, the lower bounds IOut<object!> and IOut<string?>). // Instead, method type inference infers IOut<object!> and a warning is reported // converting the second argument to the inferred parameter type. comp.VerifyTypes(); comp.VerifyDiagnostics( // (7,14): warning CS8620: Nullability of reference types in argument of type 'IOut<string?>' doesn't match target type 'IOut<object>' for parameter 'y' in 'IOut<object> Program.F<IOut<object>>(IOut<object> x, IOut<object> y)'. // F(x, y); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IOut<string?>", "IOut<object>", "y", "IOut<object> Program.F<IOut<object>>(IOut<object> x, IOut<object> y)").WithLocation(7, 14)); } [Fact] public void TypeInference_LowerAndUpperBounds_NestedNullability() { var source = @"interface IIn<in T> { } interface IOut<out T> { } class Program { static T FIn<T>(T x, T y, IIn<T> z) => throw null!; static T FOut<T>(T x, T y, IOut<T> z) => throw null!; static IIn<T> CreateIIn<T>(T t) => throw null!; static IOut<T> CreateIOut<T>(T t) => throw null!; static void G1(IIn<string?> x1, IIn<string> y1) { FIn(x1, y1, CreateIIn(x1))/*T:IIn<string!>!*/; // 1 FIn(x1, y1, CreateIIn(y1))/*T:IIn<string!>!*/; FOut(x1, y1, CreateIOut(x1))/*T:IIn<string!>!*/; FOut(x1, y1, CreateIOut(y1))/*T:IIn<string!>!*/; } static void G2(IOut<string?> x2, IOut<string> y2) { FIn(x2, y2, CreateIIn(x2))/*T:IOut<string?>!*/; FIn(x2, y2, CreateIIn(y2))/*T:IOut<string?>!*/; // 2 FOut(x2, y2, CreateIOut(x2))/*T:IOut<string?>!*/; FOut(x2, y2, CreateIOut(y2))/*T:IOut<string?>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // Ideally we'd fail to infer nullability for // 1 and // 2 rather than inferring the // wrong nullability and then reporting a warning converting the arguments. // (See MethodTypeInferrer.TryMergeAndReplaceIfStillCandidate which ignores // the variance used merging earlier candidates when merging later candidates.) comp.VerifyTypes(); comp.VerifyDiagnostics( // (11,21): warning CS8620: Nullability of reference types in argument of type 'IIn<IIn<string?>>' doesn't match target type 'IIn<IIn<string>>' for parameter 'z' in 'IIn<string> Program.FIn<IIn<string>>(IIn<string> x, IIn<string> y, IIn<IIn<string>> z)'. // FIn(x1, y1, CreateIIn(x1))/*T:IIn<string!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "CreateIIn(x1)").WithArguments("IIn<IIn<string?>>", "IIn<IIn<string>>", "z", "IIn<string> Program.FIn<IIn<string>>(IIn<string> x, IIn<string> y, IIn<IIn<string>> z)").WithLocation(11, 21), // (19,21): warning CS8620: Nullability of reference types in argument of type 'IIn<IOut<string>>' doesn't match target type 'IIn<IOut<string?>>' for parameter 'z' in 'IOut<string?> Program.FIn<IOut<string?>>(IOut<string?> x, IOut<string?> y, IIn<IOut<string?>> z)'. // FIn(x2, y2, CreateIIn(y2))/*T:IOut<string?>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "CreateIIn(y2)").WithArguments("IIn<IOut<string>>", "IIn<IOut<string?>>", "z", "IOut<string?> Program.FIn<IOut<string?>>(IOut<string?> x, IOut<string?> y, IIn<IOut<string?>> z)").WithLocation(19, 21)); } [Fact] public void TypeInference_05() { var source = @"class C { static T F<T>(T x, T? y) where T : class => x; static void G(C? x, C y) { F(x, x).ToString(); F(x, y).ToString(); F(y, x).ToString(); F(y, y).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8634: The type 'C?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>(T, T?)'. Nullability of type argument 'C?' doesn't match 'class' constraint. // F(x, x).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>(T, T?)", "T", "C?").WithLocation(6, 9), // (6,9): warning CS8602: Dereference of a possibly null reference. // F(x, x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x, x)").WithLocation(6, 9), // (7,9): warning CS8634: The type 'C?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>(T, T?)'. Nullability of type argument 'C?' doesn't match 'class' constraint. // F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>(T, T?)", "T", "C?").WithLocation(7, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x, y)").WithLocation(7, 9)); } [Fact] public void TypeInference_06() { var source = @"class C { static T F<T, U>(T t, U u) where U : T => t; static void G(C? x, C y) { F(x, x).ToString(); // warning: may be null F(x, y).ToString(); // warning may be null F(y, x).ToString(); // warning: x does not satisfy U constraint F(y, y).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // F(x, x).ToString(); // warning: may be null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x, x)").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // F(x, y).ToString(); // warning may be null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x, y)").WithLocation(7, 9), // (8,9): warning CS8631: The type 'C?' cannot be used as type parameter 'U' in the generic type or method 'C.F<T, U>(T, U)'. Nullability of type argument 'C?' doesn't match constraint type 'C'. // F(y, x).ToString(); // warning: x does not satisfy U constraint Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F").WithArguments("C.F<T, U>(T, U)", "C", "U", "C?").WithLocation(8, 9)); } [Fact] public void TypeInference_LowerBounds_NestedNullability_MismatchedNullability() { var source0 = @"public class A { public static A<object> F; public static A<string> G; } public class A<T> { } public class B<T, U> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static B<T, U> CreateB<T, U>(A<T> t, A<U> u) => throw null!; static void G(A<object?> t1, A<object> t2, A<string?> u1, A<string> u2) { var t3 = A.F/*T:A<object>!*/; var u3 = A.G/*T:A<string>!*/; var x = CreateB(t1, u2)/*T:B<object?, string!>!*/; var y = CreateB(t2, u1)/*T:B<object!, string?>!*/; var z = CreateB(t1, u3)/*T:B<object?, string>!*/; var w = CreateB(t3, u2)/*T:B<object, string!>!*/; F(x, y)/*T:B<object!, string!>!*/; F(x, z)/*T:B<object?, string!>!*/; F(x, w)/*T:B<object?, string!>!*/; F(y, z)/*T:B<object!, string?>!*/; F(y, w)/*T:B<object!, string!>!*/; F(w, z)/*T:B<object?, string!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (13,11): warning CS8620: Nullability of reference types in argument of type 'B<object?, string>' doesn't match target type 'B<object, string>' for parameter 'x' in 'B<object, string> C.F<B<object, string>>(B<object, string> x, B<object, string> y)'. // F(x, y)/*T:B<object!, string!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?, string>", "B<object, string>", "x", "B<object, string> C.F<B<object, string>>(B<object, string> x, B<object, string> y)").WithLocation(13, 11), // (13,14): warning CS8620: Nullability of reference types in argument of type 'B<object, string?>' doesn't match target type 'B<object, string>' for parameter 'y' in 'B<object, string> C.F<B<object, string>>(B<object, string> x, B<object, string> y)'. // F(x, y)/*T:B<object!, string!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("B<object, string?>", "B<object, string>", "y", "B<object, string> C.F<B<object, string>>(B<object, string> x, B<object, string> y)").WithLocation(13, 14), // (16,14): warning CS8620: Nullability of reference types in argument of type 'B<object?, string>' doesn't match target type 'B<object, string?>' for parameter 'y' in 'B<object, string?> C.F<B<object, string?>>(B<object, string?> x, B<object, string?> y)'. // F(y, z)/*T:B<object!, string?>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("B<object?, string>", "B<object, string?>", "y", "B<object, string?> C.F<B<object, string?>>(B<object, string?> x, B<object, string?> y)").WithLocation(16, 14), // (17,11): warning CS8620: Nullability of reference types in argument of type 'B<object, string?>' doesn't match target type 'B<object, string>' for parameter 'x' in 'B<object, string> C.F<B<object, string>>(B<object, string> x, B<object, string> y)'. // F(y, w)/*T:B<object!, string!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("B<object, string?>", "B<object, string>", "x", "B<object, string> C.F<B<object, string>>(B<object, string> x, B<object, string> y)").WithLocation(17, 11) ); } [Fact] public void TypeInference_UpperBounds_NestedNullability_MismatchedNullability() { var source0 = @"public class A { public static X<object> F; public static X<string> G; } public interface IIn<in T> { } public class B<T, U> { } public class X<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(IIn<T> x, IIn<T> y) => throw null!; static IIn<B<T, U>> CreateB<T, U>(X<T> t, X<U> u) => throw null!; static void G(X<object?> t1, X<object> t2, X<string?> u1, X<string> u2) { var t3 = A.F/*T:X<object>!*/; var u3 = A.G/*T:X<string>!*/; var x = CreateB(t1, u2)/*T:IIn<B<object?, string!>!>!*/; var y = CreateB(t2, u1)/*T:IIn<B<object!, string?>!>!*/; var z = CreateB(t1, u3)/*T:IIn<B<object?, string>!>!*/; var w = CreateB(t3, u2)/*T:IIn<B<object, string!>!>!*/; F(x, y)/*T:B<object!, string!>!*/; // 1 2 F(x, z)/*T:B<object?, string!>!*/; F(x, w)/*T:B<object?, string!>!*/; F(y, z)/*T:B<object!, string?>!*/; // 3 F(y, w)/*T:B<object!, string!>!*/; // 4 F(w, z)/*T:B<object?, string!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (13,11): warning CS8620: Nullability of reference types in argument of type 'IIn<B<object?, string>>' doesn't match target type 'IIn<B<object, string>>' for parameter 'x' in 'B<object, string> C.F<B<object, string>>(IIn<B<object, string>> x, IIn<B<object, string>> y)'. // F(x, y)/*T:B<object!, string!>!*/; // 1 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("IIn<B<object?, string>>", "IIn<B<object, string>>", "x", "B<object, string> C.F<B<object, string>>(IIn<B<object, string>> x, IIn<B<object, string>> y)").WithLocation(13, 11), // (13,14): warning CS8620: Nullability of reference types in argument of type 'IIn<B<object, string?>>' doesn't match target type 'IIn<B<object, string>>' for parameter 'y' in 'B<object, string> C.F<B<object, string>>(IIn<B<object, string>> x, IIn<B<object, string>> y)'. // F(x, y)/*T:B<object!, string!>!*/; // 1 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IIn<B<object, string?>>", "IIn<B<object, string>>", "y", "B<object, string> C.F<B<object, string>>(IIn<B<object, string>> x, IIn<B<object, string>> y)").WithLocation(13, 14), // (16,14): warning CS8620: Nullability of reference types in argument of type 'IIn<B<object?, string>>' doesn't match target type 'IIn<B<object, string?>>' for parameter 'y' in 'B<object, string?> C.F<B<object, string?>>(IIn<B<object, string?>> x, IIn<B<object, string?>> y)'. // F(y, z)/*T:B<object!, string?>!*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IIn<B<object?, string>>", "IIn<B<object, string?>>", "y", "B<object, string?> C.F<B<object, string?>>(IIn<B<object, string?>> x, IIn<B<object, string?>> y)").WithLocation(16, 14), // (17,11): warning CS8620: Nullability of reference types in argument of type 'IIn<B<object, string?>>' doesn't match target type 'IIn<B<object, string>>' for parameter 'x' in 'B<object, string> C.F<B<object, string>>(IIn<B<object, string>> x, IIn<B<object, string>> y)'. // F(y, w)/*T:B<object!, string!>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IIn<B<object, string?>>", "IIn<B<object, string>>", "x", "B<object, string> C.F<B<object, string>>(IIn<B<object, string>> x, IIn<B<object, string>> y)").WithLocation(17, 11) ); } [Fact] public void TypeInference_LowerBounds_NestedNullability_TypeParameters() { var source = @"interface IOut<out T> { } class C { static T F<T>(T x, T y) => throw null!; static void G<T>(IOut<T?> x, IOut<T> y) where T : class { F(x, x)/*T:IOut<T?>!*/; F(x, y)/*T:IOut<T?>!*/; F(y, x)/*T:IOut<T?>!*/; F(y, y)/*T:IOut<T!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] [WorkItem(33346, "https://github.com/dotnet/roslyn/issues/33346")] public void TypeInference_LowerBounds_NestedNullability_Arrays() { var source0 = @"public class A { public static string[] F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static void G(string?[] x, string[] y) { var z = A.F/*T:string[]!*/; F(x, x)/*T:string?[]!*/; F(x, y)/*T:string?[]!*/; F(x, z)/*T:string?[]!*/; F(y, x)/*T:string?[]!*/; F(y, y)/*T:string![]!*/; F(y, z)/*T:string[]!*/; F(z, x)/*T:string?[]!*/; F(z, y)/*T:string[]!*/; F(z, z)/*T:string[]!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_LowerBounds_NestedNullability_Dynamic() { var source = @"interface IOut<out T> { } class C { static T F<T>(T x, T y) => throw null!; static void G(IOut<dynamic?> x, IOut<dynamic> y) { F(x, x)/*T:IOut<dynamic?>!*/; F(x, y)/*T:IOut<dynamic?>!*/; F(y, x)/*T:IOut<dynamic?>!*/; F(y, y)/*T:IOut<dynamic!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_LowerBounds_NestedNullability_Pointers() { var source = @"unsafe class C { static T F<T>(T x, T y) => throw null!; static void G(object?* x, object* y) // 1 { _ = z/*T:object**/; F(x, x)/*T:object?**/; // 2 F(x, y)/*T:object!**/; // 3 F(x, z)/*T:object?**/; // 4 F(y, x)/*T:object!**/; // 5 F(y, y)/*T:object!**/; // 6 F(y, z)/*T:object!**/; // 7 F(z, x)/*T:object?**/; // 8 F(z, y)/*T:object!**/; // 9 F(z, z)/*T:object**/; // 10 } #nullable disable public static object* z = null; // 11 }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(TestOptions.UnsafeDebugDll)); comp.VerifyTypes(); comp.VerifyDiagnostics( // (4,28): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // static void G(object?* x, object* y) // 1 Diagnostic(ErrorCode.ERR_ManagedAddr, "x").WithArguments("object").WithLocation(4, 28), // (4,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // static void G(object?* x, object* y) // 1 Diagnostic(ErrorCode.ERR_ManagedAddr, "y").WithArguments("object").WithLocation(4, 39), // (7,9): error CS0306: The type 'object*' may not be used as a type argument // F(x, x)/*T:object?**/; // 2 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(7, 9), // (8,9): error CS0306: The type 'object*' may not be used as a type argument // F(x, y)/*T:object!**/; // 3 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(8, 9), // (9,9): error CS0306: The type 'object*' may not be used as a type argument // F(x, z)/*T:object?**/; // 4 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(9, 9), // (10,9): error CS0306: The type 'object*' may not be used as a type argument // F(y, x)/*T:object!**/; // 5 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(10, 9), // (11,9): error CS0306: The type 'object*' may not be used as a type argument // F(y, y)/*T:object!**/; // 6 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(11, 9), // (12,9): error CS0306: The type 'object*' may not be used as a type argument // F(y, z)/*T:object!**/; // 7 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(12, 9), // (13,9): error CS0306: The type 'object*' may not be used as a type argument // F(z, x)/*T:object?**/; // 8 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(13, 9), // (14,9): error CS0306: The type 'object*' may not be used as a type argument // F(z, y)/*T:object!**/; // 9 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(14, 9), // (15,9): error CS0306: The type 'object*' may not be used as a type argument // F(z, z)/*T:object**/; // 10 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(15, 9), // (20,27): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // public static object* z = null; // 11 Diagnostic(ErrorCode.ERR_ManagedAddr, "z").WithArguments("object").WithLocation(20, 27) ); } [Fact] public void TypeInference_LowerBounds_NestedNullability_Tuples() { var source0 = @"public class A { public static B<object> F; public static B<string> G; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static (T, U) Create<T, U>(B<T> t, B<U> u) => throw null!; static void G(B<object?> t1, B<object> t2, B<string?> u1, B<string> u2) { var t3 = A.F/*T:B<object>!*/; var u3 = A.G/*T:B<string>!*/; var x = Create(t1, u2)/*T:(object?, string!)*/; var y = Create(t2, u1)/*T:(object!, string?)*/; var z = Create(t1, u3)/*T:(object?, string)*/; var w = Create(t3, u2)/*T:(object, string!)*/; F(x, y)/*T:(object?, string?)*/; F(x, z)/*T:(object?, string)*/; F(x, w)/*T:(object?, string!)*/; F(y, z)/*T:(object?, string?)*/; F(y, w)/*T:(object, string?)*/; F(w, z)/*T:(object?, string)*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_LowerBounds_NestedNullability_Tuples_Variant() { var source0 = @"public class A { public static (object, string) F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>(T x, T y) => throw null!; static I<T> CreateI<T>(T t) => throw null!; static void G1(I<(object, string)> x1, I<(object?, string?)> y1) { var z1 = CreateI(A.F)/*T:I<(object, string)>!*/; F(x1, x1)/*T:I<(object!, string!)>!*/; F(x1, y1)/*T:I<(object!, string!)>!*/; F(x1, z1)/*T:I<(object!, string!)>!*/; F(y1, x1)/*T:I<(object!, string!)>!*/; F(y1, y1)/*T:I<(object?, string?)>!*/; F(y1, z1)/*T:I<(object?, string?)>!*/; F(z1, x1)/*T:I<(object!, string!)>!*/; F(z1, y1)/*T:I<(object?, string?)>!*/; F(z1, z1)/*T:I<(object, string)>!*/; } static IIn<T> CreateIIn<T>(T t) => throw null!; static void G2(IIn<(object, string)> x2, IIn<(object?, string?)> y2) { var z2 = CreateIIn(A.F)/*T:IIn<(object, string)>!*/; F(x2, x2)/*T:IIn<(object!, string!)>!*/; F(x2, y2)/*T:IIn<(object!, string!)>!*/; F(x2, z2)/*T:IIn<(object!, string!)>!*/; F(y2, x2)/*T:IIn<(object!, string!)>!*/; F(y2, y2)/*T:IIn<(object?, string?)>!*/; F(y2, z2)/*T:IIn<(object, string)>!*/; F(z2, x2)/*T:IIn<(object!, string!)>!*/; F(z2, y2)/*T:IIn<(object, string)>!*/; F(z2, z2)/*T:IIn<(object, string)>!*/; } static IOut<T> CreateIOut<T>(T t) => throw null!; static void G3(IOut<(object, string)> x3, IOut<(object?, string?)> y3) { var z3 = CreateIOut(A.F)/*T:IOut<(object, string)>!*/; F(x3, x3)/*T:IOut<(object!, string!)>!*/; F(x3, y3)/*T:IOut<(object?, string?)>!*/; F(x3, z3)/*T:IOut<(object, string)>!*/; F(y3, x3)/*T:IOut<(object?, string?)>!*/; F(y3, y3)/*T:IOut<(object?, string?)>!*/; F(y3, z3)/*T:IOut<(object?, string?)>!*/; F(z3, x3)/*T:IOut<(object, string)>!*/; F(z3, y3)/*T:IOut<(object?, string?)>!*/; F(z3, z3)/*T:IOut<(object, string)>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (12,15): warning CS8620: Nullability of reference types in argument of type 'I<(object?, string?)>' doesn't match target type 'I<(object, string)>' for parameter 'y' in 'I<(object, string)> C.F<I<(object, string)>>(I<(object, string)> x, I<(object, string)> y)'. // F(x1, y1)/*T:I<(object, string)>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<(object?, string?)>", "I<(object, string)>", "y", "I<(object, string)> C.F<I<(object, string)>>(I<(object, string)> x, I<(object, string)> y)").WithLocation(12, 15), // (14,11): warning CS8620: Nullability of reference types in argument of type 'I<(object?, string?)>' doesn't match target type 'I<(object, string)>' for parameter 'x' in 'I<(object, string)> C.F<I<(object, string)>>(I<(object, string)> x, I<(object, string)> y)'. // F(y1, x1)/*T:I<(object, string)>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<(object?, string?)>", "I<(object, string)>", "x", "I<(object, string)> C.F<I<(object, string)>>(I<(object, string)> x, I<(object, string)> y)").WithLocation(14, 11), // (26,15): warning CS8620: Nullability of reference types in argument of type 'IIn<(object?, string?)>' doesn't match target type 'IIn<(object, string)>' for parameter 'y' in 'IIn<(object, string)> C.F<IIn<(object, string)>>(IIn<(object, string)> x, IIn<(object, string)> y)'. // F(x2, y2)/*T:IIn<(object!, string!)>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y2").WithArguments("IIn<(object?, string?)>", "IIn<(object, string)>", "y", "IIn<(object, string)> C.F<IIn<(object, string)>>(IIn<(object, string)> x, IIn<(object, string)> y)").WithLocation(26, 15), // (28,11): warning CS8620: Nullability of reference types in argument of type 'IIn<(object?, string?)>' doesn't match target type 'IIn<(object, string)>' for parameter 'x' in 'IIn<(object, string)> C.F<IIn<(object, string)>>(IIn<(object, string)> x, IIn<(object, string)> y)'. // F(y2, x2)/*T:IIn<(object!, string!)>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y2").WithArguments("IIn<(object?, string?)>", "IIn<(object, string)>", "x", "IIn<(object, string)> C.F<IIn<(object, string)>>(IIn<(object, string)> x, IIn<(object, string)> y)").WithLocation(28, 11), // (40,11): warning CS8620: Nullability of reference types in argument of type 'IOut<(object, string)>' doesn't match target type 'IOut<(object?, string?)>' for parameter 'x' in 'IOut<(object?, string?)> C.F<IOut<(object?, string?)>>(IOut<(object?, string?)> x, IOut<(object?, string?)> y)'. // F(x3, y3)/*T:IOut<(object?, string?)>?*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x3").WithArguments("IOut<(object, string)>", "IOut<(object?, string?)>", "x", "IOut<(object?, string?)> C.F<IOut<(object?, string?)>>(IOut<(object?, string?)> x, IOut<(object?, string?)> y)").WithLocation(40, 11), // (42,15): warning CS8620: Nullability of reference types in argument of type 'IOut<(object, string)>' doesn't match target type 'IOut<(object?, string?)>' for parameter 'y' in 'IOut<(object?, string?)> C.F<IOut<(object?, string?)>>(IOut<(object?, string?)> x, IOut<(object?, string?)> y)'. // F(y3, x3)/*T:IOut<(object?, string?)>?*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x3").WithArguments("IOut<(object, string)>", "IOut<(object?, string?)>", "y", "IOut<(object?, string?)> C.F<IOut<(object?, string?)>>(IOut<(object?, string?)> x, IOut<(object?, string?)> y)").WithLocation(42, 15)); } [Fact] public void Assignment_NestedNullability_MismatchedNullability() { var source0 = @"public class A { public static object F; public static string G; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class B<T, U> { } class C { static B<T, U> CreateB<T, U>(T t, U u) => throw null!; static void G(object? t1, object t2, string? u1, string u2) { var t3 = A.F/*T:object!*/; var u3 = A.G/*T:string!*/; var x0 = CreateB(t1, u2)/*T:B<object?, string!>!*/; var y0 = CreateB(t2, u1)/*T:B<object!, string?>!*/; var z0 = CreateB(t1, u3)/*T:B<object?, string!>!*/; var w0 = CreateB(t3, u2)/*T:B<object!, string!>!*/; var x = x0; var y = y0; var z = z0; var w = w0; x = y0; // 1 x = z0; x = w0; // 2 y = z0; // 3 y = w0; // 4 w = z0; // 5 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (17,13): warning CS8619: Nullability of reference types in value of type 'B<object, string?>' doesn't match target type 'B<object?, string>'. // x = y0; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y0").WithArguments("B<object, string?>", "B<object?, string>").WithLocation(17, 13), // (19,13): warning CS8619: Nullability of reference types in value of type 'B<object, string>' doesn't match target type 'B<object?, string>'. // x = w0; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w0").WithArguments("B<object, string>", "B<object?, string>").WithLocation(19, 13), // (20,13): warning CS8619: Nullability of reference types in value of type 'B<object?, string>' doesn't match target type 'B<object, string?>'. // y = z0; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "z0").WithArguments("B<object?, string>", "B<object, string?>").WithLocation(20, 13), // (21,13): warning CS8619: Nullability of reference types in value of type 'B<object, string>' doesn't match target type 'B<object, string?>'. // y = w0; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w0").WithArguments("B<object, string>", "B<object, string?>").WithLocation(21, 13), // (22,13): warning CS8619: Nullability of reference types in value of type 'B<object?, string>' doesn't match target type 'B<object, string>'. // w = z0; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "z0").WithArguments("B<object?, string>", "B<object, string>").WithLocation(22, 13) ); } [Fact] public void TypeInference_09() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>(I<T> x, I<T> y) { throw new System.Exception(); } static void G1(I<string> x1, I<string?> y1) { F(x1, x1)/*T:string!*/.ToString(); F(x1, y1)/*T:string!*/.ToString(); F(y1, x1)/*T:string!*/.ToString(); F(y1, y1)/*T:string?*/.ToString(); } static T F<T>(IIn<T> x, IIn<T> y) { throw new System.Exception(); } static void G2(IIn<string> x2, IIn<string?> y2) { F(x2, x2)/*T:string!*/.ToString(); F(x2, y2)/*T:string!*/.ToString(); F(y2, x2)/*T:string!*/.ToString(); F(y2, y2)/*T:string?*/.ToString(); } static T F<T>(IOut<T> x, IOut<T> y) { throw new System.Exception(); } static void G3(IOut<string> x3, IOut<string?> y3) { F(x3, x3)/*T:string!*/.ToString(); F(x3, y3)/*T:string?*/.ToString(); F(y3, x3)/*T:string?*/.ToString(); F(y3, y3)/*T:string?*/.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyTypes(); comp.VerifyDiagnostics( // (13,15): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'y' in 'string C.F<string>(I<string> x, I<string> y)'. // F(x1, y1)/*T:string!*/.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<string?>", "I<string>", "y", "string C.F<string>(I<string> x, I<string> y)").WithLocation(13, 15), // (14,11): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'x' in 'string C.F<string>(I<string> x, I<string> y)'. // F(y1, x1)/*T:string!*/.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<string?>", "I<string>", "x", "string C.F<string>(I<string> x, I<string> y)").WithLocation(14, 11), // (15,9): warning CS8602: Dereference of a possibly null reference. // F(y1, y1)/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y1, y1)").WithLocation(15, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // F(y2, y2)/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y2, y2)").WithLocation(26, 9), // (35,9): warning CS8602: Dereference of a possibly null reference. // F(x3, y3)/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x3, y3)").WithLocation(35, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // F(y3, x3)/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y3, x3)").WithLocation(36, 9), // (37,9): warning CS8602: Dereference of a possibly null reference. // F(y3, y3)/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y3, y3)").WithLocation(37, 9)); } [Fact] public void TypeInference_10() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>(I<T> x, I<T?> y) where T : class { throw new System.Exception(); } static void G1(I<string> x1, I<string?> y1) { F(x1, x1).ToString(); // 1 F(x1, y1).ToString(); F(y1, x1).ToString(); // 2 and 3 F(y1, y1).ToString(); // 4 } static T F<T>(IIn<T> x, IIn<T?> y) where T : class { throw new System.Exception(); } static void G2(IIn<string> x2, IIn<string?> y2) { F(x2, x2).ToString(); // 5 F(x2, y2).ToString(); F(y2, x2).ToString(); // 6 F(y2, y2).ToString(); } static T F<T>(IOut<T> x, IOut<T?> y) where T : class { throw new System.Exception(); } static void G3(IOut<string> x3, IOut<string?> y3) { F(x3, x3).ToString(); F(x3, y3).ToString(); F(y3, x3).ToString(); // 7 F(y3, y3).ToString(); // 8 } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,15): warning CS8620: Nullability of reference types in argument of type 'I<string>' doesn't match target type 'I<string?>' for parameter 'y' in 'string C.F<string>(I<string> x, I<string?> y)'. // F(x1, x1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1").WithArguments("I<string>", "I<string?>", "y", "string C.F<string>(I<string> x, I<string?> y)").WithLocation(12, 15), // (14,11): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'x' in 'string C.F<string>(I<string> x, I<string?> y)'. // F(y1, x1).ToString(); // 2 and 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<string?>", "I<string>", "x", "string C.F<string>(I<string> x, I<string?> y)").WithLocation(14, 11), // (14,15): warning CS8620: Nullability of reference types in argument of type 'I<string>' doesn't match target type 'I<string?>' for parameter 'y' in 'string C.F<string>(I<string> x, I<string?> y)'. // F(y1, x1).ToString(); // 2 and 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1").WithArguments("I<string>", "I<string?>", "y", "string C.F<string>(I<string> x, I<string?> y)").WithLocation(14, 15), // (15,11): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'x' in 'string C.F<string>(I<string> x, I<string?> y)'. // F(y1, y1).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<string?>", "I<string>", "x", "string C.F<string>(I<string> x, I<string?> y)").WithLocation(15, 11), // (23,15): warning CS8620: Nullability of reference types in argument of type 'IIn<string>' doesn't match target type 'IIn<string?>' for parameter 'y' in 'string C.F<string>(IIn<string> x, IIn<string?> y)'. // F(x2, x2).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x2").WithArguments("IIn<string>", "IIn<string?>", "y", "string C.F<string>(IIn<string> x, IIn<string?> y)").WithLocation(23, 15), // (25,15): warning CS8620: Nullability of reference types in argument of type 'IIn<string>' doesn't match target type 'IIn<string?>' for parameter 'y' in 'string C.F<string>(IIn<string> x, IIn<string?> y)'. // F(y2, x2).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x2").WithArguments("IIn<string>", "IIn<string?>", "y", "string C.F<string>(IIn<string> x, IIn<string?> y)").WithLocation(25, 15), // (36,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>(IOut<T>, IOut<T?>)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // F(y3, x3).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>(IOut<T>, IOut<T?>)", "T", "string?").WithLocation(36, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // F(y3, x3).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y3, x3)").WithLocation(36, 9), // (37,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>(IOut<T>, IOut<T?>)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // F(y3, y3).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>(IOut<T>, IOut<T?>)", "T", "string?").WithLocation(37, 9), // (37,9): warning CS8602: Dereference of a possibly null reference. // F(y3, y3).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y3, y3)").WithLocation(37, 9)); } [Fact] public void TypeInference_11() { var source0 = @"public class A<T> { public T F; } public class UnknownNull { public A<object> A1; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source1 = @"#pragma warning disable 8618 public class MaybeNull { public A<object?> A2; } public class NotNull { public A<object> A3; }"; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { ref0 }); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static void F1(UnknownNull x1, UnknownNull y1) { F(x1.A1, y1.A1)/*T:A<object>!*/.F.ToString(); } static void F2(UnknownNull x2, MaybeNull y2) { F(x2.A1, y2.A2)/*T:A<object?>!*/.F.ToString(); } static void F3(MaybeNull x3, UnknownNull y3) { F(x3.A2, y3.A1)/*T:A<object?>!*/.F.ToString(); } static void F4(MaybeNull x4, MaybeNull y4) { F(x4.A2, y4.A2)/*T:A<object?>!*/.F.ToString(); } static void F5(UnknownNull x5, NotNull y5) { F(x5.A1, y5.A3)/*T:A<object!>!*/.F.ToString(); } static void F6(NotNull x6, UnknownNull y6) { F(x6.A3, y6.A1)/*T:A<object!>!*/.F.ToString(); } static void F7(MaybeNull x7, NotNull y7) { F(x7.A2, y7.A3)/*T:A<object!>!*/.F.ToString(); } static void F8(NotNull x8, MaybeNull y8) { F(x8.A3, y8.A2)/*T:A<object!>!*/.F.ToString(); } static void F9(NotNull x9, NotNull y9) { F(x9.A3, y9.A3)/*T:A<object!>!*/.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0, ref1 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(x2.A1, y2.A2)/*T:A<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x2.A1, y2.A2)/*T:A<object?>!*/.F").WithLocation(10, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F(x3.A2, y3.A1)/*T:A<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x3.A2, y3.A1)/*T:A<object?>!*/.F").WithLocation(14, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F(x4.A2, y4.A2)/*T:A<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x4.A2, y4.A2)/*T:A<object?>!*/.F").WithLocation(18, 9), // (30,11): warning CS8620: Nullability of reference types in argument of type 'A<object?>' doesn't match target type 'A<object>' for parameter 'x' in 'A<object> C.F<A<object>>(A<object> x, A<object> y)'. // F(x7.A2, y7.A3)/*T:A<object!>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x7.A2").WithArguments("A<object?>", "A<object>", "x", "A<object> C.F<A<object>>(A<object> x, A<object> y)").WithLocation(30, 11), // (34,18): warning CS8620: Nullability of reference types in argument of type 'A<object?>' doesn't match target type 'A<object>' for parameter 'y' in 'A<object> C.F<A<object>>(A<object> x, A<object> y)'. // F(x8.A3, y8.A2)/*T:A<object!>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y8.A2").WithArguments("A<object?>", "A<object>", "y", "A<object> C.F<A<object>>(A<object> x, A<object> y)").WithLocation(34, 18) ); } [Fact] public void TypeInference_12() { var source = @"class C<T> { internal T F; } class C { static C<T> Create<T>(T t) { return new C<T>(); } static void F(object? x) { if (x == null) { Create(x).F = null; var y = Create(x); y.F = null; } else { Create(x).F = null; // warn var y = Create(x); y.F = null; // warn } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,16): warning CS8618: Non-nullable field 'F' is uninitialized. Consider declaring the field as nullable. // internal T F; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "F").WithArguments("field", "F").WithLocation(3, 16), // (21,27): warning CS8625: Cannot convert null literal to non-nullable reference type. // Create(x).F = null; // warn Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 27), // (23,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // y.F = null; // warn Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(23, 19)); } [Fact] [WorkItem(49472, "https://github.com/dotnet/roslyn/issues/49472")] public void TypeInference_13() { var source = @"#nullable enable using System; using System.Collections.Generic; static class Program { static void Main() { var d1 = new Dictionary<string, string?>(); var d2 = d1.ToDictionary(kv => kv.Key, kv => kv.Value); d2[""""].ToString(); } static Dictionary<TKey, TValue> ToDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> e, Func<TSource, TKey> k, Func<TSource, TValue> v) { return new Dictionary<TKey, TValue>(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // d2[""].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"d2[""""]").WithLocation(10, 9)); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var localDeclaration = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1); var symbol = model.GetDeclaredSymbol(localDeclaration); Assert.Equal("System.Collections.Generic.Dictionary<System.String!, System.String?>? d2", symbol.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void TypeInference_ArgumentOrder() { var source = @"interface I<T> { T P { get; } } class C { static T F<T, U>(I<T> x, I<U> y) => x.P; static void M(I<object?> x, I<string> y) { F(y: y, x: x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(y: y, x: x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y: y, x: x)").WithLocation(10, 9)); } [Fact] public void TypeInference_Local() { var source = @"class C { static T F<T>(T t) => t; static void G() { object x = new object(); object? y = x; F(x).ToString(); F(y).ToString(); y = null; F(y).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // F(y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y)").WithLocation(11, 9)); } [Fact] public void TypeInference_Call() { var source = @"class C { static T F<T>(T t) => t; static object F1() => new object(); static object? F2() => null; static void G() { F(F1()).ToString(); F(F2()).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F(F2()).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(F2())").WithLocation(9, 9)); } [Fact] public void TypeInference_Property() { var source = @"class C { static T F<T>(T t) => t; static object P => new object(); static object? Q => null; static void G() { F(P).ToString(); F(Q).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F(Q).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(Q)").WithLocation(9, 9)); } [Fact] public void TypeInference_FieldAccess() { var source = @"class C { static T F<T>(T t) => t; static object F1 = new object(); static object? F2 = null; static void G() { F(F1).ToString(); F(F2).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F(F2).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(F2)").WithLocation(9, 9)); } [Fact] public void TypeInference_Literal() { var source = @"class C { static T F<T>(T t) => t; static void G() { F(0).ToString(); F('A').ToString(); F(""B"").ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_Default() { var source = @"class C { static T F<T>(T t) => t; static void G() { F(default(object)).ToString(); F(default(int)).ToString(); F(default(string)).ToString(); F(default).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'C.F<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(default).ToString(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("C.F<T>(T)").WithLocation(9, 9), // (6,9): warning CS8602: Dereference of a possibly null reference. // F(default(object)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(default(object))").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F(default(string)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(default(string))").WithLocation(8, 9)); } [Fact] public void TypeInference_Tuple_01() { var source = @"class C { static (T, U) F<T, U>((T, U) t) => t; static void G(string x, string? y) { var t = (x, y); F(t).Item1.ToString(); F(t).Item2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F(t).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(t).Item2").WithLocation(8, 9)); } [Fact] public void TypeInference_Tuple_02() { var source = @"class C { static T F<T>(T t) => t; static void G(string x, string? y) { var t = (x, y); F(t).Item1.ToString(); F(t).Item2.ToString(); F(t).x.ToString(); F(t).y.ToString(); var u = (a: x, b: y); F(u).Item1.ToString(); F(u).Item2.ToString(); F(u).a.ToString(); F(u).b.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F(t).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(t).Item2").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F(t).y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(t).y").WithLocation(10, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F(u).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(u).Item2").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F(u).b.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(u).b").WithLocation(15, 9)); } [Fact] public void TypeInference_Tuple_03() { var source = @"class C { static void F(object? x, object? y) { if (x == null) return; var t = (x, y); t.x.ToString(); t.y.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.y").WithLocation(8, 9)); } [Fact] public void TypeInference_ObjectCreation() { var source = @"class C { static T F<T>(T t) => t; static void G() { F(new C { }).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_DelegateCreation() { var source = @"delegate void D(); class C { static T F<T>(T t) => t; static void G() { F(new D(G)).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_BinaryOperator() { var source = @"class C { static T F<T>(T t) => t; static void G(string x, string? y) { F(x + x).ToString(); F(x + y).ToString(); F(y + x).ToString(); F(y + y).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_NullCoalescingOperator() { var source = @"class C { static T F<T>(T t) => t; static void G(int i, object x, object? y) { switch (i) { case 1: F(x ?? x).ToString(); break; case 2: F(x ?? y).ToString(); break; case 3: F(y ?? x).ToString(); break; case 4: F(y ?? y).ToString(); break; } } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // F(x ?? x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x ?? x)").WithLocation(9, 17), // (12,17): warning CS8602: Dereference of a possibly null reference. // F(x ?? y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x ?? y)").WithLocation(12, 17), // (18,17): warning CS8602: Dereference of a possibly null reference. // F(y ?? y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y ?? y)").WithLocation(18, 17)); } [Fact] public void Members_Fields() { var source = @"#pragma warning disable 0649 class C { internal string? F; } class Program { static void F(C a) { G(a.F); if (a.F != null) G(a.F); C b = new C(); G(b.F); if (b.F != null) G(b.F); } static void G(string s) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.G(string s)'. // G(a.F); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a.F").WithArguments("s", "void Program.G(string s)").WithLocation(10, 11), // (13,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.G(string s)'. // G(b.F); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b.F").WithArguments("s", "void Program.G(string s)").WithLocation(13, 11)); } [Fact] public void Members_Fields_UnconstrainedType() { var source = @" class C<T> { internal T field = default; static void F(C<T> a, bool c) { if (c) a.field.ToString(); // 1 else if (a.field != null) a.field.ToString(); C<T> b = new C<T>(); if (c) b.field.ToString(); // 2 else if (b.field != null) b.field.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,24): warning CS8601: Possible null reference assignment. // internal T field = default; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(4, 24), // (8,16): warning CS8602: Dereference of a possibly null reference. // if (c) a.field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.field").WithLocation(8, 16), // (11,16): warning CS8602: Dereference of a possibly null reference. // if (c) b.field.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.field").WithLocation(11, 16)); } [Fact] public void Members_AutoProperties() { var source = @"class C { internal string? P { get; set; } } class Program { static void F(C a) { G(a.P); if (a.P != null) G(a.P); C b = new C(); G(b.P); if (b.P != null) G(b.P); } static void G(string s) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.G(string s)'. // G(a.P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a.P").WithArguments("s", "void Program.G(string s)").WithLocation(9, 11), // (12,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.G(string s)'. // G(b.P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b.P").WithArguments("s", "void Program.G(string s)").WithLocation(12, 11)); } [Fact] public void Members_Properties() { var source = @"class C { internal string? P { get { throw new System.Exception(); } set { } } } class Program { static void F(C a) { G(a.P); if (a.P != null) G(a.P); C b = new C(); G(b.P); if (b.P != null) G(b.P); } static void G(string s) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.G(string s)'. // G(a.P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a.P").WithArguments("s", "void Program.G(string s)").WithLocation(9, 11), // (12,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.G(string s)'. // G(b.P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b.P").WithArguments("s", "void Program.G(string s)").WithLocation(12, 11)); } [Fact] public void Members_AutoPropertyFromConstructor() { var source = @"class A { protected static void F(string s) { } protected string? P { get; set; } protected A() { F(P); if (P != null) F(P); } } class B : A { B() { F(this.P); if (this.P != null) F(this.P); F(base.P); if (base.P != null) F(base.P); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,11): warning CS8604: Possible null reference argument for parameter 's' in 'void A.F(string s)'. // F(this.P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "this.P").WithArguments("s", "void A.F(string s)").WithLocation(17, 11), // (19,11): warning CS8604: Possible null reference argument for parameter 's' in 'void A.F(string s)'. // F(base.P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "base.P").WithArguments("s", "void A.F(string s)").WithLocation(19, 11), // (9,11): warning CS8604: Possible null reference argument for parameter 's' in 'void A.F(string s)'. // F(P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "P").WithArguments("s", "void A.F(string s)").WithLocation(9, 11)); } [Fact] public void ModifyMembers_01() { var source = @"#pragma warning disable 0649 class C { object? F; static void M(C c) { if (c.F == null) return; c = new C(); c.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F").WithLocation(9, 9)); } [Fact] public void ModifyMembers_02() { var source = @"#pragma warning disable 0649 class A { internal C? C; } class B { internal A? A; } class C { internal B? B; } class Program { static void F() { object o; C? c = new C(); c.B = new B(); c.B.A = new A(); o = c.B.A; // 1 c.B.A = null; o = c.B.A; // 2 c.B = new B(); o = c.B.A; // 3 c.B = null; o = c.B.A; // 4 c = new C(); o = c.B.A; // 5 c = null; o = c.B.A; // 6 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (24,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.A; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.A").WithLocation(24, 13), // (26,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.A; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.A").WithLocation(26, 13), // (28,13): warning CS8602: Dereference of a possibly null reference. // o = c.B.A; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.B").WithLocation(28, 13), // (28,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.A; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.A").WithLocation(28, 13), // (30,13): warning CS8602: Dereference of a possibly null reference. // o = c.B.A; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.B").WithLocation(30, 13), // (30,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.A; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.A").WithLocation(30, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // o = c.B.A; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(32, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // o = c.B.A; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.B").WithLocation(32, 13), // (32,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.A; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.A").WithLocation(32, 13)); } [Fact] public void ModifyMembers_03() { var source = @"#pragma warning disable 0649 struct S { internal object? F; } class C { internal C? A; internal S B; } class Program { static void M() { object o; C c = new C(); o = c.A.A; // 1 o = c.B.F; // 1 c.A = new C(); c.B = new S(); o = c.A.A; // 2 o = c.B.F; // 2 c.A.A = new C(); c.B.F = new C(); o = c.A.A; // 3 o = c.B.F; // 3 c.A = new C(); c.B = new S(); o = c.A.A; // 4 o = c.B.F; // 4 c = new C(); o = c.A.A; // 5 o = c.B.F; // 5 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,13): warning CS8602: Dereference of a possibly null reference. // o = c.A.A; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.A").WithLocation(17, 13), // (17,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(17, 13), // (18,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.F; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.F").WithLocation(18, 13), // (21,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(21, 13), // (22,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.F; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.F").WithLocation(22, 13), // (29,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(29, 13), // (30,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.F; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.F").WithLocation(30, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // o = c.A.A; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.A").WithLocation(32, 13), // (32,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(32, 13), // (33,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.F; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.F").WithLocation(33, 13)); } [Fact] public void ModifyMembers_Properties() { var source = @"#pragma warning disable 0649 struct S { internal object? P { get; set; } } class C { internal C? A { get; set; } internal S B; } class Program { static void M() { object o; C c = new C(); o = c.A.A; // 1 o = c.B.P; // 1 c.A = new C(); c.B = new S(); o = c.A.A; // 2 o = c.B.P; // 2 c.A.A = new C(); c.B.P = new C(); o = c.A.A; // 3 o = c.B.P; // 3 c.A = new C(); c.B = new S(); o = c.A.A; // 4 o = c.B.P; // 4 c = new C(); o = c.A.A; // 5 o = c.B.P; // 5 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,13): warning CS8602: Dereference of a possibly null reference. // o = c.A.A; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.A").WithLocation(17, 13), // (17,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(17, 13), // (18,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.P; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.P").WithLocation(18, 13), // (21,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(21, 13), // (22,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.P; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.P").WithLocation(22, 13), // (29,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(29, 13), // (30,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.P; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.P").WithLocation(30, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // o = c.A.A; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.A").WithLocation(32, 13), // (32,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(32, 13), // (33,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.P; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.P").WithLocation(33, 13)); } [Fact] public void ModifyMembers_Struct() { var source = @"#pragma warning disable 0649 struct A { internal object? F; } struct B { internal A A; internal object? G; } class Program { static void F() { object o; B b = new B(); b.G = new object(); b.A.F = new object(); o = b.G; // 1 o = b.A.F; // 1 b.A = default(A); o = b.G; // 2 o = b.A.F; // 2 b = default(B); o = b.G; // 3 o = b.A.F; // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = b.A.F; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b.A.F").WithLocation(23, 13), // (25,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = b.G; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b.G").WithLocation(25, 13), // (26,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = b.A.F; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b.A.F").WithLocation(26, 13)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void ModifyMembers_StructPropertyExplicitAccessors() { var source = @"#pragma warning disable 0649 struct S { private object? _p; internal object? P { get { return _p; } set { _p = value; } } } class C { S F; void M() { object o; o = F.P; // 1 F.P = new object(); o = F.P; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = F.P; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F.P").WithLocation(13, 13)); } [Fact] public void ModifyMembers_StructProperty() { var source = @"#pragma warning disable 0649 public struct S { public object? P { get; set; } } class C { S F; void M() { object o; o = F.P; // 1 F.P = new object(); o = F.P; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = F.P; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F.P").WithLocation(12, 13)); } [Fact] public void ModifyMembers_StructPropertyFromMetadata() { var source0 = @"public struct S { public object? P { get; set; } }"; var comp0 = CreateCompilation(source0); var ref0 = comp0.EmitToImageReference(); var source = @"#pragma warning disable 0649 class C { S F; void M() { object o; o = F.P; // 1 F.P = new object(); o = F.P; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = F.P; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F.P").WithLocation(8, 13)); } [Fact] public void ModifyMembers_ClassPropertyNoBackingField() { var source = @"#pragma warning disable 0649 class C { object? P { get { return null; } set { } } void M() { object o; o = P; // 1 P = new object(); o = P; // 2 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = P; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P").WithLocation(8, 13)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void ModifyMembers_StructPropertyNoBackingField_01() { var source = @"#pragma warning disable 0649 struct S { internal object? P { get { return null; } set { } } } class C { S F; void M() { object o; o = F.P; // 1 F.P = new object(); o = F.P; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = F.P; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F.P").WithLocation(12, 13)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void ModifyMembers_StructPropertyNoBackingField_02() { var source = @"struct S<T> { internal T P => throw null!; } class Program { static S<T> Create<T>(T t) { return new S<T>(); } static void F<T>() where T : class, new() { T? x = null; var sx = Create(x); sx.P.ToString(); T? y = new T(); var sy = Create(y); sy.P.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Possible dereference of a null reference. // sx.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "sx.P").WithLocation(15, 9)); } // Calling a method should reset the state for members. [Fact] [WorkItem(29975, "https://github.com/dotnet/roslyn/issues/29975")] public void Members_CallMethod() { var source = @"#pragma warning disable 0649 class A { internal object? P { get; set; } } class B { internal A? Q { get; set; } } class Program { static void M() { object o; B b = new B() { Q = new A() { P = new object() } }; o = b.Q.P; // 1 b.Q.P.ToString(); o = b.Q.P; // 2 b.Q.ToString(); o = b.Q.P; // 3 b = new B() { Q = new A() { P = new object() } }; o = b.Q.P; // 4 b.ToString(); o = b.Q.P; // 5 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29975: Should report warnings. comp.VerifyDiagnostics(/*...*/); } [Fact] public void Members_ObjectInitializer() { var source = @"#pragma warning disable 0649 class A { internal object? F1; internal object? F2; } class B { internal A? G; } class Program { static void F() { (new B() { G = new A() { F1 = new object() } }).G.F1.ToString(); B b; b = new B() { G = new A() { F1 = new object() } }; b.G.F1.ToString(); // 1 b.G.F2.ToString(); // 1 b = new B() { G = new A() { F2 = new object() } }; b.G.F1.ToString(); // 2 b.G.F2.ToString(); // 2 b = new B() { G = new A() }; b.G.F1.ToString(); // 3 b.G.F2.ToString(); // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // b.G.F2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F2").WithLocation(19, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // b.G.F1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F1").WithLocation(21, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // b.G.F1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F1").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // b.G.F2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F2").WithLocation(25, 9)); } [Fact] public void Members_ObjectInitializer_Struct() { var source = @"#pragma warning disable 0649 struct A { internal object? F1; internal object? F2; } struct B { internal A G; } class Program { static void F() { (new B() { G = new A() { F1 = new object() } }).G.F1.ToString(); B b; b = new B() { G = new A() { F1 = new object() } }; b.G.F1.ToString(); // 1 b.G.F2.ToString(); // 1 b = new B() { G = new A() { F2 = new object() } }; b.G.F1.ToString(); // 2 b.G.F2.ToString(); // 2 b = new B() { G = new A() }; b.G.F1.ToString(); // 3 b.G.F2.ToString(); // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // b.G.F2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F2").WithLocation(19, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // b.G.F1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F1").WithLocation(21, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // b.G.F1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F1").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // b.G.F2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F2").WithLocation(25, 9)); } [Fact] public void Members_ObjectInitializer_Properties() { var source = @"#pragma warning disable 0649 class A { internal object? P1 { get; set; } internal object? P2 { get; set; } } class B { internal A? Q { get; set; } } class Program { static void F() { (new B() { Q = new A() { P1 = new object() } }).Q.P1.ToString(); B b; b = new B() { Q = new A() { P1 = new object() } }; b.Q.P1.ToString(); // 1 b.Q.P2.ToString(); // 1 b = new B() { Q = new A() { P2 = new object() } }; b.Q.P1.ToString(); // 2 b.Q.P2.ToString(); // 2 b = new B() { Q = new A() }; b.Q.P1.ToString(); // 3 b.Q.P2.ToString(); // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // b.Q.P2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Q.P2").WithLocation(19, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // b.Q.P1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Q.P1").WithLocation(21, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // b.Q.P1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Q.P1").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // b.Q.P2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Q.P2").WithLocation(25, 9)); } [Fact] public void Members_ObjectInitializer_Events() { var source = @"delegate void D(); class C { event D? E; static void F() { C c; c = new C() { }; c.E.Invoke(); // warning c = new C() { E = F }; c.E.Invoke(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c.E.Invoke(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.E").WithLocation(9, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Members_ObjectInitializer_DerivedType() { var source = @"#pragma warning disable 0649 class A { internal A? F; } class B : A { internal object? G; } class Program { static void Main() { A a; a = new B() { F = new A(), G = new object() }; a.F.ToString(); a = new A(); a.F.ToString(); // 1 a = new B() { F = new B() { F = new A() } }; a.F.ToString(); a.F.F.ToString(); a = new B() { G = new object() }; a.F.ToString(); // 2 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // a.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.F").WithLocation(18, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // a.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.F").WithLocation(23, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Members_Assignment() { var source = @"#pragma warning disable 0649 class A { internal A? F; } class B : A { internal object? G; } class Program { static void Main() { B b = new B(); A a; a = b; a.F.ToString(); // 1 b.F = new A(); a = b; a.F.ToString(); b = new B() { F = new B() { F = new A() } }; a = b; a.F.ToString(); a.F.F.ToString(); b = new B() { G = new object() }; a = b; a.F.ToString(); // 2 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,9): warning CS8602: Dereference of a possibly null reference. // a.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.F").WithLocation(17, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // a.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.F").WithLocation(27, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_01() { var source = @"class A { internal object? FA; } class B : A { internal object FB = new object(); } class Program { static void F() { A a = new B() { FA = 1 }; a.FA.ToString(); a = new B() { FA = 2, FB = null }; // 1 ((B)a).FA.ToString(); // 2 ((B)a).FB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // a = new B() { FA = 2, FB = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 36), // (16,9): warning CS8602: Dereference of a possibly null reference. // ((B)a).FA.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((B)a).FA").WithLocation(16, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_02() { var source = @"class A { internal object? FA; } class B : A { internal object FB = new object(); } class Program { static void F() { B b = new B() { FA = 1 }; A a = b; a.FA.ToString(); a = new B() { FB = null }; // 1 b = (B)a; b.FB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // a = new B() { FB = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 28)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_03() { var source = @"interface IA { object? PA { get; set; } } interface IB : IA { object PB { get; set; } } class Program { static void F(IB b) { b.PA = 1; b.PB = null; // 1 ((IA)b).PA.ToString(); ((IB)(object)b).PB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // b.PB = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 16)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_04() { var source = @"interface IA { object? PA { get; set; } } interface IB : IA { object PB { get; set; } } class Program { static void F(IB b) { b.PA = 1; b.PB = null; // 1 object o = b; b = o; // 2 b.PA.ToString(); // 3 b = (IB)o; b.PB.ToString(); ((IB)o).PA.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // b.PB = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 16), // (16,13): error CS0266: Cannot implicitly convert type 'object' to 'IB'. An explicit conversion exists (are you missing a cast?) // b = o; // 2 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "o").WithArguments("object", "IB").WithLocation(16, 13), // (17,9): warning CS8602: Dereference of a possibly null reference. // b.PA.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.PA").WithLocation(17, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // ((IB)o).PA.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((IB)o).PA").WithLocation(20, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_05() { var source = @"#pragma warning disable 0649 class C { internal object? F; } class Program { static void F(object x, object? y) { if (((C)x).F != null) ((C)x).F.ToString(); // 1 if (((C?)y)?.F != null) ((C)y).F.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // ((C)x).F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((C)x).F").WithLocation(11, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // ((C)y).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((C)y).F").WithLocation(13, 13) ); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_06() { var source = @"class C { internal object F() => null!; } class Program { static void F(object? x) { if (((C?)x)?.F() != null) ((C)x).F().ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_07() { var source = @"interface I { object? P { get; } } class Program { static void F(object x, object? y) { if (((I)x).P != null) ((I)x).P.ToString(); // 1 if (((I?)y)?.P != null) ((I)y).P.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // ((I)x).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((I)x).P").WithLocation(10, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // ((I)y).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((I)y).P").WithLocation(12, 13) ); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_08() { var source = @"interface I { object F(); } class Program { static void F(object? x) { if (((I?)x)?.F() != null) ((I)x).F().ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_09() { var source = @"class A { internal bool? F; } class B : A { } class Program { static void M(bool b1, bool b2) { A a; if (b1 ? b2 && (a = new B() { F = true }).F.Value : false) { } if (true ? b2 && (a = new B() { F = false }).F.Value : false) { } if (false ? false : b2 && (a = new B() { F = b1 }).F.Value) { } if (false ? b2 && (a = new B() { F = null }).F.Value : true) { } _ = (a = new B() { F = null }).F.Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (25,13): warning CS8629: Nullable value type may be null. // _ = (a = new B() { F = null }).F.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(a = new B() { F = null }).F").WithLocation(25, 13)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_10() { var source = @"class A { internal object? FA; } class B : A { internal object FB = new object(); } class Program { static void F() { A a = new B() { FB = null }; // 1 a = new A() { FA = 1 }; a.FA.ToString(); ((B)a).FB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,30): warning CS8625: Cannot convert null literal to non-nullable reference type. // A a = new B() { FB = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 30)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Conversions_NullableConversions_01() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F4<T>() where T : struct, I { T? t = new T() { P = 4, Q = null }; // 1 t.Value.P.ToString(); t.Value.Q.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // T? t = new T() { P = 4, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 37), // (12,9): warning CS8602: Dereference of a possibly null reference. // t.Value.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Value.Q").WithLocation(12, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_NullableConversions_02() { var source = @"class C { internal object? F; internal object G = null!; } class Program { static void F() { (C, C)? t = (new C() { F = 1 }, new C() { G = null }); // 1 (((C, C))t).Item1.F.ToString(); (((C, C))t).Item2.G.ToString(); // 2 (C, C)? u = (new C() { F = 2 }, new C() { G = null }); // 3 ((C)u.Value.Item1).F.ToString(); ((C)u.Value.Item2).G.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,55): warning CS8625: Cannot convert null literal to non-nullable reference type. // (C, C)? t = (new C() { F = 1 }, new C() { G = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 55), // (12,9): warning CS8602: Dereference of a possibly null reference. // (((C, C))t).Item2.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(((C, C))t).Item2.G").WithLocation(12, 9), // (13,55): warning CS8625: Cannot convert null literal to non-nullable reference type. // (C, C)? u = (new C() { F = 2 }, new C() { G = null }); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 55), // (15,9): warning CS8602: Dereference of a possibly null reference. // ((C)u.Value.Item2).G.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((C)u.Value.Item2).G").WithLocation(15, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Conversions_NullableConversions_03() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { (S, S)? t = (new S() { F = 1 }, new S() { G = null }); // 1 (((S, S))t).Item1.F.ToString(); (((S, S))t).Item2.G.ToString(); // 2 (S, S)? u = (new S() { F = 2 }, new S() { G = null }); // 3 ((S)u.Value.Item1).F.ToString(); ((S)u.Value.Item2).G.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,55): warning CS8625: Cannot convert null literal to non-nullable reference type. // (S, S)? t = (new S() { F = 1 }, new S() { G = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 55), // (12,9): warning CS8602: Dereference of a possibly null reference. // (((S, S))t).Item2.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(((S, S))t).Item2.G").WithLocation(12, 9), // (13,55): warning CS8625: Cannot convert null literal to non-nullable reference type. // (S, S)? u = (new S() { F = 2 }, new S() { G = null }); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 55), // (15,9): warning CS8602: Dereference of a possibly null reference. // ((S)u.Value.Item2).G.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((S)u.Value.Item2).G").WithLocation(15, 9)); } [Fact] public void Conversions_NullableConversions_04() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F1(string x1) { S y1 = new S() { F = 1, G = null }; // 1 (object, S)? t1 = (x1, y1); t1.Value.Item2.F.ToString(); t1.Value.Item2.G.ToString(); // 2 } static void F2(string x2) { S y2 = new S() { F = 1, G = null }; // 3 var t2 = ((object, S)?)(x2, y2); t2.Value.Item2.F.ToString(); t2.Value.Item2.G.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S y1 = new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 37), // (13,9): warning CS8602: Dereference of a possibly null reference. // t1.Value.Item2.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1.Value.Item2.G").WithLocation(13, 9), // (17,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S y2 = new S() { F = 1, G = null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(17, 37), // (20,9): warning CS8602: Dereference of a possibly null reference. // t2.Value.Item2.G.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2.Value.Item2.G").WithLocation(20, 9)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void Conversions_NullableConversions_05() { var source = @"struct S { internal object? P { get; set; } internal object Q { get; set; } } class Program { static void Main() { S? s = new S() { P = 1, Q = null }; // 1 s.Value.P.ToString(); s.Value.Q.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S? s = new S() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 37), // (12,9): warning CS8602: Dereference of a possibly null reference. // s.Value.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.Value.Q").WithLocation(12, 9)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void Conversions_NullableConversions_06() { var source = @"struct S { private object? _p; private object _q; internal object? P { get { return _p; } set { _p = value; } } internal object Q { get { return _q; } set { _q = value; } } } class Program { static void Main() { S? s = new S() { P = 1, Q = null }; // 1 s.Value.P.ToString(); s.Value.Q.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S? s = new S() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 37), // (14,9): warning CS8602: Dereference of a possibly null reference. // s.Value.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.Value.Q").WithLocation(14, 9)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void Conversions_NullableConversions_07() { var source = @"struct S { internal object? P { get { return 1; } set { } } internal object Q { get { return 2; } set { } } } class Program { static void Main() { S? s = new S() { P = 1, Q = null }; // 1 s.Value.P.ToString(); s.Value.Q.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S? s = new S() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 37), // (12,9): warning CS8602: Dereference of a possibly null reference. // s.Value.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.Value.Q").WithLocation(12, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_TupleConversions_01() { var source = @"class A { internal object? FA; } class B : A { internal object FB = new object(); } class Program { static void F() { (B, object) t = (new B() { FA = 1 }, new B() { FB = null }); // 1 t.Item1.FA.ToString(); ((A)t.Item1).FA.ToString(); ((B)t.Item2).FB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,61): warning CS8625: Cannot convert null literal to non-nullable reference type. // (B, object) t = (new B() { FA = 1 }, new B() { FB = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 61)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_TupleConversions_02() { var source = @"class A { internal object? FA; } class B : A { internal object FB = new object(); } class Program { static void F() { (B, object) t = (new B() { FA = 1 }, new B() { FB = null }); // 1 (((A, A))t).Item1.FA.ToString(); // 2 (((B, B))t).Item2.FB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,61): warning CS8625: Cannot convert null literal to non-nullable reference type. // (B, object) t = (new B() { FA = 1 }, new B() { FB = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 61), // (14,9): warning CS8602: Dereference of a possibly null reference. // (((A, A))t).Item1.FA.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(((A, A))t).Item1.FA").WithLocation(14, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_TupleConversions_03() { var source = @"class A { internal object? FA; } class B : A { internal object FB = new object(); } class Program { static void F() { B b = new B() { FA = 1, FB = null }; // 1 (B, (A, A)) t; t = (b, (b, b)); t.Item1.FB.ToString(); // 2 t.Item2.Item1.FA.ToString(); t = ((B, (A, A)))(b, (b, b)); t.Item1.FB.ToString(); t.Item2.Item1.FA.ToString(); // 3 (A, (B, B)) u; u = t; // 4 u.Item1.FA.ToString(); // 5 u.Item2.Item2.FB.ToString(); u = ((A, (B, B)))t; u.Item1.FA.ToString(); // 6 u.Item2.Item2.FB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // B b = new B() { FA = 1, FB = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 38), // (16,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.FB.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1.FB").WithLocation(16, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.Item1.FA.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2.Item1.FA").WithLocation(20, 9), // (22,13): error CS0266: Cannot implicitly convert type '(B, (A, A))' to '(A, (B, B))'. An explicit conversion exists (are you missing a cast?) // u = t; // 4 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("(B, (A, A))", "(A, (B, B))").WithLocation(22, 13), // (23,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.FA.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1.FA").WithLocation(23, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.FA.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1.FA").WithLocation(26, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(34086, "https://github.com/dotnet/roslyn/issues/34086")] public void Conversions_TupleConversions_04() { var source = @"class C { internal object? F; } class Program { static void F() { (object, object)? t = (new C() { F = 1 }, new object()); (((C, object))t).Item1.F.ToString(); // 1 (object, object)? u = (new C() { F = 2 }, new object()); ((C)u.Value.Item1).F.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/34086: Track state across Nullable<T> conversions with nested conversions. comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // (((C, object))t).Item1.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(((C, object))t).Item1.F").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // ((C)u.Value.Item1).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((C)u.Value.Item1).F").WithLocation(12, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(34086, "https://github.com/dotnet/roslyn/issues/34086")] public void Conversions_TupleConversions_05() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { (S?, object?) t = (new S() { F = 1 }, new S() { G = null }); // 1 (((S, S))t).Item1.F.ToString(); (((S, S))t).Item2.G.ToString(); // 2 (S?, object?) u = (new S() { F = 2 }, new S() { G = null }); // 3 u.Item1.Value.F.ToString(); ((S?)u.Item2).Value.G.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/34086: Track state across Nullable<T> conversions with nested conversions. comp.VerifyDiagnostics( // (10,61): warning CS8625: Cannot convert null literal to non-nullable reference type. // (S?, object?) t = (new S() { F = 1 }, new S() { G = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 61), // (11,9): warning CS8602: Dereference of a possibly null reference. // (((S, S))t).Item1.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(((S, S))t).Item1.F").WithLocation(11, 9), // (11,10): warning CS8619: Nullability of reference types in value of type '(S?, object?)' doesn't match target type '(S, S)'. // (((S, S))t).Item1.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((S, S))t").WithArguments("(S?, object?)", "(S, S)").WithLocation(11, 10), // (12,10): warning CS8619: Nullability of reference types in value of type '(S?, object?)' doesn't match target type '(S, S)'. // (((S, S))t).Item2.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((S, S))t").WithArguments("(S?, object?)", "(S, S)").WithLocation(12, 10), // (13,61): warning CS8625: Cannot convert null literal to non-nullable reference type. // (S?, object?) u = (new S() { F = 2 }, new S() { G = null }); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 61)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Conversions_TupleConversions_06() { var source = @"class Program { static void F1((object?, object) t1) { var u1 = ((string, string))t1; // 1 u1.Item1.ToString(); u1.Item1.ToString(); } static void F2((object?, object) t2) { var u2 = ((string?, string?))t2; u2.Item1.ToString(); // 2 u2.Item2.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,18): warning CS8619: Nullability of reference types in value of type '(object?, object)' doesn't match target type '(string, string)'. // var u1 = ((string, string))t1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((string, string))t1").WithArguments("(object?, object)", "(string, string)").WithLocation(5, 18), // (12,9): warning CS8602: Dereference of a possibly null reference. // u2.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.Item1").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // u2.Item2.ToString(); /// 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.Item2").WithLocation(13, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Conversions_TupleConversions_07() { var source = @"class A { public static implicit operator B?(A a) => null; } class B { } class Program { static void F(A a, B b) { (B, B) t = (a, b); // 1 t.Item1.ToString(); // 2 t.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,20): warning CS8619: Nullability of reference types in value of type '(B? a, B b)' doesn't match target type '(B, B)'. // (B, B) t = (a, b); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(a, b)").WithArguments("(B? a, B b)", "(B, B)").WithLocation(12, 20), // (13,9): warning CS8602: Possible dereference of a null reference. // t.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(13, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Conversions_TupleConversions_08() { var source = @"class A { public static implicit operator B?(A a) => null; } class B { } class Program { static void F(A a, B b) { var t = ((B, B))(b, a); // 1, 2 t.Item1.ToString(); t.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,17): warning CS8619: Nullability of reference types in value of type '(B b, B? a)' doesn't match target type '(B, B)'. // var t = ((B, B))(b, a); // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((B, B))(b, a)").WithArguments("(B b, B? a)", "(B, B)").WithLocation(12, 17), // (12,29): warning CS8600: Converting null literal or possible null value to non-nullable type. // var t = ((B, B))(b, a); // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "a").WithLocation(12, 29)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_09() { var source = @"class A { public static implicit operator B?(A a) => null; } class B { } struct S { internal object? F; } class Program { static void F1() { (B, S) t1 = (new A(), new S() { F = 1 }); // 1 t1.Item1.ToString(); // 2 t1.Item2.F.ToString(); } static void F2() { (A, S?) t2 = (new A(), new S() { F = 2 }); t2.Item1.ToString(); t2.Item2.Value.F.ToString(); } static void F3() { (B, S?) t3 = (new A(), new S() { F = 3 }); // 3 t3.Item1.ToString(); // 4 t3.Item2.Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,21): warning CS8619: Nullability of reference types in value of type '(B?, S)' doesn't match target type '(B, S)'. // (B, S) t1 = (new A(), new S() { F = 1 }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(new A(), new S() { F = 1 })").WithArguments("(B?, S)", "(B, S)").WithLocation(16, 21), // (17,9): warning CS8602: Possible dereference of a null reference. // t1.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1.Item1").WithLocation(17, 9), // (28,22): warning CS8619: Nullability of reference types in value of type '(B?, S?)' doesn't match target type '(B, S?)'. // (B, S?) t3 = (new A(), new S() { F = 3 }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(new A(), new S() { F = 3 })").WithArguments("(B?, S?)", "(B, S?)").WithLocation(28, 22), // (29,9): warning CS8602: Possible dereference of a null reference. // t3.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3.Item1").WithLocation(29, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_10() { var source = @"class A { public static implicit operator B?(A a) => null; } class B { } struct S { internal object? F; } class Program { static void F1() { var t1 = ((S, B))(new S() { F = 1 }, new A()); // 1, 2 t1.Item1.F.ToString(); // 3 t1.Item2.ToString(); } static void F2() { var t2 = ((S?, A))(new S() { F = 2 }, new A()); t2.Item1.Value.F.ToString(); // 4, 5 t2.Item2.ToString(); } static void F3() { var t3 = ((S?, B))(new S() { F = 3 }, new A()); // 6, 7 t3.Item1.Value.F.ToString(); // 8, 9 t3.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,18): warning CS8619: Nullability of reference types in value of type '(S, B?)' doesn't match target type '(S, B)'. // var t1 = ((S, B))(new S() { F = 1 }, new A()); // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((S, B))(new S() { F = 1 }, new A())").WithArguments("(S, B?)", "(S, B)").WithLocation(16, 18), // (16,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // var t1 = ((S, B))(new S() { F = 1 }, new A()); // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "new A()").WithLocation(16, 46), // (17,9): warning CS8602: Dereference of a possibly null reference. // t1.Item1.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1.Item1.F").WithLocation(17, 9), // (23,9): warning CS8629: Nullable value type may be null. // t2.Item1.Value.F.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2.Item1").WithLocation(23, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // t2.Item1.Value.F.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2.Item1.Value.F").WithLocation(23, 9), // (28,18): warning CS8619: Nullability of reference types in value of type '(S?, B?)' doesn't match target type '(S?, B)'. // var t3 = ((S?, B))(new S() { F = 3 }, new A()); // 6, 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((S?, B))(new S() { F = 3 }, new A())").WithArguments("(S?, B?)", "(S?, B)").WithLocation(28, 18), // (28,47): warning CS8600: Converting null literal or possible null value to non-nullable type. // var t3 = ((S?, B))(new S() { F = 3 }, new A()); // 6, 7 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "new A()").WithLocation(28, 47), // (29,9): warning CS8629: Nullable value type may be null. // t3.Item1.Value.F.ToString(); // 8, 9 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t3.Item1").WithLocation(29, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // t3.Item1.Value.F.ToString(); // 8, 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3.Item1.Value.F").WithLocation(29, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_11() { var source = @"class A { public static implicit operator B?(A a) => null; } class B { } struct S { internal object? F; } class Program { static void F1() { (A, S) t1 = (new A(), new S() { F = 1 }); (B, S?) u1 = t1; // 1 u1.Item1.ToString(); // 2 u1.Item2.Value.F.ToString(); } static void F2() { (A, S) t2 = (new A(), new S() { F = 2 }); var u2 = ((B, S?))t2; // 3 u2.Item1.ToString(); // 4 u2.Item2.Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/34495: Improve warning message to reference user-defined conversion and t1.Item1 or t2.Item1. comp.VerifyDiagnostics( // (17,22): warning CS8601: Possible null reference assignment. // (B, S?) u1 = t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t1").WithLocation(17, 22), // (18,9): warning CS8602: Possible dereference of a null reference. // u1.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u1.Item1").WithLocation(18, 9), // (24,18): warning CS8601: Possible null reference assignment. // var u2 = ((B, S?))t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "((B, S?))t2").WithLocation(24, 18), // (25,9): warning CS8602: Possible dereference of a null reference. // u2.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.Item1").WithLocation(25, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_12() { var source = @"#pragma warning disable 0649 class A { public static implicit operator B?(A a) => null; } class B { } struct S { internal object? F; } class Program { static void F1() { (int, (A, S)) t1 = (1, (new A(), new S() { F = 1 })); (object x, (B, S?) y) u1 = t1; // 1 u1.y.Item1.ToString(); // 2 u1.y.Item2.Value.F.ToString(); } static void F2() { (int, (A, S)) t2 = (2, (new A(), new S() { F = 2 })); var u2 = ((object x, (B, S?) y))t2; // 3 u2.y.Item1.ToString(); // 4 u2.y.Item2.Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/34495: Improve warning message to reference user-defined conversion and t1.Item2.Item1 or t2.Item2.Item1. comp.VerifyDiagnostics( // (18,36): warning CS8601: Possible null reference assignment. // (object x, (B, S?) y) u1 = t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t1").WithLocation(18, 36), // (19,9): warning CS8602: Possible dereference of a null reference. // u1.y.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u1.y.Item1").WithLocation(19, 9), // (25,18): warning CS8601: Possible null reference assignment. // var u2 = ((object x, (B, S?) y))t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "((object x, (B, S?) y))t2").WithLocation(25, 18), // (26,9): warning CS8602: Possible dereference of a null reference. // u2.y.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.y.Item1").WithLocation(26, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_13() { var source = @"class A { public static implicit operator B(A a) => throw null!; } class B { } struct S { internal object? F; internal object G; } class Program { static void F() { A x = new A(); S y = new S() { F = 1, G = null }; // 1 var t = (x, y, x, y, x, y, x, y, x, y); (B?, S?, B?, S?, B?, S?, B?, S?, B?, S?) u = t; u.Item1.ToString(); u.Item2.Value.F.ToString(); u.Item2.Value.G.ToString(); // 2 u.Item9.ToString(); u.Item10.Value.F.ToString(); u.Item10.Value.G.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // S y = new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(18, 36), // (23,9): warning CS8602: Possible dereference of a null reference. // u.Item2.Value.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2.Value.G").WithLocation(23, 9), // (26,9): warning CS8602: Possible dereference of a null reference. // u.Item10.Value.G.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item10.Value.G").WithLocation(26, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_14() { var source = @"class A { public static implicit operator A?(int i) => new A(); } class B { public static implicit operator B(int i) => new B(); } class Program { static void F1((int, int) t1) { (A, B?) u1 = t1; // 1 u1.Item1.ToString(); // 2 u1.Item2.ToString(); } static void F2((int, int) t2) { var u2 = ((B?, A))t2; // 3 u2.Item1.ToString(); // 4 u2.Item2.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/34495: Improve warning message to reference user-defined conversion and t1.Item2 or t2.Item1. comp.VerifyDiagnostics( // (13,22): warning CS8601: Possible null reference assignment. // (A, B?) u1 = t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t1").WithLocation(13, 22), // (14,9): warning CS8602: Dereference of a possibly null reference. // u1.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u1.Item1").WithLocation(14, 9), // (19,18): warning CS8601: Possible null reference assignment. // var u2 = ((B?, A))t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "((B?, A))t2").WithLocation(19, 18), // (20,9): warning CS8602: Dereference of a possibly null reference. // u2.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.Item1").WithLocation(20, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // u2.Item2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.Item2").WithLocation(21, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_15() { var source = @"class A { public static implicit operator A?(int i) => new A(); } class B { public static implicit operator B(int i) => new B(); } struct S { public static implicit operator S((A, B?) t) => default; } class Program { static void F1((int, int) t) { F2(t); // 1 F3(t); // 2 } static void F2((A, B?) t) { } static void F3(S? s) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32599: Handle tuple element conversions. comp.VerifyDiagnostics(); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_16() { var source = @"class A { } class B { public static implicit operator B?(A a) => new B(); } struct S { public static implicit operator (A?, A)(S s) => default; } class Program { static void F1(S s) { F2(s); // 1 F3(s); // 2 } static void F2((A, A?)? t) { } static void F3((B?, B) t) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32599: Handle tuple element conversions. // Diagnostics on user-defined conversions need improvement: https://github.com/dotnet/roslyn/issues/31798 comp.VerifyDiagnostics( // (16,12): warning CS8620: Argument of type 'S' cannot be used for parameter 't' of type '(A, A?)?' in 'void Program.F2((A, A?)? t)' due to differences in the nullability of reference types. // F2(s); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s").WithArguments("S", "(A, A?)?", "t", "void Program.F2((A, A?)? t)").WithLocation(16, 12)); } [Fact] public void Conversions_BoxingConversions_01() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { object o = new S() { F = 1, G = null }; // 1 ((S)o).F.ToString(); // 2 ((S)o).G.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,41): warning CS8625: Cannot convert null literal to non-nullable reference type. // object o = new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 41), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((S)o).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((S)o).F").WithLocation(11, 9)); } [Fact] public void Conversions_BoxingConversions_02() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { ((S)(object)new S() { F = 1 }).F.ToString(); // 1 ((S)(object)new S() { G = null }).F.ToString(); // 2, 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // ((S)(object)new S() { F = 1 }).F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((S)(object)new S() { F = 1 }).F").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((S)(object)new S() { G = null }).F.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((S)(object)new S() { G = null }).F").WithLocation(11, 9), // (11,35): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((S)(object)new S() { G = null }).F.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 35) ); } [Fact] public void Conversions_BoxingConversions_03() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { object? o = (S?)new S() { F = 1, G = null }; // 1 ((S?)o).Value.F.ToString(); // 2 ((S?)o).Value.G.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,46): warning CS8625: Cannot convert null literal to non-nullable reference type. // object? o = (S?)new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 46), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((S?)o).Value.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((S?)o).Value.F").WithLocation(11, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Conversions_BoxingConversions_04() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F1<T>() where T : I, new() { object o1 = new T() { P = 1, Q = null }; // 1 ((T)o1).P.ToString(); // 2 ((T)o1).Q.ToString(); } static void F2<T>() where T : class, I, new() { object o2 = new T() { P = 2, Q = null }; // 3 ((T)o2).P.ToString(); // 4 ((T)o2).Q.ToString(); } static void F3<T>() where T : struct, I { object o3 = new T() { P = 3, Q = null }; // 5 ((T)o3).P.ToString(); // 6 ((T)o3).Q.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,42): warning CS8625: Cannot convert null literal to non-nullable reference type. // object o1 = new T() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 42), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((T)o1).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T)o1).P").WithLocation(11, 9), // (16,42): warning CS8625: Cannot convert null literal to non-nullable reference type. // object o2 = new T() { P = 2, Q = null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 42), // (17,9): warning CS8602: Dereference of a possibly null reference. // ((T)o2).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T)o2).P").WithLocation(17, 9), // (22,42): warning CS8625: Cannot convert null literal to non-nullable reference type. // object o3 = new T() { P = 3, Q = null }; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(22, 42), // (23,9): warning CS8602: Dereference of a possibly null reference. // ((T)o3).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T)o3).P").WithLocation(23, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Conversions_BoxingConversions_05() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F1<T1>() where T1 : I, new() { ((T1)(object)new T1() { P = 1 }).P.ToString(); // 1 ((T1)(object)new T1() { Q = null }).Q.ToString(); // 2 } static void F2<T2>() where T2 : class, I, new() { ((T2)(object)new T2() { P = 2 }).P.ToString(); // 3 ((T2)(object)new T2() { Q = null }).Q.ToString(); // 4 } static void F3<T3>() where T3 : struct, I { ((T3)(object)new T3() { P = 3 }).P.ToString(); // 5 ((T3)(object)new T3() { Q = null }).Q.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // ((T1)(object)new T1() { P = 1 }).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T1)(object)new T1() { P = 1 }).P").WithLocation(10, 9), // (11,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((T1)(object)new T1() { Q = null }).Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 37), // (15,9): warning CS8602: Dereference of a possibly null reference. // ((T2)(object)new T2() { P = 2 }).P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T2)(object)new T2() { P = 2 }).P").WithLocation(15, 9), // (16,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((T2)(object)new T2() { Q = null }).Q.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 37), // (20,9): warning CS8602: Dereference of a possibly null reference. // ((T3)(object)new T3() { P = 3 }).P.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T3)(object)new T3() { P = 3 }).P").WithLocation(20, 9), // (21,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((T3)(object)new T3() { Q = null }).Q.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 37)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Conversions_BoxingConversions_06() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F1<T>() where T : I, new() { (object, object) t1 = (new T() { P = 1 }, new T() { Q = null }); // 1 ((T)t1.Item1).P.ToString(); // 2 (((T, T))t1).Item2.Q.ToString(); } static void F2<T>() where T : class, I, new() { (object, object) t2 = (new T() { P = 2 }, new T() { Q = null }); // 3 ((T)t2.Item1).P.ToString(); // 4 (((T, T))t2).Item2.Q.ToString(); } static void F3<T>() where T : struct, I { (object, object) t3 = (new T() { P = 3 }, new T() { Q = null }); // 5 ((T)t3.Item1).P.ToString(); // 6 (((T, T))t3).Item2.Q.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,65): warning CS8625: Cannot convert null literal to non-nullable reference type. // (object, object) t1 = (new T() { P = 1 }, new T() { Q = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 65), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((T)t1.Item1).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T)t1.Item1).P").WithLocation(11, 9), // (16,65): warning CS8625: Cannot convert null literal to non-nullable reference type. // (object, object) t2 = (new T() { P = 2 }, new T() { Q = null }); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 65), // (17,9): warning CS8602: Dereference of a possibly null reference. // ((T)t2.Item1).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T)t2.Item1).P").WithLocation(17, 9), // (22,65): warning CS8625: Cannot convert null literal to non-nullable reference type. // (object, object) t3 = (new T() { P = 3 }, new T() { Q = null }); // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(22, 65), // (23,9): warning CS8602: Dereference of a possibly null reference. // ((T)t3.Item1).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T)t3.Item1).P").WithLocation(23, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Conversions_BoxingConversions_07() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F<T>() where T : struct, I { object o = (T?)new T() { P = 1, Q = null }; // 1 ((T?)o).Value.P.ToString(); // 2 ((T?)o).Value.Q.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,45): warning CS8625: Cannot convert null literal to non-nullable reference type. // object o = (T?)new T() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 45), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((T?)o).Value.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T?)o).Value.P").WithLocation(11, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] [WorkItem(34086, "https://github.com/dotnet/roslyn/issues/34086")] public void Conversions_BoxingConversions_08() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F<T>() where T : struct, I { (object, object) t = ((T?, T?))(new T() { P = 1 }, new T() { Q = null }); // 1 ((T?)t.Item1).Value.P.ToString(); // 2 (((T?, T?))t).Item2.Value.Q.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,30): warning CS8619: Nullability of reference types in value of type '(T?, T?)' doesn't match target type '(object, object)'. // (object, object) t = ((T?, T?))(new T() { P = 1 }, new T() { Q = null }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((T?, T?))(new T() { P = 1 }, new T() { Q = null })").WithArguments("(T?, T?)", "(object, object)").WithLocation(10, 30), // (10,74): warning CS8625: Cannot convert null literal to non-nullable reference type. // (object, object) t = ((T?, T?))(new T() { P = 1 }, new T() { Q = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 74), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((T?)t.Item1).Value.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T?)t.Item1).Value.P").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // (((T?, T?))t).Item2.Value.Q.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(((T?, T?))t).Item2").WithLocation(12, 9)); } [Fact] public void Members_FieldCycle_01() { var source = @"class C { C? F; void M() { F = this; F.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F.F").WithLocation(7, 9)); } [Fact] public void Members_FieldCycle_02() { var source = @"class C { C? F; void M() { F = new C() { F = this }; F.F.ToString(); F.F.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F.F.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F.F.F").WithLocation(8, 9)); } [Fact] public void Members_FieldCycle_03() { var source = @"class C { C? F; static void M() { var x = new C(); x.F = x; var y = new C() { F = x }; y.F.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Members_FieldCycle_04() { var source = @"class C { C? F; static void M(C x) { object? y = x; for (int i = 0; i < 3; i++) { x.F = x; y = null; } x.F.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x.F.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(12, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.F.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F.F").WithLocation(12, 9)); } [Fact] public void Members_FieldCycle_05() { var source = @"class C { C? F; static void M(C x) { (x.F, _) = (x, 0); x.F.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.F.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F.F").WithLocation(7, 9)); } [Fact] public void Members_FieldCycle_06() { var source = @"#pragma warning disable 0649 class A { internal B B = default!; } class B { internal A? A; } class Program { static void M(A a) { a.B.A = a; a.B.A.B.A.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // a.B.A.B.A.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.B.A.B.A").WithLocation(15, 9)); } [Fact] [WorkItem(33908, "https://github.com/dotnet/roslyn/issues/33908")] public void Members_FieldCycle_07() { var source = @"#pragma warning disable 8618 class C { C F; static void M() { C x = null; while (true) { C y = new C() { F = x }; x = y; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,7): warning CS0414: The field 'C.F' is assigned but its value is never used // C F; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("C.F").WithLocation(4, 7), // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // C x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 15), // (10,33): warning CS8601: Possible null reference assignment. // C y = new C() { F = x }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(10, 33)); } [Fact] [WorkItem(33908, "https://github.com/dotnet/roslyn/issues/33908")] public void Members_FieldCycle_08() { var source = @"#pragma warning disable 8618 class C { C F; static void M() { C x = null; while (true) { C y = new C() { F = x }; x = new C() { F = y }; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,7): warning CS0414: The field 'C.F' is assigned but its value is never used // C F; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("C.F").WithLocation(4, 7), // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // C x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 15), // (10,33): warning CS8601: Possible null reference assignment. // C y = new C() { F = x }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(10, 33)); } [Fact] [WorkItem(33908, "https://github.com/dotnet/roslyn/issues/33908")] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Members_FieldCycle_09() { var source = @"#pragma warning disable 8618 class C<T> { internal T F; } class Program { static void F<T>() where T : C<T>, new() { T x = default; while (true) { T y = new T() { F = x }; x = y; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(10, 15), // (13,33): warning CS8601: Possible null reference assignment. // T y = new T() { F = x }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(13, 33)); } [Fact] [WorkItem(33908, "https://github.com/dotnet/roslyn/issues/33908")] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Members_FieldCycle_10() { var source = @"interface I<T> { T P { get; set; } } class Program { static void F1<T>() where T : I<T>, new() { T x1 = default; while (true) { T y1 = new T() { P = x1 }; x1 = y1; } } static void F2<T>() where T : class, I<T>, new() { T x2 = default; while (true) { T y2 = new T() { P = x2 }; x2 = y2; } } static void F3<T>() where T : struct, I<T> { T x3 = default; while (true) { T y3 = new T() { P = x3 }; x3 = y3; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,34): warning CS8601: Possible null reference assignment. // T y1 = new T() { P = x1 }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x1").WithLocation(12, 34), // (18,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x2 = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(18, 16), // (21,34): warning CS8601: Possible null reference assignment. // T y2 = new T() { P = x2 }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x2").WithLocation(21, 34)); } [Fact] public void Members_FieldCycle_Struct() { var source = @"struct S { internal C F; internal C? G; } class C { internal S S; static void Main() { var s = new S() { F = new C(), G = new C() }; s.F.S = s; s.G.S = s; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } // Valid struct since the property is not backed by a field. [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void Members_PropertyCycle_Struct() { var source = @"#pragma warning disable 0649 struct S { internal S(object? f) { F = f; } internal object? F; internal S P { get { return new S(F); } set { F = value.F; } } } class C { static void M(S s) { s.P.F.ToString(); // 1 if (s.P.F == null) return; s.P.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // s.P.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.P.F").WithLocation(19, 9)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void Members_StructProperty_Default() { var source = @"#pragma warning disable 0649 struct S { internal object F; private object _p; internal object P { get { return _p; } set { _p = value; } } internal object Q { get; set; } } class Program { static void Main() { S s = default; s.F.ToString(); // 1 s.P.ToString(); s.Q.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // s.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.F").WithLocation(14, 9)); } [Fact] public void Members_StaticField_Struct() { var source = @"struct S<T> where T : class { internal T F; internal T? G; internal static S<T> Instance = new S<T>(); } class Program { static void F<T>() where T : class, new() { S<T>.Instance.F = null; // 1 S<T>.Instance.G = new T(); S<T>.Instance.F.ToString(); // 2 S<T>.Instance.G.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,27): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // S<T>.Instance.F = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 27), // (13,9): warning CS8602: Dereference of a possibly null reference. // S<T>.Instance.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "S<T>.Instance.F").WithLocation(13, 9)); } [Fact] public void Members_DefaultConstructor_Class() { var source = @"#pragma warning disable 649 #pragma warning disable 8618 class A { internal object? A1; internal object A2; } class B { internal B() { B2 = null!; } internal object? B1; internal object B2; } class Program { static void Main() { A a = new A(); a.A1.ToString(); // 1 a.A2.ToString(); B b = new B(); b.B1.ToString(); // 2 b.B2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (22,9): warning CS8602: Dereference of a possibly null reference. // a.A1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.A1").WithLocation(22, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // b.B1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.B1").WithLocation(25, 9)); } [Fact] public void SelectAnonymousType() { var source = @"using System.Collections.Generic; using System.Linq; class C { int? E; static void F(IEnumerable<C> c) { const int F = 0; c.Select(o => new { E = o.E ?? F }); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,10): warning CS0649: Field 'C.E' is never assigned to, and will always have its default value // int? E; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "E").WithArguments("C.E", "").WithLocation(5, 10)); } [Fact] public void Constraints_01() { var source = @"interface I<T> { T P { get; set; } } class A { } class B { static void F1<T>(T t1) where T : A { t1.ToString(); t1 = default; // 1 } static void F2<T>(T t2) where T : A? { t2.ToString(); // 2 t2 = default; } static void F3<T>(T t3) where T : I<T> { t3.P.ToString(); t3 = default; } static void F4<T>(T t4) where T : I<T>? { t4.P.ToString(); // 3 and 4 t4.P = default; // 5 t4 = default; } static void F5<T>(T t5) where T : I<T?> { t5.P.ToString(); // 6 and 7 t5.P = default; t5 = default; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t1 = default; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(11, 14), // (15,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(15, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // t4.P.ToString(); // 3 and 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t4").WithLocation(25, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // t4.P.ToString(); // 3 and 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t4.P").WithLocation(25, 9), // (26,16): warning CS8601: Possible null reference assignment. // t4.P = default; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(26, 16), // (29,41): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F5<T>(T t5) where T : I<T?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(29, 41), // (31,9): warning CS8602: Dereference of a possibly null reference. // t5.P.ToString(); // 6 and 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t5.P").WithLocation(31, 9) ); } [Fact] public void Constraints_02() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : class { } public static void F2<T2>(T2 t2) where T2 : class? { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var b = m.GlobalNamespace.GetMember("B"); if (isSource) { Assert.Empty(b.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", b.GetAttributes().First().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : class!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.ReferenceTypeConstraintIsNullable); Assert.Empty(t1.GetAttributes()); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T2>(T2 t2) where T2 : class?", f2.ToDisplayString(SymbolDisplayFormat.TestFormat.WithGenericsOptions(SymbolDisplayFormat.TestFormat.GenericsOptions | SymbolDisplayGenericsOptions.IncludeTypeConstraints))); Assert.Equal("void B.F2<T2>(T2 t2) where T2 : class", f2.ToDisplayString(SymbolDisplayFormat.TestFormat.WithGenericsOptions(SymbolDisplayFormat.TestFormat.GenericsOptions | SymbolDisplayGenericsOptions.IncludeTypeConstraints). WithMiscellaneousOptions(SymbolDisplayFormat.TestFormatWithConstraints.MiscellaneousOptions & ~(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier)))); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t2.GetAttributes().Single().ToString()); } } } [Fact] public void Constraints_03() { var source = @" class A<T1> where T1 : class { public static void F1(T1? t1) { } } class B<T2> where T2 : class? { public static void F2(T2 t2) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var a = (NamedTypeSymbol)m.GlobalNamespace.GetMember("A"); Assert.Equal("A<T1> where T1 : class!", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = a.TypeParameters[0]; Assert.False(t1.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(1)", t1.GetAttributes().Single().ToString()); } var b = (NamedTypeSymbol)m.GlobalNamespace.GetMember("B"); Assert.Equal("B<T2> where T2 : class?", b.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = b.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t2.GetAttributes().Single().ToString()); } } } [Fact] public void Constraints_04() { var source = @" #pragma warning disable CS8321 class B { public static void Test() { void F1<T1>(T1? t1) where T1 : class { } void F2<T2>(T2 t2) where T2 : class? { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var localSyntaxes = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToArray(); Assert.Equal(2, localSyntaxes.Length); var f1 = model.GetDeclaredSymbol(localSyntaxes[0]).GetSymbol<LocalFunctionSymbol>(); Assert.Equal("void F1<T1>(T1? t1) where T1 : class!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.ReferenceTypeConstraintIsNullable); Assert.Empty(t1.GetAttributes()); var f2 = model.GetDeclaredSymbol(localSyntaxes[1]).GetSymbol<LocalFunctionSymbol>(); Assert.Equal("void F2<T2>(T2 t2) where T2 : class?", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); Assert.Empty(t2.GetAttributes()); } [Fact] public void Constraints_05() { var source = @" #pragma warning disable CS8321 class B<T1> where T1 : class? { public static void F2<T2>(T2 t2) where T2 : class? { void F3<T3>(T3 t3) where T3 : class? { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,29): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // class B<T1> where T1 : class? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 29), // (6,54): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static void F2<T2>(T2 t2) where T2 : class? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 54), // (8,44): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void F3<T3>(T3 t3) where T3 : class? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 44) ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var b = (NamedTypeSymbol)m.GlobalNamespace.GetMember("B"); Assert.Equal("B<T1> where T1 : class?", b.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = b.TypeParameters[0]; Assert.True(t1.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t1.GetAttributes().Single().ToString()); } var f2 = (MethodSymbol)b.GetMember("F2"); Assert.Equal("void B<T1>.F2<T2>(T2 t2) where T2 : class?", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t2.GetAttributes().Single().ToString()); } } comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); var expected = new[] { // (4,29): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // class B<T1> where T1 : class? Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(4, 29), // (6,54): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // public static void F2<T2>(T2 t2) where T2 : class? Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(6, 54), // (8,44): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // void F3<T3>(T3 t3) where T3 : class? Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(8, 44) }; comp.VerifyDiagnostics(expected); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); comp.VerifyDiagnostics(expected .Concat(new[] { // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.3", "8.0").WithLocation(1, 1), }).ToArray() ); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, skipUsesIsNullable: true); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9, skipUsesIsNullable: true); comp.VerifyDiagnostics(); } [Fact] public void Constraints_06() { var source = @" #pragma warning disable CS8321 class B<T1> where T1 : class? { public static void F1(T1? t1) {} public static void F2<T2>(T2? t2) where T2 : class? { void F3<T3>(T3? t3) where T3 : class? { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F2<T2>(T2? t2) where T2 : class? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(9, 31), // (6,27): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F1(T1? t1) Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T1?").WithArguments("9.0").WithLocation(6, 27), // (11,21): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F3<T3>(T3? t3) where T3 : class? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T3?").WithArguments("9.0").WithLocation(11, 21) ); } [Fact] public void Constraints_07() { var source = @" class B { public static void F1<T11, T12>(T12? t1) where T11 : class where T12 : T11 {} public static void F2<T21, T22>(T22? t1) where T21 : class where T22 : class, T21 {} public static void F3<T31, T32>(T32? t1) where T31 : B where T32 : T31 {} public static void F4<T41, T42>(T42? t1) where T41 : B where T42 : T41? {} }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,37): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F1<T11, T12>(T12? t1) where T11 : class where T12 : T11 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T12?").WithArguments("9.0").WithLocation(4, 37), // (13,37): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F4<T41, T42>(T42? t1) where T41 : B where T42 : T41? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T42?").WithArguments("9.0").WithLocation(13, 37) ); } [Fact] public void Constraints_08() { var source = @" #pragma warning disable CS8321 class B<T11, T12> where T12 : T11? { public static void F2<T21, T22>() where T22 : T21? { void F3<T31, T32>() where T32 : T31? { } } public static void F4<T4>() where T4 : T4? {} }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class B<T11, T12> where T12 : T11? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T11?").WithArguments("9.0").WithLocation(4, 31), // (6,51): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F2<T21, T22>() where T22 : T21? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T21?").WithArguments("9.0").WithLocation(6, 51), // (8,41): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F3<T31, T32>() where T32 : T31? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T31?").WithArguments("9.0").WithLocation(8, 41), // (13,27): error CS0454: Circular constraint dependency involving 'T4' and 'T4' // public static void F4<T4>() where T4 : T4? Diagnostic(ErrorCode.ERR_CircularConstraint, "T4").WithArguments("T4", "T4").WithLocation(13, 27), // (13,44): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F4<T4>() where T4 : T4? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T4?").WithArguments("9.0").WithLocation(13, 44) ); } [Fact] public void Constraints_09() { var source = @" class B { public static void F1<T1>() where T1 : Node<T1>? {} public static void F2<T2>() where T2 : Node<T2?> {} public static void F3<T3>() where T3 : Node<T3?>? {} } class Node<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,49): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T3>() where T3 : Node<T3?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T3?").WithArguments("9.0").WithLocation(10, 49) ); } [Fact] public void Constraints_10() { var source = @" class B { public static void F1<T1>() where T1 : class, Node<T1>? {} public static void F2<T2>() where T2 : class, Node<T2?> {} public static void F3<T3>() where T3 : class, Node<T3?>? {} } class Node<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,51): error CS0450: 'Node<T2?>': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F2<T2>() where T2 : class, Node<T2?> Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "Node<T2?>").WithArguments("Node<T2?>").WithLocation(7, 51), // (10,51): error CS0450: 'Node<T3?>': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F3<T3>() where T3 : class, Node<T3?>? Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "Node<T3?>?").WithArguments("Node<T3?>").WithLocation(10, 51), // (4,51): error CS0450: 'Node<T1>': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F1<T1>() where T1 : class, Node<T1>? Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "Node<T1>?").WithArguments("Node<T1>").WithLocation(4, 51) ); } [Fact] public void Constraints_11() { var source = @" class B { public static void F1<T1>() where T1 : class?, Node<T1>? {} public static void F2<T2>() where T2 : class?, Node<T2?> {} public static void F3<T3>() where T3 : class?, Node<T3?>? {} } class Node<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,57): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F2<T2>() where T2 : class?, Node<T2?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(7, 57), // (7,52): error CS0450: 'Node<T2?>': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F2<T2>() where T2 : class?, Node<T2?> Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "Node<T2?>").WithArguments("Node<T2?>").WithLocation(7, 52), // (10,57): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T3>() where T3 : class?, Node<T3?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T3?").WithArguments("9.0").WithLocation(10, 57), // (10,52): error CS0450: 'Node<T3?>': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F3<T3>() where T3 : class?, Node<T3?>? Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "Node<T3?>?").WithArguments("Node<T3?>").WithLocation(10, 52), // (4,52): error CS0450: 'Node<T1>': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F1<T1>() where T1 : class?, Node<T1>? Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "Node<T1>?").WithArguments("Node<T1>").WithLocation(4, 52) ); } [Fact] public void Constraints_12() { var source = @" class B { public static void F1<T1>() where T1 : INode<T1>? {} public static void F2<T2>() where T2 : INode<T2?> {} public static void F3<T3>() where T3 : INode<T3?>? {} } interface INode<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,50): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F2<T2>() where T2 : INode<T2?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(7, 50), // (10,50): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T3>() where T3 : INode<T3?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T3?").WithArguments("9.0").WithLocation(10, 50) ); } [Fact] public void Constraints_13() { var source = @" class B { public static void F1<T1>() where T1 : class, INode<T1>? {} public static void F2<T2>() where T2 : class, INode<T2?> {} public static void F3<T3>() where T3 : class, INode<T3?>? {} } interface INode<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); } [Fact] public void Constraints_14() { var source = @" class B { public static void F1<T1>() where T1 : class?, INode<T1>? {} public static void F2<T2>() where T2 : class?, INode<T2?> {} public static void F3<T3>() where T3 : class?, INode<T3?>? {} } interface INode<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,58): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T3>() where T3 : class?, INode<T3?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T3?").WithArguments("9.0").WithLocation(10, 58) ); } [Fact] public void Constraints_15() { var source = @" class B { public static void F1<T11, T12>() where T11 : INode where T12 : class?, T11, INode<T12?> {} public static void F2<T21, T22>() where T21 : INode? where T22 : class?, T21, INode<T22?> {} public static void F3<T31, T32>() where T31 : INode? where T32 : class?, T31, INode<T32?>? {} public static void F4<T41, T42>() where T41 : INode? where T42 : class?, T41?, INode<T42?>? {} } interface INode {} interface INode<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,89): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T31, T32>() where T31 : INode? where T32 : class?, T31, INode<T32?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T32?").WithArguments("9.0").WithLocation(10, 89), // (13,78): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F4<T41, T42>() where T41 : INode? where T42 : class?, T41?, INode<T42?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T41?").WithArguments("9.0").WithLocation(13, 78), // (13,90): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F4<T41, T42>() where T41 : INode? where T42 : class?, T41?, INode<T42?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T42?").WithArguments("9.0").WithLocation(13, 90) ); } [Fact] public void Constraints_16() { var source = @" class B { public static void F1<T11, T12>(T12? t1) where T11 : INode where T12 : class?, T11 {} public static void F2<T21, T22>(T22? t2) where T21 : INode? where T22 : class?, T21 {} public static void F3<T31, T32>(T32? t1) where T31 : INode where T32 : class?, T31? {} } interface INode {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,37): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F2<T21, T22>(T22? t2) where T21 : INode? where T22 : class?, T21 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T22?").WithArguments("9.0").WithLocation(7, 37), // (10,37): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T31, T32>(T32? t1) where T31 : INode where T32 : class?, T31? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T32?").WithArguments("9.0").WithLocation(10, 37), // (10,84): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T31, T32>(T32? t1) where T31 : INode where T32 : class?, T31? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T31?").WithArguments("9.0").WithLocation(10, 84) ); } [Fact] public void Constraints_17() { var source = @" #pragma warning disable CS8321 class B<[System.Runtime.CompilerServices.Nullable(0)] T1> { public static void F2<[System.Runtime.CompilerServices.Nullable(1)] T2>(T2 t2) { void F3<[System.Runtime.CompilerServices.Nullable(2)] T3>(T3 t3) { } } }"; var comp = CreateCompilation(new[] { source, NullableAttributeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,10): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // class B<[System.Runtime.CompilerServices.Nullable(0)] T1> Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "System.Runtime.CompilerServices.Nullable(0)").WithLocation(4, 10), // (6,28): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // public static void F2<[System.Runtime.CompilerServices.Nullable(1)] T2>(T2 t2) Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "System.Runtime.CompilerServices.Nullable(1)").WithLocation(6, 28), // (8,18): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // void F3<[System.Runtime.CompilerServices.Nullable(2)] T3>(T3 t3) Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "System.Runtime.CompilerServices.Nullable(2)").WithLocation(8, 18) ); } [Fact] public void Constraints_18() { var source = @" class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } class B : A<int> { public override void F1<T11>(T11? t1) { } public override void F2<T22>(T22 t2) { } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,26): error CS0115: 'B.F1<T11>(T11?)': no suitable method found to override // public override void F1<T11>(T11? t1) where T : class Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B.F1<T11>(T11?)").WithLocation(15, 26), // (15,39): error CS0453: The type 'T11' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<T11>(T11? t1) where T : class Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t1").WithArguments("System.Nullable<T>", "T", "T11").WithLocation(15, 39)); } [Fact] public void Constraints_19() { var source1 = @" public class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var source2 = @" class B : A<int> { public override void F1<T11>(T11? t1) { } public override void F2<T22>(T22 t2) { } } "; var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }) .VerifyDiagnostics( // (4,26): error CS0115: 'B.F1<T11>(T11?)': no suitable method found to override // public override void F1<T11>(T11? t1) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B.F1<T11>(T11?)").WithLocation(4, 26), // (4,39): error CS0453: The type 'T11' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<T11>(T11? t1) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t1").WithArguments("System.Nullable<T>", "T", "T11").WithLocation(4, 39)); } [Fact] public void Constraints_20() { var source1 = @" public class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var source3 = @" class B : A<int> { public override void F1<T11>(T11? t1) { } public override void F2<T22>(T22 t2) { } } "; var comp3 = CreateCompilation(new[] { source3 }, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (4,26): error CS0115: 'B.F1<T11>(T11?)': no suitable method found to override // public override void F1<T11>(T11? t1) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B.F1<T11>(T11?)").WithLocation(4, 26), // (4,39): error CS0453: The type 'T11' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<T11>(T11? t1) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t1").WithArguments("System.Nullable<T>", "T", "T11").WithLocation(4, 39)); } [Fact] public void Constraints_21() { var source1 = @" public class A<T> { public virtual void F1<T1>() where T1 : class { } public virtual void F2<T2>() where T2 : class? { } } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var source2 = @" class B : A<int> { public override void F1<T11>() { } public override void F2<T22>() { } } "; var comp2 = CreateCompilation(new[] { source2 }, references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", bf2.GetAttributes().Single().ToString()); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); } } [Fact] public void Constraints_22() { var source = @" class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } class B : A<int> { public override void F1<T11>(T11? t1) { } public override void F2<T22>(T22 t2) { } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,26): error CS0115: 'B.F1<T11>(T11?)': no suitable method found to override // public override void F1<T11>(T11? t1) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B.F1<T11>(T11?)").WithLocation(15, 26), // (15,39): error CS0453: The type 'T11' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<T11>(T11? t1) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t1").WithArguments("System.Nullable<T>", "T", "T11").WithLocation(15, 39)); var bf1 = (MethodSymbol)comp.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>(T11? t1)", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.IsReferenceType); Assert.Null(bf1.OverriddenMethod); var bf2 = (MethodSymbol)comp.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>(T22 t2) where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); var af2 = bf2.OverriddenMethod; Assert.Equal("void A<System.Int32>.F2<T2>(T2 t2) where T2 : class?", af2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = af2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); } [Fact] public void Constraints_23() { var source1 = @" public interface IA { void F1<T1>() where T1 : class?; void F2<T2>() where T2 : class; void F3<T3>() where T3 : C1<C2>; void F4<T4>() where T4 : C1<C2>; void F5<T51, T52>() where T51 : class where T52 : C1<T51>; void F6<T61, T62>() where T61 : class where T62 : C1<T61?>; } public class C1<T> {} public class C2 {} "; var source2 = @" class B : IA { public void F1<T11>() where T11 : class { } public void F2<T22>() where T22 : class? { } public void F3<T33>() where T33 : C1<C2?> { } public void F4<T44>() where T44 : C1<C2>? { } public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> { } public void F6<T661, T662>() where T661 : class where T662 : C1<T661> { } } class D : IA { public void F1<T111>() where T111 : class? { } public void F2<T222>() where T222 : class { } public void F3<T333>() where T333 : C1<C2> { } public void F4<T444>() where T444 : C1<C2> { } public void F5<T5551, T5552>() where T5551 : class where T5552 : C1<T5551> { } public void F6<T6661, T6662>() where T6661 : class where T6662 : C1<T6661?> { } } "; var comp1 = CreateCompilation(new[] { source2, source1 }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T11' of method 'B.F1<T11>()' doesn't match the constraints for type parameter 'T1' of interface method 'IA.F1<T1>()'. Consider using an explicit interface implementation instead. // public void F1<T11>() where T11 : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("T11", "B.F1<T11>()", "T1", "IA.F1<T1>()").WithLocation(4, 17), // (8,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA.F2<T2>()").WithLocation(8, 17), // (12,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1<C2?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA.F3<T3>()").WithLocation(12, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'T44' of method 'B.F4<T44>()' doesn't match the constraints for type parameter 'T4' of interface method 'IA.F4<T4>()'. Consider using an explicit interface implementation instead. // public void F4<T44>() where T44 : C1<C2>? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T44", "B.F4<T44>()", "T4", "IA.F4<T4>()").WithLocation(16, 17), // (20,17): warning CS8633: Nullability in constraints for type parameter 'T552' of method 'B.F5<T551, T552>()' doesn't match the constraints for type parameter 'T52' of interface method 'IA.F5<T51, T52>()'. Consider using an explicit interface implementation instead. // public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F5").WithArguments("T552", "B.F5<T551, T552>()", "T52", "IA.F5<T51, T52>()").WithLocation(20, 17), // (24,17): warning CS8633: Nullability in constraints for type parameter 'T662' of method 'B.F6<T661, T662>()' doesn't match the constraints for type parameter 'T62' of interface method 'IA.F6<T61, T62>()'. Consider using an explicit interface implementation instead. // public void F6<T661, T662>() where T661 : class where T662 : C1<T661> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F6").WithArguments("T662", "B.F6<T661, T662>()", "T62", "IA.F6<T61, T62>()").WithLocation(24, 17) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", bf2.GetAttributes().Single().ToString()); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); var bf3 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F3"); Assert.Equal("void B.F3<T33>() where T33 : C1<C2?>!", bf3.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); var bf4 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F4"); Assert.Equal("void B.F4<T44>() where T44 : C1<C2!>?", bf4.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } var comp2 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); comp2.VerifyDiagnostics( ); var comp3 = CreateCompilation(new[] { source2 }, references: new[] { comp2.ToMetadataReference() }, options: WithNullable(NullableContextOptions.Warnings), parseOptions: TestOptions.Regular8); comp3.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (8,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA.F2<T2>()").WithLocation(8, 17), // (12,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1<C2?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA.F3<T3>()").WithLocation(12, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'T44' of method 'B.F4<T44>()' doesn't match the constraints for type parameter 'T4' of interface method 'IA.F4<T4>()'. Consider using an explicit interface implementation instead. // public void F4<T44>() where T44 : C1<C2>? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T44", "B.F4<T44>()", "T4", "IA.F4<T4>()").WithLocation(16, 17), // (20,17): warning CS8633: Nullability in constraints for type parameter 'T552' of method 'B.F5<T551, T552>()' doesn't match the constraints for type parameter 'T52' of interface method 'IA.F5<T51, T52>()'. Consider using an explicit interface implementation instead. // public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F5").WithArguments("T552", "B.F5<T551, T552>()", "T52", "IA.F5<T51, T52>()").WithLocation(20, 17), // (20,69): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T551?").WithArguments("9.0").WithLocation(20, 69), // (51,73): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F6<T6661, T6662>() where T6661 : class where T6662 : C1<T6661?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T6661?").WithArguments("9.0").WithLocation(51, 73) ); var comp4 = CreateCompilation(new[] { source1 }); var comp5 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp4.ToMetadataReference() }); comp5.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T11' of method 'B.F1<T11>()' doesn't match the constraints for type parameter 'T1' of interface method 'IA.F1<T1>()'. Consider using an explicit interface implementation instead. // public void F1<T11>() where T11 : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("T11", "B.F1<T11>()", "T1", "IA.F1<T1>()").WithLocation(4, 17), // (24,17): warning CS8633: Nullability in constraints for type parameter 'T662' of method 'B.F6<T661, T662>()' doesn't match the constraints for type parameter 'T62' of interface method 'IA.F6<T61, T62>()'. Consider using an explicit interface implementation instead. // public void F6<T661, T662>() where T661 : class where T662 : C1<T661> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F6").WithArguments("T662", "B.F6<T661, T662>()", "T62", "IA.F6<T61, T62>()").WithLocation(24, 17) ); } [Fact] public void Constraints_24() { var source = @" interface IA { void F1<T1>() where T1 : class; void F2<T2>() where T2 : class?; } class B : IA { void IA.F1<T11>() { } void IA.F2<T22>() { } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F1"); Assert.Equal("void B.IA.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F2"); Assert.Equal("void B.IA.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", bf2.GetAttributes().Single().ToString()); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); } } [Fact] public void Constraints_25() { var source1 = @" public interface IA { void F1<T1>() where T1 : class; void F2<T2>() where T2 : class?; } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var source2 = @" class B : IA { void IA.F1<T11>() { } void IA.F2<T22>() { } } "; var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)), references: new[] { comp1.EmitToImageReference() }); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F1"); Assert.Equal("void B.IA.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F2"); Assert.Equal("void B.IA.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { CSharpAttributeData nullableAttribute = bf2.GetAttributes().Single(); Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", nullableAttribute.ToString()); Assert.Same(m, nullableAttribute.AttributeClass.ContainingModule); Assert.Equal(Accessibility.Internal, nullableAttribute.AttributeClass.DeclaredAccessibility); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); } } [Fact] public void Constraints_26() { var source1 = @" public interface IA { void F1<T1>() where T1 : class; void F2<T2>() where T2 : class?; } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var comp2 = CreateCompilation(NullableContextAttributeDefinition); var source3 = @" class B : IA { void IA.F1<T11>() { } void IA.F2<T22>() { } } "; var comp3 = CreateCompilation(new[] { source3 }, options: WithNullableEnable(TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)), references: new[] { comp1.EmitToImageReference(), comp2.EmitToImageReference() }); comp3.VerifyDiagnostics( ); CompileAndVerify(comp3, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F1"); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } Assert.Equal("void B.IA.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F2"); Assert.Equal("void B.IA.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { CSharpAttributeData nullableAttribute = bf2.GetAttributes().Single(); Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", nullableAttribute.ToString()); Assert.NotEqual(m, nullableAttribute.AttributeClass.ContainingModule); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); } } [Fact] public void Constraints_27() { var source1 = @" public interface IA { void F1<T1>() where T1 : class; void F2<T2>() where T2 : class?; } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var source2 = @" class B : IA { void IA.F1<T11>() { } void IA.F2<T22>() { } } "; var comp2 = CreateCompilation(new[] { source2 }, references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F1"); Assert.Equal("void B.IA.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F2"); Assert.Equal("void B.IA.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", bf2.GetAttributes().Single().ToString()); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); } } [Fact] public void Constraints_28() { var source = @" interface IA { void F1<T1>(T1? t1) where T1 : class; void F2<T2>(T2 t2) where T2 : class?; } class B : IA { void IA.F1<T11>(T11? t1) where T11 : class? { } void IA.F2<T22>(T22 t2) where T22 : class { } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,42): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // void IA.F1<T11>(T11? t1) where T11 : class? Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "class?").WithLocation(10, 42)); var bf1 = (MethodSymbol)comp.GlobalNamespace.GetMember("B.IA.F1"); Assert.Equal("void B.IA.F1<T11>(T11? t1) where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.True(t11.IsReferenceType); var bf2 = (MethodSymbol)comp.GlobalNamespace.GetMember("B.IA.F2"); Assert.Equal("void B.IA.F2<T22>(T22 t2) where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); } [Fact] public void Constraints_29() { var source = @" class B { public static void F2<T2>() where T2 : class? { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T2>() where T2 : class?", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(f2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", f2.GetAttributes().Single().ToString()); } TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); Assert.Empty(t2.GetAttributes()); } } [Fact] public void Constraints_30() { var source = @" class B<T2> where T2 : class? { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var b = (NamedTypeSymbol)m.GlobalNamespace.GetMember("B"); Assert.Equal("B<T2> where T2 : class?", b.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = b.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t2.GetAttributes().Single().ToString()); } } } [Fact] public void Constraints_31() { var source = @" #pragma warning disable CS8321 class B { public static void Test() { void F2<T2>() where T2 : class? { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var localSyntaxes = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToArray(); Assert.Equal(1, localSyntaxes.Length); var f2 = model.GetDeclaredSymbol(localSyntaxes[0]).GetSymbol<LocalFunctionSymbol>(); Assert.Equal("void F2<T2>() where T2 : class?", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); Assert.Empty(t2.GetAttributes()); } [Fact] public void Constraints_32() { var source = @" #pragma warning disable CS8321 class B<T1> where T1 : struct? { public static void F2<T2>(T2 t2) where T2 : struct? { void F3<T3>(T3 t3) where T3 : struct? { } } }"; var comp = CreateCompilation(source); var expected = new[] { // (4,30): error CS1073: Unexpected token '?' // class B<T1> where T1 : struct? Diagnostic(ErrorCode.ERR_UnexpectedToken, "?").WithArguments("?").WithLocation(4, 30), // (6,55): error CS1073: Unexpected token '?' // public static void F2<T2>(T2 t2) where T2 : struct? Diagnostic(ErrorCode.ERR_UnexpectedToken, "?").WithArguments("?").WithLocation(6, 55), // (8,45): error CS1073: Unexpected token '?' // void F3<T3>(T3 t3) where T3 : struct? Diagnostic(ErrorCode.ERR_UnexpectedToken, "?").WithArguments("?").WithLocation(8, 45) }; comp.VerifyDiagnostics(expected); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(expected); comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(expected); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); comp.VerifyDiagnostics(expected .Concat(new[] { // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.3", "8.0").WithLocation(1, 1) }).ToArray() ); } [Fact] public void Constraints_33() { var source = @" interface IA<TA> { } class C<TC> where TC : IA<object>, IA<object?> { } class B<TB> where TB : IA<object?>, IA<object> { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,36): error CS0405: Duplicate constraint 'IA<object>' for type parameter 'TC' // class C<TC> where TC : IA<object>, IA<object?> Diagnostic(ErrorCode.ERR_DuplicateBound, "IA<object?>").WithArguments("IA<object>", "TC").WithLocation(5, 36), // (8,37): error CS0405: Duplicate constraint 'IA<object>' for type parameter 'TB' // class B<TB> where TB : IA<object?>, IA<object> Diagnostic(ErrorCode.ERR_DuplicateBound, "IA<object>").WithArguments("IA<object>", "TB").WithLocation(8, 37) ); } [Fact] public void Constraints_34() { var source = @" interface IA<TA> { } class B<TB> where TB : IA<object>?, IA<object> { } class C<TC> where TC : IA<object>, IA<object>? { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,37): error CS0405: Duplicate constraint 'IA<object>' for type parameter 'TB' // class B<TB> where TB : IA<object>?, IA<object> Diagnostic(ErrorCode.ERR_DuplicateBound, "IA<object>").WithArguments("IA<object>", "TB").WithLocation(5, 37), // (8,36): error CS0405: Duplicate constraint 'IA<object>' for type parameter 'TC' // class C<TC> where TC : IA<object>, IA<object>? Diagnostic(ErrorCode.ERR_DuplicateBound, "IA<object>?").WithArguments("IA<object>", "TC").WithLocation(8, 36) ); } [Fact] public void Constraints_35() { var source1 = @" public interface IA<S> { void F1<T1>() where T1 : class?; void F2<T2>() where T2 : class; void F3<T3>() where T3 : C1<C2>; void F4<T4>() where T4 : C1<C2>; void F5<T51, T52>() where T51 : class where T52 : C1<T51>; void F6<T61, T62>() where T61 : class where T62 : C1<T61?>; } public class C1<T> {} public class C2 {} "; var source2 = @" class B : IA<string> { public void F1<T11>() where T11 : class { } public void F2<T22>() where T22 : class? { } public void F3<T33>() where T33 : C1<C2?> { } public void F4<T44>() where T44 : C1<C2>? { } public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> { } public void F6<T661, T662>() where T661 : class where T662 : C1<T661> { } } class D : IA<string> { public void F1<T111>() where T111 : class? { } public void F2<T222>() where T222 : class { } public void F3<T333>() where T333 : C1<C2> { } public void F4<T444>() where T444 : C1<C2> { } public void F5<T5551, T5552>() where T5551 : class where T5552 : C1<T5551> { } public void F6<T6661, T6662>() where T6661 : class where T6662 : C1<T6661?> { } } "; var comp1 = CreateCompilation(new[] { source2, source1 }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T11' of method 'B.F1<T11>()' doesn't match the constraints for type parameter 'T1' of interface method 'IA<string>.F1<T1>()'. Consider using an explicit interface implementation instead. // public void F1<T11>() where T11 : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("T11", "B.F1<T11>()", "T1", "IA<string>.F1<T1>()").WithLocation(4, 17), // (8,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA<string>.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA<string>.F2<T2>()").WithLocation(8, 17), // (12,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA<string>.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1<C2?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA<string>.F3<T3>()").WithLocation(12, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'T44' of method 'B.F4<T44>()' doesn't match the constraints for type parameter 'T4' of interface method 'IA<string>.F4<T4>()'. Consider using an explicit interface implementation instead. // public void F4<T44>() where T44 : C1<C2>? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T44", "B.F4<T44>()", "T4", "IA<string>.F4<T4>()").WithLocation(16, 17), // (20,17): warning CS8633: Nullability in constraints for type parameter 'T552' of method 'B.F5<T551, T552>()' doesn't match the constraints for type parameter 'T52' of interface method 'IA<string>.F5<T51, T52>()'. Consider using an explicit interface implementation instead. // public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F5").WithArguments("T552", "B.F5<T551, T552>()", "T52", "IA<string>.F5<T51, T52>()").WithLocation(20, 17), // (24,17): warning CS8633: Nullability in constraints for type parameter 'T662' of method 'B.F6<T661, T662>()' doesn't match the constraints for type parameter 'T62' of interface method 'IA<string>.F6<T61, T62>()'. Consider using an explicit interface implementation instead. // public void F6<T661, T662>() where T661 : class where T662 : C1<T661> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F6").WithArguments("T662", "B.F6<T661, T662>()", "T62", "IA<string>.F6<T61, T62>()").WithLocation(24, 17) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", bf2.GetAttributes().Single().ToString()); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); var bf3 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F3"); Assert.Equal("void B.F3<T33>() where T33 : C1<C2?>!", bf3.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); var bf4 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F4"); Assert.Equal("void B.F4<T44>() where T44 : C1<C2!>?", bf4.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } var comp2 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); comp2.VerifyDiagnostics( ); var comp3 = CreateCompilation(new[] { source2 }, references: new[] { comp2.ToMetadataReference() }, options: WithNullable(NullableContextOptions.Warnings), parseOptions: TestOptions.Regular8); comp3.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (8,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA<string>.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA<string>.F2<T2>()").WithLocation(8, 17), // (12,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA<string>.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1<C2?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA<string>.F3<T3>()").WithLocation(12, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'T44' of method 'B.F4<T44>()' doesn't match the constraints for type parameter 'T4' of interface method 'IA<string>.F4<T4>()'. Consider using an explicit interface implementation instead. // public void F4<T44>() where T44 : C1<C2>? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T44", "B.F4<T44>()", "T4", "IA<string>.F4<T4>()").WithLocation(16, 17), // (20,17): warning CS8633: Nullability in constraints for type parameter 'T552' of method 'B.F5<T551, T552>()' doesn't match the constraints for type parameter 'T52' of interface method 'IA<string>.F5<T51, T52>()'. Consider using an explicit interface implementation instead. // public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F5").WithArguments("T552", "B.F5<T551, T552>()", "T52", "IA<string>.F5<T51, T52>()").WithLocation(20, 17), // (20,69): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T551?").WithArguments("9.0").WithLocation(20, 69), // (51,73): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F6<T6661, T6662>() where T6661 : class where T6662 : C1<T6661?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T6661?").WithArguments("9.0").WithLocation(51, 73) ); var comp4 = CreateCompilation(new[] { source1 }); var comp5 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp4.ToMetadataReference() }); comp5.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T11' of method 'B.F1<T11>()' doesn't match the constraints for type parameter 'T1' of interface method 'IA<string>.F1<T1>()'. Consider using an explicit interface implementation instead. // public void F1<T11>() where T11 : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("T11", "B.F1<T11>()", "T1", "IA<string>.F1<T1>()").WithLocation(4, 17), // (24,17): warning CS8633: Nullability in constraints for type parameter 'T662' of method 'B.F6<T661, T662>()' doesn't match the constraints for type parameter 'T62' of interface method 'IA<string>.F6<T61, T62>()'. Consider using an explicit interface implementation instead. // public void F6<T661, T662>() where T661 : class where T662 : C1<T661> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F6").WithArguments("T662", "B.F6<T661, T662>()", "T62", "IA<string>.F6<T61, T62>()").WithLocation(24, 17) ); } [Fact] public void Constraints_36() { var source1 = @" public interface IA { void F1<T1>() where T1 : class?, IB, IC?; void F2<T2>() where T2 : class, IB?, IC?; void F3<T3>() where T3 : class?, IB?, IC; void F4<T41, T42>() where T41 : class where T42 : T41?, IB, IC?; void F5<T51, T52>() where T51 : class where T52 : T51, IB?, IC?; void F6<T61, T62>() where T61 : class where T62 : T61?, IB?, IC; void F7<T71, T72>() where T71 : class? where T72 : T71, IB, IC?; void F8<T81, T82>() where T81 : class where T82 : T81, IB?, IC?; void F9<T91, T92>() where T91 : class? where T92 : T91, IB?, IC; } public interface IB {} public interface IC {} "; var source2 = @" class B : IA { public void F1<T11>() where T11 : class, IB, IC { } public void F2<T22>() where T22 : class, IB, IC { } public void F3<T33>() where T33 : class, IB, IC { } public void F4<T441, T442>() where T441 : class where T442 : T441, IB, IC { } public void F5<T551, T552>() where T551 : class where T552 : T551, IB, IC { } public void F6<T661, T662>() where T661 : class where T662 : T661, IB, IC { } public void F7<T771, T772>() where T771 : class where T772 : T771, IB, IC { } public void F8<T881, T882>() where T881 : class where T882 : T881, IB, IC { } public void F9<T991, T992>() where T991 : class where T992 : T991, IB, IC { } } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); var expected = new[] { // (28,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : class where T772 : T771, IB, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(28, 17), // (36,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : class where T992 : T991, IB, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(36, 17) }; comp2.VerifyDiagnostics(expected); var comp3 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp3.VerifyDiagnostics(expected); var comp4 = CreateCompilation(new[] { source2 }, options: WithNullableDisable(), references: new[] { comp1.ToMetadataReference() }); comp4.VerifyDiagnostics(); var comp5 = CreateCompilation(new[] { source2 }, options: WithNullableDisable(), references: new[] { comp1.EmitToImageReference() }); comp5.VerifyDiagnostics(); var comp6 = CreateCompilation(new[] { source1 }, options: WithNullableDisable(), parseOptions: TestOptions.Regular8); comp6.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (7,55): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F4<T41, T42>() where T41 : class where T42 : T41?, IB, IC?; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T41?").WithArguments("9.0").WithLocation(7, 55), // (9,55): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F6<T61, T62>() where T61 : class where T62 : T61?, IB?, IC; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T61?").WithArguments("9.0").WithLocation(9, 55) ); var comp7 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp6.ToMetadataReference() }); comp7.VerifyDiagnostics(expected); var comp9 = CreateCompilation(new[] { source2 }, options: WithNullableDisable(), references: new[] { comp6.ToMetadataReference() }); comp9.VerifyDiagnostics(); } [Fact] public void Constraints_37() { var source = @" public interface IA { void F1<T1>() where T1 : class, IB, IC; void F2<T2>() where T2 : class, IB, IC; void F3<T3>() where T3 : class, IB, IC; void F4<T41, T42>() where T41 : class where T42 : T41, IB, IC; void F5<T51, T52>() where T51 : class where T52 : T51, IB, IC; void F6<T61, T62>() where T61 : class where T62 : T61, IB, IC; void F7<T71, T72>() where T71 : class where T72 : T71, IB, IC; void F8<T81, T82>() where T81 : class where T82 : T81, IB, IC; void F9<T91, T92>() where T91 : class where T92 : T91, IB, IC; } public interface IB {} public interface IC {} class B : IA { public void F1<T11>() where T11 : class?, IB, IC? { } public void F2<T22>() where T22 : class, IB?, IC? { } public void F3<T33>() where T33 : class?, IB?, IC { } public void F4<T441, T442>() where T441 : class where T442 : T441?, IB, IC? { } public void F5<T551, T552>() where T551 : class where T552 : T551, IB?, IC? { } public void F6<T661, T662>() where T661 : class where T662 : T661?, IB?, IC { } public void F7<T771, T772>() where T771 : class? where T772 : T771, IB, IC? { } public void F8<T881, T882>() where T881 : class where T882 : T881, IB?, IC? { } public void F9<T991, T992>() where T991 : class? where T992 : T991, IB?, IC { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (55,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : class? where T992 : T991, IB?, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(55, 17), // (47,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : class? where T772 : T771, IB, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(47, 17) ); } [Fact] public void Constraints_38() { var source = @" public interface IA { void F1<T1>() where T1 : ID?, IB, IC?; void F2<T2>() where T2 : ID, IB?, IC?; void F3<T3>() where T3 : ID?, IB?, IC; void F4<T41, T42>() where T41 : ID where T42 : T41?, IB, IC?; void F5<T51, T52>() where T51 : ID where T52 : T51, IB?, IC?; void F6<T61, T62>() where T61 : ID where T62 : T61?, IB?, IC; void F7<T71, T72>() where T71 : ID? where T72 : T71, IB, IC?; void F8<T81, T82>() where T81 : ID where T82 : T81, IB?, IC?; void F9<T91, T92>() where T91 : ID? where T92 : T91, IB?, IC; } public interface IB {} public interface IC {} public interface ID {} class B : IA { public void F1<T11>() where T11 : ID, IB, IC { } public void F2<T22>() where T22 : ID, IB, IC { } public void F3<T33>() where T33 : ID, IB, IC { } public void F4<T441, T442>() where T441 : ID where T442 : T441, IB, IC { } public void F5<T551, T552>() where T551 : ID where T552 : T551, IB, IC { } public void F6<T661, T662>() where T661 : ID where T662 : T661, IB, IC { } public void F7<T771, T772>() where T771 : ID where T772 : T771, IB, IC { } public void F8<T881, T882>() where T881 : ID where T882 : T881, IB, IC { } public void F9<T991, T992>() where T991 : ID where T992 : T991, IB, IC { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp1.VerifyDiagnostics( // (7,52): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F4<T41, T42>() where T41 : ID where T42 : T41?, IB, IC?; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T41?").WithArguments("9.0").WithLocation(7, 52), // (9,52): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F6<T61, T62>() where T61 : ID where T62 : T61?, IB?, IC; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T61?").WithArguments("9.0").WithLocation(9, 52), // (58,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : ID where T992 : T991, IB, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(58, 17), // (50,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : ID where T772 : T771, IB, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(50, 17) ); } [Fact] public void Constraints_39() { var source = @" public interface IA { void F1<T1>() where T1 : ID, IB, IC; void F2<T2>() where T2 : ID, IB, IC; void F3<T3>() where T3 : ID, IB, IC; void F4<T41, T42>() where T41 : ID where T42 : T41, IB, IC; void F5<T51, T52>() where T51 : ID where T52 : T51, IB, IC; void F6<T61, T62>() where T61 : ID where T62 : T61, IB, IC; void F7<T71, T72>() where T71 : ID where T72 : T71, IB, IC; void F8<T81, T82>() where T81 : ID where T82 : T81, IB, IC; void F9<T91, T92>() where T91 : ID where T92 : T91, IB, IC; } public interface IB {} public interface IC {} public interface ID {} class B : IA { public void F1<T11>() where T11 : ID?, IB, IC? { } public void F2<T22>() where T22 : ID, IB?, IC? { } public void F3<T33>() where T33 : ID?, IB?, IC { } public void F4<T441, T442>() where T441 : ID where T442 : T441?, IB, IC? { } public void F5<T551, T552>() where T551 : ID where T552 : T551, IB?, IC? { } public void F6<T661, T662>() where T661 : ID where T662 : T661?, IB?, IC { } public void F7<T771, T772>() where T771 : ID? where T772 : T771, IB, IC? { } public void F8<T881, T882>() where T881 : ID where T882 : T881, IB?, IC? { } public void F9<T991, T992>() where T991 : ID? where T992 : T991, IB?, IC { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp1.VerifyDiagnostics( // (38,63): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F4<T441, T442>() where T441 : ID where T442 : T441?, IB, IC? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T441?").WithArguments("9.0").WithLocation(38, 63), // (46,63): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F6<T661, T662>() where T661 : ID where T662 : T661?, IB?, IC Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T661?").WithArguments("9.0").WithLocation(46, 63), // (58,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : ID? where T992 : T991, IB?, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(58, 17), // (50,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : ID? where T772 : T771, IB, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(50, 17) ); } [Fact] public void Constraints_40() { var source = @" public interface IA { void F1<T1>() where T1 : D?, IB, IC?; void F2<T2>() where T2 : D, IB?, IC?; void F3<T3>() where T3 : D?, IB?, IC; void F4<T41, T42>() where T41 : D where T42 : T41?, IB, IC?; void F5<T51, T52>() where T51 : D where T52 : T51, IB?, IC?; void F6<T61, T62>() where T61 : D where T62 : T61?, IB?, IC; void F7<T71, T72>() where T71 : D? where T72 : T71, IB, IC?; void F8<T81, T82>() where T81 : D where T82 : T81, IB?, IC?; void F9<T91, T92>() where T91 : D? where T92 : T91, IB?, IC; } public interface IB {} public interface IC {} public class D {} class B : IA { public void F1<T11>() where T11 : D, IB, IC { } public void F2<T22>() where T22 : D, IB, IC { } public void F3<T33>() where T33 : D, IB, IC { } public void F4<T441, T442>() where T441 : D where T442 : T441, IB, IC { } public void F5<T551, T552>() where T551 : D where T552 : T551, IB, IC { } public void F6<T661, T662>() where T661 : D where T662 : T661, IB, IC { } public void F7<T771, T772>() where T771 : D where T772 : T771, IB, IC { } public void F8<T881, T882>() where T881 : D where T882 : T881, IB, IC { } public void F9<T991, T992>() where T991 : D where T992 : T991, IB, IC { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (58,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : D where T992 : T991, IB, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(58, 17), // (50,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : D where T772 : T771, IB, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(50, 17) ); } [Fact] public void Constraints_41() { var source = @" public interface IA { void F1<T1>() where T1 : D, IB, IC; void F2<T2>() where T2 : D, IB, IC; void F3<T3>() where T3 : D, IB, IC; void F4<T41, T42>() where T41 : D where T42 : T41, IB, IC; void F5<T51, T52>() where T51 : D where T52 : T51, IB, IC; void F6<T61, T62>() where T61 : D where T62 : T61, IB, IC; void F7<T71, T72>() where T71 : D where T72 : T71, IB, IC; void F8<T81, T82>() where T81 : D where T82 : T81, IB, IC; void F9<T91, T92>() where T91 : D where T92 : T91, IB, IC; } public interface IB {} public interface IC {} public class D {} class B : IA { public void F1<T11>() where T11 : D?, IB, IC? { } public void F2<T22>() where T22 : D, IB?, IC? { } public void F3<T33>() where T33 : D?, IB?, IC { } public void F4<T441, T442>() where T441 : D where T442 : T441?, IB, IC? { } public void F5<T551, T552>() where T551 : D where T552 : T551, IB?, IC? { } public void F6<T661, T662>() where T661 : D where T662 : T661?, IB?, IC { } public void F7<T771, T772>() where T771 : D? where T772 : T771, IB, IC? { } public void F8<T881, T882>() where T881 : D where T882 : T881, IB?, IC? { } public void F9<T991, T992>() where T991 : D? where T992 : T991, IB?, IC { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (58,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : D? where T992 : T991, IB?, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(58, 17), // (50,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : D? where T772 : T771, IB, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(50, 17) ); } [Fact] public void Constraints_42() { var source = @" public interface IA { void F1<T1>() where T1 : class?, IB?, IC?; void F2<T2>() where T2 : class?, IB?, IC?; void F3<T3>() where T3 : class?, IB?, IC?; void F4<T41, T42>() where T41 : class? where T42 : T41, IB?, IC?; void F5<T51, T52>() where T51 : class? where T52 : T51, IB?, IC?; void F6<T61, T62>() where T61 : class? where T62 : T61, IB?, IC?; void F7<T71, T72>() where T71 : class where T72 : T71?, IB?, IC?; void F8<T81, T82>() where T81 : class where T82 : T81?, IB?, IC?; void F9<T91, T92>() where T91 : class where T92 : T91?, IB?, IC?; } public interface IB {} public interface IC {} class B : IA { public void F1<T11>() where T11 : class?, IB?, IC? { } public void F2<T22>() where T22 : class?, IB?, IC? { } public void F3<T33>() where T33 : class?, IB?, IC? { } public void F4<T441, T442>() where T441 : class where T442 : T441?, IB?, IC? { } public void F5<T551, T552>() where T551 : class where T552 : T551?, IB?, IC? { } public void F6<T661, T662>() where T661 : class where T662 : T661?, IB?, IC? { } public void F7<T771, T772>() where T771 : class? where T772 : T771, IB?, IC? { } public void F8<T881, T882>() where T881 : class? where T882 : T881, IB?, IC? { } public void F9<T991, T992>() where T991 : class? where T992 : T991, IB?, IC? { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (55,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : class? where T992 : T991, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(55, 17), // (35,17): warning CS8633: Nullability in constraints for type parameter 'T441' of method 'B.F4<T441, T442>()' doesn't match the constraints for type parameter 'T41' of interface method 'IA.F4<T41, T42>()'. Consider using an explicit interface implementation instead. // public void F4<T441, T442>() where T441 : class where T442 : T441?, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T441", "B.F4<T441, T442>()", "T41", "IA.F4<T41, T42>()").WithLocation(35, 17), // (39,17): warning CS8633: Nullability in constraints for type parameter 'T551' of method 'B.F5<T551, T552>()' doesn't match the constraints for type parameter 'T51' of interface method 'IA.F5<T51, T52>()'. Consider using an explicit interface implementation instead. // public void F5<T551, T552>() where T551 : class where T552 : T551?, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F5").WithArguments("T551", "B.F5<T551, T552>()", "T51", "IA.F5<T51, T52>()").WithLocation(39, 17), // (43,17): warning CS8633: Nullability in constraints for type parameter 'T661' of method 'B.F6<T661, T662>()' doesn't match the constraints for type parameter 'T61' of interface method 'IA.F6<T61, T62>()'. Consider using an explicit interface implementation instead. // public void F6<T661, T662>() where T661 : class where T662 : T661?, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F6").WithArguments("T661", "B.F6<T661, T662>()", "T61", "IA.F6<T61, T62>()").WithLocation(43, 17), // (47,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : class? where T772 : T771, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(47, 17), // (51,17): warning CS8633: Nullability in constraints for type parameter 'T881' of method 'B.F8<T881, T882>()' doesn't match the constraints for type parameter 'T81' of interface method 'IA.F8<T81, T82>()'. Consider using an explicit interface implementation instead. // public void F8<T881, T882>() where T881 : class? where T882 : T881, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F8").WithArguments("T881", "B.F8<T881, T882>()", "T81", "IA.F8<T81, T82>()").WithLocation(51, 17) ); } [Fact] public void Constraints_43() { var source = @" public interface IA { void F7<T71, T72>() where T71 : class where T72 : T71?, IB?, IC?; void F8<T81, T82>() where T81 : class where T82 : T81?, IB?, IC?; void F9<T91, T92>() where T91 : class where T92 : T91?, IB?, IC?; } public interface IB {} public interface IC {} class B : IA { public void F7<T771, T772>() where T771 : class? where T772 : T771?, IB?, IC? { } public void F8<T881, T882>() where T881 : class? where T882 : T881?, IB?, IC? { } public void F9<T991, T992>() where T991 : class? where T992 : T991?, IB?, IC? { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp1.VerifyDiagnostics( // (25,67): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F9<T991, T992>() where T991 : class? where T992 : T991?, IB?, IC? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T991?").WithArguments("9.0").WithLocation(25, 67), // (21,67): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F8<T881, T882>() where T881 : class? where T882 : T881?, IB?, IC? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T881?").WithArguments("9.0").WithLocation(21, 67), // (17,67): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F7<T771, T772>() where T771 : class? where T772 : T771?, IB?, IC? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T771?").WithArguments("9.0").WithLocation(17, 67), // (25,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : class? where T992 : T991?, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(25, 17), // (21,17): warning CS8633: Nullability in constraints for type parameter 'T881' of method 'B.F8<T881, T882>()' doesn't match the constraints for type parameter 'T81' of interface method 'IA.F8<T81, T82>()'. Consider using an explicit interface implementation instead. // public void F8<T881, T882>() where T881 : class? where T882 : T881?, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F8").WithArguments("T881", "B.F8<T881, T882>()", "T81", "IA.F8<T81, T82>()").WithLocation(21, 17), // (17,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : class? where T772 : T771?, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(17, 17) ); } [Fact] public void Constraints_44() { var source1 = @" public interface IA { void F1<T1>() where T1 : class?, IB?; void F2<T2>() where T2 : class, IB?; void F3<T3>() where T3 : C1, IB?; void F4<T4>() where T4 : C1?, IB?; } public class C1 {} public interface IB {} "; var source2 = @" class B : IA { public void F1<T11>() where T11 : class, IB? { } public void F2<T22>() where T22 : class?, IB? { } public void F3<T33>() where T33 : C1?, IB? { } public void F4<T44>() where T44 : C1, IB? { } } class D : IA { public void F1<T111>() where T111 : class?, IB? { } public void F2<T222>() where T222 : class, IB? { } public void F3<T333>() where T333 : C1, IB? { } public void F4<T444>() where T444 : C1?, IB? { } } "; var comp1 = CreateCompilation(new[] { source2, source1 }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T11' of method 'B.F1<T11>()' doesn't match the constraints for type parameter 'T1' of interface method 'IA.F1<T1>()'. Consider using an explicit interface implementation instead. // public void F1<T11>() where T11 : class, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("T11", "B.F1<T11>()", "T1", "IA.F1<T1>()").WithLocation(4, 17), // (8,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA.F2<T2>()").WithLocation(8, 17), // (12,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA.F3<T3>()").WithLocation(12, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'T44' of method 'B.F4<T44>()' doesn't match the constraints for type parameter 'T4' of interface method 'IA.F4<T4>()'. Consider using an explicit interface implementation instead. // public void F4<T44>() where T44 : C1, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T44", "B.F4<T44>()", "T4", "IA.F4<T4>()").WithLocation(16, 17) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.True(t11.IsNotNullable); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.False(t22.IsNotNullable); var bf3 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F3"); TypeParameterSymbol t33 = bf3.TypeParameters[0]; Assert.False(t33.IsNotNullable); var bf4 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F4"); TypeParameterSymbol t44 = bf4.TypeParameters[0]; Assert.True(t44.IsNotNullable); } var comp2 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); comp2.VerifyDiagnostics( ); var comp3 = CreateCompilation(new[] { source2 }, references: new[] { comp2.ToMetadataReference() }, options: WithNullable(NullableContextOptions.Warnings)); comp3.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (8,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA.F2<T2>()").WithLocation(8, 17), // (12,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA.F3<T3>()").WithLocation(12, 17) ); symbolValidator2(comp3.SourceModule); void symbolValidator2(ModuleSymbol m) { var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.Null(t11.IsNotNullable); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.False(t22.IsNotNullable); var bf3 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F3"); TypeParameterSymbol t33 = bf3.TypeParameters[0]; Assert.False(t33.IsNotNullable); var bf4 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F4"); TypeParameterSymbol t44 = bf4.TypeParameters[0]; Assert.Null(t44.IsNotNullable); } var comp4 = CreateCompilation(new[] { source1 }); var comp5 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp4.ToMetadataReference() }); comp5.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T11' of method 'B.F1<T11>()' doesn't match the constraints for type parameter 'T1' of interface method 'IA.F1<T1>()'. Consider using an explicit interface implementation instead. // public void F1<T11>() where T11 : class, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("T11", "B.F1<T11>()", "T1", "IA.F1<T1>()").WithLocation(4, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'T44' of method 'B.F4<T44>()' doesn't match the constraints for type parameter 'T4' of interface method 'IA.F4<T4>()'. Consider using an explicit interface implementation instead. // public void F4<T44>() where T44 : C1, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T44", "B.F4<T44>()", "T4", "IA.F4<T4>()").WithLocation(16, 17) ); symbolValidator1(comp5.SourceModule); var comp6 = CreateCompilation(new[] { source2 }, references: new[] { comp4.ToMetadataReference() }); comp6.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( ); symbolValidator2(comp6.SourceModule); } [Fact] public void Constraints_45() { var source1 = @" public interface IA { void F2<T2>() where T2 : class?, IB; void F3<T3>() where T3 : C1?, IB; } public class C1 {} public interface IB {} "; var source2 = @" class B : IA { public void F2<T22>() where T22 : class?, IB? { } public void F3<T33>() where T33 : C1?, IB? { } } class D : IA { public void F2<T222>() where T222 : class?, IB { } public void F3<T333>() where T333 : C1?, IB { } } "; var comp1 = CreateCompilation(new[] { source2, source1 }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA.F2<T2>()").WithLocation(4, 17), // (8,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA.F3<T3>()").WithLocation(8, 17) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("D.F2"); TypeParameterSymbol t222 = bf2.TypeParameters[0]; Assert.True(t222.IsNotNullable); var bf3 = (MethodSymbol)m.GlobalNamespace.GetMember("D.F3"); TypeParameterSymbol t333 = bf3.TypeParameters[0]; Assert.True(t333.IsNotNullable); } var comp2 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); comp2.VerifyDiagnostics( ); var comp3 = CreateCompilation(new[] { source2 }, references: new[] { comp2.ToMetadataReference() }, options: WithNullable(NullableContextOptions.Warnings)); comp3.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA.F2<T2>()").WithLocation(4, 17), // (8,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA.F3<T3>()").WithLocation(8, 17) ); symbolValidator2(comp3.SourceModule); void symbolValidator2(ModuleSymbol m) { var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("D.F2"); TypeParameterSymbol t222 = bf2.TypeParameters[0]; Assert.Null(t222.IsNotNullable); var bf3 = (MethodSymbol)m.GlobalNamespace.GetMember("D.F3"); TypeParameterSymbol t333 = bf3.TypeParameters[0]; Assert.Null(t333.IsNotNullable); } var comp4 = CreateCompilation(new[] { source1 }); var comp5 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp4.ToMetadataReference() }); comp5.VerifyDiagnostics( ); symbolValidator1(comp5.SourceModule); var comp6 = CreateCompilation(new[] { source2 }, references: new[] { comp4.ToMetadataReference() }); comp6.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( ); symbolValidator2(comp6.SourceModule); } [Fact] public void Constraints_46() { var source = @" class B { public static void F1<T1>() where T1 : notnull { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>() where T1 : notnull", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(f1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", f1.GetAttributes().Single().ToString()); } TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.IsReferenceType); Assert.True(t1.IsNotNullable); var attributes = t1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_47() { var source = @" class B { public static void F1<T1>() where T1 : notnull { } }"; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>() where T1 : notnull", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(f1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", f1.GetAttributes().Single().ToString()); } TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.IsReferenceType); Assert.True(t1.HasNotNullConstraint); Assert.True(t1.IsNotNullable); var attributes = t1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_48() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : object? { } public static void F2<T2>(T2? t2) where T2 : System.Object? { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F1<T1>(T1? t1) where T1 : object? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T1?").WithArguments("9.0").WithLocation(4, 31), // (4,50): error CS0702: Constraint cannot be special class 'object' // public static void F1<T1>(T1? t1) where T1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(4, 50), // (8,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F2<T2>(T2? t2) where T2 : System.Object? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(8, 31), // (8,50): error CS0702: Constraint cannot be special class 'object' // public static void F2<T2>(T2? t2) where T2 : System.Object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "System.Object?").WithArguments("object").WithLocation(8, 50) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1)", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.IsReferenceType); Assert.False(t1.IsNotNullable); Assert.Empty(t1.GetAttributes()); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T2>(T2? t2)", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.False(t2.IsReferenceType); Assert.False(t2.IsNotNullable); Assert.Empty(t2.GetAttributes()); } [Fact] public void Constraints_49() { var source = @" class B { public static void F1<T1>() where T1 : notnull { } }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7_3); var expected = new[] { // (4,44): error CS8652: The feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // public static void F1<T1>() where T1 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(4, 44) }; comp.VerifyDiagnostics(expected); { var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>() where T1 : notnull", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.IsReferenceType); Assert.True(t1.IsNotNullable); Assert.Empty(t1.GetAttributes()); } comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); comp.VerifyDiagnostics(expected .Concat(new[] { // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.3", "8.0").WithLocation(1, 1), }).ToArray() ); { var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>() where T1 : notnull", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.IsReferenceType); Assert.True(t1.IsNotNullable); Assert.Empty(t1.GetAttributes()); } } [Fact] public void Constraints_50() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : notnull { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F1<T1>(T1? t1) where T1 : notnull Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T1?").WithArguments("9.0").WithLocation(4, 31) ); } [Fact] public void Constraints_51() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : struct, notnull { } public static void F2<T2>(T2? t2) where T2 : notnull, struct { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,59): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F2<T2>(T2? t2) where T2 : notnull, struct Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(8, 59), // (4,58): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F1<T1>(T1? t1) where T1 : struct, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(4, 58) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : struct", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsValueType); Assert.True(t1.HasNotNullConstraint); Assert.True(t1.IsNotNullable); Assert.Empty(t1.GetAttributes()); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T2>(T2? t2) where T2 : struct", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.IsValueType); Assert.True(t2.HasNotNullConstraint); Assert.True(t2.IsNotNullable); Assert.Empty(t2.GetAttributes()); } [Fact] public void Constraints_52() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : class, notnull { } public static void F2<T2>(T2? t2) where T2 : notnull, class { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,57): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F1<T1>(T1? t1) where T1 : class, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(4, 57), // (8,59): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F2<T2>(T2? t2) where T2 : notnull, class Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(8, 59) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : class!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.True(t1.IsNotNullable); Assert.Empty(t1.GetAttributes()); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T2>(T2? t2) where T2 : class!", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.IsReferenceType); Assert.True(t2.IsNotNullable); Assert.Empty(t2.GetAttributes()); } [Fact] public void Constraints_53() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : class?, notnull { } public static void F2<T2>(T2? t2) where T2 : notnull, class? { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); Assert.True(((MethodSymbol)comp.SourceModule.GlobalNamespace.GetMember("B.F1")).TypeParameters[0].IsNotNullable); comp.VerifyDiagnostics( // (4,58): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F1<T1>(T1? t1) where T1 : class?, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(4, 58), // (8,59): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F2<T2>(T2? t2) where T2 : notnull, class? Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class?").WithLocation(8, 59) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : class?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.True(t1.IsNotNullable); Assert.Empty(t1.GetAttributes()); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T2>(T2? t2) where T2 : class?", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.IsReferenceType); Assert.True(t2.IsNotNullable); Assert.Empty(t2.GetAttributes()); } [Fact] public void Constraints_54() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : class?, B { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F1<T1>(T1? t1) where T1 : class?, B Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T1?").WithArguments("9.0").WithLocation(4, 31), // (4,58): error CS0450: 'B': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F1<T1>(T1? t1) where T1 : class?, B Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "B").WithArguments("B").WithLocation(4, 58) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : class?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.False(t1.IsNotNullable); } [Fact] public void Constraints_55() { var source = @" interface I<TI> { void F1<TF1>(TF1 x) where TF1 : TI; } class A : I<object> { void I<object>.F1<TF1A>(TF1A x) {} } class B : I<object?> { void I<object?>.F1<TF1B>(TF1B x) {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var af1 = (MethodSymbol)m.GlobalNamespace.GetMember("A.I<System.Object>.F1"); Assert.Equal("I<System.Object>.F1", af1.Name); Assert.Equal("I<System.Object>.F1", af1.MetadataName); if (isSource) { Assert.Equal("void A.I<System.Object!>.F1<TF1A>(TF1A x) where TF1A : System.Object!", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void A.I<System.Object>.F1<TF1A>(TF1A x) where TF1A : System.Object!", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", af1.GetAttributes().Single().ToString()); } TypeParameterSymbol at1 = af1.TypeParameters[0]; Assert.False(at1.IsReferenceType); Assert.True(at1.IsNotNullable); if (isSource) { Assert.Empty(at1.GetAttributes()); Assert.Equal("void I<System.Object!>.F1<TF1>(TF1 x) where TF1 : System.Object!", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(0)", at1.GetAttributes().Single().ToString()); var impl = af1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I<System.Object>.F1<TF1>(TF1 x)", impl.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(impl.TypeParameters[0].IsNotNullable); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.I<System.Object>.F1"); Assert.Equal("I<System.Object>.F1", bf1.Name); Assert.Equal("I<System.Object>.F1", bf1.MetadataName); if (isSource) { Assert.Equal("void B.I<System.Object?>.F1<TF1B>(TF1B x)", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void B.I<System.Object>.F1<TF1B>(TF1B x)", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = bf1.TypeParameters[0]; Assert.False(tf1.IsReferenceType); Assert.False(tf1.IsNotNullable); if (isSource) { Assert.Empty(tf1.GetAttributes()); Assert.Equal("void I<System.Object?>.F1<TF1>(TF1 x)", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { var attributes = tf1.GetAttributes(); Assert.Equal(1, attributes.Length); Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", attributes[0].ToString()); var impl = bf1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I<System.Object>.F1<TF1>(TF1 x)", impl.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(impl.TypeParameters[0].IsNotNullable); } } } [Fact] public void Constraints_56() { var source = @" interface I<TI> { void F1<TF1>(TF1 x) where TF1 : TI; } class A : I<A> { void I<A>.F1<TF1A>(TF1A x) {} } class B : I<A?> { void I<A?>.F1<TF1B>(TF1B x) {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var af1 = (MethodSymbol)m.GlobalNamespace.GetMember("A.I<A>.F1"); Assert.Equal("I<A>.F1", af1.Name); Assert.Equal("I<A>.F1", af1.MetadataName); if (isSource) { Assert.Equal("void A.I<A!>.F1<TF1A>(TF1A! x) where TF1A : A!", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void A.I<A>.F1<TF1A>(TF1A! x) where TF1A : A!", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", af1.GetAttributes().Single().ToString()); } TypeParameterSymbol at1 = af1.TypeParameters[0]; Assert.True(at1.IsReferenceType); Assert.True(at1.IsNotNullable); if (isSource) { Assert.Empty(at1.GetAttributes()); Assert.Equal("void I<A!>.F1<TF1>(TF1 x) where TF1 : A!", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(0)", at1.GetAttributes().Single().ToString()); Assert.Equal("void I<A>.F1<TF1>(TF1 x) where TF1 : A", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.I<A>.F1"); Assert.Equal("I<A>.F1", bf1.Name); Assert.Equal("I<A>.F1", bf1.MetadataName); if (isSource) { Assert.Equal("void B.I<A?>.F1<TF1B>(TF1B x) where TF1B : A?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void B.I<A>.F1<TF1B>(TF1B x) where TF1B : A?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Empty(bf1.GetAttributes()); } TypeParameterSymbol tf1 = bf1.TypeParameters[0]; Assert.True(tf1.IsReferenceType); Assert.False(tf1.IsNotNullable); if (isSource) { Assert.Empty(tf1.GetAttributes()); Assert.Equal("void I<A?>.F1<TF1>(TF1 x) where TF1 : A?", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Empty(tf1.GetAttributes()); Assert.Equal("void I<A>.F1<TF1>(TF1 x) where TF1 : A", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } } } [Fact] public void Constraints_57() { var source = @" interface I<TI> { void F1<TF1>(TF1 x) where TF1 : class?, TI; } class A : I<object> { void I<object>.F1<TF1A>(TF1A x) {} } class B : I<object?> { void I<object?>.F1<TF1B>(TF1B x) {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var af1 = (MethodSymbol)m.GlobalNamespace.GetMember("A.I<System.Object>.F1"); Assert.Equal("I<System.Object>.F1", af1.Name); Assert.Equal("I<System.Object>.F1", af1.MetadataName); if (isSource) { Assert.Equal("void A.I<System.Object!>.F1<TF1A>(TF1A! x) where TF1A : class?, System.Object!", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void A.I<System.Object>.F1<TF1A>(TF1A! x) where TF1A : class?, System.Object!", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } TypeParameterSymbol at1 = af1.TypeParameters[0]; Assert.True(at1.IsReferenceType); Assert.True(at1.IsNotNullable); if (isSource) { Assert.Equal("void I<System.Object!>.F1<TF1>(TF1 x) where TF1 : class?, System.Object!", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void I<System.Object>.F1<TF1>(TF1 x) where TF1 : class?, System.Object", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.I<System.Object>.F1"); Assert.Equal("I<System.Object>.F1", bf1.Name); Assert.Equal("I<System.Object>.F1", bf1.MetadataName); if (isSource) { Assert.Equal("void B.I<System.Object?>.F1<TF1B>(TF1B x) where TF1B : class?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void B.I<System.Object>.F1<TF1B>(TF1B x) where TF1B : class?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } TypeParameterSymbol tf1 = bf1.TypeParameters[0]; Assert.True(tf1.IsReferenceType); Assert.False(tf1.IsNotNullable); if (isSource) { Assert.Equal("void I<System.Object?>.F1<TF1>(TF1 x) where TF1 : class?", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void I<System.Object>.F1<TF1>(TF1 x) where TF1 : class?, System.Object", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } } } [Fact] public void Constraints_58() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : B, notnull { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,53): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F1<T1>(T1? t1) where T1 : B, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(4, 53) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : notnull, B!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.True(t1.IsNotNullable); } [Fact] public void Constraints_59() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : notnull, B? { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : notnull, B?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.True(t1.HasNotNullConstraint); Assert.True(t1.IsNotNullable); } } [Fact] public void Constraints_60() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : notnull, B { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : notnull, B!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.True(t1.IsNotNullable); } [Fact] public void Constraints_61() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : object?, B { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,50): error CS0702: Constraint cannot be special class 'object' // public static void F1<T1>(T1? t1) where T1 : object?, B Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(4, 50) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : B!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.True(t1.IsNotNullable); } [Fact] public void Constraints_62() { var source = @" interface I<TI> { void F1<TF1>(TF1 x) where TF1 : B?, TI; } class A : I<object> { void I<object>.F1<TF1A>(TF1A x) {} } class B : I<object?> { void I<object?>.F1<TF1B>(TF1B x) {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var af1 = (MethodSymbol)m.GlobalNamespace.GetMember("A.I<System.Object>.F1"); Assert.Equal("I<System.Object>.F1", af1.Name); Assert.Equal("I<System.Object>.F1", af1.MetadataName); if (isSource) { Assert.Equal("void A.I<System.Object!>.F1<TF1A>(TF1A! x) where TF1A : System.Object!, B?", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void A.I<System.Object>.F1<TF1A>(TF1A! x) where TF1A : System.Object!, B?", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } TypeParameterSymbol at1 = af1.TypeParameters[0]; Assert.True(at1.IsReferenceType); Assert.True(at1.IsNotNullable); if (isSource) { Assert.Equal("void I<System.Object!>.F1<TF1>(TF1 x) where TF1 : System.Object!, B?", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void I<System.Object>.F1<TF1>(TF1 x) where TF1 : System.Object, B?", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.I<System.Object>.F1"); Assert.Equal("I<System.Object>.F1", bf1.Name); Assert.Equal("I<System.Object>.F1", bf1.MetadataName); if (isSource) { Assert.Equal("void B.I<System.Object?>.F1<TF1B>(TF1B x) where TF1B : B?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void B.I<System.Object>.F1<TF1B>(TF1B x) where TF1B : B?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } TypeParameterSymbol tf1 = bf1.TypeParameters[0]; Assert.True(tf1.IsReferenceType); Assert.False(tf1.IsNotNullable); if (isSource) { Assert.Equal("void I<System.Object?>.F1<TF1>(TF1 x) where TF1 : B?", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void I<System.Object>.F1<TF1>(TF1 x) where TF1 : System.Object, B?", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } } } [Fact] public void Constraints_63() { var source = @" interface I<TI1, TI2> { void F1<TF1>(TF1 x) where TF1 : TI1, TI2; } class A : I<object, B?> { void I<object, B?>.F1<TF1A>(TF1A x) {} } class B : I<object?, B?> { void I<object?, B?>.F1<TF1B>(TF1B x) {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var af1 = (MethodSymbol)m.GlobalNamespace.GetMember("A.I<System.Object,B>.F1"); Assert.Equal("I<System.Object,B>.F1", af1.Name); Assert.Equal("I<System.Object,B>.F1", af1.MetadataName); if (isSource) { Assert.Equal("void A.I<System.Object!, B?>.F1<TF1A>(TF1A! x) where TF1A : System.Object!, B?", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void A.I<System.Object, B>.F1<TF1A>(TF1A! x) where TF1A : System.Object!, B?", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } TypeParameterSymbol at1 = af1.TypeParameters[0]; Assert.True(at1.IsReferenceType); Assert.True(at1.IsNotNullable); if (isSource) { Assert.Equal("void I<System.Object!, B?>.F1<TF1>(TF1 x) where TF1 : System.Object!, B?", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void I<System.Object, B>.F1<TF1>(TF1 x) where TF1 : B", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.I<System.Object,B>.F1"); Assert.Equal("I<System.Object,B>.F1", bf1.Name); Assert.Equal("I<System.Object,B>.F1", bf1.MetadataName); if (isSource) { Assert.Equal("void B.I<System.Object?, B?>.F1<TF1B>(TF1B x) where TF1B : B?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void B.I<System.Object, B>.F1<TF1B>(TF1B x) where TF1B : B?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } TypeParameterSymbol tf1 = bf1.TypeParameters[0]; Assert.True(tf1.IsReferenceType); Assert.False(tf1.IsNotNullable); if (isSource) { Assert.Equal("void I<System.Object?, B?>.F1<TF1>(TF1 x) where TF1 : B?", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void I<System.Object, B>.F1<TF1>(TF1 x) where TF1 : B", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } } } [Fact] public void Constraints_64() { var source = @" interface I1 { void F1<TF1>(); void F2<TF2>() where TF2 : notnull; void F3<TF3>() where TF3 : notnull; void F4<TF4>() where TF4 : I3; void F5<TF5>() where TF5 : I3; void F6<TF6>() where TF6 : I3?; void F7<TF7>() where TF7 : notnull, I3; void F8<TF8>() where TF8 : notnull, I3; void F9<TF9>() where TF9 : notnull, I3; void F10<TF10>() where TF10 : notnull, I3?; void F11<TF11>() where TF11 : notnull, I3?; void F12<TF12>() where TF12 : notnull, I3?; void F13<TF13>() where TF13 : notnull, I3?; } public interface I3 { } class A : I1 { public void F1<TF1A>() where TF1A : notnull {} public void F2<TF2A>() {} public void F3<TF3A>() where TF3A : notnull {} public void F4<TF4A>() where TF4A : notnull, I3 {} public void F5<TF5A>() where TF5A : notnull, I3? {} public void F6<TF6A>() where TF6A : notnull, I3? {} public void F7<TF7A>() where TF7A : I3 {} public void F8<TF8A>() where TF8A : I3? {} public void F9<TF9A>() where TF9A : notnull, I3 {} public void F10<TF10A>() where TF10A : I3 {} public void F11<TF11A>() where TF11A : I3? {} public void F12<TF12A>() where TF12A : notnull, I3 {} public void F13<TF13A>() where TF13A : notnull, I3? {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (25,17): warning CS8633: Nullability in constraints for type parameter 'TF1A' of method 'A.F1<TF1A>()' doesn't match the constraints for type parameter 'TF1' of interface method 'I1.F1<TF1>()'. Consider using an explicit interface implementation instead. // public void F1<TF1A>() where TF1A : notnull Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("TF1A", "A.F1<TF1A>()", "TF1", "I1.F1<TF1>()").WithLocation(25, 17), // (27,17): warning CS8633: Nullability in constraints for type parameter 'TF2A' of method 'A.F2<TF2A>()' doesn't match the constraints for type parameter 'TF2' of interface method 'I1.F2<TF2>()'. Consider using an explicit interface implementation instead. // public void F2<TF2A>() Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("TF2A", "A.F2<TF2A>()", "TF2", "I1.F2<TF2>()").WithLocation(27, 17), // (35,17): warning CS8633: Nullability in constraints for type parameter 'TF6A' of method 'A.F6<TF6A>()' doesn't match the constraints for type parameter 'TF6' of interface method 'I1.F6<TF6>()'. Consider using an explicit interface implementation instead. // public void F6<TF6A>() where TF6A : notnull, I3? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F6").WithArguments("TF6A", "A.F6<TF6A>()", "TF6", "I1.F6<TF6>()").WithLocation(35, 17), // (39,17): warning CS8633: Nullability in constraints for type parameter 'TF8A' of method 'A.F8<TF8A>()' doesn't match the constraints for type parameter 'TF8' of interface method 'I1.F8<TF8>()'. Consider using an explicit interface implementation instead. // public void F8<TF8A>() where TF8A : I3? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F8").WithArguments("TF8A", "A.F8<TF8A>()", "TF8", "I1.F8<TF8>()").WithLocation(39, 17), // (45,17): warning CS8633: Nullability in constraints for type parameter 'TF11A' of method 'A.F11<TF11A>()' doesn't match the constraints for type parameter 'TF11' of interface method 'I1.F11<TF11>()'. Consider using an explicit interface implementation instead. // public void F11<TF11A>() where TF11A : I3? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F11").WithArguments("TF11A", "A.F11<TF11A>()", "TF11", "I1.F11<TF11>()").WithLocation(45, 17) ); } [Fact] public void Constraints_65() { var source1 = @" public interface I1 { void F1<TF1>(); void F2<TF2>() where TF2 : notnull; void F3<TF3>() where TF3 : notnull; void F4<TF4>() where TF4 : I3; void F5<TF5>() where TF5 : I3; void F7<TF7>() where TF7 : notnull, I3; void F8<TF8>() where TF8 : notnull, I3; void F9<TF9>() where TF9 : notnull, I3; } public interface I3 { } "; var source2 = @" class A : I1 { public void F1<TF1A>() where TF1A : notnull {} public void F2<TF2A>() {} public void F3<TF3A>() where TF3A : notnull {} public void F4<TF4A>() where TF4A : notnull, I3 {} public void F5<TF5A>() where TF5A : notnull, I3? {} public void F7<TF7A>() where TF7A : I3 {} public void F8<TF8A>() where TF8A : I3? {} public void F9<TF9A>() where TF9A : notnull, I3 {} } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); foreach (var reference in new[] { comp1.ToMetadataReference(), comp1.EmitToImageReference() }) { var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { reference }); comp2.VerifyDiagnostics( // (6,17): warning CS8633: Nullability in constraints for type parameter 'TF2A' of method 'A.F2<TF2A>()' doesn't match the constraints for type parameter 'TF2' of interface method 'I1.F2<TF2>()'. Consider using an explicit interface implementation instead. // public void F2<TF2A>() Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("TF2A", "A.F2<TF2A>()", "TF2", "I1.F2<TF2>()").WithLocation(6, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'TF8A' of method 'A.F8<TF8A>()' doesn't match the constraints for type parameter 'TF8' of interface method 'I1.F8<TF8>()'. Consider using an explicit interface implementation instead. // public void F8<TF8A>() where TF8A : I3? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F8").WithArguments("TF8A", "A.F8<TF8A>()", "TF8", "I1.F8<TF8>()").WithLocation(16, 17) ); } string il = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot abstract virtual instance void F1<TF1>() cil managed { } // end of method I1::F1 } // end of class I1"; string source3 = @" class A : I1 { public void F1<TF1A>() where TF1A : notnull {} } "; var comp3 = CreateCompilationWithIL(new[] { source3 }, il, options: WithNullableEnable()); comp3.VerifyDiagnostics(); } [Fact] public void Constraints_66() { var source1 = @" public interface I1 { void F1<TF1>(); void F2<TF2>() where TF2 : notnull; void F3<TF3>() where TF3 : notnull; void F4<TF4>() where TF4 : I3; void F7<TF7>() where TF7 : notnull, I3; void F9<TF9>() where TF9 : notnull, I3; void F10<TF10>() where TF10 : notnull, I3?; void F12<TF12>() where TF12 : notnull, I3?; } public interface I3 { } "; var source2 = @" class A : I1 { public void F1<TF1A>() where TF1A : notnull {} public void F2<TF2A>() {} public void F3<TF3A>() where TF3A : notnull {} public void F4<TF4A>() where TF4A : notnull, I3 {} public void F7<TF7A>() where TF7A : I3 {} public void F9<TF9A>() where TF9A : notnull, I3 {} public void F10<TF10A>() where TF10A : I3 {} public void F12<TF12A>() where TF12A : notnull, I3 {} } "; var comp1 = CreateCompilation(source1, options: WithNullableEnable()); foreach (var reference in new[] { comp1.ToMetadataReference(), comp1.EmitToImageReference() }) { var comp2 = CreateCompilation(source2, options: WithNullable(NullableContextOptions.Warnings), references: new[] { reference }); comp2.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'TF1A' of method 'A.F1<TF1A>()' doesn't match the constraints for type parameter 'TF1' of interface method 'I1.F1<TF1>()'. Consider using an explicit interface implementation instead. // public void F1<TF1A>() where TF1A : notnull Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("TF1A", "A.F1<TF1A>()", "TF1", "I1.F1<TF1>()").WithLocation(4, 17) ); } } [Fact] public void Constraints_67() { var source = @" class A { public void F1<TF1>(object x1, TF1 y1, TF1 z1 ) where TF1 : notnull { y1.ToString(); x1 = z1; } public void F2<TF2>(object x2, TF2 y2, TF2 z2 ) where TF2 : class { y2.ToString(); x2 = z2; } public void F3<TF3>(object x3, TF3 y3, TF3 z3 ) where TF3 : class? { y3.ToString(); x3 = z3; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // y3.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y3").WithLocation(18, 9), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = z3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z3").WithLocation(19, 14) ); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_68() { var source = @" #nullable enable class A { } class C<T> where T : A { C<A?> M(C<A?> c1) { return c1; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,11): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // C<A?> M(C<A?> c1) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M").WithArguments("C<T>", "A", "T", "A?").WithLocation(6, 11), // (6,19): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // C<A?> M(C<A?> c1) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "c1").WithArguments("C<T>", "A", "T", "A?").WithLocation(6, 19)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_69() { var source = @" #nullable enable class C<T> where T : notnull { } interface I { C<object?> Property { get; } // 1 C<object?> Method(C<object?> p); // 2 } class C2 : I { public C<object?> Field = new C<object?>(); // 3 C<object?> Property => Field; // 4 C<object?> Method(C<object?> p) => Field; // 5 C<object?> I.Property => Field; // 6 C<object?> I.Method(C<object?> p) => Field; // 7 } delegate C<object?> D(C<object?> p); // 8 "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,16): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> Property { get; } // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Property").WithArguments("C<T>", "T", "object?").WithLocation(6, 16), // (7,16): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> Method(C<object?> p); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Method").WithArguments("C<T>", "T", "object?").WithLocation(7, 16), // (7,34): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> Method(C<object?> p); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("C<T>", "T", "object?").WithLocation(7, 34), // (11,23): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // public C<object?> Field = new C<object?>(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Field").WithArguments("C<T>", "T", "object?").WithLocation(11, 23), // (11,37): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // public C<object?> Field = new C<object?>(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "object?").WithArguments("C<T>", "T", "object?").WithLocation(11, 37), // (12,16): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> Property => Field; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Property").WithArguments("C<T>", "T", "object?").WithLocation(12, 16), // (13,16): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> Method(C<object?> p) => Field; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Method").WithArguments("C<T>", "T", "object?").WithLocation(13, 16), // (13,34): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> Method(C<object?> p) => Field; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("C<T>", "T", "object?").WithLocation(13, 34), // (15,18): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> I.Property => Field; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Property").WithArguments("C<T>", "T", "object?").WithLocation(15, 18), // (16,18): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> I.Method(C<object?> p) => Field; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Method").WithArguments("C<T>", "T", "object?").WithLocation(16, 18), // (16,36): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> I.Method(C<object?> p) => Field; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("C<T>", "T", "object?").WithLocation(16, 36), // (19,12): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // delegate C<object?> D(C<object?> p); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "object?").WithArguments("C<T>", "T", "object?").WithLocation(19, 12), // (19,25): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // delegate C<object?> D(C<object?> p); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "object?").WithArguments("C<T>", "T", "object?").WithLocation(19, 25)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_70() { var source = @" #nullable enable class C<T> where T : class { } interface I { C<object?> Property { get; } // 1 C<object?> Method(C<object?> p); // 2 } class C2 : I { public C<object?> Field = new C<object?>(); // 3 C<object?> Property => Field; // 4 C<object?> Method(C<object?> p) => Field; // 5 C<object?> I.Property => Field; // 6 C<object?> I.Method(C<object?> p) => Field; // 7 } delegate C<object?> D(C<object?> p); // 8 "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,16): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> Property { get; } // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Property").WithArguments("C<T>", "T", "object?").WithLocation(6, 16), // (7,16): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> Method(C<object?> p); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Method").WithArguments("C<T>", "T", "object?").WithLocation(7, 16), // (7,34): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> Method(C<object?> p); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "p").WithArguments("C<T>", "T", "object?").WithLocation(7, 34), // (11,23): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // public C<object?> Field = new C<object?>(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Field").WithArguments("C<T>", "T", "object?").WithLocation(11, 23), // (11,37): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // public C<object?> Field = new C<object?>(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T>", "T", "object?").WithLocation(11, 37), // (12,16): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> Property => Field; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Property").WithArguments("C<T>", "T", "object?").WithLocation(12, 16), // (13,16): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> Method(C<object?> p) => Field; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Method").WithArguments("C<T>", "T", "object?").WithLocation(13, 16), // (13,34): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> Method(C<object?> p) => Field; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "p").WithArguments("C<T>", "T", "object?").WithLocation(13, 34), // (15,18): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> I.Property => Field; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Property").WithArguments("C<T>", "T", "object?").WithLocation(15, 18), // (16,18): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> I.Method(C<object?> p) => Field; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Method").WithArguments("C<T>", "T", "object?").WithLocation(16, 18), // (16,36): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> I.Method(C<object?> p) => Field; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "p").WithArguments("C<T>", "T", "object?").WithLocation(16, 36), // (19,12): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // delegate C<object?> D(C<object?> p); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T>", "T", "object?").WithLocation(19, 12), // (19,25): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // delegate C<object?> D(C<object?> p); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T>", "T", "object?").WithLocation(19, 25)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_71() { var source = @" #nullable enable #pragma warning disable 8019 using static C1<A>; using static C1<A?>; // 1 using static C2<A>; using static C2<A?>; using static C3<A>; // 2 using static C3<A?>; using static C4<A>; using static C4<A?>; class A { } static class C1<T> where T : A { } static class C2<T> where T : A? { } static class C3<T> where T : class { } static class C4<T> where T : class? { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,14): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C1<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // using static C1<A?>; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "C1<A?>").WithArguments("C1<T>", "A", "T", "A?").WithLocation(6, 14), // (10,14): warning CS8634: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C3<T>'. Nullability of type argument 'A?' doesn't match 'class' constraint. // using static C3<A?>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "C3<A?>").WithArguments("C3<T>", "T", "A?").WithLocation(10, 14)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_72() { var source = @" #nullable enable #pragma warning disable 8019 using D1 = C1<A>; using D2 = C1<A?>; // 1 using D3 = C2<A>; using D4 = C2<A?>; using D5 = C3<A>; // 2 using D6 = C3<A?>; using D7 = C4<A>; using D8 = C4<A?>; class A { } static class C1<T> where T : A { } static class C2<T> where T : A? { } static class C3<T> where T : class { } static class C4<T> where T : class? { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,7): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C1<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // using D2 = C1<A?>; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "D2").WithArguments("C1<T>", "A", "T", "A?").WithLocation(6, 7), // (10,7): warning CS8634: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C3<T>'. Nullability of type argument 'A?' doesn't match 'class' constraint. // using D6 = C3<A?>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "D6").WithArguments("C3<T>", "T", "A?").WithLocation(10, 7)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_73() { var source = @" #nullable enable class C<T> { void M1((string, string?) p) { } // 1 void M2((string, string) p) { } void M3(C<(string, string?)> p) { } // 2 void M4(C<(string, string)> p) { } } "; var compilation = CreateCompilation(new[] { Tuple2NonNullable, source }, targetFramework: TargetFramework.Mscorlib46); compilation.VerifyDiagnostics( // (4,31): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // void M1((string, string?) p) { } // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("(T1, T2)", "T2", "string?").WithLocation(4, 31), // (6,34): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // void M3(C<(string, string?)> p) { } // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("(T1, T2)", "T2", "string?").WithLocation(6, 34)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_74() { var source = @" #nullable enable class C<T> where T : notnull { } class D1 { D1((string, string?) p) { } // 1 D1(C<(string, string?)> p) { } // 2 D1(C<string?> p) { } // 3 } class D2 { D2((string, string) p) { } D2(C<(string, string)> p) { } D2(C<string> p) { } } "; var compilation = CreateCompilation(new[] { Tuple2NonNullable, source }, targetFramework: TargetFramework.Mscorlib46); compilation.VerifyDiagnostics( // (5,26): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // D1((string, string?) p) { } // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("(T1, T2)", "T2", "string?").WithLocation(5, 26), // (6,29): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // D1(C<(string, string?)> p) { } // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("(T1, T2)", "T2", "string?").WithLocation(6, 29), // (7,19): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // D1(C<string?> p) { } // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("C<T>", "T", "string?").WithLocation(7, 19)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_75() { var source = @" #nullable enable class C<T> where T : notnull { } class D1 { public static implicit operator D1(C<string> c) => new D1(); public static implicit operator C<string>(D1 D1) => new C<string>(); } class D2 { public static implicit operator D2(C<string?> c) => new D2(); // 1 public static implicit operator C<string?>(D2 D2) => new C<string?>(); // 2, 3 } "; var compilation = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib46); compilation.VerifyDiagnostics( // (9,51): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // public static implicit operator D2(C<string?> c) => new D2(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "c").WithArguments("C<T>", "T", "string?").WithLocation(9, 51), // (10,37): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // public static implicit operator C<string?>(D2 D2) => new C<string?>(); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "C<string?>").WithArguments("C<T>", "T", "string?").WithLocation(10, 37), // (10,64): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // public static implicit operator C<string?>(D2 D2) => new C<string?>(); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("C<T>", "T", "string?").WithLocation(10, 64)); } [Fact] [WorkItem(33303, "https://github.com/dotnet/roslyn/issues/33303")] public void Constraints_76() { var source = @" #nullable enable #pragma warning disable 8600, 219 class C { void TupleLiterals() { string s1 = string.Empty; string? s2 = null; var t1 = (s1, s1); var t2 = (s1, s2); // 1 var t3 = (s2, s1); // 2 var t4 = (s2, s2); // 3, 4 var t5 = ((string)null, s1); // 5 var t6 = ((string)null, s1, s1, s1, s1, s1, s1, (string)null, (string)null); // 6, 7, 8 } } "; var compilation = CreateCompilation(new[] { Tuple2NonNullable, TupleRestNonNullable, source }, targetFramework: TargetFramework.Mscorlib46); compilation.VerifyDiagnostics( // (9,23): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t2 = (s1, s2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "s2").WithArguments("(T1, T2)", "T2", "string?").WithLocation(9, 23), // (10,19): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t3 = (s2, s1); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "s2").WithArguments("(T1, T2)", "T1", "string?").WithLocation(10, 19), // (11,19): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t4 = (s2, s2); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "s2").WithArguments("(T1, T2)", "T1", "string?").WithLocation(11, 19), // (11,23): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t4 = (s2, s2); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "s2").WithArguments("(T1, T2)", "T2", "string?").WithLocation(11, 23), // (12,19): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t5 = ((string)null, s1); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "(string)null").WithArguments("(T1, T2)", "T1", "string?").WithLocation(12, 19), // (13,19): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t6 = ((string)null, s1, s1, s1, s1, s1, s1, (string)null, (string)null); // 6, 7, 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "(string)null").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "T1", "string?").WithLocation(13, 19), // (13,57): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t6 = ((string)null, s1, s1, s1, s1, s1, s1, (string)null, (string)null); // 6, 7, 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "(string)null").WithArguments("(T1, T2)", "T1", "string?").WithLocation(13, 57), // (13,71): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t6 = ((string)null, s1, s1, s1, s1, s1, s1, (string)null, (string)null); // 6, 7, 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "(string)null").WithArguments("(T1, T2)", "T2", "string?").WithLocation(13, 71) ); } [Fact] [WorkItem(33303, "https://github.com/dotnet/roslyn/issues/33303")] public void Constraints_77() { var source = @" using System; #nullable enable #pragma warning disable 168 class C { void TupleTypes() { (string?, string) t1; (string?, string, string, string, string, string, string, string, string?) t2; Type t3 = typeof((string?, string)); Type t4 = typeof((string?, string, string, string, string, string, string, string, string?)); } } "; var compilation = CreateCompilation(new[] { Tuple2NonNullable, TupleRestNonNullable, source }, targetFramework: TargetFramework.Mscorlib46); compilation.VerifyDiagnostics( // (7,10): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // (string?, string) t1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("(T1, T2)", "T1", "string?").WithLocation(7, 10), // (8,10): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // (string?, string, string, string, string, string, string, string, string?) t2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "T1", "string?").WithLocation(8, 10), // (8,75): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // (string?, string, string, string, string, string, string, string, string?) t2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("(T1, T2)", "T2", "string?").WithLocation(8, 75), // (9,27): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // Type t3 = typeof((string?, string)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("(T1, T2)", "T1", "string?").WithLocation(9, 27), // (10,27): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // Type t4 = typeof((string?, string, string, string, string, string, string, string, string?)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "T1", "string?").WithLocation(10, 27), // (10,92): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // Type t4 = typeof((string?, string, string, string, string, string, string, string, string?)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("(T1, T2)", "T2", "string?").WithLocation(10, 92) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33011")] [WorkItem(33303, "https://github.com/dotnet/roslyn/issues/33303")] public void Constraints_78() { var source = @" #nullable enable #pragma warning disable 8600 class C { void Deconstruction() { string s1; string? s2; C c = new C(); (s1, s1) = ("""", """"); (s2, s1) = ((string)null, """"); var v1 = (s2, s1) = ((string)null, """"); // 1 var v2 = (s1, s1) = ((string)null, """"); // 2 (s2, s1) = c; (string? s3, string s4) = c; var v2 = (s2, s1) = c; // 3 } public void Deconstruct(out string? s1, out string s2) { s1 = null; s2 = string.Empty; } } "; var compilation = CreateCompilation(new[] { Tuple2NonNullable, source }, targetFramework: TargetFramework.Mscorlib46); compilation.VerifyDiagnostics( ); } [Fact] [WorkItem(33303, "https://github.com/dotnet/roslyn/issues/33303")] public void Constraints_79() { var source = @" using System; #nullable enable #pragma warning disable 168 class C { void TupleTypes() { (string?, string) t1; Type t2 = typeof((string?, string)); } } "; var compilation = CreateCompilation(new[] { Tuple2NonNullable, TupleRestNonNullable, source }, targetFramework: TargetFramework.Mscorlib46, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); compilation.VerifyDiagnostics( // (3,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(3, 2), // (4,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(4, 2), // (4,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(4, 2), // (6,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T1 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(6, 20), // (7,16): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // (string?, string) t1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(7, 16), // (7,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T1 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(7, 20), // (7,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T2 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(7, 20), // (8,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T2 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(8, 20), // (8,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T3 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(8, 20), // (8,33): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // Type t2 = typeof((string?, string)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(8, 33), // (9,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T4 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(9, 20), // (10,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T5 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(10, 20), // (11,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T6 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(11, 20), // (12,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T7 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(12, 20)); } [Fact] public void Constraints_80() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>()", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } var source2 = @" #nullable disable public interface I1 { void F1<TF1, TF2>() where TF2 : class; } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator2, symbolValidator: symbolValidator2); void symbolValidator2(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1, TF2>() where TF2 : class", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); foreach (TypeParameterSymbol tf1 in f1.TypeParameters) { Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } } [Fact] public void Constraints_81() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : new(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : new()", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_82() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : class; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : class", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_83() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : struct; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : struct", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_84() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : unmanaged; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : unmanaged", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_85() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : I1; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : I1", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_86() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : class?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (5,37): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void F1<TF1>() where TF1 : class?; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 37) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetMember("I1"); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : class?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_87() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : I1?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (5,34): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void F1<TF1>() where TF1 : I1?; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 34) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : I1?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_88() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetMember("I1"); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>()", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } var source2 = @" #nullable enable public interface I1 { void F1<TF1, TF2>() where TF1 : class?; } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator2, symbolValidator: symbolValidator2); void symbolValidator2(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetMember("I1"); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1, TF2>() where TF1 : class?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); foreach (TypeParameterSymbol tf1 in f1.TypeParameters) { Assert.False(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } } [Fact] public void Constraints_89() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : new(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetMember("I1"); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : new()", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_90() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : class; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetMember("I1"); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", i1.GetAttributes().Single().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : class!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_91() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : struct; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : struct", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_92() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : unmanaged; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : unmanaged", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_93() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : I1; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : I1!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_94() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : class?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetMember("I1"); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : class?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_95() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : I1?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : I1?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_96() { var source1 = @" #nullable disable public interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } var source2 = @" #nullable disable public interface I1<TF1, TF2> where TF2 : class { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator2, symbolValidator: symbolValidator2); void symbolValidator2(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1, TF2> where TF2 : class", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); foreach (TypeParameterSymbol tf1 in i1.TypeParameters) { Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } } [Fact] public void Constraints_97() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : new() { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : new()", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_98() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : class { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : class", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_99() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : struct { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : struct", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_100() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : unmanaged { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : unmanaged", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_101() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_102() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : class? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (3,43): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public interface I1<TF1> where TF1 : class? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 43) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : class?", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_103() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : I1<TF1>? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (3,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public interface I1<TF1> where TF1 : I1<TF1>? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 45) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : I1<TF1>?", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_104() { var source1 = @" #nullable enable public interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } var source2 = @" #nullable enable public interface I1<TF1, TF2> where TF1 : class? { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator2, symbolValidator: symbolValidator2); void symbolValidator2(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1, TF2> where TF1 : class?", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } foreach (TypeParameterSymbol tf1 in i1.TypeParameters) { Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } } [Fact] public void Constraints_105() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : new() { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : new()", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_106() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : class { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : class!", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_107() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : struct { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : struct", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_108() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : unmanaged { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : unmanaged", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_109() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : I1<TF1>!", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_110() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : class? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : class?", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_111() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : I1<TF1>? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : I1<TF1>?", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_112() { var source1 = @" #nullable disable #nullable enable warnings partial interface I1<TF1> { } partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_113() { var source1 = @" #nullable enable partial interface I1<TF1> { } partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_114() { var source1 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> { } #nullable enable partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_115() { var source1 = @" #nullable enable partial interface I1<TF1> { } #nullable disable #nullable enable warnings partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_116() { var source1 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> { } partial interface I1<TF1> where TF1 : notnull { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.HasNotNullConstraint); Assert.True(tf1.IsNotNullable); var source2 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : new() { } partial interface I1<TF1> where TF1 : notnull, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,19): error CS0265: Partial declarations of 'I1<TF1>' have inconsistent constraints for type parameter 'TF1' // partial interface I1<TF1> where TF1 : new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<TF1>", "TF1").WithLocation(3, 19) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.HasNotNullConstraint); Assert.Null(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : notnull, new() { } partial interface I1<TF1> where TF1 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (3,19): error CS0265: Partial declarations of 'I1<TF1>' have inconsistent constraints for type parameter 'TF1' // partial interface I1<TF1> where TF1 : notnull, new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<TF1>", "TF1").WithLocation(3, 19) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.True(tf1.HasNotNullConstraint); Assert.True(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); } [Fact] public void Constraints_117() { var source1 = @" #nullable enable partial interface I1<TF1> { } partial interface I1<TF1> where TF1 : notnull { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.HasNotNullConstraint); Assert.True(tf1.IsNotNullable); var source2 = @" #nullable enable partial interface I1<TF1> where TF1 : new() { } partial interface I1<TF1> where TF1 : notnull, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,19): error CS0265: Partial declarations of 'I1<TF1>' have inconsistent constraints for type parameter 'TF1' // partial interface I1<TF1> where TF1 : new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<TF1>", "TF1").WithLocation(3, 19) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.HasNotNullConstraint); Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); } [Fact] public void Constraints_118() { var source1 = @" #nullable disable #nullable enable warnings partial interface I1<TF1> { } #nullable enable partial interface I1<TF1> where TF1 : notnull { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var source2 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : new() { } #nullable enable partial interface I1<TF1> where TF1 : notnull, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,19): error CS0265: Partial declarations of 'I1<TF1>' have inconsistent constraints for type parameter 'TF1' // partial interface I1<TF1> where TF1 : new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<TF1>", "TF1").WithLocation(3, 19) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.HasNotNullConstraint); Assert.Null(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @" #nullable enable partial interface I1<TF1> where TF1 : notnull, new() { } #nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (3,19): error CS0265: Partial declarations of 'I1<TF1>' have inconsistent constraints for type parameter 'TF1' // partial interface I1<TF1> where TF1 : notnull, new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<TF1>", "TF1").WithLocation(3, 19) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.True(tf1.HasNotNullConstraint); Assert.True(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); } [Fact] public void Constraints_119() { var source1 = @" #nullable enable partial interface I1<TF1> { } #nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : notnull { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var source2 = @" #nullable enable partial interface I1<TF1> where TF1 : new() { } #nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : notnull, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,19): error CS0265: Partial declarations of 'I1<TF1>' have inconsistent constraints for type parameter 'TF1' // partial interface I1<TF1> where TF1 : new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<TF1>", "TF1").WithLocation(3, 19) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); } [Fact] public void Constraints_120() { var source1 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> { } partial interface I1<TF1> where TF1 : object? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (7,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 39), // (7,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 45) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : new() { } partial interface I1<TF1> where TF1 : object?, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (7,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 39), // (7,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 45) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @"#nullable disable #nullable enable warnings partial interface I1<TF1, TF2> where TF2 : new() { } partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (7,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 44), // (7,50): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 50) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.Null(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] public void Constraints_121() { var source1 = @" #nullable enable partial interface I1<TF1> { } partial interface I1<TF1> where TF1 : object? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (7,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 39) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @" #nullable enable partial interface I1<TF1> where TF1 : new() { } partial interface I1<TF1> where TF1 : object?, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (7,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 39) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @" #nullable enable partial interface I1<TF1, TF2> where TF2 : new() { } partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (7,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 44) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.False(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_122() { var source1 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> { } #nullable enable partial interface I1<TF1> where TF1 : object? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (8,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 39) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : new() { } #nullable enable partial interface I1<TF1> where TF1 : object?, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (8,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 39) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @"#nullable disable #nullable enable warnings partial interface I1<TF1, TF2> where TF2 : new() { } #nullable enable partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (8,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 44) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.False(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_123() { var source1 = @" #nullable enable partial interface I1<TF1> { } #nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : object? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (8,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 39), // (8,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 45) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @" #nullable enable partial interface I1<TF1> where TF1 : new() { } #nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : object?, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (8,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 39), // (8,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 45) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @" #nullable enable partial interface I1<TF1, TF2> where TF2 : new() { } #nullable disable #nullable enable warnings partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (8,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 44), // (8,50): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 50) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.False(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] public void Constraints_124() { var source1 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : object? { } partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39), // (3,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 45) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : object?, new() { } partial interface I1<TF1> where TF1 : new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39), // (3,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 45) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @"#nullable disable #nullable enable warnings partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } partial interface I1<TF1, TF2> where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (3,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 44), // (3,50): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 50) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.Null(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] public void Constraints_125() { var source1 = @" #nullable enable partial interface I1<TF1> where TF1 : object? { } partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @" #nullable enable partial interface I1<TF1> where TF1 : object?, new() { } partial interface I1<TF1> where TF1 : new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @" #nullable enable partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } partial interface I1<TF1, TF2> where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (3,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 44) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.False(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_126() { var source1 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : object? { } #nullable enable partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39), // (3,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 45) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : object?, new() { } #nullable enable partial interface I1<TF1> where TF1 : new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39), // (3,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 45) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @"#nullable disable #nullable enable warnings partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } #nullable enable partial interface I1<TF1, TF2> where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (3,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 44), // (3,50): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 50) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.False(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_127() { var source1 = @" #nullable enable partial interface I1<TF1> where TF1 : object? { } #nullable disable #nullable enable warnings partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @" #nullable enable partial interface I1<TF1> where TF1 : object?, new() { } #nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @" #nullable enable partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } #nullable disable #nullable enable warnings partial interface I1<TF1, TF2> where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (3,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 44) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.False(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] public void Constraints_128() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>(); partial void M1<TF1>() { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); } [Fact] public void Constraints_129() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>(); partial void M1<TF1>() { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_130() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>(); #nullable enable partial void M1<TF1>() { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.Null(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); var source2 = @" partial class A { #nullable enable partial void M1<TF1>() { } #nullable disable #nullable enable warnings partial void M1<TF1>(); } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); m1 = comp2.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.Null(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_131() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>(); #nullable disable #nullable enable warnings partial void M1<TF1>() { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.Null(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); var source2 = @"#nullable disable partial class A { #nullable enable warnings partial void M1<TF1>() { } #nullable enable partial void M1<TF1>(); } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); m1 = comp2.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.Null(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] public void Constraints_132() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>(); partial void M1<TF1>() where TF1 : notnull { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_133() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>(); partial void M1<TF1>() where TF1 : notnull { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (7,14): warning CS8667: Partial method declarations of 'A.M1<TF1>()' have inconsistent nullability in constraints for type parameter 'TF1' // partial void M1<TF1>() where TF1 : notnull Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, "M1").WithArguments("A.M1<TF1>()", "TF1").WithLocation(7, 14) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.True(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_134() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>(); #nullable enable partial void M1<TF1>() where TF1 : notnull { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.Null(m1.TypeParameters[0].IsNotNullable); Assert.True(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_135() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>(); #nullable disable #nullable enable warnings partial void M1<TF1>() where TF1 : notnull { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (8,14): warning CS8667: Partial method declarations of 'A.M1<TF1>()' have inconsistent nullability in constraints for type parameter 'TF1' // partial void M1<TF1>() where TF1 : notnull Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, "M1").WithArguments("A.M1<TF1>()", "TF1").WithLocation(8, 14) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.True(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_136() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>(); partial void M1<TF1>() where TF1 : object? { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (7,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 36), // (7,42): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial void M1<TF1>() where TF1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 42) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.Null(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_137() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>(); partial void M1<TF1>() where TF1 : object? { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (7,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 36) ); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_138() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>(); #nullable enable partial void M1<TF1>() where TF1 : object? { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (8,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 36) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.Null(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] public void Constraints_139() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>(); #nullable disable #nullable enable warnings partial void M1<TF1>() where TF1 : object? { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (8,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 36), // (8,42): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial void M1<TF1>() where TF1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 42) ); } [Fact] public void Constraints_140() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>() { } partial void M1<TF1>(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); } [Fact] public void Constraints_141() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>() { } partial void M1<TF1>(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_142() { var source1 = @"#nullable disable partial class A { #nullable enable warnings partial void M1<TF1>() { } #nullable enable partial void M1<TF1>(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.Null(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_143() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>() { } #nullable disable #nullable enable warnings partial void M1<TF1>(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.Null(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] public void Constraints_144() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>() { } partial void M1<TF1>() where TF1 : notnull; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_145() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>() { } partial void M1<TF1>() where TF1 : notnull; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (5,14): warning CS8667: Partial method declarations of 'A.M1<TF1>()' have inconsistent nullability in constraints for type parameter 'TF1' // partial void M1<TF1>() Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, "M1").WithArguments("A.M1<TF1>()", "TF1").WithLocation(5, 14) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.True(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_146() { var source1 = @"#nullable disable partial class A { #nullable enable warnings partial void M1<TF1>() { } #nullable enable partial void M1<TF1>() where TF1 : notnull; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.True(m1.TypeParameters[0].IsNotNullable); Assert.Null(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_147() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>() { } #nullable disable #nullable enable warnings partial void M1<TF1>() where TF1 : notnull; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (5,14): warning CS8667: Partial method declarations of 'A.M1<TF1>()' have inconsistent nullability in constraints for type parameter 'TF1' // partial void M1<TF1>() Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, "M1").WithArguments("A.M1<TF1>()", "TF1").WithLocation(5, 14) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.True(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_148() { var source1 = @"#nullable disable partial class A { #nullable enable warnings partial void M1<TF1>() { } partial void M1<TF1>() where TF1 : object?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (9,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object?; Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(9, 36), // (9,42): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial void M1<TF1>() where TF1 : object?; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 42) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.Null(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] public void Constraints_149() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>() { } partial void M1<TF1>() where TF1 : object?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (9,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object?; Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(9, 36) ); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_150() { var source1 = @"#nullable disable partial class A { #nullable enable warnings partial void M1<TF1>() { } #nullable enable partial void M1<TF1>() where TF1 : object?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (10,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object?; Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(10, 36) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.Null(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] public void Constraints_151() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>() { } #nullable disable #nullable enable warnings partial void M1<TF1>() where TF1 : object?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (10,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object?; Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(10, 36), // (10,42): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial void M1<TF1>() where TF1 : object?; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 42) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/34798")] public void Constraints_152() { var source = @" class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } class B : A<int> { public override void F1<T11>(T11? t1) where T11 : class { } public override void F2<T22>(T22 t2) { } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>(T11? t1) where T11 : class", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t11.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(1)", t11.GetAttributes().Single().ToString()); } var af1 = bf1.OverriddenMethod; Assert.Equal("void A<System.Int32>.F1<T1>(T1? t1) where T1 : class", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = af1.TypeParameters[0]; Assert.False(t1.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(1)", t1.GetAttributes().Single().ToString()); } var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>(T22 t2) where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t22.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t22.GetAttributes().Single().ToString()); } var af2 = bf2.OverriddenMethod; Assert.Equal("void A<System.Int32>.F2<T2>(T2 t2) where T2 : class?", af2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = af2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t2.GetAttributes().Single().ToString()); } } } [Fact] public void Constraints_153() { var source1 = @" public class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var source2 = @" class B : A<int> { public override void F1<T11>(T11? t1) where T11 : class { } public override void F2<T22>(T22 t2) { } } "; var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var b = m.GlobalNamespace.GetMember("B"); if (isSource) { Assert.Empty(b.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", b.GetAttributes().First().ToString()); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>(T11? t1) where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>(T22 t2) where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t22.GetAttributes()); } else { CSharpAttributeData nullableAttribute = t22.GetAttributes().Single(); Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", nullableAttribute.ToString()); Assert.Same(m, nullableAttribute.AttributeClass.ContainingModule); Assert.Equal(Accessibility.Internal, nullableAttribute.AttributeClass.DeclaredAccessibility); } } } [Fact] public void Constraints_154() { var source1 = @" public class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var comp2 = CreateCompilation(NullableAttributeDefinition); var source3 = @" class B : A<int> { public override void F1<T11>(T11? t1) where T11 : class { } public override void F2<T22>(T22 t2) { } } "; var comp3 = CreateCompilation(new[] { source3 }, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference(), comp2.EmitToImageReference() }, parseOptions: TestOptions.Regular8); CompileAndVerify(comp3, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var b = m.GlobalNamespace.GetMember("B"); if (isSource) { Assert.Empty(b.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", b.GetAttributes().First().ToString()); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>(T11? t1) where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>(T22 t2) where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t22.GetAttributes()); } else { CSharpAttributeData nullableAttribute = t22.GetAttributes().Single(); Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", nullableAttribute.ToString()); Assert.NotEqual(m, nullableAttribute.AttributeClass.ContainingModule); } } } [Fact] public void DynamicConstraint_01() { var source = @" class B<S> { public static void F1<T1>(T1 t1) where T1 : dynamic { } public static void F2<T2>(T2 t2) where T2 : B<dynamic> { } }"; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (4,49): error CS1967: Constraint cannot be the dynamic type // public static void F1<T1>(T1 t1) where T1 : dynamic Diagnostic(ErrorCode.ERR_DynamicTypeAsBound, "dynamic").WithLocation(4, 49), // (8,49): error CS1968: Constraint cannot be a dynamic type 'B<dynamic>' // public static void F2<T2>(T2 t2) where T2 : B<dynamic> Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "B<dynamic>").WithArguments("B<dynamic>").WithLocation(8, 49) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B<S>.F1<T1>(T1 t1)", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B<S>.F2<T2>(T2 t2)", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } [Fact] [WorkItem(36276, "https://github.com/dotnet/roslyn/issues/36276")] public void DynamicConstraint_02() { var source1 = @" #nullable enable class Test1<T> { public virtual void M1<S>() where S : T { } } class Test2 : Test1<dynamic> { public override void M1<S>() { } void Test() { base.M1<object?>(); this.M1<object?>(); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (18,9): warning CS8631: The type 'object?' cannot be used as type parameter 'S' in the generic type or method 'Test1<dynamic>.M1<S>()'. Nullability of type argument 'object?' doesn't match constraint type 'object'. // base.M1<object?>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "base.M1<object?>").WithArguments("Test1<dynamic>.M1<S>()", "object", "S", "object?").WithLocation(18, 9), // (19,9): warning CS8631: The type 'object?' cannot be used as type parameter 'S' in the generic type or method 'Test2.M1<S>()'. Nullability of type argument 'object?' doesn't match constraint type 'object'. // this.M1<object?>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "this.M1<object?>").WithArguments("Test2.M1<S>()", "object", "S", "object?").WithLocation(19, 9) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>() where S : System.Object!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); var baseM1 = m1.OverriddenMethod; Assert.Equal("void Test1<dynamic!>.M1<S>() where S : System.Object!", baseM1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(baseM1.TypeParameters[0].IsNotNullable); } } [Fact] [WorkItem(36276, "https://github.com/dotnet/roslyn/issues/36276")] public void DynamicConstraint_03() { var source1 = @" #nullable disable class Test1<T> { public virtual void M1<S>() where S : T { } } class Test2 : Test1<dynamic> { public override void M1<S>() { } void Test() { #nullable enable base.M1<object?>(); this.M1<object?>(); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>()", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); var baseM1 = m1.OverriddenMethod; Assert.Equal("void Test1<dynamic>.M1<S>()", baseM1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(baseM1.TypeParameters[0].IsNotNullable); } } [Fact] public void DynamicConstraint_04() { var source1 = @" #nullable enable class Test1<T> { public virtual void M1<S>() where S : T { } } class Test2 : Test1<Test1<dynamic>> { public override void M1<S>() { } void Test() { base.M1<Test1<object?>>(); this.M1<Test1<object?>>(); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (18,9): warning CS8631: The type 'Test1<object?>' cannot be used as type parameter 'S' in the generic type or method 'Test1<Test1<dynamic>>.M1<S>()'. Nullability of type argument 'Test1<object?>' doesn't match constraint type 'Test1<object>'. // base.M1<Test1<object?>>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "base.M1<Test1<object?>>").WithArguments("Test1<Test1<dynamic>>.M1<S>()", "Test1<object>", "S", "Test1<object?>").WithLocation(18, 9), // (19,9): warning CS8631: The type 'Test1<object?>' cannot be used as type parameter 'S' in the generic type or method 'Test2.M1<S>()'. Nullability of type argument 'Test1<object?>' doesn't match constraint type 'Test1<object>'. // this.M1<Test1<object?>>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "this.M1<Test1<object?>>").WithArguments("Test2.M1<S>()", "Test1<object>", "S", "Test1<object?>").WithLocation(19, 9) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>() where S : Test1<System.Object!>!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); var baseM1 = m1.OverriddenMethod; Assert.Equal("void Test1<Test1<dynamic!>!>.M1<S>() where S : Test1<System.Object!>!", baseM1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(baseM1.TypeParameters[0].IsNotNullable); } } [Fact] public void DynamicConstraint_05() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : I1?, T {} } public interface I1 {} public class Test2 : Test1<dynamic> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); var baseM1 = m1.OverriddenMethod; Assert.Equal("void Test1<dynamic!>.M1<S>(S x) where S : System.Object!, I1?", baseM1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(baseM1.TypeParameters[0].IsNotNullable); } } [Fact] public void NotNullConstraint_01() { var source1 = @" #nullable enable public class A { void Test(int? a, int? b) { M<int?>(a); M(a); if (b == null) return; b.Value.ToString(); M(b); } void M<T> (T x) where T : notnull { ((object)x).ToString(); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (7,9): warning CS8714: The type 'int?' cannot be used as type parameter 'T' in the generic type or method 'A.M<T>(T)'. Nullability of type argument 'int?' doesn't match 'notnull' constraint. // M<int?>(a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M<int?>").WithArguments("A.M<T>(T)", "T", "int?").WithLocation(7, 9), // (8,9): warning CS8714: The type 'int?' cannot be used as type parameter 'T' in the generic type or method 'A.M<T>(T)'. Nullability of type argument 'int?' doesn't match 'notnull' constraint. // M(a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M").WithArguments("A.M<T>(T)", "T", "int?").WithLocation(8, 9), // (11,9): warning CS8714: The type 'int?' cannot be used as type parameter 'T' in the generic type or method 'A.M<T>(T)'. Nullability of type argument 'int?' doesn't match 'notnull' constraint. // M(b); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M").WithArguments("A.M<T>(T)", "T", "int?").WithLocation(11, 9) ); } [Fact] public void NotNullConstraint_02() { var source1 = @" #nullable enable public class A<T> where T : notnull { public void M<S> (S x) where S : T { ((object)x).ToString(); } } public class B : A<System.ValueType> { void Test(int? a, int? b) { M<int?>(a); M(a); if (b == null) return; b.Value.ToString(); M(b); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (15,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'A<ValueType>.M<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M<int?>(a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M<int?>").WithArguments("A<System.ValueType>.M<S>(S)", "System.ValueType", "S", "int?").WithLocation(15, 9), // (16,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'A<ValueType>.M<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M(a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M").WithArguments("A<System.ValueType>.M<S>(S)", "System.ValueType", "S", "int?").WithLocation(16, 9), // (19,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'A<ValueType>.M<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M(b); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M").WithArguments("A<System.ValueType>.M<S>(S)", "System.ValueType", "S", "int?").WithLocation(19, 9) ); } [Fact] public void NotNullConstraint_03() { var source1 = @" #nullable enable public class A<T> { public void M<S> (S x) where S : T { ((object)x).ToString(); } } public class B : A<System.ValueType> { void Test(int? a, int? b) { M<int?>(a); M(a); if (b == null) return; b.Value.ToString(); M(b); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (7,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((object)x).ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)x").WithLocation(7, 10), // (7,10): warning CS8602: Dereference of a possibly null reference. // ((object)x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object)x").WithLocation(7, 10), // (15,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'A<ValueType>.M<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M<int?>(a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M<int?>").WithArguments("A<System.ValueType>.M<S>(S)", "System.ValueType", "S", "int?").WithLocation(15, 9), // (16,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'A<ValueType>.M<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M(a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M").WithArguments("A<System.ValueType>.M<S>(S)", "System.ValueType", "S", "int?").WithLocation(16, 9), // (19,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'A<ValueType>.M<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M(b); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M").WithArguments("A<System.ValueType>.M<S>(S)", "System.ValueType", "S", "int?").WithLocation(19, 9) ); } [Fact] public void NotNullConstraint_04() { var source1 = @" #nullable enable public class A<T> { public void M<S> (S x) where S : T { ((object)x).ToString(); } } public class B : A<System.ValueType?> { void Test(int? a, int? b) { M<int?>(a); M(a); if (b == null) return; b.Value.ToString(); M(b); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (7,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((object)x).ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)x").WithLocation(7, 10), // (7,10): warning CS8602: Dereference of a possibly null reference. // ((object)x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object)x").WithLocation(7, 10) ); } [Fact] public void NotNullConstraint_05() { var source1 = @" #nullable enable public class A<T> where T : notnull { public void M<S> (S x) where S : T { ((object)x).ToString(); } } public class B : A<System.ValueType?> { void Test(int? a, int? b) { M<int?>(a); M(a); if (b == null) return; b.Value.ToString(); M(b); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (11,14): warning CS8714: The type 'System.ValueType?' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. Nullability of type argument 'System.ValueType?' doesn't match 'notnull' constraint. // public class B : A<System.ValueType?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "B").WithArguments("A<T>", "T", "System.ValueType?").WithLocation(11, 14) ); } [Fact] public void NotNullConstraint_06() { var source1 = @" #nullable enable public class A<T> where T : notnull { public void M<S>(S? x, S y, S? z) where S : class, T { M<S?>(x); M(x); if (z == null) return; M(z); } public void M<S>(S x) where S : T { ((object)x).ToString(); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (7,9): warning CS8631: The type 'S?' cannot be used as type parameter 'S' in the generic type or method 'A<T>.M<S>(S)'. Nullability of type argument 'S?' doesn't match constraint type 'T'. // M<S?>(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M<S?>").WithArguments("A<T>.M<S>(S)", "T", "S", "S?").WithLocation(7, 9), // (8,9): warning CS8631: The type 'S?' cannot be used as type parameter 'S' in the generic type or method 'A<T>.M<S>(S)'. Nullability of type argument 'S?' doesn't match constraint type 'T'. // M(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M").WithArguments("A<T>.M<S>(S)", "T", "S", "S?").WithLocation(8, 9) ); } [Fact] [WorkItem(36005, "https://github.com/dotnet/roslyn/issues/36005")] public void NotNullConstraint_07() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : T { } public virtual void M2(T x) { } } public class Test2 : Test1<System.ValueType> { public override void M1<S>(S x) { object y = x; y.ToString(); } public override void M2(System.ValueType x) { } public void Test() { int? x = null; M1<int?>(x); // 1 M2(x); // 2 } } public class Test3 : Test1<object> { public override void M1<S>(S x) { object y = x; y.ToString(); } public override void M2(object x) { } public void Test() { int? x = null; M1<int?>(x); // 3 M2(x); // 4 } } public class Test4 : Test1<int?> { public override void M1<S>(S x) { object y = x; // 5 y.ToString(); // 6 } public override void M2(int? x) { } public void Test() { int? x = null; M1<int?>(x); M2(x); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (26,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'Test2.M1<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M1<int?>(x); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<int?>").WithArguments("Test2.M1<S>(S)", "System.ValueType", "S", "int?").WithLocation(26, 9), // (27,12): warning CS8604: Possible null reference argument for parameter 'x' in 'void Test2.M2(ValueType x)'. // M2(x); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "void Test2.M2(ValueType x)").WithLocation(27, 12), // (46,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'Test3.M1<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'object'. // M1<int?>(x); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<int?>").WithArguments("Test3.M1<S>(S)", "object", "S", "int?").WithLocation(46, 9), // (47,12): warning CS8604: Possible null reference argument for parameter 'x' in 'void Test3.M2(object x)'. // M2(x); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "void Test3.M2(object x)").WithLocation(47, 12), // (55,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = x; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(55, 20), // (56,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(56, 9) ); var source2 = @" #nullable enable public class Test22 : Test2 { public override void M1<S>(S x) { object y = x; y.ToString(); } public new void Test() { int? x = null; M1<int?>(x); // 1 M2(x); // 2 } } public class Test33 : Test3 { public override void M1<S>(S x) { object y = x; y.ToString(); } public new void Test() { int? x = null; M1<int?>(x); // 3 M2(x); // 4 } } public class Test44 : Test4 { public override void M1<S>(S x) { object y = x; // 5 y.ToString(); // 6 } public new void Test() { int? x = null; M1<int?>(x); M2(x); } } "; var comp2 = CreateCompilation(new[] { source2 }, references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics( // (14,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'Test22.M1<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M1<int?>(x); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<int?>").WithArguments("Test22.M1<S>(S)", "System.ValueType", "S", "int?").WithLocation(14, 9), // (15,12): warning CS8604: Possible null reference argument for parameter 'x' in 'void Test2.M2(ValueType x)'. // M2(x); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "void Test2.M2(ValueType x)").WithLocation(15, 12), // (29,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'Test33.M1<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'object'. // M1<int?>(x); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<int?>").WithArguments("Test33.M1<S>(S)", "object", "S", "int?").WithLocation(29, 9), // (30,12): warning CS8604: Possible null reference argument for parameter 'x' in 'void Test3.M2(object x)'. // M2(x); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "void Test3.M2(object x)").WithLocation(30, 12), // (38,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = x; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(38, 20), // (39,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(39, 9) ); } [Fact] public void NotNullConstraint_08() { var source1 = @" #nullable enable public class A { void M<T> (T x) where T : notnull? { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (5,31): error CS0246: The type or namespace name 'notnull' could not be found (are you missing a using directive or an assembly reference?) // void M<T> (T x) where T : notnull? Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "notnull").WithArguments("notnull").WithLocation(5, 31), // (5,31): error CS0701: 'notnull?' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M<T> (T x) where T : notnull? Diagnostic(ErrorCode.ERR_BadBoundType, "notnull?").WithArguments("notnull?").WithLocation(5, 31) ); } [Fact] public void NotNullConstraint_09() { var source1 = @" #nullable enable public class A { void M<T>() where T : notnull { } void Test() { M<notnull>(); M<object>(); M<notnull?>(); } } class notnull {} "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (12,9): error CS0311: The type 'object' cannot be used as type parameter 'T' in the generic type or method 'A.M<T>()'. There is no implicit reference conversion from 'object' to 'notnull'. // M<object>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M<object>").WithArguments("A.M<T>()", "notnull", "T", "object").WithLocation(12, 9), // (13,9): warning CS8631: The type 'notnull?' cannot be used as type parameter 'T' in the generic type or method 'A.M<T>()'. Nullability of type argument 'notnull?' doesn't match constraint type 'notnull'. // M<notnull?>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M<notnull?>").WithArguments("A.M<T>()", "notnull", "T", "notnull?").WithLocation(13, 9) ); } [Fact] public void NotNullConstraint_10() { var source1 = @" #nullable enable public class A { void M<T>() where T : notnull? { } void Test() { M<notnull>(); M<object>(); M<notnull?>(); } } class notnull {} "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (12,9): error CS0311: The type 'object' cannot be used as type parameter 'T' in the generic type or method 'A.M<T>()'. There is no implicit reference conversion from 'object' to 'notnull'. // M<object>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M<object>").WithArguments("A.M<T>()", "notnull", "T", "object").WithLocation(12, 9) ); } [Fact] public void NotNullConstraint_11() { var source1 = @" #nullable enable public class A { void M<notnull>() where notnull : notnull { } void Test() { M<notnull>(); M<object>(); M<notnull?>(); } } class notnull {} "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (5,12): error CS0454: Circular constraint dependency involving 'notnull' and 'notnull' // void M<notnull>() where notnull : notnull Diagnostic(ErrorCode.ERR_CircularConstraint, "notnull").WithArguments("notnull", "notnull").WithLocation(5, 12) ); } [Fact] public void NotNullConstraint_12() { var source1 = @" #nullable enable public class A { void M<notnull>() where notnull : notnull? { } void Test() { M<notnull>(); M<object>(); M<notnull?>(); } } class notnull {} "; var comp1 = CreateCompilation(new[] { source1 }, parseOptions: TestOptions.Regular8); comp1.VerifyDiagnostics( // (5,12): error CS0454: Circular constraint dependency involving 'notnull' and 'notnull' // void M<notnull>() where notnull : notnull? Diagnostic(ErrorCode.ERR_CircularConstraint, "notnull").WithArguments("notnull", "notnull").WithLocation(5, 12), // (5,39): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void M<notnull>() where notnull : notnull? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "notnull?").WithArguments("9.0").WithLocation(5, 39) ); } [Fact] public void NotNullConstraint_13() { var source1 = @" #nullable enable public class A { void M<notnull>() where notnull : notnull { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (5,12): error CS0454: Circular constraint dependency involving 'notnull' and 'notnull' // void M<notnull>() where notnull : notnull Diagnostic(ErrorCode.ERR_CircularConstraint, "notnull").WithArguments("notnull", "notnull").WithLocation(5, 12) ); } [Fact] public void NotNullConstraint_14() { var source1 = @" #nullable enable public class A { void M<notnull>() where notnull : notnull? { } } "; var comp1 = CreateCompilation(new[] { source1 }, parseOptions: TestOptions.Regular8); comp1.VerifyDiagnostics( // (5,12): error CS0454: Circular constraint dependency involving 'notnull' and 'notnull' // void M<notnull>() where notnull : notnull? Diagnostic(ErrorCode.ERR_CircularConstraint, "notnull").WithArguments("notnull", "notnull").WithLocation(5, 12), // (5,39): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void M<notnull>() where notnull : notnull? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "notnull?").WithArguments("9.0").WithLocation(5, 39) ); } [Fact] [WorkItem(46410, "https://github.com/dotnet/roslyn/issues/46410")] public void NotNullConstraint_15() { var source = @"#nullable enable abstract class A<T, U> where T : notnull { internal static void M<V>(V v) where V : T { } internal abstract void F<V>(V v) where V : U; } class B : A<System.ValueType, int?> { internal override void F<T>(T t) { M<T>(t); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8631: The type 'T' cannot be used as type parameter 'V' in the generic type or method 'A<ValueType, int?>.M<V>(V)'. Nullability of type argument 'T' doesn't match constraint type 'System.ValueType'. // M<T>(t); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M<T>").WithArguments("A<System.ValueType, int?>.M<V>(V)", "System.ValueType", "V", "T").WithLocation(11, 9)); } [Fact] public void ObjectConstraint_01() { var source = @" class B { public static void F1<T1>() where T1 : object { } public static void F2<T2>() where T2 : System.Object { } }"; foreach (var options in new[] { WithNullableEnable(), WithNullableDisable() }) { var comp1 = CreateCompilation(new[] { source }, options: options); comp1.VerifyDiagnostics( // (4,44): error CS0702: Constraint cannot be special class 'object' // public static void F1<T1>() where T1 : object Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object").WithArguments("object").WithLocation(4, 44), // (8,44): error CS0702: Constraint cannot be special class 'object' // public static void F2<T2>() where T2 : System.Object Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "System.Object").WithArguments("object").WithLocation(8, 44) ); } } [Fact] public void ObjectConstraint_02() { var source = @" class B { public static void F1<T1>() where T1 : object? { } public static void F2<T2>() where T2 : System.Object? { } }"; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (4,44): error CS0702: Constraint cannot be special class 'object' // public static void F1<T1>() where T1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(4, 44), // (8,44): error CS0702: Constraint cannot be special class 'object' // public static void F2<T2>() where T2 : System.Object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "System.Object?").WithArguments("object").WithLocation(8, 44) ); var comp2 = CreateCompilation(new[] { source }, options: WithNullableDisable()); comp2.VerifyDiagnostics( // (4,44): error CS0702: Constraint cannot be special class 'object' // public static void F1<T1>() where T1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(4, 44), // (4,50): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static void F1<T1>() where T1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 50), // (8,44): error CS0702: Constraint cannot be special class 'object' // public static void F2<T2>() where T2 : System.Object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "System.Object?").WithArguments("object").WithLocation(8, 44), // (8,57): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static void F2<T2>() where T2 : System.Object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 57) ); } [Fact] public void ObjectConstraint_03() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : T {} } public class Test2 : Test1<object> { } public class Test3 : Test1<object> { public override void M1<S>(S x) { } } public class Test4 : Test1<object?> { } public class Test5 : Test1<object?> { public override void M1<S>(S x) { } } #nullable disable public class Test6 : Test1<object> { } public class Test7 : Test1<object> { #nullable enable public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); var source2 = @" #nullable enable public class Test21 : Test2 { public void Test() { M1<object?>(new object()); // 1 } } public class Test22 : Test2 { public override void M1<S>(S x) { x.ToString(); x = default; } public void Test() { M1<object?>(new object()); // 2 } } public class Test31 : Test3 { public void Test() { M1<object?>(new object()); // 3 } } public class Test32 : Test3 { public override void M1<S>(S x) { x.ToString(); x = default; } public void Test() { M1<object?>(new object()); // 4 } } public class Test41 : Test4 { public void Test() { M1<object?>(new object()); } } public class Test42 : Test4 { public override void M1<S>(S x) { x.ToString(); // 5 x = default; } public void Test() { M1<object?>(new object()); } } public class Test51 : Test5 { public void Test() { M1<object?>(new object()); } } public class Test52 : Test5 { public override void M1<S>(S x) { x.ToString(); // 6 x = default; } public void Test() { M1<object?>(new object()); } } public class Test61 : Test6 { public void Test() { M1<object?>(new object()); } } public class Test62 : Test6 { public override void M1<S>(S x) { x.ToString(); x = default; } public void Test() { M1<object?>(new object()); } } public class Test71 : Test7 { public void Test() { M1<object?>(new object()); } } public class Test72 : Test7 { public override void M1<S>(S x) { x.ToString(); x = default; } public void Test() { M1<object?>(new object()); } } "; foreach (var reference in new[] { comp1.ToMetadataReference(), comp1.EmitToImageReference() }) { var comp2 = CreateCompilation(new[] { source2 }, references: new[] { reference }, parseOptions: TestOptions.Regular8); comp2.VerifyDiagnostics( // (7,9): warning CS8631: The type 'object?' cannot be used as type parameter 'S' in the generic type or method 'Test1<object>.M1<S>(S)'. Nullability of type argument 'object?' doesn't match constraint type 'object'. // M1<object?>(new object()); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<object?>").WithArguments("Test1<object>.M1<S>(S)", "object", "S", "object?").WithLocation(7, 9), // (21,9): warning CS8631: The type 'object?' cannot be used as type parameter 'S' in the generic type or method 'Test22.M1<S>(S)'. Nullability of type argument 'object?' doesn't match constraint type 'object'. // M1<object?>(new object()); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<object?>").WithArguments("Test22.M1<S>(S)", "object", "S", "object?").WithLocation(21, 9), // (29,9): warning CS8631: The type 'object?' cannot be used as type parameter 'S' in the generic type or method 'Test3.M1<S>(S)'. Nullability of type argument 'object?' doesn't match constraint type 'object'. // M1<object?>(new object()); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<object?>").WithArguments("Test3.M1<S>(S)", "object", "S", "object?").WithLocation(29, 9), // (43,9): warning CS8631: The type 'object?' cannot be used as type parameter 'S' in the generic type or method 'Test32.M1<S>(S)'. Nullability of type argument 'object?' doesn't match constraint type 'object'. // M1<object?>(new object()); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<object?>").WithArguments("Test32.M1<S>(S)", "object", "S", "object?").WithLocation(43, 9), // (59,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(59, 9), // (81,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(81, 9) ); } } [Fact] public void ObjectConstraint_04() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : T {} } public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x)", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_05() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : T {} } #nullable enable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_06() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : T {} } #nullable enable public class Test2 : Test1<object?> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x)", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.False(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_07() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : I1, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_08() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : I1?, T {} } public interface I1 {} #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_09() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : I1, T {} } public interface I1 {} #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_10() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : I1, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_11() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : I1?, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_12() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : I1, T {} } public interface I1 {} #nullable enable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!, I1", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_13() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : class, T {} } public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : class", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_14() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : class?, T {} } #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : class?, System.Object", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_15() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : class, T {} } #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : class!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_16() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : class, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S! x) where S : class!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_17() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : class?, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S! x) where S : class?, System.Object!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_18() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : class, T {} } public interface I1 {} #nullable enable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S! x) where S : class, System.Object!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_19() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : notnull, T {} } #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : notnull", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_20() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : notnull, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : notnull", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_21() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : struct, T {} } #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : struct", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_22() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : struct, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : struct", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_23() { var source1 = @" #nullable disable public class Test1<T, U> { public virtual void M1<S>(S x) where S : U, T {} } public class Test2 : Test1<object, int> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Int32", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_24() { var source1 = @" #nullable enable public class Test1<T, U> { public virtual void M1<S>(S x) where S : U, T {} } public class Test2 : Test1<object, int> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Int32", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_25() { var source1 = @" #nullable disable public class Test1<T, U> { public virtual void M1<S>(S x) where S : U, T {} } public class Test2 : Test1<object, int?> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object, System.Int32?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_26() { var source1 = @" #nullable enable public class Test1<T, U> { public virtual void M1<S>(S x) where S : U, T {} } public class Test2 : Test1<object, int?> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!, System.Int32?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_27() { string il = @" .class private auto ansi sealed beforefieldinit Microsoft.CodeAnalysis.EmbeddedAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void Microsoft.CodeAnalysis.EmbeddedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } // end of method EmbeddedAttribute::.ctor } // end of class Microsoft.CodeAnalysis.EmbeddedAttribute .class private auto ansi sealed beforefieldinit System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void Microsoft.CodeAnalysis.EmbeddedAttribute::.ctor() = ( 01 00 00 00 ) .field public initonly uint8[] NullableFlags .method public hidebysig specialname rtspecialname instance void .ctor(uint8 A_1) cil managed { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ldarg.0 IL_0008: ldc.i4.1 IL_0009: newarr [mscorlib]System.Byte IL_000e: dup IL_000f: ldc.i4.0 IL_0010: ldarg.1 IL_0011: stelem.i1 IL_0012: stfld uint8[] System.Runtime.CompilerServices.NullableAttribute::NullableFlags IL_0017: ret } // end of method NullableAttribute::.ctor .method public hidebysig specialname rtspecialname instance void .ctor(uint8[] A_1) cil managed { // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: stfld uint8[] System.Runtime.CompilerServices.NullableAttribute::NullableFlags IL_000e: ret } // end of method NullableAttribute::.ctor } // end of class System.Runtime.CompilerServices.NullableAttribute .class interface public abstract auto ansi I1 { } // end of class I1 .class public auto ansi beforefieldinit Test2 extends class [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void class [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Test2::.ctor .method public hidebysig instance void M1<([mscorlib]System.Object) S>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M1 .method public hidebysig instance void M2<(I1, [mscorlib]System.Object) S>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M2 .method public hidebysig instance void M3<class ([mscorlib]System.Object) S>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M3 .method public hidebysig virtual instance void M4<class ([mscorlib]System.Object) S>(!!S x) cil managed { .param type S .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 02 00 00 ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M4 .method public hidebysig virtual instance void M5<class ([mscorlib]System.Object) S>(!!S x) cil managed { .param type S .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 01 00 00 ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M5 .method public hidebysig virtual instance void M6<([mscorlib]System.Object) S>(!!S x) cil managed { .param type S .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 01 00 00 ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M6 .method public hidebysig instance void M7<S>(!!S x) cil managed { .param type S .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 02 00 00 ) .param [1] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 01 00 00 ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M7 .method public hidebysig instance void M8<valuetype .ctor ([mscorlib]System.Object, [mscorlib]System.ValueType) S>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M8 .method public hidebysig virtual instance void M9<([mscorlib]System.Int32, [mscorlib]System.Object) S>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M9 .method public hidebysig virtual instance void M10<(valuetype [mscorlib]System.Nullable`1<int32>, [mscorlib]System.Object) S>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M10 } // end of class Test2 "; var compilation = CreateCompilationWithIL(new[] { "" }, il, options: WithNullableEnable()); var m1 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x)", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); var m2 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M2"); Assert.Equal("void Test2.M2<S>(S x) where S : I1", m2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m2.TypeParameters[0].IsNotNullable); var m3 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M3"); Assert.Equal("void Test2.M3<S>(S x) where S : class", m3.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m3.TypeParameters[0].IsNotNullable); var m4 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M4"); Assert.Equal("void Test2.M4<S>(S x) where S : class?, System.Object", m4.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m4.TypeParameters[0].IsNotNullable); var m5 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M5"); Assert.Equal("void Test2.M5<S>(S x) where S : class!", m5.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m5.TypeParameters[0].IsNotNullable); var m6 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M6"); Assert.Equal("void Test2.M6<S>(S x) where S : notnull", m6.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m6.TypeParameters[0].IsNotNullable); var m7 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M7"); Assert.Equal("void Test2.M7<S>(S x)", m7.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.False(m7.TypeParameters[0].IsNotNullable); var m8 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M8"); Assert.Equal("void Test2.M8<S>(S x) where S : struct", m8.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m8.TypeParameters[0].IsNotNullable); var m9 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M9"); Assert.Equal("void Test2.M9<S>(S x) where S : System.Int32", m9.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m9.TypeParameters[0].IsNotNullable); var m10 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M10"); Assert.Equal("void Test2.M10<S>(S x) where S : System.Object, System.Int32?", m10.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m10.TypeParameters[0].IsNotNullable); } [Fact] public void ObjectConstraint_28() { string il = @" .class public auto ansi beforefieldinit Test2 extends class [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void class [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Test2::.ctor .method public hidebysig instance void M1<([mscorlib]System.Object, !!S) S,U>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M1 } // end of class Test2 "; var compilation = CreateCompilationWithIL(new[] { "" }, il, options: WithNullableEnable()); var m1 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S, U>(S x) where S : System.Object", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } [Fact] public void ObjectConstraint_29() { string il = @" .class public auto ansi beforefieldinit Test2 extends class [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void class [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Test2::.ctor .method public hidebysig instance void M1<([mscorlib]System.Object, !!U) S, (!!S) U>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M1 } // end of class Test2 "; var compilation = CreateCompilationWithIL(new[] { "" }, il, options: WithNullableEnable()); var m1 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S, U>(S x) where S : System.Object, U", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } [Fact] public void ObjectConstraint_30() { var source1 = @" #nullable disable public class Test1<T> { #nullable enable public virtual void M1<S>(S x) where S : class?, T {} } #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : class?, System.Object", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_31() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable disable object, #nullable enable object? > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_32() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< object?, #nullable disable object > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_33() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable disable object, #nullable enable object > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_34() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< object, #nullable disable object > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_35() { var source1 = @" #nullable disable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : T1, T2 {} } public class Test2<T> : Test1<object, T> { public override void M1<S>(S x) { } } #nullable enable public class Test3 : Test2<Test3?> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var t2m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2<T>.M1<S>(S x) where S : T", t2m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(t2m1.TypeParameters[0].IsNotNullable); var t3m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test3.M1"); Assert.Equal("void Test3.M1<S>(S x) where S : System.Object, Test3?", t3m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(t3m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_36() { var source1 = @" #nullable disable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : T1, T2 {} } public class Test2<T> : Test1<object, T> { public override void M1<S>(S x) { } } "; var source2 = @" #nullable enable public class Test3 : Test2<Test3?> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); var comp2 = CreateCompilation(new[] { source2 }, references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var t3m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test3.M1"); Assert.Equal("void Test3.M1<S>(S x) where S : System.Object, Test3?", t3m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(t3m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_37() { var source1 = @" #nullable disable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : T1, T2 {} } public class Test2<T> : Test1<object, T> where T : struct { public override void M1<S>(S x) { } } #nullable enable public class Test3 : Test2<int> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var t2m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2<T>.M1<S>(S x) where S : T", t2m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(t2m1.TypeParameters[0].IsNotNullable); var t3m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test3.M1"); Assert.Equal("void Test3.M1<S>(S x) where S : System.Int32", t3m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(t3m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_01() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable disable string, #nullable enable string? > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1?, System.String", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_02() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< string?, #nullable disable string > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1?, System.String", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_03() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable disable string, #nullable enable string > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S! x) where S : I1?, System.String!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_04() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< string, #nullable disable string > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1?, System.String!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_05() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable enable string?, string? > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1?, System.String?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.False(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_06() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable enable string, string > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S! x) where S : I1?, System.String!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_07() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable disable string, string > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1?, System.String", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void UnconstrainedTypeParameter_Local() { var source = @" #pragma warning disable CS0168 class B { public static void F1<T1>() { T1? x; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,9): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T1? x; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T1?").WithArguments("9.0").WithLocation(7, 9) ); } [Fact] public void ConstraintsChecks_01() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : ID<string> { } public interface IB : IA<ID<string?>> // 1 {} public interface IC : IA<ID<string>?> // 2 {} public interface IE : IA<ID<string>> {} public interface ID<T> {} class B { public void Test1() { IA<ID<string?>> x1; // 3 IA<ID<string>?> y1; // 4 IA<ID<string>> z1; } public void M1<TM1>(TM1 x) where TM1: ID<string> {} public void Test2(ID<string?> a2, ID<string> b2, ID<string>? c2) { M1(a2); // 5 M1(b2); M1(c2); // 6 M1<ID<string?>>(a2); // 7 M1<ID<string?>>(b2); // 8 M1<ID<string>?>(b2); // 9 M1<ID<string>>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8631: The type 'ID<string?>' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'ID<string?>' doesn't match constraint type 'ID<string>'. // public interface IB : IA<ID<string?>> // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "IB").WithArguments("IA<TA>", "ID<string>", "TA", "ID<string?>").WithLocation(8, 18), // (11,18): warning CS8631: The type 'ID<string>?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'ID<string>?' doesn't match constraint type 'ID<string>'. // public interface IC : IA<ID<string>?> // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "IC").WithArguments("IA<TA>", "ID<string>", "TA", "ID<string>?").WithLocation(11, 18), // (24,12): warning CS8631: The type 'ID<string?>' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'ID<string?>' doesn't match constraint type 'ID<string>'. // IA<ID<string?>> x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "ID<string?>").WithArguments("IA<TA>", "ID<string>", "TA", "ID<string?>").WithLocation(24, 12), // (25,12): warning CS8631: The type 'ID<string>?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'ID<string>?' doesn't match constraint type 'ID<string>'. // IA<ID<string>?> y1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "ID<string>?").WithArguments("IA<TA>", "ID<string>", "TA", "ID<string>?").WithLocation(25, 12), // (34,9): warning CS8631: The type 'ID<string?>' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'ID<string?>' doesn't match constraint type 'ID<string>'. // M1(a2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B.M1<TM1>(TM1)", "ID<string>", "TM1", "ID<string?>").WithLocation(34, 9), // (36,9): warning CS8631: The type 'ID<string>?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'ID<string>?' doesn't match constraint type 'ID<string>'. // M1(c2); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B.M1<TM1>(TM1)", "ID<string>", "TM1", "ID<string>?").WithLocation(36, 9), // (37,9): warning CS8631: The type 'ID<string?>' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'ID<string?>' doesn't match constraint type 'ID<string>'. // M1<ID<string?>>(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<ID<string?>>").WithArguments("B.M1<TM1>(TM1)", "ID<string>", "TM1", "ID<string?>").WithLocation(37, 9), // (38,9): warning CS8631: The type 'ID<string?>' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'ID<string?>' doesn't match constraint type 'ID<string>'. // M1<ID<string?>>(b2); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<ID<string?>>").WithArguments("B.M1<TM1>(TM1)", "ID<string>", "TM1", "ID<string?>").WithLocation(38, 9), // (38,25): warning CS8620: Nullability of reference types in argument of type 'ID<string>' doesn't match target type 'ID<string?>' for parameter 'x' in 'void B.M1<ID<string?>>(ID<string?> x)'. // M1<ID<string?>>(b2); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b2").WithArguments("ID<string>", "ID<string?>", "x", "void B.M1<ID<string?>>(ID<string?> x)").WithLocation(38, 25), // (39,9): warning CS8631: The type 'ID<string>?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'ID<string>?' doesn't match constraint type 'ID<string>'. // M1<ID<string>?>(b2); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<ID<string>?>").WithArguments("B.M1<TM1>(TM1)", "ID<string>", "TM1", "ID<string>?").WithLocation(39, 9) ); } [Fact] public void ConstraintsChecks_02() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class { } public interface IB : IA<string?> // 1 {} public interface IC : IA<string> {} class B { public void Test1() { IA<string?> x1; // 2 IA<string> z1; } public void M1<TM1>(TM1 x) where TM1: class {} public void Test2(string? a2, string b2) { M1(a2); // 3 M1(b2); M1<string?>(a2); // 4 M1<string?>(b2); // 5 M1<string>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8634: The type 'string?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // public interface IB : IA<string?> // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "IB").WithArguments("IA<TA>", "TA", "string?").WithLocation(8, 18), // (18,12): warning CS8634: The type 'string?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // IA<string?> x1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("IA<TA>", "TA", "string?").WithLocation(18, 12), // (27,9): warning CS8634: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // M1(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(27, 9), // (29,9): warning CS8634: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // M1<string?>(a2); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<string?>").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(29, 9), // (30,9): warning CS8634: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // M1<string?>(b2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<string?>").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(30, 9) ); } [Fact] public void ConstraintsChecks_03() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : ID<string>? { } public interface IC : IA<ID<string>?> {} public interface IE : IA<ID<string>> {} public interface ID<T> {} class B { public void Test1() { IA<ID<string>?> y1; IA<ID<string>> z1; } public void M1<TM1>(TM1 x) where TM1: ID<string>? {} public void Test2(ID<string> b2, ID<string>? c2) { M1(b2); M1(c2); M1<ID<string>?>(c2); M1<ID<string>>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( ); } [Fact] public void ConstraintsChecks_04() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class? { } public interface IB : IA<string?> {} public interface IC : IA<string> {} class B { public void Test1() { IA<string?> x1; IA<string> z1; } public void M1<TM1>(TM1 x) where TM1: class? {} public void Test2(string? a2, string b2) { M1(a2); M1(b2); M1<string?>(a2); M1<string>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( ); } [Fact] public void ConstraintsChecks_05() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : ID<string> { } public interface IB<TIB> : IA<TIB> where TIB : ID<string?> // 1 {} public interface IC<TIC> : IA<TIC> where TIC : ID<string>? // 2 {} public interface IE<TIE> : IA<TIE> where TIE : ID<string> {} public interface ID<T> {} class B<TB1, TB2, TB3> where TB1 : ID<string?> where TB2 : ID<string>? where TB3 : ID<string> { public void Test1() { IA<TB1> x1; // 3 IA<TB2> y1; // 4 IA<TB3> z1; } public void M1<TM1>(TM1 x) where TM1: ID<string> {} public void Test2(TB1 a2, TB3 b2, TB2 c2) { M1(a2); // 5 M1(b2); M1(c2); // 6 M1<TB1>(a2); // 7 M1<TB2>(c2); // 8 M1<TB3>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8631: The type 'TIB' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIB' doesn't match constraint type 'ID<string>'. // public interface IB<TIB> : IA<TIB> where TIB : ID<string?> // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "IB").WithArguments("IA<TA>", "ID<string>", "TA", "TIB").WithLocation(8, 18), // (11,18): warning CS8631: The type 'TIC' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIC' doesn't match constraint type 'ID<string>'. // public interface IC<TIC> : IA<TIC> where TIC : ID<string>? // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "IC").WithArguments("IA<TA>", "ID<string>", "TA", "TIC").WithLocation(11, 18), // (24,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // IA<TB1> x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "ID<string>", "TA", "TB1").WithLocation(24, 12), // (25,12): warning CS8631: The type 'TB2' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // IA<TB2> y1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB2").WithArguments("IA<TA>", "ID<string>", "TA", "TB2").WithLocation(25, 12), // (34,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1(a2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(34, 9), // (36,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1(c2); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(36, 9), // (37,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1<TB1>(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(37, 9), // (38,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1<TB2>(c2); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB2>").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(38, 9) ); } [Fact] public void ConstraintsChecks_06() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class { } public interface IB<TIB> : IA<TIB> where TIB : C? // 1 {} public interface IC<TIC> : IA<TIC> where TIC : C {} public class C {} class B<TB1, TB2> where TB1 : C? where TB2 : C { public void Test1() { IA<TB1> x1; // 2 IA<TB2> z1; } public void M1<TM1>(TM1 x) where TM1: class {} public void Test2(TB1 a2, TB2 b2) { M1(a2); // 3 M1(b2); M1<TB1>(a2); // 4 M1<TB2>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8634: The type 'TIB' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIB' doesn't match 'class' constraint. // public interface IB<TIB> : IA<TIB> where TIB : C? // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "IB").WithArguments("IA<TA>", "TA", "TIB").WithLocation(8, 18), // (21,12): warning CS8634: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // IA<TB1> x1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(21, 12), // (30,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(30, 9), // (32,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1<TB1>(a2); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<TB1>").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(32, 9) ); } [Fact] public void ConstraintsChecks_07() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : ID<string>? { } public interface IC<TIC> : IA<TIC> where TIC : ID<string>? {} public interface IE<TIE> : IA<TIE> where TIE : ID<string> {} public interface ID<T> {} class B<TB2, TB3> where TB2 : ID<string>? where TB3 : ID<string> { public void Test1() { IA<TB2> y1; IA<TB3> z1; } public void M1<TM1>(TM1 x) where TM1: ID<string>? {} public void Test2(TB3 b2, TB2 c2) { M1(b2); M1(c2); M1<TB2>(c2); M1<TB3>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics(); } [Fact] public void ConstraintsChecks_08() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class? { } public interface IB<TIB> : IA<TIB> where TIB : C? {} public interface IC<TIC> : IA<TIC> where TIC : C {} public class C {} class B<TB1, TB2> where TB1 : C? where TB2 : C { public void Test1() { IA<TB1> x1; IA<TB2> z1; } public void M1<TM1>(TM1 x) where TM1: class? {} public void Test2(TB1 a2, TB2 b2) { M1(a2); M1(b2); M1<TB1>(a2); M1<TB2>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics(); } [Fact] public void ConstraintsChecks_09() { var source = @" #pragma warning disable CS0168 #nullable disable public interface IA<TA> where TA : ID<string> { } #nullable enable public interface IC : IA<ID<string>?> {} public interface IE : IA<ID<string>> {} public interface ID<T> {} class B { public void Test1() { IA<ID<string>?> y1; IA<ID<string>> z1; } #nullable disable public void M1<TM1>(TM1 x) where TM1: ID<string> {} #nullable enable public void Test2(ID<string> b2, ID<string>? c2) { M1(b2); M1(c2); M1<ID<string>?>(c2); M1<ID<string>>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( ); } [Fact] public void ConstraintsChecks_10() { var source = @" #pragma warning disable CS0168 #nullable disable public interface IA<TA> where TA : class { } #nullable enable public interface IB : IA<string?> {} public interface IC : IA<string> {} class B { public void Test1() { IA<string?> x1; IA<string> z1; } #nullable disable public void M1<TM1>(TM1 x) where TM1: class {} #nullable enable public void Test2(string? a2, string b2) { M1(a2); M1(b2); M1<string?>(a2); M1<string?>(b2); M1<string>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.M1"); Assert.Equal("void B.M1<TM1>(TM1 x) where TM1 : class", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tm1 = m1.TypeParameters[0]; Assert.Null(tm1.ReferenceTypeConstraintIsNullable); Assert.Empty(tm1.GetAttributes()); } } [Fact] public void ConstraintsChecks_11() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : ID<string> { } #nullable disable public interface IB<TIB> : IA<TIB> where TIB : ID<string?> // 1 {} #nullable disable public interface IC<TIC> : IA<TIC> where TIC : ID<string>? // 2 {} #nullable disable public interface IE<TIE> : IA<TIE> where TIE : ID<string> // 3 {} #nullable enable public interface ID<T> {} #nullable disable class B<TB1, TB2, TB3> where TB1 : ID<string?> where TB2 : ID<string>? where TB3 : ID<string> { #nullable enable public void Test1() { IA<TB1> x1; // 4 IA<TB2> y1; // 5 IA<TB3> z1; // 6 } #nullable enable public void M1<TM1>(TM1 x) where TM1: ID<string> {} #nullable enable public void Test2(TB1 a2, TB3 b2, TB2 c2) { M1(a2); // 7 M1(b2); // 8 M1(c2); // 9 M1<TB1>(a2); // 10 M1<TB2>(c2); // 11 M1<TB3>(b2); // 12 } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29678: Constraint violations are not reported for type references outside of method bodies. comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (24,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // IA<TB1> x1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "ID<string>", "TA", "TB1").WithLocation(24, 12), // (25,12): warning CS8631: The type 'TB2' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // IA<TB2> y1; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB2").WithArguments("IA<TA>", "ID<string>", "TA", "TB2").WithLocation(25, 12), // (34,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(34, 9), // (36,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1(c2); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(36, 9), // (37,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1<TB1>(a2); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(37, 9), // (38,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1<TB2>(c2); // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB2>").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(38, 9) ); } [Fact] public void ConstraintsChecks_12() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class { } #nullable disable public interface IB<TIB> : IA<TIB> where TIB : C? // 1 {} #nullable disable public interface IC<TIC> : IA<TIC> where TIC : C // 2 {} #nullable enable public class C {} #nullable disable class B<TB1, TB2> where TB1 : C? where TB2 : C { #nullable enable public void Test1() { IA<TB1> x1; // 3 IA<TB2> z1; // 4 } #nullable enable public void M1<TM1>(TM1 x) where TM1: class {} #nullable enable public void Test2(TB1 a2, TB2 b2) { M1(a2); // 5 M1(b2); // 6 M1<TB1>(a2); // 7 M1<TB2>(b2); // 8 } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29678: Constraint violations are not reported for type references outside of method bodies. comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (21,12): warning CS8634: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // IA<TB1> x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(21, 12), // (30,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1(a2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(30, 9), // (32,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1<TB1>(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<TB1>").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(32, 9) ); } [Fact] public void ConstraintsChecks_13() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class { } public interface IB<TIB> : IA<TIB> where TIB : class? // 1 {} public interface IC<TIC> : IA<TIC> where TIC : class {} class B<TB1, TB2> where TB1 : class? where TB2 : class { public void Test1() { IA<TB1> x1; // 2 IA<TB2> z1; } public void M1<TM1>(TM1 x) where TM1: class {} public void Test2(TB1 a2, TB2 b2) { M1(a2); // 3 M1(b2); M1<TB1>(a2); // 4 M1<TB2>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8634: The type 'TIB' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIB' doesn't match 'class' constraint. // public interface IB<TIB> : IA<TIB> where TIB : class? // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "IB").WithArguments("IA<TA>", "TA", "TIB").WithLocation(8, 18), // (18,12): warning CS8634: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // IA<TB1> x1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(18, 12), // (27,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(27, 9), // (29,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1<TB1>(a2); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<TB1>").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(29, 9) ); } [Fact] public void ConstraintsChecks_14() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class? { } public interface IB<TIB> : IA<TIB> where TIB : class? {} public interface IC<TIC> : IA<TIC> where TIC : class {} class B<TB1, TB2> where TB1 : class? where TB2 : class { public void Test1() { IA<TB1> x1; IA<TB2> z1; } public void M1<TM1>(TM1 x) where TM1: class? {} public void Test2(TB1 a2, TB2 b2) { M1(a2); M1(b2); M1<TB1>(a2); M1<TB2>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics(); } [Fact] public void ConstraintsChecks_15() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class { } #nullable disable public interface IB<TIB> : IA<TIB> where TIB : class? // 1 {} #nullable disable public interface IC<TIC> : IA<TIC> where TIC : class // 2 {} #nullable disable class B<TB1, TB2> where TB1 : class? where TB2 : class { #nullable enable public void Test1() { IA<TB1> x1; // 3 IA<TB2> z1; // 4 } #nullable enable public void M1<TM1>(TM1 x) where TM1: class {} #nullable enable public void Test2(TB1 a2, TB2 b2) { M1(a2); // 5 M1(b2); // 6 M1<TB1>(a2); // 7 M1<TB2>(b2); // 8 } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29678: Constraint violations are not reported for type references outside of method bodies. comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (18,12): warning CS8634: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // IA<TB1> x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(18, 12), // (27,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1(a2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(27, 9), // (29,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1<TB1>(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<TB1>").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(29, 9) ); } [Fact] public void ConstraintsChecks_16() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : IE?, ID<string>, IF? { } public interface IB<TIB> : IA<TIB> where TIB : IE?, ID<string?>, IF? // 1 {} public interface IC<TIC> : IA<TIC> where TIC : IE?, ID<string>?, IF? // 2 {} public interface IE<TIE> : IA<TIE> where TIE : IE?, ID<string>, IF? {} public interface ID<T> {} class B<TB1, TB2, TB3, TB4> where TB1 : IE?, ID<string?>, IF? where TB2 : IE?, ID<string>?, IF? where TB3 : IE?, ID<string>, IF? where TB4 : IE, ID<string>?, IF? { public void Test1() { IA<TB1> x1; // 3 IA<TB2> y1; // 4 IA<TB3> z1; IA<TB4> u1; } public void M1<TM1>(TM1 x) where TM1: IE?, ID<string>, IF? {} public void Test2(TB1 a2, TB3 b2, TB2 c2, TB4 d2) { M1(a2); // 5 M1(b2); M1(c2); // 6 M1(d2); M1<TB1>(a2); // 7 M1<TB2>(c2); // 8 M1<TB3>(b2); M1<TB4>(d2); } } public interface IE {} public interface IF {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8631: The type 'TIB' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIB' doesn't match constraint type 'ID<string>'. // public interface IB<TIB> : IA<TIB> where TIB : IE?, ID<string?>, IF? // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "IB").WithArguments("IA<TA>", "ID<string>", "TA", "TIB").WithLocation(8, 18), // (11,18): warning CS8631: The type 'TIC' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIC' doesn't match constraint type 'ID<string>'. // public interface IC<TIC> : IA<TIC> where TIC : IE?, ID<string>?, IF? // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "IC").WithArguments("IA<TA>", "ID<string>", "TA", "TIC").WithLocation(11, 18), // (28,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // IA<TB1> x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "ID<string>", "TA", "TB1").WithLocation(28, 12), // (29,12): warning CS8631: The type 'TB2' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // IA<TB2> y1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB2").WithArguments("IA<TA>", "ID<string>", "TA", "TB2").WithLocation(29, 12), // (39,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1(a2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(39, 9), // (41,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1(c2); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(41, 9), // (43,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1<TB1>(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(43, 9), // (44,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1<TB2>(c2); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB2>").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(44, 9) ); } [Fact] public void ConstraintsChecks_17() { var source = @" #pragma warning disable CS0168 #nullable disable public interface IA<TA> where TA : IE?, ID<string>, IF? { } #nullable enable public interface IB<TIB> : IA<TIB> where TIB : IE?, ID<string?>, IF? {} public interface IC<TIC> : IA<TIC> where TIC : IE?, ID<string>?, IF? {} public interface IE<TIE> : IA<TIE> where TIE : IE?, ID<string>, IF? {} public interface ID<T> {} class B<TB1, TB2, TB3, TB4> where TB1 : IE?, ID<string?>, IF? where TB2 : IE?, ID<string>?, IF? where TB3 : IE?, ID<string>, IF? where TB4 : IE, ID<string>?, IF? { public void Test1() { IA<TB1> x1; IA<TB2> y1; IA<TB3> z1; IA<TB4> u1; } #nullable disable public void M1<TM1>(TM1 x) where TM1: IE?, ID<string>, IF? {} #nullable enable public void Test2(TB1 a2, TB3 b2, TB2 c2, TB4 d2) { M1(a2); M1(b2); M1(c2); M1(d2); M1<TB1>(a2); M1<TB2>(c2); M1<TB3>(b2); M1<TB4>(d2); } } public interface IE {} public interface IF {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify(); } [Fact] public void ConstraintsChecks_18() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : IE?, ID<string>, IF? { } #nullable disable public interface IB<TIB> : IA<TIB> where TIB : IE?, ID<string?>, IF? // 1 {} #nullable disable public interface IC<TIC> : IA<TIC> where TIC : IE?, ID<string>?, IF? // 2 {} #nullable disable public interface IE<TIE> : IA<TIE> where TIE : IE?, ID<string>, IF? // 3 {} #nullable enable public interface ID<T> {} #nullable disable class B<TB1, TB2, TB3, TB4> where TB1 : IE?, ID<string?>, IF? where TB2 : IE?, ID<string>?, IF? where TB3 : IE?, ID<string>, IF? where TB4 : IE, ID<string>?, IF? { #nullable enable public void Test1() { IA<TB1> x1; // 4 IA<TB2> y1; // 5 IA<TB3> z1; // 6 IA<TB4> u1; // 7 } #nullable enable public void M1<TM1>(TM1 x) where TM1: IE?, ID<string>, IF? {} #nullable enable public void Test2(TB1 a2, TB3 b2, TB2 c2, TB4 d2) { M1(a2); // 8 M1(b2); // 9 M1(c2); // 10 M1(d2); // 11 M1<TB1>(a2); // 12 M1<TB2>(c2); // 13 M1<TB3>(b2); // 14 M1<TB4>(d2); // 15 } } public interface IE {} public interface IF {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29678: Constraint violations are not reported for type references outside of method bodies. comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (33,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // IA<TB1> x1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "ID<string>", "TA", "TB1").WithLocation(33, 12), // (34,12): warning CS8631: The type 'TB2' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // IA<TB2> y1; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB2").WithArguments("IA<TA>", "ID<string>", "TA", "TB2").WithLocation(34, 12), // (46,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1(a2); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(46, 9), // (48,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1(c2); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(48, 9), // (50,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1<TB1>(a2); // 12 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(50, 9), // (51,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1<TB2>(c2); // 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB2>").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(51, 9) ); } [Fact] public void ConstraintsChecks_19() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class, IB, IC { } class B<TB1> where TB1 : class?, IB?, IC? { public void Test1() { IA<TB1> x1; // 1 } public void M1<TM1>(TM1 x) where TM1: class, IB, IC {} public void Test2(TB1 a2) { M1(a2); // 2 M1<TB1>(a2); // 3 } } public interface IB {} public interface IC {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (12,12): warning CS8634: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // IA<TB1> x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(12, 12), // (12,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'IB'. // IA<TB1> x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "IB", "TA", "TB1").WithLocation(12, 12), // (12,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'IC'. // IA<TB1> x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "IC", "TA", "TB1").WithLocation(12, 12), // (20,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1(a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("B<TB1>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(20, 9), // (20,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IB'. // M1(a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1>(TM1)", "IB", "TM1", "TB1").WithLocation(20, 9), // (20,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IC'. // M1(a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1>(TM1)", "IC", "TM1", "TB1").WithLocation(20, 9), // (21,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1<TB1>(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<TB1>").WithArguments("B<TB1>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(21, 9), // (21,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IB'. // M1<TB1>(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1>.M1<TM1>(TM1)", "IB", "TM1", "TB1").WithLocation(21, 9), // (21,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IC'. // M1<TB1>(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1>.M1<TM1>(TM1)", "IC", "TM1", "TB1").WithLocation(21, 9) ); } [Fact] public void ConstraintsChecks_20() { var source = @" class B<TB1> where TB1 : class, IB? { public void M1<TM1, TM2>(TM1 x, TM2 y) where TM2 : TM1 {} public void Test2(TB1? a2, TB1 b2) { M1(b2, a2); // 1 M1<TB1, TB1?>(b2, a2); // 2 } } public interface IB {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (9,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1(b2, a2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(9, 9), // (10,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1<TB1, TB1?>(b2, a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1, TB1?>").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(10, 9) ); } [Fact] public void ConstraintsChecks_21() { var source = @" class B<TB1> where TB1 : class?, IB { public void M1<TM1, TM2>(TM1 x, TM2 y) where TM2 : TM1 {} public void Test2(TB1? a2, TB1 b2) { M1(b2, a2); // 1 M1<TB1, TB1?>(b2, a2); // 2 } } public interface IB {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (9,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1(b2, a2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(9, 9), // (10,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1<TB1, TB1?>(b2, a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1, TB1?>").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(10, 9) ); } [Fact] public void ConstraintsChecks_22() { var source = @" class B<TB1> where TB1 : class, IB? { #nullable disable public void M1<TM1, TM2>(TM1 x, TM2 y) where TM2 : TM1 {} #nullable enable public void Test2(TB1? a2, TB1 b2) { M1(b2, a2); // 1 M1<TB1, TB1?>(b2, a2); // 2 } } public interface IB {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (9,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1(b2, a2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(9, 9), // (10,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1<TB1, TB1?>(b2, a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1, TB1?>").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(10, 9) ); } [Fact] public void ConstraintsChecks_23() { var source = @" class B<TB1> where TB1 : A?, IB, IC? { public void M1<TM1, TM2>(TM1 x, TM2 y) where TM2 : TM1 {} public void Test2(TB1? a2, TB1 b2) { M1(b2, a2); // 1 M1<TB1, TB1?>(b2, a2); // 2 } } public class A {} public interface IB {} public interface IC {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (9,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1(b2, a2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(9, 9), // (10,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1<TB1, TB1?>(b2, a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1, TB1?>").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(10, 9) ); } [Fact] public void ConstraintsChecks_24() { var source = @" class B<TB1> where TB1 : A?, IB, IC? { #nullable disable public void M1<TM1, TM2>(TM1 x, TM2 y) where TM2 : TM1 {} #nullable enable public void Test2(TB1? a2, TB1 b2) { M1(b2, a2); // 1 M1<TB1, TB1?>(b2, a2); // 2 } } public class A {} public interface IB {} public interface IC {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (9,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1(b2, a2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(9, 9), // (10,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1<TB1, TB1?>(b2, a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1, TB1?>").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(10, 9) ); } [Fact] public void ConstraintsChecks_25() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : notnull { } public interface IB : IA<string?> // 1 {} public interface IC : IA<string> {} class B { public void Test1() { IA<string?> x1; // 2 IA<string> z1; } public void M1<TM1>(TM1 x) where TM1: notnull {} public void Test2(string? a2, string b2) { M1(a2); // 3 M1(b2); M1<string?>(a2); // 4 M1<string?>(b2); // 5 M1<string>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8714: The type 'string?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // public interface IB : IA<string?> // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "IB").WithArguments("IA<TA>", "TA", "string?").WithLocation(8, 18), // (18,12): warning CS8714: The type 'string?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // IA<string?> x1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("IA<TA>", "TA", "string?").WithLocation(18, 12), // (27,9): warning CS8714: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M1(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(27, 9), // (29,9): warning CS8714: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M1<string?>(a2); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<string?>").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(29, 9), // (30,9): warning CS8714: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M1<string?>(b2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<string?>").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(30, 9) ); } [Fact] public void ConstraintsChecks_26() { var source = @" #pragma warning disable CS0168 #nullable disable public interface IA<TA> where TA : notnull { } #nullable enable public interface IB : IA<string?> {} public interface IC : IA<string> {} class B { public void Test1() { IA<string?> x1; IA<string> z1; } #nullable disable public void M1<TM1>(TM1 x) where TM1: notnull {} #nullable enable public void Test2(string? a2, string b2) { M1(a2); M1(b2); M1<string?>(a2); M1<string?>(b2); M1<string>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8714: The type 'string?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // public interface IB : IA<string?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "IB").WithArguments("IA<TA>", "TA", "string?").WithLocation(8, 18), // (18,12): warning CS8714: The type 'string?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // IA<string?> x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("IA<TA>", "TA", "string?").WithLocation(18, 12), // (27,9): warning CS8714: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M1(a2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(27, 9), // (29,9): warning CS8714: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M1<string?>(a2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<string?>").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(29, 9), // (30,9): warning CS8714: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M1<string?>(b2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<string?>").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(30, 9) ); } [Fact] [WorkItem(34843, "https://github.com/dotnet/roslyn/issues/34843")] public void ConstraintsChecks_27() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : notnull { } #nullable disable public interface IB<TIB> : IA<TIB> where TIB : C? // 1 {} #nullable disable public interface IC<TIC> : IA<TIC> where TIC : C // 2 {} public class C {} #nullable disable class B<TB1, TB2> where TB1 : C? where TB2 : C { #nullable enable public void Test1() { IA<TB1> x1; // 3 IA<TB2> z1; // 4 } #nullable enable public void M1<TM1>(TM1 x) where TM1: notnull {} #nullable enable public void Test2(TB1 a2, TB2 b2) { M1(a2); // 5 M1(b2); // 6 M1<TB1>(a2); // 7 M1<TB2>(b2); // 8 } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29678: Constraint violations are not reported for type references outside of method bodies. comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (21,12): warning CS8714: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // IA<TB1> x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(21, 12), // (30,9): warning CS8714: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // M1(a2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(30, 9), // (32,9): warning CS8714: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // M1<TB1>(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<TB1>").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(32, 9) ); } [Fact] public void ConstraintsChecks_28() { var source0 = @" public interface IA<TA> where TA : notnull { } public class A { public void M1<TM1>(TM1 x) where TM1: notnull {} } "; var source1 = @" #pragma warning disable CS0168 public interface IB<TIB> : IA<TIB> // 1 {} public interface IC<TIC> : IA<TIC> where TIC : notnull {} class B<TB1, TB2> : A where TB2 : notnull { public void Test1() { IA<TB1> x1; // 2 IA<TB2> z1; } public void Test2(TB1 a2, TB2 b2) { M1(a2); // 3 M1(b2); M1<TB1>(a2); // 4 M1<TB2>(b2); } } "; var comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); foreach (var reference in new[] { comp0.ToMetadataReference(), comp0.EmitToImageReference() }) { var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { reference }); comp1.VerifyDiagnostics( // (4,18): warning CS8714: The type 'TIB' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIB' doesn't match 'notnull' constraint. // public interface IB<TIB> : IA<TIB> // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "IB").WithArguments("IA<TA>", "TA", "TIB").WithLocation(4, 18), // (14,12): warning CS8714: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // IA<TB1> x1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(14, 12), // (20,9): warning CS8714: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'A.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // M1(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("A.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(20, 9), // (22,9): warning CS8714: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'A.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // M1<TB1>(a2); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<TB1>").WithArguments("A.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(22, 9) ); } } [Fact] public void ConstraintsChecks_29() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : notnull { } #nullable disable public interface IB<TIB> : IA<TIB> // 1 {} #nullable disable public interface IC<TIC> : IA<TIC> where TIC : notnull // 2 {} #nullable disable class B<TB1, TB2> where TB2 : notnull { #nullable enable public void Test1() { IA<TB1> x1; // 3 IA<TB2> z1; // 4 } #nullable enable public void M1<TM1>(TM1 x) where TM1: notnull {} #nullable enable public void Test2(TB1 a2, TB2 b2) { M1(a2); // 5 M1(b2); // 6 M1<TB1>(a2); // 7 M1<TB2>(b2); // 8 } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29678: Constraint violations are not reported for type references outside of method bodies. comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify(); } [Fact] public void ConstraintsChecks_30() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : notnull, IB, IC { } class B<TB1> where TB1 : IB?, IC? { public void Test1() { IA<TB1> x1; // 1 } public void M1<TM1>(TM1 x) where TM1: notnull, IB, IC {} public void Test2(TB1 a2) { M1(a2); // 2 M1<TB1>(a2); // 3 } } public interface IB {} public interface IC {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (12,12): warning CS8714: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // IA<TB1> x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(12, 12), // (12,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'IB'. // IA<TB1> x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "IB", "TA", "TB1").WithLocation(12, 12), // (12,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'IC'. // IA<TB1> x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "IC", "TA", "TB1").WithLocation(12, 12), // (20,9): warning CS8714: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // M1(a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("B<TB1>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(20, 9), // (20,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IB'. // M1(a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1>(TM1)", "IB", "TM1", "TB1").WithLocation(20, 9), // (20,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IC'. // M1(a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1>(TM1)", "IC", "TM1", "TB1").WithLocation(20, 9), // (21,9): warning CS8714: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // M1<TB1>(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<TB1>").WithArguments("B<TB1>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(21, 9), // (21,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IB'. // M1<TB1>(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1>.M1<TM1>(TM1)", "IB", "TM1", "TB1").WithLocation(21, 9), // (21,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IC'. // M1<TB1>(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1>.M1<TM1>(TM1)", "IC", "TM1", "TB1").WithLocation(21, 9) ); } [Fact] [WorkItem(34892, "https://github.com/dotnet/roslyn/issues/34892")] public void ConstraintsChecks_31() { var source = @" #nullable enable public class AA { public void M3<T3>(T3 z) where T3 : class { } public void M4<T4>(T4 z) where T4 : AA { } #nullable disable public void F1<T1>(T1 x) where T1 : class { #nullable enable M3<T1>(x); } #nullable disable public void F2<T2>(T2 x) where T2 : AA { #nullable enable M4<T2>(x); } } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics(); } [Fact] [WorkItem(34844, "https://github.com/dotnet/roslyn/issues/34844")] public void ConstraintsChecks_32() { var source = @" #pragma warning disable CS0649 #nullable disable class A<T1, T2, T3> where T2 : class where T3 : notnull { T1 F1; T2 F2; T3 F3; B F4; #nullable enable void M3() { C.Test<T1>(); C.Test<T2>(); C.Test<T3>(); } void M4() { D.Test(F1); D.Test(F2); D.Test(F3); D.Test(F4); } } class B {} class C { public static void Test<T>() where T : notnull {} } class D { public static void Test<T>(T x) where T : notnull {} } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics(); } [Fact] [WorkItem(29981, "https://github.com/dotnet/roslyn/issues/29981")] public void UnconstrainedTypeParameter_MayBeNonNullable() { var source = @"class C1<T1> { static object? NullableObject() => null; static T1 F1() => default; // warn: return type T1 may be non-null static T1 F2() => default(T1); // warn: return type T1 may be non-null static T1 F4() { T1 t1 = (T1)NullableObject(); return t1; } } class C2<T2> where T2 : class { static object? NullableObject() => null; static T2 F1() => default; // warn: return type T2 may be non-null static T2 F2() => default(T2); // warn: return type T2 may be non-null static T2 F4() { T2 t2 = (T2)NullableObject(); // warn: T2 may be non-null return t2; } } class C3<T3> where T3 : new() { static object? NullableObject() => null; static T3 F1() => default; // warn: return type T3 may be non-null static T3 F2() => default(T3); // warn: return type T3 may be non-null static T3 F3() => new T3(); static T3 F4() { T3 t = (T3)NullableObject(); // warn: T3 may be non-null return t3; } } class C4<T4> where T4 : I { static object? NullableObject() => null; static T4 F1() => default; // warn: return type T4 may be non-null static T4 F2() => default(T4); // warn: return type T4 may be non-null static T4 F4() { T4 t4 = (T4)NullableObject(); // warn: T4 may be non-null return t4; } } class C5<T5> where T5 : A { static object? NullableObject() => null; static T5 F1() => default; // warn: return type T5 may be non-null static T5 F2() => default(T5); // warn: return type T5 may be non-null static T5 F4() { T5 t5 = (T5)NullableObject(); // warn: T5 may be non-null return t5; } } interface I { } class A { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T1 t1 = (T1)NullableObject(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T1)NullableObject()").WithLocation(8, 17), // (9,16): warning CS8603: Possible null reference return. // return t1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(9, 16), // (15,23): warning CS8603: Possible null reference return. // static T2 F1() => default; // warn: return type T2 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(15, 23), // (16,23): warning CS8603: Possible null reference return. // static T2 F2() => default(T2); // warn: return type T2 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T2)").WithLocation(16, 23), // (19,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T2 t2 = (T2)NullableObject(); // warn: T2 may be non-null Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T2)NullableObject()").WithLocation(19, 17), // (20,16): warning CS8603: Possible null reference return. // return t2; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(20, 16), // (26,23): warning CS8603: Possible null reference return. // static T3 F1() => default; // warn: return type T3 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(26, 23), // (27,23): warning CS8603: Possible null reference return. // static T3 F2() => default(T3); // warn: return type T3 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T3)").WithLocation(27, 23), // (31,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T3 t = (T3)NullableObject(); // warn: T3 may be non-null Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T3)NullableObject()").WithLocation(31, 16), // (32,16): error CS0103: The name 't3' does not exist in the current context // return t3; Diagnostic(ErrorCode.ERR_NameNotInContext, "t3").WithArguments("t3").WithLocation(32, 16), // (38,23): warning CS8603: Possible null reference return. // static T4 F1() => default; // warn: return type T4 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(38, 23), // (39,23): warning CS8603: Possible null reference return. // static T4 F2() => default(T4); // warn: return type T4 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T4)").WithLocation(39, 23), // (42,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T4 t4 = (T4)NullableObject(); // warn: T4 may be non-null Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T4)NullableObject()").WithLocation(42, 17), // (43,16): warning CS8603: Possible null reference return. // return t4; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t4").WithLocation(43, 16), // (49,23): warning CS8603: Possible null reference return. // static T5 F1() => default; // warn: return type T5 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(49, 23), // (50,23): warning CS8603: Possible null reference return. // static T5 F2() => default(T5); // warn: return type T5 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T5)").WithLocation(50, 23), // (53,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T5 t5 = (T5)NullableObject(); // warn: T5 may be non-null Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T5)NullableObject()").WithLocation(53, 17), // (54,16): warning CS8603: Possible null reference return. // return t5; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t5").WithLocation(54, 16), // (4,23): warning CS8603: Possible null reference return. // static T1 F1() => default; // warn: return type T1 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(4, 23), // (5,23): warning CS8603: Possible null reference return. // static T1 F2() => default(T1); // warn: return type T1 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T1)").WithLocation(5, 23)); } [Fact] public void UnconstrainedTypeParameter_MayBeNullable_01() { var source = @"class C { static void F(object o) { } static void F1<T1>(bool b, T1 t1) { if (b) F(t1); if (b) F((object)t1); t1.ToString(); } static void F2<T2>(bool b, T2 t2) where T2 : struct { if (b) F(t2); if (b) F((object)t2); t2.ToString(); } static void F3<T3>(bool b, T3 t3) where T3 : class { if (b) F(t3); if (b) F((object)t3); t3.ToString(); } static void F4<T4>(bool b, T4 t4) where T4 : new() { if (b) F(t4); if (b) F((object)t4); t4.ToString(); } static void F5<T5>(bool b, T5 t5) where T5 : I { if (b) F(t5); if (b) F((object)t5); t5.ToString(); } static void F6<T6>(bool b, T6 t6) where T6 : A { if (b) F(t6); if (b) F((object)t6); t6.ToString(); } } interface I { } class A { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // if (b) F(t1); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t1").WithArguments("o", "void C.F(object o)").WithLocation(8, 18), // (9,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (b) F((object)t1); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t1").WithLocation(9, 18), // (9,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // if (b) F((object)t1); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(object)t1").WithArguments("o", "void C.F(object o)").WithLocation(9, 18), // (10,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(10, 9), // (26,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // if (b) F(t4); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t4").WithArguments("o", "void C.F(object o)").WithLocation(26, 18), // (27,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (b) F((object)t4); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t4").WithLocation(27, 18), // (27,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // if (b) F((object)t4); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(object)t4").WithArguments("o", "void C.F(object o)").WithLocation(27, 18), // (28,9): warning CS8602: Dereference of a possibly null reference. // t4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t4").WithLocation(28, 9) ); } [Fact] public void UnconstrainedTypeParameter_MayBeNullable_02() { var source = @"class C { static void F1<T1>(T1 x1) { object? y1; y1 = (object?)x1; y1 = (object)x1; // warn: T1 may be null } static void F2<T2>(T2 x2) where T2 : class { object? y2; y2 = (object?)x2; y2 = (object)x2; } static void F3<T3>(T3 x3) where T3 : new() { object? y3; y3 = (object?)x3; y3 = (object)x3; // warn unless new() constraint implies non-nullable y3 = (object)new T3(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y1 = (object)x1; // warn: T1 may be null Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)x1").WithLocation(7, 14), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y3 = (object)x3; // warn unless new() constraint implies non-nullable Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)x3").WithLocation(19, 14) ); } [Fact] public void UnconstrainedTypeParameter_Return_01() { var source = @"class C { static object? F01<T>(T t) => t; static object? F02<T>(T t) where T : class => t; static object? F03<T>(T t) where T : struct => t; static object? F04<T>(T t) where T : new() => t; static object? F05<T, U>(U u) where U : T => u; static object? F06<T, U>(U u) where U : class, T => u; static object? F07<T, U>(U u) where U : struct, T => u; static object? F08<T, U>(U u) where U : T, new() => u; static object? F09<T>(T t) => (object?)t; static object? F10<T>(T t) where T : class => (object?)t; static object? F11<T>(T t) where T : struct => (object?)t; static object? F12<T>(T t) where T : new() => (object?)t; static object? F13<T, U>(U u) where U : T => (object?)u; static object? F14<T, U>(U u) where U : class, T => (object?)u; static object? F15<T, U>(U u) where U : struct, T => (object?)u; static object? F16<T, U>(U u) where U : T, new() => (object?)u; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void UnconstrainedTypeParameter_Return_02() { var source = @"class C { static object F01<T>(T t) => t; static object F02<T>(T t) where T : class => t; static object F03<T>(T t) where T : struct => t; static object F04<T>(T t) where T : new() => t; static object F05<T, U>(U u) where U : T => u; static object F06<T, U>(U u) where U : class, T => u; static object F07<T, U>(U u) where U : struct, T => u; static object F08<T, U>(U u) where U : T, new() => u; static object F09<T>(T t) => (object)t; static object F10<T>(T t) where T : class => (object)t; static object F11<T>(T t) where T : struct => (object)t; static object F12<T>(T t) where T : new() => (object)t; static object F13<T, U>(U u) where U : T => (object)u; static object F14<T, U>(U u) where U : class, T => (object)u; static object F15<T, U>(U u) where U : struct, T => (object)u; static object F16<T, U>(U u) where U : T, new() => (object)u; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,34): warning CS8603: Possible null reference return. // static object F01<T>(T t) => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(3, 34), // (6,50): warning CS8603: Possible null reference return. // static object F04<T>(T t) where T : new() => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 50), // (7,49): warning CS8603: Possible null reference return. // static object F05<T, U>(U u) where U : T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(7, 49), // (10,56): warning CS8603: Possible null reference return. // static object F08<T, U>(U u) where U : T, new() => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 56), // (11,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // static object F09<T>(T t) => (object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(11, 34), // (11,34): warning CS8603: Possible null reference return. // static object F09<T>(T t) => (object)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(object)t").WithLocation(11, 34), // (14,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // static object F12<T>(T t) where T : new() => (object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(14, 50), // (14,50): warning CS8603: Possible null reference return. // static object F12<T>(T t) where T : new() => (object)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(object)t").WithLocation(14, 50), // (15,49): warning CS8600: Converting null literal or possible null value to non-nullable type. // static object F13<T, U>(U u) where U : T => (object)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)u").WithLocation(15, 49), // (15,49): warning CS8603: Possible null reference return. // static object F13<T, U>(U u) where U : T => (object)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(object)u").WithLocation(15, 49), // (18,56): warning CS8600: Converting null literal or possible null value to non-nullable type. // static object F16<T, U>(U u) where U : T, new() => (object)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)u").WithLocation(18, 56), // (18,56): warning CS8603: Possible null reference return. // static object F16<T, U>(U u) where U : T, new() => (object)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(object)u").WithLocation(18, 56)); } [Fact] public void UnconstrainedTypeParameter_Return_03() { var source = @"class C { static T F01<T>(T t) => t; static T F02<T>(T t) where T : class => t; static T F03<T>(T t) where T : struct => t; static T F04<T>(T t) where T : new() => t; static T F05<T, U>(U u) where U : T => u; static T F06<T, U>(U u) where U : class, T => u; static T F07<T, U>(U u) where U : struct, T => u; static T F08<T, U>(U u) where U : T, new() => u; static T F09<T>(T t) => (T)t; static T F10<T>(T t) where T : class => (T)t; static T F11<T>(T t) where T : struct => (T)t; static T F12<T>(T t) where T : new() => (T)t; static T F13<T, U>(U u) where U : T => (T)u; static T F14<T, U>(U u) where U : class, T => (T)u; static T F15<T, U>(U u) where U : struct, T => (T)u; static T F16<T, U>(U u) where U : T, new() => (T)u; static U F17<T, U>(T t) where U : T => (U)t; // W on return static U F18<T, U>(T t) where U : class, T => (U)t; // W on cast, W on return static U F19<T, U>(T t) where U : struct, T => (U)t; static U F20<T, U>(T t) where U : T, new() => (U)t; // W on return static U F21<T, U>(T t) => (U)(object)t; // W on cast, W on return }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,44): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F17<T, U>(T t) where U : T => (U)t; // W on return Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(19, 44), // (19,44): warning CS8603: Possible null reference return. // static U F17<T, U>(T t) where U : T => (U)t; // W on return Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(19, 44), // (20,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F18<T, U>(T t) where U : class, T => (U)t; // W on cast, W on return Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(20, 51), // (20,51): warning CS8603: Possible null reference return. // static U F18<T, U>(T t) where U : class, T => (U)t; // W on cast, W on return Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(20, 51), // (21,52): warning CS8605: Unboxing a possibly null value. // static U F19<T, U>(T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(21, 52), // (22,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F20<T, U>(T t) where U : T, new() => (U)t; // W on return Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 51), // (22,51): warning CS8603: Possible null reference return. // static U F20<T, U>(T t) where U : T, new() => (U)t; // W on return Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(22, 51), // (23,32): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>(T t) => (U)(object)t; // W on cast, W on return Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)t").WithLocation(23, 32), // (23,32): warning CS8603: Possible null reference return. // static U F21<T, U>(T t) => (U)(object)t; // W on cast, W on return Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)(object)t").WithLocation(23, 32), // (23,35): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>(T t) => (U)(object)t; // W on cast, W on return Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(23, 35)); } [Fact] public void UnconstrainedTypeParameter_Uninitialized() { var source = @" class C { static void F1<T>() { T t; t.ToString(); // 1 } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): error CS0165: Use of unassigned local variable 't' // t.ToString(); // 1 Diagnostic(ErrorCode.ERR_UseDefViolation, "t").WithArguments("t").WithLocation(7, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(7, 9)); } [Fact] [WorkItem(29981, "https://github.com/dotnet/roslyn/issues/29981")] public void UnconstrainedTypeParameter_OutVariable() { var source = @" class C { static void F1<T>(out T t) => t = default; // 1 static void F2<T>(out T t) => t = default(T); // 2 static void F3<T>(T t1, out T t2) => t2 = t1; static void F4<T, U>(U u, out T t) where U : T => t = u; static void F5<T, U>(U u, out T t) where T : U => t = (T)u; // 3 static void F6<T, U>(U u, out T t) => t = (T)(object)u; // 4 } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,39): warning CS8601: Possible null reference assignment. // static void F1<T>(out T t) => t = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(4, 39), // (5,39): warning CS8601: Possible null reference assignment. // static void F2<T>(out T t) => t = default(T); // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default(T)").WithLocation(5, 39), // (8,59): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F5<T, U>(U u, out T t) where T : U => t = (T)u; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(8, 59), // (8,59): warning CS8601: Possible null reference assignment. // static void F5<T, U>(U u, out T t) where T : U => t = (T)u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "(T)u").WithLocation(8, 59), // (9,47): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F6<T, U>(U u, out T t) => t = (T)(object)u; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)(object)u").WithLocation(9, 47), // (9,47): warning CS8601: Possible null reference assignment. // static void F6<T, U>(U u, out T t) => t = (T)(object)u; // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "(T)(object)u").WithLocation(9, 47), // (9,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F6<T, U>(U u, out T t) => t = (T)(object)u; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)u").WithLocation(9, 50)); } [Fact] [WorkItem(29983, "https://github.com/dotnet/roslyn/issues/29983")] public void UnconstrainedTypeParameter_TypeInferenceThroughCall() { var source = @" class C { static T Copy<T>(T t) => t; static void CopyOut<T>(T t1, out T t2) => t2 = t1; static void CopyOutInherit<T1, T2>(T1 t1, out T2 t2) where T1 : T2 => t2 = t1; static void M<U>(U u) { var x1 = Copy(u); x1.ToString(); // 1 CopyOut(u, out var x2); x2.ToString(); // 2 CopyOut(u, out U x3); x3.ToString(); // 3 if (u == null) throw null!; var x4 = Copy(u); x4.ToString(); CopyOut(u, out var x5); x5.ToString(); CopyOut(u, out U x6); x6.ToString(); CopyOutInherit(u, out var x7); x7.ToString(); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29983: Should not report warning for `x6.ToString()`. comp.VerifyDiagnostics( // (29,9): error CS0411: The type arguments for method 'C.CopyOutInherit<T1, T2>(T1, out T2)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // CopyOutInherit(u, out var x7); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "CopyOutInherit").WithArguments("C.CopyOutInherit<T1, T2>(T1, out T2)").WithLocation(29, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(10, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(13, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(16, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // x4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(21, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // x5.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x5").WithLocation(24, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // x6.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x6").WithLocation(27, 9)); } [Fact] [WorkItem(29993, "https://github.com/dotnet/roslyn/issues/29993")] public void TypeParameter_Return_01() { var source = @" class C { static U F1<T, U>(T t) => (U)(object)t; // 1 and 2 static U F2<T, U>(T t) where U : class => (U)(object)t; // 3, 4 and 5 static U F3<T, U>(T t) where U : struct => (U)(object)t; // 6 static U F4<T, U>(T t) where T : class => (U)(object)t; static U F5<T, U>(T t) where T : struct => (U)(object)t; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29993: Errors are different than expected. comp.VerifyDiagnostics( // (4,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F1<T, U>(T t) => (U)(object)t; // 1 and 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(4, 34), // (4,31): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F1<T, U>(T t) => (U)(object)t; // 1 and 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)t").WithLocation(4, 31), // (4,31): warning CS8603: Possible null reference return. // static U F1<T, U>(T t) => (U)(object)t; // 1 and 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)(object)t").WithLocation(4, 31), // (5,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F2<T, U>(T t) where U : class => (U)(object)t; // 3, 4 and 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(5, 50), // (5,47): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F2<T, U>(T t) where U : class => (U)(object)t; // 3, 4 and 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)t").WithLocation(5, 47), // (5,47): warning CS8603: Possible null reference return. // static U F2<T, U>(T t) where U : class => (U)(object)t; // 3, 4 and 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)(object)t").WithLocation(5, 47), // (6,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F3<T, U>(T t) where U : struct => (U)(object)t; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(6, 51), // (6,48): warning CS8605: Unboxing a possibly null value. // static U F3<T, U>(T t) where U : struct => (U)(object)t; // 6 Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)(object)t").WithLocation(6, 48) ); } [Fact] public void TrackUnconstrainedTypeParameter_LocalsAndParameters() { var source = @"class C { static void F0<T>() { default(T).ToString(); // 1 default(T)?.ToString(); } static void F1<T>() { T x1 = default; x1.ToString(); // 3 x1!.ToString(); x1?.ToString(); if (x1 != null) x1.ToString(); T y1 = x1; y1.ToString(); // 4 } static void F2<T>(T x2, T[] a2) { x2.ToString(); // 5 x2!.ToString(); x2?.ToString(); if (x2 != null) x2.ToString(); T y2 = x2; y2.ToString(); // 6 a2[0].ToString(); // 7 } static void F3<T>() where T : new() { T x3 = new T(); x3.ToString(); x3!.ToString(); var a3 = new[] { new T() }; a3[0].ToString(); // 8 } static T F4<T>(T x4) { T y4 = x4; return y4; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // default(T).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T)").WithLocation(5, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(16, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(20, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(25, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // a2[0].ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2[0]").WithLocation(26, 9), // (34,9): warning CS8602: Dereference of a possibly null reference. // a3[0].ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a3[0]").WithLocation(34, 9) ); } [Fact] public void TrackUnconstrainedTypeParameter_ExplicitCast() { var source = @"class C { static void F(object o) { } static void F1<T1>(T1 t1) { F((object)t1); if (t1 != null) F((object)t1); } static void F2<T2>(T2 t2) where T2 : class { F((object)t2); if (t2 != null) F((object)t2); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,11): warning CS8600: Converting null literal or possible null value to non-nullable type. // F((object)t1); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t1").WithLocation(8, 11), // (8,11): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // F((object)t1); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(object)t1").WithArguments("o", "void C.F(object o)").WithLocation(8, 11) ); } [Fact] public void NullableT_BaseAndInterfaces() { var source = @"interface IA<T> { } interface IB<T> : IA<T?> { } interface IC<T> { } class A<T> { } class B<T> : A<(T, T?)> { } class C<T, U, V> : A<T?>, IA<U>, IC<V> { } class D<T, U, V> : A<T>, IA<U?>, IC<V> { } class E<T, U, V> : A<T>, IA<U>, IC<V?> { } class P { static void F1(IB<object> o) { } static void F2(B<object> o) { } static void F3(C<object, object, object> o) { } static void F4(D<object, object, object> o) { } static void F5(E<object, object, object> o) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (2,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // interface IB<T> : IA<T?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(2, 22), // (5,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class B<T> : A<(T, T?)> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 20), // (6,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C<T, U, V> : A<T?>, IA<U>, IC<V> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(6, 22), // (7,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class D<T, U, V> : A<T>, IA<U?>, IC<V> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(7, 29), // (8,36): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class E<T, U, V> : A<T>, IA<U>, IC<V?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "V?").WithArguments("9.0").WithLocation(8, 36) ); } [Fact] public void NullableT_Constraints() { var source = @"interface I<T, U> where U : T? { } class A<T> { } class B { static void F<T, U>() where U : A<T?> { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (1,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // interface I<T, U> where U : T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(1, 29), // (5,39): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F<T, U>() where U : A<T?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 39) ); } [Fact] [WorkItem(29995, "https://github.com/dotnet/roslyn/issues/29995")] public void NullableT_Members() { var source = @"using System; #pragma warning disable 0067 #pragma warning disable 0169 #pragma warning disable 8618 delegate T? D<T>(); class A<T> { } class B<T> { const object c = default(T?[]); T? F; B(T? t) { } static void M<U>(T? t, U? u) { } static B<T?> P { get; set; } event EventHandler<T?> E; public static explicit operator A<T?>(B<T> t) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); // https://github.com/dotnet/roslyn/issues/29995: Report error for `const object c = default(T?[]);`. comp.VerifyDiagnostics( // (5,10): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // delegate T? D<T>(); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 10), // (11,30): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // const object c = default(T?[]); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(11, 30), // (12,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? F; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(12, 5), // (13,7): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // B(T? t) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(13, 7), // (14,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void M<U>(T? t, U? u) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(14, 22), // (14,28): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void M<U>(T? t, U? u) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(14, 28), // (15,14): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static B<T?> P { get; set; } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(15, 14), // (16,24): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // event EventHandler<T?> E; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(16, 24), // (17,39): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static explicit operator A<T?>(B<T> t) => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(17, 39) ); } [Fact] public void NullableT_ReturnType() { var source = @"interface I { } class A { } class B { static T? F1<T>() => throw null!; // error static T? F2<T>() where T : class => throw null!; static T? F3<T>() where T : struct => throw null!; static T? F4<T>() where T : new() => throw null!; // error static T? F5<T>() where T : unmanaged => throw null!; static T? F6<T>() where T : I => throw null!; // error static T? F7<T>() where T : A => throw null!; } class C { static U?[] F1<T, U>() where U : T => throw null!; // error static U?[] F2<T, U>() where T : class where U : T => throw null!; static U?[] F3<T, U>() where T : struct where U : T => throw null!; static U?[] F4<T, U>() where T : new() where U : T => throw null!; // error static U?[] F5<T, U>() where T : unmanaged where U : T => throw null!; static U?[] F6<T, U>() where T : I where U : T => throw null!; // error static U?[] F7<T, U>() where T : A where U : T => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (16,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static U?[] F2<T, U>() where T : class where U : T => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(16, 12), // (8,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static T? F4<T>() where T : new() => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 12), // (18,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static U?[] F4<T, U>() where T : new() where U : T => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(18, 12), // (10,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static T? F6<T>() where T : I => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(10, 12), // (20,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static U?[] F6<T, U>() where T : I where U : T => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(20, 12), // (5,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static T? F1<T>() => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 12), // (15,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static U?[] F1<T, U>() where U : T => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(15, 12), // (17,23): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' // static U?[] F3<T, U>() where T : struct where U : T => throw null!; Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(17, 23), // (19,23): error CS8379: Type parameter 'T' has the 'unmanaged' constraint so 'T' cannot be used as a constraint for 'U' // static U?[] F5<T, U>() where T : unmanaged where U : T => throw null!; Diagnostic(ErrorCode.ERR_ConWithUnmanagedCon, "U").WithArguments("U", "T").WithLocation(19, 23)); } [Fact] public void NullableT_Parameters() { var source = @"interface I { } abstract class A { internal abstract void F1<T>(T? t); // error internal abstract void F2<T>(T? t) where T : class; internal abstract void F3<T>(T? t) where T : struct; internal abstract void F4<T>(T? t) where T : new(); // error internal abstract void F5<T>(T? t) where T : unmanaged; internal abstract void F6<T>(T? t) where T : I; // error internal abstract void F7<T>(T? t) where T : A; } class B : A { internal override void F1<U>(U? u) { } // error internal override void F2<U>(U? u) { } internal override void F3<U>(U? u) { } internal override void F4<U>(U? u) { } // error internal override void F5<U>(U? u) { } internal override void F6<U>(U? u) { } // error internal override void F7<U>(U? u) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,34): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // internal abstract void F1<T>(T? t); // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 34), // (7,34): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // internal abstract void F4<T>(T? t) where T : new(); // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 34), // (9,34): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // internal abstract void F6<T>(T? t) where T : I; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(9, 34), // (12,7): error CS0534: 'B' does not implement inherited abstract member 'A.F4<T>(T?)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F4<T>(T?)").WithLocation(12, 7), // (12,7): error CS0534: 'B' does not implement inherited abstract member 'A.F1<T>(T?)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F1<T>(T?)").WithLocation(12, 7), // (12,7): error CS0534: 'B' does not implement inherited abstract member 'A.F2<T>(T?)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F2<T>(T?)").WithLocation(12, 7), // (12,7): error CS0534: 'B' does not implement inherited abstract member 'A.F6<T>(T?)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F6<T>(T?)").WithLocation(12, 7), // (12,7): error CS0534: 'B' does not implement inherited abstract member 'A.F7<T>(T?)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F7<T>(T?)").WithLocation(12, 7), // (14,28): error CS0115: 'B.F1<U>(U?)': no suitable method found to override // internal override void F1<U>(U? u) { } // error Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B.F1<U>(U?)").WithLocation(14, 28), // (14,37): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // internal override void F1<U>(U? u) { } // error Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(14, 37), // (15,28): error CS0115: 'B.F2<U>(U?)': no suitable method found to override // internal override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B.F2<U>(U?)").WithLocation(15, 28), // (15,37): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // internal override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(15, 37), // (17,28): error CS0115: 'B.F4<U>(U?)': no suitable method found to override // internal override void F4<U>(U? u) { } // error Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F4").WithArguments("B.F4<U>(U?)").WithLocation(17, 28), // (17,37): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // internal override void F4<U>(U? u) { } // error Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(17, 37), // (19,28): error CS0115: 'B.F6<U>(U?)': no suitable method found to override // internal override void F6<U>(U? u) { } // error Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F6").WithArguments("B.F6<U>(U?)").WithLocation(19, 28), // (19,37): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // internal override void F6<U>(U? u) { } // error Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 37), // (20,28): error CS0115: 'B.F7<U>(U?)': no suitable method found to override // internal override void F7<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F7").WithArguments("B.F7<U>(U?)").WithLocation(20, 28), // (20,37): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // internal override void F7<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 37)); } [Fact] public void NullableT_ContainingType() { var source = @"class A<T> { internal interface I { } internal enum E { } } class C { static void F1<T>(A<T?>.I i) { } static void F2<T>(A<T?>.E[] e) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F2<T>(A<T?>.E[] e) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(9, 25), // (8,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F1<T>(A<T?>.I i) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 25) ); } [Fact] public void NullableT_MethodBody() { var source = @"#pragma warning disable 0168 class C<T> { static void M<U>() { T? t; var u = typeof(U?); object? o = default(T?); o = new U?[0]; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? t; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(6, 9), // (7,24): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // var u = typeof(U?); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(7, 24), // (8,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // object? o = default(T?); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 29), // (9,17): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // o = new U?[0]; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(9, 17) ); } [Fact] public void NullableT_Lambda() { var source = @"delegate void D<T>(T t); class C { static void F<T>(D<T> d) { } static void G<T>() { F((T? t) => { }); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // F((T? t) => { }); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 12)); } [Fact] public void NullableT_LocalFunction() { var source = @"#pragma warning disable 8321 class C { static void F1<T>() { T? L1() => throw null!; } static void F2() { void L2<T>(T?[] t) { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? L1() => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(6, 9), // (10,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void L2<T>(T?[] t) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(10, 20)); } [Fact] [WorkItem(29996, "https://github.com/dotnet/roslyn/issues/29996")] public void NullableT_FromMetadata_BaseAndInterfaces() { var source0 = @".class public System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class interface public abstract IA`1<T> { } .class interface public abstract IB`1<T> implements class IA`1<!T> { .interfaceimpl type class IA`1<!T> .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) } .class public A`1<T> { } .class public B`1<T> extends class A`1<!T> { .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) }"; var ref0 = CompileIL(source0); var source1 = @"class C { static void F(IB<object> b) { } static void G(B<object> b) { } }"; var comp = CreateCompilation(source1, new[] { ref0 }); // https://github.com/dotnet/roslyn/issues/29996: Report errors for T? in metadata? comp.VerifyDiagnostics(); } [Fact] [WorkItem(29996, "https://github.com/dotnet/roslyn/issues/29996")] public void NullableT_FromMetadata_Methods() { var source0 = @".class public System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class interface public abstract I { } .class public A { } .class public C { .method public static !!T F1<T>() { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public static !!T F2<class T>() { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public static !!T F3<valuetype .ctor ([mscorlib]System.ValueType) T>() { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public static !!T F4<.ctor T>() { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public static !!T F5<(I) T>() { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public static !!T F6<(A) T>() { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } }"; var ref0 = CompileIL(source0); var source1 = @"class P { static void Main() { C.F1<int>(); // error C.F1<object>(); C.F2<object>(); C.F3<int>(); C.F4<object>(); // error C.F5<I>(); // error C.F6<A>(); } }"; var comp = CreateCompilation(source1, new[] { ref0 }); // https://github.com/dotnet/roslyn/issues/29996: Report errors for T? in metadata? comp.VerifyDiagnostics(); } [WorkItem(27289, "https://github.com/dotnet/roslyn/issues/27289")] [Fact] public void NullableTInConstraint_01() { var source = @"class A { } class B<T> where T : T? { } class C<T> where T : class, T? { } class D<T> where T : struct, T? { } class E<T> where T : A, T? { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (2,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class B<T> where T : T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(2, 22), // (4,30): error CS0701: 'T?' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // class D<T> where T : struct, T? { } Diagnostic(ErrorCode.ERR_BadBoundType, "T?").WithArguments("T?").WithLocation(4, 30), // (3,9): error CS0454: Circular constraint dependency involving 'T' and 'T' // class C<T> where T : class, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(3, 9), // (2,9): error CS0454: Circular constraint dependency involving 'T' and 'T' // class B<T> where T : T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(2, 9), // (5,9): error CS0454: Circular constraint dependency involving 'T' and 'T' // class E<T> where T : A, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(5, 9)); } [WorkItem(27289, "https://github.com/dotnet/roslyn/issues/27289")] [Fact] public void NullableTInConstraint_02() { var source = @"class A<T, U> where U : T? { } class B<T, U> where T : class where U : T? { } class C<T, U> where T : U? where U : T? { } class D<T, U> where T : class, U? where U : class, T? { } class E<T, U> where T : class, U where U : T? { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (2,15): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // where U : T? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(2, 15), // (11,15): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // where T : U? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(11, 15), // (12,15): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // where U : T? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(12, 15), // (10,9): error CS0454: Circular constraint dependency involving 'T' and 'U' // class C<T, U> Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "U").WithLocation(10, 9), // (15,9): error CS0454: Circular constraint dependency involving 'T' and 'U' // class D<T, U> Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "U").WithLocation(15, 9), // (20,9): error CS0454: Circular constraint dependency involving 'T' and 'U' // class E<T, U> Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "U").WithLocation(20, 9)); } [WorkItem(27289, "https://github.com/dotnet/roslyn/issues/27289")] [Fact] public void NullableTInConstraint_03() { var source = @"class A<T> where T : T, T? { } class B<U> where U : U?, U { } class C<V> where V : V?, V? { } delegate void D1<T1, U1>() where U1 : T1, T1?; delegate void D2<T2, U2>() where U2 : class, T2?, T2; delegate void D3<T3, U3>() where T3 : class where U3 : T3, T3?;"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (1,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class A<T> where T : T, T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(1, 25), // (1,25): error CS0405: Duplicate constraint 'T' for type parameter 'T' // class A<T> where T : T, T? { } Diagnostic(ErrorCode.ERR_DuplicateBound, "T?").WithArguments("T", "T").WithLocation(1, 25), // (1,9): error CS0454: Circular constraint dependency involving 'T' and 'T' // class A<T> where T : T, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(1, 9), // (2,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class B<U> where U : U?, U { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(2, 22), // (2,26): error CS0405: Duplicate constraint 'U' for type parameter 'U' // class B<U> where U : U?, U { } Diagnostic(ErrorCode.ERR_DuplicateBound, "U").WithArguments("U", "U").WithLocation(2, 26), // (2,9): error CS0454: Circular constraint dependency involving 'U' and 'U' // class B<U> where U : U?, U { } Diagnostic(ErrorCode.ERR_CircularConstraint, "U").WithArguments("U", "U").WithLocation(2, 9), // (3,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C<V> where V : V?, V? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "V?").WithArguments("9.0").WithLocation(3, 22), // (3,26): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C<V> where V : V?, V? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "V?").WithArguments("9.0").WithLocation(3, 26), // (3,26): error CS0405: Duplicate constraint 'V' for type parameter 'V' // class C<V> where V : V?, V? { } Diagnostic(ErrorCode.ERR_DuplicateBound, "V?").WithArguments("V", "V").WithLocation(3, 26), // (3,9): error CS0454: Circular constraint dependency involving 'V' and 'V' // class C<V> where V : V?, V? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "V").WithArguments("V", "V").WithLocation(3, 9), // (5,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // where U1 : T1, T1?; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T1?").WithArguments("9.0").WithLocation(5, 20), // (5,20): error CS0405: Duplicate constraint 'T1' for type parameter 'U1' // where U1 : T1, T1?; Diagnostic(ErrorCode.ERR_DuplicateBound, "T1?").WithArguments("T1", "U1").WithLocation(5, 20), // (7,23): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // where U2 : class, T2?, T2; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(7, 23), // (7,28): error CS0405: Duplicate constraint 'T2' for type parameter 'U2' // where U2 : class, T2?, T2; Diagnostic(ErrorCode.ERR_DuplicateBound, "T2").WithArguments("T2", "U2").WithLocation(7, 28), // (10,20): error CS0405: Duplicate constraint 'T3' for type parameter 'U3' // where U3 : T3, T3?; Diagnostic(ErrorCode.ERR_DuplicateBound, "T3?").WithArguments("T3", "U3").WithLocation(10, 20)); } [Fact] public void NullableTInConstraint_04() { var source = @"class A { } class B { static void F1<T>() where T : T? { } static void F2<T>() where T : class, T? { } static void F3<T>() where T : struct, T? { } static void F4<T>() where T : A, T? { } static void F5<T, U>() where U : T? { } static void F6<T, U>() where T : class where U : T? { } static void F7<T, U>() where T : struct where U : T? { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,20): error CS0454: Circular constraint dependency involving 'T' and 'T' // static void F2<T>() where T : class, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(5, 20), // (6,43): error CS0701: 'T?' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // static void F3<T>() where T : struct, T? { } Diagnostic(ErrorCode.ERR_BadBoundType, "T?").WithArguments("T?").WithLocation(6, 43), // (7,20): error CS0454: Circular constraint dependency involving 'T' and 'T' // static void F4<T>() where T : A, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(7, 20), // (8,38): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F5<T, U>() where U : T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 38), // (10,55): error CS0701: 'T?' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // static void F7<T, U>() where T : struct where U : T? { } Diagnostic(ErrorCode.ERR_BadBoundType, "T?").WithArguments("T?").WithLocation(10, 55), // (4,35): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F1<T>() where T : T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 35), // (4,20): error CS0454: Circular constraint dependency involving 'T' and 'T' // static void F1<T>() where T : T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(4, 20)); } [Fact] public void NullableTInConstraint_05() { var source = @"#pragma warning disable 8321 class A { } class B { static void M() { void F1<T>() where T : T? { } void F2<T>() where T : class, T? { } void F3<T>() where T : struct, T? { } void F4<T>() where T : A, T? { } void F5<T, U>() where U : T? { } void F6<T, U>() where T : class where U : T? { } void F7<T, U>() where T : struct where U : T? { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,32): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F1<T>() where T : T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 32), // (7,17): error CS0454: Circular constraint dependency involving 'T' and 'T' // void F1<T>() where T : T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(7, 17), // (8,17): error CS0454: Circular constraint dependency involving 'T' and 'T' // void F2<T>() where T : class, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(8, 17), // (9,40): error CS0701: 'T?' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void F3<T>() where T : struct, T? { } Diagnostic(ErrorCode.ERR_BadBoundType, "T?").WithArguments("T?").WithLocation(9, 40), // (10,17): error CS0454: Circular constraint dependency involving 'T' and 'T' // void F4<T>() where T : A, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(10, 17), // (11,35): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F5<T, U>() where U : T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(11, 35), // (13,52): error CS0701: 'T?' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void F7<T, U>() where T : struct where U : T? { } Diagnostic(ErrorCode.ERR_BadBoundType, "T?").WithArguments("T?").WithLocation(13, 52)); } [Fact] public void NullableTInConstraint_06() { var source = @"#pragma warning disable 8321 class A<T> where T : class { static void F1<U>() where U : T? { } static void F2() { void F3<U>() where U : T? { } } } class B { static void F4<T>() where T : class { void F5<U>() where U : T? { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableTInConstraint_07() { var source = @"interface I<T, U> where T : class where U : T { } class A<T, U> where T : class where U : T? { } class B1<T> : A<T, T>, I<T, T> where T : class { } class B2<T> : A<T, T?>, I<T, T?> where T : class { } class B3<T> : A<T?, T>, I<T?, T> where T : class { } class B4<T> : A<T?, T?>, I<T?, T?> where T : class { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,7): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'I<T, U>'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // class B2<T> : A<T, T?>, I<T, T?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "B2").WithArguments("I<T, U>", "T", "U", "T?").WithLocation(15, 7), // (19,7): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'A<T, U>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // class B3<T> : A<T?, T>, I<T?, T> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "B3").WithArguments("A<T, U>", "T", "T?").WithLocation(19, 7), // (19,7): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'I<T, U>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // class B3<T> : A<T?, T>, I<T?, T> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "B3").WithArguments("I<T, U>", "T", "T?").WithLocation(19, 7), // (23,7): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'A<T, U>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // class B4<T> : A<T?, T?>, I<T?, T?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "B4").WithArguments("A<T, U>", "T", "T?").WithLocation(23, 7), // (23,7): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'I<T, U>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // class B4<T> : A<T?, T?>, I<T?, T?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "B4").WithArguments("I<T, U>", "T", "T?").WithLocation(23, 7)); } // `class C<T> where T : class, T?` from metadata. [Fact] public void NullableTInConstraint_08() { // https://github.com/dotnet/roslyn/issues/29997: `where T : class, T?` is not valid in C#, // so the class needs to be defined in IL. How and where should the custom // attribute be declared for the constraint type in the following? var source0 = @".class public System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) .class public C<class (!T) T> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void Main() { object o; o = new C<object?>(); // 1 o = new C<object>(); // 2 } }"; var comp = CreateCompilation(new[] { source1 }, new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,19): error CS0454: Circular constraint dependency involving 'T' and 'T' // o = new C<object?>(); // 1 Diagnostic(ErrorCode.ERR_CircularConstraint, "object?").WithArguments("T", "T").WithLocation(6, 19), // (7,19): error CS0454: Circular constraint dependency involving 'T' and 'T' // o = new C<object>(); // 2 Diagnostic(ErrorCode.ERR_CircularConstraint, "object").WithArguments("T", "T").WithLocation(7, 19)); } // `class C<T, U> where U : T?` from metadata. [Fact] public void NullableTInConstraint_09() { var source0 = @"public class C<T, U> where T : class where U : T? { }"; var source1 = @"class Program { static void Main() { object o; o = new C<object?, object?>(); // 1 o = new C<object?, object>(); // 2 o = new C<object, object?>(); // 3 o = new C<object, object>(); // 4 } }"; var comp = CreateCompilation(source0, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (3,15): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // where U : T? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(3, 15), // (3,16): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // where U : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 16) ); MetadataReference ref0 = comp.ToMetadataReference(); comp = CreateCompilation(new[] { source1 }, new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); ref0 = comp.EmitToImageReference(); comp = CreateCompilation(new[] { source1 }, new[] { ref0 }, options: WithNullableEnable()); var c = comp.GetTypeByMetadataName("C`2"); Assert.IsAssignableFrom<PENamedTypeSymbol>(c); Assert.Equal("C<T, U> where T : class! where U : T?", c.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); comp.VerifyDiagnostics( // (6,19): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T, U>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // o = new C<object?, object?>(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T, U>", "T", "object?").WithLocation(6, 19), // (7,19): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T, U>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // o = new C<object?, object>(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T, U>", "T", "object?").WithLocation(7, 19) ); } [WorkItem(26294, "https://github.com/dotnet/roslyn/issues/26294")] [Fact] public void NullableTInConstraint_10() { var source = @"interface I<T> { } class C { static void F1<T>() where T : class, I<T?> { } static void F2<T>() where T : I<dynamic?> { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,35): error CS1968: Constraint cannot be a dynamic type 'I<dynamic>' // static void F2<T>() where T : I<dynamic?> { } Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "I<dynamic?>").WithArguments("I<dynamic?>").WithLocation(5, 35)); } [Fact] public void DuplicateConstraints() { var source = @"interface I<T> where T : class { } class C<T> where T : class { static void F1<U>() where U : T, T { } static void F2<U>() where U : T, T? { } static void F3<U>() where U : T?, T { } static void F4<U>() where U : T?, T? { } static void F5<U>() where U : I<T>, I<T> { } static void F6<U>() where U : I<T>, I<T?> { } static void F7<U>() where U : I<T?>, I<T> { } static void F8<U>() where U : I<T?>, I<T?> { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,38): error CS0405: Duplicate constraint 'T' for type parameter 'U' // static void F1<U>() where U : T, T { } Diagnostic(ErrorCode.ERR_DuplicateBound, "T").WithArguments("T", "U").WithLocation(4, 38), // (5,38): error CS0405: Duplicate constraint 'T' for type parameter 'U' // static void F2<U>() where U : T, T? { } Diagnostic(ErrorCode.ERR_DuplicateBound, "T?").WithArguments("T", "U").WithLocation(5, 38), // (6,39): error CS0405: Duplicate constraint 'T' for type parameter 'U' // static void F3<U>() where U : T?, T { } Diagnostic(ErrorCode.ERR_DuplicateBound, "T").WithArguments("T", "U").WithLocation(6, 39), // (7,39): error CS0405: Duplicate constraint 'T' for type parameter 'U' // static void F4<U>() where U : T?, T? { } Diagnostic(ErrorCode.ERR_DuplicateBound, "T?").WithArguments("T", "U").WithLocation(7, 39), // (8,41): error CS0405: Duplicate constraint 'I<T>' for type parameter 'U' // static void F5<U>() where U : I<T>, I<T> { } Diagnostic(ErrorCode.ERR_DuplicateBound, "I<T>").WithArguments("I<T>", "U").WithLocation(8, 41), // (9,41): error CS0405: Duplicate constraint 'I<T>' for type parameter 'U' // static void F6<U>() where U : I<T>, I<T?> { } Diagnostic(ErrorCode.ERR_DuplicateBound, "I<T?>").WithArguments("I<T>", "U").WithLocation(9, 41), // (10,20): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'I<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // static void F7<U>() where U : I<T?>, I<T> { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "U").WithArguments("I<T>", "T", "T?").WithLocation(10, 20), // (10,42): error CS0405: Duplicate constraint 'I<T>' for type parameter 'U' // static void F7<U>() where U : I<T?>, I<T> { } Diagnostic(ErrorCode.ERR_DuplicateBound, "I<T>").WithArguments("I<T>", "U").WithLocation(10, 42), // (11,20): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'I<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // static void F8<U>() where U : I<T?>, I<T?> { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "U").WithArguments("I<T>", "T", "T?").WithLocation(11, 20), // (11,42): error CS0405: Duplicate constraint 'I<T>' for type parameter 'U' // static void F8<U>() where U : I<T?>, I<T?> { } Diagnostic(ErrorCode.ERR_DuplicateBound, "I<T?>").WithArguments("I<T>", "U").WithLocation(11, 42)); } [Fact] public void PartialClassConstraints() { var source = @"class A<T, U> where T : A<T, U> where U : B<T, U> { } partial class B<T, U> where T : A<T, U> where U : B<T, U> { } partial class B<T, U> where T : A<T, U> where U : B<T, U> { }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void PartialClassConstraintMismatch() { var source = @"class A { } partial class B<T> where T : A { } partial class B<T> where T : A? { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (2,15): error CS0265: Partial declarations of 'B<T>' have inconsistent constraints for type parameter 'T' // partial class B<T> where T : A { } Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B").WithArguments("B<T>", "T").WithLocation(2, 15)); } [Fact] public void TypeUnification_01() { var source = @"interface I<T> { } class C1<T, U> : I<T>, I<U> { } class C2<T, U> : I<T>, I<U?> { } class C3<T, U> : I<T?>, I<U> { } class C4<T, U> : I<T?>, I<U?> { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (3,26): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C2<T, U> : I<T>, I<U?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(3, 26), // (4,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C3<T, U> : I<T?>, I<U> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 20), // (5,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C4<T, U> : I<T?>, I<U?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 20), // (5,27): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C4<T, U> : I<T?>, I<U?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(5, 27), // (2,7): error CS0695: 'C1<T, U>' cannot implement both 'I<T>' and 'I<U>' because they may unify for some type parameter substitutions // class C1<T, U> : I<T>, I<U> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C1").WithArguments("C1<T, U>", "I<T>", "I<U>").WithLocation(2, 7), // (5,7): error CS0695: 'C4<T, U>' cannot implement both 'I<T?>' and 'I<U?>' because they may unify for some type parameter substitutions // class C4<T, U> : I<T?>, I<U?> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T, U>", "I<T?>", "I<U?>").WithLocation(5, 7), // (3,7): error CS0695: 'C2<T, U>' cannot implement both 'I<T>' and 'I<U?>' because they may unify for some type parameter substitutions // class C2<T, U> : I<T>, I<U?> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C2").WithArguments("C2<T, U>", "I<T>", "I<U?>").WithLocation(3, 7), // (4,7): error CS0695: 'C3<T, U>' cannot implement both 'I<T?>' and 'I<U>' because they may unify for some type parameter substitutions // class C3<T, U> : I<T?>, I<U> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I<T?>", "I<U>").WithLocation(4, 7) ); } [Fact] public void TypeUnification_02() { var source = @"interface I<T> { } class C1<T, U> : I<T>, I<U> where T : struct { } class C2<T, U> : I<T>, I<U?> where T : struct { } class C3<T, U> : I<T?>, I<U> where T : struct { } class C4<T, U> : I<T?>, I<U?> where T : struct { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (2,7): error CS0695: 'C1<T, U>' cannot implement both 'I<T>' and 'I<U>' because they may unify for some type parameter substitutions // class C1<T, U> : I<T>, I<U> where T : struct { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C1").WithArguments("C1<T, U>", "I<T>", "I<U>").WithLocation(2, 7), // (3,7): error CS0695: 'C2<T, U>' cannot implement both 'I<T>' and 'I<U?>' because they may unify for some type parameter substitutions // class C2<T, U> : I<T>, I<U?> where T : struct { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C2").WithArguments("C2<T, U>", "I<T>", "I<U?>").WithLocation(3, 7), // (3,26): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C2<T, U> : I<T>, I<U?> where T : struct { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(3, 26), // (4,7): error CS0695: 'C3<T, U>' cannot implement both 'I<T?>' and 'I<U>' because they may unify for some type parameter substitutions // class C3<T, U> : I<T?>, I<U> where T : struct { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I<T?>", "I<U>").WithLocation(4, 7), // (5,7): error CS0695: 'C4<T, U>' cannot implement both 'I<T?>' and 'I<U?>' because they may unify for some type parameter substitutions // class C4<T, U> : I<T?>, I<U?> where T : struct { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T, U>", "I<T?>", "I<U?>").WithLocation(5, 7), // (5,27): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C4<T, U> : I<T?>, I<U?> where T : struct { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(5, 27) ); } [Fact] public void TypeUnification_03() { var source = @"interface I<T> { } class C1<T, U> : I<T>, I<U> where T : class { } class C2<T, U> : I<T>, I<U?> where T : class { } class C3<T, U> : I<T?>, I<U> where T : class { } class C4<T, U> : I<T?>, I<U?> where T : class { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (2,7): error CS0695: 'C1<T, U>' cannot implement both 'I<T>' and 'I<U>' because they may unify for some type parameter substitutions // class C1<T, U> : I<T>, I<U> where T : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C1").WithArguments("C1<T, U>", "I<T>", "I<U>").WithLocation(2, 7), // (3,7): error CS0695: 'C2<T, U>' cannot implement both 'I<T>' and 'I<U?>' because they may unify for some type parameter substitutions // class C2<T, U> : I<T>, I<U?> where T : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C2").WithArguments("C2<T, U>", "I<T>", "I<U?>").WithLocation(3, 7), // (3,26): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C2<T, U> : I<T>, I<U?> where T : class { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(3, 26), // (4,7): error CS0695: 'C3<T, U>' cannot implement both 'I<T?>' and 'I<U>' because they may unify for some type parameter substitutions // class C3<T, U> : I<T?>, I<U> where T : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I<T?>", "I<U>").WithLocation(4, 7), // (5,7): error CS0695: 'C4<T, U>' cannot implement both 'I<T?>' and 'I<U?>' because they may unify for some type parameter substitutions // class C4<T, U> : I<T?>, I<U?> where T : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T, U>", "I<T?>", "I<U?>").WithLocation(5, 7), // (5,27): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C4<T, U> : I<T?>, I<U?> where T : class { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(5, 27) ); } [Fact] public void TypeUnification_04() { var source = @"interface I<T> { } class C1<T, U> : I<T>, I<U> where T : struct where U : class { } class C2<T, U> : I<T>, I<U?> where T : struct where U : class { } class C3<T, U> : I<T?>, I<U> where T : struct where U : class { } class C4<T, U> : I<T?>, I<U?> where T : struct where U : class { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // Constraints are ignored when unifying types. comp.VerifyDiagnostics( // (2,7): error CS0695: 'C1<T, U>' cannot implement both 'I<T>' and 'I<U>' because they may unify for some type parameter substitutions // class C1<T, U> : I<T>, I<U> where T : struct where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C1").WithArguments("C1<T, U>", "I<T>", "I<U>").WithLocation(2, 7), // (3,7): error CS0695: 'C2<T, U>' cannot implement both 'I<T>' and 'I<U?>' because they may unify for some type parameter substitutions // class C2<T, U> : I<T>, I<U?> where T : struct where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C2").WithArguments("C2<T, U>", "I<T>", "I<U?>").WithLocation(3, 7), // (4,7): error CS0695: 'C3<T, U>' cannot implement both 'I<T?>' and 'I<U?>' because they may unify for some type parameter substitutions // class C3<T, U> : I<T?>, I<U> where T : struct where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I<T?>", "I<U>").WithLocation(4, 7), // (5,7): error CS0695: 'C4<T, U>' cannot implement both 'I<T?>' and 'I<U?>' because they may unify for some type parameter substitutions // class C4<T, U> : I<T?>, I<U?> where T : struct where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T, U>", "I<T?>", "I<U?>").WithLocation(5, 7)); } [Fact] public void TypeUnification_05() { var source = @"interface I<T> where T : class? { } class C1<T, U> : I<T>, I<U> where T : class where U : class { } class C2<T, U> : I<T>, I<U?> where T : class where U : class { } class C3<T, U> : I<T?>, I<U> where T : class where U : class { } class C4<T, U> : I<T?>, I<U?> where T : class where U : class { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (2,7): error CS0695: 'C1<T, U>' cannot implement both 'I<T>' and 'I<U>' because they may unify for some type parameter substitutions // class C1<T, U> : I<T>, I<U> where T : class where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C1").WithArguments("C1<T, U>", "I<T>", "I<U>").WithLocation(2, 7), // (3,7): error CS0695: 'C2<T, U>' cannot implement both 'I<T>' and 'I<U?>' because they may unify for some type parameter substitutions // class C2<T, U> : I<T>, I<U?> where T : class where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C2").WithArguments("C2<T, U>", "I<T>", "I<U?>").WithLocation(3, 7), // (4,7): error CS0695: 'C3<T, U>' cannot implement both 'I<T?>' and 'I<U>' because they may unify for some type parameter substitutions // class C3<T, U> : I<T?>, I<U> where T : class where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I<T?>", "I<U>").WithLocation(4, 7), // (5,7): error CS0695: 'C4<T, U>' cannot implement both 'I<T?>' and 'I<U?>' because they may unify for some type parameter substitutions // class C4<T, U> : I<T?>, I<U?> where T : class where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T, U>", "I<T?>", "I<U?>").WithLocation(5, 7)); } [Fact] public void AssignmentNullability() { var source = @"class C { static void F1(string? x1, string y1) { object? z1; (z1 = x1).ToString(); (z1 = y1).ToString(); } static void F2(string? x2, string y2) { object z2; (z2 = x2).ToString(); (z2 = y2).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (z1 = x1).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1 = x1").WithLocation(6, 10), // (12,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // (z2 = x2).ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(12, 15), // (12,10): warning CS8602: Dereference of a possibly null reference. // (z2 = x2).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2 = x2").WithLocation(12, 10)); } [WorkItem(27008, "https://github.com/dotnet/roslyn/issues/27008")] [Fact] public void OverriddenMethodNullableValueTypeParameter_01() { var source0 = @"public abstract class A { public abstract void F(int? i); }"; var comp0 = CreateCompilation(source0); var ref0 = comp0.EmitToImageReference(); var source = @"class B : A { public override void F(int? i) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); } [Fact] public void OverriddenMethodNullableValueTypeParameter_02() { var source0 = @"public abstract class A<T> where T : struct { public abstract void F(T? t); }"; var comp0 = CreateCompilation(source0); var ref0 = comp0.EmitToImageReference(); var source = @"class B1<T> : A<T> where T : struct { public override void F(T? t) { } } class B2 : A<int> { public override void F(int? t) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); } [WorkItem(27967, "https://github.com/dotnet/roslyn/issues/27967")] [Fact] public void UnannotatedTypeArgument_Interface() { var source0 = @"public interface I<T> { } public class B : I<object[]> { } public class C : I<C> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class Program { static void F(B x) { I<object[]?> a = x; I<object[]> b = x; } static void F(C y) { I<C?> a = y; I<C> b = y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); } [WorkItem(27967, "https://github.com/dotnet/roslyn/issues/27967")] [Fact] public void UnannotatedTypeArgument_BaseType() { var source0 = @"public class A<T> { } public class B : A<object[]> { } public class C : A<C> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class Program { static void F(B x) { A<object[]?> a = x; A<object[]> b = x; } static void F(C y) { A<C?> a = y; A<C> b = y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); } [Fact] public void UnannotatedTypeArgument_Interface_Lookup() { var source0 = @"public interface I<T> { void F(T t); } public interface I1 : I<object> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"interface I2 : I<object> { } class Program { static void F(I1 i1, I2 i2, object x, object? y) { i1.F(x); i1.F(y); i2.F(x); i2.F(y); // warn } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (11,14): warning CS8604: Possible null reference argument for parameter 't' in 'void I<object>.F(object t)'. // i2.F(y); // warn Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("t", "void I<object>.F(object t)").WithLocation(11, 14)); } [Fact] public void UnannotatedTypeArgument_BaseType_Lookup() { var source0 = @"public class A<T> { public static void F(T t) { } } public class B1 : A<object> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class B2 : A<object> { } class Program { static void F(object x, object? y) { B1.F(x); B1.F(y); B2.F(x); B2.F(y); // warn } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (11,14): warning CS8604: Possible null reference argument for parameter 't' in 'void A<object>.F(object t)'. // B2.F(y); // warn Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("t", "void A<object>.F(object t)").WithLocation(11, 14)); } [Fact] public void UnannotatedConstraint_01() { var source0 = @"public class A1 { } public class A2<T> { } public class B1<T> where T : A1 { } public class B2<T> where T : A2<object> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class Program { static void Main() { new B1<A1?>(); new B1<A1>(); new B2<A2<object?>>(); new B2<A2<object>>(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); var typeParameters = comp.GetMember<NamedTypeSymbol>("B1").TypeParameters; Assert.Equal("A1", typeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); typeParameters = comp.GetMember<NamedTypeSymbol>("B2").TypeParameters; Assert.Equal("A2<System.Object>", typeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); } [Fact] public void UnannotatedConstraint_02() { var source0 = @" public class A1 { } public class A2<T> { } #nullable disable public class B1<T, U> where T : A1 where U : A1? { } #nullable disable public class B2<T, U> where T : A2<object> where U : A2<object?> { }"; var comp0 = CreateCompilation(new[] { source0 }); comp0.VerifyDiagnostics( // (5,48): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public class B1<T, U> where T : A1 where U : A1? { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 48), // (7,63): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public class B2<T, U> where T : A2<object> where U : A2<object?> { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 63) ); var ref0 = comp0.EmitToImageReference(); var source = @"class Program { static void Main() { new B1<A1, A1?>(); new B1<A1?, A1>(); new B2<A2<object>, A2<object?>>(); new B2<A2<object?>, A2<object>>(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,29): warning CS8631: The type 'A2<object>' cannot be used as type parameter 'U' in the generic type or method 'B2<T, U>'. Nullability of type argument 'A2<object>' doesn't match constraint type 'A2<object?>'. // new B2<A2<object?>, A2<object>>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A2<object>").WithArguments("B2<T, U>", "A2<object?>", "U", "A2<object>").WithLocation(8, 29)); var typeParameters = comp.GetMember<NamedTypeSymbol>("B1").TypeParameters; Assert.Equal("A1", typeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); Assert.Equal("A1?", typeParameters[1].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); typeParameters = comp.GetMember<NamedTypeSymbol>("B2").TypeParameters; Assert.Equal("A2<System.Object>", typeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); Assert.Equal("A2<System.Object?>", typeParameters[1].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); } [Fact] public void UnannotatedConstraint_Override() { var source0 = @" public interface I<T> { } public abstract class A<T> where T : class { #nullable disable public abstract void F1<U>() where U : T, I<T>; #nullable disable public abstract void F2<U>() where U : T?, I<T?>; #nullable enable public abstract void F3<U>() where U : T, I<T>; #nullable enable public abstract void F4<U>() where U : T?, I<T?>; }"; var comp0 = CreateCompilation(new[] { source0 }, parseOptions: TestOptions.Regular8); comp0.VerifyDiagnostics( // (8,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public abstract void F2<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 45), // (8,44): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public abstract void F2<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 44), // (8,51): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public abstract void F2<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 51), // (8,50): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public abstract void F2<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 50), // (12,44): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public abstract void F4<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(12, 44), // (12,50): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public abstract void F4<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(12, 50) ); var source = @" #nullable disable class B1 : A<string> { public override void F1<U>() { } public override void F2<U>() { } public override void F3<U>() { } public override void F4<U>() { } } #nullable disable class B2 : A<string?> { public override void F1<U>() { } public override void F2<U>() { } public override void F3<U>() { } public override void F4<U>() { } } #nullable enable class B3 : A<string> { public override void F1<U>() { } public override void F2<U>() { } public override void F3<U>() { } public override void F4<U>() { } } #nullable enable class B4 : A<string?> { public override void F1<U>() { } public override void F2<U>() { } public override void F3<U>() { } public override void F4<U>() { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { new CSharpCompilationReference(comp0) }); comp.VerifyDiagnostics( // (11,20): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // class B2 : A<string?> Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 20) ); verifyAllConstraintTypes(); comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); comp0.VerifyDiagnostics( // (8,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public abstract void F2<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 45), // (8,51): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public abstract void F2<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 51) ); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { new CSharpCompilationReference(comp0) }); comp.VerifyDiagnostics( // (11,20): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // class B2 : A<string?> Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 20), // (27,7): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // class B4 : A<string?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "B4").WithArguments("A<T>", "T", "string?").WithLocation(27, 7) ); verifyAllConstraintTypes(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { comp0.EmitToImageReference() }); comp.VerifyDiagnostics( // (11,20): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // class B2 : A<string?> Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 20), // (27,7): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // class B4 : A<string?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "B4").WithArguments("A<T>", "T", "string?").WithLocation(27, 7) ); verifyAllConstraintTypes(); void verifyAllConstraintTypes() { string bangOrEmpty = comp0.Options.NullableContextOptions == NullableContextOptions.Disable ? "" : "!"; verifyConstraintTypes("B1.F1", "System.String", "I<System.String>"); verifyConstraintTypes("B1.F2", "System.String?", "I<System.String?>"); verifyConstraintTypes("B1.F3", "System.String" + bangOrEmpty, "I<System.String" + bangOrEmpty + ">!"); verifyConstraintTypes("B1.F4", "System.String?", "I<System.String?>!"); verifyConstraintTypes("B2.F1", "System.String?", "I<System.String?>"); verifyConstraintTypes("B2.F2", "System.String?", "I<System.String?>"); verifyConstraintTypes("B2.F3", "System.String?", "I<System.String?>!"); verifyConstraintTypes("B2.F4", "System.String?", "I<System.String?>!"); verifyConstraintTypes("B3.F1", "System.String!", "I<System.String!>"); verifyConstraintTypes("B3.F2", "System.String?", "I<System.String?>"); verifyConstraintTypes("B3.F3", "System.String!", "I<System.String!>!"); verifyConstraintTypes("B3.F4", "System.String?", "I<System.String?>!"); verifyConstraintTypes("B4.F1", "System.String?", "I<System.String?>"); verifyConstraintTypes("B4.F2", "System.String?", "I<System.String?>"); verifyConstraintTypes("B4.F3", "System.String?", "I<System.String?>!"); verifyConstraintTypes("B4.F4", "System.String?", "I<System.String?>!"); } void verifyConstraintTypes(string methodName, params string[] expectedTypes) { var constraintTypes = comp.GetMember<MethodSymbol>(methodName).TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics; AssertEx.Equal(expectedTypes, constraintTypes.SelectAsArray(t => t.ToTestDisplayString(true))); } } [Fact] public void Constraint_LocalFunction_01() { var source = @" class C { #nullable enable void M1() { local(new C(), new C(), new C(), null); void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? { T? x = t; x!.ToString(); } } #nullable disable void M2() { local(new C(), new C(), new C(), null); void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? { T? x = t; // warn 1 x!.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (20,14): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? x = t; // warn 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(20, 14), // (20,13): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? x = t; // warn 1 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(20, 13), // (18,56): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 56), // (18,85): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 85), // (18,99): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 99), // (18,98): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(18, 98) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var localSyntaxes = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>(); verifyLocalFunction(localSyntaxes.ElementAt(0), "C.M1.local", new[] { "C!" }); verifyLocalFunction(localSyntaxes.ElementAt(1), "C.M2.local", new[] { "C" }); void verifyLocalFunction(LocalFunctionStatementSyntax localSyntax, string expectedName, string[] expectedConstraintTypes) { var localSymbol = model.GetDeclaredSymbol(localSyntax).GetSymbol<LocalFunctionSymbol>(); var constraintTypes = localSymbol.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics; AssertEx.Equal(expectedConstraintTypes, constraintTypes.SelectAsArray(t => t.ToTestDisplayString(true))); } } [Fact] public void Constraint_LocalFunction_02() { var source = @" class C { void M3() { local(new C(), new C(), new C(), null); void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? { T? x = t; // warn 2 x!.ToString(); // warn 3 } } }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,14): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? x = t; // warn 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 14), // (9,13): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? x = t; // warn 2 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(9, 13), // (7,56): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 56), // (7,85): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 85), // (7,99): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 99), // (7,98): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 98) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var localSyntaxes = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>(); verifyLocalFunction(localSyntaxes.ElementAt(0), "C.M3.local", new[] { "C" }); void verifyLocalFunction(LocalFunctionStatementSyntax localSyntax, string expectedName, string[] expectedConstraintTypes) { var localSymbol = model.GetDeclaredSymbol(localSyntax).GetSymbol<LocalFunctionSymbol>(); var constraintTypes = localSymbol.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics; AssertEx.Equal(expectedConstraintTypes, constraintTypes.SelectAsArray(t => t.ToTestDisplayString(true))); } } [Fact] public void Constraint_Oblivious_01() { var source0 = @"public interface I<T> { } public class A<T> where T : I<T> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); var ref0 = comp0.EmitToImageReference(); var source = @"using System; class B1 : I<B1> { } class B2 : I<B2?> { } class C { static void Main() { Type t; t = typeof(A<B1>); t = typeof(A<B2>); // 1 t = typeof(A<B1?>); // 2 t = typeof(A<B2?>); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (10,22): warning CS8631: The type 'B2' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. Nullability of type argument 'B2' doesn't match constraint type 'I<B2>'. // t = typeof(A<B2>); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "B2").WithArguments("A<T>", "I<B2>", "T", "B2").WithLocation(10, 22), // (11,22): warning CS8631: The type 'B1?' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. Nullability of type argument 'B1?' doesn't match constraint type 'I<B1?>'. // t = typeof(A<B1?>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "B1?").WithArguments("A<T>", "I<B1?>", "T", "B1?").WithLocation(11, 22) ); var constraintTypes = comp.GetMember<NamedTypeSymbol>("A").TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics; Assert.Equal("I<T>", constraintTypes[0].ToTestDisplayString(true)); } [Fact] public void Constraint_Oblivious_02() { var source0 = @"public class A<T, U, V> where T : A<T, U, V> where V : U { protected interface I { } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); var ref0 = comp0.EmitToImageReference(); var source = @"class B : A<B, object, object> { static void F(I i) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); } [Fact] public void Constraint_Oblivious_03() { var source0 = @"public class A { } public class B0<T> where T : A { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"#pragma warning disable 0169 class B1<T> where T : A? { } class B2<T> where T : A { } #nullable enable class B3<T> where T : A? { } #nullable enable class B4<T> where T : A { } #nullable disable class C { B0<A?> F1; // 1 B0<A> F2; B1<A?> F3; // 2 B1<A> F4; B2<A?> F5; // 3 B2<A> F6; B3<A?> F7; // 4 B3<A> F8; B4<A?> F9; // 5 and 6 B4<A> F10; } #nullable enable class D { B0<A?> G1; B0<A> G2; B1<A?> G3; B1<A> G4; B2<A?> G5; B2<A> G6; B3<A?> G7; B3<A> G8; B4<A?> G9; // 7 B4<A> G10; }"; var comp = CreateCompilation(new[] { source }, references: new[] { ref0 }); comp.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_UninitializedNonNullableField).Verify( // (15,9): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B1<A?> F3; // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(15, 9), // (4,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // class B1<T> where T : A? { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 24), // (17,9): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B2<A?> F5; // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 9), // (19,9): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B3<A?> F7; // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(19, 9), // (35,12): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'B4<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // B4<A?> G9; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "G9").WithArguments("B4<T>", "A", "T", "A?").WithLocation(35, 12), // (21,9): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B4<A?> F9; // 5 and 6 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 9), // (13,9): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B0<A?> F1; // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 9) ); } [Fact] public void Constraint_Oblivious_04() { var source0 = @"public class A<T> { } public class B0<T> where T : A<object> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"#pragma warning disable 0169 class B1<T> where T : A<object?> { } class B2<T> where T : A<object> { } #nullable enable class B3<T> where T : A<object?> { } #nullable enable class B4<T> where T : A<object> { } #nullable disable class C { B0<A<object?>> F1; // 1 B0<A<object>> F2; B1<A<object?>> F3; // 2 B1<A<object>> F4; B2<A<object?>> F5; // 3 B2<A<object>> F6; B3<A<object?>> F7; // 4 B3<A<object>> F8; B4<A<object?>> F9; // 5 and 6 B4<A<object>> F10; } #nullable enable class D { B0<A<object?>> G1; B0<A<object>> G2; B1<A<object?>> G3; B1<A<object>> G4; // 7 B2<A<object?>> G5; B2<A<object>> G6; B3<A<object?>> G7; B3<A<object>> G8; // 8 B4<A<object?>> G9; // 9 B4<A<object>> G10; }"; var comp = CreateCompilation(new[] { source }, references: new[] { ref0 }); comp.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_UninitializedNonNullableField).Verify( // (4,31): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // class B1<T> where T : A<object?> { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 31), // (15,16): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B1<A<object?>> F3; // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(15, 16), // (17,16): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B2<A<object?>> F5; // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 16), // (19,16): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B3<A<object?>> F7; // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(19, 16), // (21,16): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B4<A<object?>> F9; // 5 and 6 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 16), // (13,16): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B0<A<object?>> F1; // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 16), // (30,19): warning CS8631: The type 'A<object>' cannot be used as type parameter 'T' in the generic type or method 'B1<T>'. Nullability of type argument 'A<object>' doesn't match constraint type 'A<object?>'. // B1<A<object>> G4; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "G4").WithArguments("B1<T>", "A<object?>", "T", "A<object>").WithLocation(30, 19), // (34,19): warning CS8631: The type 'A<object>' cannot be used as type parameter 'T' in the generic type or method 'B3<T>'. Nullability of type argument 'A<object>' doesn't match constraint type 'A<object?>'. // B3<A<object>> G8; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "G8").WithArguments("B3<T>", "A<object?>", "T", "A<object>").WithLocation(34, 19), // (35,20): warning CS8631: The type 'A<object?>' cannot be used as type parameter 'T' in the generic type or method 'B4<T>'. Nullability of type argument 'A<object?>' doesn't match constraint type 'A<object>'. // B4<A<object?>> G9; // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "G9").WithArguments("B4<T>", "A<object>", "T", "A<object?>").WithLocation(35, 20) ); } [Fact] public void Constraint_TypeParameterConstraint() { var source0 = @"public class A1<T, U> where T : class where U : class, T { } public class A2<T, U> where T : class where U : class, T? { }"; var comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @" class B1<T> where T : A1<T, T?> { } // 1 class B2<T> where T : A2<T?, T> { } // 2 #nullable enable class B3<T> where T : A1<T, T?> { } #nullable enable class B4<T> where T : A2<T?, T> { }"; var comp = CreateCompilation(new[] { source }, references: new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (2,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // class B1<T> where T : A1<T, T?> { } // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(2, 30), // (2,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class B1<T> where T : A1<T, T?> { } // 1 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(2, 29), // (3,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // class B2<T> where T : A2<T?, T> { } // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 27), // (3,26): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class B2<T> where T : A2<T?, T> { } // 2 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(3, 26), // (5,10): warning CS8634: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'A1<T, U>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // class B3<T> where T : A1<T, T?> { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "T").WithArguments("A1<T, U>", "U", "T?").WithLocation(5, 10), // (5,10): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'A1<T, U>'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // class B3<T> where T : A1<T, T?> { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "T").WithArguments("A1<T, U>", "T", "U", "T?").WithLocation(5, 10), // (7,10): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'A2<T, U>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // class B4<T> where T : A2<T?, T> { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "T").WithArguments("A2<T, U>", "T", "T?").WithLocation(7, 10)); } // Boxing conversion. [Fact] public void Constraint_BoxingConversion() { var source0 = @"public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } public struct S0 : I<object> { } public struct SIn0 : IIn<object> { } public struct SOut0 : IOut<object> { } public class A { public static void F0<T>() where T : I<object> { } public static void FIn0<T>() where T : IIn<object> { } public static void FOut0<T>() where T : IOut<object> { } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"struct S1 : I<object?> { } struct S2 : I<object> { } struct SIn1 : IIn<object?> { } struct SIn2 : IIn<object> { } struct SOut1 : IOut<object?> { } struct SOut2 : IOut<object> { } class B : A { static void F1<T>() where T : I<object?> { } static void F2<T>() where T : I<object> { } static void FIn1<T>() where T : IIn<object?> { } static void FIn2<T>() where T : IIn<object> { } static void FOut1<T>() where T : IOut<object?> { } static void FOut2<T>() where T : IOut<object> { } static void F() { F0<S0>(); F0<S1>(); F0<S2>(); F1<S0>(); F1<S1>(); F1<S2>(); // 1 F2<S0>(); F2<S1>(); // 2 F2<S2>(); } static void FIn() { FIn0<SIn0>(); FIn0<SIn1>(); FIn0<SIn2>(); FIn1<SIn0>(); FIn1<SIn1>(); FIn1<SIn2>(); // 3 FIn2<SIn0>(); FIn2<SIn1>(); FIn2<SIn2>(); } static void FOut() { FOut0<SOut0>(); FOut0<SOut1>(); FOut0<SOut2>(); FOut1<SOut0>(); FOut1<SOut1>(); FOut1<SOut2>(); FOut2<SOut0>(); FOut2<SOut1>(); // 4 FOut2<SOut2>(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (22,9): warning CS8627: The type 'S2' cannot be used as type parameter 'T' in the generic type or method 'B.F1<T>()'. Nullability of type argument 'S2' doesn't match constraint type 'I<object?>'. // F1<S2>(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F1<S2>").WithArguments("B.F1<T>()", "I<object?>", "T", "S2").WithLocation(22, 9), // (24,9): warning CS8627: The type 'S1' cannot be used as type parameter 'T' in the generic type or method 'B.F2<T>()'. Nullability of type argument 'S1' doesn't match constraint type 'I<object>'. // F2<S1>(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F2<S1>").WithArguments("B.F2<T>()", "I<object>", "T", "S1").WithLocation(24, 9), // (34,9): warning CS8627: The type 'SIn2' cannot be used as type parameter 'T' in the generic type or method 'B.FIn1<T>()'. Nullability of type argument 'SIn2' doesn't match constraint type 'IIn<object?>'. // FIn1<SIn2>(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "FIn1<SIn2>").WithArguments("B.FIn1<T>()", "IIn<object?>", "T", "SIn2").WithLocation(34, 9), // (48,9): warning CS8627: The type 'SOut1' cannot be used as type parameter 'T' in the generic type or method 'B.FOut2<T>()'. Nullability of type argument 'SOut1' doesn't match constraint type 'IOut<object>'. // FOut2<SOut1>(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "FOut2<SOut1>").WithArguments("B.FOut2<T>()", "IOut<object>", "T", "SOut1").WithLocation(48, 9)); } [Fact] public void Constraint_ImplicitTypeParameterConversion() { var source0 = @"public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } public class A { public static void F0<T>() where T : I<object> { } public static void FIn0<T>() where T : IIn<object> { } public static void FOut0<T>() where T : IOut<object> { } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class B : A { static void F1<T>() where T : I<object?> { } static void F2<T>() where T : I<object> { } static void FIn1<T>() where T : IIn<object?> { } static void FIn2<T>() where T : IIn<object> { } static void FOut1<T>() where T : IOut<object?> { } static void FOut2<T>() where T : IOut<object> { } static void F<T, U>() where T : I<object?> where U : I<object> { F0<T>(); F0<U>(); F1<T>(); F1<U>(); // 1 F2<T>(); // 2 F2<U>(); } static void FIn<T, U>() where T : IIn<object?> where U : IIn<object> { FIn0<T>(); FIn0<U>(); FIn1<T>(); FIn1<U>(); // 3 FIn2<T>(); FIn2<U>(); } static void FOut<T, U>() where T : IOut<object?> where U : IOut<object> { FOut0<T>(); FOut0<U>(); FOut1<T>(); FOut1<U>(); FOut2<T>(); // 4 FOut2<U>(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (14,9): warning CS8627: The type 'U' cannot be used as type parameter 'T' in the generic type or method 'B.F1<T>()'. Nullability of type argument 'U' doesn't match constraint type 'I<object?>'. // F1<U>(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F1<U>").WithArguments("B.F1<T>()", "I<object?>", "T", "U").WithLocation(14, 9), // (15,9): warning CS8627: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'B.F2<T>()'. Nullability of type argument 'T' doesn't match constraint type 'I<object>'. // F2<T>(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F2<T>").WithArguments("B.F2<T>()", "I<object>", "T", "T").WithLocation(15, 9), // (23,9): warning CS8627: The type 'U' cannot be used as type parameter 'T' in the generic type or method 'B.FIn1<T>()'. Nullability of type argument 'U' doesn't match constraint type 'IIn<object?>'. // FIn1<U>(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "FIn1<U>").WithArguments("B.FIn1<T>()", "IIn<object?>", "T", "U").WithLocation(23, 9), // (33,9): warning CS8627: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'B.FOut2<T>()'. Nullability of type argument 'T' doesn't match constraint type 'IOut<object>'. // FOut2<T>(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "FOut2<T>").WithArguments("B.FOut2<T>()", "IOut<object>", "T", "T").WithLocation(33, 9)); } [Fact] public void Constraint_MethodTypeInference() { var source0 = @"public class A { } public class B { public static void F0<T>(T t) where T : A { } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C : B { static void F1<T>(T t) where T : A { } static void G(A x, A? y) { F0(x); F1(x); F0(y); F1(y); // 1 x = y; F0(x); F1(x); // 2 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (11,9): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C.F1<T>(T)'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // F1(y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F1").WithArguments("C.F1<T>(T)", "A", "T", "A?").WithLocation(11, 9), // (12,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = y; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(12, 13), // (14,9): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C.F1<T>(T)'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // F1(x); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F1").WithArguments("C.F1<T>(T)", "A", "T", "A?").WithLocation(14, 9)); } [Fact] [WorkItem(29999, "https://github.com/dotnet/roslyn/issues/29999")] public void ThisAndBaseMemberInLambda() { var source = @"delegate void D(); class A { internal string? F; } class B : A { void M() { D d; d = () => { int n = this.F.Length; // 1 this.F = string.Empty; n = this.F.Length; }; d = () => { int n = base.F.Length; // 2 base.F = string.Empty; n = base.F.Length; }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,21): warning CS8602: Dereference of a possibly null reference. // int n = this.F.Length; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.F").WithLocation(13, 21), // (19,21): warning CS8602: Dereference of a possibly null reference. // int n = base.F.Length; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "base.F").WithLocation(19, 21)); } [Fact] [WorkItem(29999, "https://github.com/dotnet/roslyn/issues/29999")] public void ThisAndBaseMemberInLocalFunction() { var source = @"#pragma warning disable 8321 class A { internal string? F; } class B : A { void M() { void f() { int n = this.F.Length; // 1 this.F = string.Empty; n = this.F.Length; } void g() { int n = base.F.Length; // 2 base.F = string.Empty; n = base.F.Length; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,21): warning CS8602: Dereference of a possibly null reference. // int n = this.F.Length; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.F").WithLocation(12, 21), // (18,21): warning CS8602: Dereference of a possibly null reference. // int n = base.F.Length; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "base.F").WithLocation(18, 21)); } [WorkItem(31620, "https://github.com/dotnet/roslyn/issues/31620")] [Fact] public void InstanceMemberInLambda() { var source = @"using System; class Program { private object? _f; private object _g = null!; private void F() { Func<bool, object> f = (bool b1) => { Func<bool, object> g = (bool b2) => { if (b2) { _g = null; // 1 return _g; // 2 } return _g; }; if (b1) return _f; // 3 _f = new object(); return _f; }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,26): warning CS8625: Cannot convert null literal to non-nullable reference type. // _g = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 26), // (15,28): warning CS8603: Possible null reference return. // return _g; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "_g").WithLocation(15, 28), // (19,28): warning CS8603: Possible null reference return. // if (b1) return _f; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "_f").WithLocation(19, 28)); } [WorkItem(31620, "https://github.com/dotnet/roslyn/issues/31620")] [Fact] public void InstanceMemberInLocalFunction() { var source = @"#pragma warning disable 8321 class Program { private object? _f; private object _g = null!; private void F() { object f(bool b1) { if (b1) return _f; // 1 _f = new object(); return _f; object g(bool b2) { if (b2) { _g = null; // 2 return _g; // 3 } return _g; } } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,28): warning CS8603: Possible null reference return. // if (b1) return _f; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "_f").WithLocation(10, 28), // (17,26): warning CS8625: Cannot convert null literal to non-nullable reference type. // _g = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(17, 26), // (18,28): warning CS8603: Possible null reference return. // return _g; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "_g").WithLocation(18, 28)); } [WorkItem(29049, "https://github.com/dotnet/roslyn/issues/29049")] [Fact] public void TypeWithAnnotations_GetHashCode() { var source = @"interface I<T> { } class A : I<A> { } class B<T> where T : I<A?> { } class Program { static void Main() { new B<A>(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (8,15): warning CS8631: The type 'A' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. Nullability of type argument 'A' doesn't match constraint type 'I<A?>'. // new B<A>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A").WithArguments("B<T>", "I<A?>", "T", "A").WithLocation(8, 15)); // Diagnostics must support GetHashCode() and Equals(), to allow removing // duplicates (see CommonCompiler.ReportErrors). foreach (var diagnostic in diagnostics) { diagnostic.GetHashCode(); Assert.True(diagnostic.Equals(diagnostic)); } } [WorkItem(29041, "https://github.com/dotnet/roslyn/issues/29041")] [WorkItem(29048, "https://github.com/dotnet/roslyn/issues/29048")] [WorkItem(30001, "https://github.com/dotnet/roslyn/issues/30001")] [Fact] public void ConstraintCyclesFromMetadata_01() { var source0 = @"using System; public class A0<T> where T : IEquatable<T> { } public class A1<T> where T : class, IEquatable<T> { } public class A3<T> where T : struct, IEquatable<T> { } public class A4<T> where T : struct, IEquatable<T?> { } public class A5<T> where T : IEquatable<string?> { } public class A6<T> where T : IEquatable<int?> { }"; var source = @"class B { static void Main() { new A0<string?>(); // 1 new A0<string>(); new A5<string?>(); // 4 new A5<string>(); // 5 } }"; // No [NullNullTypes] var comp0 = CreateCompilation(source0); var ref0 = comp0.EmitToImageReference(); var comp = CreateCompilation(source, references: new[] { ref0 }); var expectedDiagnostics = new[] { // (5,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A0<string?>(); // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 22), // (9,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A5<string?>(); // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 22) }; comp.VerifyDiagnostics(expectedDiagnostics); verifyTypeParameterConstraint("A0", "System.IEquatable<T>"); verifyTypeParameterConstraint("A1", "System.IEquatable<T>"); verifyTypeParameterConstraint("A3", "System.IEquatable<T>"); verifyTypeParameterConstraint("A4", "System.IEquatable<T?>"); verifyTypeParameterConstraint("A5", "System.IEquatable<System.String?>"); verifyTypeParameterConstraint("A6", "System.IEquatable<System.Int32?>"); // [NullNullTypes(false)] comp0 = CreateCompilation(new[] { source0 }, options: WithNullableDisable()); ref0 = comp0.EmitToImageReference(); comp = CreateCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics(expectedDiagnostics); verifyTypeParameterConstraint("A0", "System.IEquatable<T>"); verifyTypeParameterConstraint("A1", "System.IEquatable<T>"); verifyTypeParameterConstraint("A3", "System.IEquatable<T>"); verifyTypeParameterConstraint("A4", "System.IEquatable<T?>"); verifyTypeParameterConstraint("A5", "System.IEquatable<System.String?>"); verifyTypeParameterConstraint("A6", "System.IEquatable<System.Int32?>"); // [NullNullTypes(true)] comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); ref0 = comp0.EmitToImageReference(); comp = CreateCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A0<string?>(); // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 22), // (9,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A5<string?>(); // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 22) ); verifyTypeParameterConstraint("A0", "System.IEquatable<T>"); verifyTypeParameterConstraint("A1", "System.IEquatable<T>"); verifyTypeParameterConstraint("A3", "System.IEquatable<T>"); verifyTypeParameterConstraint("A4", "System.IEquatable<T?>"); verifyTypeParameterConstraint("A5", "System.IEquatable<System.String?>"); verifyTypeParameterConstraint("A6", "System.IEquatable<System.Int32?>"); comp = CreateCompilation(source, references: new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,16): warning CS8631: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'A0<T>'. Nullability of type argument 'string?' doesn't match constraint type 'System.IEquatable<string?>'. // new A0<string?>(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "string?").WithArguments("A0<T>", "System.IEquatable<string?>", "T", "string?").WithLocation(5, 16), // (9,16): warning CS8631: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'A5<T>'. Nullability of type argument 'string?' doesn't match constraint type 'System.IEquatable<string?>'. // new A5<string?>(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "string?").WithArguments("A5<T>", "System.IEquatable<string?>", "T", "string?").WithLocation(9, 16) ); verifyTypeParameterConstraint("A0", "System.IEquatable<T>"); verifyTypeParameterConstraint("A1", "System.IEquatable<T>"); verifyTypeParameterConstraint("A3", "System.IEquatable<T>"); verifyTypeParameterConstraint("A4", "System.IEquatable<T?>"); verifyTypeParameterConstraint("A5", "System.IEquatable<System.String?>"); verifyTypeParameterConstraint("A6", "System.IEquatable<System.Int32?>"); void verifyTypeParameterConstraint(string typeName, string expected) { var type = comp.GetMember<NamedTypeSymbol>(typeName); var constraintType = type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0]; Assert.Equal(expected, constraintType.ToTestDisplayString()); } } [WorkItem(29041, "https://github.com/dotnet/roslyn/issues/29041")] [WorkItem(29048, "https://github.com/dotnet/roslyn/issues/29048")] [WorkItem(30003, "https://github.com/dotnet/roslyn/issues/30003")] [Fact] public void ConstraintCyclesFromMetadata_02() { var source0 = @"using System; public class A2<T> where T : class, IEquatable<T?> { } "; var source = @"class B { static void Main() { new A2<string?>(); // 2 new A2<string>(); // 3 } }"; // No [NullNullTypes] var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular8); comp0.VerifyDiagnostics( // (2,48): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public class A2<T> where T : class, IEquatable<T?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(2, 48), // (2,49): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public class A2<T> where T : class, IEquatable<T?> { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(2, 49) ); MetadataReference ref0 = comp0.ToMetadataReference(); var comp = CreateCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A2<string?>(); // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 22) ); verifyTypeParameterConstraint("A2", "System.IEquatable<T?>"); // [NullNullTypes(false)] comp0 = CreateCompilation(new[] { source0 }, options: WithNullableDisable(), parseOptions: TestOptions.Regular8); comp0.VerifyDiagnostics( // (2,48): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public class A2<T> where T : class, IEquatable<T?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(2, 48), // (2,49): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public class A2<T> where T : class, IEquatable<T?> { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(2, 49) ); ref0 = comp0.ToMetadataReference(); comp = CreateCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A2<string?>(); // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 22) ); verifyTypeParameterConstraint("A2", "System.IEquatable<T?>"); // [NullNullTypes(true)] comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); ref0 = comp0.EmitToImageReference(); comp = CreateCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A2<string?>(); // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 22) ); verifyTypeParameterConstraint("A2", "System.IEquatable<T?>"); comp = CreateCompilation(source, references: new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,16): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'A2<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // new A2<string?>(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("A2<T>", "T", "string?").WithLocation(5, 16), // (5,16): warning CS8631: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'A2<T>'. Nullability of type argument 'string?' doesn't match constraint type 'System.IEquatable<string?>'. // new A2<string?>(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "string?").WithArguments("A2<T>", "System.IEquatable<string?>", "T", "string?").WithLocation(5, 16) ); verifyTypeParameterConstraint("A2", "System.IEquatable<T?>"); void verifyTypeParameterConstraint(string typeName, string expected) { var type = comp.GetMember<NamedTypeSymbol>(typeName); var constraintType = type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0]; Assert.Equal(expected, constraintType.ToTestDisplayString()); } } [WorkItem(29186, "https://github.com/dotnet/roslyn/issues/29186")] [Fact] public void AttributeArgumentCycle_OtherAttribute() { var source = @"using System; class AAttribute : Attribute { internal AAttribute(object o) { } } interface IA { } interface IB<T> where T : IA { } [A(typeof(IB<IA>))] class C { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(30178, "https://github.com/dotnet/roslyn/issues/30178")] public void GenericSubstitution_01() { var source = @" #nullable enable class A<T1, T2> where T1 : class where T2 : class { T1 F; #nullable disable class B : A<T1, T2> { #nullable enable void M1() { F = null; // 1 } } void M2() { F = null; // 2 } #nullable disable class C : A<C, C> { #nullable enable void M3() { F = null; // 3 } } #nullable disable class D : A<T1, D> { #nullable enable void M4() { F = null; // 4 } } #nullable disable class E : A<T2, T2> { #nullable enable void M5() { F = null; // 5 } } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (7,8): warning CS8618: Non-nullable field 'F' is uninitialized. Consider declaring the field as nullable. // T1 F; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "F").WithArguments("field", "F").WithLocation(7, 8), // (7,8): warning CS0414: The field 'A<T1, T2>.F' is assigned but its value is never used // T1 F; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A<T1, T2>.F").WithLocation(7, 8), // (15,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 17), // (21,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 13), // (30,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(30, 17), // (40,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(40, 17), // (50,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(50, 17) ); var b = comp.GetTypeByMetadataName("A`2+B"); Assert.NotNull(b); Assert.True(b.BaseTypeNoUseSiteDiagnostics.IsDefinition); } [Fact] [WorkItem(30177, "https://github.com/dotnet/roslyn/issues/30177")] [WorkItem(30178, "https://github.com/dotnet/roslyn/issues/30178")] public void GenericSubstitution_02() { var source = @" #nullable disable class A<T1, T2> where T1 : class where T2 : class { #nullable enable #pragma warning disable 8618 T1 F; #nullable enable class B : A<T1, T2> { void M1() { F = null; // 1 } } #nullable enable void M2() { F = null; // 2 } #nullable enable class C : A<C, C> { void M3() { F = null; // 3 } } #nullable enable class D : A<T1, D> { void M4() { F = null; // 4 } } #nullable enable class E : A<T2, T2> { void M5() { F = null; // 5 } } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (9,8): warning CS0414: The field 'A<T1, T2>.F' is assigned but its value is never used // T1 F; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A<T1, T2>.F").WithLocation(9, 8), // (16,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 17), // (23,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(23, 13), // (31,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(31, 17), // (40,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(40, 17), // (49,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(49, 17)); var b = comp.GetTypeByMetadataName("A`2+B"); Assert.NotNull(b); Assert.False(b.BaseTypeNoUseSiteDiagnostics.IsDefinition); } [Fact] public void GenericSubstitution_03() { var source = @"#nullable disable class A<T> where T : class { class B : A<T> {} } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); var b = comp.GetTypeByMetadataName("A`1+B"); Assert.NotNull(b); Assert.True(b.BaseTypeNoUseSiteDiagnostics.IsDefinition); } [Fact] [WorkItem(30178, "https://github.com/dotnet/roslyn/issues/30178")] public void GenericSubstitution_04() { var source = @"#nullable enable class A<T> where T : class { class B : A<T> {} } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); var b = comp.GetTypeByMetadataName("A`1+B"); Assert.NotNull(b); Assert.False(b.BaseTypeNoUseSiteDiagnostics.IsDefinition); } [Fact] [WorkItem(30178, "https://github.com/dotnet/roslyn/issues/30178")] public void GenericSubstitution_05() { var source = @" #nullable enable class A<T1, T2> where T1 : class where T2 : class { #nullable disable T1 F; #nullable enable class B : A<T1, T2> { void M1() { F = null; // 1 } } void M2() { F = null; // 2 } class C : A<C, C> { void M3() { F = null; // 3 } } class D : A<T1, D> { void M1() { F = null; // 4 } } class E : A<T2, T2> { void M1() { F = null; // 5 } } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (8,8): warning CS0414: The field 'A<T1, T2>.F' is assigned but its value is never used // T1 F; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A<T1, T2>.F").WithLocation(8, 8), // (14,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 17), // (27,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(27, 17), // (35,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(35, 17), // (43,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(43, 17) ); var b = comp.GetTypeByMetadataName("A`2+B"); Assert.NotNull(b); Assert.False(b.BaseTypeNoUseSiteDiagnostics.IsDefinition); } [Fact] [WorkItem(30177, "https://github.com/dotnet/roslyn/issues/30177")] [WorkItem(30178, "https://github.com/dotnet/roslyn/issues/30178")] public void GenericSubstitution_06() { var source = @" #nullable disable class A<T1, T2> where T1 : class where T2 : class { T1 F; #nullable enable class B : A<T1, T2> { void M1() { F = null; // 1 } } #nullable enable void M2() { F = null; } #nullable enable class C : A<C, C> { void M3() { F = null; // 2 } } #nullable enable class D : A<T1, D> { void M3() { F = null; // 3 } } #nullable enable class E : A<T2, T2> { void M3() { F = null; // 4 } } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (7,8): warning CS0414: The field 'A<T1, T2>.F' is assigned but its value is never used // T1 F; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A<T1, T2>.F").WithLocation(7, 8), // (14,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 17), // (29,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(29, 17), // (38,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(38, 17), // (47,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(47, 17)); var b = comp.GetTypeByMetadataName("A`2+B"); Assert.NotNull(b); Assert.False(b.BaseTypeNoUseSiteDiagnostics.IsDefinition); } [Fact] [WorkItem(35083, "https://github.com/dotnet/roslyn/issues/35083")] public void GenericSubstitution_07() { var source = @" class A { void M1<T>() { } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); var a = comp.GetTypeByMetadataName("A"); var m1 = a.GetMember<MethodSymbol>("M1"); var m11 = new[] { m1.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(a, NullableAnnotation.Annotated))), m1.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(a, NullableAnnotation.NotAnnotated))), m1.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(a, NullableAnnotation.Oblivious))) }; var m12 = new[] { m1.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(a, NullableAnnotation.Annotated))), m1.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(a, NullableAnnotation.NotAnnotated))), m1.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(a, NullableAnnotation.Oblivious))) }; for (int i = 0; i < m11.Length; i++) { var method1 = m11[i]; Assert.True(method1.Equals(method1)); for (int j = 0; j < m12.Length; j++) { var method2 = m12[j]; // always equal by default Assert.True(method1.Equals(method2)); Assert.True(method2.Equals(method1)); // can differ when considering nullability if (i == j) { Assert.True(method1.Equals(method2, SymbolEqualityComparer.IncludeNullability.CompareKind)); Assert.True(method2.Equals(method1, SymbolEqualityComparer.IncludeNullability.CompareKind)); } else { Assert.False(method1.Equals(method2, SymbolEqualityComparer.IncludeNullability.CompareKind)); Assert.False(method2.Equals(method1, SymbolEqualityComparer.IncludeNullability.CompareKind)); } Assert.Equal(method1.GetHashCode(), method2.GetHashCode()); } } } [Fact] [WorkItem(30171, "https://github.com/dotnet/roslyn/issues/30171")] public void NonNullTypesContext_01() { var source = @" using System.Diagnostics.CodeAnalysis; class A { #nullable disable PLACEHOLDER B[] F1; #nullable enable PLACEHOLDER C[] F2; } class B {} class C {} "; var comp1 = CreateCompilation(new[] { source.Replace("PLACEHOLDER", "") }); verify(comp1); var comp2 = CreateCompilation(new[] { source.Replace("PLACEHOLDER", "annotations") }); verify(comp2); void verify(CSharpCompilation comp) { var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B[]", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); var f2 = comp.GetMember<FieldSymbol>("A.F2"); Assert.Equal("C![]!", f2.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var arrays = tree.GetRoot().DescendantNodes().OfType<ArrayTypeSyntax>().ToArray(); Assert.Equal(2, arrays.Length); Assert.Equal("B[]", model.GetTypeInfo(arrays[0]).Type.ToTestDisplayString(includeNonNullable: true)); Assert.Equal("C![]", model.GetTypeInfo(arrays[1]).Type.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_02() { var source0 = @" #pragma warning disable CS0169 class A { #nullable enable PLACEHOLDER B #nullable disable PLACEHOLDER F1; } class B {} "; var source1 = source0.Replace("PLACEHOLDER", ""); var source2 = source0.Replace("PLACEHOLDER", "annotations"); assertNonNullTypesContext(source1, NullableContextOptions.Disable); assertNonNullTypesContext(source1, NullableContextOptions.Warnings); assertNonNullTypesContext(source2, NullableContextOptions.Disable); assertNonNullTypesContext(source2, NullableContextOptions.Warnings); void assertNonNullTypesContext(string source, NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_03() { var source = @" #pragma warning disable CS0169 class A { #nullable disable PLACEHOLDER B #nullable enable PLACEHOLDER F1; } class B {} "; verify(source.Replace("PLACEHOLDER", "")); verify(source.Replace("PLACEHOLDER", "annotations")); void verify(string source) { var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_04() { var source0 = @" #pragma warning disable CS0169 class A { B #nullable enable PLACEHOLDER ? F1; } class B {} "; var source1 = source0.Replace("PLACEHOLDER", ""); var source2 = source0.Replace("PLACEHOLDER", "annotations"); assertNonNullTypesContext(source1, NullableContextOptions.Disable); assertNonNullTypesContext(source1, NullableContextOptions.Warnings); assertNonNullTypesContext(source2, NullableContextOptions.Disable); assertNonNullTypesContext(source2, NullableContextOptions.Warnings); void assertNonNullTypesContext(string source, NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_05() { var source = @" #pragma warning disable CS0169 class A { B #nullable disable PLACEHOLDER ? F1; } class B {} "; verify(source.Replace("PLACEHOLDER", "")); verify(source.Replace("PLACEHOLDER", "annotations")); void verify(string source) { var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics( // (8,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // ? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 6) ); } } [Fact] public void NonNullTypesContext_06() { var source0 = @" #pragma warning disable CS0169 class A { #nullable enable PLACEHOLDER string #nullable disable PLACEHOLDER F1; } "; var source1 = source0.Replace("PLACEHOLDER", ""); var source2 = source0.Replace("PLACEHOLDER", "annotations"); assertNonNullTypesContext(source1, NullableContextOptions.Disable); assertNonNullTypesContext(source1, NullableContextOptions.Warnings); assertNonNullTypesContext(source2, NullableContextOptions.Disable); assertNonNullTypesContext(source2, NullableContextOptions.Warnings); void assertNonNullTypesContext(string source, NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("System.String!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_07() { var source = @" #pragma warning disable CS0169 class A { #nullable disable string #nullable enable F1; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("System.String", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_08() { var source = @" #pragma warning disable CS0169 class A { B[ #nullable enable ] #nullable disable F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B[]!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_09() { var source = @" #pragma warning disable CS0169 class A { B[ #nullable disable ] #nullable enable F1; } class B {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B![]", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_10() { var source = @" #pragma warning disable CS0169 class A { (B, B #nullable enable ) #nullable disable F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal(NullableAnnotation.NotAnnotated, f1.TypeWithAnnotations.NullableAnnotation); } } [Fact] public void NonNullTypesContext_11() { var source = @" #pragma warning disable CS0169 class A { (B, B #nullable disable ) #nullable enable F1; } class B {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal(NullableAnnotation.Oblivious, f1.TypeWithAnnotations.NullableAnnotation); } [Fact] public void NonNullTypesContext_12() { var source = @" #pragma warning disable CS0169 class A { B<A #nullable enable > #nullable disable F1; } class B<T> {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B<A>!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_13() { var source = @" #pragma warning disable CS0169 class A { B<A #nullable disable > #nullable enable F1; } class B<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B<A!>", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_14() { var source = @" class A { void M<T>(out T x){} void Test() { M(out #nullable enable var #nullable disable local); } } class var {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single(); Assert.Equal("var!", model.GetDeclaredSymbol(decl.Designation).GetSymbol<LocalSymbol>().TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_15() { var source = @" class A { void M<T>(out T x){} void Test() { M(out #nullable disable var #nullable enable local); } } class var {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single(); Assert.Equal("var", model.GetDeclaredSymbol(decl.Designation).GetSymbol<LocalSymbol>().TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_16() { var source = @" class A<T> where T : #nullable enable class #nullable disable { } "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var a = comp.GetTypeByMetadataName("A`1"); Assert.Equal("A<T> where T : class!", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); } } [Fact] public void NonNullTypesContext_17() { var source = @" class A<T> where T : #nullable disable class #nullable enable { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var a = comp.GetTypeByMetadataName("A`1"); Assert.Equal("A<T> where T : class", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); } [Fact] public void NonNullTypesContext_18() { var source = @" class A<T> where T : class #nullable enable ? #nullable disable { } "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var a = comp.GetTypeByMetadataName("A`1"); Assert.Equal("A<T> where T : class?", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier))); Assert.Equal("A<T> where T : class", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_19() { var source = @" class A<T> where T : class #nullable disable ? #nullable enable { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var a = comp.GetTypeByMetadataName("A`1"); Assert.Equal("A<T> where T : class?", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier))); Assert.Equal("A<T> where T : class", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); comp.VerifyDiagnostics( // (4,5): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // ? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 5) ); } [Fact] public void NonNullTypesContext_20() { var source = @" class A<T> where T : #nullable enable unmanaged #nullable disable { } class unmanaged {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var a = comp.GetTypeByMetadataName("A`1"); Assert.Equal("A<T> where T : unmanaged!", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); } } [Fact] public void NonNullTypesContext_21() { var source = @" class A<T> where T : #nullable disable unmanaged #nullable enable { } class unmanaged {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var a = comp.GetTypeByMetadataName("A`1"); Assert.Equal("A<T> where T : unmanaged", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); } [Fact] public void NonNullTypesContext_22() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Enable, type, "A<System.String!>"); } private static void AssertGetSpeculativeTypeInfo(string source, NullableContextOptions nullableContextOptions, TypeSyntax type, string expected) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var decl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); Assert.Equal(expected, model.GetSpeculativeTypeInfo(decl.Identifier.SpanStart, type, SpeculativeBindingOption.BindAsTypeOrNamespace).Type.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_23() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Disable, type, "A<System.String>"); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Warnings, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_24() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable disable A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Enable, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_25() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable enable A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Disable, type, "A<System.String!>"); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Warnings, type, "A<System.String!>"); } [Fact] public void NonNullTypesContext_26() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable disable b; #nullable enable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Enable, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_27() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable enable b; #nullable disable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Disable, type, "A<System.String!>"); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Warnings, type, "A<System.String!>"); } [Fact] public void NonNullTypesContext_28() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable disable b; #nullable enable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable enable A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Enable, type, "A<System.String!>"); } [Fact] public void NonNullTypesContext_29() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable enable b; #nullable disable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable disable A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Disable, type, "A<System.String>"); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Warnings, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_30() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Enable, type, "A<System.String!>!"); } private static void AssertTryGetSpeculativeSemanticModel(string source, NullableContextOptions nullableContextOptions, TypeSyntax type, string expected) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var decl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); Assert.True(model.TryGetSpeculativeSemanticModel(decl.Identifier.SpanStart, type, out model, SpeculativeBindingOption.BindAsTypeOrNamespace)); Assert.Equal(expected, model.GetTypeInfo(type).Type.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_31() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Disable, type, "A<System.String>"); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Warnings, type, "A<System.String>!"); } [Fact] public void NonNullTypesContext_32() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable disable A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Enable, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_33() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable enable A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Disable, type, "A<System.String!>!"); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Warnings, type, "A<System.String!>!"); } [Fact] public void NonNullTypesContext_34() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable disable b; #nullable enable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Enable, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_35() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable enable b; #nullable disable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Disable, type, "A<System.String!>!"); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Warnings, type, "A<System.String!>!"); } [Fact] public void NonNullTypesContext_36() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable disable b; #nullable enable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable enable A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Enable, type, "A<System.String!>!"); } [Fact] public void NonNullTypesContext_37() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable enable b; #nullable disable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable disable A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Disable, type, "A<System.String>"); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Warnings, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_38() { var source = @" using B = C; #pragma warning disable CS0169 class A { #nullable enable B #nullable disable F1; } class C {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("C!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_39() { var source = @" using B = C; #pragma warning disable CS0169 class A { #nullable disable B #nullable enable F1; } class C {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("C", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_40() { var source = @" #pragma warning disable CS0169 class A { C. #nullable enable B #nullable disable F1; } namespace C { class B {} } "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("C.B!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_41() { var source = @" #pragma warning disable CS0169 class A { C. #nullable disable B #nullable enable F1; } namespace C { class B {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("C.B", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_42() { var source = @" #pragma warning disable CS0169 class A { C.B<A #nullable enable > #nullable disable F1; } namespace C { class B<T> {} } "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("C.B<A>!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_43() { var source = @" #pragma warning disable CS0169 class A { C.B<A #nullable disable > #nullable enable F1; } namespace C { class B<T> {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("C.B<A!>", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_49() { var source = @" #pragma warning disable CS0169 #nullable enable class A { B #nullable restore ? #nullable enable F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics( // (8,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // ? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 6) ); } } [Fact] public void NonNullTypesContext_51() { var source = @" #pragma warning disable CS0169 class A { B #nullable restore ? F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics( // (8,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // ? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 6) ); } } [Fact] public void NonNullTypesContext_52() { var source = @" #pragma warning disable CS0169 #nullable disable class A { B #nullable restore ? #nullable enable F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics( // (8,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // ? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 6) ); } } [Fact] public void NonNullTypesContext_53() { var source = @" #pragma warning disable CS0169 #nullable enable class A { #nullable restore B #nullable enable F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_55() { var source = @" #pragma warning disable CS0169 class A { #nullable restore B F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_56() { var source = @" #pragma warning disable CS0169 #nullable disable class A { #nullable restore B #nullable enable F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_57() { var source = @" #pragma warning disable CS0169 #nullable disable class A { B #nullable restore ? #nullable disable F1; } class B {} "; assertType(NullableContextOptions.Enable); void assertType(NullableContextOptions nullableContextOptions) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_58() { var source = @" #pragma warning disable CS0169 #nullable disable class A { B #nullable restore ? #nullable disable F1; } class B {} "; assertType(NullableContextOptions.Enable); void assertType(NullableContextOptions nullableContextOptions) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_59() { var source = @" #pragma warning disable CS0169 class A { B #nullable restore ? F1; } class B {} "; assertType(NullableContextOptions.Enable); void assertType(NullableContextOptions nullableContextOptions) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_60() { var source = @" #pragma warning disable CS0169 #nullable enable class A { B #nullable restore ? #nullable disable F1; } class B {} "; assertType(NullableContextOptions.Enable); void assertType(NullableContextOptions nullableContextOptions) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_61() { var source = @" #pragma warning disable CS0169 #nullable disable class A { #nullable restore B #nullable disable F1; } class B {} "; assertType(NullableContextOptions.Enable); void assertType(NullableContextOptions nullableContextOptions) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_62() { var source = @" #pragma warning disable CS0169 class A { #nullable restore #pragma warning disable CS8618 B F1; } class B {} "; assertType(NullableContextOptions.Enable); void assertType(NullableContextOptions nullableContextOptions) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] [WorkItem(34843, "https://github.com/dotnet/roslyn/issues/34843")] [WorkItem(34844, "https://github.com/dotnet/roslyn/issues/34844")] public void ObliviousTypeParameter_01() { var source = $@" #pragma warning disable {(int)ErrorCode.WRN_UninitializedNonNullableField} #pragma warning disable {(int)ErrorCode.WRN_UnreferencedField} #pragma warning disable {(int)ErrorCode.WRN_UnreferencedFieldAssg} #pragma warning disable {(int)ErrorCode.WRN_UnreferencedVarAssg} #pragma warning disable {(int)ErrorCode.WRN_UnassignedInternalField} " + @" #nullable disable class A<T1, T2, T3> where T2 : class where T3 : B { T1 F1; T2 F2; T3 F3; B F4; #nullable enable void M1() { F1.ToString(); F2.ToString(); F3.ToString(); F4.ToString(); } #nullable enable void M2() { T1 x2 = default; T2 y2 = default; T3 z2 = default; } #nullable enable void M3() { C.Test<T1>(); C.Test<T2>(); C.Test<T3>(); } #nullable enable void M4() { D.Test(F1); D.Test(F2); D.Test(F3); D.Test(F4); } } class B {} #nullable enable class C { public static void Test<T>() where T : notnull {} } #nullable enable class D { public static void Test<T>(T x) where T : notnull {} } "; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (29,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T1 x2 = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(29, 17), // (30,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T2 y2 = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(30, 17), // (31,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T3 z2 = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(31, 17)); } [Fact] [WorkItem(30220, "https://github.com/dotnet/roslyn/issues/30220")] public void ObliviousTypeParameter_02() { var source = $@" #pragma warning disable {(int)ErrorCode.WRN_UnreferencedVar} " + @" #nullable enable class A<T1> where T1 : class { #nullable disable class B<T2> where T2 : T1 { } #nullable enable void M1() { B<T1> a1; B<T1?> b1; A<T1>.B<T1> c1; A<T1>.B<T1?> d1; A<C>.B<C> e1; A<C>.B<C?> f1; } } class C {} "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (20,17): warning CS8631: The type 'T1?' cannot be used as type parameter 'T2' in the generic type or method 'A<T1>.B<T2>'. Nullability of type argument 'T1?' doesn't match constraint type 'T1'. // A<T1>.B<T1?> d1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "T1?").WithArguments("A<T1>.B<T2>", "T1", "T2", "T1?").WithLocation(20, 17), // (22,16): warning CS8631: The type 'C?' cannot be used as type parameter 'T2' in the generic type or method 'A<C>.B<T2>'. Nullability of type argument 'C?' doesn't match constraint type 'C'. // A<C>.B<C?> f1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "C?").WithArguments("A<C>.B<T2>", "C", "T2", "C?").WithLocation(22, 16) ); } [Fact] [WorkItem(34842, "https://github.com/dotnet/roslyn/issues/34842")] public void ObliviousTypeParameter_03() { var source = $@"#pragma warning disable {(int)ErrorCode.WRN_UnreferencedFieldAssg} " + @"#nullable disable class A<T1, T2, T3> where T2 : class where T3 : notnull { T1 F1; T2 F2; T3 F3; B F4; #nullable enable void M1() { F1 = default; F2 = default; F2 = null; F3 = default; F4 = default; } } class B { } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( ); } [Fact] [WorkItem(34842, "https://github.com/dotnet/roslyn/issues/34842")] public void ObliviousTypeParameter_04() { var source = @"#nullable disable class A<T1, T2, T3> where T2 : class where T3 : notnull { void M1(T1 x, T2 y, T3 z, B w) #nullable enable { x = default; y = default; y = null; z = default; w = default; } } class B { } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( ); } [WorkItem(23270, "https://github.com/dotnet/roslyn/issues/23270")] [Fact] public void NotNullAfterDereference_00() { var source = @"class Program { static void M(object? obj) { obj.F(); obj.ToString(); // 1 obj.ToString(); } } static class E { internal static void F(this object? obj) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(6, 9)); } [WorkItem(23270, "https://github.com/dotnet/roslyn/issues/23270")] [Fact] public void NotNullAfterDereference_01() { var source = @"class Program { static void F(object? x) { x.ToString(); // 1 object? y; y.ToString(); // 2 y = null; y.ToString(); // 3 x.ToString(); y.ToString(); x = y; if (y != null) { x.ToString(); } x.ToString(); y.ToString(); // 4 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(5, 9), // (7,9): error CS0165: Use of unassigned local variable 'y' // y.ToString(); // 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(7, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(18, 9)); } [Fact] public void NotNullAfterDereference_02() { var source = @"class Program { static void F<T>(T x) { x.ToString(); // 1 T y; y.ToString(); // 2 y = default; y.ToString(); // 4 x.ToString(); y.ToString(); x = y; if (y != null) { x.ToString(); } x.ToString(); y.ToString(); // 5 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(5, 9), // (7,9): error CS0165: Use of unassigned local variable 'y' // y.ToString(); // 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(7, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(18, 9)); } [Fact] public void NotNullAfterDereference_03() { var source = @"class C { void F1(C x) { } static void G1(C? x) { x?.F1(x); x!.F1(x); x.F1(x); } static void G2(bool b, C? y) { y?.F2(y); if (b) y!.F2(y); // 3 y.F2(y); // 4, 5 } } static class E { internal static void F2(this C x, C y) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,22): warning CS8604: Possible null reference argument for parameter 'y' in 'void E.F2(C x, C y)'. // if (b) y!.F2(y); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("y", "void E.F2(C x, C y)").WithLocation(13, 22), // (14,9): warning CS8604: Possible null reference argument for parameter 'x' in 'void E.F2(C x, C y)'. // y.F2(y); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void E.F2(C x, C y)").WithLocation(14, 9), // (14,14): warning CS8604: Possible null reference argument for parameter 'y' in 'void E.F2(C x, C y)'. // y.F2(y); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("y", "void E.F2(C x, C y)").WithLocation(14, 14)); } [Fact] public void NotNullAfterDereference_04() { var source = @"class Program { static void F<T>(bool b, string? s) { int n; if (b) { n = s/*T:string?*/.Length; // 1 n = s/*T:string!*/.Length; } n = b ? s/*T:string?*/.Length + // 2 s/*T:string!*/.Length : 0; n = s/*T:string?*/.Length; // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,17): warning CS8602: Dereference of a possibly null reference. // n = s/*T:string?*/.Length; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 17), // (12,17): warning CS8602: Dereference of a possibly null reference. // n = b ? s/*T:string?*/.Length + // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 17), // (14,13): warning CS8602: Dereference of a possibly null reference. // n = s/*T:string?*/.Length; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 13)); comp.VerifyTypes(); } [Fact] public void NotNullAfterDereference_05() { var source = @"class Program { static void F(string? s) { int n; try { n = s/*T:string?*/.Length; // 1 try { n = s/*T:string!*/.Length; } finally { n = s/*T:string!*/.Length; } } catch (System.IO.IOException) { n = s/*T:string?*/.Length; // 2 } catch { n = s/*T:string?*/.Length; // 3 } finally { n = s/*T:string?*/.Length; // 4 } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,17): warning CS8602: Dereference of a possibly null reference. // n = s/*T:string?*/.Length; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 17), // (20,17): warning CS8602: Dereference of a possibly null reference. // n = s/*T:string?*/.Length; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(20, 17), // (24,17): warning CS8602: Dereference of a possibly null reference. // n = s/*T:string?*/.Length; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(24, 17), // (28,17): warning CS8602: Dereference of a possibly null reference. // n = s/*T:string?*/.Length; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(28, 17)); comp.VerifyTypes(); } [Fact] public void NotNullAfterDereference_06() { var source = @"class C { object F = default!; static void G(C? c) { c.F = c; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // One warning only, rather than one warning for dereference of c.F // and another warning for assignment c.F = c. comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // c.F = c; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(6, 9)); } [Fact] public void NotNullAfterDereference_Call() { var source = @"#pragma warning disable 0649 class C { object? y; void F(object? o) { } static void G(C? x) { x.F(x = null); // 1 x.F(x.y); // 2, 3 x.F(x.y); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for x.F(x.y). comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // x.F(x = null); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // x.F(x.y); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 9)); } [Fact] public void NotNullAfterDereference_Array() { var source = @"class Program { static int F(object? o) => 0; static void G(object[]? x, object[] y) { object z; z = x[F(x = null)]; // 1 z = x[x.Length]; // 2, 3 z = x[x.Length]; y[F(y = null)] = 1; y[y.Length] = 2; // 4, 5 y[y.Length] = 3; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for x[x.Length] and y[y.Length]. comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // z = x[F(x = null)]; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 13), // (8,13): warning CS8602: Dereference of a possibly null reference. // z = x[x.Length]; // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13), // (10,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // y[F(y = null)] = 1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(10, 17), // (11,9): warning CS8602: Dereference of a possibly null reference. // y[y.Length] = 2; // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 9)); } [Fact] public void NotNullAfterDereference_Indexer() { var source = @"#pragma warning disable 0649 class C { object? F; object this[object? o] { get { return 1; } set { } } static void G(C? x, C y) { object z; z = x[x = null]; // 1 z = x[x.F]; // 2 z = x[x.F]; y[y = null] = 1; // 3 y[y.F] = 2; // 4 y[y.F] = 3; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for x[x.F] and y[y.F]. comp.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // z = x[x = null]; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // z = x[x.F]; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 13), // (16,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // y[y = null] = 1; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 15), // (17,9): warning CS8602: Dereference of a possibly null reference. // y[y.F] = 2; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(17, 9) ); } [Fact] public void NotNullAfterDereference_Field() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C { object? F; static object? G(object? o) => o; static void M(C? x, C? y) { object? o; o = x.F; // 1 o = x.F; y.F = G(y = null); // 2 y.F = G(y.F); // 3, 4 y.F = G(y.F); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for y.F = G(y.F). comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // o = x.F; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 13), // (12,9): warning CS8602: Dereference of a possibly null reference. // y.F = G(y = null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.F = G(y.F); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(13, 9)); } [Fact] public void NotNullAfterDereference_Property() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C { object? P { get; set; } static object? F(object? o) => o; static void M(C? x, C? y) { object? o; o = x.P; // 1 o = x.P; y.P = F(y = null); // 2 y.P = F(y.P); // 3, 4 y.P = F(y.P); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for y.P = F(y.P). comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // o = x.F; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 13), // (12,9): warning CS8602: Dereference of a possibly null reference. // y.F = G(y = null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.F = G(y.F); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(13, 9)); } [Fact] public void NotNullAfterDereference_Event() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 delegate void D(); class C { event D E; D F; static D G(C? c) => throw null!; static void M(C? x, C? y, C? z) { x.E(); // 1 x.E(); y.E += G(y = null); // 2 y.E += y.F; // 3, 4 y.E += y.F; y.E(); z.E = null; // 5 z.E(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for y.E += y.F. comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // x.E(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.E += G(y = null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // y.E += y.F; // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(14, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // z.E = null; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(17, 9), // (17,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // z.E = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(17, 15), // (18,9): warning CS8602: Dereference of a possibly null reference. // z.E(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.E").WithLocation(18, 9)); } [Fact] public void NotNullAfterDereference_Dynamic() { var source = @"class Program { static void F(dynamic? d) { d.ToString(); // 1 d.ToString(); } static void G(dynamic? x, dynamic? y) { object z; z = x[x = null]; // 2 z = x[x.F]; // 3, 4 z = x[x.F]; y[y = null] = 1; y[y.F] = 2; // 5, 6 y[y.F] = 3; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for x[x.F] and y[y.F]. comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // d.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d").WithLocation(5, 9), // (11,13): warning CS8602: Dereference of a possibly null reference. // z = x[x = null]; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // z = x[x.F]; // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 13), // (14,9): warning CS8602: Dereference of a possibly null reference. // y[y = null] = 1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // y[y.F] = 2; // 5, 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(15, 9)); } [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] [Fact] public void NotNullAfterDereference_MethodGroup_01() { var source = @"delegate void D(); class C { void F1() { } static void F(C? x, C? y) { D d; d = x.F1; // warning d = y.F2; // ok } } static class E { internal static void F2(this C? c) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // d = x.F1; // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13)); } [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] [Fact] public void NotNullAfterDereference_MethodGroup_02() { var source = @"delegate void D1(int i); delegate void D2(); class C { void F(int i) { } static void F1(D1 d) { } static void F2(D2 d) { } static void G(C? x, C? y) { F1(x.F); // 1 (x.F is a member method group) F1(x.F); F2(y.F); // 2 (y.F is an extension method group) F2(y.F); } } static class E { internal static void F(this C x) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,12): warning CS8602: Dereference of a possibly null reference. // F1(x.F); // 1 (x.F is a member method group) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 12), // (12,12): warning CS8604: Possible null reference argument for parameter 'x' in 'void E.F(C x)'. // F2(y.F); // 2 (y.F is an extension method group) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void E.F(C x)").WithLocation(12, 12)); } [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] [Fact] public void MethodGroupReinferredAfterReceiver() { var source = @"public class C { G<T> CreateG<T>(T t) => new G<T>(); void Main(string? s1, string? s2) { Run(CreateG(s1).M, s2)/*T:(string?, string?)*/; if (s1 == null) return; Run(CreateG(s1).M, s2)/*T:(string!, string?)*/; if (s2 == null) return; Run(CreateG(s1).M, s2)/*T:(string!, string!)*/; } (T, U) Run<T, U>(MyDelegate<T, U> del, U u) => del(u); } public class G<T> { public T t = default(T)!; public (T, U) M<U>(U u) => (t, u); } public delegate (T, U) MyDelegate<T, U>(U u); "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(33638, "https://github.com/dotnet/roslyn/issues/33638")] [Fact] public void TupleFromNestedGenerics() { var source = @"public class G<T> { public (T, U) M<U>(T t, U u) => (t, u); } public class C { public (T, U) M<T, U>(T t, U u) => (t, u); } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [WorkItem(30562, "https://github.com/dotnet/roslyn/issues/30562")] [Fact] public void NotNullAfterDereference_ForEach() { var source = @"class Enumerable { public System.Collections.IEnumerator GetEnumerator() => throw null!; } class Program { static void F1(object[]? x1, object[]? y1) { foreach (var x in x1) { } // 1 foreach (var x in x1) { } } static void F2(object[]? x1, object[]? y1) { foreach (var y in y1) { } // 2 y1.GetEnumerator(); } static void F3(Enumerable? x2, Enumerable? y2) { foreach (var x in x2) { } // 3 foreach (var x in x2) { } } static void F4(Enumerable? x2, Enumerable? y2) { y2.GetEnumerator(); // 4 foreach (var y in y2) { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in x1) { } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(9, 27), // (14,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in y1) { } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(14, 27), // (19,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in x2) { } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(19, 27), // (24,9): warning CS8602: Dereference of a possibly null reference. // y2.GetEnumerator(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(24, 9)); } [Fact] public void SpecialAndWellKnownMemberLookup() { var source0 = @" namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Int32 { } public class Type { } public struct Boolean { } public struct Enum { } public class Attribute { } public struct Nullable<T> { public static implicit operator Nullable<T>(T x) { throw null!; } public static explicit operator T(Nullable<T> x) { throw null!; } } namespace Collections.Generic { public class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null!; } } } "; var comp = CreateEmptyCompilation(new[] { source0 }, options: WithNullableEnable()); var implicitOp = comp.GetSpecialTypeMember(SpecialMember.System_Nullable_T__op_Implicit_FromT); var explicitOp = comp.GetSpecialTypeMember(SpecialMember.System_Nullable_T__op_Explicit_ToT); var getDefault = comp.GetWellKnownTypeMember(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default); Assert.NotNull(implicitOp); Assert.NotNull(explicitOp); Assert.NotNull(getDefault); Assert.True(implicitOp.IsDefinition); Assert.True(explicitOp.IsDefinition); Assert.True(getDefault.IsDefinition); } [Fact] public void ExpressionTrees_ByRefDynamic() { string source = @" using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Action<dynamic>> e = x => Goo(ref x); } static void Goo<T>(ref T x) { } } "; CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, options: WithNullableEnable()); } [Fact] [WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")] public void TypeSymbolGetHashCode_Annotated() { var text = @" class C<T> where T : class { C<T?> M() => throw null!; } "; var comp = CreateNullableCompilation(text); var type = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal("C<T>", type.ToTestDisplayString(includeNonNullable: true)); Assert.True(type.IsDefinition); var type2 = comp.GetMember<MethodSymbol>("C.M").ReturnType; Assert.Equal("C<T?>", type2.ToTestDisplayString(includeNonNullable: true)); Assert.False(type2.IsDefinition); AssertHashCodesMatch(type, type2); } [Fact] [WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")] public void TypeSymbolGetHashCode_NotAnnotated() { var text = @" class C<T> where T : class { C<T> M() => throw null!; } "; var comp = CreateNullableCompilation(text); var type = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal("C<T>", type.ToTestDisplayString(includeNonNullable: true)); Assert.True(type.IsDefinition); var type2 = comp.GetMember<MethodSymbol>("C.M").ReturnType; Assert.Equal("C<T!>", type2.ToTestDisplayString(includeNonNullable: true)); Assert.False(type2.IsDefinition); AssertHashCodesMatch(type, type2); } [Fact] [WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")] public void TypeSymbolGetHashCode_ContainingType() { var text = @" class C<T> where T : class { interface I { } } "; var comp = CreateNullableCompilation(text); var iDefinition = comp.GetMember<NamedTypeSymbol>("C.I"); Assert.Equal("C<T>.I", iDefinition.ToTestDisplayString(includeNonNullable: true)); Assert.True(iDefinition.IsDefinition); var cDefinition = iDefinition.ContainingType; Assert.Equal("C<T>", cDefinition.ToTestDisplayString(includeNonNullable: true)); Assert.True(cDefinition.IsDefinition); var c2 = cDefinition.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(cDefinition.TypeParameters.Single(), NullableAnnotation.NotAnnotated))); Assert.Equal("C<T!>", c2.ToTestDisplayString(includeNonNullable: true)); Assert.False(c2.IsDefinition); AssertHashCodesMatch(cDefinition, c2); var i2 = c2.GetTypeMember("I"); Assert.Equal("C<T!>.I", i2.ToTestDisplayString(includeNonNullable: true)); Assert.False(i2.IsDefinition); AssertHashCodesMatch(iDefinition, i2); var c3 = cDefinition.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(cDefinition.TypeParameters.Single(), NullableAnnotation.Annotated))); Assert.Equal("C<T?>", c3.ToTestDisplayString(includeNonNullable: true)); Assert.False(c3.IsDefinition); AssertHashCodesMatch(cDefinition, c3); var i3 = c3.GetTypeMember("I"); Assert.Equal("C<T?>.I", i3.ToTestDisplayString(includeNonNullable: true)); Assert.False(i3.IsDefinition); AssertHashCodesMatch(iDefinition, i3); } [Fact] [WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")] public void TypeSymbolGetHashCode_ContainingType_GenericNestedType() { var text = @" class C<T> where T : class { interface I<U> where U : class { } } "; var comp = CreateNullableCompilation(text); var iDefinition = comp.GetMember<NamedTypeSymbol>("C.I"); Assert.Equal("C<T>.I<U>", iDefinition.ToTestDisplayString(includeNonNullable: true)); Assert.True(iDefinition.IsDefinition); // Construct from iDefinition with annotated U from iDefinition var i1 = iDefinition.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(iDefinition.TypeParameters.Single(), NullableAnnotation.Annotated))); Assert.Equal("C<T>.I<U?>", i1.ToTestDisplayString(includeNonNullable: true)); AssertHashCodesMatch(iDefinition, i1); var cDefinition = iDefinition.ContainingType; Assert.Equal("C<T>", cDefinition.ToTestDisplayString(includeNonNullable: true)); Assert.True(cDefinition.IsDefinition); // Construct from cDefinition with unannotated T from cDefinition var c2 = cDefinition.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(cDefinition.TypeParameters.Single(), NullableAnnotation.NotAnnotated))); var i2 = c2.GetTypeMember("I"); Assert.Equal("C<T!>.I<U>", i2.ToTestDisplayString(includeNonNullable: true)); Assert.Same(i2.OriginalDefinition, iDefinition); AssertHashCodesMatch(i2, iDefinition); // Construct from i2 with U from iDefinition var i2a = i2.Construct(iDefinition.TypeParameters.Single()); Assert.Equal("C<T!>.I<U>", i2a.ToTestDisplayString(includeNonNullable: true)); AssertHashCodesMatch(iDefinition, i2a); // Construct from i2 with annotated U from iDefinition var i2b = i2.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(iDefinition.TypeParameters.Single(), NullableAnnotation.Annotated))); Assert.Equal("C<T!>.I<U?>", i2b.ToTestDisplayString(includeNonNullable: true)); AssertHashCodesMatch(iDefinition, i2b); // Construct from i2 with U from i2 var i2c = i2.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(i2.TypeParameters.Single(), NullableAnnotation.Annotated))); Assert.Equal("C<T!>.I<U?>", i2c.ToTestDisplayString(includeNonNullable: true)); AssertHashCodesMatch(iDefinition, i2c); var c3 = cDefinition.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(cDefinition.TypeParameters.Single(), NullableAnnotation.Annotated))); var i3 = c3.GetTypeMember("I"); Assert.Equal("C<T?>.I<U>", i3.ToTestDisplayString(includeNonNullable: true)); AssertHashCodesMatch(iDefinition, i3); var i3b = i3.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(i3.TypeParameters.Single(), NullableAnnotation.Annotated))); Assert.Equal("C<T?>.I<U?>", i3b.ToTestDisplayString(includeNonNullable: true)); AssertHashCodesMatch(iDefinition, i3b); // Construct from cDefinition with modified T from cDefinition var modifiers = ImmutableArray.Create(CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Object))); var c4 = cDefinition.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(cDefinition.TypeParameters.Single(), customModifiers: modifiers))); Assert.Equal("C<T modopt(System.Object)>", c4.ToTestDisplayString()); Assert.False(c4.IsDefinition); Assert.False(cDefinition.Equals(c4, TypeCompareKind.ConsiderEverything)); Assert.False(cDefinition.Equals(c4, TypeCompareKind.CLRSignatureCompareOptions)); Assert.True(cDefinition.Equals(c4, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)); Assert.Equal(cDefinition.GetHashCode(), c4.GetHashCode()); var i4 = c4.GetTypeMember("I"); Assert.Equal("C<T modopt(System.Object)>.I<U>", i4.ToTestDisplayString()); Assert.Same(i4.OriginalDefinition, iDefinition); Assert.False(iDefinition.Equals(i4, TypeCompareKind.ConsiderEverything)); Assert.False(iDefinition.Equals(i4, TypeCompareKind.CLRSignatureCompareOptions)); Assert.True(iDefinition.Equals(i4, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)); Assert.Equal(iDefinition.GetHashCode(), i4.GetHashCode()); } private static void AssertHashCodesMatch(TypeSymbol c, TypeSymbol c2) { Assert.True(c.Equals(c2)); Assert.True(c.Equals(c2, SymbolEqualityComparer.Default.CompareKind)); Assert.False(c.Equals(c2, SymbolEqualityComparer.ConsiderEverything.CompareKind)); Assert.True(c.Equals(c2, TypeCompareKind.AllIgnoreOptions)); Assert.Equal(c2.GetHashCode(), c.GetHashCode()); } [Fact] [WorkItem(35619, "https://github.com/dotnet/roslyn/issues/35619")] public void ExplicitInterface_UsingOuterDefinition_Simple() { var text = @" class Outer<T> { protected internal interface Interface { void Method(); } internal class C : Outer<T>.Interface { void Interface.Method() { } } } "; var comp = CreateNullableCompilation(text); comp.VerifyDiagnostics(); } [Fact] [WorkItem(35619, "https://github.com/dotnet/roslyn/issues/35619")] public void ExplicitInterface_UsingOuterDefinition() { var text = @" class Outer<T> where T : class { internal class Inner<U> where U : class { protected internal interface Interface { void Method(); } // The implemented interface is Outer<T!>.Inner<U!>.Interface internal class Derived6 : Outer<T>.Inner<U>.Interface { // The explicit interface is Outer<T>.Inner<U!>.Interface void Inner<U>.Interface.Method() { } } } } "; CreateCompilation(text, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(35619, "https://github.com/dotnet/roslyn/issues/35619")] public void ExplicitInterface_WithExplicitOuter() { var text = @" class Outer<T> where T : class { internal class Inner<U> where U : class { protected internal interface Interface { void Method(); } // The implemented interface is Outer<T!>.Inner<U!>.Interface internal class Derived6 : Outer<T>.Inner<U>.Interface { // The explicit interface is Outer<T!>.Inner<U!>.Interface void Outer<T>.Inner<U>.Interface.Method() { } } } } "; CreateCompilation(text, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] public void ExplicitInterface_WithExplicitOuter_DisabledT() { var text = @" class Outer<T> where T : class { internal class Inner<U> where U : class { protected internal interface Interface { void Method(); } // The implemented interface is Outer<T!>.Inner<U!>.Interface internal class Derived6 : Outer<T>.Inner<U>.Interface { // The explicit interface is Outer<T~>.Inner<U!>.Interface void Outer< #nullable disable T #nullable enable >.Inner<U>.Interface.Method() { } } } } "; CreateCompilation(text, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] public void ExplicitInterface_WithExplicitOuter_DisabledT_ImplementedInterfaceMatches() { var text = @" class Outer<T> where T : class { internal class Inner<U> where U : class { protected internal interface Interface { void Method(); } // The implemented interface is Outer<T~>.Inner<U!>.Interface internal class Derived6 : Inner<U>.Interface { // The explicit interface is Outer<T~>.Inner<U!>.Interface void Outer< #nullable disable T #nullable enable >.Inner<U>.Interface.Method() { } } } } "; CreateCompilation(text, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] public void TestErrorsImplementingGenericNestedInterfaces_Explicit() { var text = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { T Property { set; } void Method<Z>(T a, U[] b, List<V> c, Dictionary<W, Z> d); } internal class Derived4 { internal class Derived5 : Outer<T>.Inner<U>.Interface<U, T> { T Outer<T>.Inner<U>.Interface<U, T>.Property { set { } } void Inner<U>.Interface<U, T>.Method<K>(T a, U[] b, List<U> c, Dictionary<K, T> D) { } } internal class Derived6 : Outer<T>.Inner<U>.Interface<U, T> { T Outer<T>.Inner<U>.Interface<U, T>.Property { set { } } void Inner<U>.Interface<U, T>.Method<K>(T a, U[] b, List<U> c, Dictionary<T, K> D) { } } } } } "; CreateCompilation(text, options: WithNullableEnable()).VerifyDiagnostics( // (14,39): error CS0535: 'Outer<T>.Inner<U>.Derived4.Derived5' does not implement interface member 'Outer<T>.Inner<U>.Interface<U, T>.Method<Z>(T, U[], List<U>, Dictionary<T, Z>)' // internal class Derived5 : Outer<T>.Inner<U>.Interface<U, T> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<T>.Inner<U>.Interface<U, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5", "Outer<T>.Inner<U>.Interface<U, T>.Method<Z>(T, U[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<T, Z>)").WithLocation(14, 39), // (20,47): error CS0539: 'Outer<T>.Inner<U>.Derived4.Derived5.Method<K>(T, U[], List<U>, Dictionary<K, T>)' in explicit interface declaration is not found among members of the interface that can be implemented // void Inner<U>.Interface<U, T>.Method<K>(T a, U[] b, List<U> c, Dictionary<K, T> D) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Method<K>(T, U[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<K, T>)").WithLocation(20, 47) ); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] public void TestErrorsImplementingGenericNestedInterfaces_Explicit_IncorrectPartialQualification() { var source = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { T Property { set; } void Method<Z>(T a, U[] b, List<V> c, Dictionary<W, Z> d); } internal class Derived3 : Interface<long, string> { T Interface<long, string>.Property { set { } } void Inner<U>.Interface<long, string>.Method<K>(T a, U[] B, List<long> C, Dictionary<string, K> d) { } } } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_01() { var source1 = @" public interface I1<I1T1, I1T2> { void M(); } public interface I2<I2T1, I2T2> : I1<I2T1, I2T2> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2> { void I1<CT1, CT2>.M() { } }"; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_02() { var source1 = @" public interface I1<I1T1> { void M(); } public struct S<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<S<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2> { void I1<S<CT1, CT2>>.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_03() { var source1 = @" public interface I1<I1T1> { void M(); } public class C1<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<C1<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2> { void I1<C1<CT1, CT2>>.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_04() { var source1 = @" public interface I1<I1T1> { void M(); } public class C1<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<C1<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2>, I1<C1<CT1, CT2>> { void I1<C1<CT1, CT2>>.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_05() { var source1 = @" public interface I1<I1T1> { void M(); } public struct S<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<S<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2> { void I1<S<CT1, CT2 #nullable disable > #nullable enable >.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_06() { var source1 = @" public interface I1<I1T1> { void M(); } public class C1<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<C1<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2> { void I1<C1<CT1, CT2 #nullable disable > #nullable enable >.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_07() { var source1 = @" public interface I1<I1T1> { void M(); } public interface I2<I2T1, I2T2> : I1<(I2T1, I2T2)> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2> { void I1<(CT1 a, CT2 b)>.M() { } } "; var expected = new DiagnosticDescription[] { // (4,10): error CS0540: 'C<CT1, CT2>.I1<(CT1 a, CT2 b)>.M()': containing type does not implement interface 'I1<(CT1 a, CT2 b)>' // void I1<(CT1 a, CT2 b)>.M() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<(CT1 a, CT2 b)>").WithArguments("C<CT1, CT2>.I1<(CT1 a, CT2 b)>.M()", "I1<(CT1 a, CT2 b)>").WithLocation(4, 10) }; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(expected); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(expected); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_08() { var source1 = @" public interface I1<I1T1> { void M(); } public interface I2<I2T1, I2T2> : I1<(I2T1, I2T2)> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2>, I1<(CT1 a, CT2 b)> { void I1<(CT1 c, CT2 d)>.M() { } } "; var expected = new DiagnosticDescription[] { // (2,7): error CS8140: 'I1<(CT1 a, CT2 b)>' is already listed in the interface list on type 'C<CT1, CT2>' with different tuple element names, as 'I1<(CT1, CT2)>'. // class C<CT1, CT2> : I2<CT1, CT2>, I1<(CT1 a, CT2 b)> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I1<(CT1 a, CT2 b)>", "I1<(CT1, CT2)>", "C<CT1, CT2>").WithLocation(2, 7), // (4,10): error CS0540: 'C<CT1, CT2>.I1<(CT1 c, CT2 d)>.M()': containing type does not implement interface 'I1<(CT1 c, CT2 d)>' // void I1<(CT1 c, CT2 d)>.M() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<(CT1 c, CT2 d)>").WithArguments("C<CT1, CT2>.I1<(CT1 c, CT2 d)>.M()", "I1<(CT1 c, CT2 d)>").WithLocation(4, 10) }; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(expected); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(expected); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_09() { var source1 = @" public interface I1<I1T1> { void M(); } public class C1<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<C1<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2>, #nullable disable I1<C1<CT1, CT2>> #nullable enable { void I1<C1<CT1, CT2>>.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_10() { var source1 = @" public interface I1<I1T1> { void M(); } public class C1<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<C1<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2>, I1<C1<CT1, CT2 #nullable disable > #nullable enable > { void I1<C1<CT1, CT2>>.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] public void WriteOfReadonlyStaticMemberOfAnotherInstantiation01() { var text = @"public static class Goo<T> { static Goo() { Goo<T>.Y = 3; } public static int Y { get; } }"; CreateCompilation(text, options: WithNullableEnable(TestOptions.ReleaseDll)).VerifyEmitDiagnostics(); CreateCompilation(text, options: WithNullableEnable(TestOptions.ReleaseDll), parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyEmitDiagnostics(); } [Fact] public void TestOverrideGenericMethodWithTypeParamDiffNameWithCustomModifiers() { var text = @" namespace Metadata { using System; public class GD : Outer<string>.Inner<ulong> { public override void Method<X>(string[] x, ulong[] y, X[] z) { Console.Write(""Hello {0}"", z.Length); } static void Main() { new GD().Method<byte>(null, null, new byte[] { 0, 127, 255 }); } } } "; var verifier = CompileAndVerify( text, new[] { TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll }, options: WithNullableEnable(TestOptions.ReleaseExe), expectedOutput: @"Hello 3", expectedSignatures: new[] { // The ILDASM output is following, and Roslyn handles it correctly. // Verifier tool gives different output due to the limitation of Reflection // @".method public hidebysig virtual instance System.Void Method<X>(" + // @"System.String modopt([mscorlib]System.Runtime.CompilerServices.IsConst)[] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) x," + // @"UInt64 modopt([mscorlib]System.Runtime.CompilerServices.IsConst)[] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) y," + // @"!!X modopt([mscorlib]System.Runtime.CompilerServices.IsConst)[] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) z) cil managed") Signature("Metadata.GD", "Method", @".method public hidebysig virtual instance System.Void Method<X>(" + @"modopt(System.Runtime.CompilerServices.IsConst) System.String[] x, " + @"modopt(System.Runtime.CompilerServices.IsConst) System.UInt64[] y, "+ @"modopt(System.Runtime.CompilerServices.IsConst) X[] z) cil managed"), }, symbolValidator: module => { var expected = @"[NullableContext(1)] [Nullable({ 0, 1 })] Metadata.GD void Method<X>(System.String![]! x, System.UInt64[]! y, X[]! z) [Nullable(0)] X System.String![]! x System.UInt64[]! y X[]! z GD() "; var actual = NullableAttributesVisitor.GetString((PEModuleSymbol)module); AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual); }); } [Fact] [WorkItem(30747, "https://github.com/dotnet/roslyn/issues/30747")] public void MissingTypeKindBasisTypes() { var source1 = @" public struct A {} public enum B {} public class C {} public delegate void D(); public interface I1 {} "; var compilation1 = CreateEmptyCompilation(source1, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { MinCorlibRef }); compilation1.VerifyEmitDiagnostics(); Assert.Equal(TypeKind.Struct, compilation1.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation1.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation1.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation1.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation1.GetTypeByMetadataName("I1").TypeKind); var source2 = @" interface I2 { I1 M(A a, B b, C c, D d); } "; var compilation2 = CreateEmptyCompilation(source2, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { compilation1.EmitToImageReference(), MinCorlibRef }); compilation2.VerifyEmitDiagnostics(); // Verification against a corlib not named exactly mscorlib is expected to fail. CompileAndVerify(compilation2, verify: Verification.Fails); Assert.Equal(TypeKind.Struct, compilation2.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation2.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation2.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation2.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation2.GetTypeByMetadataName("I1").TypeKind); var compilation3 = CreateEmptyCompilation(source2, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { compilation1.ToMetadataReference(), MinCorlibRef }); compilation3.VerifyEmitDiagnostics(); CompileAndVerify(compilation3, verify: Verification.Fails); Assert.Equal(TypeKind.Struct, compilation3.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation3.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation3.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation3.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation3.GetTypeByMetadataName("I1").TypeKind); var compilation4 = CreateEmptyCompilation(source2, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { compilation1.EmitToImageReference() }); compilation4.VerifyDiagnostics( // (4,10): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "A").WithArguments("System.ValueType", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 10), // (4,15): error CS0012: The type 'Enum' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("System.Enum", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 15), // (4,25): error CS0012: The type 'MulticastDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.MulticastDelegate", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 25) ); var a = compilation4.GetTypeByMetadataName("A"); var b = compilation4.GetTypeByMetadataName("B"); var c = compilation4.GetTypeByMetadataName("C"); var d = compilation4.GetTypeByMetadataName("D"); var i1 = compilation4.GetTypeByMetadataName("I1"); Assert.Equal(TypeKind.Class, a.TypeKind); Assert.NotNull(a.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, b.TypeKind); Assert.NotNull(b.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, c.TypeKind); Assert.Null(c.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, d.TypeKind); Assert.NotNull(d.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Interface, i1.TypeKind); Assert.Null(i1.GetUseSiteDiagnostic()); var compilation5 = CreateEmptyCompilation(source2, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { compilation1.ToMetadataReference() }); compilation5.VerifyEmitDiagnostics( // 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), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1)); var compilation6 = CreateEmptyCompilation(source2, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { compilation1.EmitToImageReference(), MscorlibRef }); compilation6.VerifyDiagnostics( // (4,10): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "A").WithArguments("System.ValueType", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 10), // (4,15): error CS0012: The type 'Enum' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("System.Enum", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 15), // (4,25): error CS0012: The type 'MulticastDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.MulticastDelegate", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 25) ); a = compilation6.GetTypeByMetadataName("A"); b = compilation6.GetTypeByMetadataName("B"); c = compilation6.GetTypeByMetadataName("C"); d = compilation6.GetTypeByMetadataName("D"); i1 = compilation6.GetTypeByMetadataName("I1"); Assert.Equal(TypeKind.Class, a.TypeKind); Assert.NotNull(a.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, b.TypeKind); Assert.NotNull(b.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, c.TypeKind); Assert.Null(c.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, d.TypeKind); Assert.NotNull(d.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Interface, i1.TypeKind); Assert.Null(i1.GetUseSiteDiagnostic()); var compilation7 = CreateEmptyCompilation(source2, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { compilation1.ToMetadataReference(), MscorlibRef }); compilation7.VerifyEmitDiagnostics(); CompileAndVerify(compilation7); Assert.Equal(TypeKind.Struct, compilation7.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation7.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation7.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation7.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation7.GetTypeByMetadataName("I1").TypeKind); } [Fact, WorkItem(718176, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/718176")] public void AccessPropertyWithoutArguments() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface I Property Value(Optional index As Object = Nothing) As Object End Interface"; var ref1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C : I { public dynamic get_Value(object index = null) => ""Test""; public void set_Value(object index = null, object value = null) { } } class Test { static void Main() { I x = new C(); System.Console.WriteLine(x.Value.Length); } }"; var comp = CreateCompilation(source2, new[] { ref1.WithEmbedInteropTypes(true), CSharpRef }, options: WithNullableEnable(TestOptions.ReleaseExe)); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void NullabilityOfTypeParameters_001() { var source = @" class Outer { void M<T>(T x) { object y; y = x; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(7, 13) ); } [Fact] public void NullabilityOfTypeParameters_002() { var source = @" class Outer { void M<T>(T x) { dynamic y; y = x; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(7, 13) ); } [Fact] public void NullabilityOfTypeParameters_003() { var source = @" class Outer { void M<T>(T x) where T : I1 { object y; y = x; dynamic z; z = x; } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_004() { var source = @" class Outer { void M<T, U>(U x) where U : T { T y; y = x; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_005() { var source = @" class Outer { void M<T>(T x) { if (x == null) return; object y; y = x; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_006() { var source = @" class Outer { void M<T>(T x) { if (x == null) return; dynamic y; y = x; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_007() { var source = @" class Outer { T M0<T>(T x0, T y0) { if (x0 == null) throw null!; M2(x0) = x0; M2<T>(x0) = y0; M2(x0).ToString(); M2<T>(x0).ToString(); throw null!; } void M1(object? x1, object? y1) { if (x1 == null) return; M2(x1) = x1; M2(x1) = y1; } ref U M2<U>(U a) where U : notnull => throw null!; } "; // Note: you cannot pass a `T` to a `U : object` even if the `T` was null-tested CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2(x0) = x0; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2").WithArguments("Outer.M2<U>(U)", "U", "T").WithLocation(7, 9), // (8,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2<T>(x0) = y0; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2<T>").WithArguments("Outer.M2<U>(U)", "U", "T").WithLocation(8, 9), // (10,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2(x0).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2").WithArguments("Outer.M2<U>(U)", "U", "T").WithLocation(10, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // M2(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0)").WithLocation(10, 9), // (11,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2<T>(x0).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2<T>").WithArguments("Outer.M2<U>(U)", "U", "T").WithLocation(11, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // M2<T>(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2<T>(x0)").WithLocation(11, 9), // (19,18): warning CS8601: Possible null reference assignment. // M2(x1) = y1; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y1").WithLocation(19, 18) ); } [Fact] public void NullabilityOfTypeParameters_008() { var source = @" class Outer { void M0<T, U>(T x0, U y0, U z0) where U : T { if (x0 == null) return; if (y0 == null) return; M2(x0) = y0; M2(x0) = z0; M2<T>(x0) = y0; M2<T>(x0) = z0; M2(x0).ToString(); M2<T>(x0).ToString(); } ref U M2<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // M2(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // M2<T>(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2<T>(x0)").WithLocation(13, 9) ); } [Fact] public void NullabilityOfTypeParameters_009() { var source = @" class Outer { void M0<T>(T x0, T y0) { x0 = y0; } void M1<T>(T y1) { T x1 = y1; x1 = y1; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_010() { var source = @" class Outer { void M0<T>(Outer x0, T y0) where T : Outer? { x0 = y0; } void M1<T>(T y1) where T : Outer? { Outer x1 = y1; x1 = y1; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x0 = y0; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y0").WithLocation(6, 14), // (11,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer x1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(11, 20), // (12,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(12, 14) ); } [Fact] public void NullabilityOfTypeParameters_011() { var source = @" class Outer { void M0<T>(Outer x0, T y0) where T : Outer? { if (y0 == null) return; x0 = y0; } void M1<T>(T y1) where T : Outer? { if (y1 == null) return; Outer x1 = y1; x1 = y1; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(30938, "https://github.com/dotnet/roslyn/issues/30938")] public void NullabilityOfTypeParameters_012() { var source = @" class Outer { void M<T>(object? x, object y) { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // z = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "T").WithLocation(7, 13), // (8,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // z = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("object", "T").WithLocation(8, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9)); } [Fact] [WorkItem(30938, "https://github.com/dotnet/roslyn/issues/30938")] public void NullabilityOfTypeParameters_013() { var source = @" class Outer { void M<T>(dynamic? x, dynamic y) { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_014() { var source = @" class Outer { void M<T>(object? x, object y) where T : I1 { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // z = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "T").WithLocation(7, 13), // (8,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // z = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("object", "T").WithLocation(8, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9)); } [Fact] public void NullabilityOfTypeParameters_015() { var source = @" class Outer { void M<T>(dynamic? x, dynamic y) where T : I1 { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_016() { var source = @" class Outer { void M<T>(object? x, object y) where T : I1? { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // z = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "T").WithLocation(7, 13), // (8,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // z = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("object", "T").WithLocation(8, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9)); } [Fact] public void NullabilityOfTypeParameters_017() { var source = @" class Outer { void M<T>(dynamic? x, dynamic y) where T : I1? { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_018() { var source = @" class Outer { void M<T, U>(T x) where U : T { U y; y = x; y = (U)x; y.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'T' to 'U'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("T", "U").WithLocation(7, 13), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_019() { var source = @" class Outer { void M<T, U>(T x) where U : T, I1 { U y; y = x; y = (U)x; y.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'T' to 'U'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("T", "U").WithLocation(7, 13), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_020() { var source = @" class Outer { void M<T, U>(T x) where U : T, I1? { U y; y = x; y = (U)x; y.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'T' to 'U'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("T", "U").WithLocation(7, 13), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_021() { var source = @" class Outer { void M<T, U>(T x) where U : T where T : I1 { U y; y = x; y = (U)x; y.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'T' to 'U'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("T", "U").WithLocation(7, 13) ); } [Fact] public void NullabilityOfTypeParameters_022() { var source = @" class Outer { void M<T>(object? x) { if (x == null) return; T y; y = x; y = (T)x; y.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "T").WithLocation(8, 13) ); } [Fact] [WorkItem(30939, "https://github.com/dotnet/roslyn/issues/30939")] public void NullabilityOfTypeParameters_023() { var source = @" class Outer { void M1<T>(dynamic? x) { if (x == null) return; T y; y = x; y = (T)x; y.ToString(); } void M2<T>(dynamic? x) { if (x != null) return; T y; y = x; y = (T)x; y.ToString(); // 1 } void M3<T>(dynamic? x) { if (x != null) { T y; y = x; y = (T)x; y.ToString(); } else { T y; y = x; y = (T)x; y.ToString(); // 2 } } void M4<T>(dynamic? x) { if (x == null) { T y; y = x; y = (T)x; y.ToString(); // 3 } else { T y; y = x; y = (T)x; y.ToString(); } } void M5<T>(dynamic? x) { // Since `||` here could be a user-defined `operator |` invocation, // no reasonable inferences can be made. if (x == null || false) { T y; y = x; y = (T)x; y.ToString(); // 4 } else { T y; y = x; y = (T)x; y.ToString(); // 5 } } void M6<T>(dynamic? x) { // Since `&&` here could be a user-defined `operator &` invocation, // no reasonable inferences can be made. if (x == null && true) { T y; y = x; y = (T)x; y.ToString(); // 6 } else { T y; y = x; y = (T)x; y.ToString(); // 7 } } void M7<T>(dynamic? x) { if (!(x == null)) { T y; y = x; y = (T)x; y.ToString(); } else { T y; y = x; y = (T)x; y.ToString(); // 8 } } void M8<T>(dynamic? x) { if (!(x != null)) { T y; y = x; y = (T)x; y.ToString(); // 9 } else { T y; y = x; y = (T)x; y.ToString(); } } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(18, 9), // (34,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(34, 13), // (44,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(44, 13), // (63,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(63, 13), // (70,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(70, 13), // (82,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(82, 13), // (89,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(89, 13), // (106,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(106, 13), // (116,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(116, 13)); } [Fact] [WorkItem(30939, "https://github.com/dotnet/roslyn/issues/30939")] public void DynamicControlTest() { var source = @" class Outer { void M1(dynamic? x) { if (x == null) return; string y; y = x; y = (string)x; y.ToString(); } void M2(dynamic? x) { if (x != null) return; string y; y = x; // 1 y = (string)x; // 2 y.ToString(); // 3 } void M3(dynamic? x) { if (x != null) { string y; y = x; y = (string)x; y.ToString(); } else { string y; y = x; // 4 y = (string)x; // 5 y.ToString(); // 6 } } void M4(dynamic? x) { if (x == null) { string y; y = x; // 7 y = (string)x; // 8 y.ToString(); // 9 } else { string y; y = x; y = (string)x; y.ToString(); } } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (16,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(16, 13), // (17,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = (string)x; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)x").WithLocation(17, 13), // (18,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(18, 9), // (32,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(32, 17), // (33,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = (string)x; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)x").WithLocation(33, 17), // (34,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(34, 13), // (42,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; // 7 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(42, 17), // (43,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = (string)x; // 8 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)x").WithLocation(43, 17), // (44,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(44, 13)); } [Fact] [WorkItem(30940, "https://github.com/dotnet/roslyn/issues/30940")] [WorkItem(30941, "https://github.com/dotnet/roslyn/issues/30941")] public void NullabilityOfTypeParameters_024() { var source = @" class Outer { void M<T>(Outer? x, Outer y) where T : Outer? { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'Outer' to 'T'. An explicit conversion exists (are you missing a cast?) // z = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("Outer", "T").WithLocation(7, 13), // (8,13): error CS0266: Cannot implicitly convert type 'Outer' to 'T'. An explicit conversion exists (are you missing a cast?) // z = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("Outer", "T").WithLocation(8, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9) ); } [Fact] [WorkItem(30940, "https://github.com/dotnet/roslyn/issues/30940")] public void NullabilityOfTypeParameters_025() { var source = @" class Outer { void M<T>(Outer? x) where T : Outer? { if (x == null) return; T y; y = x; y = (T)x; y.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,13): error CS0266: Cannot implicitly convert type 'Outer' to 'T'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("Outer", "T").WithLocation(8, 13) ); } [Fact] [WorkItem(30940, "https://github.com/dotnet/roslyn/issues/30940")] [WorkItem(30941, "https://github.com/dotnet/roslyn/issues/30941")] public void NullabilityOfTypeParameters_026() { var source = @" class Outer { void M<T>(Outer? x, Outer y) where T : Outer { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'Outer' to 'T'. An explicit conversion exists (are you missing a cast?) // z = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("Outer", "T").WithLocation(7, 13), // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // z = x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(7, 13), // (8,13): error CS0266: Cannot implicitly convert type 'Outer' to 'T'. An explicit conversion exists (are you missing a cast?) // z = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("Outer", "T").WithLocation(8, 13), // (9,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // z = (T)x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)x").WithLocation(9, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9) ); } [Fact] [WorkItem(30940, "https://github.com/dotnet/roslyn/issues/30940")] public void NullabilityOfTypeParameters_027() { var source = @" class Outer { void M<T>(Outer? x) where T : Outer { if (x == null) return; T y; y = x; y = (T)x; y.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,13): error CS0266: Cannot implicitly convert type 'Outer' to 'T'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("Outer", "T").WithLocation(8, 13) ); } [Fact] public void NullabilityOfTypeParameters_028() { var source = @" class Outer { void M0<T>(Outer x0, T y0) where T : Outer { x0 = y0; } void M1<T>(T y1) where T : Outer { Outer x1 = y1; x1 = y1; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_029() { var source = @" class Outer { void M0<T>(T x) { x = default; x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_030() { var source = @" class Outer { void M0<T>(T x) { x = default(T); x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_031() { var source = @" class Outer { void M0<T>(T x) where T : I1? { x = default; x.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_032() { var source = @" class Outer { void M0<T>(T x) where T : I1? { x = default(T); x.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_033() { var source = @" class Outer { void M0<T>(T x) where T : Outer { x = default; x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_034() { var source = @" class Outer { void M0<T>(T x) where T : Outer { x = default(T); x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(T)").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_035() { var source = @" class Outer { void M0<T>(T x) where T : I1 { x = default; x.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_036() { var source = @" class Outer { void M0<T>(T x) where T : I1 { x = default(T); x.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_037() { var source = @" class Outer { void M0<T>(T x) { x.ToString(); x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9) ); } [Fact] public void NullabilityOfTypeParameters_038() { var source = @" class Outer { void M0<T>(T x) where T : I1? { x.ToString(); x.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9) ); } [Fact] public void NullabilityOfTypeParameters_039() { var source = @" class Outer { void M0<T>(T x) where T : I1 { x.ToString(); x.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_040() { var source = @" class Outer { void M0<T>(T x) where T : Outer? { x.ToString(); x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9) ); } [Fact] public void NullabilityOfTypeParameters_041() { var source = @" class Outer { void M0<T>(T x) where T : Outer { x.ToString(); x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_042() { var source = @" class Outer { void M0<T>(T x) { M1(x); M1<T>(x); } void M1<T>(T x) where T : notnull {} } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8714: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M1(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(6, 9), // (7,9): warning CS8714: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M1<T>(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<T>").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_043() { var source = @" class Outer { void M0<T>(T x) { if (x == null) return; M1(x); M1<T>(x); } void M1<T>(T x) where T : notnull {} } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8714: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M1(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(7, 9), // (8,9): warning CS8714: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M1<T>(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<T>").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_044() { var source = @" class Outer { void M0<T>(T x) where T : class? { M1(x); M1<T>(x); } void M1<T>(T x) where T : class {} } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8634: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'class' constraint. // M1(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(6, 9), // (7,9): warning CS8634: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'class' constraint. // M1<T>(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<T>").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_045() { var source = @" class Outer { void M0<T>(T x) where T : class? { if (x == null) return; M1(x); M1<T>(x); } void M1<T>(T x) where T : class {} } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8634: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'class' constraint. // M1(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(7, 9), // (8,9): warning CS8634: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'class' constraint. // M1<T>(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<T>").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_046() { var source = @" class Outer { void M0<T>(T x) where T : class? { x = null; x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9)); } [Fact] public void NullabilityOfTypeParameters_047() { var source = @" class Outer { void M0<T>(T x) where T : class { x = null; x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_048() { var source = @" class Outer { void M0<T>(T x) where T : Outer? { x = null; x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9)); } [Fact] public void NullabilityOfTypeParameters_049() { var source = @" class Outer { void M0<T>(T x) where T : Outer { x = null; x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_050() { var source = @" class Outer { void M0<T>(T x) { M1(x, x).ToString(); } T M1<T>(T x, T y) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // M1(x, x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x, x)").WithLocation(6, 9) ); } [Fact] public void NullabilityOfTypeParameters_051() { var source = @" class Outer { void M0<T>(T x, T y) { if (x == null) return; M1(x, y).ToString(); } T M1<T>(T x, T y) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // M1(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x, y)").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_052() { var source = @" class Outer { void M0<T>(T x, T y) { if (y == null) return; M1(x, y).ToString(); } T M1<T>(T x, T y) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // M1(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x, y)").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_053() { var source = @" class Outer { void M0<T>(T x, T y) { if (x == null) return; if (y == null) return; M1(x, y).ToString(); M1<T>(x, y).ToString(); } T M1<T>(T x, T y) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M1(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x, y)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // M1<T>(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1<T>(x, y)").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_054() { var source = @" class Outer { void M0<T>(T x, object y) { M1(x, y).ToString(); } T M1<T>(T x, T y) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,12): warning CS8604: Possible null reference argument for parameter 'x' in 'object Outer.M1<object>(object x, object y)'. // M1(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "object Outer.M1<object>(object x, object y)").WithLocation(6, 12) ); } [Fact] public void NullabilityOfTypeParameters_055() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { M2(x0, y0) = z0; } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_056() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; M2(x0, y0) = z0; M2(x0, y0).ToString(); } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M2(x0, y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0, y0)").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_057() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (y0 == null) return; M2(x0, y0) = z0; } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_058() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; if (y0 == null) return; M2(x0, y0) = z0; M2<T>(x0, y0) = z0; M2(x0, y0).ToString(); } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M2(x0, y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0, y0)").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_059() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T, I1 { if (x0 == null) return; if (y0 == null) return; M2(x0, y0) = z0; } ref U M2<U>(U a, U b) => throw null!; } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_060() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : class, T { if (x0 == null) return; if (y0 == null) return; M2(x0, y0) = z0; } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_061() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; if (y0 == null) return; if (z0 == null) return; M2(x0, y0) = z0; } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_062() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { M2(out x0, out y0) = z0; } ref U M2<U>(out U a, out U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_063() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; M2(out M3(x0), out y0) = z0; M2(out M3<T>(x0), out y0); M2<T>(out M3(x0), out y0); M2<T>(out M3<T>(x0), out y0); M2(out M3(x0), out y0).ToString(); M2<T>(out M3(x0), out y0).ToString(); } ref U M2<U>(out U a, out U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // M2(out M3(x0), out y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(out M3(x0), out y0)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // M2<T>(out M3(x0), out y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2<T>(out M3(x0), out y0)").WithLocation(13, 9) ); } [Fact] public void NullabilityOfTypeParameters_064() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (y0 == null) return; M2(out x0, out M3(y0)) = z0; M2(out x0, out M3<T>(y0)); M2<T>(out x0, out M3(y0)); M2<T>(out x0, out M3<T>(y0)); M2(out x0, out M3(y0)).ToString(); // warn M2<T>(out x0, out M3(y0)).ToString(); // warn } ref U M2<U>(out U a, out U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // M2(out x0, out M3(y0)).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(out x0, out M3(y0))").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // M2<T>(out x0, out M3(y0)).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2<T>(out x0, out M3(y0))").WithLocation(13, 9) ); } [Fact] public void NullabilityOfTypeParameters_065() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; if (y0 == null) return; M2(out M3(x0), out M3(y0)) = z0; M2<T>(out M3(x0), out M3(y0)) = z0; M2(out M3<T>(x0), out M3(y0)) = z0; M2(out M3(x0), out M3<T>(y0)) = z0; M2(out M3(x0), out M3(y0)).ToString(); } ref U M2<U>(out U a, out U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // M2(out M3(x0), out M3(y0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(out M3(x0), out M3(y0))").WithLocation(12, 9) ); } [Fact] public void NullabilityOfTypeParameters_066() { var source = @" class Outer { void M0<T>(T x0, object? y0) { object? z0 = new object(); z0 = x0; M2(out y0, out M3(z0)).ToString(); } ref U M2<U>(out U a, out U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M2(out y0, out M3(z0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(out y0, out M3(z0))").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_067() { var source = @" class Outer { void M0<T>(T x0, object? y0) { object? z0 = new object(); z0 = x0; M2(y0, z0).ToString(); } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M2(y0, z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(y0, z0)").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_068() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T where T : class? { M2(M3(x0), M3(y0)) = z0; } ref U M2<U>(I1<U> a, I1<U> b) => throw null!; I1<U> M3<U>(U a) => throw null!; } interface I1<in T> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_069() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T where T : class? { if (x0 == null) return; M2(M3(x0), M3(y0)) = z0; M2<T>(M3<T>(x0), M3<T>(y0)) = z0; M2(M3(x0), M3(y0)).ToString(); } ref U M2<U>(I1<U> a, I1<U> b) => throw null!; I1<U> M3<U>(U a) => throw null!; } interface I1<in T> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M2(M3(x0), M3(y0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(M3(x0), M3(y0))").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_070() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T where T : class? { if (y0 == null) return; M2(M3(x0), M3(y0)) = z0; M2<T>(M3(x0), M3(y0)) = z0; M2(M3(x0), M3(y0)).ToString(); } ref U M2<U>(I1<U> a, I1<U> b) => throw null!; I1<U> M3<U>(U a) => throw null!; } interface I1<in T> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M2(M3(x0), M3(y0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(M3(x0), M3(y0))").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_071() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T where T : class? { if (x0 == null) return; if (y0 == null) return; M2(M3(x0), M3(y0)) = z0; M2<T>(M3(x0), M3(y0)) = z0; M2(M3<T>(x0), M3(y0)) = z0; M2(M3(x0), M3(y0)).ToString(); } ref U M2<U>(I1<U> a, I1<U> b) => throw null!; I1<U> M3<U>(U a) => throw null!; } interface I1<in T> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // M2(M3(x0), M3(y0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(M3(x0), M3(y0))").WithLocation(12, 9) ); } [Fact] public void NullabilityOfTypeParameters_072() { var source = @" class Outer { void M0<T>(T x0, I1<object?> y0) { object? z0 = new object(); z0 = x0; M2(y0, M3(z0)).ToString(); } ref U M2<U>(I1<U> a, I1<U> b) => throw null!; I1<U> M3<U>(U a) => throw null!; } interface I1<in T> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M2(y0, M3(z0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(y0, M3(z0))").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_073() { var source = @" class Outer { void M0<T>(object x0, T y0) { if (y0 == null) return; object? z0 = new object(); z0 = y0; M2(out x0, out M3(z0)).ToString(); } ref U M2<U>(out U a, out U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_074() { var source = @" class Outer { void M0<T>(object x0, T y0) { if (y0 == null) return; object? z0 = new object(); z0 = y0; M2(out M3(z0), out x0).ToString(); } ref U M2<U>(out U a, out U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_075() { var source = @" class Outer { void M0<T>() where T : new() { T x0; x0 = new T(); x0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_076() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { M2(ref x0, ref y0) = z0; } ref U M2<U>(ref U a, ref U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_077() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; M2(ref M3(x0), ref y0) = z0; M2<T>(ref M3(x0), ref y0); M2(ref M3(x0), ref y0).ToString(); } ref U M2<U>(ref U a, ref U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M2(ref M3(x0), ref y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(ref M3(x0), ref y0)").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_078() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (y0 == null) return; M2(ref x0, ref M3(y0)) = z0; M2<T>(ref x0, ref M3(y0)); M2(ref x0, ref M3(y0)).ToString(); } ref U M2<U>(ref U a, ref U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M2(ref x0, ref M3(y0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(ref x0, ref M3(y0))").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_079() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; if (y0 == null) return; M2(ref M3(x0), ref M3(y0)) = z0; M2<T>(ref M3(x0), ref M3(y0)) = z0; } ref U M2<U>(ref U a, ref U b) where U : notnull => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(ref U, ref U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2(ref M3(x0), ref M3(y0)) = z0; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2").WithArguments("Outer.M2<U>(ref U, ref U)", "U", "T").WithLocation(8, 9), // (9,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(ref U, ref U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2<T>(ref M3(x0), ref M3(y0)) = z0; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2<T>").WithArguments("Outer.M2<U>(ref U, ref U)", "U", "T").WithLocation(9, 9) ); } [Fact] [WorkItem(30946, "https://github.com/dotnet/roslyn/issues/30946")] public void NullabilityOfTypeParameters_080() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (x0 == null) return; M2(x0).M3(ref y0); M2<T>(x0).M3(ref y0); } Other<U> M2<U>(U a) where U : notnull => throw null!; } class Other<U> where U : notnull { public void M3(ref U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2(x0).M3(ref y0); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2").WithArguments("Outer.M2<U>(U)", "U", "T").WithLocation(7, 9), // (8,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2<T>(x0).M3(ref y0); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2<T>").WithArguments("Outer.M2<U>(U)", "U", "T").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_081() { var source = @" class Outer { void M0<T>(T x0) { M2(x0); } void M2(object a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,12): warning CS8604: Possible null reference argument for parameter 'a' in 'void Outer.M2(object a)'. // M2(x0); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x0").WithArguments("a", "void Outer.M2(object a)").WithLocation(6, 12) ); } [Fact] public void NullabilityOfTypeParameters_082() { var source = @" class Outer { void M0<T>(T x0) { M2(x0); } void M2(in object a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,12): warning CS8604: Possible null reference argument for parameter 'a' in 'void Outer.M2(in object a)'. // M2(x0); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x0").WithArguments("a", "void Outer.M2(in object a)").WithLocation(6, 12) ); } [Fact] public void NullabilityOfTypeParameters_083() { var source = @" class Outer { void M0<T>(T x0, I1<T> y0, I1<string?> z0) where T : class? { M3(M2(x0)); M3<I1<T>>(y0); M3<I1<string?>>(z0); } I1<U> M2<U>(U a) => throw null!; void M3<U>(U a) where U : I1<object> => throw null!; } interface I1<out U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U>(U)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<object>'. // M3(M2(x0)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3").WithArguments("Outer.M3<U>(U)", "I1<object>", "U", "I1<T>").WithLocation(6, 9), // (7,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U>(U)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<object>'. // M3<I1<T>>(y0); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<T>>").WithArguments("Outer.M3<U>(U)", "I1<object>", "U", "I1<T>").WithLocation(7, 9), // (8,9): warning CS8631: The type 'I1<string?>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U>(U)'. Nullability of type argument 'I1<string?>' doesn't match constraint type 'I1<object>'. // M3<I1<string?>>(z0); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<string?>>").WithArguments("Outer.M3<U>(U)", "I1<object>", "U", "I1<string?>").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_084() { var source = @" class Outer { void M0<T, U>(T x0, I1<T> y0, I1<object> z0, U? a0) where T : class? where U : class, T { M3(M2(x0), a0); if (x0 == null) return; M3(M2(x0), a0); M3<I1<T>, U>(y0, null); M3<I1<object>, string>(z0, null); } I1<U> M2<U>(U a) => throw null!; void M3<U, W>(U a, W? b) where U : I1<W?> where W : class => throw null!; } interface I1<in U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U, W>(U, W?)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<U?>'. // M3(M2(x0), a0); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3").WithArguments("Outer.M3<U, W>(U, W?)", "I1<U?>", "U", "I1<T>").WithLocation(6, 9), // (9,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U, W>(U, W?)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<U?>'. // M3(M2(x0), a0); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3").WithArguments("Outer.M3<U, W>(U, W?)", "I1<U?>", "U", "I1<T>").WithLocation(9, 9), // (11,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U, W>(U, W?)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<U?>'. // M3<I1<T>, U>(y0, null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<T>, U>").WithArguments("Outer.M3<U, W>(U, W?)", "I1<U?>", "U", "I1<T>").WithLocation(11, 9), // (12,9): warning CS8631: The type 'I1<object>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U, W>(U, W?)'. Nullability of type argument 'I1<object>' doesn't match constraint type 'I1<string?>'. // M3<I1<object>, string>(z0, null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<object>, string>").WithArguments("Outer.M3<U, W>(U, W?)", "I1<string?>", "U", "I1<object>").WithLocation(12, 9) ); } [Fact] public void NullabilityOfTypeParameters_085() { var source = @" class Outer { void M0<T>(T x0, I1<T> y0, I1<object> z0, T a0) { if (x0 == null) return; M3(M2(x0), a0); M3(M2(a0), x0); M3<I1<object>, object?>(z0, null); } I1<U> M2<U>(U a) => throw null!; void M3<U, W>(U a, W b) where U : I1<W> => throw null!; } interface I1<U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8631: The type 'I1<object>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U, W>(U, W)'. Nullability of type argument 'I1<object>' doesn't match constraint type 'I1<object?>'. // M3<I1<object>, object?>(z0, null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<object>, object?>").WithArguments("Outer.M3<U, W>(U, W)", "I1<object?>", "U", "I1<object>").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_086() { var source = @" class Outer { void M0<T>(T x0, I1<string> z0) where T : class? { if (x0 == null) return; M3(M2(x0)); M3(M2<T>(x0)); M3<I1<T>>(M2(x0)); M3<I1<string>>(z0); } I1<U> M2<U>(U a) => throw null!; void M3<U>(U a) where U : I1<object> => throw null!; } interface I1<out U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U>(U)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<object>'. // M3(M2(x0)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3").WithArguments("Outer.M3<U>(U)", "I1<object>", "U", "I1<T>").WithLocation(7, 9), // (8,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U>(U)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<object>'. // M3(M2<T>(x0)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3").WithArguments("Outer.M3<U>(U)", "I1<object>", "U", "I1<T>").WithLocation(8, 9), // (9,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U>(U)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<object>'. // M3<I1<T>>(M2(x0)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<T>>").WithArguments("Outer.M3<U>(U)", "I1<object>", "U", "I1<T>").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_087() { var source = @" class Outer { void M0<T, U>(T x0, I1<T> y0, I1<object> z0, U? a0) where T : class? where U : class, T { M3(M2(x0), a0); if (x0 == null) return; M3(M2(x0), a0); M3<I1<T>, U>(y0, null); M3<I1<object>, string>(z0, null); } I1<U> M2<U>(U a) => throw null!; void M3<U, W>(U a, W? b) where U : I1<W> where W : class => throw null!; } interface I1<in U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_088() { var source = @" class Outer { void M0<T, U>(T x0, I1<T> y0, I1<object> z0, U a0) where T : class? where U : class?, T { M3(M2(x0), a0); if (x0 == null) return; M3(M2(x0), a0); // 1 M3<I1<T>, U>(y0, a0); M3<I1<object>, string?>(z0, null); } I1<U> M2<U>(U a) => throw null!; void M3<U, W>(U a, W b) where U : I1<W> => throw null!; } interface I1<in U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,9): warning CS8631: The type 'I1<object>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U, W>(U, W)'. Nullability of type argument 'I1<object>' doesn't match constraint type 'I1<string?>'. // M3<I1<object>, string?>(z0, null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<object>, string?>").WithArguments("Outer.M3<U, W>(U, W)", "I1<string?>", "U", "I1<object>").WithLocation(12, 9) ); } [Fact] public void NullabilityOfTypeParameters_089() { var source = @" class Outer { void M0<T>(T x0, I1<T> y0, I1<object> z0, T a0) { if (x0 == null) return; if (a0 == null) return; M3(M2(x0), a0); M3(M2(a0), x0); M3<I1<object>, object>(z0, new object()); } I1<U> M2<U>(U a) => throw null!; void M3<U, W>(U a, W b) where U : I1<W> => throw null!; } interface I1<U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_090() { var source = @" class Outer { void M0<T>(T x0, I1<T> y0, I1<object> z0, T a0) { M3(M2(x0), a0); M3<I1<T>,T>(y0, a0); } I1<U> M2<U>(U a) => throw null!; void M3<U, W>(U a, W b) where U : I1<W> => throw null!; } interface I1<U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_091() { var source = @" class Outer { void M0<T>(T x0) where T : I1? { x0?.ToString(); x0?.M1(x0); x0.ToString(); } } interface I1 { void M1(object x); } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_092() { var source = @" class Outer { void M0<T>(T x0) { if (x0 is null) return; x0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_093() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (y0 == null) return; T z0 = x0 ?? y0; M1(z0) = x0; M1(z0).ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_094() { var source = @" class Outer { void M0<T>(T x0, T y0) { (x0 ?? y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (x0 ?? y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0 ?? y0").WithLocation(6, 10) ); } [Fact] [WorkItem(30952, "https://github.com/dotnet/roslyn/issues/30952")] public void NullabilityOfTypeParameters_095() { var source = @" class Outer { void M0<T>(object? x0, T z0) { if (x0 is T y0) { M2(y0) = z0; x0.ToString(); y0.ToString(); } } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(30952, "https://github.com/dotnet/roslyn/issues/30952")] public void NullabilityOfTypeParameters_096() { var source = @" class Outer { void M0<T>(T x0, object? z0) { if (x0 is object y0) { M2(y0) = z0; x0.ToString(); y0.ToString(); } } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,22): warning CS8601: Possible null reference assignment. // M2(y0) = z0; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "z0").WithLocation(8, 22) ); } [Fact] public void NullabilityOfTypeParameters_097() { var source = @" class Outer { void M0<T>(T x0, T z0) { if (x0 is var y0) { M2(y0) = z0; x0.ToString(); y0.ToString(); } } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(9, 13), // (10,13): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(10, 13) ); } [Fact] public void NullabilityOfTypeParameters_098() { var source = @" class Outer { void M0<T>(T x0) { if (x0 is default) return; x0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (x0 is default) return; Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(6, 19), // (7,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_099() { var source = @" class Outer { void M0<T>(T x0) { if (x0 is default(T)) return; x0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,19): error CS0150: A constant value is expected // if (x0 is default(T)) return; Diagnostic(ErrorCode.ERR_ConstantExpected, "default(T)").WithLocation(6, 19), // (7,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_100() { var source = @" class Outer { void M0<T>(T x0, T y0) where T : class? { if (x0 is null) return; M2(x0) = y0; M2(x0).ToString(); x0.ToString(); } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // M2(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0)").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_101() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (y0 == null) return; (x0 ?? y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_102() { var source = @" class Outer { void M0<T>(T x0, T y0) where T : class? { if (x0 == null) return; M2(x0) = y0; M2(x0).ToString(); x0.ToString(); } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // M2(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0)").WithLocation(9, 9) ); } [Fact] [WorkItem(30952, "https://github.com/dotnet/roslyn/issues/30952")] public void NullabilityOfTypeParameters_103() { var source = @" class Outer { void M0<T>(T x0, T z0) { if (x0 is T y0) { M2(x0) = z0; M2(y0) = z0; M2(x0).ToString(); M2(y0).ToString(); x0.ToString(); y0.ToString(); } } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // M2(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0)").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // M2(y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(y0)").WithLocation(11, 13) ); } [Fact] public void NullabilityOfTypeParameters_104() { var source = @" class Outer<T> { void M0(bool b, T x0) { T y0; if (b) { y0 = M2(); } else { y0 = x0; } y0.ToString(); } #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (17,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(17, 9) ); } [Fact] public void NullabilityOfTypeParameters_105() { var source = @" class Outer<T> { void M0(bool b, T x0) { T y0; if (b) { y0 = x0; } else { y0 = M2(); } y0.ToString(); } #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (17,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(17, 9) ); } [Fact] public void NullabilityOfTypeParameters_106() { var source = @" class Outer<T> { void M0(bool b, T x0) { T y0; if (b || x0 == null) { y0 = M3(); } else { y0 = x0; } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_107() { var source = @" class Outer<T> { void M0(bool b, T x0) { T y0; if (b && x0 != null) { y0 = x0; } else { y0 = M3(); } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_108() { var source = @" class Outer<T> { void M0(T x0) { x0!.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_109() { var source = @" class Outer { void M0<T>(T x0) where T : I1<T?> { x0 = default; } void M1<T>(T x1) where T : I1<T> { x1 = default; } } interface I1<T> {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (4,35): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void M0<T>(T x0) where T : I1<T?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 35) ); } [Fact] public void NullabilityOfTypeParameters_110() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (x0 == null) return; T z0 = x0 ?? y0; M1(z0).ToString(); M1(z0) = y0; z0.ToString(); z0?.ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(10, 9)); } [Fact] public void NullabilityOfTypeParameters_111() { var source = @" class Outer { void M0<T>(T x0, T y0, T a0) { if (x0 == null) return; if (y0 == null) return; T z0 = x0 ?? y0; M1(z0) = a0; z0?.ToString(); M1(z0).ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_112() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (x0 == null) return; var z0 = x0; z0 = y0; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_113() { var source = @" class Outer { void M0<T>(T x0, T y0, T u0, T v0) { var a0 = new[] {x0, y0}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; M2(v0).ToString(); } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M2(v0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(v0)").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_114() { var source = @" class Outer { void M0<T>(T x0, T y0, T u0, T v0) { if (x0 == null) return; var a0 = new[] {x0, y0}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; M2<T>(v0) = a0[1]; M2(v0).ToString(); } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // M2(v0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(v0)").WithLocation(13, 9) ); } [Fact] public void NullabilityOfTypeParameters_115() { var source = @" class Outer { void M0<T>(T x0, T y0, T u0, T v0) { if (y0 == null) return; var a0 = new[] {x0, y0}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; M2<T>(v0) = a0[1]; M2(v0).ToString(); } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // M2(v0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(v0)").WithLocation(13, 9) ); } [Fact] public void NullabilityOfTypeParameters_116() { var source = @" class Outer { void M0<T>(T x0, T y0, T u0, T v0) { if (x0 == null) return; if (y0 == null) return; var a0 = new[] {x0, y0}; a0[0] = u0; a0[0].ToString(); if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // a0[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a0[0]").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_117() { var source = @" class Outer<T> { void M0(T x0, T u0, T v0) { var a0 = new[] {x0, M3()}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_118() { var source = @" class Outer<T> { void M0(T x0, T u0, T v0) { var a0 = new[] {M3(), x0}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_119() { var source = @" class Outer<T> { void M0(T x0, T u0, T v0) { if (x0 == null) return; var a0 = new[] {x0, M3()}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_120() { var source = @" class Outer<T> { void M0(T x0, T u0, T v0) { if (x0 == null) return; var a0 = new[] {M3(), x0}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_121() { var source = @" class Outer<T> { void M0(T u0, T v0) { var a0 = new[] {M3(), M3()}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_122() { var source = @" class Outer<T> { void M0(bool b, T x0) { T y0; if (b) { y0 = M3(); } else { y0 = M3(); } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_123() { var source = @" class Outer<T> { void M0(bool b, T x0, T a0, T b0) { if (a0 == null) return; if (b0 == null) return; T y0; if (b) { y0 = a0; } else { y0 = b0; } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_124() { var source = @" class Outer<T> { void M0(bool b, T x0, T a0, T b0) { T y0; if (b) { y0 = a0; } else { y0 = b0; } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(18, 9) ); } [Fact] public void NullabilityOfTypeParameters_125() { var source = @" class Outer<T> { void M0(bool b, T x0, T a0, T b0) { if (a0 == null) return; T y0; if (b) { y0 = a0; } else { y0 = b0; } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (20,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(20, 9) ); } [Fact] public void NullabilityOfTypeParameters_126() { var source = @" class Outer<T> { void M0(bool b, T x0, T a0, T b0) { if (b0 == null) return; T y0; if (b) { y0 = a0; } else { y0 = b0; } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (20,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(20, 9) ); } [Fact] public void NullabilityOfTypeParameters_127() { var source = @" class C<T> { public C<object> X = null!; public C<object?> Y = null!; void F(object? y0) { if (y0 == null) return; object? x0; x0 = null; _ = new C<int>() { Y = M(x0), X = M(y0) }; } ref C<S> M<S>(S x) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_128() { var source = @" class C<T> { void F(object? y0) { if (y0 == null) return; object? x0; x0 = null; M2( out M1(x0), out M1(y0) ); } ref C<S> M1<S>(S x) => throw null!; void M2(out C<object?> x, out C<object> y) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_129() { var source = @" class C<T> { void F(object? y0) { if (y0 == null) return; object? x0; x0 = null; M2( ref M1(x0), ref M1(y0) ); } ref C<S> M1<S>(S x) => throw null!; void M2(ref C<object?> x, ref C<object> y) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_130() { var source = @" class C<T> { void F(object? y0) { if (y0 == null) return; object? x0; x0 = null; M2(M1(x0), M1(y0)) = (C<object?> a, C<object> b) => throw null!; } C<S> M1<S>(S x) => throw null!; ref System.Action<U, V> M2<U, V>(U x, V y) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_131() { var source = @" class C<T> where T : class? { void F(T y0) { if (y0 == null) return; T x0; x0 = null; M2(M1(x0), M1(y0)) = (C<T> a, C<T> b) => throw null!; } C<S> M1<S>(S x) where S : class? => throw null!; ref System.Action<U, V> M2<U, V>(U x, V y) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,13): warning CS8622: Nullability of reference types in type of parameter 'a' of 'lambda expression' doesn't match the target delegate 'Action<C<T?>, C<T>>'. // (C<T> a, C<T> b) => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(C<T> a, C<T> b) => throw null!").WithArguments("a", "lambda expression", "System.Action<C<T?>, C<T>>").WithLocation(11, 13)); } [Fact] public void NullabilityOfTypeParameters_132() { var source = @" class C<T> where T : class? { void F(T x0, T y0) { M2(M1(x0), M1(y0)) = (C<T> a, C<T> b) => throw null!; } C<S> M1<S>(S x) where S : class? => throw null!; ref System.Action<U, V> M2<U, V>(U x, V y) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_133() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; T z0 = M2() ?? y0; M1(z0) = x0; M1<T>(z0) = x0; M1(z0).ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_134() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; T z0 = y0 ?? M2(); M1(z0) = x0; M1<T>(z0) = x0; M1(z0).ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_135() { var source = @" class Outer<T> { void M0(T x0) { T z0 = M2() ?? M2(); M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_136() { var source = @" class Outer<T> { void M0(T x0, T y0) { T z0 = M2() ?? y0; M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9)); } [Fact] public void NullabilityOfTypeParameters_137() { var source = @" class Outer<T> { void M0(T x0, T y0) { T z0 = y0 ?? M2(); M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_138() { var source = @" class C<T> where T : class? { void F(T x0, T y0) { T z0 = x0 ?? y0; M2(M1(z0)) = (C<T> a) => throw null!; } C<S> M1<S>(S x) where S : class? => throw null!; ref System.Action<U> M2<U>(U x) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_139() { var source = @" class C<T> where T : class? { void F(T x0, T y0) { T z0 = x0 ?? y0; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_140() { var source = @" class C<T> where T : class? { void F(T x0, T y0) { T z0 = new [] {x0, y0}[0]; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_141() { var source = @" struct C<T> where T : class? { void F(T x0, object? y0) { F1 = x0; F2 = y0; x0 = F1; y0 = F2; } #nullable disable T F1; object F2; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_142() { var source = @" class Outer { void M0<T>(bool b, T x0, T y0) { (b ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (b ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x0 : y0").WithLocation(6, 10) ); } [Fact] public void NullabilityOfTypeParameters_143() { var source = @" class Outer { void M0<T>(bool b, T x0, T y0) { if (y0 == null) return; (b ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,10): warning CS8602: Dereference of a possibly null reference. // (b ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x0 : y0").WithLocation(7, 10) ); } [Fact] public void NullabilityOfTypeParameters_144() { var source = @" class Outer { void M0<T>(bool b, T x0, T y0) { if (x0 == null) return; (b ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,10): warning CS8602: Dereference of a possibly null reference. // (b ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x0 : y0").WithLocation(7, 10) ); } [Fact] public void NullabilityOfTypeParameters_145() { var source = @" class Outer { void M0<T>(bool b, T x0, T y0, T a0) { if (x0 == null) return; if (y0 == null) return; T z0 = b ? x0 : y0; M1(z0) = a0; z0?.ToString(); M1(z0).ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(11, 9) ); } [Fact, WorkItem(33924, "https://github.com/dotnet/roslyn/issues/33924")] public void NullabilityOfTypeParameters_146() { var source = @" class Outer<T> { void M0(bool b, T x0, T y0) { if (y0 == null) return; T z0 = b ? M2() : y0; M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact, WorkItem(33924, "https://github.com/dotnet/roslyn/issues/33924")] public void NullabilityOfTypeParameters_147() { var source = @" class Outer<T> { void M0(bool b, T x0, T y0) { if (y0 == null) return; T z0 = b ? y0 : M2(); M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact, WorkItem(33924, "https://github.com/dotnet/roslyn/issues/33924")] public void NullabilityOfTypeParameters_148() { var source = @" class Outer<T> { void M0(bool b, T x0) { T z0 = b ? M2() : M2(); M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_149() { var source = @" class Outer<T> { void M0(bool b, T x0, T y0) { T z0 = b ? M2() : y0; M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_150() { var source = @" class Outer<T> { void M0(bool b, T x0, T y0) { T z0 = b ? y0 : M2(); M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_151() { var source = @" class C<T> where T : class? { void F(bool b, T x0, T y0) { T z0 = b ? x0 : y0; M2(M1(z0)) = (C<T> a) => throw null!; } C<S> M1<S>(S x) where S : class? => throw null!; ref System.Action<U> M2<U>(U x) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_153() { var source = @" class Outer { void M0<T>(T x0, T y0) { (true ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (true ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "true ? x0 : y0").WithLocation(6, 10) ); } [Fact] public void NullabilityOfTypeParameters_154() { var source = @" class Outer { void M0<T>(bool b, T x0, T y0) { if (y0 == null) return; (true ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,10): warning CS8602: Dereference of a possibly null reference. // (true ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "true ? x0 : y0").WithLocation(7, 10) ); } [Fact, WorkItem(33924, "https://github.com/dotnet/roslyn/issues/33924")] public void NullabilityOfTypeParameters_155() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (x0 == null) return; (true ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_156() { var source = @" class Outer { void M0<T>(T x0, T y0, T a0) { if (x0 == null) return; if (y0 == null) return; T z0 = true ? x0 : y0; M1(z0) = a0; M1(z0).ToString(); z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(12, 9)); } [Fact] public void NullabilityOfTypeParameters_157() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; T z0 = true ? M2() : y0; M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(10, 9)); } [Fact] public void NullabilityOfTypeParameters_158() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; T z0 = true ? y0 : M2(); M1(z0) = x0; M1(z0).ToString(); z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9)); } [Fact] public void NullabilityOfTypeParameters_159() { var source = @" class Outer<T> { void M0(T x0) { T z0 = true ? M2() : M2(); M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_160() { var source = @" class Outer<T> { void M0(T x0, T y0) { T z0 = true ? M2() : y0; M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_161() { var source = @" class Outer<T> { void M0(T x0, T y0) { T z0 = true ? y0 : M2(); M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_162() { var source = @" class Outer { void M0<T>(T x0, T y0) { (false ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (false ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "false ? x0 : y0").WithLocation(6, 10) ); } [Fact, WorkItem(33924, "https://github.com/dotnet/roslyn/issues/33924")] public void NullabilityOfTypeParameters_163() { var source = @" class Outer { void M0<T>(bool b, T x0, T y0) { if (y0 == null) return; (false ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_164() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (x0 == null) return; (false ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,10): warning CS8602: Dereference of a possibly null reference. // (false ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "false ? x0 : y0").WithLocation(7, 10) ); } [Fact] public void NullabilityOfTypeParameters_165() { var source = @" class Outer { void M0<T>(T x0, T y0, T a0) { if (x0 == null) return; if (y0 == null) return; T z0 = false ? x0 : y0; M1(z0) = a0; M1(z0).ToString(); z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(12, 9)); } [Fact] public void NullabilityOfTypeParameters_166() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; T z0 = false ? M2() : y0; M1(z0) = x0; M1(z0).ToString(); z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9)); } [Fact] public void NullabilityOfTypeParameters_167() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; T z0 = false ? y0 : M2(); M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(10, 9)); } [Fact] public void NullabilityOfTypeParameters_168() { var source = @" class Outer<T> { void M0(T x0) { T z0 = false ? M2() : M2(); M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_169() { var source = @" class Outer<T> { void M0(T x0, T y0) { T z0 = false ? M2() : y0; M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_170() { var source = @" class Outer<T> { void M0(T x0, T y0) { T z0 = false ? y0 : M2(); M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_171() { var source = @" class Outer<T, U> where T : Outer<T, U>? where U : T { void M0(T x0) { U y0 = (U)x0; U z0 = y0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_172() { var source = @" class Outer<T, U> where T : class? where U : T { void M0(T x0) { U y0 = (U)x0; U z0 = y0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9)); } [Fact] public void NullableClassConditionalAccess() { var source = @" class Program<T> where T : Program<T>? { T field = default!; static void M(T t) { T t1 = t?.field; // 1 T? t2 = t?.field; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t1 = t?.field; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t?.field").WithLocation(8, 16) ); } [Fact] public void NullabilityOfTypeParameters_173() { var source = @" class Outer<T, U> where T : Outer<T, U>?, U { void M0(T x0) { T? z0 = x0?.M1(); U? y0 = z0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_174() { var source = @" class Outer<T, U> where T : Outer<T, U>? where U : T { void M0(T x0) { T? z0 = x0?.M1(); U? y0 = (U?)z0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_175() { var source = @" class Outer<T, U> where T : Outer<T, U>?, U { void M0(T x0) { if (x0 == null) return; T? z0 = x0?.M1(); U? y0 = z0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(12, 9) ); } [Fact] public void NullabilityOfTypeParameters_176() { var source = @" class Outer<T, U> where T : Outer<T, U>?, U { void M0(Outer<T, U>? x0) { T? z0 = x0?.M1(); U? y0 = z0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_177() { var source = @" class Outer<T, U> where T : Outer<T, U>?, U { void M0(Outer<T, U> x0) { T? z0 = x0?.M1(); U? y0 = z0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_178() { var source = @" class Outer<T> where T : Outer<T>? { void M0(T x0) { Outer<T> z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } Outer<T> M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> z0 = x0?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0?.M1()").WithLocation(6, 23), // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_179() { var source = @" class Outer<T> where T : Outer<T>? { void M0(T x0) { if (x0 == null) return; Outer<T> z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } Outer<T> M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> z0 = x0?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0?.M1()").WithLocation(7, 23), // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_180() { var source = @" class Outer<T> where T : Outer<T>? { void M0(T x0) { Outer<T> z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } Outer<T>? M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> z0 = x0?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0?.M1()").WithLocation(6, 23), // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_181() { var source = @" class Outer<T> where T : Outer<T>? { void M0(T x0) { if (x0 == null) return; Outer<T> z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } Outer<T>? M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> z0 = x0?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0?.M1()").WithLocation(7, 23), // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_182() { var source = @" class Outer<T, U> where T : Outer<T, U>?, U where U : class? { void M0(T x0) { U? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } U M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_183() { var source = @" class Outer<T, U> where T : Outer<T, U>?, U where U : class? { void M0(T x0) { if (x0 == null) return; U? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } U M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_184() { var source = @" class Outer<T, U> where T : U where U : Outer<T, U>? { void M0(U x0) { U? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_185() { var source = @" class Outer<T, U> where T : U where U : Outer<T, U>? { void M0(U x0) { T? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_186() { var source = @" class Outer<T, U> where T : U where U : Outer<T, U>? { void M0(U x0) { if (x0 == null) return; U? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_187() { var source = @" class Outer<T, U> where T : U where U : Outer<T, U>? { void M0(U x0) { if (x0 == null) return; T? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_188() { var source = @" class Outer<T, U> where T : Outer<T, U>? where U : class? { void M0(T x0) { U? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } U M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_189() { var source = @" class Outer<T, U> where T : Outer<T, U>? where U : class? { void M0(T x0) { if (x0 == null) return; U? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } U M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_190() { var source = @" class Outer<T, U> where T : Outer<T, U>? where U : class { void M0(T x0) { U z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } U M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // U z0 = x0?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0?.M1()").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_191() { var source = @" class Outer<T, U> where T : Outer<T, U>? where U : class { void M0(T x0) { if (x0 == null) return; U z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } U M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // U z0 = x0?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0?.M1()").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_192() { var source = @" class Outer<T> { void M0(T x0) { object y0 = x0 as object; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y0 = x0 as object; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as object").WithLocation(6, 21), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_193() { var source = @" class Outer<T> { void M0(T x0) { if (x0 == null) return; object y0 = x0 as object; y0?.ToString(); y0.ToString(); // 1 } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_194() { var source = @" class Outer<T> { void M0(T x0) { dynamic y0 = x0 as dynamic; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // dynamic y0 = x0 as dynamic; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as dynamic").WithLocation(6, 22), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_195() { var source = @" class Outer<T> { void M0(T x0) { if (x0 == null) return; dynamic y0 = x0 as dynamic; y0?.ToString(); y0.ToString(); // 1 } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_196() { var source = @" class Outer<T> where T : class? { void M0(object x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_197() { var source = @" class Outer<T> where T : class? { void M0(object? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_198() { var source = @" class Outer<T> where T : class? { void M0(object? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_199() { var source = @" class Outer<T> where T : class? { void M0(dynamic x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_200() { var source = @" class Outer<T> where T : class? { void M0(dynamic? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_201() { var source = @" class Outer<T> where T : class? { void M0(dynamic? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_202() { var source = @" class Outer<T> where T : notnull { void M0(T x0) { object y0 = x0 as object; y0?.ToString(); y0.ToString(); // 1 } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_203() { var source = @" class Outer<T> where T : notnull { void M0(T x0) { dynamic y0 = x0 as dynamic; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_204() { var source = @" class Outer<T> where T : class { void M0(object x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_205() { var source = @" class Outer<T> where T : class { void M0(object? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_206() { var source = @" class Outer<T> where T : class { void M0(object? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_207() { var source = @" class Outer<T> where T : class { void M0(dynamic x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_208() { var source = @" class Outer<T> where T : class { void M0(dynamic? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_209() { var source = @" class Outer<T> where T : class { void M0(dynamic? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_210() { var source = @" class Outer<T> { void M0(T x0) { Outer<T> y0 = x0 as Outer<T>; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> y0 = x0 as Outer<T>; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as Outer<T>").WithLocation(6, 23), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_211() { var source = @" class Outer<T> { void M0(T x0) { if (x0 == null) return; Outer<T> y0 = x0 as Outer<T>; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> y0 = x0 as Outer<T>; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as Outer<T>").WithLocation(7, 23), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_212() { var source = @" class Outer<T> where T : class? { void M0(Outer<T>? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_213() { var source = @" class Outer<T> where T : class? { void M0(Outer<T>? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_214() { var source = @" class Outer<T> where T : class? { void M0(Outer<T> x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_215() { var source = @" class Outer<T> where T : class { void M0(T x0) { Outer<T> y0 = x0 as Outer<T>; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> y0 = x0 as Outer<T>; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as Outer<T>").WithLocation(6, 23), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_216() { var source = @" class Outer<T> where T : class { void M0(Outer<T>? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_217() { var source = @" class Outer<T> where T : class { void M0(Outer<T>? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_218() { var source = @" class Outer<T> where T : class { void M0(Outer<T> x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_219() { var source = @" class Outer<T> where T : Outer<T>? { void M0(T x0) { Outer<T> y0 = x0 as Outer<T>; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> y0 = x0 as Outer<T>; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as Outer<T>").WithLocation(6, 23), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_220() { var source = @" class Outer<T> where T : Outer<T>? { void M0(T x0) { if (x0 == null) return; Outer<T> y0 = x0 as Outer<T>; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_221() { var source = @" class Outer<T> where T : Outer<T>? { void M0(Outer<T> x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_222() { var source = @" class Outer<T> where T : Outer<T> { void M0(T x0) { Outer<T> y0 = x0 as Outer<T>; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_223() { var source = @" class Outer<T> where T : Outer<T> { void M0(Outer<T>? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_224() { var source = @" class Outer<T> where T : Outer<T> { void M0(Outer<T>? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_225() { var source = @" class Outer<T> where T : Outer<T> { void M0(Outer<T> x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_226() { var source = @" class Outer<T> where T : I1? { void M0(T x0) { I1 y0 = x0 as I1; y0?.ToString(); y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // I1 y0 = x0 as I1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as I1").WithLocation(6, 17), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_227() { var source = @" class Outer<T> where T : I1? { void M0(T x0) { if (x0 == null) return; I1 y0 = x0 as I1; y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_228() { var source = @" class Outer<T> where T : class?, I1? { void M0(I1 x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_229() { var source = @" class Outer<T> where T : I1 { void M0(T x0) { I1 y0 = x0 as I1; y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_230() { var source = @" class Outer<T> where T : class?, I1 { void M0(I1? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_231() { var source = @" class Outer<T> where T : class?, I1 { void M0(I1? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_232() { var source = @" class Outer<T> where T : class?, I1 { void M0(I1 x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_233() { var source = @" class Outer<T> where T : class? { void M0(T x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_234() { var source = @" class Outer<T> where T : class? { void M0(T x0) { if (x0 == null) return; T y0 = x0 as T; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_235() { var source = @" class Outer<T> where T : class { void M0(T x0) { T y0 = x0 as T; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_237() { var source = @" class Outer<T, U> where T : U where U : class? { void M0(T x0) { U y0 = x0 as U; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_238() { var source = @" class Outer<T, U> where T : U where U : class? { void M0(T x0) { if (x0 == null) return; U y0 = x0 as U; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_239() { var source = @" class Outer<T, U> where T : U where U : class { void M0(T x0) { U y0 = x0 as U; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_240() { var source = @" class Outer<T, U> where T : class, U where U : class? { void M0(T x0) { U y0 = x0 as U; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_241() { var source = @" class Outer<T, U> where T : class?, U where U : class? { void M0(T x0) { U y0 = x0 as U; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_242() { var source = @" class Outer<T, U> where T : class?, U where U : class? { void M0(T x0) { if (x0 == null) return; U y0 = x0 as U; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_243() { var source = @" class Outer<T, U> where T : class?, U where U : class { void M0(T x0) { U y0 = x0 as U; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_244() { var source = @" class Outer<T, U> where T : class, U where U : class? { void M0(U x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_245() { var source = @" class Outer<T, U> where T : class, U where U : class? { void M0(U x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_246() { var source = @" class Outer<T, U> where T : class, U where U : class { void M0(U x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_248() { var source = @" class Outer<T, U> where T : class?, U where U : class? { void M0(U x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_249() { var source = @" class Outer<T, U> where T : class?, U where U : class? { void M0(U x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_250() { var source = @" class Outer<T, U> where T : class?, U where U : class { void M0(U x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_251() { var source = @" class Outer<T, U> where T : class?, U { void M0(U x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_252() { var source = @" class Outer<T, U> where T : class?, U { void M0(U x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_253() { var source = @" class Outer<T, U> where T : class, U { void M0(U x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_254() { var source = @" class Outer<T, U> where T : class, U { void M0(U x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_255() { var source = @" class Outer { void M0<T>(T x0, T y0, T z0) { if (y0 == null) return; z0 ??= y0; M1(z0) = x0; M1(z0).ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(10, 9)); } [Fact] public void NullabilityOfTypeParameters_256() { var source = @" class Outer { void M0<T>(T x0, T y0) { (x0 ??= y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (x0 ??= y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0 ??= y0").WithLocation(6, 10)); } [Fact] public void NullabilityOfTypeParameters_257() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (y0 == null) return; (x0 ??= y0)?.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_258() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (x0 == null) return; x0 ??= y0; M1(x0).ToString(); M1(x0) = y0; x0?.ToString(); x0.ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M1(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x0)").WithLocation(8, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(11, 9)); } [Fact] public void NullabilityOfTypeParameters_259() { var source = @" class Outer { void M0<T>(T x0, T y0, T a0) { if (x0 == null) return; if (y0 == null) return; x0 ??= y0; M1(x0) = a0; x0?.ToString(); M1(x0).ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M1(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x0)").WithLocation(11, 9)); } [Fact] public void NullabilityOfTypeParameters_260() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; y0 ??= M2(); M1(y0) = x0; M1<T>(y0) = x0; M1(y0).ToString(); y0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M1(y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(y0)").WithLocation(11, 9)); } [Fact] public void NullabilityOfTypeParameters_261() { var source = @" class Outer<T> { void M0(T x0, T y0) { y0 ??= M2(); M1(y0) = x0; y0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_262() { var source = @" class Outer<T1, T2> where T1 : class, T2 { void M0(T1 t1, T2 t2) { t1 ??= t2 as T1; M1(t1) ??= t2 as T1; } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // t1 ??= t2 as T1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t2 as T1").WithLocation(6, 16)); } [Fact] [WorkItem(33295, "https://github.com/dotnet/roslyn/issues/33295")] public void NullabilityOfTypeParameters_263() { var source = @" #nullable enable class C<T> { public T FieldWithInferredAnnotation; } class C { static void Main() { Test(null); } static void Test(string? s) { s = """"; hello: var c = GetC(s); c.FieldWithInferredAnnotation.ToString(); s = null; goto hello; } public static C<T> GetC<T>(T t) => new C<T> { FieldWithInferredAnnotation = t }; public static T GetT<T>(T t) => t; }"; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (5,12): warning CS8618: Non-nullable field 'FieldWithInferredAnnotation' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public T FieldWithInferredAnnotation; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "FieldWithInferredAnnotation").WithArguments("field", "FieldWithInferredAnnotation").WithLocation(5, 12), // (19,5): warning CS8602: Dereference of a possibly null reference. // c.FieldWithInferredAnnotation.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.FieldWithInferredAnnotation").WithLocation(19, 5)); } [Fact] public void UpdateFieldFromReceiverType() { var source = @"class A<T> { } class B<T> { internal T F = default!; } class Program { internal static B<T> Create<T>(T t) => throw null!; static void M1(object x, object? y) { var b1 = Create(x); b1.F = x; b1.F = y; // 1 } static void M2(A<object?> x, A<object> y, A<object?> z) { var b2 = Create(x); b2.F = y; // 2 b2.F = z; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,16): warning CS8601: Possible null reference assignment. // b1.F = y; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(13, 16), // (18,16): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'A<object?>'. // b2.F = y; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object>", "A<object?>").WithLocation(18, 16)); } [Fact] public void UpdatePropertyFromReceiverType() { var source = @"class A<T> { } class B<T> { internal T P { get; set; } = default!; } class Program { internal static B<T> Create<T>(T t) => throw null!; static void M1(object x, object? y) { var b1 = Create(x); b1.P = x; b1.P = y; // 1 } static void M2(A<object?> x, A<object> y, A<object?> z) { var b2 = Create(x); b2.P = y; // 2 b2.P = z; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,16): warning CS8601: Possible null reference assignment. // b1.P = y; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(13, 16), // (18,16): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'A<object?>'. // b2.P = y; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object>", "A<object?>").WithLocation(18, 16)); } [WorkItem(31018, "https://github.com/dotnet/roslyn/issues/31018")] [Fact] public void UpdateEventFromReceiverType() { var source = @"#pragma warning disable 0067 delegate void D<T>(T t); class C<T> { internal event D<T> E; } class Program { internal static C<T> Create<T>(T t) => throw null!; static void M1(object x, D<object> y, D<object?> z) { var c1 = Create(x); c1.E += y; c1.E += z; // 1 } static void M2(object? x, D<object> y, D<object?> z) { var c2 = Create(x); c2.E += y; // 2 c2.E += z; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/31018: Report warnings. comp.VerifyDiagnostics( // (5,25): warning CS8618: Non-nullable event 'E' is uninitialized. Consider declaring the event as nullable. // internal event D<T> E; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E").WithArguments("event", "E").WithLocation(5, 25) ); } [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] [Fact] public void UpdateMethodFromReceiverType_01() { var source = @"class C<T> { internal void F(T t) { } } class Program { internal static C<T> Create<T>(T t) => throw null!; static void M(object x, object? y, string? z) { var c = Create(x); c.F(x); c.F(y); // 1 c.F(z); // 2 c.F(null); // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,13): warning CS8604: Possible null reference argument for parameter 't' in 'void C<object>.F(object t)'. // c.F(y); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("t", "void C<object>.F(object t)").WithLocation(12, 13), // (13,13): warning CS8604: Possible null reference argument for parameter 't' in 'void C<object>.F(object t)'. // c.F(z); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "z").WithArguments("t", "void C<object>.F(object t)").WithLocation(13, 13), // (14,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.F(null); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 13)); } [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] [Fact] public void UpdateMethodFromReceiverType_02() { var source = @"class A<T> { } class B<T> { internal void F<U>(U u) where U : A<T> { } } class Program { internal static B<T> Create<T>(T t) => throw null!; static void M1(object x, A<object> y, A<object?> z) { var b1 = Create(x); b1.F(y); b1.F(z); // 1 } static void M2(object? x, A<object> y, A<object?> z) { var b2 = Create(x); b2.F(y); // 2 b2.F(z); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8631: The type 'A<object?>' cannot be used as type parameter 'U' in the generic type or method 'B<object>.F<U>(U)'. Nullability of type argument 'A<object?>' doesn't match constraint type 'A<object>'. // b1.F(z); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "b1.F").WithArguments("B<object>.F<U>(U)", "A<object>", "U", "A<object?>").WithLocation(13, 9), // (18,9): warning CS8631: The type 'A<object>' cannot be used as type parameter 'U' in the generic type or method 'B<object?>.F<U>(U)'. Nullability of type argument 'A<object>' doesn't match constraint type 'A<object?>'. // b2.F(y); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "b2.F").WithArguments("B<object?>.F<U>(U)", "A<object?>", "U", "A<object>").WithLocation(18, 9)); } [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] [Fact] public void UpdateMethodFromReceiverType_03() { var source = @"class C<T> { internal static T F() => throw null!; } class Program { internal static C<T> Create<T>(T t) => throw null!; static void M(object x) { var c1 = Create(x); c1.F().ToString(); x = null; var c2 = Create(x); c2.F().ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): error CS0176: Member 'C<object>.F()' cannot be accessed with an instance reference; qualify it with a type name instead // c1.F().ToString(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "c1.F").WithArguments("C<object>.F()").WithLocation(11, 9), // (12,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 13), // (14,9): error CS0176: Member 'C<object>.F()' cannot be accessed with an instance reference; qualify it with a type name instead // c2.F().ToString(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "c2.F").WithArguments("C<object>.F()").WithLocation(14, 9)); } [Fact] public void AnnotationsInMetadata_01() { var source = @" using System.Collections.Generic; class B { public int F01; public int? F02; public string F03; public string? F04; public KeyValuePair<int, long> F05; public KeyValuePair<string, object> F06; public KeyValuePair<string?, object> F07; public KeyValuePair<string, object?> F08; public KeyValuePair<string?, object?> F09; public KeyValuePair<int, object> F10; public KeyValuePair<int, object?> F11; public KeyValuePair<object, int> F12; public KeyValuePair<object?, int> F13; public Dictionary<int, long> F14; public Dictionary<int, long>? F15; public Dictionary<string, object> F16; public Dictionary<string, object>? F17; public Dictionary<string?, object> F18; public Dictionary<string?, object>? F19; public Dictionary<string, object?> F20; public Dictionary<string, object?>? F21; public Dictionary<string?, object?> F22; public Dictionary<string?, object?>? F23; public Dictionary<int, object> F24; public Dictionary<int, object>? F25; public Dictionary<int, object?> F26; public Dictionary<int, object?>? F27; public Dictionary<object, int> F28; public Dictionary<object, int>? F29; public Dictionary<object?, int> F30; public Dictionary<object?, int>? F31; } "; var comp = CreateCompilation(new[] { source }); CompileAndVerify(comp, symbolValidator: validateAnnotationsContextFalse); comp = CreateCompilation(new[] { source }, options: WithNullable(NullableContextOptions.Warnings)); CompileAndVerify(comp, symbolValidator: validateAnnotationsContextFalse); comp = CreateCompilation(new[] { @"#nullable enable warnings " + source }); CompileAndVerify(comp, symbolValidator: validateAnnotationsContextFalse); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); CompileAndVerify(comp, symbolValidator: validateAnnotationsContextTrue); comp = CreateCompilation(new[] { source }, options: WithNullable(NullableContextOptions.Annotations)); CompileAndVerify(comp, symbolValidator: validateAnnotationsContextTrue); comp = CreateCompilation(new[] { @"#nullable enable annotations " + source }); CompileAndVerify(comp, symbolValidator: validateAnnotationsContextTrue); static void validateAnnotationsContextFalse(ModuleSymbol m) { (string type, string attribute)[] baseline = new[] { ("System.Int32", null), ("System.Int32?", null), ("System.String", null), ("System.String?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.KeyValuePair<System.Int32, System.Int64>", null), ("System.Collections.Generic.KeyValuePair<System.String, System.Object>", null), ("System.Collections.Generic.KeyValuePair<System.String?, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({0, 2, 0})"), ("System.Collections.Generic.KeyValuePair<System.String, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 0, 2})"), ("System.Collections.Generic.KeyValuePair<System.String?, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 2, 2})"), ("System.Collections.Generic.KeyValuePair<System.Int32, System.Object>", null), ("System.Collections.Generic.KeyValuePair<System.Int32, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 2})"), ("System.Collections.Generic.KeyValuePair<System.Object, System.Int32>", null), ("System.Collections.Generic.KeyValuePair<System.Object?, System.Int32>", "System.Runtime.CompilerServices.NullableAttribute({0, 2})"), ("System.Collections.Generic.Dictionary<System.Int32, System.Int64>", null), ("System.Collections.Generic.Dictionary<System.Int32, System.Int64>?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", null), ("System.Collections.Generic.Dictionary<System.String, System.Object>?", "System.Runtime.CompilerServices.NullableAttribute({2, 0, 0})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({0, 2, 0})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object>?", "System.Runtime.CompilerServices.NullableAttribute({2, 2, 0})"), ("System.Collections.Generic.Dictionary<System.String, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 0, 2})"), ("System.Collections.Generic.Dictionary<System.String, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute({2, 0, 2})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 2, 2})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object>", null), ("System.Collections.Generic.Dictionary<System.Int32, System.Object>?", "System.Runtime.CompilerServices.NullableAttribute({2, 0})"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 2})"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.Dictionary<System.Object, System.Int32>", null), ("System.Collections.Generic.Dictionary<System.Object, System.Int32>?", "System.Runtime.CompilerServices.NullableAttribute({2, 0})"), ("System.Collections.Generic.Dictionary<System.Object?, System.Int32>", "System.Runtime.CompilerServices.NullableAttribute({0, 2})"), ("System.Collections.Generic.Dictionary<System.Object?, System.Int32>?", "System.Runtime.CompilerServices.NullableAttribute(2)") }; Assert.Equal(31, baseline.Length); AnnotationsInMetadataFieldSymbolValidator(m, baseline); } static void validateAnnotationsContextTrue(ModuleSymbol m) { (string type, string attribute)[] baseline = new[] { ("System.Int32", null), ("System.Int32?", null), ("System.String!", "System.Runtime.CompilerServices.NullableAttribute(1)"), ("System.String?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.KeyValuePair<System.Int32, System.Int64>", null), ("System.Collections.Generic.KeyValuePair<System.String!, System.Object!>", "System.Runtime.CompilerServices.NullableAttribute({0, 1, 1})"), ("System.Collections.Generic.KeyValuePair<System.String?, System.Object!>", "System.Runtime.CompilerServices.NullableAttribute({0, 2, 1})"), ("System.Collections.Generic.KeyValuePair<System.String!, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 1, 2})"), ("System.Collections.Generic.KeyValuePair<System.String?, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 2, 2})"), ("System.Collections.Generic.KeyValuePair<System.Int32, System.Object!>", "System.Runtime.CompilerServices.NullableAttribute({0, 1})"), ("System.Collections.Generic.KeyValuePair<System.Int32, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 2})"), ("System.Collections.Generic.KeyValuePair<System.Object!, System.Int32>", "System.Runtime.CompilerServices.NullableAttribute({0, 1})"), ("System.Collections.Generic.KeyValuePair<System.Object?, System.Int32>", "System.Runtime.CompilerServices.NullableAttribute({0, 2})"), ("System.Collections.Generic.Dictionary<System.Int32, System.Int64>!", "System.Runtime.CompilerServices.NullableAttribute(1)"), ("System.Collections.Generic.Dictionary<System.Int32, System.Int64>?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.Dictionary<System.String!, System.Object!>!", "System.Runtime.CompilerServices.NullableAttribute(1)"), ("System.Collections.Generic.Dictionary<System.String!, System.Object!>?", "System.Runtime.CompilerServices.NullableAttribute({2, 1, 1})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object!>!", "System.Runtime.CompilerServices.NullableAttribute({1, 2, 1})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object!>?", "System.Runtime.CompilerServices.NullableAttribute({2, 2, 1})"), ("System.Collections.Generic.Dictionary<System.String!, System.Object?>!", "System.Runtime.CompilerServices.NullableAttribute({1, 1, 2})"), ("System.Collections.Generic.Dictionary<System.String!, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute({2, 1, 2})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object?>!", "System.Runtime.CompilerServices.NullableAttribute({1, 2, 2})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object!>!", "System.Runtime.CompilerServices.NullableAttribute(1)"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object!>?", "System.Runtime.CompilerServices.NullableAttribute({2, 1})"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object?>!", "System.Runtime.CompilerServices.NullableAttribute({1, 2})"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.Dictionary<System.Object!, System.Int32>!", "System.Runtime.CompilerServices.NullableAttribute(1)"), ("System.Collections.Generic.Dictionary<System.Object!, System.Int32>?", "System.Runtime.CompilerServices.NullableAttribute({2, 1})"), ("System.Collections.Generic.Dictionary<System.Object?, System.Int32>!", "System.Runtime.CompilerServices.NullableAttribute({1, 2})"), ("System.Collections.Generic.Dictionary<System.Object?, System.Int32>?", "System.Runtime.CompilerServices.NullableAttribute(2)") }; } } private static void AnnotationsInMetadataFieldSymbolValidator(ModuleSymbol m, (string type, string attribute)[] baseline) { var b = m.GlobalNamespace.GetMember<NamedTypeSymbol>("B"); for (int i = 0; i < baseline.Length; i++) { var name = "F" + (i + 1).ToString("00"); var f = b.GetMember<FieldSymbol>(name); Assert.Equal(baseline[i].type, f.TypeWithAnnotations.ToTestDisplayString(true)); if (baseline[i].attribute == null) { Assert.Empty(f.GetAttributes()); } else { Assert.Equal(baseline[i].attribute, f.GetAttributes().Single().ToString()); } } } [Fact] public void AnnotationsInMetadata_02() { var ilSource = @" // =============== CLASS MEMBERS DECLARATION =================== .class private auto ansi beforefieldinit B`12<class T01,class T02,class T03,class T04, class T05,class T06,class T07,class T08, class T09,class T10,class T11,class T12> extends [mscorlib]System.Object { .param type T01 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 00 00 00 ) .param type T02 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 01 00 00 ) .param type T03 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 02 00 00 ) .param type T04 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 03 00 00 ) .param type T05 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 04 00 00 ) .param type T06 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 05 00 00 ) .param type T07 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 00 00 00 ) .param type T08 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 01 00 00 ) .param type T09 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 02 00 00 ) .param type T10 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 02 00 00 00 01 01 00 00 ) .param type T11 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 00 00 00 00 00 00 ) .param type T12 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 FF FF FF FF 00 00 ) .field public int32 F01 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 00 00 00 ) .field public int32 F02 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 01 00 00 ) .field public int32 F03 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 02 00 00 ) .field public int32 F04 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 03 00 00 ) .field public int32 F05 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 00 00 00 ) .field public int32 F06 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 01 00 00 ) .field public int32 F07 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 02 00 00 ) .field public int32 F08 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 04 00 00 ) .field public int32 F09 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 FF FF FF FF 00 00 ) .field public valuetype [mscorlib]System.Nullable`1<int32> F10 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 00 00 00 ) .field public valuetype [mscorlib]System.Nullable`1<int32> F11 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 02 00 00 00 00 00 00 00 ) .field public valuetype [mscorlib]System.Nullable`1<int32> F12 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 FF FF FF FF 00 00 ) .field public string F13 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 00 00 00 ) .field public string F14 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 03 00 00 ) .field public string F15 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 00 00 00 ) .field public string F16 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 01 00 00 ) .field public string F17 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 02 00 00 ) .field public string F18 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 04 00 00 ) .field public string F19 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 FF FF FF FF 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F20 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 00 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F21 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 03 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F22 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 FF FF FF FF 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F23 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 00 00 00 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F24 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 01 01 01 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F25 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 02 02 02 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F26 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 01 04 05 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F27 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 00 01 02 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F28 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 01 02 00 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F29 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 02 00 01 00 00 ) .field public string F30 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 02 00 00 00 01 01 00 00 ) .field public string F31 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 00 00 00 00 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F32 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 04 00 00 00 01 01 01 01 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F33 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 02 00 00 00 01 01 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F34 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 00 00 00 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method B`12::.ctor } // end of class B`12 .class public auto ansi beforefieldinit System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(uint8 x) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method NullableAttribute::.ctor .method public hidebysig specialname rtspecialname instance void .ctor(uint8[] x) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method NullableAttribute::.ctor } // end of class System.Runtime.CompilerServices.NullableAttribute // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** /* class B<[Nullable(0)]T01, [Nullable(1)]T02, [Nullable(2)]T03, [Nullable(3)]T04, [Nullable(4)]T05, [Nullable(5)]T06, [Nullable(new byte[] { 0 })]T07, [Nullable(new byte[] { 1 })]T08, [Nullable(new byte[] { 2 })]T09, [Nullable(new byte[] { 1, 1 })]T10, [Nullable(new byte[] { })]T11, [Nullable(null)]T12> where T01 : class where T02 : class where T03 : class where T04 : class where T05 : class where T06 : class where T07 : class where T08 : class where T09 : class where T10 : class where T11 : class where T12 : class { [Nullable(0)] public int F01; [Nullable(1)] public int F02; [Nullable(2)] public int F03; [Nullable(3)] public int F04; [Nullable(new byte[] { 0 })] public int F05; [Nullable(new byte[] { 1 })] public int F06; [Nullable(new byte[] { 2 })] public int F07; [Nullable(new byte[] { 4 })] public int F08; [Nullable(null)] public int F09; [Nullable(0)] public int? F10; [Nullable(new byte[] { 0, 0 })] public int? F11; [Nullable(null)] public int? F12; [Nullable(0)] public string F13; [Nullable(3)] public string F14; [Nullable(new byte[] { 0 })] public string F15; [Nullable(new byte[] { 1 })] public string F16; [Nullable(new byte[] { 2 })] public string F17; [Nullable(new byte[] { 4 })] public string F18; [Nullable(null)] public string F19; [Nullable(0)] public System.Collections.Generic.Dictionary<string, object> F20; [Nullable(3)] public System.Collections.Generic.Dictionary<string, object> F21; [Nullable(null)] public System.Collections.Generic.Dictionary<string, object> F22; [Nullable(new byte[] { 0, 0, 0 })] public System.Collections.Generic.Dictionary<string, object> F23; [Nullable(new byte[] { 1, 1, 1 })] public System.Collections.Generic.Dictionary<string, object> F24; [Nullable(new byte[] { 2, 2, 2 })] public System.Collections.Generic.Dictionary<string, object> F25; [Nullable(new byte[] { 1, 4, 5 })] public System.Collections.Generic.Dictionary<string, object> F26; [Nullable(new byte[] { 0, 1, 2 })] public System.Collections.Generic.Dictionary<string, object> F27; [Nullable(new byte[] { 1, 2, 0 })] public System.Collections.Generic.Dictionary<string, object> F28; [Nullable(new byte[] { 2, 0, 1 })] public System.Collections.Generic.Dictionary<string, object> F29; [Nullable(new byte[] { 1, 1 })] public string F30; [Nullable(new byte[] { })] public string F31; [Nullable(new byte[] { 1, 1, 1, 1 })] public System.Collections.Generic.Dictionary<string, object> F32; [Nullable(new byte[] { 1, 1 })] public System.Collections.Generic.Dictionary<string, object> F33; [Nullable(new byte[] { })] public System.Collections.Generic.Dictionary<string, object> F34; }*/ "; var source = @""; var compilation = CreateCompilation(new[] { source }, new[] { CompileIL(ilSource) }); NamedTypeSymbol b = compilation.GetTypeByMetadataName("B`12"); (string type, string attribute)[] fieldsBaseline = new[] { ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute(0)"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute(1)"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute(3)"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute({0})"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute({1})"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute({2})"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute({4})"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute(null)"), ("System.Int32?", "System.Runtime.CompilerServices.NullableAttribute(0)"), ("System.Int32?", "System.Runtime.CompilerServices.NullableAttribute({0, 0})"), ("System.Int32?", "System.Runtime.CompilerServices.NullableAttribute(null)"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute(0)"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute(3)"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute({0})"), ("System.String!", "System.Runtime.CompilerServices.NullableAttribute({1})"), ("System.String?", "System.Runtime.CompilerServices.NullableAttribute({2})"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute({4})"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute(null)"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute(0)"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute(3)"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute(null)"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({0, 0, 0})"), ("System.Collections.Generic.Dictionary<System.String!, System.Object!>!", "System.Runtime.CompilerServices.NullableAttribute({1, 1, 1})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute({2, 2, 2})"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({1, 4, 5})"), ("System.Collections.Generic.Dictionary<System.String!, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 1, 2})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object>!", "System.Runtime.CompilerServices.NullableAttribute({1, 2, 0})"), ("System.Collections.Generic.Dictionary<System.String, System.Object!>?", "System.Runtime.CompilerServices.NullableAttribute({2, 0, 1})"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute({1, 1})"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute({})"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({1, 1, 1, 1})"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({1, 1})"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({})"), }; Assert.Equal(34, fieldsBaseline.Length); AnnotationsInMetadataFieldSymbolValidator(b.ContainingModule, fieldsBaseline); (bool? constraintIsNullable, string attribute)[] typeParametersBaseline = new[] { ((bool?)null, "System.Runtime.CompilerServices.NullableAttribute(0)"), (false, "System.Runtime.CompilerServices.NullableAttribute(1)"), (true, "System.Runtime.CompilerServices.NullableAttribute(2)"), (null, "System.Runtime.CompilerServices.NullableAttribute(3)"), (null, "System.Runtime.CompilerServices.NullableAttribute(4)"), (null, "System.Runtime.CompilerServices.NullableAttribute(5)"), (null, "System.Runtime.CompilerServices.NullableAttribute({0})"), (null, "System.Runtime.CompilerServices.NullableAttribute({1})"), (null, "System.Runtime.CompilerServices.NullableAttribute({2})"), (null, "System.Runtime.CompilerServices.NullableAttribute({1, 1})"), (null, "System.Runtime.CompilerServices.NullableAttribute({})"), (null, "System.Runtime.CompilerServices.NullableAttribute(null)"), }; Assert.Equal(12, typeParametersBaseline.Length); for (int i = 0; i < typeParametersBaseline.Length; i++) { var t = b.TypeParameters[i]; Assert.Equal(typeParametersBaseline[i].constraintIsNullable, t.ReferenceTypeConstraintIsNullable); Assert.Equal(typeParametersBaseline[i].attribute, t.GetAttributes().Single().ToString()); } } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInFinally_01() { var source = @"public static class Program { public static void Main() { string? s = string.Empty; try { } finally { s = null; } _ = s.Length; // warning } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 13) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_02() { var source = @"public static class Program { public static int Main() { string? s = string.Empty; try { s = null; MayThrow(); s = string.Empty; } catch (System.Exception) { } return s.Length; // warning: possibly null } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,16): warning CS8602: Dereference of a possibly null reference. // return s.Length; // warning: possibly null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(16, 16) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_03() { var source = @"public static class Program { public static int Main() { string? s = string.Empty; try { s = null; MayThrow(); s = string.Empty; } catch (System.Exception) { return s.Length; // warning: possibly null } return s.Length; } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,20): warning CS8602: Dereference of a possibly null reference. // return s.Length; // warning: possibly null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 20) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_04() { var source = @"public static class Program { public static int Main() { string? s = string.Empty; try { s = null; MayThrow(); s = string.Empty; } catch (System.Exception) { _ = s.Length; // warning 1 } finally { _ = s.Length; // warning 2 } return s.Length; // ok (previously dereferenced) } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17), // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_05() { var source = @"public static class Program { public static int Main() { string? s = null; try { MayThrow(); s = string.Empty; _ = s.Length; // ok } catch (System.Exception) { _ = s.Length; // warning 1 } finally { _ = s.Length; // warning 2 } return s.Length; // ok (previously dereferenced) } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17), // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_06() { var source = @"public static class Program { public static int Main() { string? s = null; try { MayThrow(); s = string.Empty; _ = s.Length; // ok } catch (System.NullReferenceException) { _ = s.Length; // warning 1 } catch (System.Exception) { _ = s.Length; // warning 2 } finally { _ = s.Length; // warning 3 } return s.Length; // ok (previously dereferenced) } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17), // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17), // (22,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(22, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_07() { var source = @"public static class Program { public static int Main() { string? s = null; try { MayThrow(); s = string.Empty; _ = s.Length; // ok } catch (System.NullReferenceException) { _ = s.Length; // warning 1 } catch (System.Exception) { _ = s.Length; // warning 2 } return s.Length; // ok } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17), // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateBeforeTry_08() { var source = @"public static class Program { public static int Main() { string? s = null; try { MayThrow(); _ = s.Length; // warning 1 } catch (System.NullReferenceException) { _ = s.Length; // warning 2 } catch (System.Exception) { _ = s.Length; // warning 3 } return s.Length; // ok (previously dereferenced) } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17), // (13,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 17), // (17,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_09() { var source = @"public static class Program { public static int Main() { string? s = string.Empty; try { s = null; MayThrow(); s = string.Empty; } finally { _ = s.Length; // warning } return s.Length; // ok } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInCatch_10() { var source = @"public static class Program { public static int Main() { string? s = string.Empty; try { MayThrow(); } catch (System.Exception) { s = null; MayThrow(); s = string.Empty; } finally { _ = s.Length; // warning } return s.Length; // ok } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInNestedTry_01() { var source = @"public static class Program { public static void Main() { { string? s = string.Empty; try { try { s = null; } catch (System.Exception) { } finally { } } catch (System.Exception) { } finally { } _ = s.Length; // warning 1a } { string? s = string.Empty; try { try { } catch (System.Exception) { s = null; } finally { } } catch (System.Exception) { } finally { } _ = s.Length; // warning 1b } { string? s = string.Empty; try { try { } catch (System.Exception) { } finally { s = null; } } catch (System.Exception) { } finally { } _ = s.Length; // warning 1c } { string? s = string.Empty; try { } catch (System.Exception) { try { s = null; } catch (System.Exception) { } finally { } } finally { _ = s.Length; // warning 2a } } { string? s = string.Empty; try { } catch (System.Exception) { try { } catch (System.Exception) { s = null; } finally { } } finally { _ = s.Length; // warning 2b } } { string? s = string.Empty; try { } catch (System.Exception) { try { } catch (System.Exception) { } finally { s = null; } } finally { _ = s.Length; // warning 2c } } { string? s = string.Empty; try { } catch (System.Exception) { } finally { try { s = null; } catch (System.Exception) { } finally { } } _ = s.Length; // warning 3a } { string? s = string.Empty; try { } catch (System.Exception) { } finally { try { } catch (System.Exception) { s = null; } finally { } } _ = s.Length; // warning 3b } { string? s = string.Empty; try { } catch (System.Exception) { } finally { try { } catch (System.Exception) { } finally { s = null; } } _ = s.Length; // warning 3c } } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (27,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1a Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(27, 17), // (52,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1b Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(52, 17), // (77,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1c Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(77, 17), // (100,21): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2a Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(100, 21), // (124,21): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2b Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(124, 21), // (148,21): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2c Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(148, 21), // (174,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 3a Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(174, 17), // (199,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 3b Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(199, 17), // (224,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 3c Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(224, 17) ); } [WorkItem(30938, "https://github.com/dotnet/roslyn/issues/30938")] [Fact] public void ExplicitCastAndInferredTargetType() { var source = @"class Program { static void F(object? x) { if (x == null) return; var y = x; x = null; y = (object)x; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = (object)x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)x").WithLocation(8, 13)); } [Fact] [WorkItem(31395, "https://github.com/dotnet/roslyn/issues/31395")] public void InheritNullabilityOfNonNullableClassMember() { var source = @"#pragma warning disable 8618 class C<T> { internal T F; } class Program { static bool b = false; static void F1(string? s) { var a1 = new C<string>() { F = s }; // 0 if (b) F(a1.F/*T:string?*/); // 1 var b1 = a1; if (b) F(b1.F/*T:string?*/); // 2 } static void F2<T>(T? t) where T : class { var a2 = new C<T>() { F = t }; // 3 if (b) F(a2.F/*T:T?*/); // 4 var b2 = a2; if (b) F(b2.F/*T:T?*/); // 5 } static void F(object o) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,40): warning CS8601: Possible null reference assignment. // var a1 = new C<string>() { F = s }; // 0 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(11, 40), // (12,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(a1.F/*T:string?*/); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a1.F").WithArguments("o", "void Program.F(object o)").WithLocation(12, 18), // (14,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(b1.F/*T:string?*/); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b1.F").WithArguments("o", "void Program.F(object o)").WithLocation(14, 18), // (18,35): warning CS8601: Possible null reference assignment. // var a2 = new C<T>() { F = t }; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(18, 35), // (19,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(a2.F/*T:T?*/); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a2.F").WithArguments("o", "void Program.F(object o)").WithLocation(19, 18), // (21,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(b2.F/*T:T?*/); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b2.F").WithArguments("o", "void Program.F(object o)").WithLocation(21, 18)); comp.VerifyTypes(); } [Fact] public void InheritNullabilityOfNonNullableStructMember() { var source = @"#pragma warning disable 8618 struct S<T> { internal T F; } class Program { static bool b = false; static void F1(string? s) { var a1 = new S<string>() { F = s }; // 0 if (b) F(a1.F/*T:string?*/); // 1 var b1 = a1; if (b) F(b1.F/*T:string?*/); // 2 } static void F2<T>(T? t) where T : class { var a2 = new S<T>() { F = t }; // 3 if (b) F(a2.F/*T:T?*/); // 4 var b2 = a2; if (b) F(b2.F/*T:T?*/); // 5 } static void F(object o) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,40): warning CS8601: Possible null reference assignment. // var a1 = new S<string>() { F = s }; // 0 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(11, 40), // (12,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(a1.F/*T:string?*/); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a1.F").WithArguments("o", "void Program.F(object o)").WithLocation(12, 18), // (14,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(b1.F/*T:string?*/); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b1.F").WithArguments("o", "void Program.F(object o)").WithLocation(14, 18), // (18,35): warning CS8601: Possible null reference assignment. // var a2 = new S<T>() { F = t }; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(18, 35), // (19,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(a2.F/*T:T?*/); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a2.F").WithArguments("o", "void Program.F(object o)").WithLocation(19, 18), // (21,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(b2.F/*T:T?*/); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b2.F").WithArguments("o", "void Program.F(object o)").WithLocation(21, 18)); comp.VerifyTypes(); } /// <summary> /// Nullability of variable members is tracked up to a fixed depth. /// </summary> [Fact] [WorkItem(31395, "https://github.com/dotnet/roslyn/issues/31395")] public void InheritNullabilityMaxDepth_01() { var source = @"#pragma warning disable 8618 class A { internal B? B; } class B { internal A? A; } class Program { static void F() { var a1 = new A() { B = new B() }; var a2 = new A() { B = new B() { A = a1 } }; var a3 = new A() { B = new B() { A = a2 } }; a1.B.ToString(); a2.B.A.B.ToString(); a3.B.A.B.A.B.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // a3.B.A.B.A.B.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a3.B.A.B.A.B").WithLocation(19, 9)); } /// <summary> /// Nullability of variable members is tracked up to a fixed depth. /// </summary> [Fact] [WorkItem(31395, "https://github.com/dotnet/roslyn/issues/31395")] public void InheritNullabilityMaxDepth_02() { var source = @"class Program { static void F(string x, object y) { (((((string? x5, object? y5) x4, string? y4) x3, object? y3) x2, string? y2) x1, object? y1) t = (((((x, y), x), y), x), y); t.y1.ToString(); t.x1.y2.ToString(); t.x1.x2.y3.ToString(); t.x1.x2.x3.y4.ToString(); t.x1.x2.x3.x4.y5.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // t.x1.x2.x3.x4.y5.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.x1.x2.x3.x4.y5").WithLocation(10, 9)); } /// <summary> /// Nullability of variable members is tracked up to a fixed depth. /// </summary> [Fact] [WorkItem(31395, "https://github.com/dotnet/roslyn/issues/31395")] [WorkItem(35773, "https://github.com/dotnet/roslyn/issues/35773")] public void InheritNullabilityMaxDepth_03() { var source = @"class Program { static void Main() { (((((string x5, string y5) x4, string y4) x3, string y3) x2, string y2) x1, string y1) t = default; t.x1.x2.x3.x4.x5.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void DiagnosticOptions_01() { var source = @" partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } private static void AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(string source) { string id = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable); var source2 = @" partial class Program { #nullable enable static void F(object o) { } }"; var comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable()); comp.VerifyDiagnostics(); foreach (ReportDiagnostic option in Enum.GetValues(typeof(ReportDiagnostic))) { comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable().WithSpecificDiagnosticOptions(id, option)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable().WithGeneralDiagnosticOption(option)); comp.VerifyDiagnostics(); } assertDiagnosticOptions(NullableContextOptions.Enable); assertDiagnosticOptions(NullableContextOptions.Warnings); void assertDiagnosticOptions(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions); var diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): error CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithWarningAsError(true) ); Assert.Equal(DiagnosticSeverity.Error, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error). WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): error CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithWarningAsError(true) ); Assert.Equal(DiagnosticSeverity.Error, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): error CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithWarningAsError(true) ); Assert.Equal(DiagnosticSeverity.Error, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): hidden CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Hidden, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): hidden CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Hidden, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); } } [Fact] public void DiagnosticOptions_02() { var source = @" #pragma warning disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } private static void AssertDiagnosticOptions_NullableWarningsNeverGiven(string source) { string id1 = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable); string id2 = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable); var source2 = @" partial class Program { #nullable enable static void F(object o) { } static object M() { return new object(); } }"; var comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable()); comp.VerifyDiagnostics(); foreach (ReportDiagnostic option in Enum.GetValues(typeof(ReportDiagnostic))) { comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable().WithSpecificDiagnosticOptions(id1, id2, option)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable().WithGeneralDiagnosticOption(option)); comp.VerifyDiagnostics(); } assertDiagnosticOptions(NullableContextOptions.Disable); assertDiagnosticOptions(NullableContextOptions.Enable); assertDiagnosticOptions(NullableContextOptions.Warnings); assertDiagnosticOptions(NullableContextOptions.Annotations); void assertDiagnosticOptions(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Default)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithGeneralDiagnosticOption(ReportDiagnostic.Default)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Error)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Error). WithGeneralDiagnosticOption(ReportDiagnostic.Default)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Error)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Suppress)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Suppress). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Hidden)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Hidden). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); comp.VerifyDiagnostics(); } } [Fact] public void DiagnosticOptions_03() { var source = @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_04() { var source = @" #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_05() { var source = @" #nullable disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_06() { var source = @" #nullable enable partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(source); } private static void AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(string source) { var source2 = @" partial class Program { #nullable enable static void F(object o) { } }"; assertDiagnosticOptions(NullableContextOptions.Disable); assertDiagnosticOptions(NullableContextOptions.Enable); assertDiagnosticOptions(NullableContextOptions.Warnings); assertDiagnosticOptions(NullableContextOptions.Annotations); void assertDiagnosticOptions(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions options = WithNullable(nullableContextOptions); string id = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable); var comp = CreateCompilation(new[] { source, source2 }, options: options); var diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (8,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 11) ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options.WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): error CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithWarningAsError(true) ); Assert.Equal(DiagnosticSeverity.Error, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error). WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): error CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithWarningAsError(true) ); Assert.Equal(DiagnosticSeverity.Error, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): error CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithWarningAsError(true) ); Assert.Equal(DiagnosticSeverity.Error, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): hidden CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Hidden, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): hidden CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Hidden, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); } } [Fact] public void DiagnosticOptions_07() { var source = @" #pragma warning disable #nullable disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_08() { var source = @" #pragma warning disable #nullable enable partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_09() { var source = @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" #nullable disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_10() { var source = @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" #nullable enable partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_11() { var source = @" #nullable disable #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_12() { var source = @" #nullable disable #pragma warning disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_13() { var source = @" #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" #nullable disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_14() { var source = @" #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" #nullable enable partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_15() { var source = @" #nullable disable #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_16() { var source = @" #pragma warning restore partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_17() { var source = @" #nullable disable #pragma warning restore partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_18() { var source = @" #pragma warning restore #nullable disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_19() { var source = @" #nullable enable #pragma warning restore partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_20() { var source = @" #pragma warning restore #nullable enable partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_21() { var source = @" #nullable enable #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_22() { var source = @" #nullable restore partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_23() { var source = @" #nullable safeonly "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,11): error CS8637: Expected 'enable', 'disable', or 'restore' // #nullable safeonly Diagnostic(ErrorCode.ERR_NullableDirectiveQualifierExpected, "safeonly").WithLocation(2, 11) ); } [Fact] public void DiagnosticOptions_26() { var source = @" #nullable restore #nullable disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_27() { var source = @" #nullable restore #nullable enable partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_30() { var source = @" #nullable disable #nullable restore partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_32() { var source = @" #nullable enable #nullable restore partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_36() { var source = @" partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } private static void AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(string source) { var source2 = @" partial class Program { #nullable enable static object M() { return new object(); } }"; string id = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable); assertDiagnosticOptions1(NullableContextOptions.Enable); assertDiagnosticOptions1(NullableContextOptions.Warnings); assertDiagnosticOptions2(NullableContextOptions.Disable); assertDiagnosticOptions2(NullableContextOptions.Annotations); void assertDiagnosticOptions1(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions); var diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error). WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); } void assertDiagnosticOptions2(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions); comp.VerifyDiagnostics(); foreach (ReportDiagnostic option in Enum.GetValues(typeof(ReportDiagnostic))) { comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable().WithSpecificDiagnosticOptions(id, option)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable().WithGeneralDiagnosticOption(option)); comp.VerifyDiagnostics(); } } } [Fact] public void DiagnosticOptions_37() { var source = @" #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_38() { var source = @" #nullable enable partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } private static void AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(string source) { var source2 = @" partial class Program { #nullable enable static object M() { return new object(); } }"; assertDiagnosticOptions(NullableContextOptions.Disable); assertDiagnosticOptions(NullableContextOptions.Enable); assertDiagnosticOptions(NullableContextOptions.Warnings); assertDiagnosticOptions(NullableContextOptions.Annotations); void assertDiagnosticOptions(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions options = WithNullable(nullableContextOptions); string id = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable); var comp = CreateCompilation(new[] { source, source2 }, options: options); var diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options.WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error). WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); } } [Fact] public void DiagnosticOptions_39() { var source = @" #pragma warning disable #nullable enable partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_40() { var source = @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" #nullable enable partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_41() { var source = @" #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" #nullable enable partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_42() { var source = @" #nullable disable #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_43() { var source = @" #pragma warning restore partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_44() { var source = @" #nullable disable #pragma warning restore partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_45() { var source = @" #nullable enable #pragma warning restore partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_46() { var source = @" #pragma warning restore #nullable enable partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_48() { var source = @" #nullable enable #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_49() { var source = @" #nullable restore partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_53() { var source = @" #nullable restore #nullable enable partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_56() { var source = @" #nullable disable #nullable restore partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_58() { var source = @" #nullable enable #nullable restore partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_62() { var source = @" #nullable disable warnings partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_63() { var source = @" #nullable enable warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_64() { var source = @" #pragma warning disable #nullable enable warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_65() { var source = @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" #nullable enable warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_66() { var source = @" #pragma warning restore #nullable enable warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_67() { var source = @" #nullable restore #nullable enable warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_68() { var source = @" #nullable restore warnings partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_69() { var source = @" #nullable disable #nullable restore warnings partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_70() { var source = @" #nullable enable #nullable restore warnings partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_72() { var source = @" #nullable restore warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_73() { var source = @" #nullable disable #nullable restore warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_74() { var source = @" #nullable enable #nullable restore warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] [WorkItem(31394, "https://github.com/dotnet/roslyn/issues/31394")] public void InheritMemberNullability_Class() { var source = @"#pragma warning disable 8618 class C<T> { internal T F; } class Program { static void F() { C<object> x = new C<object?>() { F = null }; x.F/*T:object?*/.ToString(); // 1 C<object?> y = new C<object>() { F = new object() }; y.F/*T:object!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,23): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // C<object> x = new C<object?>() { F = null }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C<object?>() { F = null }").WithArguments("C<object?>", "C<object>").WithLocation(10, 23), // (11,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(11, 9), // (12,24): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // C<object?> y = new C<object>() { F = new object() }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C<object>() { F = new object() }").WithArguments("C<object>", "C<object?>").WithLocation(12, 24)); comp.VerifyTypes(); } [Fact] [WorkItem(31394, "https://github.com/dotnet/roslyn/issues/31394")] public void InheritMemberNullability_Struct() { var source = @"#pragma warning disable 8618 struct S<T> { internal T F; } class Program { static void F() { S<object> x = new S<object?>(); x.F/*T:object?*/.ToString(); // 1 S<object?> y = new S<object>() { F = new object() }; y.F/*T:object!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,23): warning CS8619: Nullability of reference types in value of type 'S<object?>' doesn't match target type 'S<object>'. // S<object> x = new S<object?>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new S<object?>()").WithArguments("S<object?>", "S<object>").WithLocation(10, 23), // (11,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(11, 9), // (12,24): warning CS8619: Nullability of reference types in value of type 'S<object>' doesn't match target type 'S<object?>'. // S<object?> y = new S<object>() { F = new object() }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new S<object>() { F = new object() }").WithArguments("S<object>", "S<object?>").WithLocation(12, 24)); comp.VerifyTypes(); } [Fact] [WorkItem(31394, "https://github.com/dotnet/roslyn/issues/31394")] public void InheritMemberNullability_AnonymousTypeField() { var source = @"class C<T> { } class Program { static void F1(C<object> x1, C<object?>? y1) { var a1 = new { F = x1 }; a1.F/*T:C<object!>!*/.ToString(); a1 = new { F = y1 }; a1.F/*T:C<object!>?*/.ToString(); // 1 } static void F2(C<object>? x2, C<object?> y2) { var a2 = new { F = x2 }; a2.F/*T:C<object!>?*/.ToString(); // 2 a2 = new { F = y2 }; a2.F/*T:C<object!>!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: C<object?>? F>' doesn't match target type '<anonymous type: C<object> F>'. // a1 = new { F = y1 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new { F = y1 }").WithArguments("<anonymous type: C<object?>? F>", "<anonymous type: C<object> F>").WithLocation(8, 14), // (9,9): warning CS8602: Dereference of a possibly null reference. // a1.F/*T:C<object!>?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a1.F").WithLocation(9, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // a2.F/*T:C<object!>?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2.F").WithLocation(14, 9), // (15,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: C<object?> F>' doesn't match target type '<anonymous type: C<object>? F>'. // a2 = new { F = y2 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new { F = y2 }").WithArguments("<anonymous type: C<object?> F>", "<anonymous type: C<object>? F>").WithLocation(15, 14)); comp.VerifyTypes(); } [Fact] [WorkItem(31394, "https://github.com/dotnet/roslyn/issues/31394")] public void InheritMemberNullability_TupleElement_01() { var source = @"class C<T> { } class Program { static void F1(C<object> x1, C<object?>? y1) { var t1 = (x1, y1); t1.Item1/*T:C<object!>!*/.ToString(); t1 = (y1, y1); t1.Item1/*T:C<object!>?*/.ToString(); // 1 } static void F2(C<object>? x2, C<object?> y2) { var t2 = (x2, y2); t2.Item1/*T:C<object!>?*/.ToString(); // 2 t2 = (y2, y2); t2.Item1/*T:C<object!>!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8619: Nullability of reference types in value of type '(C<object?>?, C<object?>?)' doesn't match target type '(C<object> x1, C<object?>? y1)'. // t1 = (y1, y1); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(y1, y1)").WithArguments("(C<object?>?, C<object?>?)", "(C<object> x1, C<object?>? y1)").WithLocation(8, 14), // (9,9): warning CS8602: Dereference of a possibly null reference. // t1.Item1/*T:C<object!>?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1.Item1").WithLocation(9, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // t2.Item1/*T:C<object!>?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2.Item1").WithLocation(14, 9), // (15,14): warning CS8619: Nullability of reference types in value of type '(C<object?>, C<object?>)' doesn't match target type '(C<object>? x2, C<object?> y2)'. // t2 = (y2, y2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(y2, y2)").WithArguments("(C<object?>, C<object?>)", "(C<object>? x2, C<object?> y2)").WithLocation(15, 14)); comp.VerifyTypes(); } [Fact] [WorkItem(31394, "https://github.com/dotnet/roslyn/issues/31394")] public void InheritMemberNullability_TupleElement_02() { var source = @"class C<T> { } class Program { static void F(C<object> x, C<object?>? y) { (C<object?>? a, C<object> b) t = (x, y); t.a/*T:C<object?>!*/.ToString(); t.b/*T:C<object!>?*/.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,42): warning CS8619: Nullability of reference types in value of type '(C<object> x, C<object?>? y)' doesn't match target type '(C<object?>? a, C<object> b)'. // (C<object?>? a, C<object> b) t = (x, y); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(C<object> x, C<object?>? y)", "(C<object?>? a, C<object> b)").WithLocation(6, 42), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.b/*T:C<object!>?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.b").WithLocation(8, 9)); comp.VerifyTypes(); } private static readonly NullableAnnotation[] s_AllNullableAnnotations = ((NullableAnnotation[])Enum.GetValues(typeof(NullableAnnotation))).Where(n => n != NullableAnnotation.Ignored).ToArray(); private static readonly NullableFlowState[] s_AllNullableFlowStates = (NullableFlowState[])Enum.GetValues(typeof(NullableFlowState)); [Fact] public void TestJoinForNullableAnnotations() { var inputs = new[] { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }; Func<int, int, NullableAnnotation> getResult = (i, j) => NullableAnnotationExtensions.Join(inputs[i], inputs[j]); var expected = new NullableAnnotation[3, 3] { { NullableAnnotation.Annotated, NullableAnnotation.Annotated, NullableAnnotation.Annotated }, { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.Oblivious }, { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }, }; AssertEqual(expected, getResult, inputs.Length); } [Fact] public void TestJoinForNullableFlowStates() { var inputs = new[] { NullableFlowState.NotNull, NullableFlowState.MaybeNull }; Func<int, int, NullableFlowState> getResult = (i, j) => inputs[i].Join(inputs[j]); var expected = new NullableFlowState[2, 2] { { NullableFlowState.NotNull, NullableFlowState.MaybeNull }, { NullableFlowState.MaybeNull, NullableFlowState.MaybeNull }, }; AssertEqual(expected, getResult, inputs.Length); } [Fact] public void TestMeetForNullableAnnotations() { var inputs = new[] { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }; Func<int, int, NullableAnnotation> getResult = (i, j) => NullableAnnotationExtensions.Meet(inputs[i], inputs[j]); var expected = new NullableAnnotation[3, 3] { { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }, { NullableAnnotation.Oblivious, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }, { NullableAnnotation.NotAnnotated, NullableAnnotation.NotAnnotated, NullableAnnotation.NotAnnotated }, }; AssertEqual(expected, getResult, inputs.Length); } [Fact] public void TestMeetForNullableFlowStates() { var inputs = new[] { NullableFlowState.NotNull, NullableFlowState.MaybeNull }; Func<int, int, NullableFlowState> getResult = (i, j) => inputs[i].Meet(inputs[j]); var expected = new NullableFlowState[2, 2] { { NullableFlowState.NotNull, NullableFlowState.NotNull }, { NullableFlowState.NotNull, NullableFlowState.MaybeNull }, }; AssertEqual(expected, getResult, inputs.Length); } [Fact] public void TestEnsureCompatible() { var inputs = new[] { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }; Func<int, int, NullableAnnotation> getResult = (i, j) => NullableAnnotationExtensions.EnsureCompatible(inputs[i], inputs[j]); var expected = new NullableAnnotation[3, 3] { { NullableAnnotation.Annotated, NullableAnnotation.Annotated, NullableAnnotation.NotAnnotated }, { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }, { NullableAnnotation.NotAnnotated, NullableAnnotation.NotAnnotated, NullableAnnotation.NotAnnotated }, }; AssertEqual(expected, getResult, inputs.Length); } private static void AssertEqual(NullableAnnotation[,] expected, Func<int, int, NullableAnnotation> getResult, int size) { AssertEx.Equal<NullableAnnotation>(expected, getResult, (na1, na2) => na1 == na2, na => $"NullableAnnotation.{na}", "{0,-32:G}", size); } private static void AssertEqual(NullableFlowState[,] expected, Func<int, int, NullableFlowState> getResult, int size) { AssertEx.Equal<NullableFlowState>(expected, getResult, (na1, na2) => na1 == na2, na => $"NullableFlowState.{na}", "{0,-32:G}", size); } [Fact] public void TestAbsorptionForNullableAnnotations() { foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { Assert.Equal(a, a.Meet(a.Join(b))); Assert.Equal(a, a.Join(a.Meet(b))); } } } [Fact] public void TestAbsorptionForNullableFlowStates() { foreach (var a in s_AllNullableFlowStates) { foreach (var b in s_AllNullableFlowStates) { Assert.Equal(a, a.Meet(a.Join(b))); Assert.Equal(a, a.Join(a.Meet(b))); } } } [Fact] public void TestJoinForNullableAnnotationsIsAssociative() { foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { foreach (var c in s_AllNullableAnnotations) { var leftFirst = a.Join(b).Join(c); var rightFirst = a.Join(b.Join(c)); Assert.Equal(leftFirst, rightFirst); } } } } [Fact] public void TestJoinForNullableFlowStatesIsAssociative() { foreach (var a in s_AllNullableFlowStates) { foreach (var b in s_AllNullableFlowStates) { foreach (var c in s_AllNullableFlowStates) { var leftFirst = a.Join(b).Join(c); var rightFirst = a.Join(b.Join(c)); Assert.Equal(leftFirst, rightFirst); } } } } [Fact] public void TestMeetForNullableAnnotationsIsAssociative() { foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { foreach (var c in s_AllNullableAnnotations) { var leftFirst = a.Meet(b).Meet(c); var rightFirst = a.Meet(b.Meet(c)); Assert.Equal(leftFirst, rightFirst); } } } } [Fact] public void TestMeetForNullableFlowStatesIsAssociative() { foreach (var a in s_AllNullableFlowStates) { foreach (var b in s_AllNullableFlowStates) { foreach (var c in s_AllNullableFlowStates) { var leftFirst = a.Meet(b).Meet(c); var rightFirst = a.Meet(b.Meet(c)); Assert.Equal(leftFirst, rightFirst); } } } } [Fact] public void TestEnsureCompatibleIsAssociative() { Func<bool, bool> identity = x => x; foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { foreach (var c in s_AllNullableAnnotations) { foreach (bool isPossiblyNullableReferenceTypeTypeParameter in new[] { true, false }) { var leftFirst = a.EnsureCompatible(b).EnsureCompatible(c); var rightFirst = a.EnsureCompatible(b.EnsureCompatible(c)); Assert.Equal(leftFirst, rightFirst); } } } } } [Fact] public void TestJoinForNullableAnnotationsIsCommutative() { foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { var leftFirst = a.Join(b); var rightFirst = b.Join(a); Assert.Equal(leftFirst, rightFirst); } } } [Fact] public void TestJoinForNullableFlowStatesIsCommutative() { Func<bool, bool> identity = x => x; foreach (var a in s_AllNullableFlowStates) { foreach (var b in s_AllNullableFlowStates) { var leftFirst = a.Join(b); var rightFirst = b.Join(a); Assert.Equal(leftFirst, rightFirst); } } } [Fact] public void TestMeetForNullableAnnotationsIsCommutative() { foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { var leftFirst = a.Meet(b); var rightFirst = b.Meet(a); Assert.Equal(leftFirst, rightFirst); } } } [Fact] public void TestMeetForNullableFlowStatesIsCommutative() { foreach (var a in s_AllNullableFlowStates) { foreach (var b in s_AllNullableFlowStates) { var leftFirst = a.Meet(b); var rightFirst = b.Meet(a); Assert.Equal(leftFirst, rightFirst); } } } [Fact] public void TestEnsureCompatibleIsCommutative() { foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { var leftFirst = a.EnsureCompatible(b); var rightFirst = b.EnsureCompatible(a); Assert.Equal(leftFirst, rightFirst); } } } [Fact] public void NullableT_CSharp7() { var source = @"class Program { static void F<T>(T? x) where T : struct { _ = x.Value; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7, options: WithNullableEnable()); comp.VerifyDiagnostics( // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.0", "8.0").WithLocation(1, 1) ); } [Fact] public void NullableT_WarningDisabled() { var source = @"#nullable disable //#nullable disable warnings class Program { static void F<T>(T? x) where T : struct { _ = x.Value; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void NullableT_01() { var source = @"class Program { static void F<T>(T? x) where T : struct { _ = x.Value; // 1 _ = x.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,13): warning CS8629: Nullable value type may be null. // _ = x.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(5, 13) ); } [Fact] public void NullableT_02() { var source = @"class Program { static void F<T>(T x) where T : struct { T? y = x; _ = y.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_03() { var source = @"class Program { static void F<T>(T? x) where T : struct { T y = x; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,15): error CS0266: Cannot implicitly convert type 'T?' to 'T'. An explicit conversion exists (are you missing a cast?) // T y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("T?", "T").WithLocation(5, 15), // (5,15): warning CS8629: Nullable value type may be null. // T y = x; Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(5, 15)); } [Fact] public void NullableT_04() { var source = @"class Program { static T F1<T>(T? x) where T : struct { return (T)x; // 1 } static T F2<T>() where T : struct { return (T)default(T?); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,16): warning CS8629: Nullable value type may be null. // return (T)x; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)x").WithLocation(5, 16), // (9,16): warning CS8629: Nullable value type may be null. // return (T)default(T?); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)default(T?)").WithLocation(9, 16)); } [Fact] public void NullableT_05() { var source = @"using System; class Program { static void F<T>() where T : struct { _ = nameof(Nullable<T>.HasValue); _ = nameof(Nullable<T>.Value); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_06() { var source = @"class Program { static void F<T>(T? x, T? y) where T : struct { _ = (T)x; // 1 _ = (T)x; x = y; _ = (T)x; // 2 _ = (T)x; _ = (T)y; // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,13): warning CS8629: Nullable value type may be null. // _ = (T)x; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)x").WithLocation(5, 13), // (8,13): warning CS8629: Nullable value type may be null. // _ = (T)x; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)x").WithLocation(8, 13), // (10,13): warning CS8629: Nullable value type may be null. // _ = (T)y; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)y").WithLocation(10, 13)); } [Fact] public void NullableT_07() { var source = @"class Program { static void F1((int, int) x) { (int, int)? y = x; _ = y.Value; var z = ((int, int))y; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_08() { var source = @"class Program { static void F1((int, int)? x) { var y = ((int, int))x; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,17): warning CS8629: Nullable value type may be null. // var y = ((int, int))x; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "((int, int))x").WithLocation(5, 17)); } [Fact] public void NullableT_09() { var source = @"class Program { static void F<T>(T t) where T : struct { T? x = null; _ = x.Value; // 1 T? y = default; _ = y.Value; // 2 T? z = default(T); _ = z.Value; T? w = t; _ = w.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8629: Nullable value type may be null. // _ = x.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(6, 13), // (8,13): warning CS8629: Nullable value type may be null. // _ = y.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(8, 13) ); } [WorkItem(31502, "https://github.com/dotnet/roslyn/issues/31502")] [Fact] public void NullableT_10() { var source = @"class Program { static void F<T>(T t) where T : struct { T? x = new System.Nullable<T>(); _ = x.Value; // 1 T? y = new System.Nullable<T>(t); _ = y.Value; T? z = new T?(); _ = z.Value; // 2 T? w = new T?(t); _ = w.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8629: Nullable value type may be null. // _ = x.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(6, 13), // (10,13): warning CS8629: Nullable value type may be null. // _ = z.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "z").WithLocation(10, 13) ); } [Fact] public void NullableT_11() { var source = @"class C<T> where T : struct { static void F1(T? t1) { if (t1.HasValue) _ = t1.Value; else _ = t1.Value; // 1 } static void F2(T? t2) { if (!t2.HasValue) _ = t2.Value; // 2 else _ = t2.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,17): warning CS8629: Nullable value type may be null. // _ = t1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t1").WithLocation(8, 17), // (13,17): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(13, 17) ); } [Fact] public void NullableT_12() { var source = @"class C<T> where T : struct { static void F1(T? t1) { if (t1 != null) _ = t1.Value; else _ = t1.Value; // 1 } static void F2(T? t2) { if (t2 == null) _ = t2.Value; // 2 else _ = t2.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,17): warning CS8629: Nullable value type may be null. // _ = t1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t1").WithLocation(8, 17), // (13,17): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(13, 17) ); } [Fact] public void NullableT_13() { var source = @"class C<T> where T : struct { static void F1(T? t1) { if (null != t1) _ = (T)t1; else _ = (T)t1; // 1 } static void F2(T? t2) { if (null == t2) { var o2 = (object)t2; // 2 o2.ToString(); // 3 } else { var o2 = (object)t2; o2.ToString(); } } static void F3(T? t3) { if (null == t3) { var d3 = (dynamic)t3; // 4 d3.ToString(); // 5 } else { var d3 = (dynamic)t3; d3.ToString(); } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,17): warning CS8629: Nullable value type may be null. // _ = (T)t1; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)t1").WithLocation(8, 17), // (14,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var o2 = (object)t2; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t2").WithLocation(14, 22), // (15,13): warning CS8602: Dereference of a possibly null reference. // o2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o2").WithLocation(15, 13), // (27,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var d3 = (dynamic)t3; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(dynamic)t3").WithLocation(27, 22), // (28,13): warning CS8602: Dereference of a possibly null reference. // d3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d3").WithLocation(28, 13)); } [Fact] public void NullableT_14() { var source = @"class C<T> where T : struct { static void F1(T? t1) { if (t1.HasValue) { if (t1.HasValue) _ = t1.Value; else _ = t1.Value; } } static void F2(T? t2) { if (t2 != null) { if (!t2.HasValue) _ = t2.Value; else _ = t2.Value; } } static void F3(T? t3) { if (!t3.HasValue) { if (t3 != null) _ = t3.Value; else _ = t3.Value; // 1 } } static void F4(T? t4) { if (t4 == null) { if (t4 == null) _ = t4.Value; // 2 else _ = t4.Value; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (24,22): warning CS8629: Nullable value type may be null. // else _ = t3.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t3").WithLocation(24, 22), // (31,33): warning CS8629: Nullable value type may be null. // if (t4 == null) _ = t4.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4").WithLocation(31, 33) ); } [Fact] public void NullableT_15() { var source = @"class C<T> where T : struct { static void F1(T? x1, T? y1) { _ = x1.HasValue ? x1.Value : y1.Value; // 1 } static void F2(T? x2, T? y2) { _ = !x2.HasValue ? y2.Value : // 2 x2.Value; } static void F3(T? x3, T? y3) { _ = x3.HasValue || y3.HasValue ? x3.Value : // 3 y3.Value; // 4 } static void F4(T? x4, T? y4) { _ = x4.HasValue && y4.HasValue ? (T)x4 : (T)y4; // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8629: Nullable value type may be null. // y1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y1").WithLocation(7, 13), // (12,13): warning CS8629: Nullable value type may be null. // y2.Value : // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y2").WithLocation(12, 13), // (18,13): warning CS8629: Nullable value type may be null. // x3.Value : // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x3").WithLocation(18, 13), // (19,13): warning CS8629: Nullable value type may be null. // y3.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y3").WithLocation(19, 13), // (25,13): warning CS8629: Nullable value type may be null. // (T)y4; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)y4").WithLocation(25, 13) ); } [Fact] public void NullableT_16() { var source = @"class C<T> where T : struct { static void F1(T? x1, T? y1) { _ = x1 != null ? x1.Value : y1.Value; // 1 } static void F2(T? x2, T? y2) { _ = x2 == null ? y2.Value : // 2 x2.Value; } static void F3(T? x3, T? y3) { _ = x3 != null || y3 != null ? x3.Value : // 3 y3.Value; // 4 } static void F4(T? x4, T? y4) { _ = x4 != null && y4 != null ? (T)x4 : (T)y4; // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8629: Nullable value type may be null. // y1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y1").WithLocation(7, 13), // (12,13): warning CS8629: Nullable value type may be null. // y2.Value : // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y2").WithLocation(12, 13), // (18,13): warning CS8629: Nullable value type may be null. // x3.Value : // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x3").WithLocation(18, 13), // (19,13): warning CS8629: Nullable value type may be null. // y3.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y3").WithLocation(19, 13), // (25,13): warning CS8629: Nullable value type may be null. // (T)y4; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)y4").WithLocation(25, 13) ); } [Fact, WorkItem(33924, "https://github.com/dotnet/roslyn/issues/33924")] public void NullableT_17() { var source = @"class C<T> where T : struct { static void F1(T? x1, T? y1) { _ = (T)(x1 != null ? x1 : y1); // 1 } static void F2(T? x2, T? y2) { if (y2 == null) return; _ = (T)(x2 != null ? x2 : y2); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,13): warning CS8629: Nullable value type may be null. // _ = (T)(x1 != null ? x1 : y1); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)(x1 != null ? x1 : y1)").WithLocation(5, 13)); } [Fact] public void NullableT_18() { var source = @"class C<T> where T : struct { static void F1(T? x1, T? y1) { object? z1 = x1 != null ? (object?)x1 : y1; _ = z1/*T:object?*/.ToString(); // 1 dynamic? w1 = x1 != null ? (dynamic?)x1 : y1; _ = w1/*T:dynamic?*/.ToString(); // 2 } static void F2(T? x2, T? y2) { if (y2 == null) return; object? z2 = x2 != null ? (object?)x2 : y2; _ = z2/*T:object?*/.ToString(); // 3 dynamic? w2 = x2 != null ? (dynamic?)x2 : y2; _ = w2/*T:dynamic?*/.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8602: Dereference of a possibly null reference. // _ = z1/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1").WithLocation(6, 13), // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = w1/*T:dynamic?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w1").WithLocation(8, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = z2/*T:object!*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2").WithLocation(14, 13), // (16,13): warning CS8602: Dereference of a possibly null reference. // _ = w2/*T:dynamic!*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w2").WithLocation(16, 13) ); comp.VerifyTypes(); } [Fact] public void NullableT_19() { var source = @"#pragma warning disable 0649 struct A { internal B? B; } struct B { internal C? C; } struct C { } class Program { static void F1(A? na1) { if (na1?.B?.C != null) { _ = na1.Value.B.Value.C.Value; } else { A a1 = na1.Value; // 1 B b1 = a1.B.Value; // 2 C c1 = b1.C.Value; // 3 } } static void F2(A? na2) { if (na2?.B?.C != null) { _ = (C)((B)((A)na2).B).C; } else { A a2 = (A)na2; // 4 B b2 = (B)a2.B; // 5 C c2 = (C)b2.C; // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,20): warning CS8629: Nullable value type may be null. // A a1 = na1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "na1").WithLocation(23, 20), // (24,20): warning CS8629: Nullable value type may be null. // B b1 = a1.B.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "a1.B").WithLocation(24, 20), // (25,20): warning CS8629: Nullable value type may be null. // C c1 = b1.C.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "b1.C").WithLocation(25, 20), // (36,20): warning CS8629: Nullable value type may be null. // A a2 = (A)na2; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(A)na2").WithLocation(36, 20), // (37,20): warning CS8629: Nullable value type may be null. // B b2 = (B)a2.B; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(B)a2.B").WithLocation(37, 20), // (38,20): warning CS8629: Nullable value type may be null. // C c2 = (C)b2.C; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(C)b2.C").WithLocation(38, 20) ); } [Fact] public void NullableT_20() { var source = @"#pragma warning disable 0649 struct A { internal B? B; } struct B { } class Program { static void F1(A? na1) { if (na1?.B != null) { var a1 = (object)na1; a1.ToString(); } else { var a1 = (object)na1; // 1 a1.ToString(); // 2 } } static void F2(A? na2) { if (na2?.B != null) { var a2 = (System.ValueType)na2; a2.ToString(); } else { var a2 = (System.ValueType)na2; // 3 a2.ToString(); // 4 } } static void F3(A? na3) { if (na3?.B != null) { var a3 = (A)na3; var b3 = (object)a3.B; b3.ToString(); } else { var a3 = (A)na3; // 5 var b3 = (object)a3.B; // 6 b3.ToString(); // 7 } } static void F4(A? na4) { if (na4?.B != null) { var a4 = (A)na4; var b4 = (System.ValueType)a4.B; b4.ToString(); } else { var a4 = (A)na4; // 8 var b4 = (System.ValueType)a4.B; // 9 b4.ToString(); // 10 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var a1 = (object)na1; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)na1").WithLocation(20, 22), // (21,13): warning CS8602: Dereference of a possibly null reference. // a1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a1").WithLocation(21, 13), // (33,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var a2 = (System.ValueType)na2; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(System.ValueType)na2").WithLocation(33, 22), // (34,13): warning CS8602: Dereference of a possibly null reference. // a2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2").WithLocation(34, 13), // (47,22): warning CS8629: Nullable value type may be null. // var a3 = (A)na3; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(A)na3").WithLocation(47, 22), // (48,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var b3 = (object)a3.B; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)a3.B").WithLocation(48, 22), // (49,13): warning CS8602: Dereference of a possibly null reference. // b3.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b3").WithLocation(49, 13), // (62,22): warning CS8629: Nullable value type may be null. // var a4 = (A)na4; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(A)na4").WithLocation(62, 22), // (63,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var b4 = (System.ValueType)a4.B; // 9 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(System.ValueType)a4.B").WithLocation(63, 22), // (64,13): warning CS8602: Dereference of a possibly null reference. // b4.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b4").WithLocation(64, 13)); } [Fact] public void NullableT_21() { var source = @"#pragma warning disable 0649 struct A { internal B? B; public static implicit operator C(A a) => new C(); } struct B { public static implicit operator C(B b) => new C(); } class C { } class Program { static void F1(A? na1) { if (na1?.B != null) { var c1 = (C)na1; c1.ToString(); } else { var c1 = (C)na1; // 1 c1.ToString(); // 2 } } static void F2(A? na2) { if (na2?.B != null) { var a2 = (A)na2; var c2 = (C)a2.B; c2.ToString(); } else { var a2 = (A)na2; // 3 var c2 = (C)a2.B; // 4 c2.ToString(); // 5 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (25,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var c1 = (C)na1; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)na1").WithLocation(25, 22), // (26,13): warning CS8602: Dereference of a possibly null reference. // c1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(26, 13), // (39,22): warning CS8629: Nullable value type may be null. // var a2 = (A)na2; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(A)na2").WithLocation(39, 22), // (40,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var c2 = (C)a2.B; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)a2.B").WithLocation(40, 22), // (41,13): warning CS8602: Dereference of a possibly null reference. // c2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(41, 13)); } [Fact] public void NullableT_22() { var source = @"#pragma warning disable 0649 struct S { internal C? C; } class C { internal S? S; } class Program { static void F1(S? ns) { if (ns?.C != null) { _ = ns.Value.C.ToString(); } else { var s = ns.Value; // 1 var c = s.C; c.ToString(); // 2 } } static void F2(C? nc) { if (nc?.S != null) { _ = nc.S.Value; } else { var ns = nc.S; // 3 _ = ns.Value; // 4 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,21): warning CS8629: Nullable value type may be null. // var s = ns.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ns").WithLocation(20, 21), // (22,13): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(22, 13), // (34,22): warning CS8602: Dereference of a possibly null reference. // var ns = nc.S; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "nc").WithLocation(34, 22), // (35,17): warning CS8629: Nullable value type may be null. // _ = ns.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ns").WithLocation(35, 17) ); } [Fact] public void NullableT_IntToLong() { var source = @"class Program { // int -> long? static void F1(int i) { var nl1 = (long?)i; _ = nl1.Value; long? nl2 = i; _ = nl2.Value; int? ni = i; long? nl3 = ni; _ = nl3.Value; } // int? -> long? static void F2(int? ni) { if (ni.HasValue) { long? nl1 = ni; _ = nl1.Value; var nl2 = (long?)ni; _ = nl2.Value; } else { long? nl3 = ni; _ = nl3.Value; // 1 var nl4 = (long?)ni; _ = nl4.Value; // 2 } } // int? -> long static void F3(int? ni) { if (ni.HasValue) { _ = (long)ni; } else { _ = (long)ni; // 3 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (27,17): warning CS8629: Nullable value type may be null. // _ = nl3.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl3").WithLocation(27, 17), // (29,17): warning CS8629: Nullable value type may be null. // _ = nl4.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl4").WithLocation(29, 17), // (41,17): warning CS8629: Nullable value type may be null. // _ = (long)ni; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(long)ni").WithLocation(41, 17) ); } [Fact] public void NullableT_LongToStruct() { var source = @"struct S { public static implicit operator S(long l) => new S(); } class Program { // int -> long -> S -> S? static void F1(int i) { var s1 = (S?)i; _ = s1.Value; S? s2 = i; _ = s2.Value; int? ni = i; S? s3 = ni; _ = s3.Value; } // int? -> long? -> S? static void F2(int? ni) { if (ni.HasValue) { var s1 = (S?)ni; _ = s1.Value; S? s2 = ni; _ = s2.Value; } else { var s3 = (S?)ni; _ = s3.Value; // 1 S? s4 = ni; _ = s4.Value; // 2 } } // int? -> long? -> S? -> S static void F3(int? ni) { if (ni.HasValue) { _ = (S)ni; } else { _ = (S)ni; // 3 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (31,17): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(31, 17), // (33,17): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(33, 17), // (45,20): warning CS8629: Nullable value type may be null. // _ = (S)ni; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ni").WithLocation(45, 20) ); } [Fact] public void NullableT_LongToNullableStruct() { var source = @"struct S { public static implicit operator S?(long l) => new S(); } class Program { // int -> long -> S? static void F1(int i) { var s1 = (S?)i; _ = s1.Value; // 1 S? s2 = i; _ = s2.Value; // 2 int? ni = i; S? s3 = ni; _ = s3.Value; // 3 } // int? -> long? -> S? static void F2(int? ni) { if (ni.HasValue) { var s1 = (S?)ni; _ = s1.Value; // 4 S? s2 = ni; _ = s2.Value; // 5 } else { var s3 = (S?)ni; _ = s3.Value; // 6 S? s4 = ni; _ = s4.Value; // 7 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(13, 13), // (16,13): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(16, 13), // (24,17): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(24, 17), // (26,17): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(26, 17), // (31,17): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(31, 17), // (33,17): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(33, 17) ); } [Fact] public void NullableT_NullableLongToStruct() { var source = @"struct S { public static implicit operator S(long? l) => new S(); } class Program { // int -> int? -> long? -> S static void F1(int i) { _ = (S)i; S s = i; } // int? -> long? -> S static void F2(int? ni) { _ = (S)ni; S s = ni; } // int? -> long? -> S -> S? static void F3(int? ni) { var ns1 = (S?)ni; _ = ns1.Value; S? ns2 = ni; _ = ns1.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_NullableLongToNullableStruct() { var source = @"struct S { public static implicit operator S?(long? l) => new S(); } class Program { // int -> int? -> long? -> S static void F1(int i) { _ = (S)i; // 1 } // int? -> long? -> S? static void F2(int? ni) { if (ni.HasValue) { var ns1 = (S?)ni; _ = ns1.Value; // 2 S? ns2 = ni; _ = ns2.Value; // 3 } else { var ns3 = (S?)ni; _ = ns3.Value; // 4 S? ns4 = ni; _ = ns4.Value; // 5 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8629: Nullable value type may be null. // _ = (S)i; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(S)i").WithLocation(10, 13), // (18,17): warning CS8629: Nullable value type may be null. // _ = ns1.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ns1").WithLocation(18, 17), // (20,17): warning CS8629: Nullable value type may be null. // _ = ns2.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ns2").WithLocation(20, 17), // (25,17): warning CS8629: Nullable value type may be null. // _ = ns3.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ns3").WithLocation(25, 17), // (27,17): warning CS8629: Nullable value type may be null. // _ = ns4.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ns4").WithLocation(27, 17) ); } [Fact] public void NullableT_StructToInt() { var source = @"struct S { public static implicit operator int(S s) => 0; } class Program { // S -> int -> long? static void F1(S s) { var nl1 = (long?)s; _ = nl1.Value; long? nl2 = s; _ = nl2.Value; } // S? -> int? -> long? static void F2(S? ns) { if (ns.HasValue) { var nl1 = (long?)ns; _ = nl1.Value; long? nl2 = ns; _ = nl2.Value; } else { var nl1 = (long?)ns; _ = nl1.Value; // 1 long? nl2 = ns; _ = nl2.Value; // 2 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (28,17): warning CS8629: Nullable value type may be null. // _ = nl1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl1").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = nl2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl2").WithLocation(30, 17) ); } [Fact] public void NullableT_StructToNullableInt() { var source = @"struct S { public static implicit operator int?(S s) => 0; } class Program { // S -> int? -> long? static void F1(S s) { var nl1 = (long?)s; _ = nl1.Value; // 1 long? nl2 = s; _ = nl2.Value; // 2 } // S? -> int? -> long? static void F2(S? ns) { if (ns.HasValue) { var nl1 = (long?)ns; _ = nl1.Value; // 3 long? nl2 = ns; _ = nl2.Value; // 4 } else { var nl1 = (long?)ns; _ = nl1.Value; // 5 long? nl2 = ns; _ = nl2.Value; // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = nl1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = nl2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = nl1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = nl2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl2").WithLocation(23, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = nl1.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl1").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = nl2.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl2").WithLocation(30, 17) ); } [Fact] public void NullableT_NullableStructToInt() { var source = @"struct S { public static implicit operator int(S? s) => 0; } class Program { // S -> S? -> int -> long static void F1(S s) { _ = (long)s; long l2 = s; } // S? -> int -> long static void F2(S? ns) { if (ns.HasValue) { _ = (long)ns; long l2 = ns; } else { _ = (long)ns; long l2 = ns; } } // S? -> int -> long -> long? static void F3(S? ns) { if (ns.HasValue) { var nl1 = (long?)ns; _ = nl1.Value; long? nl2 = ns; _ = nl2.Value; } else { var nl1 = (long?)ns; _ = nl1.Value; long? nl2 = ns; _ = nl2.Value; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_NullableStructToNullableInt() { var source = @"struct S { public static implicit operator int?(S? s) => 0; } class Program { // S -> S? -> int? -> long? static void F1(S s) { var nl1 = (long?)s; _ = nl1.Value; // 1 long? nl2 = s; _ = nl2.Value; // 2 } // S? -> int? -> long? static void F2(S? ns) { if (ns.HasValue) { var nl1 = (long?)ns; _ = nl1.Value; // 3 long? nl2 = ns; _ = nl2.Value; // 4 } else { var nl3 = (long?)ns; _ = nl3.Value; // 5 long? nl4 = ns; _ = nl4.Value; // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = nl1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = nl2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = nl1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = nl2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl2").WithLocation(23, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = nl3.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl3").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = nl4.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl4").WithLocation(30, 17) ); } [Fact] [WorkItem(35334, "https://github.com/dotnet/roslyn/issues/35334")] public void NullableT_StructToClass() { var source = @"struct S { public static implicit operator C(S s) => new C(); } class C { } class Program { // S -> C static void F1(S s) { var c1 = (C)s; _ = c1.ToString(); C c2 = s; _ = c2.ToString(); } // S? -> C? static void F2(S? ns) { if (ns.HasValue) { var c1 = (C?)ns; _ = c1.ToString(); // 1 C? c2 = ns; _ = c2.ToString(); } else { var c3 = (C?)ns; _ = c3.ToString(); // 2 C? c4 = ns; _ = c4.ToString(); // 3 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(24, 17), // (31,17): warning CS8602: Dereference of a possibly null reference. // _ = c3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c3").WithLocation(31, 17), // (33,17): warning CS8602: Dereference of a possibly null reference. // _ = c4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c4").WithLocation(33, 17)); } [Fact] public void NullableT_StructToNullableClass() { var source = @"struct S { public static implicit operator C?(S s) => new C(); } class C { } class Program { // S -> C? static void F1(S s) { var c1 = (C?)s; _ = c1.ToString(); // 1 C? c2 = s; _ = c2.ToString(); // 2 } // S? -> C? static void F2(S? ns) { if (ns.HasValue) { var c1 = (C?)ns; _ = c1.ToString(); // 3 C? c2 = ns; _ = c2.ToString(); // 4 } else { var c3 = (C?)ns; _ = c3.ToString(); // 5 C? c4 = ns; _ = c4.ToString(); // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(14, 13), // (16,13): warning CS8602: Dereference of a possibly null reference. // _ = c2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(16, 13), // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(24, 17), // (26,17): warning CS8602: Dereference of a possibly null reference. // _ = c2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(26, 17), // (31,17): warning CS8602: Dereference of a possibly null reference. // _ = c3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c3").WithLocation(31, 17), // (33,17): warning CS8602: Dereference of a possibly null reference. // _ = c4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c4").WithLocation(33, 17)); } [Fact] [WorkItem(35334, "https://github.com/dotnet/roslyn/issues/35334")] public void NullableT_NullableStructToClass() { var source = @"struct S { public static implicit operator C(S? s) => new C(); } class C { } class Program { // S -> C static void F1(S s) { var c1 = (C)s; _ = c1.ToString(); C c2 = s; _ = c2.ToString(); } // S? -> C? static void F2(S? ns) { if (ns.HasValue) { var c1 = (C?)ns; _ = c1.ToString(); // 1 C? c2 = ns; _ = c2.ToString(); } else { var c3 = (C?)ns; _ = c3.ToString(); // 2 C? c4 = ns; _ = c4.ToString(); } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(24, 17), // (31,17): warning CS8602: Dereference of a possibly null reference. // _ = c3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c3").WithLocation(31, 17)); } [Fact] public void NullableT_NullableStructToNullableClass() { var source = @"struct S { public static implicit operator C?(S? s) => new C(); } class C { } class Program { // S -> C? static void F1(S s) { var c1 = (C?)s; _ = c1.ToString(); // 1 C? c2 = s; _ = c2.ToString(); // 2 } // S? -> C? static void F2(S? ns) { if (ns.HasValue) { var c1 = (C?)ns; _ = c1.ToString(); // 3 C? c2 = ns; _ = c2.ToString(); // 4 } else { var c3 = (C?)ns; _ = c3.ToString(); // 5 C? c4 = ns; _ = c4.ToString(); // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(14, 13), // (16,13): warning CS8602: Dereference of a possibly null reference. // _ = c2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(16, 13), // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(24, 17), // (26,17): warning CS8602: Dereference of a possibly null reference. // _ = c2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(26, 17), // (31,17): warning CS8602: Dereference of a possibly null reference. // _ = c3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c3").WithLocation(31, 17), // (33,17): warning CS8602: Dereference of a possibly null reference. // _ = c4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c4").WithLocation(33, 17)); } [Fact] public void NullableT_ClassToStruct() { var source = @"struct S { public static implicit operator S(C c) => new S(); } class C { } class Program { // C -> S static void F1(C c) { _ = (S)c; S s2 = c; } // C? -> S? static void F2(bool b, C? nc) { if (nc != null) { var s1 = (S?)nc; _ = s1.Value; S? s2 = nc; _ = s2.Value; } else { if (b) { var s3 = (S?)nc; // 1 _ = s3.Value; } if (b) { S? s4 = nc; // 2 _ = s4.Value; } } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (30,30): warning CS8604: Possible null reference argument for parameter 'c' in 'S.implicit operator S(C c)'. // var s3 = (S?)nc; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nc").WithArguments("c", "S.implicit operator S(C c)").WithLocation(30, 30), // (35,25): warning CS8604: Possible null reference argument for parameter 'c' in 'S.implicit operator S(C c)'. // S? s4 = nc; // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nc").WithArguments("c", "S.implicit operator S(C c)").WithLocation(35, 25)); } [Fact] public void NullableT_ClassToNullableStruct() { var source = @"struct S { public static implicit operator S?(C c) => new S(); } class C { } class Program { // C -> S? static void F1(C c) { var s1 = (S?)c; _ = s1.Value; // 1 S? s2 = c; _ = s2.Value; // 2 } // C? -> S? static void F2(bool b, C? nc) { if (nc != null) { var s1 = (S?)nc; _ = s1.Value; // 3 S? s2 = nc; _ = s2.Value; // 4 } else { if (b) { var s3 = (S?)nc; // 5 _ = s3.Value; // 6 } if (b) { S? s4 = nc; // 7 _ = s4.Value; // 8 } } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(14, 13), // (16,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(16, 13), // (24,17): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(24, 17), // (26,17): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(26, 17), // (32,30): warning CS8604: Possible null reference argument for parameter 'c' in 'S.implicit operator S?(C c)'. // var s3 = (S?)nc; // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nc").WithArguments("c", "S.implicit operator S?(C c)").WithLocation(32, 30), // (33,21): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(33, 21), // (37,25): warning CS8604: Possible null reference argument for parameter 'c' in 'S.implicit operator S?(C c)'. // S? s4 = nc; // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nc").WithArguments("c", "S.implicit operator S?(C c)").WithLocation(37, 25), // (38,21): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(38, 21) ); } [Fact] public void NullableT_NullableClassToStruct() { var source = @"struct S { public static implicit operator S(C? c) => new S(); } class C { } class Program { // C -> S static void F1(C c) { _ = (S)c; S s2 = c; } // C? -> S? static void F2(C? nc) { if (nc != null) { var s1 = (S?)nc; _ = s1.Value; S? s2 = nc; _ = s2.Value; } else { var s3 = (S?)nc; _ = s3.Value; S? s4 = nc; _ = s4.Value; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_NullableClassToNullableStruct() { var source = @"struct S { public static implicit operator S?(C? c) => new S(); } class C { } class Program { // C -> S? static void F1(C c) { var s1 = (S?)c; _ = s1.Value; // 1 S? s2 = c; _ = s2.Value; // 2 } // C? -> S? static void F2(C? nc) { if (nc != null) { var s1 = (S?)nc; _ = s1.Value; // 3 S? s2 = nc; _ = s2.Value; // 4 } else { var s3 = (S?)nc; _ = s3.Value; // 5 S? s4 = nc; _ = s4.Value; // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(14, 13), // (16,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(16, 13), // (24,17): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(24, 17), // (26,17): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(26, 17), // (31,17): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(31, 17), // (33,17): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(33, 17) ); } // https://github.com/dotnet/roslyn/issues/31675: Add similar tests for // type parameters with `class?` constraint and Nullable<T> constraint. [Fact] public void NullableT_StructToTypeParameterUnconstrained() { var source = @"struct S<T> { public static implicit operator T(S<T> s) => throw null!; } class C<T> { // S<T> -> T static void F1(S<T> s) { var t1 = (T)s; _ = t1.ToString(); // 1 T t2 = s; _ = t2.ToString(); // 2 } // S<T>? -> T static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T)ns; _ = t1.ToString(); // 3 } else { var t2 = (T)ns; _ = t2.ToString(); // 4 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(11, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = t2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(13, 13), // (21,17): warning CS8602: Dereference of a possibly null reference. // _ = t1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(21, 17), // (26,17): warning CS8602: Dereference of a possibly null reference. // _ = t2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(26, 17)); } [Fact] public void NullableT_NullableStructToTypeParameterUnconstrained() { var source = @"struct S<T> { public static implicit operator T(S<T>? s) => throw null!; } class C<T> { // S<T> -> T static void F1(S<T> s) { var t1 = (T)s; _ = t1.ToString(); // 1 T t2 = s; _ = t2.ToString(); // 2 } // S<T>? -> T static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T)ns; _ = t1.ToString(); // 3 } else { var t2 = (T)ns; _ = t2.ToString(); // 4 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(11, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = t2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(13, 13), // (21,17): warning CS8602: Dereference of a possibly null reference. // _ = t1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(21, 17), // (26,17): warning CS8602: Dereference of a possibly null reference. // _ = t2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(26, 17)); } [Fact] [WorkItem(35334, "https://github.com/dotnet/roslyn/issues/35334")] public void NullableT_StructToTypeParameterClassConstraint() { var source = @"struct S<T> { public static implicit operator T(S<T> s) => throw null!; } class C<T> where T : class { // S<T> -> T static void F1(S<T> s) { var t1 = (T)s; _ = t1.ToString(); T t2 = s; _ = t2.ToString(); } // S<T>? -> T? static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T?)ns; _ = t1.ToString(); // 1 T? t2 = ns; _ = t2.ToString(); } else { var t3 = (T?)ns; _ = t3.ToString(); // 2 T? t4 = ns; _ = t4.ToString(); // 3 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (21,17): warning CS8602: Dereference of a possibly null reference. // _ = t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(21, 17), // (28,17): warning CS8602: Dereference of a possibly null reference. // _ = t3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3").WithLocation(28, 17), // (30,17): warning CS8602: Dereference of a possibly null reference. // _ = t4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t4").WithLocation(30, 17)); } [Fact] [WorkItem(35334, "https://github.com/dotnet/roslyn/issues/35334")] public void NullableT_NullableStructToTypeParameterClassConstraint() { var source = @"struct S<T> { public static implicit operator T(S<T>? s) => throw null!; } class C<T> where T : class { // S<T> -> T static void F1(S<T> s) { var t1 = (T)s; _ = t1.ToString(); T t2 = s; _ = t2.ToString(); } // S<T>? -> T? static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T?)ns; _ = t1.ToString(); // 1 T? t2 = ns; _ = t2.ToString(); } else { var t3 = (T?)ns; _ = t3.ToString(); // 2 T? t4 = ns; _ = t4.ToString(); } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (21,17): warning CS8602: Dereference of a possibly null reference. // _ = t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(21, 17), // (28,17): warning CS8602: Dereference of a possibly null reference. // _ = t3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3").WithLocation(28, 17)); } [Fact] public void NullableT_StructToTypeParameterStructConstraint() { var source = @"struct S<T> { public static implicit operator T(S<T> s) => throw null!; } class C<T> where T : struct { // S<T> -> T static void F1(S<T> s) { var t1 = (T)s; _ = t1.ToString(); T t2 = s; _ = t2.ToString(); } // S<T>? -> T? static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T?)ns; _ = t1.Value; T? t2 = ns; _ = t2.Value; } else { var t3 = (T?)ns; _ = t3.Value; // 1 T? t4 = ns; _ = t4.Value; // 2 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (28,17): warning CS8629: Nullable value type may be null. // _ = t3.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t3").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = t4.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4").WithLocation(30, 17) ); } [Fact] public void NullableT_NullableStructToTypeParameterStructConstraint() { var source = @"struct S<T> { public static implicit operator T(S<T>? s) => throw null!; } class C<T> where T : struct { // S<T> -> T static void F1(S<T> s) { var t1 = (T)s; _ = t1.ToString(); T t2 = s; _ = t2.ToString(); } // S<T>? -> T? static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T?)ns; _ = t1.Value; T? t2 = ns; _ = t2.Value; } else { var t3 = (T?)ns; _ = t3.Value; T? t4 = ns; _ = t4.Value; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_StructToNullableTypeParameterStructConstraint() { var source = @"struct S<T> where T : struct { public static implicit operator T?(S<T> s) => throw null!; } class C<T> where T : struct { // S<T> -> T? static void F1(S<T> s) { var t1 = (T?)s; _ = t1.Value; // 1 T? t2 = s; _ = t2.Value; // 2 } // S<T>? -> T? static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T?)ns; _ = t1.Value; // 3 T? t2 = ns; _ = t2.Value; // 4 } else { var t3 = (T?)ns; // 5 _ = t3.Value; // 6 T? t4 = ns; // 7 _ = t4.Value; // 8 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = t1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = t1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(23, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = t3.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t3").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = t4.Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4").WithLocation(30, 17) ); } [Fact] public void NullableT_NullableStructToNullableTypeParameterStructConstraint() { var source = @"struct S<T> where T : struct { public static implicit operator T?(S<T>? s) => throw null!; } class C<T> where T : struct { // S<T> -> T? static void F1(S<T> s) { var t1 = (T?)s; _ = t1.Value; // 1 T? t2 = s; _ = t2.Value; // 2 } // S<T>? -> T? static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T?)ns; _ = t1.Value; // 3 T? t2 = ns; _ = t2.Value; // 4 } else { var t3 = (T?)ns; _ = t3.Value; // 5 T? t4 = ns; _ = t4.Value; // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = t1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = t1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(23, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = t3.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t3").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = t4.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4").WithLocation(30, 17) ); } [Fact] public void NullableT_TypeParameterUnconstrainedToStruct() { var source = @"struct S<T> { public static implicit operator S<T>(T t) => throw null!; } class C<T> { // T -> S<T> static void F1(T t) { _ = (S<T>)t; S<T> s2 = t; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_TypeParameterUnconstrainedToNullableStruct() { var source = @"struct S<T> { public static implicit operator S<T>?(T t) => throw null!; } class C<T> { // T -> S<T>? static void F1(T t) { var s1 = (S<T>?)t; _ = s1.Value; // 1 S<T>? s2 = t; _ = s2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(13, 13) ); } [Fact] public void NullableT_TypeParameterClassConstraintToStruct() { var source = @"struct S<T> { public static implicit operator S<T>(T t) => throw null!; } class C<T> where T : class { // T -> S<T> static void F1(T t) { _ = (S<T>)t; S<T> s2 = t; } // T? -> S<T>? static void F2(bool b, T? nt) { if (nt != null) { var s1 = (S<T>?)nt; _ = s1.Value; S<T>? s2 = nt; _ = s2.Value; } else { if (b) { var s3 = (S<T>?)nt; // 1 _ = s3.Value; } if (b) { S<T>? s4 = nt; // 2 _ = s4.Value; } } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (27,33): warning CS8604: Possible null reference argument for parameter 't' in 'S<T>.implicit operator S<T>(T t)'. // var s3 = (S<T>?)nt; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nt").WithArguments("t", "S<T>.implicit operator S<T>(T t)").WithLocation(27, 33), // (32,28): warning CS8604: Possible null reference argument for parameter 't' in 'S<T>.implicit operator S<T>(T t)'. // S<T>? s4 = nt; // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nt").WithArguments("t", "S<T>.implicit operator S<T>(T t)").WithLocation(32, 28)); } [Fact] public void NullableT_TypeParameterClassConstraintToNullableStruct() { var source = @"struct S<T> { public static implicit operator S<T>?(T t) => throw null!; } class C<T> where T : class { // T -> S<T>? static void F1(T t) { var s1 = (S<T>?)t; _ = s1.Value; // 1 S<T>? s2 = t; _ = s2.Value; // 2 } // T? -> S<T>? static void F2(bool b, T? nt) { if (nt != null) { var s1 = (S<T>?)nt; _ = s1.Value; // 3 S<T>? s2 = nt; _ = s2.Value; // 4 } else { if (b) { var s3 = (S<T>?)nt; // 5 _ = s3.Value; // 6 } if (b) { S<T>? s4 = nt; // 7 _ = s4.Value; // 8 } } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(23, 17), // (29,33): warning CS8604: Possible null reference argument for parameter 't' in 'S<T>.implicit operator S<T>?(T t)'. // var s3 = (S<T>?)nt; // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nt").WithArguments("t", "S<T>.implicit operator S<T>?(T t)").WithLocation(29, 33), // (30,21): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(30, 21), // (34,28): warning CS8604: Possible null reference argument for parameter 't' in 'S<T>.implicit operator S<T>?(T t)'. // S<T>? s4 = nt; // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nt").WithArguments("t", "S<T>.implicit operator S<T>?(T t)").WithLocation(34, 28), // (35,21): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(35, 21) ); } [Fact] public void NullableT_TypeParameterStructConstraintToStruct() { var source = @"struct S<T> { public static implicit operator S<T>(T t) => throw null!; } class C<T> where T : struct { // T -> S<T> static void F1(T t) { _ = (S<T>)t; S<T> s2 = t; } // T? -> S<T>? static void F2(T? nt) { if (nt != null) { var s1 = (S<T>?)nt; _ = s1.Value; S<T>? s2 = nt; _ = s2.Value; } else { var s3 = (S<T>?)nt; _ = s3.Value; // 1 S<T>? s4 = nt; _ = s4.Value; // 2 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (26,17): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(26, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(28, 17) ); } [Fact] public void NullableT_TypeParameterStructConstraintToNullableStruct() { var source = @"struct S<T> { public static implicit operator S<T>?(T t) => throw null!; } class C<T> where T : struct { // T -> S<T>? static void F1(T t) { var s1 = (S<T>?)t; _ = s1.Value; // 1 S<T>? s2 = t; _ = s2.Value; // 2 } // T? -> S<T>? static void F2(T? nt) { if (nt != null) { var s1 = (S<T>?)nt; _ = s1.Value; // 3 S<T>? s2 = nt; _ = s2.Value; // 4 } else { var s3 = (S<T>?)nt; // 5 _ = s3.Value; // 6 S<T>? s4 = nt; // 7 _ = s4.Value; // 8 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(23, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(30, 17) ); } [Fact] public void NullableT_NullableTypeParameterStructConstraintToStruct() { var source = @"struct S<T> where T : struct { public static implicit operator S<T>(T? t) => throw null!; } class C<T> where T : struct { // T -> S<T> static void F1(T t) { _ = (S<T>)t; S<T> s2 = t; } // T? -> S<T>? static void F2(T? nt) { if (nt != null) { var s1 = (S<T>?)nt; _ = s1.Value; S<T>? s2 = nt; _ = s2.Value; } else { var s3 = (S<T>?)nt; _ = s3.Value; S<T>? s4 = nt; _ = s4.Value; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_NullableTypeParameterStructConstraintToNullableStruct() { var source = @"struct S<T> where T : struct { public static implicit operator S<T>?(T? t) => throw null!; } class C<T> where T : struct { // T -> S<T>? static void F1(T t) { var s1 = (S<T>?)t; _ = s1.Value; // 1 S<T>? s2 = t; _ = s2.Value; // 2 } // T? -> S<T>? static void F2(T? nt) { if (nt != null) { var s1 = (S<T>?)nt; _ = s1.Value; // 3 S<T>? s2 = nt; _ = s2.Value; // 4 } else { var s3 = (S<T>?)nt; _ = s3.Value; // 5 S<T>? s4 = nt; _ = s4.Value; // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(23, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(30, 17) ); } [Fact] public void NullableT_ValueTypeConstraint_01() { var source = @"abstract class A<T> { internal abstract void F<U>(U x) where U : T; } class B1 : A<int> { internal override void F<U>(U x) { int? y = x; _ = y.Value; _ = ((int?)x).Value; } } class B2 : A<int?> { internal override void F<U>(U x) { int? y = x; _ = y.Value; // 1 _ = ((int?)x).Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // Conversions are not allowed from U to int in B1.F or from U to int? in B2.F, // so those conversions are not handled in NullableWalker either. comp.VerifyDiagnostics( // (9,18): error CS0029: Cannot implicitly convert type 'U' to 'int?' // int? y = x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("U", "int?").WithLocation(9, 18), // (11,14): error CS0030: Cannot convert type 'U' to 'int?' // _ = ((int?)x).Value; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)x").WithArguments("U", "int?").WithLocation(11, 14), // (18,18): error CS0029: Cannot implicitly convert type 'U' to 'int?' // int? y = x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("U", "int?").WithLocation(18, 18), // (19,13): warning CS8629: Nullable value type may be null. // _ = y.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(19, 13), // (20,14): error CS0030: Cannot convert type 'U' to 'int?' // _ = ((int?)x).Value; // 2 Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)x").WithArguments("U", "int?").WithLocation(20, 14)); } [Fact] public void NullableT_ValueTypeConstraint_02() { var source = @"abstract class A<T> { internal abstract void F<U>(T t) where U : T; } class B1 : A<int?> { internal override void F<U>(int? t) { U u = t; object? o = u; o.ToString(); // 1 } } class B2 : A<int?> { internal override void F<U>(int? t) { if (t == null) return; U u = t; object? o = u; o.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,15): error CS0029: Cannot implicitly convert type 'int?' to 'U' // U u = t; Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("int?", "U").WithLocation(9, 15), // (11,9): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(11, 9), // (19,15): error CS0029: Cannot implicitly convert type 'int?' to 'U' // U u = t; Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("int?", "U").WithLocation(19, 15)); } [Fact] public void NullableT_ValueTypeConstraint_03() { var source = @"abstract class A<T> { internal abstract void F<U>(T t) where U : T; } class B1 : A<int?> { internal override void F<U>(int? t) { U u = (U)(object?)t; object? o = u; o.ToString(); // 1 } } class B2 : A<int?> { internal override void F<U>(int? t) { if (t == null) return; U u = (U)(object?)t; object? o = u; o.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(11, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(21, 9)); } [Fact] public void NullableT_Box() { var source = @"class Program { static void F1<T>(T? x1, T? y1) where T : struct { if (x1 == null) return; ((object?)x1).ToString(); // 1 ((object?)y1).ToString(); // 2 } static void F2<T>(T? x2, T? y2) where T : struct { if (x2 == null) return; object? z2 = x2; z2.ToString(); object? w2 = y2; w2.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // ((object?)x1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object?)x1").WithLocation(6, 10), // (7,10): warning CS8602: Dereference of a possibly null reference. // ((object?)y1).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object?)y1").WithLocation(7, 10), // (15,9): warning CS8602: Dereference of a possibly null reference. // w2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w2").WithLocation(15, 9) ); } [Fact] public void NullableT_Box_ValueTypeConstraint() { var source = @"abstract class A<T> { internal abstract void F<U>(U x) where U : T; } class B1 : A<int> { internal override void F<U>(U x) { ((object?)x).ToString(); // 1 object y = x; y.ToString(); } } class B2 : A<int?> { internal override void F<U>(U x) { ((object?)x).ToString(); // 2 object? y = x; y.ToString(); } void F(int? x) { ((object?)x).ToString(); // 3 object? y = x; y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,10): warning CS8602: Dereference of a possibly null reference. // ((object?)x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object?)x").WithLocation(9, 10), // (18,10): warning CS8602: Dereference of a possibly null reference. // ((object?)x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object?)x").WithLocation(18, 10), // (25,10): warning CS8602: Dereference of a possibly null reference. // ((object?)x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object?)x").WithLocation(25, 10) ); } [Fact] public void NullableT_Unbox() { var source = @"class Program { static void F1<T>(object x1, object? y1) where T : struct { _ = ((T?)x1).Value; _ = ((T?)y1).Value; // 1 } static void F2<T>(object x2, object? y2) where T : struct { var z2 = (T?)x2; _ = z2.Value; var w2 = (T?)y2; _ = w2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,14): warning CS8629: Nullable value type may be null. // _ = ((T?)y1).Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T?)y1").WithLocation(6, 14), // (13,13): warning CS8629: Nullable value type may be null. // _ = w2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "w2").WithLocation(13, 13) ); } [Fact] public void NullableT_Unbox_ValueTypeConstraint() { var source = @"abstract class A<T> { internal abstract void F<U>(object? x) where U : T; } class B1 : A<int> { internal override void F<U>(object? x) { int y = (U)x; } } class B2 : A<int?> { internal override void F<U>(object? x) { _ = ((U)x).Value; _ = ((int?)(object)(U)x).Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // Conversions are not allowed from U to int in B1.F or from U to int? in B2.F, // so those conversions are not handled in NullableWalker either. comp.VerifyDiagnostics( // (9,17): error CS0029: Cannot implicitly convert type 'U' to 'int' // int y = (U)x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "(U)x").WithArguments("U", "int").WithLocation(9, 17), // (9,17): warning CS8605: Unboxing a possibly null value. // int y = (U)x; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)x").WithLocation(9, 17), // (16,20): error CS1061: 'U' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'U' could be found (are you missing a using directive or an assembly reference?) // _ = ((U)x).Value; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Value").WithArguments("U", "Value").WithLocation(16, 20), // (17,14): warning CS8629: Nullable value type may be null. // _ = ((int?)(object)(U)x).Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int?)(object)(U)x").WithLocation(17, 14), // (17,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // _ = ((int?)(object)(U)x).Value; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)(U)x").WithLocation(17, 20)); } [Fact] public void NullableT_Dynamic() { var source = @"class Program { static void F1<T>(dynamic x1, dynamic? y1) where T : struct { T? z1 = x1; _ = z1.Value; T? w1 = y1; _ = w1.Value; // 1 } static void F2<T>(dynamic x2, dynamic? y2) where T : struct { var z2 = (T?)x2; _ = z2.Value; var w2 = (T?)y2; _ = w2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8629: Nullable value type may be null. // _ = w1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "w1").WithLocation(8, 13), // (15,13): warning CS8629: Nullable value type may be null. // _ = w2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "w2").WithLocation(15, 13) ); } [Fact] public void NullableT_23() { var source = @"#pragma warning disable 649 struct S { internal int F; } class Program { static void F(S? x, S? y) { if (y == null) return; int? ni; ni = x?.F; _ = ni.Value; // 1 ni = y?.F; _ = ni.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8629: Nullable value type may be null. // _ = ni.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ni").WithLocation(13, 13), // (15,13): warning CS8629: Nullable value type may be null. // _ = ni.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ni").WithLocation(15, 13) ); } [Fact] public void NullableT_24() { var source = @"class Program { static void F(bool b, int? x, int? y) { if ((b ? x : y).HasValue) { _ = x.Value; // 1 _ = y.Value; // 2 } if ((b ? x : x).HasValue) { _ = x.Value; // 3 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,17): warning CS8629: Nullable value type may be null. // _ = x.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(7, 17), // (8,17): warning CS8629: Nullable value type may be null. // _ = y.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(8, 17), // (12,17): warning CS8629: Nullable value type may be null. // _ = x.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(12, 17) ); } [Fact] public void NullableT_25() { var source = @"class Program { static void F1(int? x) { var y = ~x; _ = y.Value; // 1 } static void F2(int x, int? y) { var z = x + y; _ = z.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8629: Nullable value type may be null. // _ = y.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(6, 13), // (11,13): warning CS8629: Nullable value type may be null. // _ = z.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "z").WithLocation(11, 13) ); } [WorkItem(31500, "https://github.com/dotnet/roslyn/issues/31500")] [Fact] public void NullableT_26() { var source = @"class Program { static void F1(int? x) { if (x == null) return; var y = ~x; _ = y.Value; } static void F2(int x, int? y) { if (y == null) return; var z = x + y; _ = z.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [WorkItem(31500, "https://github.com/dotnet/roslyn/issues/31500")] [Fact] public void NullableT_27() { var source = @"struct A { public static implicit operator B(A a) => new B(); } struct B { } class Program { static void F1(A? a) { B? b = a; _ = b.Value; // 1 } static void F2(A? a) { if (a != null) { B? b1 = a; _ = b1.Value; } else { B? b2 = a; _ = b2.Value; // 2 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8629: Nullable value type may be null. // _ = b.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "b").WithLocation(13, 13), // (25,17): warning CS8629: Nullable value type may be null. // _ = b2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "b2").WithLocation(25, 17) ); } [Fact] public void NullableT_28() { var source = @"class Program { static void F<T>(T? x, T? y) where T : struct { object z = x ?? y; object? w = x ?? y; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object z = x ?? y; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x ?? y").WithLocation(5, 20)); } [Fact] public void NullableT_29() { var source = @"class Program { static void F<T>(T? t) where T : struct { if (!t.HasValue) return; _ = t ?? default(T); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( ); } [Fact] public void NullableT_30() { var source = @"class Program { static void F<T>(T? t) where T : struct { t.HasValue = true; t.Value = default(T); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS0200: Property or indexer 'T?.HasValue' cannot be assigned to -- it is read only // t.HasValue = true; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "t.HasValue").WithArguments("T?.HasValue").WithLocation(5, 9), // (6,9): error CS0200: Property or indexer 'T?.Value' cannot be assigned to -- it is read only // t.Value = default(T); Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "t.Value").WithArguments("T?.Value").WithLocation(6, 9), // (6,9): warning CS8629: Nullable value type may be null. // t.Value = default(T); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(6, 9) ); } [Fact] public void NullableT_31() { var source = @"struct S { } class Program { static void F() { var s = (S?)F; _ = s.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): error CS0030: Cannot convert type 'method' to 'S?' // var s = (S?)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(S?)F").WithArguments("method", "S?").WithLocation(6, 18)); } [WorkItem(33330, "https://github.com/dotnet/roslyn/issues/33330")] [Fact] public void NullableT_32() { var source = @"#nullable enable class Program { static void F(int? i, int j) { _ = (int)(i & j); // 1 _ = (int)(i | j); // 2 _ = (int)(i ^ j); // 3 _ = (int)(~i); // 4 if (i.HasValue) { _ = (int)(i & j); _ = (int)(i | j); _ = (int)(i ^ j); _ = (int)(~i); } } static void F(bool? i, bool b) { _ = (bool)(i & b); // 5 _ = (bool)(i | b); // 6 _ = (bool)(i ^ b); // 7 _ = (bool)(!i); // 8 if (i.HasValue) { _ = (bool)(i & b); _ = (bool)(i | b); _ = (bool)(i ^ b); _ = (bool)(!i); } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8629: Nullable value type may be null. // _ = (int)(i & j); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int)(i & j)").WithLocation(6, 13), // (7,13): warning CS8629: Nullable value type may be null. // _ = (int)(i | j); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int)(i | j)").WithLocation(7, 13), // (8,13): warning CS8629: Nullable value type may be null. // _ = (int)(i ^ j); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int)(i ^ j)").WithLocation(8, 13), // (9,13): warning CS8629: Nullable value type may be null. // _ = (int)(~i); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int)(~i)").WithLocation(9, 13), // (20,13): warning CS8629: Nullable value type may be null. // _ = (bool)(i & b); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(bool)(i & b)").WithLocation(20, 13), // (21,13): warning CS8629: Nullable value type may be null. // _ = (bool)(i | b); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(bool)(i | b)").WithLocation(21, 13), // (22,13): warning CS8629: Nullable value type may be null. // _ = (bool)(i ^ b); // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(bool)(i ^ b)").WithLocation(22, 13), // (23,13): warning CS8629: Nullable value type may be null. // _ = (bool)(!i); // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(bool)(!i)").WithLocation(23, 13)); } [WorkItem(32626, "https://github.com/dotnet/roslyn/issues/32626")] [Fact] public void NullableCtor() { var source = @" using System; struct S { internal object? F; } class Program { static void Baseline() { S? x = new S(); x.Value.F.ToString(); // warning baseline S? y = new S() { F = 2 }; y.Value.F.ToString(); // ok baseline } static void F() { S? x = new Nullable<S>(new S()); x.Value.F.ToString(); // warning S? y = new Nullable<S>(new S() { F = 2 }); y.Value.F.ToString(); // ok } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // x.Value.F.ToString(); // warning baseline Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.F").WithLocation(14, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // x.Value.F.ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.F").WithLocation(23, 9) ); } [WorkItem(32626, "https://github.com/dotnet/roslyn/issues/32626")] [Fact] public void NullableCtorErr() { var source = @" using System; struct S { internal object? F; } class Program { static void F() { S? x = new S() { F = 2 }; x.Value.F.ToString(); // ok baseline S? y = new Nullable<S>(1); y.Value.F.ToString(); // warning 1 S? z = new Nullable<S>(null); z.Value.F.ToString(); // warning 2 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,32): error CS1503: Argument 1: cannot convert from 'int' to 'S' // S? y = new Nullable<S>(1); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "S").WithLocation(16, 32), // (17,9): warning CS8602: Dereference of a possibly null reference. // y.Value.F.ToString(); // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.F").WithLocation(17, 9), // (19,32): error CS1503: Argument 1: cannot convert from '<null>' to 'S' // S? z = new Nullable<S>(null); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "S").WithLocation(19, 32), // (20,9): warning CS8602: Dereference of a possibly null reference. // z.Value.F.ToString(); // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.Value.F").WithLocation(20, 9) ); } [WorkItem(32626, "https://github.com/dotnet/roslyn/issues/32626")] [Fact] public void NullableCtor1() { var source = @" using System; struct S { internal object? F; } class Program { static void F() { S? x = new Nullable<S>(new S() { F = 2 }); x.Value.F.ToString(); // ok S? y = new Nullable<S>(); y.Value.F.ToString(); // warning 1 S? z = new Nullable<S>(default); z.Value.F.ToString(); // warning 2 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,9): warning CS8629: Nullable value type may be null. // y.Value.F.ToString(); // warning 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(17, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // y.Value.F.ToString(); // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.F").WithLocation(17, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // z.Value.F.ToString(); // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.Value.F").WithLocation(20, 9)); } [Fact, WorkItem(38575, "https://github.com/dotnet/roslyn/issues/38575")] public void NullableCtor_Dynamic() { var source = @" using System; class C { void M() { var value = GetValue((dynamic)""""); _ = new DateTime?(value); } DateTime GetValue(object o) => default; } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_AlwaysTrueOrFalse() { var source = @"class Program { static void F1<T>(T? t1) where T : struct { if (!t1.HasValue) return; if (t1.HasValue) { } // always false if (!t1.HasValue) { } // always true if (t1 != null) { } // always false if (t1 == null) { } // always true } static void F2<T>(T? t2) where T : struct { if (!t2.HasValue) return; if (t2 == null) { } // always false if (t2 != null) { } // always true if (!t2.HasValue) { } // always false if (t2.HasValue) { } // always true } static void F3<T>(T? t3) where T : struct { if (t3 == null) return; if (!t3.HasValue) { } // always true if (t3.HasValue) { } // always false if (t3 == null) { } // always true if (t3 != null) { } // always false } static void F4<T>(T? t4) where T : struct { if (t4 == null) return; if (t4 != null) { } // always true if (t4 == null) { } // always false if (t4.HasValue) { } // always true if (!t4.HasValue) { } // always false } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_As_01() { var source = @"class Program { static void F1<T>(object x1, object? y1) where T : struct { _ = (x1 as T?).Value; // 1 _ = (y1 as T?).Value; // 2 } static void F2<T>(T x2, T? y2) where T : struct { _ = (x2 as T?).Value; _ = (y2 as T?).Value; // 3 } static void F3<T, U>(U x3) where T : struct { _ = (x3 as T?).Value; // 4 } static void F4<T, U>(U x4, U? y4) where T : struct where U : class { _ = (x4 as T?).Value; // 5 _ = (y4 as T?).Value; // 6 } static void F5<T, U>(U x5, U? y5) where T : struct where U : struct { _ = (x5 as T?).Value; // 7 _ = (y5 as T?).Value; // 8 } static void F6<T, U>(U x6) where T : struct, U { _ = (x6 as T?).Value; // 9 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,14): warning CS8629: Nullable value type may be null. // _ = (x1 as T?).Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x1 as T?").WithLocation(5, 14), // (6,14): warning CS8629: Nullable value type may be null. // _ = (y1 as T?).Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y1 as T?").WithLocation(6, 14), // (11,14): warning CS8629: Nullable value type may be null. // _ = (y2 as T?).Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y2 as T?").WithLocation(11, 14), // (15,14): warning CS8629: Nullable value type may be null. // _ = (x3 as T?).Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x3 as T?").WithLocation(15, 14), // (19,14): warning CS8629: Nullable value type may be null. // _ = (x4 as T?).Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x4 as T?").WithLocation(19, 14), // (20,14): warning CS8629: Nullable value type may be null. // _ = (y4 as T?).Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y4 as T?").WithLocation(20, 14), // (24,14): warning CS8629: Nullable value type may be null. // _ = (x5 as T?).Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x5 as T?").WithLocation(24, 14), // (25,14): warning CS8629: Nullable value type may be null. // _ = (y5 as T?).Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y5 as T?").WithLocation(25, 14), // (29,14): warning CS8629: Nullable value type may be null. // _ = (x6 as T?).Value; // 9 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x6 as T?").WithLocation(29, 14) ); } [Fact] public void NullableT_As_02() { var source = @"class Program { static void F1<T>(T? t1) where T : struct { _ = (t1 as object).ToString(); // 1 if (t1.HasValue) _ = (t1 as object).ToString(); else _ = (t1 as object).ToString(); } static void F2<T>(T? t2) where T : struct { _ = (t2 as T?).Value; // 2 if (t2.HasValue) _ = (t2 as T?).Value; else _ = (t2 as T?).Value; } static void F3<T, U>(T? t3) where T : struct where U : class { _ = (t3 as U).ToString(); // 3 if (t3.HasValue) _ = (t3 as U).ToString(); // 4 else _ = (t3 as U).ToString(); // 5 } static void F4<T, U>(T? t4) where T : struct where U : struct { _ = (t4 as U?).Value; // 6 if (t4.HasValue) _ = (t4 as U?).Value; // 7 else _ = (t4 as U?).Value; // 8 } static void F5<T>(T? t5) where T : struct { _ = (t5 as dynamic).ToString(); // 9 if (t5.HasValue) _ = (t5 as dynamic).ToString(); else _ = (t5 as dynamic).ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,14): warning CS8602: Dereference of a possibly null reference. // _ = (t1 as object).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1 as object").WithLocation(5, 14), // (13,14): warning CS8629: Nullable value type may be null. // _ = (t2 as T?).Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2 as T?").WithLocation(13, 14), // (21,14): warning CS8602: Dereference of a possibly null reference. // _ = (t3 as U).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3 as U").WithLocation(21, 14), // (23,18): warning CS8602: Dereference of a possibly null reference. // _ = (t3 as U).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3 as U").WithLocation(23, 18), // (25,18): warning CS8602: Dereference of a possibly null reference. // _ = (t3 as U).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3 as U").WithLocation(25, 18), // (29,14): warning CS8629: Nullable value type may be null. // _ = (t4 as U?).Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4 as U?").WithLocation(29, 14), // (31,18): warning CS8629: Nullable value type may be null. // _ = (t4 as U?).Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4 as U?").WithLocation(31, 18), // (33,18): warning CS8629: Nullable value type may be null. // _ = (t4 as U?).Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4 as U?").WithLocation(33, 18), // (37,14): warning CS8602: Dereference of a possibly null reference. // _ = (t5 as dynamic).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t5 as dynamic").WithLocation(37, 14) ); } [Fact] public void NullableT_As_ValueTypeConstraint_01() { var source = @"abstract class A<T> { internal abstract void F<U>(U u) where U : T; } class B1 : A<int> { internal override void F<U>(U u) { _ = (u as U?).Value; _ = (u as int?).Value; // 1 } } class B2 : A<int?> { internal override void F<U>(U u) { _ = (u as int?).Value; // 2 } }"; // Implicit conversions are not allowed from U to int in B1.F or from U to int? in B2.F, // so those conversions are not handled in NullableWalker either. var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,14): warning CS8629: Nullable value type may be null. // _ = (u as int?).Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "u as int?").WithLocation(10, 14), // (17,14): warning CS8629: Nullable value type may be null. // _ = (u as int?).Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "u as int?").WithLocation(17, 14) ); } [Fact] public void NullableT_As_ValueTypeConstraint_02() { var source = @"abstract class A<T> { internal abstract void F<U>(T t) where U : T; } class B1 : A<int> { internal override void F<U>(int t) { _ = (t as U?).Value; // 1 } } class B2 : A<int?> { internal override void F<U>(int? t) { _ = (t as U).Value; // 2 _ = (t as U?).Value; // 3 } }"; // Implicit conversions are not allowed from int to U in B1.F or from int? to U in B2.F, // so those conversions are not handled in NullableWalker either. var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,14): warning CS8629: Nullable value type may be null. // _ = (t as U?).Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t as U?").WithLocation(9, 14), // (16,14): error CS0413: The type parameter 'U' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint // _ = (t as U).Value; // 2 Diagnostic(ErrorCode.ERR_AsWithTypeVar, "t as U").WithArguments("U").WithLocation(16, 14), // (17,14): warning CS8629: Nullable value type may be null. // _ = (t as U?).Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t as U?").WithLocation(17, 14), // (17,19): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // _ = (t as U?).Value; // 3 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "U?").WithArguments("System.Nullable<T>", "T", "U").WithLocation(17, 19) ); } [Fact] [WorkItem(38213, "https://github.com/dotnet/roslyn/issues/38213")] public void NullableT_IsOperator_01() { var source = @"class C { void M() { int? i = null; _ = i is object ? i.Value : i.Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,15): warning CS8629: Nullable value type may be null. // : i.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(8, 15)); } [Fact] [WorkItem(38213, "https://github.com/dotnet/roslyn/issues/38213")] public void NullableT_IsOperator_02() { var source = @"public class C { public int? i = null; static void M(C? c) { _ = c?.i is object ? c.i.Value : c.i.Value; // 1, 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // : c.i.Value; // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(9, 15), // (9,15): warning CS8629: Nullable value type may be null. // : c.i.Value; // 1, 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.i").WithLocation(9, 15)); } [Fact] [WorkItem(38213, "https://github.com/dotnet/roslyn/issues/38213")] public void NullableT_IsOperator_03() { var source = @"class C { void M1() { int? i = null; _ = i is int ? i.Value : i.Value; // 1 } void M2() { int? i = null; _ = i is int? ? i.Value : i.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,15): warning CS8629: Nullable value type may be null. // : i.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(9, 15), // (18,15): warning CS8629: Nullable value type may be null. // : i.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(18, 15)); } [Fact] [WorkItem(38213, "https://github.com/dotnet/roslyn/issues/38213")] public void NullableT_IsOperator_NotAPureNullTest() { var source = @"class C { static void M1() { int? i = 42; _ = i is object ? i.Value : i.Value; // 1 } static void M2() { int? i = 42; _ = i is int ? i.Value : i.Value; } static void M3() { int? i = 42; _ = i is int? ? i.Value : i.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,15): warning CS8629: Nullable value type may be null. // : i.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(8, 15)); } [WorkItem(31501, "https://github.com/dotnet/roslyn/issues/31501")] [Fact] public void NullableT_Suppress_01() { var source = @"class Program { static void F<T>(T x, T? y, T? z) where T : struct { _ = (T)((T?)null)!; _ = (T)((T?)default)!; _ = (T)default(T?)!; _ = (T)((T?)x)!; _ = (T)y!; _ = ((T)z)!; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,14): warning CS8629: Nullable value type may be null. // _ = ((T)z)!; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)z").WithLocation(10, 14)); } [WorkItem(31501, "https://github.com/dotnet/roslyn/issues/31501")] [Fact] public void NullableT_Suppress_02() { var source = @"class Program { static void F<T>(T x, T? y, T? z) where T : struct { _ = ((T?)null)!.Value; _ = ((T?)default)!.Value; _ = default(T?)!.Value; _ = ((T?)x)!.Value; _ = y!.Value; _ = z.Value!; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8629: Nullable value type may be null. // _ = z.Value!; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "z").WithLocation(10, 13) ); } [Fact] public void NullableT_NotNullWhenTrue() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool F<T>([NotNullWhen(true)]T? t) where T : struct { return true; } static void G<T>(T? t) where T : struct { if (F(t)) _ = t.Value; else _ = t.Value; // 1 } }"; var comp = CreateCompilation(new[] { source, NotNullWhenAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,17): warning CS8629: Nullable value type may be null. // _ = t.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(13, 17) ); } [Fact] public void NullableT_NotNullWhenTrue_DifferentRefKinds() { var source = @"using System.Diagnostics.CodeAnalysis; class C { bool F2([NotNullWhen(true)] string? s) { s = null; return true; } bool F2([NotNullWhen(true)] ref string? s) { s = null; return true; // 1 } bool F3([NotNullWhen(true)] in string? s) { s = null; // 2 return true; } bool F4([NotNullWhen(true)] out string? s) { s = null; return true; // 3 } }"; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (13,9): error CS8762: Parameter 's' must have a non-null value when exiting with 'true'. // return true; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return true;").WithArguments("s", "true").WithLocation(13, 9), // (18,9): error CS8331: Cannot assign to variable 'in string?' because it is a readonly variable // s = null; // 2 Diagnostic(ErrorCode.ERR_AssignReadonlyNotField, "s").WithArguments("variable", "in string?").WithLocation(18, 9), // (25,9): error CS8762: Parameter 's' must have a non-null value when exiting with 'true'. // return true; // 3 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return true;").WithArguments("s", "true").WithLocation(25, 9) ); } [Fact] public void NullableT_DoesNotReturnIfFalse() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F([DoesNotReturnIf(false)] bool b) { } static void G<T>(T? x, T? y) where T : struct { F(x != null); _ = x.Value; F(y.HasValue); _ = y.Value; } }"; var comp = CreateCompilation(new[] { source, DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_AllMembers() { var source = @"class C<T> where T : struct { static void F1(T? t1) { _ = t1.HasValue; } static void F2(T? t2) { _ = t2.Value; // 1 } static void F3(T? t3) { _ = t3.GetValueOrDefault(); } static void F4(T? t4) { _ = t4.GetHashCode(); } static void F5(T? t5) { _ = t5.ToString(); } static void F6(T? t6) { _ = t6.Equals(t6); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(9, 13) ); } [WorkItem(33174, "https://github.com/dotnet/roslyn/issues/33174")] [Fact] public void NullableBaseMembers() { var source = @" static class Program { static void Main() { int? x = null; x.GetHashCode(); // ok x.Extension(); // ok x.GetType(); // warning1 int? y = null; y.MemberwiseClone(); // warning2 y.Lalala(); // does not exist } static void Extension(this int? self) { } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8629: Nullable value type may be null. // x.GetType(); // warning1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(12, 9), // (15,9): warning CS8629: Nullable value type may be null. // y.MemberwiseClone(); // warning2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(15, 9), // (15,11): error CS1540: Cannot access protected member 'object.MemberwiseClone()' via a qualifier of type 'int?'; the qualifier must be of type 'Program' (or derived from it) // y.MemberwiseClone(); // warning2 Diagnostic(ErrorCode.ERR_BadProtectedAccess, "MemberwiseClone").WithArguments("object.MemberwiseClone()", "int?", "Program").WithLocation(15, 11), // (17,11): error CS1061: 'int?' does not contain a definition for 'Lalala' and no accessible extension method 'Lalala' accepting a first argument of type 'int?' could be found (are you missing a using directive or an assembly reference?) // y.Lalala(); // does not exist Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Lalala").WithArguments("int?", "Lalala").WithLocation(17, 11) ); } [Fact] public void NullableT_Using() { var source = @"using System; struct S : IDisposable { void IDisposable.Dispose() { } } class Program { static void F1(S? s) { using (s) { } _ = s.Value; // 1 } static void F2<T>(T? t) where T : struct, IDisposable { using (t) { } _ = t.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = s.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s").WithLocation(11, 13), // (16,13): warning CS8629: Nullable value type may be null. // _ = t.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(16, 13) ); } [WorkItem(31503, "https://github.com/dotnet/roslyn/issues/31503")] [Fact] public void NullableT_ForEach() { var source = @"using System.Collections; using System.Collections.Generic; struct S : IEnumerable { public IEnumerator GetEnumerator() => throw null!; } class Program { static void F1(S? s) { foreach (var i in s) // 1 ; foreach (var i in s) ; } static void F2<T, U>(T? t) where T : struct, IEnumerable<U> { foreach (var i in t) // 2 ; foreach (var i in t) ; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,27): warning CS8629: Nullable value type may be null. // foreach (var i in s) // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s").WithLocation(11, 27), // (18,27): warning CS8629: Nullable value type may be null. // foreach (var i in t) // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(18, 27) ); } [Fact] public void NullableT_IndexAndRange() { var source = @"class Program { static void F1(int? x) { _ = ^x; } static void F2(int? y) { _ = ..y; _ = ^y..; } static void F3(int? z, int? w) { _ = z..^w; } }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void PatternIndexer() { var src = @" #nullable enable class C { static void M1(string? s) { _ = s[^1]; } static void M2(string? s) { _ = s[1..10]; } }"; var comp = CreateCompilationWithIndexAndRange(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // _ = s[^1]; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // _ = s[1..10]; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 9)); } [WorkItem(31770, "https://github.com/dotnet/roslyn/issues/31770")] [Fact] public void UserDefinedConversion_NestedNullability_01() { var source = @"class A<T> { } class B { public static implicit operator B(A<object> a) => throw null!; } class Program { static void F(B b) { } static void Main() { A<object?> a = new A<object?>(); B b = a; // 1 F(a); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/31798: Consider improving warning to reference user-defined operator. comp.VerifyDiagnostics( // (12,15): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'A<object>'. // B b = a; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a").WithArguments("A<object?>", "A<object>").WithLocation(12, 15), // (13,11): warning CS8620: Argument of type 'A<object?>' cannot be used for parameter 'b' of type 'B' in 'void Program.F(B b)' due to differences in the nullability of reference types. // F(a); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "a").WithArguments("A<object?>", "B", "b", "void Program.F(B b)").WithLocation(13, 11)); } [Fact] public void UserDefinedConversion_NestedNullability_02() { var source = @"class A<T> { } class B { public static implicit operator A<object>(B b) => throw null!; } class Program { static void F(A<object?> a) { } static void Main() { B b = new B(); A<object?> a = b; // 1 F(b); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/31798: Consider improving warning to reference user-defined operator. comp.VerifyDiagnostics( // (12,24): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'A<object?>'. // A<object?> a = b; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b").WithArguments("A<object>", "A<object?>").WithLocation(12, 24), // (13,11): warning CS8620: Argument of type 'B' cannot be used for parameter 'a' of type 'A<object?>' in 'void Program.F(A<object?> a)' due to differences in the nullability of reference types. // F(b); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b").WithArguments("B", "A<object?>", "a", "void Program.F(A<object?> a)").WithLocation(13, 11)); } [WorkItem(31864, "https://github.com/dotnet/roslyn/issues/31864")] [Fact] public void BestType_DifferentTupleNullability_01() { var source = @"using System; class Program { static void F(bool b) { DateTime? x = DateTime.MaxValue; string? y = null; _ = (b ? (x, y) : (null, null))/*T:(System.DateTime?, string?)*/; _ = (b ? (null, null) : (x, y))/*T:(System.DateTime?, string?)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(31864, "https://github.com/dotnet/roslyn/issues/31864")] [Fact] public void BestType_DifferentTupleNullability_02() { var source = @"class Program { static void F<T, U>(bool b) where T : class, new() where U : struct { T? t1 = null; T? t2 = new T(); U? u1 = null; U? u2 = new U(); _ = (b ? (t1, t2) : (null, null))/*T:(T?, T?)*/; _ = (b ? (null, null) : (u1, u2))/*T:(U?, U?)*/; _ = (b ? (t1, u2) : (null, null))/*T:(T?, U?)*/; _ = (b ? (null, null) : (t2, u1))/*T:(T?, U?)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(31864, "https://github.com/dotnet/roslyn/issues/31864")] [Fact] public void BestType_DifferentTupleNullability_03() { var source = @"class Program { static void F<T, U>() where T : class, new() where U : struct { T? t1 = null; T? t2 = new T(); U? u1 = null; U? u2 = new U(); _ = new[] { (t1, t2), (null, null) }[0]/*T:(T?, T?)*/; _ = new[] { (null, null), (u1, u2) }[0]/*T:(U?, U?)*/; _ = new[] { (t1, u2), (null, null) }[0]/*T:(T?, U?)*/; _ = new[] { (null, null), (t2, u1) }[0]/*T:(T?, U?)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_04() { var source = @"class Program { static void F<T>(bool b) where T : class, new() { _ = (b ? (new T(), new T()) : (null, null))/*T:(T?, T?)*/; _ = (b ? (null, new T()) : (new T(), new T()))/*T:(T?, T!)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_05() { var source = @"class Program { static void F<T>() where T : class, new() { _ = new[] { (new T(), new T()), (null, null) }[0]/*T:(T?, T?)*/; _ = new[] { (null, new T()), (new T(), new T()) }[0]/*T:(T?, T!)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_06() { var source = @"class Program { static void F<T>(bool b, T x, T? y) where T : class { _ = (b ? (x, y) : (y, x))/*T:(T?, T?)*/; _ = (b ? (x, x) : (y, default))/*T:(T?, T?)*/; _ = (b ? (null, x) : (x, y))/*T:(T?, T?)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_07() { var source = @"class Program { static void F<T>(T x, T? y) where T : class { _ = new[] { (x, y), (y, x) }[0]/*T:(T?, T?)*/; _ = new[] { (x, x), (y, default) }[0]/*T:(T?, T?)*/; _ = new[] { (null, x), (x, y) }[0]/*T:(T?, T?)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_08() { var source = @"class Program { static void F<T>(bool b, T? x, object y) where T : class { var t = (b ? (x: y, y: y) : (x, null))/*T:(object? x, object?)*/; var u = (b ? (x: default, y: x) : (x, y))/*T:(T? x, object? y)*/; t.x.ToString(); // 1 t.y.ToString(); // 2 u.x.ToString(); // 3 u.y.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.x").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.y").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.x").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.y").WithLocation(11, 9)); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_09() { var source = @"class Program { static void F<T>(T? x, object y) where T : class { var t = new[] { (x: y, y: y), (x, null) }[0]/*T:(object? x, object?)*/; var u = new[] { (x: default, y: x), (x, y) }[0]/*T:(T? x, object? y)*/; t.x.ToString(); // 1 t.y.ToString(); // 2 u.x.ToString(); // 3 u.y.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.x").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.y").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.x").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.y").WithLocation(11, 9)); comp.VerifyTypes(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33344")] [WorkItem(32575, "https://github.com/dotnet/roslyn/issues/32575")] public void BestType_DifferentTupleNullability_10() { var source = @"class Program { static void F<T, U>(bool b, T t, U u) where U : class { var x = (b ? (t, u) : default)/*T:(T t, U? u)*/; x.Item1.ToString(); // 1 x.Item2.ToString(); // 2 var y = (b ? default : (t, u))/*T:(T t, U? u)*/; y.Item1.ToString(); // 3 y.Item2.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32575: Not handling default for U. comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Item1").WithLocation(7, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.Item2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Item2").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // y.Item1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Item1").WithLocation(10, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // y.Item2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Item2").WithLocation(11, 9) ); comp.VerifyTypes(); } [Fact] [WorkItem(32575, "https://github.com/dotnet/roslyn/issues/32575")] [WorkItem(33344, "https://github.com/dotnet/roslyn/issues/33344")] public void BestType_DifferentTupleNullability_11() { var source = @"class Program { static void F<T, U>(T t, U u) where U : class { var x = new[] { (t, u), default }[0]/*T:(T t, U u)*/; // should be (T t, U? u) x.Item1.ToString(); // 1 x.Item2.ToString(); // 2 var y = new[] { default, (t, u) }[0]/*T:(T t, U u)*/; // should be (T t, U? u) y.Item1.ToString(); // 3 y.Item2.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // https://github.com/dotnet/roslyn/issues/32575: Not handling default for U. // SHOULD BE 4 diagnostics. ); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_12() { var source = @"class Program { static void F<U>(bool b, U? u) where U : struct { var t = b ? (1, u) : default; t.Item1.ToString(); _ = t.Item2.Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8629: Nullable value type may be null. // _ = t.Item2.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t.Item2").WithLocation(8, 13) ); } [Fact] public void BestType_DifferentTupleNullability_13() { var source = @"class Program { static void F<U>(U? u) where U : struct { var t = new[] { (1, u), default }[0]; t.Item1.ToString(); _ = t.Item2.Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8629: Nullable value type may be null. // _ = t.Item2.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t.Item2").WithLocation(8, 13) ); } [WorkItem(32006, "https://github.com/dotnet/roslyn/issues/32006")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void LambdaReturnType_DifferentTupleNullability_01() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @"using System; class Program { static T F<T>(Func<bool, T> f) { return f(true); } static void G<T, U>() where T : class, new() where U : struct { F(b => { if (b) { T? t1 = null; U? u2 = new U(); return (t1, u2); } return (null, null); })/*T:(T? t1, U? u2)*/; F(b => { if (b) return (null, null); T? t2 = new T(); U? u1 = null; return (t2, u1); })/*T:(T! t2, U? u1)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32006: Warning inferring return type. comp.VerifyDiagnostics( // (20,24): warning CS8619: Nullability of reference types in value of type '(T?, U?)' doesn't match target type '(T? t1, U? u2)'. // return (null, null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, null)").WithArguments("(T?, U?)", "(T? t1, U? u2)").WithLocation(20, 24), // (24,31): warning CS8619: Nullability of reference types in value of type '(T?, U?)' doesn't match target type '(T t2, U? u1)'. // if (b) return (null, null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, null)").WithArguments("(T?, U?)", "(T t2, U? u1)").WithLocation(24, 31)); comp.VerifyTypes(); } [WorkItem(32006, "https://github.com/dotnet/roslyn/issues/32006")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void LambdaReturnType_DifferentTupleNullability_02() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @"using System; class Program { static T F<T>(Func<bool, T> f) { return f(true); } static void G<T>() where T : class, new() { F(b => { if (b) return (new T(), new T()); return (null, null); })/*T:(T!, T!)*/; F(b => { if (b) return (null, new T()); return (new T(), new T()); })/*T:(T!, T!)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32006: Warning inferring return type. comp.VerifyDiagnostics( // (11,59): warning CS8619: Nullability of reference types in value of type '(T?, T?)' doesn't match target type '(T, T)'. // F(b => { if (b) return (new T(), new T()); return (null, null); })/*T:(T!, T!)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, null)").WithArguments("(T?, T?)", "(T, T)").WithLocation(11, 59), // (12,32): warning CS8619: Nullability of reference types in value of type '(T?, T)' doesn't match target type '(T, T)'. // F(b => { if (b) return (null, new T()); return (new T(), new T()); })/*T:(T!, T!)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, new T())").WithArguments("(T?, T)", "(T, T)").WithLocation(12, 32)); comp.VerifyTypes(); } [WorkItem(32006, "https://github.com/dotnet/roslyn/issues/32006")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void LambdaReturnType_DifferentTupleNullability_03() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @"using System; class Program { static T F<T>(Func<bool, T> f) { return f(true); } static void G<T>(T x, T? y) where T : class { F(b => { if (b) return (x, y); return (y, x); })/*T:(T?, T?)*/; F(b => { if (b) return (x, x); return (y, default); })/*T:(T!, T!)*/; F(b => { if (b) return (null, x); return (x, y); })/*T:(T! x, T? y)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32006: Warning inferring return type. comp.VerifyDiagnostics( // (12,47): warning CS8619: Nullability of reference types in value of type '(T? y, T?)' doesn't match target type '(T, T)'. // F(b => { if (b) return (x, x); return (y, default); })/*T:(T?, T?)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(y, default)").WithArguments("(T? y, T?)", "(T, T)").WithLocation(12, 47), // (13,32): warning CS8619: Nullability of reference types in value of type '(T?, T x)' doesn't match target type '(T x, T? y)'. // F(b => { if (b) return (null, x); return (x, y); })/*T:(T?, T?)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, x)").WithArguments("(T?, T x)", "(T x, T? y)").WithLocation(13, 32)); comp.VerifyTypes(); } [WorkItem(32006, "https://github.com/dotnet/roslyn/issues/32006")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void LambdaReturnType_DifferentTupleNullability_04() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @"using System; class Program { static T F<T>(Func<bool, T> f) { return f(true); } static void G<T>(T? x, object y) where T : class { F(b => { if (b) return (y, y); return (x, null); })/*T:(object!, object!)*/; F(b => { if (b) return (default, x); return (x, y); })/*T:(T? x, object! y)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32006: Warning inferring return type. comp.VerifyDiagnostics( // (11,47): warning CS8619: Nullability of reference types in value of type '(object? x, object?)' doesn't match target type '(object, object)'. // F(b => { if (b) return (y, y); return (x, null); })/*T:(object?, object?)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, null)").WithArguments("(object? x, object?)", "(object, object)").WithLocation(11, 47), // (12,32): warning CS8619: Nullability of reference types in value of type '(T?, object? x)' doesn't match target type '(T? x, object y)'. // F(b => { if (b) return (default, x); return (x, y); })/*T:(T?, object?)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default, x)").WithArguments("(T?, object? x)", "(T? x, object y)").WithLocation(12, 32)); comp.VerifyTypes(); } [Fact] public void DisplayMultidimensionalArray() { var source = @" class C { void M(A<object> o, A<string[][][,]?> s) { o = s; } } interface A<out T> {} "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8619: Nullability of reference types in value of type 'A<string[]?[][*,*]>' doesn't match target type 'A<object>'. // o = s; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "s").WithArguments("A<string[][][*,*]?>", "A<object>").WithLocation(6, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(31862, "https://github.com/dotnet/roslyn/issues/31862")] public void Issue31862_01() { var source = @" using System; using System.Collections; using System.Collections.Generic; public class Working<T> : IEnumerable<IEquatable<T>> { public IEnumerator<IEquatable<T>> GetEnumerator() => null; IEnumerator IEnumerable.GetEnumerator() => throw null!; } public class Broken<T> : IEnumerable<IEquatable<T>> { IEnumerator<IEquatable<T>> IEnumerable<IEquatable<T>>.GetEnumerator() => null; IEnumerator IEnumerable.GetEnumerator() => throw null!; } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,58): warning CS8603: Possible null reference return. // public IEnumerator<IEquatable<T>> GetEnumerator() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 58), // (15,78): warning CS8603: Possible null reference return. // IEnumerator<IEquatable<T>> IEnumerable<IEquatable<T>>.GetEnumerator() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(15, 78) ); } [Fact] [WorkItem(31862, "https://github.com/dotnet/roslyn/issues/31862")] public void Issue31862_02() { var source = @" using System; using System.Collections; using System.Collections.Generic; public class Working<T> : IEnumerable<IEquatable<T>> { public IEnumerator<IEquatable<T>?> GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } public class Broken<T> : IEnumerable<IEquatable<T>> { IEnumerator<IEquatable<T>?> IEnumerable<IEquatable<T>>.GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,40): warning CS8613: Nullability of reference types in return type of 'IEnumerator<IEquatable<T>?> Working<T>.GetEnumerator()' doesn't match implicitly implemented member 'IEnumerator<IEquatable<T>> IEnumerable<IEquatable<T>>.GetEnumerator()'. // public IEnumerator<IEquatable<T>?> GetEnumerator() => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "GetEnumerator").WithArguments("IEnumerator<IEquatable<T>?> Working<T>.GetEnumerator()", "IEnumerator<IEquatable<T>> IEnumerable<IEquatable<T>>.GetEnumerator()").WithLocation(8, 40), // (15,60): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'IEnumerator<IEquatable<T>> IEnumerable<IEquatable<T>>.GetEnumerator()'. // IEnumerator<IEquatable<T>?> IEnumerable<IEquatable<T>>.GetEnumerator() => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "GetEnumerator").WithArguments("IEnumerator<IEquatable<T>> IEnumerable<IEquatable<T>>.GetEnumerator()").WithLocation(15, 60) ); } [Fact] [WorkItem(31862, "https://github.com/dotnet/roslyn/issues/31862")] public void Issue31862_03() { var source = @" using System; using System.Collections; using System.Collections.Generic; public class Working<T> : IEnumerable<IEquatable<T>> { public IEnumerator<IEquatable<T?>> GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } public class Broken<T> : IEnumerable<IEquatable<T>> { IEnumerator<IEquatable<T?>> IEnumerable<IEquatable<T>>.GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } "; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,35): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public IEnumerator<IEquatable<T?>> GetEnumerator() => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 35), // (15,28): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // IEnumerator<IEquatable<T?>> IEnumerable<IEquatable<T>>.GetEnumerator() => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(15, 28) ); } [Fact] [WorkItem(31862, "https://github.com/dotnet/roslyn/issues/31862")] public void Issue31862_04() { var source = @" using System; using System.Collections; using System.Collections.Generic; public class Working<T> : IEnumerable<IEquatable<T>> { public IEnumerator<IEquatable<T>>? GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } public class Broken<T> : IEnumerable<IEquatable<T>> { IEnumerator<IEquatable<T>>? IEnumerable<IEquatable<T>>.GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(31862, "https://github.com/dotnet/roslyn/issues/31862")] public void Issue31862_05() { var source = @" using System; using System.Collections; using System.Collections.Generic; public class Working<T> : IEnumerable<IEquatable<T>> where T : class { public IEnumerator<IEquatable<T?>> GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } public class Broken<T> : IEnumerable<IEquatable<T>> where T : class { IEnumerator<IEquatable<T?>> IEnumerable<IEquatable<T>>.GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(37868, "https://github.com/dotnet/roslyn/issues/37868")] public void IsPatternVariableDeclaration_LeftOfAssignmentOperator() { var source = @" using System; class C { void Test1() { if (unknown is string b = ) { Console.WriteLine(b); } } void Test2(bool a) { if (a is bool (b = a)) { Console.WriteLine(b); } } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0103: The name 'unknown' does not exist in the current context // if (unknown is string b = ) Diagnostic(ErrorCode.ERR_NameNotInContext, "unknown").WithArguments("unknown").WithLocation(8, 13), // (8,35): error CS1525: Invalid expression term ')' // if (unknown is string b = ) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(8, 35), // (10,31): error CS0165: Use of unassigned local variable 'b' // Console.WriteLine(b); Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(10, 31), // (16,23): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'bool', with 1 out parameters and a void return type. // if (a is bool (b = a)) Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(b ").WithArguments("bool", "1").WithLocation(16, 23), // (16,24): error CS0103: The name 'b' does not exist in the current context // if (a is bool (b = a)) Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(16, 24), // (16,26): error CS1026: ) expected // if (a is bool (b = a)) Diagnostic(ErrorCode.ERR_CloseParenExpected, "=").WithLocation(16, 26), // (16,30): error CS1525: Invalid expression term ')' // if (a is bool (b = a)) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(16, 30), // (16,30): error CS1002: ; expected // if (a is bool (b = a)) Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(16, 30), // (16,30): error CS1513: } expected // if (a is bool (b = a)) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(16, 30), // (18,31): error CS0103: The name 'b' does not exist in the current context // Console.WriteLine(b); Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(18, 31)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_UseInExpression() { var source = @" class C { void M(string? s1, string s2) { string s3 = (s1 ??= s2); string? s4 = null, s5 = null; string s6 = (s4 ??= s5); // Warn 1 s4.ToString(); // Warn 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // string s6 = (s4 ??= s5); // Warn 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s4 ??= s5").WithLocation(8, 22), // (9,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // Warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(9, 9)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_AssignsState() { var source = @" class C { object? F = null; void M(C? c1, C c2, C c3) { c1 ??= c2; c1.ToString(); if (c3.F == null) return; c1 = null; c1 ??= c3; c1.F.ToString(); // Warn 1 c1 = null; c1 ??= c3; c1.ToString(); c1.F.ToString(); // Warn 2 if (c1.F == null) return; c1 ??= c2; c1.F.ToString(); // Warn 3 // We could support this in the future if MakeSlot is made smarter to understand // that the slot of a ??= is the slot of the left-hand side. https://github.com/dotnet/roslyn/issues/32501 (c1 ??= c3).F.ToString(); // Warn 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // c1.F.ToString(); // Warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.F").WithLocation(14, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // c1.F.ToString(); // Warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.F").WithLocation(19, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // c1.F.ToString(); // Warn 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.F").WithLocation(23, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // (c1 ??= c3).F.ToString(); // Warn 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(c1 ??= c3).F").WithLocation(27, 9)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_RightStateValidInRightOnly() { var source = @" class C { C GetC(C c) => c; void M(C? c1, C? c2, C c3) { c1 ??= (c2 = c3); c1.ToString(); c2.ToString(); // Warn 1 c1 = null; c2 = null; c1 ??= (c2 = c3).GetC(c2); c1.ToString(); c2.ToString(); // Warn 2 c1 = null; c2 = null; c1 ??= (c2 = c3).GetC(c1); // Warn 3 c1.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c2.ToString(); // Warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(9, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // c2.ToString(); // Warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(15, 9), // (19,31): warning CS8604: Possible null reference argument for parameter 'c' in 'C C.GetC(C c)'. // c1 ??= (c2 = c3).GetC(c1); // Warn 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c1").WithArguments("c", "C C.GetC(C c)").WithLocation(19, 31)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_Contravariant() { var source = @" class C { #nullable disable C GetC() => null; #nullable enable void M(C? c1, C c2) { // nullable + non-null = non-null #nullable disable C c3 #nullable enable = (c1 ??= GetC()); _ = c1/*T:C!*/; _ = c3/*T:C!*/; // oblivious + nullable = nullable // Since c3 is non-nullable, the result is non-nullable. c1 = null; var c4 = (c3 ??= c1); _ = c3/*T:C?*/; _ = c4/*T:C?*/; // oblivious + not nullable = not nullable c3 = GetC(); var c5 = (c3 ??= c2); _ = c3/*T:C!*/; _ = c5/*T:C!*/; // not nullable + oblivious = not nullable var c6 = (c2 ??= GetC()); _ = c2/*T:C!*/; _ = c6/*T:C!*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_LeftNotTracked() { var source = @" class C { void M(C?[] c1, C c2) { c1[0] ??= c2; c1[0].ToString(); // Warn } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // c1[0].ToString(); // Warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1[0]").WithLocation(7, 9)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_RefReturn() { var source = @" class C { void M1(C c1, C? c2) { M2(c1) ??= c2; // Warn 1, 2 M2(c1).ToString(); M2(c2) ??= c1; M2(c2).ToString(); // Warn 3 } ref T M2<T>(T t) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,20): warning CS8601: Possible null reference assignment. // M2(c1) ??= c2; // Warn 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c2").WithLocation(6, 20), // (10,9): warning CS8602: Dereference of a possibly null reference. // M2(c2).ToString(); // Warn 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(c2)").WithLocation(10, 9)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_NestedLHS() { var source = @" class C { object? F = null; void M1(C c1, object f) { c1.F ??= f; c1.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_Conversions() { var source = @" class C<T> { void M1(C<object>? c1, C<object?> c2, C<object?> c3, C<object>? c4) { c1 ??= c2; c3 ??= c4; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,16): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // c1 ??= c2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c2").WithArguments("C<object?>", "C<object>").WithLocation(6, 16), // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // c3 ??= c4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c4").WithLocation(7, 16), // (7,16): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // c3 ??= c4; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c4").WithArguments("C<object>", "C<object?>").WithLocation(7, 16)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_LeftStillNullableOnRight() { var source = @" class C { void M1(C? c1) { c1 ??= M2(c1); c1.ToString(); } C M2(C c1) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,19): warning CS8604: Possible null reference argument for parameter 'c1' in 'C C.M2(C c1)'. // c1 ??= M2(c1); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c1").WithArguments("c1", "C C.M2(C c1)").WithLocation(6, 19)); } [Fact] public void NullCoalescingAssignment_DefaultConvertedToNullableUnderlyingType() { var source = @" class C { void M1(int? i) { (i ??= default).ToString(); // default is converted to int, so there's no warning. } }"; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(41273, "https://github.com/dotnet/roslyn/issues/41273")] public void NullCoalescingAssignment_InTryCatchFinally01() { var source = @" using System; public class C { string x; public C() { try { x = """"; } catch (Exception) { x ??= """"; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(41273, "https://github.com/dotnet/roslyn/issues/41273")] public void NullCoalescingAssignment_InTryCatchFinally02() { var source = @" using System; public class C { string x; public C() { try { } catch (Exception) { x ??= """"; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,12): warning CS8618: Non-nullable field 'x' is uninitialized. Consider declaring the field as nullable. // public C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "x").WithLocation(7, 12) ); } [Fact] [WorkItem(41273, "https://github.com/dotnet/roslyn/issues/41273")] public void NullCoalescingAssignment_InTryCatchFinally03() { var source = @" public class C { string x; public C() { try { } finally { x ??= """"; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(41273, "https://github.com/dotnet/roslyn/issues/41273")] public void NullCoalescingAssignment_InTryCatchFinally04() { var source = @" public class C { string x; public C() // 1 { try { x = """"; } finally { x ??= null; // 2 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,12): warning CS8618: Non-nullable field 'x' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "x").WithLocation(6, 12), // (14,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // x ??= null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 19) ); } [Fact] [WorkItem(41273, "https://github.com/dotnet/roslyn/issues/41273")] public void NullCoalescingAssignment_InTryCatchFinally05() { var source = @" using System; public class C { string x; public C() // 1 { try { x = """"; } catch (Exception) { x ??= null; // 2 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,12): warning CS8618: Non-nullable field 'x' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "x").WithLocation(7, 12), // (15,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // x ??= null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 19) ); } [Fact] public void Deconstruction_01() { var source = @"class Program { static void F<T, U>() where U : class { (T x, U y) = default((T, U)); // 1 x.ToString(); // 2 y.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T x, U y) = default((T, U)); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((T, U))").WithLocation(5, 22), // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9)); } [Fact] public void Deconstruction_02() { var source = @"class Program { static void F<T, U>() where U : class { (T x, U y) = (default, default); // 1 x.ToString(); // 2 y.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,32): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T x, U y) = (default, default); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(5, 32), // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9)); } [Fact] public void Deconstruction_03() { var source = @"class Program { static void F<T>() where T : class, new() { (T x, T? y) = (null, new T()); // 1 x.ToString(); // 2 y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T x, T? y) = (null, new T()); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 24), // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9)); } [Fact] public void Deconstruction_04() { var source = @"class Program { static void F<T>(T x, T? y) where T : class { (T a, T? b) = (x, y); a.ToString(); b.ToString(); // 1 (a, b) = (y, x); // 2 a.ToString(); // 3 b.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 9), // (8,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // (a, b) = (y, x); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(8, 19), // (9,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(9, 9)); } [Fact] public void Deconstruction_05() { var source = @"class Program { static void F<T>((T, T?) t) where T : class { (T a, T? b) = t; a.ToString(); b.ToString(); // 1 (b, a) = t; // 2 a.ToString(); // 3 b.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 9), // (8,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // (b, a) = t; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(8, 18), // (9,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(9, 9)); } [Fact] public void Deconstruction_06() { var source = @"class Program { static void F<T>() where T : class, new() { (T, T?) t = (default, new T()); // 1 (T a, T? b) = t; // 2 a.ToString(); // 3 b.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,21): warning CS8619: Nullability of reference types in value of type '(T?, T)' doesn't match target type '(T, T?)'. // (T, T?) t = (default, new T()); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default, new T())").WithArguments("(T?, T)", "(T, T?)").WithLocation(5, 21), // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T a, T? b) = t; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(6, 23), // (7,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(7, 9)); } [Fact] public void Deconstruction_07() { var source = @"class Program { static void F<T, U>() where U : class { var (x, y) = default((T, U)); x.ToString(); // 1 y.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9)); } [Fact] public void Deconstruction_08() { var source = @"class Program { static void F<T>() where T : class, new() { T x = default; // 1 T? y = new T(); var (a, b) = (x, y); a.ToString(); // 2 b.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = default; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(5, 15), // (8,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(8, 9)); } [Fact] public void Deconstruction_09() { var source = @"class Program { static void F<T>() where T : class, new() { (T, T?) t = (default, new T()); // 1 var (a, b) = t; a.ToString(); // 2 b.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,21): warning CS8619: Nullability of reference types in value of type '(T?, T)' doesn't match target type '(T, T?)'. // (T, T?) t = (default, new T()); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default, new T())").WithArguments("(T?, T)", "(T, T?)").WithLocation(5, 21), // (7,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(7, 9)); } [Fact] public void Deconstruction_10() { var source = @"class Program { static void F<T>((T, T?) t) where T : class { if (t.Item2 == null) return; t.Item1 = null; // 1 var (a, b) = t; a.ToString(); // 2 b.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // t.Item1 = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 19), // (8,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(8, 9)); } [Fact] public void Deconstruction_11() { var source = @"class Program { static void F(object? x, object y, string? z) { ((object? a, object? b), string? c) = ((x, y), z); a.ToString(); // 1 b.ToString(); c.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9)); } [Fact] public void Deconstruction_12() { var source = @"class Program { static void F((object?, object) x, string? y) { ((object? a, object? b), string? c) = (x, y); a.ToString(); // 1 b.ToString(); c.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9)); } [Fact] public void Deconstruction_13() { var source = @"class Program { static void F(((object?, object), string?) t) { ((object? a, object? b), string? c) = t; a.ToString(); // 1 b.ToString(); c.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9)); } [Fact] public void Deconstruction_14() { var source = @"class Program { static void F(object? x, string y, (object, string?) z) { ((object?, object?) a, (object? b, object? c)) = ((x, y), z); a.Item1.ToString(); // 1 a.Item2.ToString(); b.ToString(); c.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // a.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.Item1").WithLocation(6, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(9, 9)); } [Fact] public void Deconstruction_15() { var source = @"class Program { static void F((object?, string) x, object y, string? z) { ((object a, object b), (object x, object y) c) = (x, (y, z)); // 1, 2 a.ToString(); // 3 b.ToString(); c.x.ToString(); c.y.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,59): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((object a, object b), (object x, object y) c) = (x, (y, z)); // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(5, 59), // (5,62): warning CS8619: Nullability of reference types in value of type '(object y, object? z)' doesn't match target type '(object x, object y)'. // ((object a, object b), (object x, object y) c) = (x, (y, z)); // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(y, z)").WithArguments("(object y, object? z)", "(object x, object y)").WithLocation(5, 62), // (6,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(6, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // c.y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.y").WithLocation(9, 9)); } [Fact] public void Deconstruction_16() { var source = @"class Program { static void F<T, U>(T t, U? u) where U : class { T x; U y; (x, _) = (t, u); (_, y) = (t, u); // 1 (x, _, (_, y)) = (t, t, (u, u)); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // (_, y) = (t, u); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(8, 22), // (9,37): warning CS8600: Converting null literal or possible null value to non-nullable type. // (x, _, (_, y)) = (t, t, (u, u)); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(9, 37)); } [Fact] public void Deconstruction_17() { var source = @"class Pair<T, U> where U : class { internal void Deconstruct(out T t, out U? u) => throw null!; } class Program { static void F<T, U>() where U : class { var (t, u) = new Pair<T, U>(); t.ToString(); // 1 u.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u").WithLocation(11, 9)); } [Fact] public void Deconstruction_18() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F<T>() where T : class { (T x1, T y1) = new Pair<T, T?>(); // 1 x1.ToString(); y1.ToString(); // 2 (T? x2, T? y2) = new Pair<T, T?>(); x2.ToString(); y2.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T x1, T y1) = new Pair<T, T?>(); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T y1").WithLocation(9, 16), // (11,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(11, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(14, 9)); } [Fact] public void Deconstruction_19() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F<T, U>() where U : class { (T, U?) t = new Pair<T, U?>(); t.Item1.ToString(); // 1 t.Item2.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,21): error CS0029: Cannot implicitly convert type 'Pair<T, U?>' to '(T, U?)' // (T, U?) t = new Pair<T, U?>(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "new Pair<T, U?>()").WithArguments("Pair<T, U?>", "(T, U?)").WithLocation(9, 21), // (10,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(11, 9)); } [Fact] public void Deconstruction_TupleAndDeconstruct() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F<T>(T? x, Pair<T, T?> y) where T : class { (T a, (T? b, T? c)) = (x, y); // 1 a.ToString(); // 2 b.ToString(); c.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,32): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T a, (T? b, T? c)) = (x, y); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(9, 32), // (10,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(12, 9)); } [Fact] [WorkItem(33005, "https://github.com/dotnet/roslyn/issues/33005")] public void Deconstruction_DeconstructAndTuple() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F<T>(Pair<T?, (T, T?)> p) where T : class { (T a, (T? b, T? c)) = p; // 1 a.ToString(); // 2 b.ToString(); c.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T a, (T? b, T? c)) = p; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T a").WithLocation(9, 10), // (10,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(12, 9) ); } [Fact] [WorkItem(33005, "https://github.com/dotnet/roslyn/issues/33005")] public void Deconstruction_DeconstructAndDeconstruct() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F<T>(Pair<T?, Pair<T, T?>> p) where T : class { (T a, (T? b, T? c)) = p; // 1 a.ToString(); // 2 b.ToString(); c.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T a, (T? b, T? c)) = p; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T a").WithLocation(9, 10), // (10,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(12, 9) ); } [Fact] public void Deconstruction_20() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F1(Pair<object, object>? p1) { var (x, y) = p1; // 1 (x, y) = p1; } static void F2(Pair<object, object>? p2) { if (p2 == null) return; var (x, y) = p2; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,22): warning CS8602: Dereference of a possibly null reference. // var (x, y) = p1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p1").WithLocation(9, 22)); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_21() { var source = @"class Program { static void F<T, U>((T, U) t) where U : struct { object? x; object? y; var u = ((x, y) = t); u.x.ToString(); // 1 u.y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/33011: Should warn for `u.x`. comp.VerifyDiagnostics(); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_22() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F(Pair<object, object?> p) { object? x; object? y; var t = ((x, y) = p); t.x.ToString(); t.y.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/33011: Should warn for `t.y`. comp.VerifyDiagnostics(); } // As above, but with struct type. [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_23() { var source = @"struct Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F(Pair<object, object?> p) { object? x; object? y; var t = ((x, y) = p); t.x.ToString(); t.y.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/33011: Should warn for `t.y` only. comp.VerifyDiagnostics(); } [Fact] public void Deconstruction_24() { var source = @"class Program { static void F(bool b, object x, object? y) { (object?, object, object?, object, object?, (object, object?), object, object, object?, object) t = (x, x, x, y, y, (y, x), x, x, y, y); // 1 var (_1, _2, _3, _4, _5, (_6a, _6b), _7, _8, _9, _10) = t; _1.ToString(); _2.ToString(); _3.ToString(); _4.ToString(); // 2 _5.ToString(); // 3 _6a.ToString(); // 4 _6b.ToString(); _7.ToString(); _8.ToString(); _9.ToString(); // 5 _10.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,109): warning CS8619: Nullability of reference types in value of type '(object, object, object, object?, object?, (object? y, object x), object, object, object?, object?)' doesn't match target type '(object?, object, object?, object, object?, (object, object?), object, object, object?, object)'. // (object?, object, object?, object, object?, (object, object?), object, object, object?, object) t = (x, x, x, y, y, (y, x), x, x, y, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, x, x, y, y, (y, x), x, x, y, y)").WithArguments("(object, object, object, object?, object?, (object? y, object x), object, object, object?, object?)", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object)").WithLocation(5, 109), // (10,9): warning CS8602: Dereference of a possibly null reference. // _4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "_4").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // _5.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "_5").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // _6a.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "_6a").WithLocation(12, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // _9.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "_9").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // _10.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "_10").WithLocation(17, 9)); } [Fact] [WorkItem(33017, "https://github.com/dotnet/roslyn/issues/33017")] public void Deconstruction_25() { var source = @"using System.Collections.Generic; class Program { static void F1<T>(IEnumerable<(T, T)> e1) { foreach (var (x1, y1) in e1) { x1.ToString(); // 1 y1.ToString(); // 2 } foreach ((object? z1, object? w1) in e1) { z1.ToString(); // 3 w1.ToString(); // 4 } } static void F2<T>(IEnumerable<(T, T?)> e2) where T : class { foreach (var (x2, y2) in e2) { x2.ToString(); y2.ToString(); // 5 } foreach ((object? z2, object? w2) in e2) { z2.ToString(); w2.ToString(); // 6 } } static void F3<T>(IEnumerable<(T, T?)> e3) where T : struct { foreach (var (x3, y3) in e3) { x3.ToString(); _ = y3.Value; // 7 } foreach ((object? z3, object? w3) in e3) { z3.ToString(); w3.ToString(); // 8 } } static void F4((object?, object?)[] arr) { foreach ((object, object) el in arr) // 9 { el.Item1.ToString(); el.Item2.ToString(); } foreach ((object i1, object i2) in arr) // 10, 11 { i1.ToString(); // 12 i2.ToString(); // 13 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(8, 13), // (9,13): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // z1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1").WithLocation(13, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // w1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w1").WithLocation(14, 13), // (22,13): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(22, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // w2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w2").WithLocation(27, 13), // (35,17): warning CS8629: Nullable value type may be null. // _ = y3.Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y3").WithLocation(35, 17), // (40,13): warning CS8602: Dereference of a possibly null reference. // w3.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w3").WithLocation(40, 13), // (45,35): warning CS8619: Nullability of reference types in value of type '(object?, object?)' doesn't match target type '(object, object)'. // foreach ((object, object) el in arr) // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "el").WithArguments("(object?, object?)", "(object, object)").WithLocation(45, 35), // (51,44): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach ((object i1, object i2) in arr) // 10, 11 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "arr").WithLocation(51, 44), // (51,44): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach ((object i1, object i2) in arr) // 10, 11 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "arr").WithLocation(51, 44), // (53,13): warning CS8602: Dereference of a possibly null reference. // i1.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "i1").WithLocation(53, 13), // (54,13): warning CS8602: Dereference of a possibly null reference. // i2.ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "i2").WithLocation(54, 13) ); } [Fact] public void Deconstruction_26() { var source = @"class Program { static void F(bool c, object? a, object? b) { if (b == null) return; var (x, y, z, w) = c ? (a, b, a, b) : (a, a, b, b); x.ToString(); // 1 y.ToString(); // 2 z.ToString(); // 3 w.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(9, 9)); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] public void Deconstruction_27() { var source = @"class Program { static void F(object? x, object y) { if (x == null) return; y = null; // 1 var t = (new[] { x }, new[] { y }); var (ax, ay) = t; ax[0].ToString(); ay[0].ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // ay[0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ay[0]").WithLocation(10, 9) ); } [Fact] public void Deconstruction_28() { var source = @"class Program { public void Deconstruct(out int x, out int y) => throw null!; static void F(Program? p) { var (x, y) = p; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,22): warning CS8602: Dereference of a possibly null reference. // var (x, y) = p; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p").WithLocation(7, 22) ); } [Fact] public void Deconstruction_29() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F(Pair<object?, Pair<object, object?>?> p) { (object? x, (object y, object? z)) = p; // 1 x.ToString(); // 2 y.ToString(); z.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // (object? x, (object y, object? z)) = p; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object? x, (object y, object? z)) = p").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(12, 9) ); } [Fact] public void Deconstruction_30() { var source = @" class Pair<T, U> { public void Deconstruct(out T t, out U u) => throw null!; } class Program { static Pair<T, U> CreatePair<T, U>(T t, U u) => new Pair<T, U>(); static void F(string? x, object? y) { if (x == null) return; var p = CreatePair(x, y); (x, y) = p; x.ToString(); // ok y.ToString(); // warning } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(17, 9) ); } [Fact] public void Deconstruction_31() { var source = @" class Pair<T, U> { public void Deconstruct(out T t, out U u) => throw null!; } class Program { static Pair<T, U> CreatePair<T, U>(T t, U u) => new Pair<T, U>(); static void F(string? x, object? y) { if (x == null) return; var p = CreatePair(x, CreatePair(x, y)); object? z; (z, (x, y)) = p; x.ToString(); // ok y.ToString(); // warning } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(18, 9) ); } [Fact] [WorkItem(35131, "https://github.com/dotnet/roslyn/issues/35131")] [WorkItem(33017, "https://github.com/dotnet/roslyn/issues/33017")] public void Deconstruction_32() { var source = @" using System.Collections.Generic; class Pair<T, U> { public void Deconstruct(out T t, out U u) => throw null!; } class Program { static List<Pair<T, U>> CreatePairList<T, U>(T t, U u) => new List<Pair<T, U>>(); static void F(string x, object? y) { foreach((var x2, var y2) in CreatePairList(x, y)) { x2.ToString(); y2.ToString(); // 1 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,13): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(17, 13) ); } [Fact] [WorkItem(35131, "https://github.com/dotnet/roslyn/issues/35131")] [WorkItem(33017, "https://github.com/dotnet/roslyn/issues/33017")] public void Deconstruction_33() { var source = @" using System.Collections.Generic; class Pair<T, U> { public void Deconstruct(out T t, out U u) => throw null!; } class Program { static List<Pair<T, U>> CreatePairList<T, U>(T t, U u) => new List<Pair<T, U>>(); static void F<T>(T x, T? y) where T : class { x = null; // 1 if (y == null) return; foreach((T x2, T? y2) in CreatePairList(x, y)) // 2 { x2.ToString(); // 3 y2.ToString(); } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(15, 13), // (17,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach((T x2, T? y2) in CreatePairList(x, y)) // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T x2").WithLocation(17, 18), // (19,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(19, 13) ); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] public void Deconstruction_34() { var source = @"class Program { static void F(object? x, object y) { if (x == null) return; y = null; // 1 var t = (new[] { x }, y); var (ax, ay) = t; ax[0].ToString(); ay.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // ay.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ay").WithLocation(10, 9) ); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] public void Deconstruction_35() { var source = @" using System.Collections.Generic; class Program { static List<T> MakeList<T>(T a) { throw null!; } static void F(object? x, object y) { if (x == null) return; y = null; // 1 var t = (new[] { x }, MakeList(y)); var (ax, ay) = t; ax[0].ToString(); ay[0].ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 13), // (18,9): warning CS8602: Dereference of a possibly null reference. // ay[0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ay[0]").WithLocation(18, 9) ); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] public void Deconstruction_36() { var source = @" using System.Collections.Generic; class Program { static List<T> MakeList<T>(T a) where T : notnull { throw null!; } static void F(object? x, object y) { if (x == null) return; y = null; // 1 var t = (new[] { x }, MakeList(y)); // 2 var (ax, ay) = t; ax[0].ToString(); ay[0].ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 13), // (14,31): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'Program.MakeList<T>(T)'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // var t = (new[] { x }, MakeList(y)); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "MakeList").WithArguments("Program.MakeList<T>(T)", "T", "object?").WithLocation(14, 31), // (17,9): warning CS8602: Dereference of a possibly null reference. // ay[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ay[0]").WithLocation(17, 9) ); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] public void Deconstruction_37() { var source = @" using System.Collections.Generic; class Program { static List<T> MakeList<T>(T a) { throw null!; } static void F(object? x, object y) { if (x == null) return; y = null; // 1 var ylist = MakeList(y); var ylist2 = MakeList(ylist); var ylist3 = MakeList(ylist2); ylist3 = null; var t = (new[] { x }, MakeList(ylist3)); var (ax, ay) = t; ax[0].ToString(); ay[0].ToString(); // 2 var ay0 = ay[0]; if (ay0 == null) return; ay0[0].ToString(); ay0[0][0].ToString(); ay0[0][0][0].ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 13), // (21,9): warning CS8602: Dereference of a possibly null reference. // ay[0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ay[0]").WithLocation(21, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // ay0[0][0][0].ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ay0[0][0][0]").WithLocation(26, 9) ); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void Deconstruction_38() { var source = @" class Program { static void F(object? x1, object y1) { var t = (x1, y1); var (x2, y2) = t; if (x1 == null) return; y1 = null; // 1 var u = (x1, y1); (x2, y2) = u; x2 = null; y2 = null; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y1 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(9, 14) ); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void Deconstruction_39() { var source = @" class Program { static void F(object? x1, object y1) { if (x1 == null) return; y1 = null; // 1 var t = (x1, y1); var (x2, y2) = (t.Item1, t.Item2); x2 = null; y2 = null; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y1 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 14) ); } [Fact] public void Deconstruction_ExtensionMethod_01() { var source = @"class Pair<T, U> { } static class E { internal static void Deconstruct(this Pair<object?, object>? p, out object x, out object? y) => throw null!; } class Program { static void F(Pair<object, object?>? p) { (object? x, object? y) = p; x.ToString(); y.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,34): warning CS8620: Argument of type 'Pair<object, object?>' cannot be used for parameter 'p' of type 'Pair<object?, object>' in 'void E.Deconstruct(Pair<object?, object>? p, out object x, out object? y)' due to differences in the nullability of reference types. // (object? x, object? y) = p; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "p").WithArguments("Pair<object, object?>", "Pair<object?, object>", "p", "void E.Deconstruct(Pair<object?, object>? p, out object x, out object? y)").WithLocation(12, 34), // (14,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(14, 9)); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_02() { var source = @"struct Pair<T, U> { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U> p, out T t, out U u) => throw null!; } class Program { static void F<T, U>(Pair<T, U> p) where U : class { var (x, y) = p; x.ToString(); // 1 y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 9) ); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_03() { var source = @"class Pair<T, U> { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U> p, out T t, out U u) => throw null!; } class Program { static void F(Pair<object?, object>? p) { (object? x, object? y) = p; // 1 x.ToString(); // 2 y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,34): warning CS8604: Possible null reference argument for parameter 'p' in 'void E.Deconstruct<object?, object>(Pair<object?, object> p, out object? t, out object u)'. // (object? x, object? y) = p; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "p").WithArguments("p", "void E.Deconstruct<object?, object>(Pair<object?, object> p, out object? t, out object u)").WithLocation(12, 34), // (13,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 9) ); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_04() { var source = @"class Pair<T, U> { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U> p, out T t, out U u) => throw null!; } class Program { static void F(Pair<object?, Pair<object, object?>?> p) { (object? x, (object y, object? z)) = p; // 1 x.ToString(); // 2 y.ToString(); z.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8604: Possible null reference argument for parameter 'p' in 'void E.Deconstruct<object, object?>(Pair<object, object?> p, out object t, out object? u)'. // (object? x, (object y, object? z)) = p; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(object? x, (object y, object? z)) = p").WithArguments("p", "void E.Deconstruct<object, object?>(Pair<object, object?> p, out object t, out object? u)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(15, 9) ); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_05() { var source = @"class Pair<T, U> { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U>? p, out T t, out U u) => throw null!; } class Program { static void F(Pair<object?, Pair<object, object?>> p) { (object? x, (object y, object? z)) = p; x.ToString(); // 1 y.ToString(); z.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(15, 9) ); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_06() { var source = @"class Pair<T, U> { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U>? p, out T t, out U u) => throw null!; } class Program { static Pair<T, U> CreatePair<T, U>(T t, U u) => new Pair<T, U>(); static void F(string? x, object? y) { if (x == null) return; var p = CreatePair(x, CreatePair(x, y)); object? z; (z, (x, y)) = p; x.ToString(); // ok y.ToString(); // warning } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(19, 9) ); } [Fact] public void Deconstruction_ExtensionMethod_07() { var source = @"class A<T, U> { } class B : A<object, object?> { } static class E { internal static void Deconstruct(this A<object?, object> a, out object? x, out object y) => throw null!; } class Program { static void F(B b) { (object? x, object? y) = b; // 1 x.ToString(); // 2 y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,34): warning CS8620: Argument of type 'B' cannot be used for parameter 'a' of type 'A<object?, object>' in 'void E.Deconstruct(A<object?, object> a, out object? x, out object y)' due to differences in the nullability of reference types. // (object? x, object? y) = b; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b").WithArguments("B", "A<object?, object>", "a", "void E.Deconstruct(A<object?, object> a, out object? x, out object y)").WithLocation(15, 34), // (16,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 9)); } [Fact] public void Deconstruction_ExtensionMethod_08() { var source = @"#nullable enable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; class Enumerable<T> : IAsyncEnumerable<T> { IAsyncEnumerator<T> IAsyncEnumerable<T>.GetAsyncEnumerator(CancellationToken token) => throw null!; } class Pair<T, U> { } static class E { internal static void Deconstruct(this Pair<object?, object> p, out object? x, out object y) => throw null!; } static class Program { static async Task Main() { var e = new Enumerable<Pair<object, object?>>(); await foreach (var (x1, y1) in e) // 1 { x1.ToString(); // 2 y1.ToString(); } await foreach ((object x2, object? y2) in e) // 3, 4 { x2.ToString(); // 5 y2.ToString(); } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { s_IAsyncEnumerable, source }); comp.VerifyDiagnostics( // (21,40): warning CS8620: Argument of type 'Pair<object, object?>' cannot be used for parameter 'p' of type 'Pair<object?, object>' in 'void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)' due to differences in the nullability of reference types. // await foreach (var (x1, y1) in e) // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "e").WithArguments("Pair<object, object?>", "Pair<object?, object>", "p", "void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)").WithLocation(21, 40), // (23,13): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(23, 13), // (26,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // await foreach ((object x2, object? y2) in e) // 3, 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "object x2").WithLocation(26, 25), // (26,51): warning CS8620: Argument of type 'Pair<object, object?>' cannot be used for parameter 'p' of type 'Pair<object?, object>' in 'void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)' due to differences in the nullability of reference types. // await foreach ((object x2, object? y2) in e) // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "e").WithArguments("Pair<object, object?>", "Pair<object?, object>", "p", "void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)").WithLocation(26, 51), // (28,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(28, 13)); } [Fact] public void Deconstruction_ExtensionMethod_09() { var source = @"#nullable enable using System.Threading.Tasks; class Enumerable<T> { public Enumerator<T> GetAsyncEnumerator() => new Enumerator<T>(); } class Enumerator<T> { public T Current => default!; public ValueTask<bool> MoveNextAsync() => default; public ValueTask DisposeAsync() => default; } class Pair<T, U> { } static class E { internal static void Deconstruct(this Pair<object?, object> p, out object? x, out object y) => throw null!; } static class Program { static async Task Main() { var e = new Enumerable<Pair<object, object?>>(); await foreach (var (x1, y1) in e) // 1 { x1.ToString(); // 2 y1.ToString(); } await foreach ((object x2, object? y2) in e) // 3, 4 { x2.ToString(); // 5 y2.ToString(); } } }"; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyDiagnostics( // (25,40): warning CS8620: Argument of type 'Pair<object, object?>' cannot be used for parameter 'p' of type 'Pair<object?, object>' in 'void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)' due to differences in the nullability of reference types. // await foreach (var (x1, y1) in e) // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "e").WithArguments("Pair<object, object?>", "Pair<object?, object>", "p", "void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)").WithLocation(25, 40), // (27,13): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(27, 13), // (30,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // await foreach ((object x2, object? y2) in e) // 3, 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "object x2").WithLocation(30, 25), // (30,51): warning CS8620: Argument of type 'Pair<object, object?>' cannot be used for parameter 'p' of type 'Pair<object?, object>' in 'void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)' due to differences in the nullability of reference types. // await foreach ((object x2, object? y2) in e) // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "e").WithArguments("Pair<object, object?>", "Pair<object?, object>", "p", "void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)").WithLocation(30, 51), // (32,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(32, 13)); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_ConstraintWarning() { var source = @"class Pair<T, U> where T : class? { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U> p, out T t, out U u) where T : class => throw null!; } class Program { static void F(Pair<object?, object> p) { var (x, y) = p; // 1 x.ToString(); // 2 y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,22): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'E.Deconstruct<T, U>(Pair<T, U>, out T, out U)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // var (x, y) = p; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "p").WithArguments("E.Deconstruct<T, U>(Pair<T, U>, out T, out U)", "T", "object?").WithLocation(14, 22), // (15,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 9) ); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_ConstraintWarning_Nested() { var source = @"class Pair<T, U> where T : class? { } class Pair2<T, U> where U : class? { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U> p, out T t, out U u) where T : class => throw null!; internal static void Deconstruct<T, U>(this Pair2<T, U> p, out T t, out U u) where U : class => throw null!; } class Program { static void F(Pair<object?, Pair2<object, object?>?> p) { var (x, (y, z)) = p; // 1, 2, 3 x.ToString(); // 4 y.ToString(); z.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (21,9): warning CS8604: Possible null reference argument for parameter 'p' in 'void E.Deconstruct<object, object?>(Pair2<object, object?> p, out object t, out object? u)'. // var (x, (y, z)) = p; // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "var (x, (y, z)) = p").WithArguments("p", "void E.Deconstruct<object, object?>(Pair2<object, object?> p, out object t, out object? u)").WithLocation(21, 9), // (21,27): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'E.Deconstruct<T, U>(Pair<T, U>, out T, out U)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // var (x, (y, z)) = p; // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "p").WithArguments("E.Deconstruct<T, U>(Pair<T, U>, out T, out U)", "T", "object?").WithLocation(21, 27), // (21,27): warning CS8634: The type 'object?' cannot be used as type parameter 'U' in the generic type or method 'E.Deconstruct<T, U>(Pair2<T, U>, out T, out U)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // var (x, (y, z)) = p; // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "p").WithArguments("E.Deconstruct<T, U>(Pair2<T, U>, out T, out U)", "U", "object?").WithLocation(21, 27), // (22,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(24, 9) ); } [Fact] public void Deconstruction_EvaluationOrder_01() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C { internal object F; } class Program { static void F0(C? x0, C? y0) { (x0.F, // 1 x0.F) = (y0.F, // 2 y0.F); } static void F1(C? x1, C? y1) { (x1.F, // 3 _) = (y1.F, // 4 x1.F); } static void F2(C? x2, C? y2) { (_, y2.F) = // 5 (y2.F, x2.F); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,10): warning CS8602: Dereference of a possibly null reference. // (x0.F, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(11, 10), // (13,18): warning CS8602: Dereference of a possibly null reference. // (y0.F, // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(13, 18), // (18,10): warning CS8602: Dereference of a possibly null reference. // (x1.F, // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(18, 10), // (20,18): warning CS8602: Dereference of a possibly null reference. // (y1.F, // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(20, 18), // (26,13): warning CS8602: Dereference of a possibly null reference. // y2.F) = // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(26, 13), // (28,21): warning CS8602: Dereference of a possibly null reference. // x2.F); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(28, 21)); } [Fact] public void Deconstruction_EvaluationOrder_02() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C { internal object F; } class Program { static void F0(C? x0, C? y0, C? z0) { ((x0.F, // 1 y0.F), // 2 z0.F) = // 3 ((y0.F, z0.F), x0.F); } static void F1(C? x1, C? y1, C? z1) { ((x1.F, // 4 _), x1.F) = ((y1.F, // 5 z1.F), // 6 z1.F); } static void F2(C? x2, C? y2, C? z2) { ((_, _), x2.F) = // 7 ((x2.F, y2.F), // 8 z2.F); // 9 } static void F3(C? x3, C? y3, C? z3) { (x3.F, // 10 (x3.F, y3.F)) = // 11 (y3.F, (z3.F, // 12 x3.F)); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,11): warning CS8602: Dereference of a possibly null reference. // ((x0.F, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(11, 11), // (12,13): warning CS8602: Dereference of a possibly null reference. // y0.F), // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(12, 13), // (13,17): warning CS8602: Dereference of a possibly null reference. // z0.F) = // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(13, 17), // (20,11): warning CS8602: Dereference of a possibly null reference. // ((x1.F, // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(20, 11), // (23,23): warning CS8602: Dereference of a possibly null reference. // ((y1.F, // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(23, 23), // (24,25): warning CS8602: Dereference of a possibly null reference. // z1.F), // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1").WithLocation(24, 25), // (31,17): warning CS8602: Dereference of a possibly null reference. // x2.F) = // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(31, 17), // (33,25): warning CS8602: Dereference of a possibly null reference. // y2.F), // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(33, 25), // (34,29): warning CS8602: Dereference of a possibly null reference. // z2.F); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2").WithLocation(34, 29), // (38,10): warning CS8602: Dereference of a possibly null reference. // (x3.F, // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(38, 10), // (40,17): warning CS8602: Dereference of a possibly null reference. // y3.F)) = // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y3").WithLocation(40, 17), // (42,26): warning CS8602: Dereference of a possibly null reference. // (z3.F, // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z3").WithLocation(42, 26)); } [Fact] public void Deconstruction_EvaluationOrder_03() { var source = @"#pragma warning disable 8618 class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; internal T First; internal U Second; } class Program { static void F0(Pair<object, object>? p0) { (_, _) = p0; // 1 } static void F1(Pair<object, object>? p1) { (_, p1.Second) = // 2 p1; } static void F2(Pair<object, object>? p2) { (p2.First, // 3 _) = p2; } static void F3(Pair<object, object>? p3) { (p3.First, // 4 p3.Second) = p3; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // p0; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p0").WithLocation(14, 17), // (19,13): warning CS8602: Dereference of a possibly null reference. // p1.Second) = // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p1").WithLocation(19, 13), // (24,10): warning CS8602: Dereference of a possibly null reference. // (p2.First, // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p2").WithLocation(24, 10), // (30,10): warning CS8602: Dereference of a possibly null reference. // (p3.First, // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p3").WithLocation(30, 10)); } [Fact] public void Deconstruction_EvaluationOrder_04() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class Pair { internal void Deconstruct(out object x, out object y) => throw null!; internal object First; internal object Second; } class Program { static void F0(Pair? x0, Pair? y0) { ((x0.First, // 1 _), y0.First) = // 2 (x0, y0.Second); } static void F1(Pair? x1, Pair? y1) { ((_, y1.First), // 3 _) = (x1, // 4 y1.Second); } static void F2(Pair? x2, Pair? y2) { ((_, _), x2.First) = // 5 (x2, y2.Second); // 6 } static void F3(Pair? x3, Pair? y3) { (x3.First, // 7 (_, y3.First)) = // 8 (y3.Second, x3); } static void F4(Pair? x4, Pair? y4) { (_, (x4.First, // 9 _)) = (x4.Second, y4); // 10 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,11): warning CS8602: Dereference of a possibly null reference. // ((x0.First, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(13, 11), // (15,17): warning CS8602: Dereference of a possibly null reference. // y0.First) = // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(15, 17), // (22,13): warning CS8602: Dereference of a possibly null reference. // y1.First), // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(22, 13), // (24,22): warning CS8602: Dereference of a possibly null reference. // (x1, // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(24, 22), // (31,17): warning CS8602: Dereference of a possibly null reference. // x2.First) = // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(31, 17), // (33,25): warning CS8602: Dereference of a possibly null reference. // y2.Second); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(33, 25), // (37,10): warning CS8602: Dereference of a possibly null reference. // (x3.First, // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(37, 10), // (39,17): warning CS8602: Dereference of a possibly null reference. // y3.First)) = // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y3").WithLocation(39, 17), // (46,14): warning CS8602: Dereference of a possibly null reference. // (x4.First, // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(46, 14), // (49,25): warning CS8602: Dereference of a possibly null reference. // y4); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y4").WithLocation(49, 25)); } [Fact] public void Deconstruction_ImplicitBoxingConversion_01() { var source = @"class Program { static void F<T, U, V>((T, U, V?) t) where U : struct where V : struct { (object a, object b, object c) = t; // 1, 2 a.ToString(); // 3 b.ToString(); c.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,42): warning CS8600: Converting null literal or possible null value to non-nullable type. // (object a, object b, object c) = t; // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(7, 42), // (7,42): warning CS8600: Converting null literal or possible null value to non-nullable type. // (object a, object b, object c) = t; // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(7, 42), // (8,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(10, 9)); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_ImplicitBoxingConversion_02() { var source = @"class Program { static void F<T>(T x, T? y) where T : struct { (T?, T?) t = (x, y); (object? a, object? b) = t; a.ToString(); b.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(8, 9)); } [Fact] public void Deconstruction_ImplicitNullableConversion_01() { var source = @"struct S { internal object F; } class Program { static void F(S s) { (S? x, S? y, S? z) = (s, new S(), default); _ = x.Value; x.Value.F.ToString(); _ = y.Value; y.Value.F.ToString(); // 1 _ = z.Value; // 2 z.Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,21): warning CS0649: Field 'S.F' is never assigned to, and will always have its default value null // internal object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("S.F", "null").WithLocation(3, 21), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.Value.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.F").WithLocation(13, 9), // (14,13): warning CS8629: Nullable value type may be null. // _ = z.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "z").WithLocation(14, 13)); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_ImplicitNullableConversion_02() { var source = @"#pragma warning disable 0649 struct S { internal object F; } class Program { static void F(S s) { (S, S) t = (s, new S()); (S? x, S? y) = t; _ = x.Value; x.Value.F.ToString(); _ = y.Value; y.Value.F.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // y.Value.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.F").WithLocation(15, 9)); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_ImplicitNullableConversion_03() { var source = @"#pragma warning disable 0649 struct S<T> { internal T F; } class Program { static void F<T>((S<T?>, S<T>) t) where T : class, new() { (S<T>? x, S<T?>? y) = t; // 1, 2 x.Value.F.ToString(); // 3 y.Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,31): warning CS8619: Nullability of reference types in value of type 'S<T?>' doesn't match target type 'S<T>?'. // (S<T>? x, S<T?>? y) = t; // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("S<T?>", "S<T>?").WithLocation(10, 31), // (10,31): warning CS8619: Nullability of reference types in value of type 'S<T>' doesn't match target type 'S<T?>?'. // (S<T>? x, S<T?>? y) = t; // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("S<T>", "S<T?>?").WithLocation(10, 31), // (11,9): warning CS8602: Dereference of a possibly null reference. // x.Value.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.F").WithLocation(11, 9)); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_ImplicitNullableConversion_04() { var source = @"#pragma warning disable 0649 struct S<T> { internal T F; } class Program { static void F<T>((object, (S<T?>, S<T>)) t) where T : class, new() { (object a, (S<T>? x, S<T?>? y) b) = t; // 1 b.x.Value.F.ToString(); // 2 b.y.Value.F.ToString(); // 3, 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,45): warning CS8619: Nullability of reference types in value of type '(S<T?>, S<T>)' doesn't match target type '(S<T>? x, S<T?>? y)'. // (object a, (S<T>? x, S<T?>? y) b) = t; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("(S<T?>, S<T>)", "(S<T>? x, S<T?>? y)").WithLocation(10, 45), // (11,9): warning CS8629: Nullable value type may be null. // b.x.Value.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "b.x").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // b.y.Value.F.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "b.y").WithLocation(12, 9), // (12,9): warning CS8602: Possible dereference of a null reference. // b.y.Value.F.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.y.Value.F").WithLocation(12, 9)); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_ImplicitUserDefinedConversion_01() { var source = @"class A { } class B { public static implicit operator B?(A a) => new B(); } class Program { static void F((object, (A?, A)) t) { (object x, (B?, B) y) = t; } }"; // https://github.com/dotnet/roslyn/issues/33011 Should have warnings about conversions from B? to B and from A? to A var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Deconstruction_TooFewVariables() { var source = @"class Program { static void F(object x, object y, object? z) { (object? a, object? b) = (x, y, z = 3); a.ToString(); b.ToString(); z.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS8132: Cannot deconstruct a tuple of '3' elements into '2' variables. // (object? a, object? b) = (x, y, z = 3); Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(object? a, object? b) = (x, y, z = 3)").WithArguments("3", "2").WithLocation(5, 9), // (6,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 9)); } [Fact] public void Deconstruction_TooManyVariables() { var source = @"class Program { static void F(object x, object y) { (object? a, object? b, object? c) = (x, y = null); // 1 a.ToString(); // 2 b.ToString(); // 3 c.ToString(); // 4 y.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables. // (object? a, object? b, object? c) = (x, y = null); // 1 Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(object? a, object? b, object? c) = (x, y = null)").WithArguments("2", "3").WithLocation(5, 9), // (5,53): warning CS8600: Converting null literal or possible null value to non-nullable type. // (object? a, object? b, object? c) = (x, y = null); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 53), // (6,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9)); } [Fact] public void Deconstruction_NoDeconstruct_01() { var source = @"class C { C(object o) { } static void F() { object? z = null; var (x, y) = new C(z = 1); x.ToString(); y.ToString(); z.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = new C(z = 1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(7, 14), // (7,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = new C(z = 1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(7, 17), // (7,22): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // var (x, y) = new C(z = 1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C(z = 1)").WithArguments("C", "Deconstruct").WithLocation(7, 22), // (7,22): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. // var (x, y) = new C(z = 1); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C(z = 1)").WithArguments("C", "2").WithLocation(7, 22)); } [Fact] public void Deconstruction_NoDeconstruct_02() { var source = @"class C { C(object o) { } static void F() { object? z = null; (object? x, object? y) = new C(z = 1); x.ToString(); y.ToString(); z.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,34): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // (object? x, object? y) = new C(z = 1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C(z = 1)").WithArguments("C", "Deconstruct").WithLocation(7, 34), // (7,34): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. // (object? x, object? y) = new C(z = 1); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C(z = 1)").WithArguments("C", "2").WithLocation(7, 34), // (8,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9)); } [Fact] public void Deconstruction_TooFewDeconstructArguments() { var source = @"class C { internal void Deconstruct(out object x, out object y, out object z) => throw null!; } class Program { static void F() { (object? x, object? y) = new C(); x.ToString(); y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,34): error CS7036: There is no argument given that corresponds to the required formal parameter 'z' of 'C.Deconstruct(out object, out object, out object)' // (object? x, object? y) = new C(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "new C()").WithArguments("z", "C.Deconstruct(out object, out object, out object)").WithLocation(9, 34), // (9,34): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. // (object? x, object? y) = new C(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(9, 34), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 9)); } [Fact] public void Deconstruction_TooManyDeconstructArguments() { var source = @"class C { internal void Deconstruct(out object x, out object y) => throw null!; } class Program { static void F() { (object? x, object? y, object? z) = new C(); x.ToString(); y.ToString(); z.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,45): error CS1501: No overload for method 'Deconstruct' takes 3 arguments // (object? x, object? y, object? z) = new C(); Diagnostic(ErrorCode.ERR_BadArgCount, "new C()").WithArguments("Deconstruct", "3").WithLocation(9, 45), // (9,45): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 3 out parameters and a void return type. // (object? x, object? y, object? z) = new C(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "3").WithLocation(9, 45), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(12, 9)); } [Fact] [WorkItem(26628, "https://github.com/dotnet/roslyn/issues/26628")] public void ImplicitConstructor_01() { var source = @"#pragma warning disable 414 class Program { object F = null; // warning }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F = null; // warning Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 16)); } [Fact] [WorkItem(26628, "https://github.com/dotnet/roslyn/issues/26628")] public void ImplicitStaticConstructor_01() { var source = @"#pragma warning disable 414 class Program { static object F = null; // warning }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,23): warning CS8625: Cannot convert null literal to non-nullable reference type. // static object F = null; // warning Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 23)); } [Fact] [WorkItem(26628, "https://github.com/dotnet/roslyn/issues/26628")] [WorkItem(33394, "https://github.com/dotnet/roslyn/issues/33394")] public void ImplicitStaticConstructor_02() { var source = @"class C { C(string s) { } static C Empty = new C(null); // warning }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // static C Empty = new C(null); // warning Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 28)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_01() { var source = @"class Program { static void F(ref object? x, ref object y) { x = 1; y = null; // 1 x.ToString(); y.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // y = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 13), // (8,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(8, 9)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_02() { var source = @"class Program { static void F(object? px, object py) { ref object? x = ref px; ref object y = ref py; x = 1; y = null; // 1 x.ToString(); y.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // y = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(10, 9)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_03() { var source = @"class Program { static void F(ref int? x, ref int? y) { x = 1; y = null; _ = x.Value; _ = y.Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8629: Nullable value type may be null. // _ = y.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(8, 13)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_04() { var source = @"class Program { static void F(int? px, int? py) { ref int? x = ref px; ref int? y = ref py; x = 1; y = null; _ = x.Value; _ = y.Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8629: Nullable value type may be null. // _ = y.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(10, 13)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_05() { var source = @"#pragma warning disable 8618 class C { internal object F; } class Program { static void F(ref C x, ref C y) { x = new C() { F = 1 }; y = new C() { F = null }; // 1 x.F.ToString(); y.F.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,27): warning CS8625: Cannot convert null literal to non-nullable reference type. // y = new C() { F = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 27), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(13, 9)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_06() { var source = @"#pragma warning disable 8618 class C { internal object? F; } class Program { static void F(ref C x, ref C y) { x = new C() { F = 1 }; y = new C() { F = null }; x.F.ToString(); y.F.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(13, 9)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_07() { var source = @"#pragma warning disable 8618 class C { internal object F; } class Program { static void F(C px, C py) { ref C x = ref px; ref C y = ref py; x = new C() { F = 1 }; y = new C() { F = null }; // 1 x.F.ToString(); y.F.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,27): warning CS8625: Cannot convert null literal to non-nullable reference type. // y = new C() { F = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 27), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(15, 9)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_08() { var source = @"#pragma warning disable 8618 class C { internal object? F; } class Program { static void F(C px, C py) { ref C x = ref px; ref C y = ref py; x = new C() { F = 1 }; y = new C() { F = null }; x.F.ToString(); y.F.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(15, 9)); } [Fact] [WorkItem(33095, "https://github.com/dotnet/roslyn/issues/33095")] public void ByRefTarget_09() { var source = @"class Program { static void F(ref string x) { ref string? y = ref x; // 1 y = null; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,29): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // ref string? y = ref x; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("string", "string?").WithLocation(5, 29) ); } [Fact] [WorkItem(33095, "https://github.com/dotnet/roslyn/issues/33095")] public void ByRefTarget_10() { var source = @"class Program { static ref string F1(ref string? x) { return ref x; // 1 } static ref string? F2(ref string y) { return ref y; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // return ref x; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("string?", "string").WithLocation(5, 20), // (9,20): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // return ref y; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("string", "string?").WithLocation(9, 20) ); } [Fact] public void AssignmentToSameVariable_01() { var source = @"#pragma warning disable 8618 class C { internal C F; } class Program { static void F() { C a = new C() { F = null }; // 1 a = a; a.F.ToString(); // 2 C b = new C() { F = new C() { F = null } }; // 3 b.F = b.F; b.F.F.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // C a = new C() { F = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 29), // (11,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // a = a; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "a = a").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // a.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.F").WithLocation(12, 9), // (13,43): warning CS8625: Cannot convert null literal to non-nullable reference type. // C b = new C() { F = new C() { F = null } }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 43), // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // b.F = b.F; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "b.F = b.F").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.F.F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.F.F").WithLocation(15, 9)); } [Fact] public void AssignmentToSameVariable_02() { var source = @"#pragma warning disable 8618 struct A { internal int? F; } struct B { internal A A; } class Program { static void F() { A a = new A() { F = 1 }; a = a; _ = a.F.Value; B b = new B() { A = new A() { F = 2 } }; b.A = b.A; _ = b.A.F.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // a = a; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "a = a").WithLocation(15, 9), // (18,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // b.A = b.A; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "b.A = b.A").WithLocation(18, 9)); } [Fact] public void AssignmentToSameVariable_03() { var source = @"#pragma warning disable 8618 class C { internal object F; } class Program { static void F(C? c) { c.F = c.F; // 1 c.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // c.F = c.F; // 1 Diagnostic(ErrorCode.WRN_AssignmentToSelf, "c.F = c.F").WithLocation(10, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.F = c.F; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(10, 9)); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_01() { var source = @"class Program { static readonly string? F = null; static readonly int? G = null; static void Main() { if (F != null) F.ToString(); if (G != null) _ = G.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_02() { var source = @"#pragma warning disable 0649, 8618 class C<T> { static T F; static void M() { if (F == null) return; F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_03() { var source = @"#pragma warning disable 0649, 8618 class C<T> { internal static T F; } class Program { static void F1<T1>() { C<T1>.F.ToString(); // 1 C<T1>.F.ToString(); } static void F2<T2>() where T2 : class { C<T2?>.F.ToString(); // 2 C<T2>.F.ToString(); } static void F3<T3>() where T3 : class { C<T3>.F.ToString(); C<T3?>.F.ToString(); } static void F4<T4>() where T4 : struct { _ = C<T4?>.F.Value; // 3 _ = C<T4?>.F.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // C<T1>.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T1>.F").WithLocation(10, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // C<T2?>.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T2?>.F").WithLocation(15, 9), // (25,13): warning CS8629: Nullable value type may be null. // _ = C<T4?>.F.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "C<T4?>.F").WithLocation(25, 13)); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_04() { var source = @"#pragma warning disable 0649, 8618 class C<T> { internal static T F; } class Program { static void F1<T1>() { C<T1>.F = default; // 1 C<T1>.F.ToString(); // 2 } static void F2<T2>() where T2 : class, new() { C<T2?>.F = new T2(); C<T2?>.F.ToString(); } static void F3<T3>() where T3 : class, new() { C<T3>.F = new T3(); C<T3>.F.ToString(); } static void F4<T4>() where T4 : class { C<T4>.F = null; // 3 C<T4>.F.ToString(); // 4 } static void F5<T5>() where T5 : struct { C<T5?>.F = default(T5); _ = C<T5?>.F.Value; } static void F6<T6>() where T6 : new() { C<T6>.F = new T6(); C<T6>.F.ToString(); } static void F7() { C<string>.F = null; // 5 _ = C<string>.F.Length; // 6 } static void F8() { C<int?>.F = 3; _ = C<int?>.F.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,19): warning CS8601: Possible null reference assignment. // C<T1>.F = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(10, 19), // (11,9): warning CS8602: Dereference of a possibly null reference. // C<T1>.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T1>.F").WithLocation(11, 9), // (25,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // C<T4>.F = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(25, 19), // (26,9): warning CS8602: Dereference of a possibly null reference. // C<T4>.F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T4>.F").WithLocation(26, 9), // (40,23): warning CS8625: Cannot convert null literal to non-nullable reference type. // C<string>.F = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(40, 23), // (41,13): warning CS8602: Dereference of a possibly null reference. // _ = C<string>.F.Length; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<string>.F").WithLocation(41, 13)); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_05() { var source = @"class C<T> { internal static T P { get => throw null!; set { } } } class Program { static void F1<T1>() { C<T1>.P = default; // 1 C<T1>.P.ToString(); // 2 } static void F2<T2>() where T2 : class, new() { C<T2?>.P = new T2(); C<T2?>.P.ToString(); } static void F3<T3>() where T3 : class, new() { C<T3>.P = new T3(); C<T3>.P.ToString(); } static void F4<T4>() where T4 : class { C<T4>.P = null; // 3 C<T4>.P.ToString(); // 4 } static void F5<T5>() where T5 : struct { C<T5?>.P = default(T5); _ = C<T5?>.P.Value; } static void F6<T6>() where T6 : new() { C<T6>.P = new T6(); C<T6>.P.ToString(); } static void F7() { C<string>.P = null; // 5 _ = C<string>.P.Length; // 6 } static void F8() { C<int?>.P = 3; _ = C<int?>.P.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,19): warning CS8601: Possible null reference assignment. // C<T1>.P = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(13, 19), // (14,9): warning CS8602: Dereference of a possibly null reference. // C<T1>.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T1>.P").WithLocation(14, 9), // (28,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // C<T4>.P = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(28, 19), // (29,9): warning CS8602: Dereference of a possibly null reference. // C<T4>.P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T4>.P").WithLocation(29, 9), // (43,23): warning CS8625: Cannot convert null literal to non-nullable reference type. // C<string>.P = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(43, 23), // (44,13): warning CS8602: Dereference of a possibly null reference. // _ = C<string>.P.Length; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<string>.P").WithLocation(44, 13)); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_06() { var source = @"#pragma warning disable 0649, 8618 struct S<T> { internal static T F; } class Program { static void F1<T1>() { S<T1>.F = default; // 1 S<T1>.F.ToString(); // 2 } static void F2<T2>() where T2 : class, new() { S<T2?>.F = new T2(); S<T2?>.F.ToString(); } static void F3<T3>() where T3 : class { S<T3>.F = null; // 3 S<T3>.F.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,19): warning CS8601: Possible null reference assignment. // S<T1>.F = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(10, 19), // (11,9): warning CS8602: Dereference of a possibly null reference. // S<T1>.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "S<T1>.F").WithLocation(11, 9), // (20,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // S<T3>.F = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 19), // (21,9): warning CS8602: Dereference of a possibly null reference. // S<T3>.F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "S<T3>.F").WithLocation(21, 9)); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_07() { var source = @"struct S<T> { internal static T P { get; set; } } class Program { static void F1<T1>() { S<T1>.P = default; // 1 S<T1>.P.ToString(); // 2 } static void F2<T2>() where T2 : class, new() { S<T2?>.P = new T2(); S<T2?>.P.ToString(); } static void F3<T3>() where T3 : class { S<T3>.P = null; // 3 S<T3>.P.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,23): warning CS8618: Non-nullable property 'P' is uninitialized. Consider declaring the property as nullable. // internal static T P { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "P").WithArguments("property", "P").WithLocation(3, 23), // (9,19): warning CS8601: Possible null reference assignment. // S<T1>.P = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(9, 19), // (10,9): warning CS8602: Dereference of a possibly null reference. // S<T1>.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "S<T1>.P").WithLocation(10, 9), // (19,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // S<T3>.P = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 19), // (20,9): warning CS8602: Dereference of a possibly null reference. // S<T3>.P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "S<T3>.P").WithLocation(20, 9)); } [Fact] public void Expression_VoidReturn() { var source = @"class Program { static object F(object x) => x; static void G(object? y) { return F(y); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): error CS0127: Since 'Program.G(object?)' returns void, a return keyword must not be followed by an object expression // return F(y); Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("Program.G(object?)").WithLocation(6, 9), // (6,18): warning CS8604: Possible null reference argument for parameter 'x' in 'object Program.F(object x)'. // return F(y); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "object Program.F(object x)").WithLocation(6, 18)); } [Fact] public void Expression_AsyncTaskReturn() { var source = @"using System.Threading.Tasks; class Program { static object F(object x) => x; static async Task G(object? y) { await Task.Delay(0); return F(y); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): error CS1997: Since 'Program.G(object?)' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'? // return F(y); Diagnostic(ErrorCode.ERR_TaskRetNoObjectRequired, "return").WithArguments("Program.G(object?)").WithLocation(8, 9), // (8,18): warning CS8604: Possible null reference argument for parameter 'x' in 'object Program.F(object x)'. // return F(y); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "object Program.F(object x)").WithLocation(8, 18)); } [Fact] [WorkItem(33481, "https://github.com/dotnet/roslyn/issues/33481")] public void TypelessTuple_VoidReturn() { var source = @"class Program { static void F() { return (null, string.Empty); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS0127: Since 'Program.F()' returns void, a return keyword must not be followed by an object expression // return (null, string.Empty); Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("Program.F()").WithLocation(5, 9)); } [Fact] [WorkItem(33481, "https://github.com/dotnet/roslyn/issues/33481")] public void TypelessTuple_AsyncTaskReturn() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Delay(0); return (null, string.Empty); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): error CS1997: Since 'Program.F()' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'? // return (null, string.Empty); Diagnostic(ErrorCode.ERR_TaskRetNoObjectRequired, "return").WithArguments("Program.F()").WithLocation(7, 9)); } [Fact] public void TypelessTuple_VoidLambdaReturn() { var source = @"class Program { static void F() { _ = new System.Action(() => { return (null, string.Empty); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // return (null, string.Empty); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 13)); } [Fact] public void TypelessTuple_AsyncTaskLambdaReturn() { var source = @"using System.Threading.Tasks; class Program { static void F() { _ = new System.Func<Task>(async () => { await Task.Delay(0); return (null, string.Empty); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): error CS8031: Async lambda expression converted to a 'Task' returning delegate cannot return a value. Did you intend to return 'Task<T>'? // return (null, string.Empty); Diagnostic(ErrorCode.ERR_TaskRetNoObjectRequiredLambda, "return").WithLocation(9, 13)); } [Fact] [WorkItem(29967, "https://github.com/dotnet/roslyn/issues/29967")] public void InterfaceProperties_01() { var source = @"interface IA<T> { T A { get; } } interface IB<T> : IA<T> { T B { get; } } class Program { static IB<T> CreateB<T>(T t) { throw null!; } static void F1<T>(T x1) { if (x1 == null) return; var y1 = CreateB(x1); y1.A.ToString(); // 1 y1.B.ToString(); // 2 } static void F2<T>() where T : class { T x2 = null; // 3 var y2 = CreateB(x2); y2.ToString(); y2.A.ToString(); // 4 y2.B.ToString(); // 5 } static void F3<T>() where T : class, new() { T? x3 = new T(); var y3 = CreateB(x3); y3.A.ToString(); y3.B.ToString(); } static void F4<T>() where T : struct { T? x4 = null; var y4 = CreateB(x4); _ = y4.A.Value; // 6 _ = y4.B.Value; // 7 } static void F5<T>() where T : struct { T? x5 = new T(); var y5 = CreateB(x5); _ = y5.A.Value; // 8 _ = y5.B.Value; // 9 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // y1.A.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1.A").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // y1.B.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1.B").WithLocation(20, 9), // (24,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x2 = null; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(24, 16), // (27,9): warning CS8602: Dereference of a possibly null reference. // y2.A.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2.A").WithLocation(27, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // y2.B.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2.B").WithLocation(28, 9), // (41,13): warning CS8629: Nullable value type may be null. // _ = y4.A.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y4.A").WithLocation(41, 13), // (42,13): warning CS8629: Nullable value type may be null. // _ = y4.B.Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y4.B").WithLocation(42, 13), // (48,13): warning CS8629: Nullable value type may be null. // _ = y5.A.Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y5.A").WithLocation(48, 13), // (49,13): warning CS8629: Nullable value type may be null. // _ = y5.B.Value; // 9 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y5.B").WithLocation(49, 13)); } [Fact] [WorkItem(29967, "https://github.com/dotnet/roslyn/issues/29967")] public void InterfaceProperties_02() { var source = @"interface IA<T> { T A { get; } } interface IB<T> { T B { get; } } interface IC<T, U> : IA<T>, IB<U> { } class Program { static IC<T, U> CreateC<T, U>(T t, U u) { throw null!; } static void F<T, U>() where T : class, new() where U : class { T? x = new T(); T y = null; // 1 var xy = CreateC(x, y); xy.A.ToString(); xy.B.ToString(); // 2 var yx = CreateC(y, x); yx.A.ToString(); // 3 yx.B.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(23, 15), // (26,9): warning CS8602: Dereference of a possibly null reference. // xy.B.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xy.B").WithLocation(26, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // yx.A.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "yx.A").WithLocation(28, 9)); } [Fact] [WorkItem(29967, "https://github.com/dotnet/roslyn/issues/29967")] public void InterfaceMethods_01() { var source = @"interface IA<T> { void A(T t); } interface IB<T> : IA<T> { void B(T t); } class Program { static bool b = false; static IB<T> CreateB<T>(T t) { throw null!; } static void F1<T>(T x1) { if (x1 == null) return; T y1 = default; var ix1 = CreateB(x1); var iy1 = b ? CreateB(y1) : null!; if (b) ix1.A(y1); // 1 if (b) ix1.B(y1); // 2 iy1.A(x1); iy1.B(x1); } static void F2<T>() where T : class, new() { T x2 = null; // 3 T? y2 = new T(); var ix2 = CreateB(x2); var iy2 = CreateB(y2); if (b) ix2.A(y2); if (b) ix2.B(y2); if (b) iy2.A(x2); // 4 if (b) iy2.B(x2); // 5 } static void F3<T>() where T : struct { T? x3 = null; T? y3 = new T(); var ix3 = CreateB(x3); var iy3 = CreateB(y3); ix3.A(y3); ix3.B(y3); iy3.A(x3); iy3.B(x3); } }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (22,22): warning CS8604: Possible null reference argument for parameter 't' in 'void IA<T>.A(T t)'. // if (b) ix1.A(y1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y1").WithArguments("t", "void IA<T>.A(T t)").WithLocation(22, 22), // (23,22): warning CS8604: Possible null reference argument for parameter 't' in 'void IB<T>.B(T t)'. // if (b) ix1.B(y1); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y1").WithArguments("t", "void IB<T>.B(T t)").WithLocation(23, 22), // (29,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x2 = null; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(29, 16), // (35,22): warning CS8604: Possible null reference argument for parameter 't' in 'void IA<T>.A(T t)'. // if (b) iy2.A(x2); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("t", "void IA<T>.A(T t)").WithLocation(35, 22), // (36,22): warning CS8604: Possible null reference argument for parameter 't' in 'void IB<T>.B(T t)'. // if (b) iy2.B(x2); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("t", "void IB<T>.B(T t)").WithLocation(36, 22)); } [Fact] [WorkItem(29967, "https://github.com/dotnet/roslyn/issues/29967")] public void InterfaceMethods_02() { var source = @"interface IA { T A<T>(T u); } interface IB<T> { T B<U>(U u); } interface IC<T> : IA, IB<T> { } class Program { static IC<T> CreateC<T>(T t) { throw null!; } static void F<T, U>() where T : class, new() where U : class { T? x = new T(); U y = null; // 1 var ix = CreateC(x); var iy = CreateC(y); ix.A(y).ToString(); // 2 ix.B(y).ToString(); iy.A(x).ToString(); iy.B(x).ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // U y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(23, 15), // (26,9): warning CS8602: Dereference of a possibly null reference. // ix.A(y).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ix.A(y)").WithLocation(26, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // iy.B(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "iy.B(x)").WithLocation(29, 9)); } [Fact] [WorkItem(36018, "https://github.com/dotnet/roslyn/issues/36018")] public void InterfaceMethods_03() { var source = @" #nullable enable interface IEquatable<T> { bool Equals(T other); } interface I1 : IEquatable<I1?>, IEquatable<string?> { } class C1 : I1 { public bool Equals(string? other) { return true; } public bool Equals(I1? other) { return true; } } class C2 { void M(I1 x, string y) { x.Equals(y); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(36018, "https://github.com/dotnet/roslyn/issues/36018")] public void InterfaceMethods_04() { var source = @" #nullable enable interface IEquatable<T> { bool Equals(T other); } interface I1 : IEquatable<I1>, IEquatable<string> { } class C1 : I1 { public bool Equals(string other) { return true; } public bool Equals(I1 other) { return true; } } class C2 { void M(I1 x, string? y) { x.Equals(y); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (28,18): warning CS8604: Possible null reference argument for parameter 'other' in 'bool IEquatable<string>.Equals(string other)'. // x.Equals(y); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("other", "bool IEquatable<string>.Equals(string other)").WithLocation(28, 18) ); } [Fact] [WorkItem(36018, "https://github.com/dotnet/roslyn/issues/36018")] public void InterfaceMethods_05() { var source = @" #nullable enable interface IEquatable<T> { bool Equals(T other); } interface I1<T> : IEquatable<I1<T>>, IEquatable<T> { } class C2 { void M(string? y, string z) { GetI1(y).Equals(y); GetI1(z).Equals(y); } I1<T> GetI1<T>(T x) => throw null!; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (16,25): warning CS8604: Possible null reference argument for parameter 'other' in 'bool IEquatable<string>.Equals(string other)'. // GetI1(z).Equals(y); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("other", "bool IEquatable<string>.Equals(string other)").WithLocation(16, 25) ); } [Fact, WorkItem(33347, "https://github.com/dotnet/roslyn/issues/33347")] public void NestedNullConditionalAccess() { var source = @" class Node { public Node? Next = null; void M(Node node) { } private static void Test(Node? node) { node?.Next?.Next?.M(node.Next); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31909, "https://github.com/dotnet/roslyn/issues/31909")] public void NestedNullConditionalAccess2() { var source = @" public class C { public C? f; void Test1(C? c) => c?.f.M(c.f.ToString()); // nested use of `c.f` is safe void Test2(C? c) => c.f.M(c.f.ToString()); void M(string s) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,27): warning CS8602: Dereference of a possibly null reference. // void Test1(C? c) => c?.f.M(c.f.ToString()); // nested use of `c.f` is safe Diagnostic(ErrorCode.WRN_NullReferenceReceiver, ".f").WithLocation(5, 27), // (6,25): warning CS8602: Dereference of a possibly null reference. // void Test2(C? c) => c.f.M(c.f.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(6, 25), // (6,25): warning CS8602: Dereference of a possibly null reference. // void Test2(C? c) => c.f.M(c.f.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.f").WithLocation(6, 25) ); } [Fact, WorkItem(33347, "https://github.com/dotnet/roslyn/issues/33347")] public void NestedNullConditionalAccess3() { var source = @" class Node { public Node? Next = null; static Node M2(Node a, Node b) => a; Node M1() => null!; private static void Test(Node notNull, Node? possiblyNull) { _ = possiblyNull?.Next?.M1() ?? M2(possiblyNull = notNull, possiblyNull.Next = notNull); possiblyNull.Next.M1(); // incorrect warning } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31905, "https://github.com/dotnet/roslyn/issues/31905")] public void NestedNullConditionalAccess4() { var source = @" public class C { public C? Nested; void Test1(C? c) => c?.Nested?.M(c.Nested.ToString()); void Test2(C? c) => c.Nested?.M(c.Nested.ToString()); void Test3(C c) => c?.Nested?.M(c.Nested.ToString()); void M(string s) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,25): warning CS8602: Dereference of a possibly null reference. // void Test2(C? c) => c.Nested?.M(c.Nested.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(7, 25) ); } [Fact] public void ConditionalAccess() { var source = @"class C { void M1(C c, C[] a) { _ = (c?.S).Length; _ = (a?[0]).P; } void M2<T>(T t) where T : I { if (t == null) return; _ = (t?.S).Length; _ = (t?[0]).P; } int P { get => 0; } string S => throw null!; } interface I { string S { get; } C this[int i] { get; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,14): warning CS8602: Dereference of a possibly null reference. // _ = (c?.S).Length; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c?.S").WithLocation(5, 14), // (6,14): warning CS8602: Dereference of a possibly null reference. // _ = (a?[0]).P; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a?[0]").WithLocation(6, 14), // (11,14): warning CS8602: Dereference of a possibly null reference. // _ = (t?.S).Length; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t?.S").WithLocation(11, 14), // (12,14): warning CS8602: Dereference of a possibly null reference. // _ = (t?[0]).P; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t?[0]").WithLocation(12, 14) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33615")] public void TestSubstituteMemberOfTuple() { var source = @"using System; class C { static void Main() { Console.WriteLine(Test(42)); } public static Test(object? a) { if (a == null) return; var x = (f1: a, f2: a); Func<object> f = () => x.Test(a); f(); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public U Test<U>(U val) { return val; } } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(33905, "https://github.com/dotnet/roslyn/issues/33905")] public void TestDiagnosticsInUnreachableCode() { var source = @"#pragma warning disable 0162 // suppress unreachable statement warning #pragma warning disable 0219 // suppress unused local warning class G<T> { public static void Test(bool b, object? o, G<string?> g) { if (b) M1(o); // 1 M2(g); // 2 if (false) M1(o); if (false) M2(g); if (false && M1(o)) M2(g); if (false && M2(g)) M1(o); if (true || M1(o)) M2(g); // 3 if (true || M2(g)) M1(o); // 4 G<string> g1 = g; // 5 if (false) { G<string> g2 = g; } if (false) { object o1 = null; } } public static bool M1(object o) => true; public static bool M2(G<string> o) => true; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,19): warning CS8604: Possible null reference argument for parameter 'o' in 'bool G<T>.M1(object o)'. // if (b) M1(o); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "bool G<T>.M1(object o)").WithLocation(7, 19), // (8,12): warning CS8620: Argument of type 'G<string?>' cannot be used for parameter 'o' of type 'G<string>' in 'bool G<T>.M2(G<string> o)' due to differences in the nullability of reference types. // M2(g); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "g").WithArguments("G<string?>", "G<string>", "o", "bool G<T>.M2(G<string> o)").WithLocation(8, 12), // (14,16): warning CS8620: Argument of type 'G<string?>' cannot be used for parameter 'o' of type 'G<string>' in 'bool G<T>.M2(G<string> o)' due to differences in the nullability of reference types. // M2(g); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "g").WithArguments("G<string?>", "G<string>", "o", "bool G<T>.M2(G<string> o)").WithLocation(14, 16), // (16,16): warning CS8604: Possible null reference argument for parameter 'o' in 'bool G<T>.M1(object o)'. // M1(o); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "bool G<T>.M1(object o)").WithLocation(16, 16), // (17,24): warning CS8619: Nullability of reference types in value of type 'G<string?>' doesn't match target type 'G<string>'. // G<string> g1 = g; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "g").WithArguments("G<string?>", "G<string>").WithLocation(17, 24)); } [Fact] [WorkItem(33446, "https://github.com/dotnet/roslyn/issues/33446")] [WorkItem(34018, "https://github.com/dotnet/roslyn/issues/34018")] public void NullInferencesInFinallyClause() { var source = @"class Node { public Node? Next = null!; static void M1(Node node) { try { Mout(out node.Next); } finally { Mout(out node); // might set node to one in which node.Next == null } node.Next.ToString(); // 1 } static void M2() { Node? node = null; try { Mout(out node); } finally { if (node is null) {} else {} } node.ToString(); } static void M3() { Node? node = null; try { Mout(out node); } finally { node ??= node; } node.ToString(); } static void M4() { Node? node = null; try { Mout(out node); } finally { try { } finally { if (node is null) {} else {} } } node.ToString(); } static void M5() { Node? node = null; try { Mout(out node); } finally { try { if (node is null) {} else {} } finally { } } node.ToString(); } static void M6() { Node? node = null; try { Mout(out node); } finally { (node, _) = (null, node); } node.ToString(); // 2 } static void MN1() { Node? node = null; Mout(out node); if (node == null) {} else {} node.ToString(); // 3 } static void MN2() { Node? node = null; try { Mout(out node); } finally { if (node == null) {} else {} } node.ToString(); } static void Mout(out Node node) => node = null!; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // node.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "node.Next").WithLocation(15, 9), // (97,9): warning CS8602: Dereference of a possibly null reference. // node.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "node").WithLocation(97, 9), // (104,9): warning CS8602: Dereference of a possibly null reference. // node.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "node").WithLocation(104, 9)); } [Fact, WorkItem(32934, "https://github.com/dotnet/roslyn/issues/32934")] public void NoCycleInStructLayout() { var source = @" #nullable enable public struct Goo<T> { public static Goo<T> Bar; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(32446, "https://github.com/dotnet/roslyn/issues/32446")] public void RefValueOfNullableType() { var source = @" using System; public class C { public void M(TypedReference r) { _ = __refvalue(r, string?).Length; // 1 _ = __refvalue(r, string).Length; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = __refvalue(r, string?).Length; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "__refvalue(r, string?)").WithLocation(7, 13) ); } [Fact, WorkItem(25375, "https://github.com/dotnet/roslyn/issues/25375")] public void ParamsNullable_SingleNullParam() { var source = @" class C { static void F(object x, params object?[] y) { } static void G(object x, params object[]? y) { } static void Main() { // Both calls here are invoked in normal form, not expanded F(string.Empty, null); // 1 G(string.Empty, null); // These are called with expanded form F(string.Empty, null, string.Empty); G(string.Empty, null, string.Empty); // 2 // Explicitly called with array F(string.Empty, new object?[] { null }); G(string.Empty, new object[] { null }); // 3 } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,25): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(string.Empty, null); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 25), // (22,25): warning CS8625: Cannot convert null literal to non-nullable reference type. // G(string.Empty, null, string.Empty); // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(22, 25), // (27,40): warning CS8625: Cannot convert null literal to non-nullable reference type. // G(string.Empty, new object[] { null }); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(27, 40) ); } [Fact, WorkItem(32172, "https://github.com/dotnet/roslyn/issues/32172")] public void NullableIgnored_InDisabledCode() { var source = @" #if UNDEF #nullable disable #endif #define DEF #if DEF #nullable disable // 1 #endif #if UNDEF #nullable enable #endif public class C { public void F(object o) { F(null); // no warning. '#nullable enable' in a disabled code region } } "; CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (9,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // #nullable disable // 1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(9, 2) ); CreateCompilation(new[] { source }, options: WithNullableEnable()) .VerifyDiagnostics(); } [Fact, WorkItem(32172, "https://github.com/dotnet/roslyn/issues/32172")] public void DirectiveIgnored_InDisabledCode() { var source = @" #nullable disable warnings #if UNDEF #nullable restore warnings #endif public class C { public void F(object o) { F(null); // no warning. '#nullable restore warnings' in a disabled code region } } "; CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (2,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // #nullable disable warnings Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(2, 2)); CreateCompilation(new[] { source }, options: WithNullableEnable()) .VerifyDiagnostics(); } [WorkItem(30987, "https://github.com/dotnet/roslyn/issues/30987")] [Fact] public void TypeInference_LowerBounds_TopLevelNullability_03() { var source = @"using System; class C { static T F<T>(T x, T y) => x; static void G1(A x, B? y) { F(x, x)/*T:A!*/; F(x, y)/*T:A?*/; F(y, x)/*T:A?*/; F(y, y)/*T:B?*/; } static void G2(A x, B? y) { _ = new [] { x, x }[0]/*T:A!*/; _ = new [] { x, y }[0]/*T:A?*/; _ = new [] { y, x }[0]/*T:A?*/; _ = new [] { y, y }[0]/*T:B?*/; } static T M<T>(Func<T> func) => func(); static void G3(bool b, A x, B? y) { M(() => { if (b) return x; return x; })/*T:A!*/; M(() => { if (b) return x; return y; })/*T:A?*/; M(() => { if (b) return y; return x; })/*T:A?*/; M(() => { if (b) return y; return y; })/*T:B?*/; } static void G4(bool b, A x, B? y) { _ = (b ? x : x)/*T:A!*/; _ = (b ? x : y)/*T:A?*/; _ = (b ? y : x)/*T:A?*/; _ = (b ? y : y)/*T:B?*/; } } class A { } class B : A { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(30987, "https://github.com/dotnet/roslyn/issues/30987")] [Fact] public void TypeInference_LowerBounds_TopLevelNullability_04() { var source = @"class D { static T F<T>(T x, T y, T z) => x; static void G1(A x, B? y, C z) { F(x, y, z)/*T:A?*/; F(y, z, x)/*T:A?*/; F(z, x, y)/*T:A?*/; F(x, z, y)/*T:A?*/; F(z, y, x)/*T:A?*/; F(y, x, z)/*T:A?*/; } } class A { } class B : A { } class C : A { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(30987, "https://github.com/dotnet/roslyn/issues/30987")] [Fact] public void TypeInference_LowerBounds_TopLevelNullability_05() { var source = @"class D { #nullable disable static T F<T>(T x, T y, T z) => x; static void G1(A x, B? y, C z) #nullable enable { F(x, y, z)/*T:A?*/; F(y, z, x)/*T:A?*/; F(z, x, y)/*T:A?*/; F(x, z, y)/*T:A?*/; F(z, y, x)/*T:A?*/; F(y, x, z)/*T:A?*/; } } class A { } class B : A { } class C : A { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static void G1(A x, B? y, C z) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 26)); comp.VerifyTypes(); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_01() { var source = @"using System; class C { static T F<T>(Func<T> f) => throw null!; static void G(object? o) { F(() => o).ToString(); // warning: maybe null if (o == null) return; F(() => o).ToString(); // no warning } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F(() => o).ToString(); // warning: maybe null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => o)").WithLocation(8, 9)); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_02() { var source = @"using System; class C { static bool M(object? o) => throw null!; static T F<T>(Func<T> f, bool ignored) => throw null!; static void G(object? o) { F(() => o, M(1)).ToString(); // warning: maybe null if (o == null) return; F(() => o, M(o = null)).ToString(); // no warning } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F(() => o, M(1)).ToString(); // warning: maybe null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => o, M(1))").WithLocation(9, 9)); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_03() { var source = @"using System; class C { static bool M(object? o) => throw null!; static Func<T> F<T>(Func<T> f, bool ignored = false) => throw null!; static void G(object? o) { var fa1 = new[] { F(() => o), F(() => o, M(o = null)) }; fa1[0]().ToString(); // warning if (o == null) return; var fa2 = new[] { F(() => o), F(() => o, M(o = null)) }; fa2[0]().ToString(); if (o == null) return; var fa3 = new[] { F(() => o, M(o = null)), F(() => o) }; fa3[0]().ToString(); // warning } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // fa1[0]().ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "fa1[0]()").WithLocation(10, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // fa3[0]().ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "fa3[0]()").WithLocation(18, 9)); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_04() { var source = @"using System; class C { static T F<T>(Func<T> f) => throw null!; static void G(object? o) { F((Func<object>)(() => o)).ToString(); // 1 if (o == null) return; F((Func<object>)(() => o)).ToString(); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,32): warning CS8603: Possible null reference return. // F((Func<object>)(() => o)).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(8, 32)); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_05() { var source = @"using System; class C { static T F<T>(Func<T> f) => throw null!; static void G(Action a) => throw null!; static void M(object? o) { F(() => o).ToString(); // 1 if (o == null) return; F(() => o).ToString(); G(() => o = null); // does not affect state in caller F(() => o).ToString(); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F(() => o).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => o)").WithLocation(9, 9)); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_06() { var source = @"using System; class C { static T F<T>(object? o, params Func<T>[] a) => throw null!; static void M(string? x) { F(x = """", () => x = null, () => x.ToString()); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_07() { var source = @"using System; class C { static T F<T>([System.Diagnostics.CodeAnalysis.NotNull] object? o, params Func<T>[] a) => throw null!; static void M(string? x) { F(x = """", () => x = null, () => x.ToString()); } } "; var comp = CreateCompilation(new[] { source, NotNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(34841, "https://github.com/dotnet/roslyn/issues/34841")] public void PartialClassWithConstraints_01() { var source1 = @"#nullable enable using System; partial class C<T> where T : IEquatable<T>, new() { }"; var source2 = @"using System; partial class C<T> where T : IEquatable<T>, new() { }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source2, source1 }); comp.VerifyDiagnostics(); validate(); void validate() { var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.Equal("System.IEquatable<T>!", t.ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } } [Fact] [WorkItem(34841, "https://github.com/dotnet/roslyn/issues/34841")] public void PartialClassWithConstraints_02() { var source1 = @"#nullable enable using System; partial class C<T> where T : class?, IEquatable<T?>, new() { }"; var source2 = @"using System; partial class C<T> where T : class, IEquatable<T>, new() { }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source2, source1 }); comp.VerifyDiagnostics(); validate(); void validate() { var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.True(t.ReferenceTypeConstraintIsNullable); Assert.Equal("System.IEquatable<T?>!", t.ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } } [Fact] [WorkItem(34841, "https://github.com/dotnet/roslyn/issues/34841")] public void PartialClassWithConstraints_03() { var source1 = @"#nullable enable using System; class C<T> where T : IEquatable<T> { }"; var source2 = @"using System; class C<T> where T : IEquatable<T> { }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics( // (2,7): error CS0101: The namespace '<global namespace>' already contains a definition for 'C' // class C<T> where T : IEquatable<T> Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>").WithLocation(2, 7) ); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("System.IEquatable<T>!", t.ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } [Fact] public void PartialClassWithConstraints_04() { var source1 = @" using System; partial class C<T> where T : IEquatable< #nullable enable string? #nullable disable > { }"; var source2 = @"using System; partial class C<T> where T : IEquatable<string #nullable enable >? #nullable disable { }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source2, source1 }); comp.VerifyDiagnostics(); validate(); void validate() { var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("System.IEquatable<System.String?>?", t.ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } } [Fact] public void PartialClassWithConstraints_05() { var source1 = @"#nullable enable partial class C<T> where T : class, new() { }"; var source2 = @" partial class C<T> where T : class, new() { }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source2, source1 }); comp.VerifyDiagnostics(); validate(); void validate() { var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.False(t.ReferenceTypeConstraintIsNullable); } } [Fact] public void PartialClassWithConstraints_06() { var source1 = @"#nullable enable partial class C<T> where T : class, new() { } partial class C<T> where T : class, new() { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.False(t.ReferenceTypeConstraintIsNullable); } [Fact] public void PartialClassWithConstraints_07() { var source1 = @"#nullable enable partial class C<T> where T : class?, new() { } partial class C<T> where T : class?, new() { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.True(t.ReferenceTypeConstraintIsNullable); } [Fact] public void PartialClassWithConstraints_08() { var source1 = @"#nullable disable partial class C<T> where T : class, new() { } partial class C<T> where T : class, new() { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.Null(t.ReferenceTypeConstraintIsNullable); } [Fact] public void PartialClassWithConstraints_09() { var source1 = @"#nullable enable partial class C<T> where T : class?, new() { } partial class C<T> where T : class, new() { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics( // (2,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : class?, new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(2, 15) ); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.True(t.ReferenceTypeConstraintIsNullable); } [Fact] public void PartialClassWithConstraints_10() { var source1 = @"#nullable enable partial class C<T> where T : class, new() { } partial class C<T> where T : class?, new() { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics( // (2,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : class, new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(2, 15) ); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.False(t.ReferenceTypeConstraintIsNullable); } [Fact] public void PartialClassWithConstraints_11() { var source1 = @"#nullable enable using System; partial class C<T> where T : IEquatable<T>? { } partial class C<T> where T : IEquatable<T> { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics( // (3,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : IEquatable<T>? Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(3, 15) ); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("System.IEquatable<T>?", t.ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } [Fact] public void PartialClassWithConstraints_12() { var source1 = @"#nullable enable using System; partial class C<T> where T : IEquatable<T> { } partial class C<T> where T : IEquatable<T>? { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics( // (3,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : IEquatable<T> Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(3, 15) ); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("System.IEquatable<T>!", t.ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } [Fact] public void PartialClassWithConstraints_13() { var source1 = @"#nullable enable using System; partial class C<T> where T : class, IEquatable<T>?, IEquatable<string?> { } "; var source2 = @"using System; partial class C<T> where T : class, IEquatable<string>, IEquatable<T> { }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); validate(0, 1); comp = CreateCompilation(new[] { source2, source1 }); comp.VerifyDiagnostics(); validate(1, 0); void validate(int i, int j) { var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("System.IEquatable<T!>?", t.ConstraintTypesNoUseSiteDiagnostics[i].ToTestDisplayString(true)); Assert.Equal("System.IEquatable<System.String?>!", t.ConstraintTypesNoUseSiteDiagnostics[j].ToTestDisplayString(true)); } } [Fact] public void PartialClassWithConstraints_14() { var source0 = @" interface I1<T, S> { } "; var source1 = @" partial class C<T> where T : I1< #nullable enable string?, #nullable disable string> { } "; var source2 = @" partial class C<T> where T : I1<string, #nullable enable string? #nullable disable > { } "; var source3 = @" partial class C<T> where T : I1<string, string #nullable enable >? #nullable disable { } "; var comp1 = CreateCompilation(new[] { source0, source1 }); comp1.VerifyDiagnostics(); var c = comp1.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("I1<System.String?, System.String>", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); var comp2 = CreateCompilation(new[] { source0, source2 }); comp2.VerifyDiagnostics(); c = comp2.GlobalNamespace.GetTypeMember("C"); t = c.TypeParameters[0]; Assert.Equal("I1<System.String, System.String?>", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); var comp3 = CreateCompilation(new[] { source0, source3 }); comp3.VerifyDiagnostics(); c = comp3.GlobalNamespace.GetTypeMember("C"); t = c.TypeParameters[0]; Assert.Equal("I1<System.String, System.String>?", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); var comp = CreateCompilation(new[] { source0, source1, source2, source3 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source0, source1, source3, source2 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source0, source2, source1, source3 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source0, source2, source3, source1 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source0, source3, source1, source2 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source0, source3, source2, source1 }); comp.VerifyDiagnostics(); validate(); void validate() { var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("I1<System.String?, System.String?>?", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); } } [Fact] public void PartialClassWithConstraints_15() { var source = @" interface I1 { } interface I2 { } #nullable enable partial class C<T> where T : I1?, #nullable disable I2 { } #nullable enable partial class C<T> where T : I1, I2? { } "; var comp1 = CreateCompilation(new[] { source }); comp1.VerifyDiagnostics( // (12,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : I1?, Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(12, 15) ); var c = comp1.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("I1?", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); Assert.Equal("I2?", t.ConstraintTypesNoUseSiteDiagnostics[1].ToTestDisplayString(true)); } [Fact] public void PartialClassWithConstraints_16() { var source = @" interface I1 { } interface I2 { } #nullable enable partial class C<T> where T : I1, #nullable disable I2 { } #nullable enable partial class C<T> where T : I1?, I2 { } "; var comp1 = CreateCompilation(new[] { source }); comp1.VerifyDiagnostics( // (12,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : I1, Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(12, 15) ); var c = comp1.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("I1!", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); Assert.Equal("I2!", t.ConstraintTypesNoUseSiteDiagnostics[1].ToTestDisplayString(true)); } [Fact] public void PartialClassWithConstraints_17() { var source = @" interface I1 { } interface I2 { } #nullable disable partial class C<T> where T : I1, #nullable enable I2? { } partial class C<T> where T : I1?, I2 { } "; var comp1 = CreateCompilation(new[] { source }); comp1.VerifyDiagnostics( // (12,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : I1, Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(12, 15) ); var c = comp1.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("I1?", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); Assert.Equal("I2?", t.ConstraintTypesNoUseSiteDiagnostics[1].ToTestDisplayString(true)); } [Fact] public void PartialClassWithConstraints_18() { var source = @" interface I1 { } interface I2 { } #nullable disable partial class C<T> where T : I1, #nullable enable I2 { } partial class C<T> where T : I1, I2? { } "; var comp1 = CreateCompilation(new[] { source }); comp1.VerifyDiagnostics( // (12,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : I1, Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(12, 15) ); var c = comp1.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("I1!", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); Assert.Equal("I2!", t.ConstraintTypesNoUseSiteDiagnostics[1].ToTestDisplayString(true)); } [Fact] public void PartialInterfacesWithConstraints_01() { var source = @" #nullable enable interface I1 { } partial interface I1<in T> where T : I1 {} partial interface I1<in T> where T : I1? {} partial interface I2<in T> where T : I1? {} partial interface I2<in T> where T : I1 {} partial interface I3<out T> where T : I1 {} partial interface I3<out T> where T : I1? {} partial interface I4<out T> where T : I1? {} partial interface I4<out T> where T : I1 {} "; var comp1 = CreateCompilation(new[] { source }); comp1.VerifyDiagnostics( // (8,19): error CS0265: Partial declarations of 'I1<T>' have inconsistent constraints for type parameter 'T' // partial interface I1<in T> where T : I1 Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<T>", "T").WithLocation(8, 19), // (14,19): error CS0265: Partial declarations of 'I2<T>' have inconsistent constraints for type parameter 'T' // partial interface I2<in T> where T : I1? Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I2").WithArguments("I2<T>", "T").WithLocation(14, 19), // (20,19): error CS0265: Partial declarations of 'I3<T>' have inconsistent constraints for type parameter 'T' // partial interface I3<out T> where T : I1 Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I3").WithArguments("I3<T>", "T").WithLocation(20, 19), // (26,19): error CS0265: Partial declarations of 'I4<T>' have inconsistent constraints for type parameter 'T' // partial interface I4<out T> where T : I1? Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I4").WithArguments("I4<T>", "T").WithLocation(26, 19) ); } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_01() { var source0 = @" #nullable enable Base<string> base1 = new C(); Base<string?> base2 = new C(); // 1 class Base<T> { } "; var source1 = @" #nullable enable partial class C : Base<string> { } "; var source2 = @" #nullable disable partial class C : Base<string> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,23): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string?>'. // Base<string?> base2 = new C(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string?>").WithLocation(5, 23) ); var cClass = comp.GetMember<NamedTypeSymbol>("C"); var @base = cClass.BaseTypeNoUseSiteDiagnostics; // note: the symbol model doesn't include a nullable annotation for base types or implemented interfaces. Assert.Equal("Base<System.String!>", @base.ToTestDisplayString(includeNonNullable: true)); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_02() { var source0 = @" #nullable enable Base<string> base1 = new C(); // 1 Base<string?> base2 = new C(); class Base<T> { } "; var source1 = @" #nullable enable partial class C : Base<string?> { } "; var source2 = @" #nullable disable partial class C : Base<string> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (4,22): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string>'. // Base<string> base1 = new C(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string>").WithLocation(4, 22) ); var cClass = comp.GetMember<NamedTypeSymbol>("C"); var @base = cClass.BaseTypeNoUseSiteDiagnostics; // note: the symbol model doesn't include a nullable annotation for base types or implemented interfaces. Assert.Equal("Base<System.String?>", @base.ToTestDisplayString(includeNonNullable: true)); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_03() { var source0 = @" #nullable enable Base<string> base1 = new C(); Base<string?> base2 = new C(); // 1 class Base<T> { } "; var source1 = @" #nullable enable partial class C : Base<string> { } "; var source2 = @" #nullable enable partial class C : Base< #nullable disable string #nullable enable > { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,23): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string?>'. // Base<string?> base2 = new C(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string?>").WithLocation(5, 23) ); var cClass = comp.GetMember<NamedTypeSymbol>("C"); var @base = cClass.BaseTypeNoUseSiteDiagnostics; Assert.Equal("Base<System.String!>", @base.ToTestDisplayString(includeNonNullable: true)); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_04() { var source0 = @" #nullable enable Base<string> base1 = new C(); // 1 Base<string?> base2 = new C(); class Base<T> { } "; var source1 = @" #nullable enable partial class C : Base<string?> { } "; var source2 = @" #nullable enable partial class C : Base< #nullable disable string #nullable enable > { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (4,22): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string>'. // Base<string> base1 = new C(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string>").WithLocation(4, 22) ); var cClass = comp.GetMember<NamedTypeSymbol>("C"); var @base = cClass.BaseTypeNoUseSiteDiagnostics; Assert.Equal("Base<System.String?>", @base.ToTestDisplayString(includeNonNullable: true)); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_05() { var source0 = @" #nullable enable Base<string> base1 = new C(); Base<string?> base2 = new C(); // 1 class Base<T> { } "; var source1 = @" #nullable enable partial class C : Base<string> { } "; var source2 = @" #nullable enable partial class C : Base< #nullable disable string > { } // Note: the top-level nullability is oblivious here. "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,23): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string?>'. // Base<string?> base2 = new C(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string?>").WithLocation(5, 23) ); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_06() { var source0 = @" #nullable enable Base<string, object?> base1 = new C(); Base<string, object> base2 = new C(); // 1 Base<string?, object?> base3 = new C(); // 2 class Base<T, U> { } "; var source1 = @" #nullable enable partial class C : Base<string, object?> { } "; var source2 = @" #nullable disable partial class C : Base<string, object> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,30): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string, object>'. // Base<string, object> base2 = new C(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string, object>").WithLocation(5, 30), // (6,32): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string?, object?>'. // Base<string?, object?> base3 = new C(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string?, object?>").WithLocation(6, 32) ); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_07() { var source0 = @" #nullable enable Base<string, object?> base1 = new C(); // 1 Base<string, object> base2 = new C(); // 2 Base<string?, object?> base3 = new C(); // 3 class Base<T, U> { } "; var source1 = @" #nullable enable partial class C : Base<string, object?> { } // 4 "; var source2 = @" #nullable disable partial class C : Base<string, object> { } "; var source3 = @" #nullable enable partial class C : Base<string?, object> { } "; var comp = CreateCompilation(new[] { source0, source1, source2, source3 }); verify(); comp = CreateCompilation(new[] { source0, source3, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (3,15): error CS0263: Partial declarations of 'C' must not specify different base classes // partial class C : Base<string, object?> { } // 4 Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C").WithArguments("C").WithLocation(3, 15), // (4,31): error CS0029: Cannot implicitly convert type 'C' to 'Base<string, object?>' // Base<string, object?> base1 = new C(); // 1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C()").WithArguments("C", "Base<string, object?>").WithLocation(4, 31), // (5,30): error CS0029: Cannot implicitly convert type 'C' to 'Base<string, object>' // Base<string, object> base2 = new C(); // 2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C()").WithArguments("C", "Base<string, object>").WithLocation(5, 30), // (6,32): error CS0029: Cannot implicitly convert type 'C' to 'Base<string?, object?>' // Base<string?, object?> base3 = new C(); // 3 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C()").WithArguments("C", "Base<string?, object?>").WithLocation(6, 32) ); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_08() { var source0 = @" #nullable enable Base<S, object?> base1 = new C1(); Base<S, object> base2 = new C1(); // 1 Base<object?, S> base3 = new C2(); // 2 Base<object, S> base4 = new C2(); class Base<T, U> { } struct S { } "; var source1 = @" #nullable enable partial class C1 : Base<S, object?> { } partial class C2 : Base<object, S> { } "; var source2 = @" #nullable disable partial class C1 : Base<S, object> { } partial class C2 : Base<object, S> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,25): warning CS8619: Nullability of reference types in value of type 'C1' doesn't match target type 'Base<S, object>'. // Base<S, object> base2 = new C1(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C1()").WithArguments("C1", "Base<S, object>").WithLocation(5, 25), // (7,26): warning CS8619: Nullability of reference types in value of type 'C2' doesn't match target type 'Base<object?, S>'. // Base<object?, S> base3 = new C2(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C2()").WithArguments("C2", "Base<object?, S>").WithLocation(7, 26) ); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_09() { var source0 = @" #nullable enable Base<S?, object?> base1 = new C1(); Base<S?, object> base2 = new C1(); // 1 Base<object?, S?> base3 = new C2(); // 2 Base<object, S?> base4 = new C2(); class Base<T, U> { } struct S { } "; var source1 = @" #nullable enable partial class C1 : Base<S?, object?> { } partial class C2 : Base<object, S?> { } "; var source2 = @" #nullable disable partial class C1 : Base<S?, object> { } partial class C2 : Base<object, S?> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,26): warning CS8619: Nullability of reference types in value of type 'C1' doesn't match target type 'Base<S?, object>'. // Base<S?, object> base2 = new C1(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C1()").WithArguments("C1", "Base<S?, object>").WithLocation(5, 26), // (7,27): warning CS8619: Nullability of reference types in value of type 'C2' doesn't match target type 'Base<object?, S?>'. // Base<object?, S?> base3 = new C2(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C2()").WithArguments("C2", "Base<object?, S?>").WithLocation(7, 27) ); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_10() { var source0 = @" #nullable enable Base<S, object?> base1 = new C1(); Base<S, object> base2 = new C1(); // 1 Base<object?, S> base3 = new C2(); // 2 Base<object, S> base4 = new C2(); class Base<T, U> { } struct S { } "; var source1 = @" #nullable enable partial class C1 : Base<S, object?> { } partial class C2 : Base<object, S> { } "; var source2 = @" #nullable enable partial class C1 : Base< S, #nullable disable object> { } #nullable enable partial class C2 : Base< object, #nullable disable S> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,25): warning CS8619: Nullability of reference types in value of type 'C1' doesn't match target type 'Base<S, object>'. // Base<S, object> base2 = new C1(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C1()").WithArguments("C1", "Base<S, object>").WithLocation(5, 25), // (7,26): warning CS8619: Nullability of reference types in value of type 'C2' doesn't match target type 'Base<object?, S>'. // Base<object?, S> base3 = new C2(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C2()").WithArguments("C2", "Base<object?, S>").WithLocation(7, 26) ); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_11() { var source0 = @" #nullable enable Base<S?, object?> base1 = new C1(); Base<S?, object> base2 = new C1(); // 1 Base<object?, S?> base3 = new C2(); // 2 Base<object, S?> base4 = new C2(); class Base<T, U> { } struct S { } "; var source1 = @" #nullable enable partial class C1 : Base<S?, object?> { } partial class C2 : Base<object, S?> { } "; var source2 = @" #nullable enable partial class C1 : Base< S?, #nullable disable object> { } #nullable enable partial class C2 : Base< object, #nullable disable S?> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); comp.VerifyDiagnostics( // (5,26): warning CS8619: Nullability of reference types in value of type 'C1' doesn't match target type 'Base<S?, object>'. // Base<S?, object> base2 = new C1(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C1()").WithArguments("C1", "Base<S?, object>").WithLocation(5, 26), // (7,27): warning CS8619: Nullability of reference types in value of type 'C2' doesn't match target type 'Base<object?, S?>'. // Base<object?, S?> base3 = new C2(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C2()").WithArguments("C2", "Base<object?, S?>").WithLocation(7, 27) ); } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_12() { var source0 = @" #nullable enable Base<S, object?> base1 = new C1<S>(); Base<S, object> base2 = new C1<S>(); // 1 Base<object?, S> base3 = new C2<S>(); // 2 Base<object, S> base4 = new C2<S>(); class Base<T, U> { } struct S { } "; var source1 = @" #nullable enable partial class C1<TStruct> : Base<TStruct, object?> where TStruct : struct { } partial class C2<TStruct> : Base<object, TStruct> where TStruct : struct { } "; var source2 = @" #nullable enable partial class C1<TStruct> : Base< TStruct, #nullable disable object> where TStruct : struct { } #nullable enable partial class C2<TStruct> : Base< object, #nullable disable TStruct> where TStruct : struct { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,25): warning CS8619: Nullability of reference types in value of type 'C1<S>' doesn't match target type 'Base<S, object>'. // Base<S, object> base2 = new C1<S>(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C1<S>()").WithArguments("C1<S>", "Base<S, object>").WithLocation(5, 25), // (7,26): warning CS8619: Nullability of reference types in value of type 'C2<S>' doesn't match target type 'Base<object?, S>'. // Base<object?, S> base3 = new C2<S>(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C2<S>()").WithArguments("C2<S>", "Base<object?, S>").WithLocation(7, 26) ); } } [Theory, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] [InlineData("")] [InlineData("where T : class")] public void PartialBaseTypeDifference_13(string constraints) { var source0 = @" #nullable enable Base<C, object?> base1 = new C1<C>(); // 1 Base<C, object> base2 = new C1<C>(); // 2 Base<object?, C> base3 = new C2<C>(); // 3 Base<object, C> base4 = new C2<C>(); // 4 class Base<T, U> { } class C { } "; var source1 = @" #nullable enable partial class C1<T> : Base<T, object?> " + constraints + @" { } // 5 partial class C2<T> : Base<object, T> " + constraints + @" { } // 6 "; var source2 = @" #nullable enable partial class C1<T> : Base< T, #nullable disable object> " + constraints + @" { } #nullable enable partial class C2<T> : Base< object, #nullable disable T> " + constraints + @" { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); comp.VerifyDiagnostics( // (3,15): error CS0263: Partial declarations of 'C1<T>' must not specify different base classes // partial class C1<T> : Base<T, object?> { } // 5 Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C1").WithArguments("C1<T>").WithLocation(3, 15), // (4,15): error CS0263: Partial declarations of 'C2<T>' must not specify different base classes // partial class C2<T> : Base<object, T> { } // 6 Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C2").WithArguments("C2<T>").WithLocation(4, 15), // (4,26): error CS0029: Cannot implicitly convert type 'C1<C>' to 'Base<C, object?>' // Base<C, object?> base1 = new C1<C>(); // 1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C1<C>()").WithArguments("C1<C>", "Base<C, object?>").WithLocation(4, 26), // (5,25): error CS0029: Cannot implicitly convert type 'C1<C>' to 'Base<C, object>' // Base<C, object> base2 = new C1<C>(); // 2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C1<C>()").WithArguments("C1<C>", "Base<C, object>").WithLocation(5, 25), // (7,26): error CS0029: Cannot implicitly convert type 'C2<C>' to 'Base<object?, C>' // Base<object?, C> base3 = new C2<C>(); // 3 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C2<C>()").WithArguments("C2<C>", "Base<object?, C>").WithLocation(7, 26), // (8,25): error CS0029: Cannot implicitly convert type 'C2<C>' to 'Base<object, C>' // Base<object, C> base4 = new C2<C>(); // 4 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C2<C>()").WithArguments("C2<C>", "Base<object, C>").WithLocation(8, 25) ); } [Fact] public void PartialMethodsWithConstraints_01() { var source1 = @"#nullable enable using System; partial class C { static partial void F<T>() where T : IEquatable<T>; }"; var source2 = @"using System; partial class C { static partial void F<T>() where T : IEquatable<T> { } }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); var f = comp.GlobalNamespace.GetMember<MethodSymbol>("C.F"); Assert.Equal("System.IEquatable<T>!", f.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); Assert.Equal("System.IEquatable<T>", f.PartialImplementationPart.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } [Fact] public void PartialMethodsWithConstraints_02() { var source1 = @"#nullable enable using System; partial class C { static partial void F<T>() where T : class?, IEquatable<T?>; }"; var source2 = @"using System; partial class C { static partial void F<T>() where T : class, IEquatable<T> { } }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); var f = comp.GlobalNamespace.GetMember<MethodSymbol>("C.F"); Assert.True(f.TypeParameters[0].ReferenceTypeConstraintIsNullable); Assert.Equal("System.IEquatable<T?>!", f.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); Assert.Null(f.PartialImplementationPart.TypeParameters[0].ReferenceTypeConstraintIsNullable); Assert.Equal("System.IEquatable<T>", f.PartialImplementationPart.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } [Fact] [WorkItem(35227, "https://github.com/dotnet/roslyn/issues/35227")] public void PartialMethodsWithConstraints_03() { var source1 = @" partial class C { #nullable enable static partial void F<T>(I<T> x) where T : class; #nullable disable static partial void F<T>(I<T> x) where T : class #nullable enable { Test2(x); } void Test1<U>() where U : class? { F<U>(null); } static void Test2<S>(I<S?> x) where S : class { } } interface I<in S> { } "; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics( // (16,9): warning CS8634: The type 'U' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>(I<T>)'. Nullability of type argument 'U' doesn't match 'class' constraint. // F<U>(null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F<U>").WithArguments("C.F<T>(I<T>)", "T", "U").WithLocation(16, 9), // (16,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // F<U>(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 14) ); } [Fact] [WorkItem(35227, "https://github.com/dotnet/roslyn/issues/35227")] public void PartialMethodsWithConstraints_04() { var source1 = @" partial class C { #nullable disable static partial void F<T>(I<T> x) where T : class; #nullable enable static partial void F<T>(I<T> x) where T : class { Test2(x); } void Test1<U>() where U : class? { F<U>(null); } static void Test2<S>(I<S?> x) where S : class { } } interface I<in S> { } "; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics( // (10,15): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 'x' of type 'I<T?>' in 'void C.Test2<T>(I<T?> x)' due to differences in the nullability of reference types. // Test2(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "x", "void C.Test2<T>(I<T?> x)").WithLocation(10, 15) ); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceMethod_DifferingNullabilityAnnotations1() { var text = @" #nullable enable public interface Interface<T> where T : class { void Method(string i); void Method(T? i); } public class Class : Interface<string> { void Interface<string>.Method(string i) { } //this explicitly implements both methods in Interface<string> public void Method(string i) { } //this is here to avoid CS0535 - not implementing interface method } "; CreateCompilation(text).VerifyDiagnostics( // (11,28): warning CS0473: Explicit interface implementation 'Class.Interface<string>.Method(string)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void Interface<string>.Method(string i) { } //this explicitly implements both methods in Interface<string> Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Class.Interface<string>.Method(string)").WithLocation(11, 28), // (12,17): warning CS8767: Nullability of reference types in type of parameter 'i' of 'void Class.Method(string i)' doesn't match implicitly implemented member 'void Interface<string>.Method(string? i)' (possibly because of nullability attributes). // public void Method(string i) { } //this is here to avoid CS0535 - not implementing interface method Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "Method").WithArguments("i", "void Class.Method(string i)", "void Interface<string>.Method(string? i)").WithLocation(12, 17)); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceMethod_DifferingNullabilityAnnotations2() { var text = @" #nullable enable public interface Interface<T> where T : class { void Method(string i); void Method(T? i); } public class Class : Interface<string> { void Interface<string>.Method(string? i) { } //this explicitly implements both methods in Interface<string> public void Method(string i) { } //this is here to avoid CS0535 - not implementing interface method } "; CreateCompilation(text).VerifyDiagnostics( // (11,28): warning CS0473: Explicit interface implementation 'Class.Interface<string>.Method(string?)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void Interface<string>.Method(string? i) { } //this explicitly implements both methods in Interface<string> Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Class.Interface<string>.Method(string?)").WithLocation(11, 28), // (12,17): warning CS8767: Nullability of reference types in type of parameter 'i' of 'void Class.Method(string i)' doesn't match implicitly implemented member 'void Interface<string>.Method(string? i)' (possibly because of nullability attributes). // public void Method(string i) { } //this is here to avoid CS0535 - not implementing interface method Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "Method").WithArguments("i", "void Class.Method(string i)", "void Interface<string>.Method(string? i)").WithLocation(12, 17)); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceMethod_DifferingNullabilityAnnotations3() { var text = @" #nullable enable public interface Interface<T> where T : class { void Method(string? i); void Method(T i); } public class Class : Interface<string> { void Interface<string>.Method(string i) { } //this explicitly implements both methods in Interface<string> public void Method(string? i) { } //this is here to avoid CS0535 - not implementing interface method } "; CreateCompilation(text).VerifyDiagnostics( // (11,28): warning CS0473: Explicit interface implementation 'Class.Interface<string>.Method(string)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void Interface<string>.Method(string i) { } //this explicitly implements both methods in Interface<string> Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Class.Interface<string>.Method(string)").WithLocation(11, 28), // (11,28): warning CS8769: Nullability of reference types in type of parameter 'i' doesn't match implemented member 'void Interface<string>.Method(string? i)' (possibly because of nullability attributes). // void Interface<string>.Method(string i) { } //this explicitly implements both methods in Interface<string> Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "Method").WithArguments("i", "void Interface<string>.Method(string? i)").WithLocation(11, 28) ); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : class; } class C1 : I { public void Goo<T>(T? value) where T : class { } } class C2 : I { void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (13,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(13, 12), // (15,12): error CS0539: 'C2.Goo<T>(T?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I.Goo<T>(T? value) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Goo").WithArguments("C2.Goo<T>(T?)").WithLocation(15, 12), // (15,22): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I.Goo<T>(T? value) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "value").WithArguments("System.Nullable<T>", "T", "T").WithLocation(15, 22)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodTakingNonNullableClassParameter_WithMethodTakingNullableClassParameter() { var source = @" #nullable enable interface I { void Goo<T>(T value) where T : class; } class C1 : I { public void Goo<T>(T? value) where T : class { } } class C2 : I { void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (13,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T)").WithLocation(13, 12), // (15,12): error CS0539: 'C2.Goo<T>(T?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I.Goo<T>(T? value) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Goo").WithArguments("C2.Goo<T>(T?)").WithLocation(15, 12), // (15,22): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I.Goo<T>(T? value) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "value").WithArguments("System.Nullable<T>", "T", "T").WithLocation(15, 22)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodTakingNullableClassParameter_WithMethodTakingNonNullableClassParameter() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : class; } class C1 : I { public void Goo<T>(T value) where T : class { } } class C2 : I { void I.Goo<T>(T value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,17): warning CS8767: Nullability of reference types in type of parameter 'value' of 'void C1.Goo<T>(T value)' doesn't match implicitly implemented member 'void I.Goo<T>(T? value)' (possibly because of nullability attributes). // public void Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "Goo").WithArguments("value", "void C1.Goo<T>(T value)", "void I.Goo<T>(T? value)").WithLocation(10, 17), // (15,12): warning CS8769: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void I.Goo<T>(T? value)' (possibly because of nullability attributes). // void I.Goo<T>(T value) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "Goo").WithArguments("value", "void I.Goo<T>(T? value)").WithLocation(15, 12)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ExplicitImplementationOverloadAcceptingNullableT() { var source = @" interface I { void Goo<T>(T value); void Goo<T>(T? value) where T : struct; } class C1 : I { public void Goo<T>(T value) { } public void Goo<T>(T? value) where T : struct { } } class C2 : I { void I.Goo<T>(T value) { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ExplicitImplementationOverloadAcceptingNullableT_OppositeDeclarationOrder() { var source = @" interface I { void Goo<T>(T? value) where T : struct; void Goo<T>(T value); } class C1 : I { public void Goo<T>(T value) { } public void Goo<T>(T? value) where T : struct { } } class C2 : I { void I.Goo<T>(T value) { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ExplicitImplementationOverloadAcceptingNullableT_WithClassConstraint() { var source = @" #nullable enable interface I { void Goo<T>(T value) where T : class; void Goo<T>(T? value) where T : struct; } class C1 : I { public void Goo<T>(T value) where T : class { } public void Goo<T>(T? value) where T : struct { } } class C2 : I { void I.Goo<T>(T value) { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ExplicitImplementationOverloadAcceptingNullableT_ReturnTypesDoNotMatchNullabilityModifiers() { var source = @" #nullable enable interface I<U> where U : class { U Goo<T>(T value); U Goo<T>(T? value) where T : struct; } class C1<U> : I<U> where U : class { public U? Goo<T>(T value) => default; public U? Goo<T>(T? value) where T : struct => default; } class C2<U> : I<U> where U : class { U? I<U>.Goo<T>(T value) => default; U? I<U>.Goo<T>(T? value) => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (11,15): warning CS8766: Nullability of reference types in return type of 'U? C1<U>.Goo<T>(T value)' doesn't match implicitly implemented member 'U I<U>.Goo<T>(T value)' (possibly because of nullability attributes). // public U? Goo<T>(T value) => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "Goo").WithArguments("U? C1<U>.Goo<T>(T value)", "U I<U>.Goo<T>(T value)").WithLocation(11, 15), // (12,15): warning CS8766: Nullability of reference types in return type of 'U? C1<U>.Goo<T>(T? value)' doesn't match implicitly implemented member 'U I<U>.Goo<T>(T? value)' (possibly because of nullability attributes). // public U? Goo<T>(T? value) where T : struct => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "Goo").WithArguments("U? C1<U>.Goo<T>(T? value)", "U I<U>.Goo<T>(T? value)").WithLocation(12, 15), // (17,13): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'U I<U>.Goo<T>(T value)' (possibly because of nullability attributes). // U? I<U>.Goo<T>(T value) => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "Goo").WithArguments("U I<U>.Goo<T>(T value)").WithLocation(17, 13), // (18,13): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'U I<U>.Goo<T>(T? value)' (possibly because of nullability attributes). // U? I<U>.Goo<T>(T? value) => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "Goo").WithArguments("U I<U>.Goo<T>(T? value)").WithLocation(18, 13)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ExplicitImplementationOverloadAcceptingNullableT_ReturnTypesDoNotMatchNullabilityModifiers_OppositeDeclarationOrder() { var source = @" #nullable enable interface I<U> where U : class { U Goo<T>(T? value) where T : struct; U Goo<T>(T value); } class C1<U> : I<U> where U : class { public U? Goo<T>(T value) => default; public U? Goo<T>(T? value) where T : struct => default; } class C2<U> : I<U> where U : class { U? I<U>.Goo<T>(T value) => default; U? I<U>.Goo<T>(T? value) => default; } "; //As a result of https://github.com/dotnet/roslyn/issues/34583 these don't test anything useful at the moment var comp = CreateCompilation(source).VerifyDiagnostics( // (11,15): warning CS8766: Nullability of reference types in return type of 'U? C1<U>.Goo<T>(T value)' doesn't match implicitly implemented member 'U I<U>.Goo<T>(T value)' (possibly because of nullability attributes). // public U? Goo<T>(T value) => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "Goo").WithArguments("U? C1<U>.Goo<T>(T value)", "U I<U>.Goo<T>(T value)").WithLocation(11, 15), // (12,15): warning CS8766: Nullability of reference types in return type of 'U? C1<U>.Goo<T>(T? value)' doesn't match implicitly implemented member 'U I<U>.Goo<T>(T? value)' (possibly because of nullability attributes). // public U? Goo<T>(T? value) where T : struct => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "Goo").WithArguments("U? C1<U>.Goo<T>(T? value)", "U I<U>.Goo<T>(T? value)").WithLocation(12, 15), // (17,13): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'U I<U>.Goo<T>(T value)' (possibly because of nullability attributes). // U? I<U>.Goo<T>(T value) => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "Goo").WithArguments("U I<U>.Goo<T>(T value)").WithLocation(17, 13), // (18,13): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'U I<U>.Goo<T>(T? value)' (possibly because of nullability attributes). // U? I<U>.Goo<T>(T? value) => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "Goo").WithArguments("U I<U>.Goo<T>(T? value)").WithLocation(18, 13)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : class; void Goo<T>(T? value) where T : struct; } class C2 : I { void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(9, 12)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_WithImplicitOverrideOfStructMember() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : class; void Goo<T>(T? value) where T : struct; } class C2 : I { public void Goo<T>(T? value) where T : struct { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(9, 12)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_WithImplicitOverrideOfClassMember() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : class; void Goo<T>(T? value) where T : struct; } class C2 : I { public void Goo<T>(T? value) where T : class { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_WithImplicitOverrideOfStructMember_OppositeDeclarationOrder() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : struct; void Goo<T>(T? value) where T : class; } class C2 : I { public void Goo<T>(T? value) where T : struct { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(9, 12)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_WithImplicitOverrideOfClassMember_OppositeDeclarationOrder() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : struct; void Goo<T>(T? value) where T : class; } class C2 : I { public void Goo<T>(T? value) where T : class { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_OppositeDeclarationOrder() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : struct; void Goo<T>(T? value) where T : class; } class C2 : I { void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(9, 12)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_DifferingReturnType() { var source = @" #nullable enable interface I { string Goo<T>(T? value) where T : class; int Goo<T>(T? value) where T : struct; } class C2 : I { int I.Goo<T>(T? value) => 42; string I.Goo<T>(T? value) => ""42""; } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(9, 12), // (12,14): error CS0539: 'C2.Goo<T>(T?)' in explicit interface declaration is not found among members of the interface that can be implemented // string I.Goo<T>(T? value) => "42"; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Goo").WithArguments("C2.Goo<T>(T?)").WithLocation(12, 14), // (12,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // string I.Goo<T>(T? value) => "42"; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "value").WithArguments("System.Nullable<T>", "T", "T").WithLocation(12, 24)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_ReturnTypeDifferingInNullabilityAnotation() { var source = @" #nullable enable interface I { object Goo<T>(T? value) where T : class; object? Goo<T>(T? value) where T : struct; } class C2 : I { object I.Goo<T>(T? value) => 42; object? I.Goo<T>(T? value) => 42; } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,7): error CS8646: 'I.Goo<T>(T?)' is explicitly implemented more than once. // class C2 : I Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I.Goo<T>(T?)").WithLocation(9, 7), // (9,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(9, 12), // (12,15): error CS0111: Type 'C2' already defines a member called 'I.Goo' with the same parameter types // object? I.Goo<T>(T? value) => 42; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Goo").WithArguments("I.Goo", "C2").WithLocation(12, 15)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodTakingNullableClassTypeParameterDefinedByClass_WithMethodTakingNullableClassParameter() { var source = @" #nullable enable abstract class Base<T> where T : class { public abstract void Goo(T? value); } class Derived<T> : Base<T> where T : class { public override void Goo(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.False(dGoo.Parameters[0].Type.IsNullableType()); Assert.True(dGoo.Parameters[0].TypeWithAnnotations.NullableAnnotation == NullableAnnotation.Annotated); } [Fact] public void ImplementMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter1() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : class; } class C1 : I { public void Goo<T>(T? value) where T : class { } } class C2 : I { void I.Goo<T>(T? value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.Parameters[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, c2Goo.Parameters[0].TypeWithAnnotations.NullableAnnotation); } [Fact] public void ImplementMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter2() { var source = @" #nullable enable interface I { void Goo<T>(T?[] value) where T : class; } class C1 : I { public void Goo<T>(T?[] value) where T : class { } } class C2 : I { void I.Goo<T>(T?[] value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(((ArrayTypeSymbol)c2Goo.Parameters[0].Type).ElementType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, ((ArrayTypeSymbol)c2Goo.Parameters[0].Type).ElementTypeWithAnnotations.NullableAnnotation); } [Fact] public void ImplementMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter3() { var source = @" #nullable enable interface I { void Goo<T>((T a, T? b)? value) where T : class; } class C1 : I { public void Goo<T>((T a, T? b)? value) where T : class { } } class C2 : I { void I.Goo<T>((T a, T? b)? value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.Parameters[0].Type.IsNullableType()); var tuple = c2Goo.Parameters[0].Type.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.True(tuple.TupleElements[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.NotAnnotated, tuple.TupleElements[0].TypeWithAnnotations.NullableAnnotation); Assert.True(tuple.TupleElements[1].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, tuple.TupleElements[1].TypeWithAnnotations.NullableAnnotation); } [Fact] public void ImplementMethodReturningNullableClassParameter_WithMethodReturningNullableClass1() { var source = @" #nullable enable interface I { T? Goo<T>() where T : class; } class C1 : I { public T? Goo<T>() where T : class => default; } class C2 : I { T? I.Goo<T>() where T : class => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.ReturnType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, c2Goo.ReturnTypeWithAnnotations.NullableAnnotation); } [Fact] public void ImplementMethodReturningNullableClassParameter_WithMethodReturningNullableClass2() { var source = @" #nullable enable interface I { T?[] Goo<T>() where T : class; } class C1 : I { public T?[] Goo<T>() where T : class => default!; } class C2 : I { T?[] I.Goo<T>() where T : class => default!; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(((ArrayTypeSymbol)c2Goo.ReturnType).ElementType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, ((ArrayTypeSymbol)c2Goo.ReturnType).ElementTypeWithAnnotations.NullableAnnotation); } [Fact] public void ImplementMethodReturningNullableClassParameter_WithMethodReturningNullableClass3() { var source = @" #nullable enable interface I { (T a, T? b)? Goo<T>() where T : class; } class C1 : I { public (T a, T? b)? Goo<T>() where T : class => default; } class C2 : I { (T a, T? b)? I.Goo<T>() where T : class => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.ReturnType.IsNullableType()); var tuple = c2Goo.ReturnType.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.True(tuple.TupleElements[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.NotAnnotated, tuple.TupleElements[0].TypeWithAnnotations.NullableAnnotation); Assert.True(tuple.TupleElements[1].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, tuple.TupleElements[1].TypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter1() { var source = @" #nullable enable abstract class Base { public abstract void Goo<T>(T? value) where T : class; } class Derived : Base { public override void Goo<T>(T? value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.Parameters[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, dGoo.Parameters[0].TypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter2() { var source = @" #nullable enable abstract class Base { public abstract void Goo<T>(T?[] value) where T : class; } class Derived : Base { public override void Goo<T>(T?[] value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(((ArrayTypeSymbol)dGoo.Parameters[0].Type).ElementType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, ((ArrayTypeSymbol)dGoo.Parameters[0].Type).ElementTypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter3() { var source = @" #nullable enable abstract class Base { public abstract void Goo<T>((T a, T? b)? value) where T : class; } class Derived : Base { public override void Goo<T>((T a, T? b)? value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.Parameters[0].Type.IsNullableType()); var tuple = dGoo.Parameters[0].Type.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.True(tuple.TupleElements[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.NotAnnotated, tuple.TupleElements[0].TypeWithAnnotations.NullableAnnotation); Assert.True(tuple.TupleElements[1].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, tuple.TupleElements[1].TypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethodReturningNullableClassParameter_WithMethodReturningNullableClass1() { var source = @" #nullable enable abstract class Base { public abstract T? Goo<T>() where T : class; } class Derived : Base { public override T? Goo<T>() where T : class => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.ReturnType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, dGoo.ReturnTypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethodReturningNullableClassParameter_WithMethodReturningNullableClass2() { var source = @" #nullable enable abstract class Base { public abstract T?[] Goo<T>() where T : class; } class Derived : Base { public override T?[] Goo<T>() where T : class => default!; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(((ArrayTypeSymbol)dGoo.ReturnType).ElementType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, ((ArrayTypeSymbol)dGoo.ReturnType).ElementTypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethodReturningNullableClassParameter_WithMethodReturningNullableClass3() { var source = @" #nullable enable abstract class Base { public abstract (T a, T? b)? Goo<T>() where T : class; } class Derived : Base { public override (T a, T? b)? Goo<T>() where T : class => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.ReturnType.IsNullableType()); var tuple = dGoo.ReturnType.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.True(tuple.TupleElements[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.NotAnnotated, tuple.TupleElements[0].TypeWithAnnotations.NullableAnnotation); Assert.True(tuple.TupleElements[1].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, tuple.TupleElements[1].TypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethod_WithMultipleClassAndStructConstraints() { var source = @" using System.IO; #nullable enable abstract class Base { public abstract T? Goo<T, U, V>(U? u, (V?, U?) vu) where T : Stream where U : struct where V : class; } class Derived : Base { public override T? Goo<T, U, V>(U? u, (V?, U?) vu) where T : class where U : struct where V : class => default!; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.ReturnType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, dGoo.ReturnTypeWithAnnotations.NullableAnnotation); Assert.True(dGoo.Parameters[0].Type.IsNullableType()); var tuple = dGoo.Parameters[1].Type; Assert.True(tuple.TupleElements[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, tuple.TupleElements[0].TypeWithAnnotations.NullableAnnotation); Assert.True(tuple.TupleElements[1].Type.IsNullableType()); } [Fact] [WorkItem(29894, "https://github.com/dotnet/roslyn/issues/29894")] public void TypeOf_03() { var source = @" #nullable enable class K<T> { } class C1 { object o1 = typeof(int); object o2 = typeof(string); object o3 = typeof(int?); object o4 = typeof(string?); // 1 object o5 = typeof(K<int?>); object o6 = typeof(K<string?>); object o7 = typeof(K<int?>?); // 2 object o8 = typeof(K<string?>?);// 3 } #nullable disable class C2 { object o1 = typeof(int); object o2 = typeof(string); object o3 = typeof(int?); object o4 = typeof(string?); // 4, 5 object o5 = typeof(K<int?>); object o6 = typeof(K<string?>); // 6 object o7 = typeof(K<int?>?); // 7, 8 object o8 = typeof(K<string?>?);// 9, 10, 11 } #nullable enable class C3<T, TClass, TStruct> where TClass : class where TStruct : struct { object o1 = typeof(T?); // 12 object o2 = typeof(TClass?); // 13 object o3 = typeof(TStruct?); } "; CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o4 = typeof(string?); // 1 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(string?)").WithLocation(9, 17), // (12,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o7 = typeof(K<int?>?); // 2 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(K<int?>?)").WithLocation(12, 17), // (13,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o8 = typeof(K<string?>?);// 3 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(K<string?>?)").WithLocation(13, 17), // (21,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o4 = typeof(string?); // 4, 5 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(string?)").WithLocation(21, 17), // (21,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // object o4 = typeof(string?); // 4, 5 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 30), // (23,32): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // object o6 = typeof(K<string?>); // 6 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(23, 32), // (24,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o7 = typeof(K<int?>?); // 7, 8 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(K<int?>?)").WithLocation(24, 17), // (24,31): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // object o7 = typeof(K<int?>?); // 7, 8 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(24, 31), // (25,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o8 = typeof(K<string?>?);// 9, 10, 11 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(K<string?>?)").WithLocation(25, 17), // (25,32): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // object o8 = typeof(K<string?>?);// 9, 10, 11 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(25, 32), // (25,34): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // object o8 = typeof(K<string?>?);// 9, 10, 11 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(25, 34), // (32,24): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // object o1 = typeof(T?); // 12 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(32, 24), // (33,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o2 = typeof(TClass?); // 13 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(TClass?)").WithLocation(33, 17)); } [Fact, WorkItem(34299, "https://github.com/dotnet/roslyn/issues/34299")] public void CheckLambdaInArrayInitializer_01() { var source = @"using System; class C { static void G(object? o, string s) { Func<object> f = () => o; // 1 _ = f /*T:System.Func<object!>!*/; var fa3 = new[] { f, () => o, // 2 () => { s = null; // 3 return null; // 4 }, }; _ = fa3 /*T:System.Func<object!>![]!*/; fa3[0]().ToString(); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (7,32): warning CS8603: Possible null reference return. // Func<object> f = () => o; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(7, 32), // (11,19): warning CS8603: Possible null reference return. // () => o, // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(11, 19), // (13,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 25), // (14,28): warning CS8603: Possible null reference return. // return null; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(14, 28)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/35302"), WorkItem(35302, "https://github.com/dotnet/roslyn/issues/35302")] public void CheckLambdaInArrayInitializer_02() { var source = @"using System; class C { static void G(object? o, string s) { if (o == null) return; var f = M(o); _ = f /*T:System.Func<object!>!*/; var fa3 = new[] { f, () => null, // 1 () => { s = null; // 2 return null; // 3 }, }; _ = fa3 /*T:System.Func<object!>![]!*/; fa3[0]().ToString(); } static Func<T> M<T>(T t) => () => t; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (12,19): warning CS8603: Possible null reference return. // () => null, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(12, 19), // (14,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 25), // (15,28): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(15, 28)); } [Fact, WorkItem(34299, "https://github.com/dotnet/roslyn/issues/34299")] public void CheckLambdaInSwitchExpression_01() { var source = @"using System; class C { static void G(int i, object? o, string s) { Func<object> f = () => i; _ = f /*T:System.Func<object!>!*/; var f2 = i switch { 1 => f, 2 => () => o, // 1 _ => () => { s = null; // 2 return null; // 3 }, }; _ = f2 /*T:System.Func<object!>!*/; f2().ToString(); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (11,24): warning CS8603: Possible null reference return. // 2 => () => o, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(11, 24), // (13,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 25), // (14,28): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(14, 28)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/35302"), WorkItem(34299, "https://github.com/dotnet/roslyn/issues/34299")] public void CheckLambdaInSwitchExpression_02() { var source = @"using System; class C { static void G(int i, object? o, string s) { if (o == null) return; var f = M(o); _ = f /*T:System.Func<object!>!*/; var f2 = i switch { 1 => f, 2 => () => o, // 1 _ => () => { s = null; // 2 return null; // 3 }, }; _ = f2 /*T:System.Func<object!>!*/; f2().ToString(); } static Func<T> M<T>(T t) => () => t; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); //comp.VerifyTypes(); comp.VerifyDiagnostics( // (12,24): warning CS8603: Possible null reference return. // 2 => () => o, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(12, 24), // (12,24): warning CS8603: Possible null reference return. // 2 => () => o, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(12, 24), // (14,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 25), // (14,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 25), // (15,28): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(15, 28), // (15,28): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(15, 28)); } [Fact, WorkItem(34299, "https://github.com/dotnet/roslyn/issues/34299")] public void CheckLambdaInLambdaInference() { var source = @"using System; class C { static Func<T> M<T>(Func<T> f) => f; static void G(int i, object? o, string? s) { if (o == null) return; var f = M(() => o); var f2 = M(() => { if (i == 1) return f; if (i == 2) return () => s; // 1 return () => { return s; // 2 }; }); f2().ToString(); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,42): warning CS8603: Possible null reference return. // if (i == 2) return () => s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(12, 42), // (14,32): warning CS8603: Possible null reference return. // return s; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(14, 32)); } [Fact, WorkItem(29956, "https://github.com/dotnet/roslyn/issues/29956")] public void ConditionalExpression_InferredResultType() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test1(object? x) { M(x)?.Self()/*T:Box<object?>?*/; M(x)?.Value()/*T:object?*/; if (x == null) return; M(x)?.Self()/*T:Box<object!>?*/; M(x)?.Value()/*T:object?*/; } void Test2<T>(T x) { M(x)?.Self()/*T:Box<T>?*/; M(x)?.Value()/*T:void*/; if (x == null) return; M(x)?.Self()/*T:Box<T>?*/; M(x)?.Value()/*T:void*/; } void Test3(int x) { M(x)?.Self()/*T:Box<int>?*/; M(x)?.Value()/*T:int?*/; if (x == null) return; // 1 M(x)?.Self()/*T:Box<int>?*/; M(x)?.Value()/*T:int?*/; } void Test4(int? x) { M(x)?.Self()/*T:Box<int?>?*/; M(x)?.Value()/*T:int?*/; if (x == null) return; M(x)?.Self()/*T:Box<int?>?*/; M(x)?.Value()/*T:int?*/; } void Test5<T>(T? x) where T : class { M(x)?.Self()/*T:Box<T?>?*/; M(x)?.Value()/*T:T?*/; if (x == null) return; M(x)?.Self()/*T:Box<T!>?*/; M(x)?.Value()/*T:T?*/; } void Test6<T>(T x) where T : struct { M(x)?.Self()/*T:Box<T>?*/; M(x)?.Value()/*T:T?*/; if (x == null) return; // 2 M(x)?.Self()/*T:Box<T>?*/; M(x)?.Value()/*T:T?*/; } void Test7<T>(T? x) where T : struct { M(x)?.Self()/*T:Box<T?>?*/; M(x)?.Value()/*T:T?*/; if (x == null) return; M(x)?.Self()/*T:Box<T?>?*/; M(x)?.Value()/*T:T?*/; } void Test8<T>(T x) where T : class { M(x)?.Self()/*T:Box<T!>?*/; M(x)?.Value()/*T:T?*/; if (x == null) return; M(x)?.Self()/*T:Box<T!>?*/; M(x)?.Value()/*T:T?*/; } void Test9<T>(T x) where T : class { M(x)?.Self()/*T:Box<T!>?*/; M(x)?.Value()/*T:T?*/; if (x != null) return; M(x)?.Self()/*T:Box<T?>?*/; M(x)?.Value()/*T:T?*/; } static Box<T> M<T>(T t) => new Box<T>(t); } class Box<T> { public Box<T> Self() => this; public T Value() => throw null!; public Box(T value) { } } "); c.VerifyTypes(); c.VerifyDiagnostics( // (26,13): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // if (x == null) return; // 1 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "x == null").WithArguments("false", "int", "int?").WithLocation(26, 13), // (53,13): error CS0019: Operator '==' cannot be applied to operands of type 'T' and '<null>' // if (x == null) return; // 2 Diagnostic(ErrorCode.ERR_BadBinaryOps, "x == null").WithArguments("==", "T", "<null>").WithLocation(53, 13)); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_01() { var source = @"#nullable enable using System; public class Program { static void Main(string? value) { int count = 84; if (value?.Length == count) { Console.WriteLine(value.Length); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_02() { var source = @"#nullable enable using System; public class Program { static void Main(string? value) { if (value?.Length == (int?) null) { Console.WriteLine(value.Length); // 1 } else { Console.WriteLine(value.Length); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(value.Length); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(10, 31)); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_03() { var source = @"#nullable enable using System; public class Program { static void Main(string? value) { int? i = null; if (value?.Length == i) { Console.WriteLine(value.Length); // 1 } else { Console.WriteLine(value.Length); // 2 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(value.Length); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(11, 31), // (15,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(value.Length); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(15, 31)); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_04() { var source = @"#nullable enable using System; public class C { public string? s; } public class Program { static void Main(C? value) { const object? i = null; if (value?.s == i) { Console.WriteLine(value.s); // 1 } else { Console.WriteLine(value.s); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (16,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(value.s); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(16, 31)); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_05() { var source = @"#nullable enable using System; public class Program { static void Main(string? x, string? y) { if (x?.Length == 2 && y?.Length == 2) { Console.WriteLine(x.Length); Console.WriteLine(y.Length); } else { Console.WriteLine(x.Length); // 1 Console.WriteLine(y.Length); // 2 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(x.Length); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 31), // (16,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(y.Length); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(16, 31)); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_06() { var source = @"#nullable enable using System; public class Program { static void Main(string? x, string? y) { if (x?.Length != 2 || y?.Length != 2) { Console.WriteLine(x.Length); // 1 Console.WriteLine(y.Length); // 2 } else { Console.WriteLine(x.Length); Console.WriteLine(y.Length); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(x.Length); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 31), // (11,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(y.Length); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 31)); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_07() { var source = @"#nullable enable using System; public class Program { static void Main(string? x, string? y) { if (x?.Length == 2 ? y?.Length == 2 : y?.Length == 3) { Console.WriteLine(x.Length); // 1 Console.WriteLine(y.Length); } else { Console.WriteLine(x.Length); // 2 Console.WriteLine(y.Length); // 3 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(x.Length); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 31), // (15,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(x.Length); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 31), // (16,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(y.Length); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(16, 31) ); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_08() { var source = @"#nullable enable using System; public class A { public static explicit operator B(A? a) => new B(); } public class B { } public class Program { static void Main(A? a) { B b = new B(); if ((B)a == b) { Console.WriteLine(a.ToString()); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(a.ToString()); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(19, 31)); } [Fact, WorkItem(35075, "https://github.com/dotnet/roslyn/issues/35075")] public void ConditionalExpression_TypeParameterConstrainedToNullableValueType() { CSharpCompilation c = CreateNullableCompilation(@" class C<T> { public virtual void M<U>(B x, U y) where U : T { } } class B : C<int?> { public override void M<U>(B x, U y) { var z = x?.Test(y)/*T:U?*/; z = null; } T Test<T>(T x) => throw null!; }"); c.VerifyTypes(); // Per https://github.com/dotnet/roslyn/issues/35075 errors should be expected c.VerifyDiagnostics(); } [Fact] public void AttributeAnnotation_DoesNotReturnIfFalse() { var source = @"#pragma warning disable 169 using System.Diagnostics.CodeAnalysis; class A : System.Attribute { internal A(object x, object y) { } } [A(Assert(F != null), F)] class Program { static object? F; static object Assert([DoesNotReturnIf(false)]bool b) => throw null!; }"; var comp = CreateCompilation(new[] { DoesNotReturnIfAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(Assert(F != null), F)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "Assert(F != null)").WithLocation(7, 4), // (7,23): warning CS8604: Possible null reference argument for parameter 'y' in 'A.A(object x, object y)'. // [A(Assert(F != null), F)] Diagnostic(ErrorCode.WRN_NullReferenceArgument, "F").WithArguments("y", "A.A(object x, object y)").WithLocation(7, 23), // (7,23): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(Assert(F != null), F)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F").WithLocation(7, 23)); } [Fact] public void AttributeAnnotation_NotNull() { var source = @"#pragma warning disable 169 using System.Diagnostics.CodeAnalysis; class A : System.Attribute { internal A(object x, object y) { } } [A(NotNull(F), F)] class Program { static object? F; static object NotNull([NotNull]object? o) => throw null!; }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(NotNull(F), F)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "NotNull(F)").WithLocation(7, 4), // (7,16): warning CS8604: Possible null reference argument for parameter 'y' in 'A.A(object x, object y)'. // [A(NotNull(F), F)] Diagnostic(ErrorCode.WRN_NullReferenceArgument, "F").WithArguments("y", "A.A(object x, object y)").WithLocation(7, 16), // (7,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(NotNull(F), F)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F").WithLocation(7, 16)); } [Fact] [WorkItem(35056, "https://github.com/dotnet/roslyn/issues/35056")] public void CircularAttribute() { var source = @"class A : System.Attribute { A([A(1)]int x) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(34827, "https://github.com/dotnet/roslyn/issues/34827")] public void ArrayConversionToInterface() { string source = @" using System.Collections.Generic; class C { void M() { IEnumerable<object> x1 = new[] { ""string"", null }; // 1 IEnumerable<object?> x2 = new[] { ""string"", null }; IEnumerable<object?> x3 = new[] { ""string"" }; IList<string> x4 = new[] { ""string"", null }; // 2 ICollection<string?> x5 = new[] { ""string"", null }; ICollection<string?> x6 = new[] { ""string"" }; IReadOnlyList<string?> x7 = new[] { ""string"" }; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,34): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'IEnumerable<object>'. // IEnumerable<object> x1 = new[] { "string", null }; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new[] { ""string"", null }").WithArguments("string?[]", "System.Collections.Generic.IEnumerable<object>").WithLocation(7, 34), // (10,28): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'IList<string>'. // IList<string> x4 = new[] { "string", null }; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new[] { ""string"", null }").WithArguments("string?[]", "System.Collections.Generic.IList<string>").WithLocation(10, 28) ); } [Fact, WorkItem(34827, "https://github.com/dotnet/roslyn/issues/34827")] public void ArrayConversionToInterface_Nested() { string source = @" using System.Collections.Generic; class C { void M() { IEnumerable<object[]> x1 = new[] { new[] { ""string"", null } }; // 1 IEnumerable<object[]?> x2 = new[] { new[] { ""string"", null } }; // 2 IEnumerable<object?[]> x3 = new[] { new[] { ""string"", null } }; IEnumerable<object?[]?> x4 = new[] { new[] { ""string"" } }; IEnumerable<IEnumerable<string>> x5 = new[] { new[] { ""string"" , null } }; // 3 IEnumerable<IEnumerable<string?>> x6 = new[] { new[] { ""string"" , null } }; IEnumerable<IEnumerable<string?>> x7 = new[] { new[] { ""string"" } }; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,36): warning CS8619: Nullability of reference types in value of type 'string?[][]' doesn't match target type 'IEnumerable<object[]>'. // IEnumerable<object[]> x1 = new[] { new[] { "string", null } }; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new[] { new[] { ""string"", null } }").WithArguments("string?[][]", "System.Collections.Generic.IEnumerable<object[]>").WithLocation(7, 36), // (8,37): warning CS8619: Nullability of reference types in value of type 'string?[][]' doesn't match target type 'IEnumerable<object[]?>'. // IEnumerable<object[]?> x2 = new[] { new[] { "string", null } }; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new[] { new[] { ""string"", null } }").WithArguments("string?[][]", "System.Collections.Generic.IEnumerable<object[]?>").WithLocation(8, 37), // (11,47): warning CS8619: Nullability of reference types in value of type 'string?[][]' doesn't match target type 'IEnumerable<IEnumerable<string>>'. // IEnumerable<IEnumerable<string>> x5 = new[] { new[] { "string" , null } }; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new[] { new[] { ""string"" , null } }").WithArguments("string?[][]", "System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<string>>").WithLocation(11, 47) ); } [Fact] [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] public void ExtensionMethodDelegate_01() { var source = @"delegate void D0(); delegate void D1<T>(T t); static class E { internal static void F<T>(this T t) { } } class Program { static void M0(string? x, string y) { D0 d; d = x.F; d = x.F<string?>; d = x.F<string>; // 1 d = y.F; d = y.F<string?>; d = y.F<string>; } static void M1() { D1<string?> d; D1<string> e; d = E.F<string?>; d = E.F<string>; // 2 e = E.F<string?>; e = E.F<string>; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string>(string t)'. // d = x.F<string>; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string>(string t)").WithLocation(14, 13), // (24,13): warning CS8622: Nullability of reference types in type of parameter 't' of 'void E.F<string>(string t)' doesn't match the target delegate 'D1<string?>'. // d = E.F<string>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "E.F<string>").WithArguments("t", "void E.F<string>(string t)", "D1<string?>").WithLocation(24, 13)); } [Fact] public void ExtensionMethodDelegate_02() { var source = @"delegate void D0(); delegate void D1<T>(T t); static class E { internal static void F<T>(this T t) { } } class Program { static void M0(string? x, string y) { _ = new D0(x.F); _ = new D0(x.F<string?>); _ = new D0(x.F<string>); // 1 _ = new D0(y.F); _ = new D0(y.F<string?>); _ = new D0(y.F<string>); } static void M1() { _ = new D1<string?>(E.F<string?>); _ = new D1<string?>(E.F<string>); // 2 _ = new D1<string>(E.F<string?>); _ = new D1<string>(E.F<string>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,20): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string>(string t)'. // _ = new D0(x.F<string>); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string>(string t)").WithLocation(13, 20), // (21,29): warning CS8622: Nullability of reference types in type of parameter 't' of 'void E.F<string>(string t)' doesn't match the target delegate 'D1<string?>'. // _ = new D1<string?>(E.F<string>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "E.F<string>").WithArguments("t", "void E.F<string>(string t)", "D1<string?>").WithLocation(21, 29)); } [Fact] [WorkItem(30287, "https://github.com/dotnet/roslyn/issues/30287")] [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] public void ExtensionMethodDelegate_03() { var source = @"delegate void D<in T>(T t); static class E { internal static void F<T>(this T t, int i) { } } class Program { static void M(string? x, string y) { D<int> d; d = x.F; d = x.F<string?>; d = x.F<string>; // 1 d = y.F; d = y.F<string?>; d = y.F<string>; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string>(string t, int i)'. // d = x.F<string>; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string>(string t, int i)").WithLocation(13, 13)); } [Fact] [WorkItem(30287, "https://github.com/dotnet/roslyn/issues/30287")] public void ExtensionMethodDelegate_04() { var source = @"delegate void D<in T>(T t); static class E { internal static void F<T>(this T t, int i) { } } class Program { static void M(string? x, string y) { _ = new D<int>(x.F); _ = new D<int>(x.F<string?>); _ = new D<int>(x.F<string>); // 1 _ = new D<int>(y.F); _ = new D<int>(y.F<string?>); _ = new D<int>(y.F<string>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,24): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string>(string t, int i)'. // _ = new D<int>(x.F<string>); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string>(string t, int i)").WithLocation(12, 24)); } [Fact] [WorkItem(30287, "https://github.com/dotnet/roslyn/issues/30287")] [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] public void ExtensionMethodDelegate_05() { var source = @"delegate void D<in T>(T t); static class E { internal static void F<T, U>(this T t, U u) { } } class Program { static void M(bool b, string? x, string y) { D<string?> d; D<string> e; if (b) d = x.F<string?, string?>; if (b) e = x.F<string?, string>; if (b) d = x.F<string, string?>; // 1 if (b) e = x.F<string, string>; // 2 if (b) d = y.F<string?, string?>; if (b) e = y.F<string?, string>; if (b) d = y.F<string, string?>; if (b) e = y.F<string, string>; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,20): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string, string?>(string t, string? u)'. // if (b) d = x.F<string, string?>; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string, string?>(string t, string? u)").WithLocation(14, 20), // (15,20): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string, string>(string t, string u)'. // if (b) e = x.F<string, string>; // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string, string>(string t, string u)").WithLocation(15, 20)); } [Fact] [WorkItem(30287, "https://github.com/dotnet/roslyn/issues/30287")] public void ExtensionMethodDelegate_06() { var source = @"delegate void D<in T>(T t); static class E { internal static void F<T, U>(this T t, U u) { } } class Program { static void M(bool b, string? x, string y) { if (b) _ = new D<string?>(x.F<string?, string?>); if (b) _ = new D<string>(x.F<string?, string>); if (b) _ = new D<string?>(x.F<string, string?>); // 1 if (b) _ = new D<string>(x.F<string, string>); // 2 if (b) _ = new D<string?>(y.F<string?, string?>); if (b) _ = new D<string>(y.F<string?, string>); if (b) _ = new D<string?>(y.F<string, string?>); if (b) _ = new D<string>(y.F<string, string>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,35): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string, string?>(string t, string? u)'. // if (b) _ = new D<string?>(x.F<string, string?>); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string, string?>(string t, string? u)").WithLocation(12, 35), // (13,34): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string, string>(string t, string u)'. // if (b) _ = new D<string>(x.F<string, string>); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string, string>(string t, string u)").WithLocation(13, 34)); } [Fact] [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] public void ExtensionMethodDelegate_07() { var source = @"delegate void D(); static class E { internal static void F<T>(this T t) { } } class Program { static void M<T, U, V>() where U : class where V : struct { D d; d = default(T).F; d = default(U).F; d = default(V).F; d = default(V?).F; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): error CS1113: Extension method 'E.F<T>(T)' defined on value type 'T' cannot be used to create delegates // d = default(T).F; Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "default(T).F").WithArguments("E.F<T>(T)", "T").WithLocation(13, 13), // (15,13): error CS1113: Extension method 'E.F<V>(V)' defined on value type 'V' cannot be used to create delegates // d = default(V).F; Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "default(V).F").WithArguments("E.F<V>(V)", "V").WithLocation(15, 13), // (16,13): error CS1113: Extension method 'E.F<V?>(V?)' defined on value type 'V?' cannot be used to create delegates // d = default(V?).F; Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "default(V?).F").WithArguments("E.F<V?>(V?)", "V?").WithLocation(16, 13)); } [Fact] [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] public void ExtensionMethodDelegate_08() { var source = @"delegate void D(); static class E { internal static void F<T>(this T t) { } } class Program { static void M<T, U, V>() where U : class where V : struct { _ = new D(default(T).F); _ = new D(default(U).F); _ = new D(default(V).F); _ = new D(default(V?).F); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,19): error CS1113: Extension method 'E.F<T>(T)' defined on value type 'T' cannot be used to create delegates // _ = new D(default(T).F); Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "default(T).F").WithArguments("E.F<T>(T)", "T").WithLocation(12, 19), // (14,19): error CS1113: Extension method 'E.F<V>(V)' defined on value type 'V' cannot be used to create delegates // _ = new D(default(V).F); Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "default(V).F").WithArguments("E.F<V>(V)", "V").WithLocation(14, 19), // (15,19): error CS1113: Extension method 'E.F<V?>(V?)' defined on value type 'V?' cannot be used to create delegates // _ = new D(default(V?).F); Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "default(V?).F").WithArguments("E.F<V?>(V?)", "V?").WithLocation(15, 19)); } [Fact] [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] public void ExtensionMethodDelegate_09() { var source = @"delegate T D<T>(); static class E { internal static T F<T>(this T t) => t; } class Program { static void M<T>() where T : class { T? t = default; D<T> d; d = t.F; // 1 d = t.F!; d = t.F<T?>; // 2 d = t.F<T?>!; _ = new D<T>(t.F); // 3 _ = new D<T>(t.F!); _ = new D<T>(t.F<T?>); // 4 _ = new D<T>(t.F<T?>!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,13): warning CS8621: Nullability of reference types in return type of 'T? E.F<T?>(T? t)' doesn't match the target delegate 'D<T>'. // d = t.F; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "t.F").WithArguments("T? E.F<T?>(T? t)", "D<T>").WithLocation(12, 13), // (14,13): warning CS8621: Nullability of reference types in return type of 'T? E.F<T?>(T? t)' doesn't match the target delegate 'D<T>'. // d = t.F<T?>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "t.F<T?>").WithArguments("T? E.F<T?>(T? t)", "D<T>").WithLocation(14, 13), // (16,22): warning CS8621: Nullability of reference types in return type of 'T? E.F<T?>(T? t)' doesn't match the target delegate 'D<T>'. // _ = new D<T>(t.F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "t.F").WithArguments("T? E.F<T?>(T? t)", "D<T>").WithLocation(16, 22), // (18,22): warning CS8621: Nullability of reference types in return type of 'T? E.F<T?>(T? t)' doesn't match the target delegate 'D<T>'. // _ = new D<T>(t.F<T?>); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "t.F<T?>").WithArguments("T? E.F<T?>(T? t)", "D<T>").WithLocation(18, 22)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void DelegateInferredNullability_01() { var source = @"delegate T D<T>(); class C<T> { internal T F() => throw null!; } class Program { static C<T> Create<T>(T t) => new C<T>(); static void M() { object? x = new object(); object y = null; // 1 D<object?> d1; D<object> d2; d1 = Create(x).F; d2 = Create(x).F; d1 = Create(y).F; d2 = Create(y).F; // 2 _ = new D<object?>(Create(x).F); _ = new D<object>(Create(x).F); _ = new D<object?>(Create(y).F); _ = new D<object>(Create(y).F); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 20), // (18,14): warning CS8621: Nullability of reference types in return type of 'object? C<object?>.F()' doesn't match the target delegate 'D<object>'. // d2 = Create(y).F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Create(y).F").WithArguments("object? C<object?>.F()", "D<object>").WithLocation(18, 14), // (22,27): warning CS8621: Nullability of reference types in return type of 'object? C<object?>.F()' doesn't match the target delegate 'D<object>'. // _ = new D<object>(Create(y).F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Create(y).F").WithArguments("object? C<object?>.F()", "D<object>").WithLocation(22, 27)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void DelegateInferredNullability_02() { var source = @"delegate void D<T>(T t); class C<T> { internal void F(T t) { } } class Program { static C<T> Create<T>(T t) => new C<T>(); static void M() { object? x = new object(); object y = null; // 1 D<object?> d1; D<object> d2; d1 = Create(x).F; // 2 d2 = Create(x).F; d1 = Create(y).F; d2 = Create(y).F; _ = new D<object?>(Create(x).F); // 3 _ = new D<object>(Create(x).F); _ = new D<object?>(Create(y).F); _ = new D<object>(Create(y).F); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 20), // (15,14): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C<object>.F(object t)' doesn't match the target delegate 'D<object?>'. // d1 = Create(x).F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Create(x).F").WithArguments("t", "void C<object>.F(object t)", "D<object?>").WithLocation(15, 14), // (19,28): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C<object>.F(object t)' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>(Create(x).F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Create(x).F").WithArguments("t", "void C<object>.F(object t)", "D<object?>").WithLocation(19, 28)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void DelegateInferredNullability_03() { var source = @"delegate T D<T>(); class C<T> { internal U F<U>() where U : T => throw null!; } class Program { static C<T> Create<T>(T t) => new C<T>(); static void M<T>() where T : class, new() { T? x = new T(); T y = null; // 1 D<T?> d1; D<T> d2; d1 = Create(x).F<T?>; // 2 d2 = Create(x).F<T>; d1 = Create(y).F<T?>; d2 = Create(y).F<T>; _ = new D<T?>(Create(x).F<T?>); // 3 _ = new D<T>(Create(x).F<T>); _ = new D<T?>(Create(y).F<T?>); _ = new D<T>(Create(y).F<T>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 15), // (15,14): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'C<T>.F<U>()'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // d1 = Create(x).F<T?>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "Create(x).F<T?>").WithArguments("C<T>.F<U>()", "T", "U", "T?").WithLocation(15, 14), // (19,23): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'C<T>.F<U>()'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // _ = new D<T?>(Create(x).F<T?>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "Create(x).F<T?>").WithArguments("C<T>.F<U>()", "T", "U", "T?").WithLocation(19, 23)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void DelegateInferredNullability_04() { var source = @"delegate void D<T>(T t); class C<T> { internal void F<U>(U u) where U : T { } } class Program { static C<T> Create<T>(T t) => new C<T>(); static void M<T>() where T : class, new() { T? x = new T(); T y = null; // 1 D<T?> d1; D<T> d2; d1 = Create(x).F; // 2 d2 = Create(x).F; d1 = Create(y).F; d2 = Create(y).F; _ = new D<T?>(Create(x).F); // 3 _ = new D<T>(Create(x).F); _ = new D<T?>(Create(y).F); _ = new D<T>(Create(y).F); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 15), // (15,14): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'C<T>.F<U>(U)'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // d1 = Create(x).F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "Create(x).F").WithArguments("C<T>.F<U>(U)", "T", "U", "T?").WithLocation(15, 14), // (19,23): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'C<T>.F<U>(U)'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // _ = new D<T?>(Create(x).F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "Create(x).F").WithArguments("C<T>.F<U>(U)", "T", "U", "T?").WithLocation(19, 23)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void DelegateInferredNullability_05() { var source = @"delegate void D<T>(T t); class C<T> { internal void F<U>(U u) where U : T { } } class Program { static C<T> Create<T>(T t) => new C<T>(); static void M<T>() where T : class, new() { T? x = new T(); T y = null; // 1 D<T?> d1; D<T> d2; d1 = Create(x).F<T?>; // 2 d2 = Create(x).F<T>; d1 = Create(y).F<T?>; d2 = Create(y).F<T>; _ = new D<T?>(Create(x).F<T?>); // 3 _ = new D<T>(Create(x).F<T>); _ = new D<T?>(Create(y).F<T?>); _ = new D<T>(Create(y).F<T>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 15), // (15,14): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'C<T>.F<U>(U)'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // d1 = Create(x).F<T?>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "Create(x).F<T?>").WithArguments("C<T>.F<U>(U)", "T", "U", "T?").WithLocation(15, 14), // (19,23): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'C<T>.F<U>(U)'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // _ = new D<T?>(Create(x).F<T?>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "Create(x).F<T?>").WithArguments("C<T>.F<U>(U)", "T", "U", "T?").WithLocation(19, 23)); } [Fact] [WorkItem(35274, "https://github.com/dotnet/roslyn/issues/35274")] public void DelegateInferredNullability_06() { var source = @"delegate T D<T>(); class C<T> { internal T F() => throw null!; } class Program { static C<T> Create<T>(T t) => new C<T>(); static void Main() { string? s = null; var x = Create(s); C<string?> y = Create(s); D<string> d; d = Create(s).F; // 1 d = x.F; // 2 d = y.F; // 3 _ = new D<string>(Create(s).F); // 4 _ = new D<string>(x.F); // 5 _ = new D<string>(y.F); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): warning CS8621: Nullability of reference types in return type of 'string? C<string?>.F()' doesn't match the target delegate 'D<string>'. // d = Create(s).F; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Create(s).F").WithArguments("string? C<string?>.F()", "D<string>").WithLocation(15, 13), // (16,13): warning CS8621: Nullability of reference types in return type of 'string? C<string?>.F()' doesn't match the target delegate 'D<string>'. // d = x.F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.F").WithArguments("string? C<string?>.F()", "D<string>").WithLocation(16, 13), // (17,13): warning CS8621: Nullability of reference types in return type of 'string? C<string?>.F()' doesn't match the target delegate 'D<string>'. // d = y.F; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "y.F").WithArguments("string? C<string?>.F()", "D<string>").WithLocation(17, 13), // (18,27): warning CS8621: Nullability of reference types in return type of 'string? C<string?>.F()' doesn't match the target delegate 'D<string>'. // _ = new D<string>(Create(s).F); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Create(s).F").WithArguments("string? C<string?>.F()", "D<string>").WithLocation(18, 27), // (19,27): warning CS8621: Nullability of reference types in return type of 'string? C<string?>.F()' doesn't match the target delegate 'D<string>'. // _ = new D<string>(x.F); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.F").WithArguments("string? C<string?>.F()", "D<string>").WithLocation(19, 27), // (20,27): warning CS8621: Nullability of reference types in return type of 'string? C<string?>.F()' doesn't match the target delegate 'D<string>'. // _ = new D<string>(y.F); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "y.F").WithArguments("string? C<string?>.F()", "D<string>").WithLocation(20, 27)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_01() { var source = @"delegate T D<T>(); static class E { internal static T F<T>(this T t) => t; } class Program { static void M() { object? x = new object(); object y = null; // 1 D<object?> d1; D<object> d2; d1 = x.F; d2 = x.F; d1 = y.F; d2 = y.F; // 2 _ = new D<object?>(x.F); _ = new D<object>(x.F); _ = new D<object?>(y.F); _ = new D<object>(y.F); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 20), // (17,14): warning CS8621: Nullability of reference types in return type of 'object? E.F<object?>(object? t)' doesn't match the target delegate 'D<object>'. // d2 = y.F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "y.F").WithArguments("object? E.F<object?>(object? t)", "D<object>").WithLocation(17, 14), // (21,27): warning CS8621: Nullability of reference types in return type of 'object? E.F<object?>(object? t)' doesn't match the target delegate 'D<object>'. // _ = new D<object>(y.F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "y.F").WithArguments("object? E.F<object?>(object? t)", "D<object>").WithLocation(21, 27)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_02() { var source = @"delegate void D<T>(T t); static class E { internal static void F<T>(this T x, T y) { } } class Program { static void M() { object? x = new object(); object y = null; // 1 D<object?> d1; D<object> d2; d1 = x.F; d2 = x.F; d1 = y.F; d2 = y.F; _ = new D<object?>(x.F); _ = new D<object>(x.F); _ = new D<object?>(y.F); _ = new D<object>(y.F); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 20)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_03() { var source = @"delegate void D<T>(T t); static class E { internal static void F<T>(this T x, T y) { } } class Program { static void M(bool b) { object? x = new object(); object y = null; // 1 D<object?> d1; D<object> d2; if (b) d1 = x.F<object?>; if (b) d2 = x.F<object>; if (b) d1 = y.F<object?>; if (b) d2 = y.F<object>; // 2 if (b) _ = new D<object?>(x.F<object?>); if (b) _ = new D<object>(x.F<object>); if (b) _ = new D<object?>(y.F<object?>); if (b) _ = new D<object>(y.F<object>); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 20), // (17,21): warning CS8604: Possible null reference argument for parameter 'x' in 'void E.F<object>(object x, object y)'. // if (b) d2 = y.F<object>; // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void E.F<object>(object x, object y)").WithLocation(17, 21), // (21,34): warning CS8604: Possible null reference argument for parameter 'x' in 'void E.F<object>(object x, object y)'. // if (b) _ = new D<object>(y.F<object>); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void E.F<object>(object x, object y)").WithLocation(21, 34)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_04() { var source = @"delegate T D<T>(); static class E { internal static T F<T>(this T t) => t; } class Program { static void M<T>(bool b) where T : class, new() { T? x = new T(); T y = null; // 1 D<T?> d1; D<T> d2; if (b) d1 = x.F<T?>; if (b) d2 = x.F<T>; if (b) d1 = y.F<T?>; if (b) d2 = y.F<T>; // 2 if (b) _ = new D<T?>(x.F<T?>); if (b) _ = new D<T>(x.F<T>); if (b) _ = new D<T?>(y.F<T?>); if (b) _ = new D<T>(y.F<T>); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 15), // (17,21): warning CS8604: Possible null reference argument for parameter 't' in 'T E.F<T>(T t)'. // if (b) d2 = y.F<T>; // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("t", "T E.F<T>(T t)").WithLocation(17, 21), // (21,29): warning CS8604: Possible null reference argument for parameter 't' in 'T E.F<T>(T t)'. // if (b) _ = new D<T>(y.F<T>); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("t", "T E.F<T>(T t)").WithLocation(21, 29)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_05() { var source = @"delegate void D<T>(T t); static class E { internal static void F<T, U>(this T t, U u) where U : T { } } class Program { static void M<T>() where T : class, new() { T? x = new T(); T y = null; // 1 D<T?> d1; D<T> d2; d1 = x.F; // 2 d2 = x.F; d1 = y.F; d2 = y.F; _ = new D<T?>(x.F); // 3 _ = new D<T>(x.F); _ = new D<T?>(y.F); _ = new D<T>(y.F); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 15), // (14,14): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'E.F<T, U>(T, U)'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // d1 = x.F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "x.F").WithArguments("E.F<T, U>(T, U)", "T", "U", "T?").WithLocation(14, 14), // (18,23): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'E.F<T, U>(T, U)'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // _ = new D<T?>(x.F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "x.F").WithArguments("E.F<T, U>(T, U)", "T", "U", "T?").WithLocation(18, 23)); } [Fact] [WorkItem(35274, "https://github.com/dotnet/roslyn/issues/35274")] public void ExtensionMethodDelegateInferredNullability_06() { var source = @"delegate T D<T>(); class C<T> { } static class E { internal static T F<T>(this C<T> c) => throw null!; } class Program { static C<T> Create<T>(T t) => new C<T>(); static void Main() { string? s = null; var x = Create(s); C<string?> y = Create(s); D<string> d; d = Create(s).F; // 1 d = x.F; // 2 d = y.F; // 3 _ = new D<string>(Create(s).F); // 4 _ = new D<string>(x.F); // 5 _ = new D<string>(y.F); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,13): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(C<string?> c)' doesn't match the target delegate 'D<string>'. // d = Create(s).F; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Create(s).F").WithArguments("string? E.F<string?>(C<string?> c)", "D<string>").WithLocation(18, 13), // (19,13): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(C<string?> c)' doesn't match the target delegate 'D<string>'. // d = x.F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.F").WithArguments("string? E.F<string?>(C<string?> c)", "D<string>").WithLocation(19, 13), // (20,13): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(C<string?> c)' doesn't match the target delegate 'D<string>'. // d = y.F; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "y.F").WithArguments("string? E.F<string?>(C<string?> c)", "D<string>").WithLocation(20, 13), // (21,27): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(C<string?> c)' doesn't match the target delegate 'D<string>'. // _ = new D<string>(Create(s).F); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Create(s).F").WithArguments("string? E.F<string?>(C<string?> c)", "D<string>").WithLocation(21, 27), // (22,27): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(C<string?> c)' doesn't match the target delegate 'D<string>'. // _ = new D<string>(x.F); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.F").WithArguments("string? E.F<string?>(C<string?> c)", "D<string>").WithLocation(22, 27), // (23,27): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(C<string?> c)' doesn't match the target delegate 'D<string>'. // _ = new D<string>(y.F); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "y.F").WithArguments("string? E.F<string?>(C<string?> c)", "D<string>").WithLocation(23, 27)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_07() { var source = @"delegate T D<T>(); static class E { internal static T F<T>(this T t) where T : class => t; } class Program { static void M<T>() where T : class, new() { T? x = new T(); T y = null; // 1 D<T?> d; d = x.F; d = y.F; // 2 _ = new D<T?>(x.F); _ = new D<T?>(y.F); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 15), // (14,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'E.F<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // d = y.F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "y.F").WithArguments("E.F<T>(T)", "T", "T?").WithLocation(14, 13), // (16,23): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'E.F<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = new D<T?>(y.F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "y.F").WithArguments("E.F<T>(T)", "T", "T?").WithLocation(16, 23)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_08() { var source = @"delegate T D<T>(); static class E { internal static T F<T>(this T t) => t; } class Program { static void M<T>() where T : class, new() { T x; N(() => { x = null; // 1 D<T> d = x.F; // 2 _ = new D<T>(x.F); // 3 }); } static void N(System.Action a) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 17), // (14,22): warning CS8621: Nullability of reference types in return type of 'T? E.F<T?>(T? t)' doesn't match the target delegate 'D<T>'. // D<T> d = x.F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.F").WithArguments("T? E.F<T?>(T? t)", "D<T>").WithLocation(14, 22), // (15,26): warning CS8621: Nullability of reference types in return type of 'T? E.F<T?>(T? t)' doesn't match the target delegate 'D<T>'. // _ = new D<T>(x.F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.F").WithArguments("T? E.F<T?>(T? t)", "D<T>").WithLocation(15, 26)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_09() { var source = @"delegate T D<T>(); static class E { internal static T F<T>(this T t) => t; } class A : System.Attribute { internal A(D<string> d) { } } [A(default(string).F)] class Program { }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,2): error CS0181: Attribute constructor parameter 'd' has type 'D<string>', which is not a valid attribute parameter type // [A(default(string).F)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("d", "D<string>").WithLocation(10, 2), // (10,4): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(string? t)' doesn't match the target delegate 'D<string>'. // [A(default(string).F)] Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "default(string).F").WithArguments("string? E.F<string?>(string? t)", "D<string>").WithLocation(10, 4)); } [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_01() { var source = @"class C<T> { public static C<T> operator &(C<T> a, C<T> b) => a; } class Program { static void M(C<string> a, string s) { var b = Create(s); _ = a & b; } static C<T> Create<T>(T t) => new C<T>(); }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } // C<T~> operator op(C<T~>, C<T~>) [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_02() { var source = @"#nullable disable class C<T> { public static C<T> operator +(C<T> a, C<T> b) => a; } class Program { static void M1<T>( #nullable disable C<T> a, #nullable enable C<T> b) { _ = a + a; _ = a + b; _ = b + a; _ = b + b; } static void M2<T>( #nullable disable C<T> c, #nullable enable C<T> d) where T : class? { _ = c + c; _ = c + d; _ = d + c; _ = d + d; } static void M3<T>( #nullable disable C<T> x, #nullable enable C<T> y, C<T?> z) where T : class { _ = x + x; _ = x + y; _ = x + z; _ = y + x; _ = y + y; _ = y + z; _ = z + x; _ = z + y; _ = z + z; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (44,17): warning CS8620: Argument of type 'C<T?>' cannot be used for parameter 'b' of type 'C<T>' in 'C<T> C<T>.operator +(C<T> a, C<T> b)' due to differences in the nullability of reference types. // _ = y + z; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C<T?>", "C<T>", "b", "C<T> C<T>.operator +(C<T> a, C<T> b)").WithLocation(44, 17), // (46,17): warning CS8620: Argument of type 'C<T>' cannot be used for parameter 'b' of type 'C<T?>' in 'C<T?> C<T?>.operator +(C<T?> a, C<T?> b)' due to differences in the nullability of reference types. // _ = z + y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<T>", "C<T?>", "b", "C<T?> C<T?>.operator +(C<T?> a, C<T?> b)").WithLocation(46, 17)); } // C<T> operator op(C<T>, C<T>) [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_03() { var source = @"#nullable enable class C<T> { public static C<T> operator -(C<T> a, C<T> b) => a; } class Program { static void M1<T>( #nullable disable C<T> a, #nullable enable C<T> b) { _ = a - a; _ = a - b; _ = b - a; _ = b - b; } static void M2<T>( #nullable disable C<T> c, #nullable enable C<T> d) where T : class? { _ = c - c; _ = c - d; _ = d - c; _ = d - d; } static void M3<T>( #nullable disable C<T> x, #nullable enable C<T> y, C<T?> z) where T : class { _ = x - x; _ = x - y; _ = x - z; _ = y - x; _ = y - y; _ = y - z; _ = z - x; _ = z - y; _ = z - z; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (44,17): warning CS8620: Argument of type 'C<T?>' cannot be used for parameter 'b' of type 'C<T>' in 'C<T> C<T>.operator -(C<T> a, C<T> b)' due to differences in the nullability of reference types. // _ = y - z; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C<T?>", "C<T>", "b", "C<T> C<T>.operator -(C<T> a, C<T> b)").WithLocation(44, 17), // (46,17): warning CS8620: Argument of type 'C<T>' cannot be used for parameter 'b' of type 'C<T?>' in 'C<T?> C<T?>.operator -(C<T?> a, C<T?> b)' due to differences in the nullability of reference types. // _ = z - y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<T>", "C<T?>", "b", "C<T?> C<T?>.operator -(C<T?> a, C<T?> b)").WithLocation(46, 17)); } // C<T~> operator op(C<T~>, C<T>) [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_04() { var source = @"class C<T> { #nullable disable public static C<T> operator *( C<T> a, #nullable enable C<T> b) => a; } class Program { static void M1<T>( #nullable disable C<T> a, #nullable enable C<T> b) { _ = a * a; _ = a * b; _ = b * a; _ = b * b; } static void M2<T>( #nullable disable C<T> c, #nullable enable C<T> d) where T : class? { _ = c * c; _ = c * d; _ = d * c; _ = d * d; } static void M3<T>( #nullable disable C<T> x, #nullable enable C<T> y, C<T?> z) where T : class { _ = x * x; _ = x * y; _ = x * z; _ = y * x; _ = y * y; _ = y * z; _ = z * x; _ = z * y; _ = z * z; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (47,17): warning CS8620: Argument of type 'C<T?>' cannot be used for parameter 'b' of type 'C<T>' in 'C<T> C<T>.operator *(C<T> a, C<T> b)' due to differences in the nullability of reference types. // _ = y * z; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C<T?>", "C<T>", "b", "C<T> C<T>.operator *(C<T> a, C<T> b)").WithLocation(47, 17), // (49,17): warning CS8620: Argument of type 'C<T>' cannot be used for parameter 'b' of type 'C<T?>' in 'C<T?> C<T?>.operator *(C<T?> a, C<T?> b)' due to differences in the nullability of reference types. // _ = z * y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<T>", "C<T?>", "b", "C<T?> C<T?>.operator *(C<T?> a, C<T?> b)").WithLocation(49, 17)); } // C<T~> operator op(C<T~>, C<T~>) where T : class? [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_05() { var source = @"#nullable enable class C<T> where T : class? { #nullable disable public static C<T> operator +(C<T> a, C<T> b) => a; } class Program { static void M1<T>( #nullable disable C<T> a, #nullable enable C<T> b) where T : class? { _ = a + a; _ = a + b; _ = b + a; _ = b + b; } static void M2<T>( #nullable disable C<T> x, #nullable enable C<T> y, C<T?> z) where T : class { _ = x + x; _ = x + y; _ = x + z; _ = y + x; _ = y + y; _ = y + z; _ = z + x; _ = z + y; _ = z + z; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (34,17): warning CS8620: Argument of type 'C<T?>' cannot be used for parameter 'b' of type 'C<T>' in 'C<T> C<T>.operator +(C<T> a, C<T> b)' due to differences in the nullability of reference types. // _ = y + z; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C<T?>", "C<T>", "b", "C<T> C<T>.operator +(C<T> a, C<T> b)").WithLocation(34, 17), // (36,17): warning CS8620: Argument of type 'C<T>' cannot be used for parameter 'b' of type 'C<T?>' in 'C<T?> C<T?>.operator +(C<T?> a, C<T?> b)' due to differences in the nullability of reference types. // _ = z + y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<T>", "C<T?>", "b", "C<T?> C<T?>.operator +(C<T?> a, C<T?> b)").WithLocation(36, 17)); } // C<T!> operator op(C<T!>, C<T!>) where T : class? [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_06() { var source = @"#nullable enable class C<T> where T : class? { public static C<T> operator -(C<T> a, C<T> b) => a; } class Program { static void M1<T>( #nullable disable C<T> a, #nullable enable C<T> b) where T : class? { _ = a - a; _ = a - b; _ = b - a; _ = b - b; } static void M2<T>( #nullable disable C<T> x, #nullable enable C<T> y, C<T?> z) where T : class { _ = x - x; _ = x - y; _ = x - z; _ = y - x; _ = y - y; _ = y - z; _ = z - x; _ = z - y; _ = z - z; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (33,17): warning CS8620: Argument of type 'C<T?>' cannot be used for parameter 'b' of type 'C<T>' in 'C<T> C<T>.operator -(C<T> a, C<T> b)' due to differences in the nullability of reference types. // _ = y - z; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C<T?>", "C<T>", "b", "C<T> C<T>.operator -(C<T> a, C<T> b)").WithLocation(33, 17), // (35,17): warning CS8620: Argument of type 'C<T>' cannot be used for parameter 'b' of type 'C<T?>' in 'C<T?> C<T?>.operator -(C<T?> a, C<T?> b)' due to differences in the nullability of reference types. // _ = z - y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<T>", "C<T?>", "b", "C<T?> C<T?>.operator -(C<T?> a, C<T?> b)").WithLocation(35, 17)); } // C<T~> operator op(C<T!>, C<T~>) where T : class? [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_07() { var source = @"#nullable enable class C<T> where T : class? { #nullable disable public static C<T> operator *( #nullable enable C<T> a, #nullable disable C<T> b) => a; } class Program { static void M1<T>( #nullable disable C<T> a, #nullable enable C<T> b) where T : class? { _ = a * a; _ = a * b; _ = b * a; _ = b * b; } static void M2<T>( #nullable disable C<T> x, #nullable enable C<T> y, C<T?> z) where T : class { _ = x * x; _ = x * y; _ = x * z; _ = y * x; _ = y * y; _ = y * z; _ = z * x; _ = z * y; _ = z * z; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (38,17): warning CS8620: Argument of type 'C<T?>' cannot be used for parameter 'b' of type 'C<T>' in 'C<T> C<T>.operator *(C<T> a, C<T> b)' due to differences in the nullability of reference types. // _ = y * z; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C<T?>", "C<T>", "b", "C<T> C<T>.operator *(C<T> a, C<T> b)").WithLocation(38, 17), // (40,17): warning CS8620: Argument of type 'C<T>' cannot be used for parameter 'b' of type 'C<T?>' in 'C<T?> C<T?>.operator *(C<T?> a, C<T?> b)' due to differences in the nullability of reference types. // _ = z * y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<T>", "C<T?>", "b", "C<T?> C<T?>.operator *(C<T?> a, C<T?> b)").WithLocation(40, 17)); } // C<T~> operator op(C<T~>, C<T~>) where T : class [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_08() { var source = @"#nullable enable class C<T> where T : class { #nullable disable public static C<T> operator /(C<T> a, C<T> b) => a; } class Program { static void M<T>( #nullable disable C<T> x, #nullable enable C<T> y) where T : class { _ = x / x; _ = x / y; _ = y / x; _ = y / y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } // C<T!> operator op(C<T!>, C<T!>) where T : class [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_09() { var source = @"#nullable enable class C<T> where T : class { public static C<T> operator &(C<T> a, C<T> b) => a; } class Program { static void M<T>( #nullable disable C<T> x, #nullable enable C<T> y) where T : class { _ = x & x; _ = x & y; _ = y & x; _ = y & y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } // C<T~> operator op(C<T!>, C<T~>) where T : class [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_10() { var source = @"#nullable enable class C<T> where T : class { #nullable disable public static C<T> operator |( #nullable enable C<T> a, #nullable disable C<T> b) => a; } class Program { static void M<T>( #nullable disable C<T> x, #nullable enable C<T> y) where T : class { _ = x | x; _ = x | y; _ = y | x; _ = y | y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/39361")] public void Operator_11() { var source = @" #nullable enable using System; struct S { public static implicit operator DateTime?(S? value) => default; bool M1(S? x1, DateTime y1) { return x1 == y1; } bool M2(DateTime? x2, DateTime y2) { return x2 == y2; } bool M3(DateTime x3, DateTime? y3) { return x3 == y3; } bool M4(DateTime x4, S? y4) { return x4 == y4; } bool M5(DateTime? x5, DateTime? y5) { return x5 == y5; } bool M6(S? x6, DateTime? y6) { return x6 == y6; } bool M7(DateTime? x7, S? y7) { return x7 == y7; } bool M8(DateTime x8, S y8) { return x8 == y8; } bool M9(S x9, DateTime y9) { return x9 == y9; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/39361")] public void Operator_12() { var source = @" #nullable enable struct S { public static bool operator-(S value) => default; bool? M1(S? x1) { return -x1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_NonNullExpr_LiteralNull_WarnsWhenTrue(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M(string s) {{ if ({equalsMethodName}(s, null)) {{ _ = s.ToString(); // 1 }} else {{ _ = s.ToString(); }} }} static void M2(string s) {{ if ({equalsMethodName}(null, s)) {{ _ = s.ToString(); // 2 }} else {{ _ = s.ToString(); }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17), // (21,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(21, 17)); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_NonNullExpr_NonNullExpr_NoWarning(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M(string s1, string s2) {{ if ({equalsMethodName}(s1, s2)) {{ _ = s1.ToString(); _ = s2.ToString(); }} else {{ _ = s1.ToString(); _ = s2.ToString(); }} }} static void M2(string s1, string s2) {{ if ({equalsMethodName}(s2, s1)) {{ _ = s1.ToString(); _ = s2.ToString(); }} else {{ _ = s1.ToString(); _ = s2.ToString(); }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38010, "https://github.com/dotnet/roslyn/issues/38010")] public void ReferenceEquals_IncompleteCall() { var source = @" #nullable enable class C { static void M() { ReferenceEquals( } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'objA' of 'object.ReferenceEquals(object, object)' // ReferenceEquals( Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "ReferenceEquals").WithArguments("objA", "object.ReferenceEquals(object, object)").WithLocation(7, 9), // (7,25): error CS1026: ) expected // ReferenceEquals( Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 25), // (7,25): error CS1002: ; expected // ReferenceEquals( Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 25)); } [Fact] [WorkItem(38010, "https://github.com/dotnet/roslyn/issues/38010")] public void EqualsMethod_BadArgCount() { var source = @" #nullable enable class C { void M(System.IEquatable<string> eq1) { object.Equals(); object.Equals(0); object.Equals(null, null, null); object.ReferenceEquals(); object.ReferenceEquals(1); object.ReferenceEquals(null, null, null); eq1.Equals(); eq1.Equals(true, false); this.Equals(); this.Equals(null, null); } public override bool Equals(object other) { return base.Equals(other); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,7): warning CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class C Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "C").WithArguments("C").WithLocation(3, 7), // (7,16): error CS1501: No overload for method 'Equals' takes 0 arguments // object.Equals(); Diagnostic(ErrorCode.ERR_BadArgCount, "Equals").WithArguments("Equals", "0").WithLocation(7, 16), // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'object.Equals(object)' // object.Equals(0); Diagnostic(ErrorCode.ERR_ObjectRequired, "object.Equals").WithArguments("object.Equals(object)").WithLocation(8, 9), // (9,16): error CS1501: No overload for method 'Equals' takes 3 arguments // object.Equals(null, null, null); Diagnostic(ErrorCode.ERR_BadArgCount, "Equals").WithArguments("Equals", "3").WithLocation(9, 16), // (11,16): error CS7036: There is no argument given that corresponds to the required formal parameter 'objA' of 'object.ReferenceEquals(object, object)' // object.ReferenceEquals(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "ReferenceEquals").WithArguments("objA", "object.ReferenceEquals(object, object)").WithLocation(11, 16), // (12,16): error CS7036: There is no argument given that corresponds to the required formal parameter 'objB' of 'object.ReferenceEquals(object, object)' // object.ReferenceEquals(1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "ReferenceEquals").WithArguments("objB", "object.ReferenceEquals(object, object)").WithLocation(12, 16), // (13,16): error CS1501: No overload for method 'ReferenceEquals' takes 3 arguments // object.ReferenceEquals(null, null, null); Diagnostic(ErrorCode.ERR_BadArgCount, "ReferenceEquals").WithArguments("ReferenceEquals", "3").WithLocation(13, 16), // (15,13): error CS1501: No overload for method 'Equals' takes 0 arguments // eq1.Equals(); Diagnostic(ErrorCode.ERR_BadArgCount, "Equals").WithArguments("Equals", "0").WithLocation(15, 13), // (16,9): error CS0176: Member 'object.Equals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead // eq1.Equals(true, false); Diagnostic(ErrorCode.ERR_ObjectProhibited, "eq1.Equals").WithArguments("object.Equals(object, object)").WithLocation(16, 9), // (18,14): error CS1501: No overload for method 'Equals' takes 0 arguments // this.Equals(); Diagnostic(ErrorCode.ERR_BadArgCount, "Equals").WithArguments("Equals", "0").WithLocation(18, 14), // (19,9): error CS0176: Member 'object.Equals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead // this.Equals(null, null); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.Equals").WithArguments("object.Equals(object, object)").WithLocation(19, 9)); } [Fact] [WorkItem(38010, "https://github.com/dotnet/roslyn/issues/38010")] public void EqualsMethod_DefaultArgument_01() { var source = @" #nullable enable class C // 1 { static void M(C c1) { if (c1.Equals()) { _ = c1.ToString(); // 2 } if (c1.Equals(null)) { _ = c1.ToString(); // 3 } } public override bool Equals(object? other = null) => false; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,7): warning CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class C // 1 Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "C").WithArguments("C").WithLocation(3, 7), // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(9, 17), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(14, 17)); } [Fact] [WorkItem(38010, "https://github.com/dotnet/roslyn/issues/38010")] public void EqualsMethod_DefaultArgument_02() { var source = @" #nullable enable class C : System.IEquatable<C> { static void M(C c1) { if (c1.Equals()) { _ = c1.ToString(); // 1 } if (c1.Equals(null)) { _ = c1.ToString(); // 2 } } public bool Equals(C? other = null) => false; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(9, 17), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(14, 17)); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_MaybeNullExpr_MaybeNullExpr_Warns(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M(string? s1, string? s2) {{ if ({equalsMethodName}(s1, s2)) {{ _ = s1.ToString(); // 1 _ = s2.ToString(); // 2 }} else {{ _ = s1.ToString(); // 3 _ = s2.ToString(); // 4 }} }} static void M2(string? s1, string? s2) {{ if ({equalsMethodName}(s2, s1)) {{ _ = s1.ToString(); // 5 _ = s2.ToString(); // 6 }} else {{ _ = s1.ToString(); // 7 _ = s2.ToString(); // 8 }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 17), // (10,17): warning CS8602: Dereference of a possibly null reference. // _ = s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 17), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(14, 17), // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = s2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(15, 17), // (23,17): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(23, 17), // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = s2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(24, 17), // (28,17): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(28, 17), // (29,17): warning CS8602: Dereference of a possibly null reference. // _ = s2.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(29, 17)); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_NonNullExpr_ConstantNull_WarnsWhenTrue(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M1(string s) {{ const string? s2 = null; if ({equalsMethodName}(s, s2)) {{ _ = s.ToString(); // 1 }} else {{ _ = s.ToString(); }} }} static void M2(string s) {{ const string? s2 = null; if ({equalsMethodName}(s2, s)) {{ _ = s.ToString(); // 2 }} else {{ _ = s.ToString(); }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 17), // (23,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(23, 17)); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_MaybeNullExpr_ConstantNull_NoWarningWhenFalse(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M1(string? s) {{ const string? s2 = null; if ({equalsMethodName}(s, s2)) {{ _ = s.ToString(); // 1 }} else {{ _ = s.ToString(); }} }} static void M2(string? s) {{ const string? s2 = null; if ({equalsMethodName}(s2, s)) {{ _ = s.ToString(); // 2 }} else {{ _ = s.ToString(); }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 17), // (23,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(23, 17)); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_NonNullExpr_MaybeNullExpr_NoWarning(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M1(string s) {{ string? s2 = null; if ({equalsMethodName}(s, s2)) {{ _ = s.ToString(); }} else {{ _ = s.ToString(); }} }} static void M2(string s) {{ string? s2 = null; if ({equalsMethodName}(s2, s)) {{ _ = s.ToString(); }} else {{ _ = s.ToString(); }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M1(string? s) {{ if ({equalsMethodName}(s, """")) {{ _ = s.ToString(); }} else {{ _ = s.ToString(); // 1 }} }} static void M2(string? s) {{ if ({equalsMethodName}("""", s)) {{ _ = s.ToString(); }} else {{ _ = s.ToString(); // 2 }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 17), // (25,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(25, 17)); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod__NullableValueTypeExpr_ValueTypeExpr_NoWarningWhenTrue(string equalsMethodName) { var source = $@" #nullable enable class C {{ int? i = 42; static void M1(C? c) {{ if ({equalsMethodName}(c?.i, 42)) {{ _ = c.i.Value.ToString(); }} else {{ _ = c.i.Value.ToString(); // 1 }} }} static void M2(C? c) {{ if ({equalsMethodName}(42, c?.i)) {{ _ = c.i.Value.ToString(); }} else {{ _ = c.i.Value.ToString(); // 2 }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = c.i.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(14, 17), // (14,17): warning CS8629: Nullable value type may be null. // _ = c.i.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.i").WithLocation(14, 17), // (26,17): warning CS8602: Dereference of a possibly null reference. // _ = c.i.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(26, 17), // (26,17): warning CS8629: Nullable value type may be null. // _ = c.i.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.i").WithLocation(26, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" #nullable enable class C { static void M1(string? s) { if ("""".Equals(s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceEqualsMethod_NonNullExpr_LiteralNull_NoWarningWhenTrue() { var source = @" #nullable enable class C { static void M1(string s) { if (s.Equals(null)) { _ = s.ToString(); // 1 } else { _ = s.ToString(); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceEqualsMethod_IEquatableMissing_MaybeNullExpr_NonNullExpr_Warns() { var source = @" #nullable enable class C { static void M1(string? s) { if ("""".Equals(s)) { _ = s.ToString(); // 1 } else { _ = s.ToString(); // 2 } } }"; var expected = new[] { // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17), // (13,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 17) }; var comp = CreateCompilation(source); comp.MakeTypeMissing(WellKnownType.System_IEquatable_T); comp.VerifyDiagnostics(expected); comp = CreateCompilation(source); comp.MakeMemberMissing(WellKnownMember.System_IEquatable_T__Equals); comp.VerifyDiagnostics(expected); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceEqualsMethod_IEquatableEqualsOverloaded_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" #pragma warning disable CS0436 namespace System { interface IEquatable<in T> { bool Equals(T t, int compareFlags); bool Equals(T t); } } #nullable enable class C : System.IEquatable<C?> { public bool Equals(C? other) => throw null!; public bool Equals(C? other, int compareFlags) => throw null!; static void M1(C? c) { C c1 = new C(); if (c1.Equals(c)) { _ = c.ToString(); } else { _ = c.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (27,17): warning CS8602: Dereference of a possibly null reference. // _ = c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(27, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceEqualsMethod_IEquatableEqualsBadSignature_MaybeNullExpr_NonNullExpr_Warns() { var source = @" #pragma warning disable CS0436 namespace System { interface IEquatable<in T> { bool Equals(T t, int compareFlags); } } #nullable enable class C : System.IEquatable<C?> { public bool Equals(C? c) => throw null!; public bool Equals(C? c, int compareFlags) => throw null!; static void M1(C? c) { C c1 = new C(); if (c1.Equals(c)) { _ = c.ToString(); // 1 } else { _ = c.ToString(); // 2 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (22,17): warning CS8602: Dereference of a possibly null reference. // _ = c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(22, 17), // (26,17): warning CS8602: Dereference of a possibly null reference. // _ = c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(26, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void IEquatableEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" using System; #nullable enable class C { static void M1(IEquatable<string?> equatable, string? s) { if (equatable.Equals(s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void IEquatableEqualsMethod_ClassConstrainedGeneric() { var source = @" using System; #nullable enable class C { static void M1<T>(IEquatable<T?> equatable, T? t) where T : class { if (equatable.Equals(t)) { _ = t.ToString(); } else { _ = t.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(15, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_UnconstrainedGeneric() { var source = @" using System; #nullable enable class C { static void M1<T>(IEquatable<T?> equatable, T? t) where T : class { if (equatable.Equals(t)) { _ = t.ToString(); } else { _ = t.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(15, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void IEquatableEqualsMethod_NullableVariance() { var source = @" using System; #nullable enable class C : IEquatable<string> { public bool Equals(string? s) => throw null!; static void M1(C c, string? s) { if (c.Equals(s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ImplInBaseType() { var source = @" using System; #nullable enable class B : IEquatable<string> { public bool Equals(string? s) => throw null!; } class C : B { static void M1(C c, string? s) { if (c.Equals(s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (20,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(20, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ExplicitImpl() { var source = @" using System; #nullable enable class C : IEquatable<string> { public bool Equals(string? s) => throw null!; bool IEquatable<string>.Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() // 1 : s.ToString(); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 15), // (14,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ImplicitImplInBaseType_ExplicitImplInDerivedType() { var source = @" using System; #nullable enable class B : IEquatable<string> { public bool Equals(string? s) => throw null!; } class C : B, IEquatable<string> { bool IEquatable<string>.Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ImplicitImplInBaseType_ExplicitImplInDerivedType_02() { var source = @" using System; #nullable enable class B : IEquatable<string> { public virtual bool Equals(string? s) => throw null!; } class C : B, IEquatable<string> { bool IEquatable<string>.Equals(string? s) => throw null!; public override bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(19, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ExplicitImplInDerivedType() { var source = @" using System; #nullable enable class B { public bool Equals(string? s) => throw null!; } class C : B, IEquatable<string> { bool IEquatable<string>.Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() // 1 : s.ToString(); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_Override() { var source = @" using System; #nullable enable class B : IEquatable<string> { public virtual bool Equals(string? s) => throw null!; } class C : B { public override bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ExplicitImplAboveNonImplementing() { var source = @" using System; #nullable enable class A : IEquatable<string> { bool IEquatable<string>.Equals(string? s) => throw null!; } class B : A { } class C : B { public bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() // 1 : s.ToString(); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(19, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_Complex() { var source = @" using System; #nullable enable class A { } class B { public virtual bool Equals(string? s) => throw null!; } class C : B, IEquatable<string> { } class D : C, IEquatable<string> { bool IEquatable<string>.Equals(string? s) => throw null!; public override bool Equals(string? s) => throw null!; } class E : D { static void M1(A a, string? s) { _ = a.Equals(s) ? s.ToString() : s.ToString(); // 1 } static void M2(B b, string? s) { _ = b.Equals(s) ? s.ToString() // 2 : s.ToString(); // 3 } static void M3(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 4 } static void M4(D d, string? s) { _ = d.Equals(s) ? s.ToString() : s.ToString(); // 5 } static void M5(E e, string? s) { _ = e.Equals(s) ? s.ToString() : s.ToString(); // 6 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (31,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(31, 15), // (37,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(37, 15), // (38,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(38, 15), // (45,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(45, 15), // (52,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(52, 15), // (59,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(59, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_VirtualImpl_ExplicitImpl_Override() { var source = @" using System; #nullable enable class A : IEquatable<string> { public virtual bool Equals(string? s) => throw null!; } class B : A, IEquatable<string> { bool IEquatable<string>.Equals(string? s) => throw null!; } class C : B { public override bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (24,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(24, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_DefaultImplementation_01() { var source = @" using System; #nullable enable interface I1 : IEquatable<string?> { bool IEquatable<string?>.Equals(string? s) => throw null!; void M1(string? s) { _ = this.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (14,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_DefaultImplementation_02() { var source = @" using System; #nullable enable interface I1 : IEquatable<string?> { bool IEquatable<string?>.Equals(string? s) => throw null!; } class C : I1 { void M1(string? s) { _ = this.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_DefaultImplementation_03() { var source = @" #nullable enable using System; interface I1 : IEquatable<string?> { bool IEquatable<string?>.Equals(string? s) => throw null!; } class C : I1 { bool Equals(string? s) => throw null!; void M1(string? s) { _ = this.Equals(s) ? s.ToString() // 1 : s.ToString(); // 2 } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_SkipIntermediateBasesAndOverrides() { var source = @" using System; #nullable enable class A : IEquatable<string?> { public virtual bool Equals(string? s) => throw null!; } class B : A, IEquatable<string?> { bool IEquatable<string?>.Equals(string? s) => throw null!; } class C : B { public override bool Equals(string? s) => throw null!; } class D : C { } class E : D { static void M1(E e, string? s) { _ = e.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (29,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(29, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_CallableExplicitImplementation() { var vbSource = @" Imports System Public Class C Implements IEquatable(Of String) Public Function Equals(str As String) As Boolean Implements IEquatable(Of String).Equals Return False End Function End Class "; var source = @" #nullable enable class Program { void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var vbComp = CreateVisualBasicCompilation(vbSource); var comp = CreateCompilation(source, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_CallableExplicitImplementation_MismatchedName() { var vbSource = @" Imports System Public Class C Implements IEquatable(Of String) Public Function MyEquals(str As String) As Boolean Implements IEquatable(Of String).Equals Return False End Function End Class "; var source = @" #nullable enable class Program { void M1(C c, string? s) { _ = c.MyEquals(s) ? s.ToString() : s.ToString(); // 1 } }"; var vbComp = CreateVisualBasicCompilation(vbSource); var comp = CreateCompilation(source, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_CallableExplicitImplementation_Override() { var vbSource = @" Imports System Public Class B Implements IEquatable(Of String) Public Overridable Function MyEquals(str As String) As Boolean Implements IEquatable(Of String).Equals Return False End Function End Class "; var source = @" #nullable enable class C : B { public override bool MyEquals(string? str) => false; void M1(C c, string? s) { _ = c.MyEquals(s) ? s.ToString() : s.ToString(); // 1 } }"; var vbComp = CreateVisualBasicCompilation(vbSource); var comp = CreateCompilation(source, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_CallableExplicitImplementation_ImplementsViaDerivedClass() { var vbSource = @" Imports System Interface IMyEquatable Function Equals(str As String) As Boolean End Interface Public Class B Implements IMyEquatable Public Shadows Function Equals(str As String) As Boolean Implements IMyEquatable.Equals Return False End Function End Class "; var source = @" #nullable enable using System; class C : B, IEquatable<string> { } class Program { void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var vbComp = CreateVisualBasicCompilation(vbSource); var comp = CreateCompilation(source, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (13,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ImplInNonImplementingBase() { var source = @" using System; #nullable enable class B { public bool Equals(string? s) => throw null!; } class C : B, IEquatable<string?> { static void M1(C c, string? s) { if (c.Equals(s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (21,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(21, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceEqualsMethod_NullableVariance_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" using System; #nullable enable class C : IEquatable<C> { public bool Equals(C? other) => throw null!; static void M1(C? c2) { C c1 = new C(); if (c1.Equals(c2)) { _ = c2.ToString(); } else { _ = c2.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = c2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(18, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceObjectEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" #nullable enable class C { static void M1(object? o) { if ("""".Equals(o)) { _ = o.ToString(); } else { _ = o.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,17): warning CS8602: Dereference of a possibly null reference. // _ = o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(13, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceObjectEqualsMethod_MaybeNullExprReferenceConversion_NonNullExpr_NoWarningWhenTrue() { var source = @" #nullable enable class C { static void M1(string? s) { if ("""".Equals((object?)s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceObjectEqualsMethod_ConditionalAccessExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" #nullable enable class C { object? F = default; static void M1(C? c) { C c1 = new C(); if (c1.Equals(c?.F)) { _ = c.F.ToString(); } else { _ = c.F.ToString(); // 1, 2 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (16,17): warning CS8602: Dereference of a possibly null reference. // _ = c.F.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(16, 17), // (16,17): warning CS8602: Dereference of a possibly null reference. // _ = c.F.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F").WithLocation(16, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void IEqualityComparerEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" using System.Collections.Generic; #nullable enable class C { static void M1(IEqualityComparer<string?> comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEqualityComparerEqualsMethod_Impl() { var source = @" using System.Collections.Generic; #nullable enable public class Comparer : IEqualityComparer<string> { public bool Equals(string? s1, string? s2) => false; public int GetHashCode(string s) => s.GetHashCode(); } class C { static void M(Comparer comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (22,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(22, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEqualityComparerEqualsMethod_ImplInBaseType() { var source = @" using System.Collections.Generic; #nullable enable public class Comparer : IEqualityComparer<string> { public bool Equals(string? s1, string? s2) => false; public int GetHashCode(string s) => s.GetHashCode(); } public class Comparer2 : Comparer { } class C { static void M(Comparer2 comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(24, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEqualityComparerEqualsMethod_ImplInNonImplementingClass() { var source = @" using System.Collections.Generic; #nullable enable public class Comparer { public bool Equals(string? s1, string? s2) => false; public int GetHashCode(string s) => s.GetHashCode(); } public class Comparer2 : Comparer, IEqualityComparer<string> { } class C { static void M(Comparer2 comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(24, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void EqualityComparerEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" using System.Collections.Generic; #nullable enable class C { static void M1(EqualityComparer<string?> comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void EqualityComparerEqualsMethod_IEqualityComparerMissing_MaybeNullExpr_NonNullExpr_Warns() { var source = @" using System.Collections.Generic; #nullable enable class C { static void M1(EqualityComparer<string?> comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); // 1 } else { _ = s.ToString(); // 2 } } }"; var comp = CreateCompilation(source); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_IEqualityComparer_T); comp.VerifyDiagnostics( // (11,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(11, 17), // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void IEqualityComparer_SubInterfaceEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" using System.Collections.Generic; #nullable enable interface MyEqualityComparer : IEqualityComparer<string?> { } class C { static void M1(MyEqualityComparer comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void IEqualityComparer_SubSubInterfaceEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" using System.Collections.Generic; #nullable enable interface MyEqualityComparer : IEqualityComparer<string?> { } interface MySubEqualityComparer : MyEqualityComparer { } class C { static void M1(MySubEqualityComparer comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(19, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void OverrideEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" #nullable enable class C { public override bool Equals(object? other) => throw null!; public override int GetHashCode() => throw null!; static void M1(C? c1) { C c2 = new C(); if (c2.Equals(c1)) { _ = c1.ToString(); } else { _ = c1.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(17, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void NotImplementingEqualsMethod_MaybeNullExpr_NonNullExpr_Warns() { var source = @" #nullable enable class C { public bool Equals(C? other) => throw null!; static void M1(C? c1) { C c2 = new C(); if (c2.Equals(c1)) { _ = c1.ToString(); // 1 } else { _ = c1.ToString(); // 2 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(12, 17), // (16,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(16, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void NotImplementingEqualsMethod_Virtual() { var source = @" #nullable enable class C { public virtual bool Equals(C? other) => throw null!; static void M1(C? c1) { C c2 = new C(); _ = c2.Equals(c1) ? c1.ToString() // 1 : c1.ToString(); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? c1.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : c1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(12, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void EqualsMethod_ImplInNonImplementingClass_Override() { var source = @" using System; #nullable enable class B { public virtual bool Equals(string? s) => throw null!; } class C : B, IEquatable<string> { public override bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void EqualsMethod_OverrideImplementsInterfaceMethod_MultipleOverride() { var source = @" #nullable enable using System; class A { public virtual bool Equals(string? s) => throw null!; } class B : A, IEquatable<string> { public override bool Equals(string? s) => throw null!; } class C : B { public override bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (23,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(23, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void EqualsMethod_OverrideImplementsInterfaceMethod_CastToBaseType() { var source = @" #nullable enable using System; class B { public virtual bool Equals(string? s) => throw null!; } class C : B, IEquatable<string> { public override bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = ((B)c).Equals(s) ? s.ToString() // 1 : s.ToString(); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 15)); } [Fact, WorkItem(42960, "https://github.com/dotnet/roslyn/issues/42960")] public void EqualsMethod_IncompleteBaseClause() { var source = @" class C : { void M(C? other) { if (Equals(other)) { other.ToString(); } if (this.Equals(other)) { other.ToString(); } } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (2,10): error CS1031: Type expected // class C : Diagnostic(ErrorCode.ERR_TypeExpected, "").WithLocation(2, 10), // (6,13): error CS0120: An object reference is required for the non-static field, method, or property 'object.Equals(object)' // if (Equals(other)) { other.ToString(); } Diagnostic(ErrorCode.ERR_ObjectRequired, "Equals").WithArguments("object.Equals(object)").WithLocation(6, 13), // (6,30): warning CS8602: Dereference of a possibly null reference. // if (Equals(other)) { other.ToString(); } Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "other").WithLocation(6, 30)); } [Fact, WorkItem(42960, "https://github.com/dotnet/roslyn/issues/42960")] public void EqualsMethod_ErrorBaseClause() { var source = @" class C : ERROR { void M(C? other) { if (Equals(other)) { other.ToString(); } if (this.Equals(other)) { other.ToString(); } } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (2,11): error CS0246: The type or namespace name 'ERROR' could not be found (are you missing a using directive or an assembly reference?) // class C : ERROR Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ERROR").WithArguments("ERROR").WithLocation(2, 11), // (6,13): error CS0120: An object reference is required for the non-static field, method, or property 'object.Equals(object)' // if (Equals(other)) { other.ToString(); } Diagnostic(ErrorCode.ERR_ObjectRequired, "Equals").WithArguments("object.Equals(object)").WithLocation(6, 13), // (6,30): warning CS8602: Dereference of a possibly null reference. // if (Equals(other)) { other.ToString(); } Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "other").WithLocation(6, 30)); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirective() { var source = @" class C { void M(object? o1) { object o2 = o1; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object o2 = o1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "o1").WithLocation(6, 21)); Assert.True(IsNullableAnalysisEnabled(comp, "C.M")); } [Theory] [InlineData("")] [InlineData("annotations")] [InlineData("warnings")] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirective_WithNullDisables(string directive) { var source = $@" #nullable disable {directive} class C {{ void M(object? o1) {{ object o2 = o1; }} }}"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(directive == "warnings" ? DiagnosticDescription.None : new[] { // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18) }); Assert.Equal(directive == "annotations", IsNullableAnalysisEnabled(comp, "C.M")); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableEnable() { ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableDirective("", // (7,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object o2 = o1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "o1").WithLocation(7, 21)); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableEnableAnnotations() { ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableDirective("annotations"); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableEnableWarnings() { ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableDirective("warnings", // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18)); } private static void ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableDirective(string directive, params DiagnosticDescription[] expectedDiagnostics) { var source = $@" #nullable enable {directive} class C {{ void M(object? o1) {{ object o2 = o1; }} }}"; var comp = CreateCompilation(source, options: WithNullableDisable()); comp.VerifyDiagnostics(expectedDiagnostics); Assert.Equal(directive != "annotations", IsNullableAnalysisEnabled(comp, "C.M")); } [Theory] [InlineData("disable")] [InlineData("disable annotations")] [InlineData("disable warnings")] [InlineData("restore")] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_WithNonInfluencingNullableDirectives(string directive) { var source = $@" #nullable {directive} class C {{ void M(object? o1) {{ object o2 = o1; }} }}"; var comp = CreateCompilation(source, options: WithNullableDisable()); comp.VerifyDiagnostics( // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18)); Assert.False(IsNullableAnalysisEnabled(comp, "C.M")); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles_NullableEnable() { ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles("", // (4,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 18), // (7,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object o4 = o3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "o3").WithLocation(7, 21)); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles_NullableEnableAnnotations() { ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles("annotations", // (4,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 18)); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles_NullableEnableWarnings() { ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles("warnings", // (4,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 18), // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o3) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18)); } private static void ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles(string directive, params DiagnosticDescription[] expectedDiagnostics) { var source1 = @" class C { void M(object? o1) { object o2 = o1; } }"; var source2 = $@" #nullable enable {directive} class D {{ void M(object? o3) {{ object o4 = o3; }} }}"; var comp = CreateCompilation(new[] { source1, source2 }, options: WithNullableDisable()); comp.VerifyDiagnostics(expectedDiagnostics); Assert.NotEqual(directive == "annotations", IsNullableAnalysisEnabled(comp, "D.M")); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_MultipleDirectivesSingleFile() { var source = @" #nullable disable class C { void M(object? o1) { #nullable enable object o2 = o1; #nullable restore } }"; var comp = CreateCompilation(source, options: WithNullableDisable()); comp.VerifyDiagnostics( // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18), // (8,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object o2 = o1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "o1").WithLocation(8, 21)); Assert.True(IsNullableAnalysisEnabled(comp, "C.M")); } [Theory] // 2 states * 3 states * 3 states = 18 combinations [InlineData("locationNonNull", "valueNonNull", "comparandNonNull", true)] [InlineData("locationNonNull", "valueNonNull", "comparandMaybeNull", true)] [InlineData("locationNonNull", "valueMaybeNull", "comparandNonNull", false)] [InlineData("locationNonNull", "valueMaybeNull", "comparandMaybeNull", false)] [InlineData("locationNonNull", "valueMaybeNull", "null", false)] [InlineData("locationNonNull", "null", "comparandMaybeNull", false)] [InlineData("locationMaybeNull", "valueNonNull", "comparandNonNull", false)] [InlineData("locationMaybeNull", "valueNonNull", "comparandMaybeNull", false)] [InlineData("locationMaybeNull", "valueNonNull", "null", true)] [InlineData("locationMaybeNull", "valueMaybeNull", "comparandNonNull", false)] [InlineData("locationMaybeNull", "valueMaybeNull", "comparandMaybeNull", false)] [InlineData("locationMaybeNull", "valueMaybeNull", "null", false)] [InlineData("locationMaybeNull", "null", "comparandNonNull", false)] [InlineData("locationMaybeNull", "null", "comparandMaybeNull", false)] [InlineData("locationMaybeNull", "null", "null", false)] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchange_LocationNullState(string location, string value, string comparand, bool isLocationNonNullAfterCall) { var source = $@" #pragma warning disable 0436 using System.Threading; using System.Diagnostics.CodeAnalysis; namespace System.Threading {{ public static class Interlocked {{ public static object? CompareExchange([NotNullIfNotNull(""value"")] ref object? location, object? value, object? comparand) {{ return location; }} }} }} class C {{ // locationNonNull is annotated, but its flow state is non-null void M(object? locationNonNull, object? locationMaybeNull, object comparandNonNull, object? comparandMaybeNull, object valueNonNull, object? valueMaybeNull) {{ locationNonNull = new object(); Interlocked.CompareExchange(ref {location}, {value}, {comparand}); _ = {location}.ToString(); }} }} "; var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (19,13): warning CS8602: Dereference of a possibly null reference. // _ = {location}.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, location).WithLocation(19, 13) }); source = $@" #pragma warning disable 0436 using System.Threading; namespace System.Threading {{ public static class Interlocked {{ public static T CompareExchange<T>(ref T location, T value, T comparand) where T : class? {{ return location; }} }} }} class C {{ // locationNonNull is annotated, but its flow state is non-null void M<T>(T? locationNonNull, T? locationMaybeNull, T comparandNonNull, T? comparandMaybeNull, T valueNonNull, T? valueMaybeNull) where T : class, new() {{ locationNonNull = new T(); Interlocked.CompareExchange(ref {location}, {value}, {comparand}); _ = {location}.ToString(); }} }} "; comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (19,13): warning CS8602: Dereference of a possibly null reference. // _ = {location}.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, location).WithLocation(19, 13) }); source = $@" class C {{ // locationNonNull is annotated, but its flow state is non-null void M(object? locationNonNull, object? locationMaybeNull, object comparandNonNull, object? comparandMaybeNull, object valueNonNull, object? valueMaybeNull) {{ locationNonNull = new object(); if ({location} == {comparand}) {{ {location} = {value}; }} _ = {location}.ToString(); }} }} "; comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (12,13): warning CS8602: Dereference of a possibly null reference. // _ = {location}.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, location).WithLocation(12, 13) }); } // This test should be merged back into CompareExchange_LocationNullState when the issue with inference with null is resolved // Currently differs by a diagnostic [Theory] [InlineData("locationNonNull", "null", "comparandNonNull", false)] public void CompareExchange_LocationNullState_2(string location, string value, string comparand, bool isLocationNonNullAfterCall) { var source = $@" #pragma warning disable 0436 using System.Threading; using System.Diagnostics.CodeAnalysis; namespace System.Threading {{ public static class Interlocked {{ public static object? CompareExchange([NotNullIfNotNull(""value"")] ref object? location, object? value, object? comparand) {{ return location; }} }} }} class C {{ // locationNonNull is annotated, but its flow state is non-null void M(object? locationNonNull, object? locationMaybeNull, object comparandNonNull, object? comparandMaybeNull, object valueNonNull, object? valueMaybeNull) {{ locationNonNull = new object(); Interlocked.CompareExchange(ref {location}, {value}, {comparand}); _ = {location}.ToString(); }} }} "; var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (19,13): warning CS8602: Dereference of a possibly null reference. // _ = {location}.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, location).WithLocation(19, 13) }); source = $@" #pragma warning disable 0436 using System.Threading; namespace System.Threading {{ public static class Interlocked {{ public static T CompareExchange<T>(ref T location, T value, T comparand) where T : class? {{ return location; }} }} }} class C {{ // locationNonNull is annotated, but its flow state is non-null void M<T>(T? locationNonNull, T? locationMaybeNull, T comparandNonNull, T? comparandMaybeNull, T valueNonNull, T? valueMaybeNull) where T : class, new() {{ locationNonNull = new T(); Interlocked.CompareExchange(ref {location}, {value}, {comparand}); _ = {location}.ToString(); }} }} "; comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (18,58): warning CS8625: Cannot convert null literal to non-nullable reference type. // Interlocked.CompareExchange(ref locationNonNull, null, comparandNonNull); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(18, 58), // Unexpected warning, due to method type inference with null https://github.com/dotnet/roslyn/issues/43536 // (19,13): warning CS8602: Dereference of a possibly null reference. // _ = locationNonNull.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "locationNonNull").WithLocation(19, 13) }); source = $@" class C {{ // locationNonNull is annotated, but its flow state is non-null void M(object? locationNonNull, object? locationMaybeNull, object comparandNonNull, object? comparandMaybeNull, object valueNonNull, object? valueMaybeNull) {{ locationNonNull = new object(); if ({location} == {comparand}) {{ {location} = {value}; }} _ = {location}.ToString(); }} }} "; comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (12,13): warning CS8602: Dereference of a possibly null reference. // _ = {location}.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, location).WithLocation(12, 13) }); } // This test should be merged back into CompareExchange_LocationNullState when the issue with inference with null is resolved // Currently differs by a diagnostic [Theory] [InlineData("locationNonNull", "null", "null", false)] public void CompareExchange_LocationNullState_3(string location, string value, string comparand, bool isLocationNonNullAfterCall) { var source = $@" #pragma warning disable 0436 using System.Threading; using System.Diagnostics.CodeAnalysis; namespace System.Threading {{ public static class Interlocked {{ public static object? CompareExchange([NotNullIfNotNull(""value"")] ref object? location, object? value, object? comparand) {{ return location; }} }} }} class C {{ // locationNonNull is annotated, but its flow state is non-null void M(object? locationNonNull, object? locationMaybeNull, object comparandNonNull, object? comparandMaybeNull, object valueNonNull, object? valueMaybeNull) {{ locationNonNull = new object(); Interlocked.CompareExchange(ref {location}, {value}, {comparand}); _ = {location}.ToString(); }} }} "; var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (19,13): warning CS8602: Dereference of a possibly null reference. // _ = {location}.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, location).WithLocation(19, 13) }); source = $@" #pragma warning disable 0436 using System.Threading; namespace System.Threading {{ public static class Interlocked {{ public static T CompareExchange<T>(ref T location, T value, T comparand) where T : class? {{ return location; }} }} }} class C {{ // locationNonNull is annotated, but its flow state is non-null void M<T>(T? locationNonNull, T? locationMaybeNull, T comparandNonNull, T? comparandMaybeNull, T valueNonNull, T? valueMaybeNull) where T : class, new() {{ locationNonNull = new T(); Interlocked.CompareExchange(ref {location}, {value}, {comparand}); _ = {location}.ToString(); }} }} "; comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (18,58): warning CS8625: Cannot convert null literal to non-nullable reference type. // Interlocked.CompareExchange(ref locationNonNull, null, null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(18, 58), // Unexpected warning, due to method type inference with null https://github.com/dotnet/roslyn/issues/43536 // (18,64): warning CS8625: Cannot convert null literal to non-nullable reference type. // Interlocked.CompareExchange(ref locationNonNull, null, null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(18, 64), // (19,13): warning CS8602: Dereference of a possibly null reference. // _ = locationNonNull.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "locationNonNull").WithLocation(19, 13) }); source = $@" class C {{ // locationNonNull is annotated, but its flow state is non-null void M(object? locationNonNull, object? locationMaybeNull, object comparandNonNull, object? comparandMaybeNull, object valueNonNull, object? valueMaybeNull) {{ locationNonNull = new object(); if ({location} == {comparand}) {{ {location} = {value}; }} _ = {location}.ToString(); }} }} "; comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (12,13): warning CS8602: Dereference of a possibly null reference. // _ = {location}.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, location).WithLocation(12, 13) }); } // This test should be merged back into CompareExchange_LocationNullState when the issue with inference with null is resolved // Currently differs by a diagnostic [Theory] [InlineData("locationNonNull", "valueNonNull", "null", true)] public void CompareExchange_LocationNullState_4(string location, string value, string comparand, bool isLocationNonNullAfterCall) { var source = $@" #pragma warning disable 0436 using System.Threading; using System.Diagnostics.CodeAnalysis; namespace System.Threading {{ public static class Interlocked {{ public static object? CompareExchange([NotNullIfNotNull(""value"")] ref object? location, object? value, object? comparand) {{ return location; }} }} }} class C {{ // locationNonNull is annotated, but its flow state is non-null void M(object? locationNonNull, object? locationMaybeNull, object comparandNonNull, object? comparandMaybeNull, object valueNonNull, object? valueMaybeNull) {{ locationNonNull = new object(); Interlocked.CompareExchange(ref {location}, {value}, {comparand}); _ = {location}.ToString(); }} }} "; var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (19,13): warning CS8602: Dereference of a possibly null reference. // _ = {location}.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, location).WithLocation(19, 13) }); source = $@" #pragma warning disable 0436 using System.Threading; namespace System.Threading {{ public static class Interlocked {{ public static T CompareExchange<T>(ref T location, T value, T comparand) where T : class? {{ return location; }} }} }} class C {{ // locationNonNull is annotated, but its flow state is non-null void M<T>(T? locationNonNull, T? locationMaybeNull, T comparandNonNull, T? comparandMaybeNull, T valueNonNull, T? valueMaybeNull) where T : class, new() {{ locationNonNull = new T(); Interlocked.CompareExchange(ref {location}, {value}, {comparand}); _ = {location}.ToString(); }} }} "; comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,72): warning CS8625: Cannot convert null literal to non-nullable reference type. // Interlocked.CompareExchange(ref locationNonNull, valueNonNull, null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(18, 72) // Unexpected warning, due to method type inference with null https://github.com/dotnet/roslyn/issues/43536 ); source = $@" class C {{ // locationNonNull is annotated, but its flow state is non-null void M(object? locationNonNull, object? locationMaybeNull, object comparandNonNull, object? comparandMaybeNull, object valueNonNull, object? valueMaybeNull) {{ locationNonNull = new object(); if ({location} == {comparand}) {{ {location} = {value}; }} _ = {location}.ToString(); }} }} "; comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (12,13): warning CS8602: Dereference of a possibly null reference. // _ = {location}.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, location).WithLocation(12, 13) }); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchange_NoLocationSlot() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static object? CompareExchange(ref object? location, object? value, object? comparand) { return location; } } } class C { void M() { var arr = new object?[1]; Interlocked.CompareExchange(ref arr[0], new object(), null); _ = arr[0].ToString(); // 1 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,13): warning CS8602: Dereference of a possibly null reference. // _ = arr[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "arr[0]").WithLocation(18, 13)); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchangeT_NotAnnotatedLocation_MaybeNullComparand() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static T CompareExchange<T>(ref T location, T value, T comparand) where T : class? { return location; } } } class C { void M<T>(T location, T value, T? comparand) where T : class { Interlocked.CompareExchange(ref location, value, comparand); // no warning because `location` will be assigned a not-null from `value` _ = location.ToString(); } void M2<T>(T location, T? value, T? comparand) where T : class { Interlocked.CompareExchange(ref location, value, comparand); // 1 _ = location.ToString(); // 2 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (21,41): warning CS8600: Converting null literal or possible null value to non-nullable type. // Interlocked.CompareExchange(ref location, value, comparand); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "location").WithLocation(21, 41), // (22,13): warning CS8602: Dereference of a possibly null reference. // _ = location.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "location").WithLocation(22, 13)); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchangeT_NotAnnotatedLocation_NonNullComparand() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static T CompareExchange<T>(ref T location, T value, T comparand) where T : class? { return location; } } } class C { void M<T>(T location, T value, T comparand) where T : class { Interlocked.CompareExchange(ref location, value, comparand); _ = location.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchangeT_NotAnnotatedLocation_NonNullReturnValue() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static T CompareExchange<T>(ref T location, T value, T comparand) where T : class? { return location; } } } class C { void M<T>(T location, T value, T comparand) where T : class { var result = Interlocked.CompareExchange(ref location, value, comparand); _ = location.ToString(); _ = result.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchangeT_NonNullLocation_MaybeNullReturnValue() { var source = @" #pragma warning disable 0436 using System.Threading; using System.Diagnostics.CodeAnalysis; namespace System.Threading { public static class Interlocked { public static T CompareExchange<T>([NotNullIfNotNull(""value"")] ref T location, T value, T comparand) where T : class? { return location; } } } class C { // location is annotated, but its flow state is non-null void M<T>(T? location, T value, T comparand) where T : class, new() { location = new T(); var result = Interlocked.CompareExchange(ref location, value, comparand); _ = location.ToString(); _ = result.ToString(); location = null; result = Interlocked.CompareExchange(ref location, value, null); _ = location.ToString(); _ = result.ToString(); // 1 } } "; // Note: the return value of CompareExchange is the value in `location` before the call. // Therefore it might make sense to give the return value a flow state equal to the flow state of `location` before the call. // Tracked by https://github.com/dotnet/roslyn/issues/36911 var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (25,13): warning CS8602: Dereference of a possibly null reference. // _ = result.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result").WithLocation(25, 13)); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchangeT_MaybeNullLocation_MaybeNullReturnValue() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static T CompareExchange<T>(ref T location, T value, T comparand) where T : class? { return location; } } } class C { void M<T>(T? location, T value, T comparand) where T : class { var result = Interlocked.CompareExchange(ref location, value, comparand); _ = location.ToString(); // 1 _ = result.ToString(); // 2 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,13): warning CS8602: Dereference of a possibly null reference. // _ = location.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "location").WithLocation(17, 13), // (18,13): warning CS8602: Dereference of a possibly null reference. // _ = result.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result").WithLocation(18, 13)); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchange_UnrecognizedOverload() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static object? CompareExchange(ref object? location, object? value) { return location; } public static object? CompareExchange(ref object? location, object? value, object? comparand) { return location; } } } class C { void M() { object? location = null; Interlocked.CompareExchange(ref location, new object()); _ = location.ToString(); // 1 Interlocked.CompareExchange(ref location, new object(), null); _ = location.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,13): warning CS8602: Dereference of a possibly null reference. // _ = location.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "location").WithLocation(19, 13)); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchangeT_UnrecognizedOverload() { var source = @" #pragma warning disable 0436 using System.Threading; using System.Diagnostics.CodeAnalysis; namespace System.Threading { public static class Interlocked { public static T CompareExchange<T>([NotNullIfNotNull(""value"")] ref T location, T value) where T : class? { return location; } public static T CompareExchange<T>([NotNullIfNotNull(""value"")] ref T location, T value, T comparand) where T : class? { return location; } } } class C { void M() { string? location = null; Interlocked.CompareExchange(ref location, ""hello""); _ = location.ToString(); location = null; Interlocked.CompareExchange(ref location, ""hello"", null); _ = location.ToString(); location = string.Empty; Interlocked.CompareExchange(ref location, ""hello"", null); // 1 _ = location.ToString(); } } "; // We expect no warning at all, but in the last scenario the issue with `null` literals in method type inference becomes visible // Tracked by https://github.com/dotnet/roslyn/issues/43536 var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (27,60): warning CS8625: Cannot convert null literal to non-nullable reference type. // Interlocked.CompareExchange(ref location, "hello", null); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(27, 60) ); } [Fact] [WorkItem(38010, "https://github.com/dotnet/roslyn/issues/38010")] public void CompareExchange_BadArgCount() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static object? CompareExchange(ref object? location, object? value, object? comparand) { return location; } } } class C { void M() { string? location = null; Interlocked.CompareExchange(ref location, new object()); // 1 _ = location.ToString(); // 2 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,21): error CS7036: There is no argument given that corresponds to the required formal parameter 'comparand' of 'Interlocked.CompareExchange(ref object?, object?, object?)' // Interlocked.CompareExchange(ref location, new object()); // 1 Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CompareExchange").WithArguments("comparand", "System.Threading.Interlocked.CompareExchange(ref object?, object?, object?)").WithLocation(17, 21), // (18,13): warning CS8602: Dereference of a possibly null reference. // _ = location.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "location").WithLocation(18, 13)); } [Fact] [WorkItem(46673, "https://github.com/dotnet/roslyn/issues/46673")] public void CompareExchange_NamedArguments() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static object? CompareExchange(ref object? location, object? value, object? comparand) { return location; } } } class C { void M() { object location1 = """"; Interlocked.CompareExchange(ref location1, comparand: """", value: null); // 1 object location2 = """"; Interlocked.CompareExchange(ref location2, comparand: null, value: """"); object location3 = """"; Interlocked.CompareExchange(comparand: """", value: null, location: ref location3); // 2 object location4 = """"; Interlocked.CompareExchange(comparand: null, value: """", location: ref location4); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,41): warning CS8600: Converting null literal or possible null value to non-nullable type. // Interlocked.CompareExchange(ref location1, comparand: "", value: null); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "location1").WithLocation(17, 41), // (23,79): warning CS8600: Converting null literal or possible null value to non-nullable type. // Interlocked.CompareExchange(comparand: "", value: null, location: ref location3); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "location3").WithLocation(23, 79)); } [Fact] [WorkItem(46673, "https://github.com/dotnet/roslyn/issues/46673")] public void CompareExchange_NamedArgumentsWithOptionalParameters() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { class Interlocked { public static T CompareExchange<T>(ref T location1, T value, T comparand = default) where T : class => value; } } class C { static void F(object target, object value) { Interlocked.CompareExchange(value: value, location1: ref target); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,84): warning CS8625: Cannot convert null literal to non-nullable reference type. // public static T CompareExchange<T>(ref T location1, T value, T comparand = default) where T : class => value; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(8, 84), // (15,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'Interlocked.CompareExchange<T>(ref T, T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // Interlocked.CompareExchange(value: value, location1: ref target); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Interlocked.CompareExchange").WithArguments("System.Threading.Interlocked.CompareExchange<T>(ref T, T, T)", "T", "object?").WithLocation(15, 9)); } [Fact] [WorkItem(37187, "https://github.com/dotnet/roslyn/issues/37187")] public void IEquatableContravariantNullability() { var def = @" using System; namespace System { public interface IEquatable<T> { bool Equals(T other); } } public class A : IEquatable<A?> { public bool Equals(A? a) => false; public static void M<T>(Span<T> s) where T : IEquatable<T>? { s[0]?.Equals(null); s[0]?.Equals(s[1]); } } public class B : IEquatable<(B?, B?)> { public bool Equals((B?, B?) l) => false; } "; var spanRef = CreateCompilation(SpanSource, options: TestOptions.UnsafeReleaseDll) .EmitToImageReference(); var comp = CreateCompilation(def + @" class C { static void Main() { var x = new Span<A?>(); var y = new Span<A>(); A.M(x); A.M(y); IEquatable<A?> i1 = new A(); IEquatable<A> i2 = i1; IEquatable<A> i3 = new A(); IEquatable<A?> i4 = i3; // warn _ = i4; IEquatable<(B?, B?)> i5 = new B(); IEquatable<(B, B)> i6 = i5; IEquatable<(B, B)> i7 = new B(); IEquatable<(B?, B?)> i8 = i7; // warn _ = i8; } }", new[] { spanRef }, options: WithNullableEnable().WithSpecificDiagnosticOptions("CS0436", ReportDiagnostic.Suppress)); comp.VerifyDiagnostics( // (34,29): warning CS8619: Nullability of reference types in value of type 'IEquatable<A>' doesn't match target type 'IEquatable<A?>'. // IEquatable<A?> i4 = i3; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i3").WithArguments("System.IEquatable<A>", "System.IEquatable<A?>").WithLocation(41, 29), // (40,35): warning CS8619: Nullability of reference types in value of type 'IEquatable<(B, B)>' doesn't match target type 'IEquatable<(B?, B?)>'. // IEquatable<(B?, B?)> i8 = i7; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i7").WithArguments("System.IEquatable<(B, B)>", "System.IEquatable<(B?, B?)>").WithLocation(47, 35) ); // Test with non-wellknown type var defComp = CreateCompilation(def, references: new[] { spanRef }, options: WithNullableEnable().WithSpecificDiagnosticOptions("CS0436", ReportDiagnostic.Suppress)); defComp.VerifyDiagnostics(); var useComp = CreateCompilation(@" using System; public interface IEquatable<T> { bool Equals(T other); } class C { static void Main() { var x = new Span<A?>(); var y = new Span<A>(); A.M(x); A.M(y); } }", references: new[] { spanRef, defComp.ToMetadataReference() }, options: WithNullableEnable()); useComp.VerifyDiagnostics(); } [Fact] public void IEquatableNotContravariantExceptNullability() { var src = @" using System; class A : IEquatable<A?> { public bool Equals(A? a) => false; } class B : A {} class C { static void Main() { var x = new Span<B?>(); var y = new Span<B>(); M(x); M(y); } static void M<T>(Span<T> s) where T : IEquatable<T>? { } }"; var comp = CreateCompilationWithSpan(src + @" namespace System { public interface IEquatable<T> { bool Equals(T other); } } ", options: WithNullableEnable().WithSpecificDiagnosticOptions("CS0436", ReportDiagnostic.Suppress)); comp.VerifyDiagnostics( // (25,9): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(Span<T>)'. There is no implicit reference conversion from 'B' to 'System.IEquatable<B>'. // M(x); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(System.Span<T>)", "System.IEquatable<B>", "T", "B").WithLocation(18, 9), // (26,9): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(Span<T>)'. There is no implicit reference conversion from 'B' to 'System.IEquatable<B>'. // M(y); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(System.Span<T>)", "System.IEquatable<B>", "T", "B").WithLocation(19, 9)); // If IEquatable is actually marked contravariant this is fine comp = CreateCompilationWithSpan(src + @" namespace System { public interface IEquatable<in T> { bool Equals(T other); } } ", options: WithNullableEnable().WithSpecificDiagnosticOptions("CS0436", ReportDiagnostic.Suppress)); comp.VerifyDiagnostics(); } [Fact] public void IEquatableInWrongNamespace() { var comp = CreateCompilation(@" public interface IEquatable<T> { bool Equals(T other); } public class A : IEquatable<A?> { public bool Equals(A? a) => false; public static void Main() { IEquatable<A?> i1 = new A(); IEquatable<A> i2 = i1; IEquatable<A?> i3 = i2; _ = i3; } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,28): warning CS8619: Nullability of reference types in value of type 'IEquatable<A?>' doesn't match target type 'IEquatable<A>'. // IEquatable<A> i2 = i1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i1").WithArguments("IEquatable<A?>", "IEquatable<A>").WithLocation(14, 28), // (15,29): warning CS8619: Nullability of reference types in value of type 'IEquatable<A>' doesn't match target type 'IEquatable<A?>'. // IEquatable<A?> i3 = i2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i2").WithArguments("IEquatable<A>", "IEquatable<A?>").WithLocation(15, 29)); } [Fact] public void IEquatableNullableVarianceOutParameters() { var comp = CreateCompilation(@" using System; class C { void M<T>(IEquatable<T?> input, out IEquatable<T> output) where T: class { output = input; } } namespace System { public interface IEquatable<T> { bool Equals(T other); } } ", options: WithNullableEnable().WithSpecificDiagnosticOptions("CS0436", ReportDiagnostic.Suppress)); comp.VerifyDiagnostics(); } [Fact] [WorkItem(37269, "https://github.com/dotnet/roslyn/issues/37269")] public void TypeParameterReturnType_01() { var source = @"using System; using System.Threading.Tasks; static class ResultExtensions { static async Task<Result<TResult, B>> MapAsync<A, B, TResult>( this Result<A, B> result, Func<A, Task<TResult>> map) { return await result.Match( async a => FromA<TResult>(await map(a)), b => Task.FromResult(FromB<TResult, B>(b))); } static Result<A, B> FromA<A, B>(A value) => throw null!; static Result<A, B> FromB<A, B>(B value) => throw null!; } class Result<A, B> { public TResult Match<TResult>(Func<A, TResult> a, Func<B, TResult> b) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,24): error CS0305: Using the generic method 'ResultExtensions.FromA<A, B>(A)' requires 2 type arguments // async a => FromA<TResult>(await map(a)), Diagnostic(ErrorCode.ERR_BadArity, "FromA<TResult>").WithArguments("ResultExtensions.FromA<A, B>(A)", "method", "2").WithLocation(10, 24)); } [Fact] public void TypeParameterReturnType_02() { var source = @"using System; using System.Threading.Tasks; static class ResultExtensions { static async Task<Result<TResult, B>> MapAsync<A, B, TResult>( this Result<A, B> result, Func<A, Task<TResult>> map) { return await result.Match( async a => FromA<TResult, B>(await map(a)), b => Task.FromResult(FromB<TResult, B>(b))); } static Result<A, B> FromA<A, B>(A value) => throw null!; static Result<A, B> FromB<A, B>(B value) => throw null!; } class Result<A, B> { public TResult Match<TResult>(Func<A, TResult> a, Func<B, TResult> b) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // Use VerifyEmitDiagnostics() to test assertions in CodeGenerator.EmitCallExpression. comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(36052, "https://github.com/dotnet/roslyn/issues/36052")] public void UnassignedLocal() { var source = @" class Program : Base { void M0() { string? x0a; x0a/*T:string?*/.ToString(); // 1 string x0b; x0b/*T:string!*/.ToString(); } void M1<T>() { T x1; x1/*T:T*/.ToString(); // 2 } void M2(object? o) { if (o is string x2a) {} x2a/*T:string!*/.ToString(); if (T() && o is var x2b) {} x2b/*T:object?*/.ToString(); // 3 } void M3() { do { } while (T() && M<string?>(out string? s3) && s3/*T:string?*/.Length > 1); // 4 do { } while (T() && M<string>(out string s3) && s3/*T:string!*/.Length > 1); } void M4() { while (T() || M<string?>(out string? s4)) { s4/*T:string?*/.ToString(); // 5 } while (T() || M<string>(out string s4)) { s4/*T:string!*/.ToString(); } } void M5() { for (string? s1; T(); ) s1/*T:string?*/.ToString(); // 6 for (string s1; T(); ) s1/*T:string!*/.ToString(); } Program(int x) : base((T() || M<string?>(out string? s6)) && s6/*T:string?*/.Length > 1) {} // 7 Program(long x) : base((T() || M<string>(out string s7)) && s7/*T:string!*/.Length > 1) {} static bool T() => true; static bool M<T>(out T x) { x = default(T)!; return true; } } class Base { public Base(bool b) {} } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_UseDefViolation).Verify( // (7,9): warning CS8602: Dereference of a possibly null reference. // x0a.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0a").WithLocation(7, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(14, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // x2b.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2b").WithLocation(21, 9), // (27,55): warning CS8602: Dereference of a possibly null reference. // } while (T() && M<string?>(out string? s3) && s3.Length > 1); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(27, 55), // (36,13): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(36, 13), // (45,33): warning CS8602: Dereference of a possibly null reference. // for (string? s1; T(); ) s1.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(45, 33), // (48,66): warning CS8602: Dereference of a possibly null reference. // Program(int x) : base((T() || M<string?>(out string? s6)) && s6.Length > 1) {} // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(48, 66)); } [Fact] [WorkItem(38183, "https://github.com/dotnet/roslyn/issues/38183")] public void UnboundGenericTypeReference_StructConstraint() { var source = @"class Program { static void Main(string[] args) { F<Boxed<int>>(); } static void F<T>() { if (typeof(T).GetGenericTypeDefinition() == typeof(Boxed<>)) { } } } class Boxed<T> where T : struct { public bool Equals(Boxed<T>? other) => false; public override bool Equals(object? obj) => Equals(obj as Boxed<T>); public override int GetHashCode() => 0; }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); CompileAndVerify(comp, expectedOutput: ""); } [Fact] [WorkItem(38183, "https://github.com/dotnet/roslyn/issues/38183")] public void UnboundGenericTypeReference_ClassConstraint() { var source = @"class Program { static void Main(string[] args) { F<Boxed<object>>(); } static void F<T>() { if (typeof(T).GetGenericTypeDefinition() == typeof(Boxed<>)) { } } } class Boxed<T> where T : class { public bool Equals(Boxed<T>? other) => false; public override bool Equals(object? obj) => Equals(obj as Boxed<T>); public override int GetHashCode() => 0; }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); CompileAndVerify(comp, expectedOutput: ""); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_Invariant_ObliviousVersusUnannotated() { var source = @" #nullable enable warnings static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I<T> source) => throw null!; } class C : I<object>, I2 {} interface I<T> {} #nullable enable annotations interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("c.Extension()", invocation.ToString()); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_Invariant_ObliviousVersusAnnotated() { var source = @" #nullable enable static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I<T> source) => throw null!; } class C : I<object?>, I2 {} interface I<T> {} #nullable disable interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 9) ); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object?>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_Invariant_ObliviousVersusAnnotated_ReverseOrder() { var source = @" #nullable enable static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I<T> source) => throw null!; } class C : I2, I<object?> {} interface I<T> {} #nullable disable interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 9) ); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object?>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_Invariant_AnnotatedVersusUnannotated() { var source = @" #nullable enable static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I<T> source) => throw null!; } class C : I<object?>, I2 {} interface I<T> {} interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,7): warning CS8645: 'I<object>' is already listed in the interface list on type 'C' with different nullability of reference types. // class C : I<object?>, I2 {} Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C").WithArguments("I<object>", "C").WithLocation(13, 7) ); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("c.Extension()", invocation.ToString()); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_Invariant_UnannotatedVersusAnnotated() { var source = @" #nullable enable static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I<T> source) => throw null!; } class C : I<object>, I2 {} interface I<T> {} interface I2 : I<object?> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,7): warning CS8645: 'I<object?>' is already listed in the interface list on type 'C' with different nullability of reference types. // class C : I<object>, I2 {} Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C").WithArguments("I<object?>", "C").WithLocation(13, 7) ); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("c.Extension()", invocation.ToString()); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_LowerBound_Contravariant() { var source = @" #nullable enable warnings static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I3<I<T>> source) => throw null!; } class C : I3<I<object>>, I2 {} interface I<T> {} interface I3<in T> {} #nullable enable annotations interface I2 : I3<I<object>> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("c.Extension()", invocation.ToString()); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_LowerBound_Variant() { var source = @" #nullable enable warnings static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I3<I<T>> source) => throw null!; } class C : I3<I<object>>, I2 {} interface I<T> {} interface I3<out T> {} #nullable enable annotations interface I2 : I3<I<object>> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("c.Extension()", invocation.ToString()); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_UpperBound_ObliviousVersusUnannotated() { var source = @" #nullable enable warnings static class P { static void M(ICon<I<object>> c) { var x = c.Extension(""""); x.ToString(); } public static T Extension<T>(this ICon<I3<T>> source, T other) where T : class => throw null!; } interface ICon<in T> where T : class {} interface I<T> where T : class {} interface I3<T> : I<T>, I2<T> where T : class {} #nullable enable annotations interface I2<T> : I<T> where T : class {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_UpperBound_AnnotatedVersusUnannotated() { var source = @" #nullable enable static class P { static void M(ICon<I<object>> c) { var x = c.Extension(""""); x.ToString(); } public static T Extension<T>(this ICon<I3<T>> source, T other) where T : class => throw null!; } interface ICon<in T> where T : class {} interface I<T> where T : class? {} interface I3<T> : I<T?>, I2<T> where T : class {} interface I2<T> : I<T> where T : class {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,11): warning CS8645: 'I<T>' is already listed in the interface list on type 'I3<T>' with different nullability of reference types. // interface I3<T> : I<T?>, I2<T> where T : class {} Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I3").WithArguments("I<T>", "I3<T>").WithLocation(15, 11) ); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38427, "https://github.com/dotnet/roslyn/issues/38427")] public void MethodTypeInference_ImplementedInterfaces_Indirect_TupleDifferences() { var source = @" static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<(int a, int b)>, I2 {} interface I<T> {} interface I2 : I<(int c, int d)> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,11): error CS1061: 'C' does not contain a definition for 'Extension' and no accessible extension method 'Extension' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // c.Extension(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Extension").WithArguments("C", "Extension").WithLocation(6, 11), // (12,7): error CS8140: 'I<(int c, int d)>' is already listed in the interface list on type 'C' with different tuple element names, as 'I<(int a, int b)>'. // class C : I<(int a, int b)>, I2 {} Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I<(int c, int d)>", "I<(int a, int b)>", "C").WithLocation(12, 7) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_Object() { var source = @" static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<object>, I2 {} interface I<T> {} interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Direct() { var source = @" #nullable enable warnings static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<object>, #nullable enable annotations I<object> { } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,5): warning CS8645: 'I<object>' is already listed in the interface list on type 'C' with different nullability of reference types. // I<object> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I<object>").WithArguments("I<object>", "C").WithLocation(15, 5) ); var interfaces = comp.GetTypeByMetadataName("C").InterfacesNoUseSiteDiagnostics(); Assert.Equal(new[] { "I<object>", "I<object!>" }, interfaces.Select(i => i.ToDisplayString(TypeWithAnnotations.TestDisplayFormat))); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void ImplementedInterfaces_Partials_ObliviousVersusUnannotated() { var source = @" partial class C : I<object> { } #nullable enable partial class C : I<object> { } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void ImplementedInterfaces_Partials_AnnotatedVersusUnannotated() { var source = @" #nullable enable partial class C : I<object?> { } partial class C : I<object> { } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,15): warning CS8645: 'I<object>' is already listed in the interface list on type 'C' with different nullability of reference types. // partial class C : I<object?> { } Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C").WithArguments("I<object>", "C").WithLocation(3, 15) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Direct_AnnotatedVersusUnannotated() { var source = @" #nullable enable static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<object>, I<object?> { } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,7): warning CS8645: 'I<object?>' is already listed in the interface list on type 'C' with different nullability of reference types. // class C : I<object>, I<object?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C").WithArguments("I<object?>", "C").WithLocation(13, 7) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Direct_NullabilityAndTupleNameDifferences() { var source = @" #nullable enable static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<(object a, object b)>, I<(object? c, object? d)> { } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,11): error CS1061: 'C' does not contain a definition for 'Extension' and no accessible extension method 'Extension' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // c.Extension(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Extension").WithArguments("C", "Extension").WithLocation(7, 11), // (13,7): error CS8140: 'I<(object? c, object? d)>' is already listed in the interface list on type 'C' with different tuple element names, as 'I<(object a, object b)>'. // class C : I<(object a, object b)>, I<(object? c, object? d)> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I<(object? c, object? d)>", "I<(object a, object b)>", "C").WithLocation(13, 7) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Direct_Object() { var source = @" static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null; } class C : I<object>, I<object> {} interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,22): error CS0528: 'I<object>' is already listed in interface list // class C : I<object>, I<object> {} Diagnostic(ErrorCode.ERR_DuplicateInterfaceInBaseList, "I<object>").WithArguments("I<object>").WithLocation(12, 22) ); } [Fact, WorkItem(38427, "https://github.com/dotnet/roslyn/issues/38427")] public void MethodTypeInference_ImplementedInterfaces_Direct_TupleDifferences() { var source = @" #nullable enable warnings static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<(int a, int b)>, I<(int c, int d)> {} interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,11): error CS1061: 'C' does not contain a definition for 'Extension' and no accessible extension method 'Extension' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // c.Extension(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Extension").WithArguments("C", "Extension").WithLocation(7, 11), // (13,7): error CS8140: 'I<(int c, int d)>' is already listed in the interface list on type 'C' with different tuple element names, as 'I<(int a, int b)>'. // class C : I<(int a, int b)>, I<(int c, int d)> {} Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I<(int c, int d)>", "I<(int a, int b)>", "C").WithLocation(13, 7) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Partial_ObliviousVsAnnotated() { var source = @" #nullable enable static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} partial class C : I<object?> { } #nullable disable partial class C : I<object> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object?>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Partial_ObliviousVsUnannotated() { var source = @" #nullable enable static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} partial class C : I<object> { } #nullable disable partial class C : I<object> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Partial_AnnotatedVsUnannotated() { var source = @" #nullable enable static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} partial class C : I<object?> { } partial class C : I<object> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,15): warning CS8645: 'I<object>' is already listed in the interface list on type 'C' with different nullability of reference types. // partial class C : I<object?> { } Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C").WithArguments("I<object>", "C").WithLocation(15, 15) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Indirect() { var source = @" #nullable enable warnings static class P { static void M<T>(T c) where T : I<object>, I2 { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} #nullable enable annotations interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Indirect_UsingBaseClass() { var source = @" #nullable enable warnings static class P { static void M<T>(T c) where T : C { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<object>, I2 {} interface I<T> {} #nullable enable annotations interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Indirect_UsingBaseClass_AnnotatedVersusUnannotated() { var source = @" #nullable enable annotations static class P { static void M<T>(T c) where T : C { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<object?>, I2 {} interface I<T> {} interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38427, "https://github.com/dotnet/roslyn/issues/38427")] public void MethodTypeInference_TypeParameter_Indirect_TupleDifferences() { var source = @" static class P { static void M<T>(T c) where T : I<(int a, int b)>, I2 { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} interface I2 : I<(int c, int d)> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,11): error CS1061: 'T' does not contain a definition for 'Extension' and no accessible extension method 'Extension' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // c.Extension(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Extension").WithArguments("T", "Extension").WithLocation(6, 11) ); } [Fact, WorkItem(38427, "https://github.com/dotnet/roslyn/issues/38427")] public void MethodTypeInference_TypeParameter_Indirect_MatchingTuples() { var source = @" static class P { static void M<T>(T c) where T : I<(int a, int b)>, I2 { var t = c.Extension(); _ = t.a; } public static T Extension<T>(this I<T> source) => throw null!; } interface I<T> {} interface I2 : I<(int a, int b)> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Direct() { var source = @" #nullable enable warnings static class P { static void M<T>(T c) where T : I<object>, #nullable enable annotations I<object> { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): error CS0405: Duplicate constraint 'I<object>' for type parameter 'T' // I<object> Diagnostic(ErrorCode.ERR_DuplicateBound, "I<object>").WithArguments("I<object>", "T").WithLocation(7, 9) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Direct_NullabilityAndTupleNameDifferences() { var source = @" #nullable enable static class P { static void M<T>(T c) where T : I<(object a, object b)>, I<(object? c, object? d)> { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,62): error CS0405: Duplicate constraint 'I<(object c, object d)>' for type parameter 'T' // static void M<T>(T c) where T : I<(object a, object b)>, I<(object? c, object? d)> Diagnostic(ErrorCode.ERR_DuplicateBound, "I<(object? c, object? d)>").WithArguments("I<(object c, object d)>", "T").WithLocation(5, 62) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Direct_NullabilityAndTupleNameDifferences_Oblivious() { var source = @" #nullable enable static class P { static void M<T>(T c) where T : I<(object a, object b)>, #nullable disable I<(object c, object d)> { } } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): error CS0405: Duplicate constraint 'I<(object c, object d)>' for type parameter 'T' // I<(object c, object d)> Diagnostic(ErrorCode.ERR_DuplicateBound, "I<(object c, object d)>").WithArguments("I<(object c, object d)>", "T").WithLocation(7, 9) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Direct_NullabilityDifferences_Oblivious() { var source = @" #nullable enable static class P { static void M<T>(T c) where T : I<(object a, object b)>, #nullable disable I<(object a, object b)> { } } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): error CS0405: Duplicate constraint 'I<(object a, object b)>' for type parameter 'T' // I<(object a, object b)> Diagnostic(ErrorCode.ERR_DuplicateBound, "I<(object a, object b)>").WithArguments("I<(object a, object b)>", "T").WithLocation(7, 9) ); } [Fact, WorkItem(38427, "https://github.com/dotnet/roslyn/issues/38427")] public void MethodTypeInference_TypeParameter_Direct_TupleDifferences() { var source = @" static class P { static void M<T>(T c) where T : I<(int a, int b)>, I<(int c, int d)> { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,56): error CS0405: Duplicate constraint 'I<(int c, int d)>' for type parameter 'T' // static void M<T>(T c) where T : I<(int a, int b)>, I<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateBound, "I<(int c, int d)>").WithArguments("I<(int c, int d)>", "T").WithLocation(4, 56) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MultipleIEnumerableT_UnannotatedObjectVersusAnnotatedObject() { var text = @" using System.Collections; using System.Collections.Generic; #nullable enable warnings class C<T> { void M(Enumerable e) { foreach (var x in e) { } } } #nullable enable interface I : IEnumerable<C<object?>> { } class Enumerable : IEnumerable<C<object>>, I #nullable disable { IEnumerator<C<object>> IEnumerable<C<object>>.GetEnumerator() { throw null!; } IEnumerator IEnumerable.GetEnumerator() { throw null!; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (17,7): warning CS8645: 'IEnumerable<C<object?>>' is already listed in the interface list on type 'Enumerable' with different nullability of reference types. // class Enumerable : IEnumerable<C<object>>, I Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Enumerable").WithArguments("System.Collections.Generic.IEnumerable<C<object?>>", "Enumerable").WithLocation(17, 7) ); var tree = comp.SyntaxTrees.Single(); var @foreach = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal("C<System.Object>", model.GetForEachStatementInfo(@foreach).ElementType.ToTestDisplayString()); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MultipleIEnumerableT_AnnotatedObjectVersusUnannotatedObject() { var text = @" using System.Collections; using System.Collections.Generic; #nullable enable warnings class C<T> { void M(Enumerable e) { foreach (var x in e) { } } } #nullable enable interface I : IEnumerable<C<object>> { } class Enumerable : IEnumerable<C<object?>>, I #nullable disable { IEnumerator<C<object>> IEnumerable<C<object>>.GetEnumerator() { throw null!; } IEnumerator IEnumerable.GetEnumerator() { throw null!; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (17,7): warning CS8645: 'IEnumerable<C<object>>' is already listed in the interface list on type 'Enumerable' with different nullability of reference types. // class Enumerable : IEnumerable<C<object?>>, I Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Enumerable").WithArguments("System.Collections.Generic.IEnumerable<C<object>>", "Enumerable").WithLocation(17, 7) ); var tree = comp.SyntaxTrees.Single(); var @foreach = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); // Note: we get the same element type regardless of the order in which interfaces are listed Assert.Equal("C<System.Object>", model.GetForEachStatementInfo(@foreach).ElementType.ToTestDisplayString()); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MultipleIEnumerableT_TupleAVersusTupleC() { var text = @" using System.Collections; using System.Collections.Generic; #nullable enable warnings class C<T> { void M(Enumerable e) { foreach (var x in e) { } } } #nullable enable interface I : IEnumerable<C<(int a, int b)>> { } class Enumerable : IEnumerable<C<(int c, int d)>>, I #nullable disable { IEnumerator<C<(int c, int d)>> IEnumerable<C<(int c, int d)>>.GetEnumerator() { throw null!; } IEnumerator IEnumerable.GetEnumerator() { throw null!; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (17,7): error CS8140: 'IEnumerable<C<(int a, int b)>>' is already listed in the interface list on type 'Enumerable' with different tuple element names, as 'IEnumerable<C<(int c, int d)>>'. // class Enumerable : IEnumerable<C<(int c, int d)>>, I Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "Enumerable").WithArguments("System.Collections.Generic.IEnumerable<C<(int a, int b)>>", "System.Collections.Generic.IEnumerable<C<(int c, int d)>>", "Enumerable").WithLocation(17, 7) ); var tree = comp.SyntaxTrees.Single(); var @foreach = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal("C<(System.Int32 a, System.Int32 b)>", model.GetForEachStatementInfo(@foreach).ElementType.ToTestDisplayString()); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MultipleIEnumerableT_TupleCVersusTupleA() { var text = @" using System.Collections; using System.Collections.Generic; #nullable enable warnings class C<T> { void M(Enumerable e) { foreach (var x in e) { } } } #nullable enable interface I : IEnumerable<C<(int c, int d)>> { } class Enumerable : IEnumerable<C<(int a, int b)>>, I #nullable disable { IEnumerator<C<(int a, int b)>> IEnumerable<C<(int a, int b)>>.GetEnumerator() { throw null!; } IEnumerator IEnumerable.GetEnumerator() { throw null!; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (17,7): error CS8140: 'IEnumerable<C<(int c, int d)>>' is already listed in the interface list on type 'Enumerable' with different tuple element names, as 'IEnumerable<C<(int a, int b)>>'. // class Enumerable : IEnumerable<C<(int a, int b)>>, I Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "Enumerable").WithArguments("System.Collections.Generic.IEnumerable<C<(int c, int d)>>", "System.Collections.Generic.IEnumerable<C<(int a, int b)>>", "Enumerable").WithLocation(17, 7) ); var tree = comp.SyntaxTrees.Single(); var @foreach = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal("C<(System.Int32 c, System.Int32 d)>", model.GetForEachStatementInfo(@foreach).ElementType.ToTestDisplayString()); } [Fact, WorkItem(42837, "https://github.com/dotnet/roslyn/issues/42837")] public void NullableDirectivesInSpeculativeModel() { var source = @" #nullable enable public class C<TSymbol> where TSymbol : class, ISymbolInternal { public object? _uniqueSymbolOrArities; private bool HasUniqueSymbol => false; public void GetUniqueSymbolOrArities(out IArityEnumerable? arities, out TSymbol? uniqueSymbol) { if (this.HasUniqueSymbol) { arities = null; #nullable disable // Can '_uniqueSymbolOrArities' be null? https://github.com/dotnet/roslyn/issues/39166 uniqueSymbol = (TSymbol)_uniqueSymbolOrArities; #nullable enable } } } interface IArityEnumerable { } interface ISymbolInternal { } "; var comp = CreateNullableCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var ifStatement = root.DescendantNodes().OfType<IfStatementSyntax>().Single(); var cast = ifStatement.DescendantNodes().OfType<CastExpressionSyntax>().Single(); var replaceWith = cast.Expression; var newIfStatement = ifStatement.ReplaceNode(cast, replaceWith); Assert.True(model.TryGetSpeculativeSemanticModel( ifStatement.SpanStart, newIfStatement, out var speculativeModel)); var assignment = newIfStatement.DescendantNodes() .OfType<AssignmentExpressionSyntax>() .ElementAt(1); var info = speculativeModel.GetSymbolInfo(assignment); Assert.Null(info.Symbol); var typeInfo = speculativeModel.GetTypeInfo(assignment); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, typeInfo.Nullability.Annotation); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_Operator() { var source = @" #nullable enable public interface I<T> where T : class? { public static T operator +(I<T> x, I<T> y) => throw null!; } class C { static void Main(I<object> x, I<object?> y) { var z = x + y; z = y + x; } } "; var compilation1 = CreateCompilation(source, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,21): warning CS8620: Argument of type 'I<object?>' cannot be used for parameter 'y' of type 'I<object>' in 'object I<object>.operator +(I<object> x, I<object> y)' due to differences in the nullability of reference types. // var z = x + y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object?>", "I<object>", "y", "object I<object>.operator +(I<object> x, I<object> y)").WithLocation(12, 21), // (13,17): warning CS8620: Argument of type 'I<object>' cannot be used for parameter 'y' of type 'I<object?>' in 'object? I<object?>.operator +(I<object?> x, I<object?> y)' due to differences in the nullability of reference types. // z = y + x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "y", "object? I<object?>.operator +(I<object?> x, I<object?> y)").WithLocation(13, 17) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_Operator_NoDirectlyImplementedOperator() { var source = @" #nullable enable public interface I2 : I<object>, I3 { } public interface I3 : I<object?> { } public interface I<T> where T : class? { public static T operator +(I<T> x, I<T> y) => throw null!; } class C { static void Main(I2 x, I2 y) { var z = x + y; z = y + x; } } "; var compilation1 = CreateCompilation(source, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (3,18): warning CS8645: 'I<object?>' is already listed in the interface list on type 'I2' with different nullability of reference types. // public interface I2 : I<object>, I3 { } Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I2").WithArguments("I<object?>", "I2").WithLocation(3, 18) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_Operator_TupleDifferences() { var source = @" #nullable enable public interface I2 : I<(int c, int d)> { } public interface I<T> { public static T operator +(I<T> x, I<T> y) => throw null!; } class C { static void M<T>(T x, T y) where T : I<(int a, int b)>, I2 { var z = x + y; z = y + x; } } "; var compilation1 = CreateCompilation(source, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (13,17): error CS0034: Operator '+' is ambiguous on operands of type 'T' and 'T' // var z = x + y; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x + y").WithArguments("+", "T", "T").WithLocation(13, 17), // (14,13): error CS0034: Operator '+' is ambiguous on operands of type 'T' and 'T' // z = y + x; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "y + x").WithArguments("+", "T", "T").WithLocation(14, 13) ); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_UnaryOperator_01() { var source = @"#pragma warning disable 649 #nullable enable class A<T> { public static A<T> operator~(A<T> a) => a; internal T F = default!; } class B<T> : A<T> { } class Program { static B<T> Create<T>(T t) { return new B<T>(); } static void F<T>() where T : class, new() { T x = null; // 1 (~Create(x)).F.ToString(); // 2 T? y = new T(); (~Create(y)).F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 15), // (20,9): warning CS8602: Dereference of a possibly null reference. // (~Create(x)).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(~Create(x)).F").WithLocation(20, 9)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_UnaryOperator_02() { var source = @"#nullable enable interface IA<T> { T P { get; } public static IA<T> operator~(IA<T> a) => a; } interface IB<T> : IA<T> { } class Program { static IB<T> Create<T>(T t) { throw null!; } static void F<T>() where T : class, new() { T x = null; // 1 (~Create(x)).P.ToString(); // 2 T? y = new T(); (~Create(y)).P.ToString(); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (18,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 15), // (19,9): warning CS8602: Dereference of a possibly null reference. // (~Create(x)).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(~Create(x)).P").WithLocation(19, 9)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_UnaryOperator_03() { var source = @"#pragma warning disable 649 #nullable enable struct S<T> { public static S<T> operator~(S<T> s) => s; internal T F; } class Program { static S<T> Create1<T>(T t) => new S<T>(); static S<T>? Create2<T>(T t) => null; static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var s1x = ~Create1(x); s1x.F.ToString(); // 2 var s2x = (~Create2(x)).Value; // 3 s2x.F.ToString(); // 4 var s1y = ~Create1(y); s1y.F.ToString(); var s2y = (~Create2(y)).Value; // 5 s2y.F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 15), // (17,9): warning CS8602: Dereference of a possibly null reference. // s1x.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1x.F").WithLocation(17, 9), // (18,20): warning CS8629: Nullable value type may be null. // var s2x = (~Create2(x)).Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "~Create2(x)").WithLocation(18, 20), // (19,9): warning CS8602: Dereference of a possibly null reference. // s2x.F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2x.F").WithLocation(19, 9), // (22,20): warning CS8629: Nullable value type may be null. // var s2y = (~Create2(y)).Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "~Create2(y)").WithLocation(22, 20)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_UnaryOperator_04() { var source = @"#pragma warning disable 649 #pragma warning disable 8629 struct S<T> { public static S<T>? operator~(S<T>? s) => s; internal T F; } class Program { static S<T> Create1<T>(T t) => new S<T>(); static S<T>? Create2<T>(T t) => null; static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var s1x = (~Create1(x)).Value; s1x.F.ToString(); // 2 var s2x = (~Create2(x)).Value; s2x.F.ToString(); // 3 var s1y = (~Create1(y)).Value; s1y.F.ToString(); var s2y = (~Create2(y)).Value; s2y.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 15), // (17,9): warning CS8602: Dereference of a possibly null reference. // s1x.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1x.F").WithLocation(17, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // s2x.F.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2x.F").WithLocation(19, 9)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_BinaryOperator_01() { var source = @"#pragma warning disable 649 #nullable enable class A<T> { public static A<T> operator+(A<T> a, B<T> b) => a; internal T F = default!; } class B<T> { public static A<T> operator*(A<T> a, B<T> b) => a; } class Program { static A<T> CreateA<T>(T t) => new A<T>(); static B<T> CreateB<T>(T t) => new B<T>(); static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var ax = CreateA(x); var bx = CreateB(x); var ay = CreateA(y); var by = CreateB(y); (ax + bx).F.ToString(); // 2 (ax + by).F.ToString(); // 3 (ay + bx).F.ToString(); // 4 (ay + by).F.ToString(); (ax * bx).F.ToString(); // 5 (ax * by).F.ToString(); // 6 (ay * bx).F.ToString(); // 7 (ay * by).F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 15), // (24,9): warning CS8602: Dereference of a possibly null reference. // (ax + bx).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(ax + bx).F").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // (ax + by).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(ax + by).F").WithLocation(25, 9), // (25,15): warning CS8620: Argument of type 'B<T>' cannot be used for parameter 'b' of type 'B<T?>' in 'A<T?> A<T?>.operator +(A<T?> a, B<T?> b)' due to differences in the nullability of reference types. // (ax + by).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "by").WithArguments("B<T>", "B<T?>", "b", "A<T?> A<T?>.operator +(A<T?> a, B<T?> b)").WithLocation(25, 15), // (26,15): warning CS8620: Argument of type 'B<T?>' cannot be used for parameter 'b' of type 'B<T>' in 'A<T> A<T>.operator +(A<T> a, B<T> b)' due to differences in the nullability of reference types. // (ay + bx).F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "bx").WithArguments("B<T?>", "B<T>", "b", "A<T> A<T>.operator +(A<T> a, B<T> b)").WithLocation(26, 15), // (28,9): warning CS8602: Dereference of a possibly null reference. // (ax * bx).F.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(ax * bx).F").WithLocation(28, 9), // (29,10): warning CS8620: Argument of type 'A<T?>' cannot be used for parameter 'a' of type 'A<T>' in 'A<T> B<T>.operator *(A<T> a, B<T> b)' due to differences in the nullability of reference types. // (ax * by).F.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "ax").WithArguments("A<T?>", "A<T>", "a", "A<T> B<T>.operator *(A<T> a, B<T> b)").WithLocation(29, 10), // (30,9): warning CS8602: Dereference of a possibly null reference. // (ay * bx).F.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(ay * bx).F").WithLocation(30, 9), // (30,10): warning CS8620: Argument of type 'A<T>' cannot be used for parameter 'a' of type 'A<T?>' in 'A<T?> B<T?>.operator *(A<T?> a, B<T?> b)' due to differences in the nullability of reference types. // (ay * bx).F.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "ay").WithArguments("A<T>", "A<T?>", "a", "A<T?> B<T?>.operator *(A<T?> a, B<T?> b)").WithLocation(30, 10)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_BinaryOperator_02() { var source = @"#pragma warning disable 649 #nullable enable class A1<T> { public static A1<T> operator+(A1<T> a, B1<T> b) => a; internal T F = default!; } class B1<T> : A1<T> { } class A2<T> { public static A2<T> operator*(A2<T> a, B2<T> b) => a; internal T F = default!; } class B2<T> : A2<T> { } class Program { static B1<T> Create1<T>(T t) => new B1<T>(); static B2<T> Create2<T>(T t) => new B2<T>(); static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var b1x = Create1(x); var b2x = Create2(x); var b1y = Create1(y); var b2y = Create2(y); (b1x + b1x).F.ToString(); // 2 (b1x + b1y).F.ToString(); // 3 (b1y + b1x).F.ToString(); // 4 (b1y + b1y).F.ToString(); (b2x * b2x).F.ToString(); // 5 (b2x * b2y).F.ToString(); // 6 (b2y * b2x).F.ToString(); // 7 (b2y * b2y).F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (25,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(25, 15), // (31,9): warning CS8602: Dereference of a possibly null reference. // (b1x + b1x).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b1x + b1x).F").WithLocation(31, 9), // (32,9): warning CS8602: Dereference of a possibly null reference. // (b1x + b1y).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b1x + b1y).F").WithLocation(32, 9), // (32,16): warning CS8620: Argument of type 'B1<T>' cannot be used for parameter 'b' of type 'B1<T?>' in 'A1<T?> A1<T?>.operator +(A1<T?> a, B1<T?> b)' due to differences in the nullability of reference types. // (b1x + b1y).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b1y").WithArguments("B1<T>", "B1<T?>", "b", "A1<T?> A1<T?>.operator +(A1<T?> a, B1<T?> b)").WithLocation(32, 16), // (33,16): warning CS8620: Argument of type 'B1<T?>' cannot be used for parameter 'b' of type 'B1<T>' in 'A1<T> A1<T>.operator +(A1<T> a, B1<T> b)' due to differences in the nullability of reference types. // (b1y + b1x).F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b1x").WithArguments("B1<T?>", "B1<T>", "b", "A1<T> A1<T>.operator +(A1<T> a, B1<T> b)").WithLocation(33, 16), // (35,9): warning CS8602: Dereference of a possibly null reference. // (b2x * b2x).F.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b2x * b2x).F").WithLocation(35, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // (b2x * b2y).F.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b2x * b2y).F").WithLocation(36, 9), // (36,16): warning CS8620: Argument of type 'B2<T>' cannot be used for parameter 'b' of type 'B2<T?>' in 'A2<T?> A2<T?>.operator *(A2<T?> a, B2<T?> b)' due to differences in the nullability of reference types. // (b2x * b2y).F.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b2y").WithArguments("B2<T>", "B2<T?>", "b", "A2<T?> A2<T?>.operator *(A2<T?> a, B2<T?> b)").WithLocation(36, 16), // (37,16): warning CS8620: Argument of type 'B2<T?>' cannot be used for parameter 'b' of type 'B2<T>' in 'A2<T> A2<T>.operator *(A2<T> a, B2<T> b)' due to differences in the nullability of reference types. // (b2y * b2x).F.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b2x").WithArguments("B2<T?>", "B2<T>", "b", "A2<T> A2<T>.operator *(A2<T> a, B2<T> b)").WithLocation(37, 16)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_BinaryOperator_03() { var source = @"#pragma warning disable 649 #nullable enable struct S<T> { public static S<T> operator+(S<T> x, S<T> y) => x; internal T F; } class Program { static S<T> Create1<T>(T t) => new S<T>(); static S<T>? Create2<T>(T t) => null; static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var s1x = Create1(x); var s2x = Create2(x); var s1y = Create1(y); var s2y = Create2(y); (s1x + s1y).F.ToString(); (s1y + s1x).F.ToString(); (s1x + s2y).Value.F.ToString(); (s1y + s2x).Value.F.ToString(); (s2x + s1y).Value.F.ToString(); (s2y + s1x).Value.F.ToString(); (s2x + s2y).Value.F.ToString(); (s2y + s2x).Value.F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 15), // (20,9): warning CS8602: Dereference of a possibly null reference. // (s1x + s1y).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s1x + s1y).F").WithLocation(20, 9), // (20,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>' in 'S<T?> S<T?>.operator +(S<T?> x, S<T?> y)' due to differences in the nullability of reference types. // (s1x + s1y).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1y").WithArguments("S<T>", "S<T?>", "y", "S<T?> S<T?>.operator +(S<T?> x, S<T?> y)").WithLocation(20, 16), // (21,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>' in 'S<T> S<T>.operator +(S<T> x, S<T> y)' due to differences in the nullability of reference types. // (s1y + s1x).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1x").WithArguments("S<T?>", "S<T>", "y", "S<T> S<T>.operator +(S<T> x, S<T> y)").WithLocation(21, 16), // (22,9): warning CS8602: Dereference of a possibly null reference. // (s1x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s1x + s2y).Value.F").WithLocation(22, 9), // (22,10): warning CS8629: Nullable value type may be null. // (s1x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1x + s2y").WithLocation(22, 10), // (22,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>' in 'S<T?> S<T?>.operator +(S<T?> x, S<T?> y)' due to differences in the nullability of reference types. // (s1x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2y").WithArguments("S<T>", "S<T?>", "y", "S<T?> S<T?>.operator +(S<T?> x, S<T?> y)").WithLocation(22, 16), // (23,10): warning CS8629: Nullable value type may be null. // (s1y + s2x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1y + s2x").WithLocation(23, 10), // (23,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>' in 'S<T> S<T>.operator +(S<T> x, S<T> y)' due to differences in the nullability of reference types. // (s1y + s2x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2x").WithArguments("S<T?>", "S<T>", "y", "S<T> S<T>.operator +(S<T> x, S<T> y)").WithLocation(23, 16), // (24,9): warning CS8602: Dereference of a possibly null reference. // (s2x + s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s2x + s1y).Value.F").WithLocation(24, 9), // (24,10): warning CS8629: Nullable value type may be null. // (s2x + s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2x + s1y").WithLocation(24, 10), // (24,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>' in 'S<T?> S<T?>.operator +(S<T?> x, S<T?> y)' due to differences in the nullability of reference types. // (s2x + s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1y").WithArguments("S<T>", "S<T?>", "y", "S<T?> S<T?>.operator +(S<T?> x, S<T?> y)").WithLocation(24, 16), // (25,10): warning CS8629: Nullable value type may be null. // (s2y + s1x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2y + s1x").WithLocation(25, 10), // (25,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>' in 'S<T> S<T>.operator +(S<T> x, S<T> y)' due to differences in the nullability of reference types. // (s2y + s1x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1x").WithArguments("S<T?>", "S<T>", "y", "S<T> S<T>.operator +(S<T> x, S<T> y)").WithLocation(25, 16), // (26,9): warning CS8602: Dereference of a possibly null reference. // (s2x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s2x + s2y).Value.F").WithLocation(26, 9), // (26,10): warning CS8629: Nullable value type may be null. // (s2x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2x + s2y").WithLocation(26, 10), // (26,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>' in 'S<T?> S<T?>.operator +(S<T?> x, S<T?> y)' due to differences in the nullability of reference types. // (s2x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2y").WithArguments("S<T>", "S<T?>", "y", "S<T?> S<T?>.operator +(S<T?> x, S<T?> y)").WithLocation(26, 16), // (27,10): warning CS8629: Nullable value type may be null. // (s2y + s2x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2y + s2x").WithLocation(27, 10), // (27,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>' in 'S<T> S<T>.operator +(S<T> x, S<T> y)' due to differences in the nullability of reference types. // (s2y + s2x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2x").WithArguments("S<T?>", "S<T>", "y", "S<T> S<T>.operator +(S<T> x, S<T> y)").WithLocation(27, 16)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_BinaryOperator_04() { var source = @"#pragma warning disable 649 #pragma warning disable 8629 struct S<T> { public static S<T>? operator+(S<T> x, S<T>? y) => x; public static S<T>? operator*(S<T>? x, S<T> y) => x; internal T F; } class Program { static S<T> Create1<T>(T t) => new S<T>(); static S<T>? Create2<T>(T t) => null; static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var s1x = Create1(x); var s2x = Create2(x); var s1y = Create1(y); var s2y = Create2(y); (s1x + s1y).Value.F.ToString(); (s1x + s2x).Value.F.ToString(); (s1x + s2y).Value.F.ToString(); (s1y + s1x).Value.F.ToString(); (s1y + s2x).Value.F.ToString(); (s1y + s2y).Value.F.ToString(); (s1x * s1y).Value.F.ToString(); (s1y * s1x).Value.F.ToString(); (s2x * s1x).Value.F.ToString(); (s2x * s1y).Value.F.ToString(); (s2y * s1x).Value.F.ToString(); (s2y * s1y).Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(15, 15), // (21,9): warning CS8602: Dereference of a possibly null reference. // (s1x + s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s1x + s1y).Value.F").WithLocation(21, 9), // (21,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>?' in 'S<T?>? S<T?>.operator +(S<T?> x, S<T?>? y)' due to differences in the nullability of reference types. // (s1x + s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1y").WithArguments("S<T>", "S<T?>?", "y", "S<T?>? S<T?>.operator +(S<T?> x, S<T?>? y)").WithLocation(21, 16), // (22,9): warning CS8602: Dereference of a possibly null reference. // (s1x + s2x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s1x + s2x).Value.F").WithLocation(22, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // (s1x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s1x + s2y).Value.F").WithLocation(23, 9), // (23,16): warning CS8620: Argument of type 'S<T>?' cannot be used for parameter 'y' of type 'S<T?>?' in 'S<T?>? S<T?>.operator +(S<T?> x, S<T?>? y)' due to differences in the nullability of reference types. // (s1x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2y").WithArguments("S<T>?", "S<T?>?", "y", "S<T?>? S<T?>.operator +(S<T?> x, S<T?>? y)").WithLocation(23, 16), // (24,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>?' in 'S<T>? S<T>.operator +(S<T> x, S<T>? y)' due to differences in the nullability of reference types. // (s1y + s1x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1x").WithArguments("S<T?>", "S<T>?", "y", "S<T>? S<T>.operator +(S<T> x, S<T>? y)").WithLocation(24, 16), // (25,16): warning CS8620: Argument of type 'S<T?>?' cannot be used for parameter 'y' of type 'S<T>?' in 'S<T>? S<T>.operator +(S<T> x, S<T>? y)' due to differences in the nullability of reference types. // (s1y + s2x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2x").WithArguments("S<T?>?", "S<T>?", "y", "S<T>? S<T>.operator +(S<T> x, S<T>? y)").WithLocation(25, 16), // (27,9): warning CS8602: Dereference of a possibly null reference. // (s1x * s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s1x * s1y).Value.F").WithLocation(27, 9), // (27,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>' in 'S<T?>? S<T?>.operator *(S<T?>? x, S<T?> y)' due to differences in the nullability of reference types. // (s1x * s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1y").WithArguments("S<T>", "S<T?>", "y", "S<T?>? S<T?>.operator *(S<T?>? x, S<T?> y)").WithLocation(27, 16), // (28,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>' in 'S<T>? S<T>.operator *(S<T>? x, S<T> y)' due to differences in the nullability of reference types. // (s1y * s1x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1x").WithArguments("S<T?>", "S<T>", "y", "S<T>? S<T>.operator *(S<T>? x, S<T> y)").WithLocation(28, 16), // (29,9): warning CS8602: Dereference of a possibly null reference. // (s2x * s1x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s2x * s1x).Value.F").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // (s2x * s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s2x * s1y).Value.F").WithLocation(30, 9), // (30,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>' in 'S<T?>? S<T?>.operator *(S<T?>? x, S<T?> y)' due to differences in the nullability of reference types. // (s2x * s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1y").WithArguments("S<T>", "S<T?>", "y", "S<T?>? S<T?>.operator *(S<T?>? x, S<T?> y)").WithLocation(30, 16), // (31,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>' in 'S<T>? S<T>.operator *(S<T>? x, S<T> y)' due to differences in the nullability of reference types. // (s2y * s1x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1x").WithArguments("S<T?>", "S<T>", "y", "S<T>? S<T>.operator *(S<T>? x, S<T> y)").WithLocation(31, 16)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_BinaryLogicalOperator_01() { var source = @"#pragma warning disable 660 #pragma warning disable 661 #nullable enable class A<T> { public static A<T> operator&(A<T> x, A<T> y) => x; public static A<T> operator|(A<T> x, A<T> y) => y; public static bool operator true(A<T> a) => true; public static bool operator false(A<T> a) => false; } class B<T> : A<T> { } class Program { static A<T> CreateA<T>(T t) => new A<T>(); static B<T> CreateB<T>(T t) => new B<T>(); static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var ax = CreateA(x); var bx = CreateB(x); var ay = CreateA(y); var by = CreateB(y); _ = (ax && ay); // 2 _ = (ax && bx); _ = (ax || by); // 3 _ = (by && ax); // 4 _ = (by || ay); _ = (by || bx); // 5 } }"; var comp = CreateCompilation(source); // https://github.com/dotnet/roslyn/issues/29605: Missing warnings. comp.VerifyDiagnostics( // (20,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(20, 15)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_BinaryLogicalOperator_02() { var source = @"#pragma warning disable 660 #pragma warning disable 661 #nullable enable struct S<T> { public static S<T> operator&(S<T> x, S<T> y) => x; public static S<T> operator|(S<T> x, S<T> y) => y; public static bool operator true(S<T>? s) => true; public static bool operator false(S<T>? s) => false; } class Program { static S<T> Create1<T>(T t) => new S<T>(); static S<T>? Create2<T>(T t) => null; static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var s1x = Create1(x); var s2x = Create2(x); var s1y = Create1(y); var s2y = Create2(y); _ = (s1x && s1y); // 2 _ = (s1x && s2x); _ = (s1x || s2y); // 3 _ = (s2y && s1x); // 4 _ = (s2y || s1y); _ = (s2y || s2x); // 5 } }"; var comp = CreateCompilation(source); // https://github.com/dotnet/roslyn/issues/29605: Missing warnings. comp.VerifyDiagnostics( // (17,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(17, 15)); } [Fact] [WorkItem(38726, "https://github.com/dotnet/roslyn/issues/38726")] public void CollectionInitializerBoxingConversion() { var source = @"#nullable enable using System.Collections; struct S : IEnumerable { IEnumerator IEnumerable.GetEnumerator() => null!; } static class Program { static void Add(this object x, object y) { } static T F<T>() where T : IEnumerable, new() { return new T() { 1, 2 }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void GetAwaiterExtensionMethod() { var source = @"#nullable enable using System.Runtime.CompilerServices; using System.Threading.Tasks; class Awaitable { } static class Program { static TaskAwaiter GetAwaiter(this Awaitable? a) => default; static async Task Main() { Awaitable? x = new Awaitable(); Awaitable y = null; // 1 await x; await y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Awaitable y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 23)); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterExtensionMethod_Await() { var source = @"#nullable enable using System.Runtime.CompilerServices; using System.Threading.Tasks; struct StructAwaitable<T> { } static class Program { static TaskAwaiter GetAwaiter(this StructAwaitable<object?> s) => default; static StructAwaitable<T> Create<T>(T t) => new StructAwaitable<T>(); static async Task Main() { object? x = new object(); object y = null; // 1 await Create(x); // 2 await Create(y); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 20), // (13,15): warning CS8620: Argument of type 'StructAwaitable<object>' cannot be used for parameter 's' of type 'StructAwaitable<object?>' in 'TaskAwaiter Program.GetAwaiter(StructAwaitable<object?> s)' due to differences in the nullability of reference types. // await Create(x); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(x)").WithArguments("StructAwaitable<object>", "StructAwaitable<object?>", "s", "TaskAwaiter Program.GetAwaiter(StructAwaitable<object?> s)").WithLocation(13, 15)); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterExtensionMethod_AwaitUsing() { var source = @"#nullable enable using System.Runtime.CompilerServices; using System.Threading.Tasks; struct StructAwaitable<T> { } class Disposable<T> { public StructAwaitable<T> DisposeAsync() => new StructAwaitable<T>(); } static class Program { static TaskAwaiter GetAwaiter(this StructAwaitable<object> s) => default; static Disposable<T> Create<T>(T t) => new Disposable<T>(); static async Task Main() { object? x = new object(); object y = null; // 1 await using (Create(x)) { } await using (Create(y)) // 2 { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { IAsyncDisposableDefinition, source }); // Should report warning for GetAwaiter(). comp.VerifyDiagnostics( // (16,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 20)); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterExtensionMethod_AwaitUsingLocal() { var source = @"#nullable enable using System.Runtime.CompilerServices; using System.Threading.Tasks; struct StructAwaitable<T> { } class Disposable<T> { public StructAwaitable<T> DisposeAsync() => new StructAwaitable<T>(); } static class Program { static TaskAwaiter GetAwaiter(this StructAwaitable<object> s) => default; static Disposable<T> Create<T>(T t) => new Disposable<T>(); static async Task Main() { object? x = new object(); object y = null; // 1 await using var dx = Create(x); await using var dy = Create(y); // 2 } }"; var comp = CreateCompilationWithTasksExtensions(new[] { IAsyncDisposableDefinition, source }); // Should report warning for GetAwaiter(). comp.VerifyDiagnostics( // (16,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 20)); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterExtensionMethod_AwaitForEach() { var source = @"#nullable enable using System.Runtime.CompilerServices; using System.Threading.Tasks; struct StructAwaitable1<T> { } struct StructAwaitable2<T> { } class Enumerable<T> { public Enumerator<T> GetAsyncEnumerator() => new Enumerator<T>(); } class Enumerator<T> { public object Current => null!; public StructAwaitable1<T> MoveNextAsync() => new StructAwaitable1<T>(); public StructAwaitable2<T> DisposeAsync() => new StructAwaitable2<T>(); } static class Program { static TaskAwaiter<bool> GetAwaiter(this StructAwaitable1<object?> s) => default; static TaskAwaiter GetAwaiter(this StructAwaitable2<object> s) => default; static Enumerable<T> Create<T>(T t) => new Enumerable<T>(); static async Task Main() { object? x = new object(); object y = null; // 1 await foreach (var o in Create(x)) // 2 { } await foreach (var o in Create(y)) // 3 { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { s_IAsyncEnumerable, source }); comp.VerifyDiagnostics( // (24,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(24, 20), // (25,33): warning CS8620: Argument of type 'StructAwaitable1<object>' cannot be used for parameter 's' of type 'StructAwaitable1<object?>' in 'TaskAwaiter<bool> Program.GetAwaiter(StructAwaitable1<object?> s)' due to differences in the nullability of reference types. // await foreach (var o in Create(x)) // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(x)").WithArguments("StructAwaitable1<object>", "StructAwaitable1<object?>", "s", "TaskAwaiter<bool> Program.GetAwaiter(StructAwaitable1<object?> s)").WithLocation(25, 33), // (28,33): warning CS8620: Argument of type 'StructAwaitable2<object?>' cannot be used for parameter 's' of type 'StructAwaitable2<object>' in 'TaskAwaiter Program.GetAwaiter(StructAwaitable2<object> s)' due to differences in the nullability of reference types. // await foreach (var o in Create(y)) // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(y)").WithArguments("StructAwaitable2<object?>", "StructAwaitable2<object>", "s", "TaskAwaiter Program.GetAwaiter(StructAwaitable2<object> s)").WithLocation(28, 33) ); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterExtensionMethod_AwaitForEach_InverseAnnotations() { var source = @"#nullable enable using System.Runtime.CompilerServices; using System.Threading.Tasks; struct StructAwaitable1<T> { } struct StructAwaitable2<T> { } class Enumerable<T> { public Enumerator<T> GetAsyncEnumerator() => new Enumerator<T>(); } class Enumerator<T> { public object Current => null!; public StructAwaitable1<T> MoveNextAsync() => new StructAwaitable1<T>(); public StructAwaitable2<T> DisposeAsync() => new StructAwaitable2<T>(); } static class Program { static TaskAwaiter<bool> GetAwaiter(this StructAwaitable1<object> s) => default; static TaskAwaiter GetAwaiter(this StructAwaitable2<object?> s) => default; static Enumerable<T> Create<T>(T t) => new Enumerable<T>(); static async Task Main() { object? x = new object(); object y = null; // 1 await foreach (var o in Create(x)) // 2 { } await foreach (var o in Create(y)) // 3 { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { s_IAsyncEnumerable, source }); comp.VerifyDiagnostics( // (24,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(24, 20), // (25,33): warning CS8620: Argument of type 'StructAwaitable2<object>' cannot be used for parameter 's' of type 'StructAwaitable2<object?>' in 'TaskAwaiter Program.GetAwaiter(StructAwaitable2<object?> s)' due to differences in the nullability of reference types. // await foreach (var o in Create(x)) // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(x)").WithArguments("StructAwaitable2<object>", "StructAwaitable2<object?>", "s", "TaskAwaiter Program.GetAwaiter(StructAwaitable2<object?> s)").WithLocation(25, 33), // (28,33): warning CS8620: Argument of type 'StructAwaitable1<object?>' cannot be used for parameter 's' of type 'StructAwaitable1<object>' in 'TaskAwaiter<bool> Program.GetAwaiter(StructAwaitable1<object> s)' due to differences in the nullability of reference types. // await foreach (var o in Create(y)) // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(y)").WithArguments("StructAwaitable1<object?>", "StructAwaitable1<object>", "s", "TaskAwaiter<bool> Program.GetAwaiter(StructAwaitable1<object> s)").WithLocation(28, 33) ); } [Fact] [WorkItem(34921, "https://github.com/dotnet/roslyn/issues/34921")] public void NullableStructMembersOfClassesAndInterfaces() { var source = @"#nullable enable interface I<T> { T P { get; } } class C<T> { internal T F = default!; } class Program { static void F1<T>(I<(T, T)> i) where T : class? { var t = i.P; t.Item1.ToString(); // 1 } static void F2<T>(C<(T, T)> c) where T : class? { var t = c.F; t.Item1.ToString();// 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(18, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString();// 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(24, 9) ); } [Fact] [WorkItem(38339, "https://github.com/dotnet/roslyn/issues/38339")] public void AllowNull_Default() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class C<T> { internal T _f1 = default(T); internal T _f2 = default; [AllowNull] internal T _f3 = default(T); [AllowNull] internal T _f4 = default; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,34): warning CS8601: Possible null reference assignment. // internal T _f1 = default(T); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default(T)").WithLocation(5, 34), // (6,34): warning CS8601: Possible null reference assignment. // internal T _f2 = default; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(6, 34)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Join() { var source = @"#nullable enable class C<T> where T : new() { static T F1(bool b) { T t1; if (b) t1 = default(T); else t1 = default(T); return t1; // 1 } static T F2(bool b, T t) { T t2; if (b) t2 = default(T); else t2 = t; return t2; // 2 } static T F3(bool b) { T t3; if (b) t3 = default(T); else t3 = new T(); return t3; // 3 } static T F4(bool b, T t) { T t4; if (b) t4 = t; else t4 = default(T); return t4; // 4 } static T F5(bool b, T t) { T t5; if (b) t5 = t; else t5 = t; return t5; } static T F6(bool b, T t) { T t6; if (b) t6 = t; else t6 = new T(); return t6; } static T F7(bool b) { T t7; if (b) t7 = new T(); else t7 = default(T); return t7; // 5 } static T F8(bool b, T t) { T t8; if (b) t8 = new T(); else t8 = t; return t8; } static T F9(bool b) { T t9; if (b) t9 = new T(); else t9 = new T(); return t9; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,16): warning CS8603: Possible null reference return. // return t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(9, 16), // (16,16): warning CS8603: Possible null reference return. // return t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(16, 16), // (23,16): warning CS8603: Possible null reference return. // return t3; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t3").WithLocation(23, 16), // (30,16): warning CS8603: Possible null reference return. // return t4; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t4").WithLocation(30, 16), // (51,16): warning CS8603: Possible null reference return. // return t7; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t7").WithLocation(51, 16)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Meet_01() { var source = @"#nullable enable class C<T> where T : new() { static T F1() { T t1; try { t1 = default(T); } finally { t1 = default(T); } return t1; // 1 } static T F2(T t) { T t2; try { t2 = default(T); } finally { t2 = t; } return t2; } static T F3() { T t3; try { t3 = default(T); } finally { t3 = new T(); } return t3; } static T F4(T t) { T t4; try { t4 = t; } finally { t4 = default(T); } return t4; // 2 } static T F5(T t) { T t5; try { t5 = t; } finally { t5 = t; } return t5; } static T F6(T t) { T t6; try { t6 = t; } finally { t6 = new T(); } return t6; } static T F7() { T t7; try { t7 = new T(); } finally { t7 = default(T); } return t7; // 3 } static T F8(T t) { T t8; try { t8 = new T(); } finally { t8 = t; } return t8; } static T F9() { T t9; try { t9 = new T(); } finally { t9 = new T(); } return t9; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,16): warning CS8603: Possible null reference return. // return t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(9, 16), // (30,16): warning CS8603: Possible null reference return. // return t4; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t4").WithLocation(30, 16), // (51,16): warning CS8603: Possible null reference return. // return t7; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t7").WithLocation(51, 16)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Meet_02() { var source = @"#nullable enable class C<T> where T : new() { static bool b = false; static void F0(T t) { } static T F2(T t) { T t2 = t; T r2; try { t2 = default(T); t2 = t; } finally { if (b) F0(t2); // 1 r2 = t2; } return r2; // 2 } static T F3(T t) { T t3 = t; T r3; try { t3 = default(T); t3 = new T(); } finally { if (b) F0(t3); // 3 r3 = t3; } return r3; // 4 } static T F4(T t) { T t4 = t; T r4; try { t4 = t; t4 = default(T); } finally { if (b) F0(t4); // 5 r4 = t4; } return r4; // 6 } static T F6(T t) { T t6 = t; T r6; try { t6 = t; t6 = new T(); } finally { F0(t6); r6 = t6; } return r6; } static T F7(T t) { T t7 = t; T r7; try { t7 = new T(); t7 = default(T); } finally { if (b) F0(t7); // 7 r7 = t7; } return r7; // 8 } static T F8(T t) { T t8 = t; T r8; try { t8 = new T(); t8 = t; } finally { F0(t8); r8 = t8; } return r8; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); // Ideally, there should not be a warning for 2 or 4 because the return // statements are only executed when no exceptions are thrown. comp.VerifyDiagnostics( // (19,23): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F0(T t)'. // if (b) F0(t2); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void C<T>.F0(T t)").WithLocation(19, 23), // (22,16): warning CS8603: Possible null reference return. // return r2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "r2").WithLocation(22, 16), // (35,23): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F0(T t)'. // if (b) F0(t3); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void C<T>.F0(T t)").WithLocation(35, 23), // (38,16): warning CS8603: Possible null reference return. // return r3; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "r3").WithLocation(38, 16), // (51,23): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F0(T t)'. // if (b) F0(t4); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t4").WithArguments("t", "void C<T>.F0(T t)").WithLocation(51, 23), // (54,16): warning CS8603: Possible null reference return. // return r4; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "r4").WithLocation(54, 16), // (83,23): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F0(T t)'. // if (b) F0(t7); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t7").WithArguments("t", "void C<T>.F0(T t)").WithLocation(83, 23), // (86,16): warning CS8603: Possible null reference return. // return r7; // 8 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "r7").WithLocation(86, 16)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_01() { var source = @"#nullable enable class Program { static T F01<T>() => default(T); static T F02<T>() where T : class => default(T); static T F03<T>() where T : struct => default(T); static T F04<T>() where T : notnull => default(T); static T F05<T, U>() where U : T => default(U); static T F06<T, U>() where U : class, T => default(U); static T F07<T, U>() where U : struct, T => default(U); static T F08<T, U>() where U : notnull, T => default(U); static T F09<T>() => (T)default(T); static T F10<T>() where T : class => (T)default(T); static T F11<T>() where T : struct => (T)default(T); static T F12<T>() where T : notnull => (T)default(T); static T F13<T, U>() where U : T => (T)default(U); static T F14<T, U>() where U : class, T => (T)default(U); static T F15<T, U>() where U : struct, T => (T)default(U); static T F16<T, U>() where U : notnull, T => (T)default(U); static U F17<T, U>() where U : T => (U)default(T); static U F18<T, U>() where U : class, T => (U)default(T); static U F19<T, U>() where U : struct, T => (U)default(T); static U F20<T, U>() where U : notnull, T => (U)default(T); static U F21<T, U>() => (U)(object)default(T); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,26): warning CS8603: Possible null reference return. // static T F01<T>() => default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(4, 26), // (5,42): warning CS8603: Possible null reference return. // static T F02<T>() where T : class => default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(5, 42), // (7,44): warning CS8603: Possible null reference return. // static T F04<T>() where T : notnull => default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(7, 44), // (8,41): warning CS8603: Possible null reference return. // static T F05<T, U>() where U : T => default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(U)").WithLocation(8, 41), // (9,48): warning CS8603: Possible null reference return. // static T F06<T, U>() where U : class, T => default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(U)").WithLocation(9, 48), // (11,50): warning CS8603: Possible null reference return. // static T F08<T, U>() where U : notnull, T => default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(U)").WithLocation(11, 50), // (12,26): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F09<T>() => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(12, 26), // (12,26): warning CS8603: Possible null reference return. // static T F09<T>() => (T)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)default(T)").WithLocation(12, 26), // (13,42): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>() where T : class => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(13, 42), // (13,42): warning CS8603: Possible null reference return. // static T F10<T>() where T : class => (T)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)default(T)").WithLocation(13, 42), // (15,44): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F12<T>() where T : notnull => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(15, 44), // (15,44): warning CS8603: Possible null reference return. // static T F12<T>() where T : notnull => (T)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)default(T)").WithLocation(15, 44), // (16,41): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F13<T, U>() where U : T => (T)default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(U)").WithLocation(16, 41), // (16,41): warning CS8603: Possible null reference return. // static T F13<T, U>() where U : T => (T)default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)default(U)").WithLocation(16, 41), // (17,48): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F14<T, U>() where U : class, T => (T)default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(U)").WithLocation(17, 48), // (17,48): warning CS8603: Possible null reference return. // static T F14<T, U>() where U : class, T => (T)default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)default(U)").WithLocation(17, 48), // (19,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F16<T, U>() where U : notnull, T => (T)default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(U)").WithLocation(19, 50), // (19,50): warning CS8603: Possible null reference return. // static T F16<T, U>() where U : notnull, T => (T)default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)default(U)").WithLocation(19, 50), // (20,41): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F17<T, U>() where U : T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(20, 41), // (20,41): warning CS8603: Possible null reference return. // static U F17<T, U>() where U : T => (U)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)default(T)").WithLocation(20, 41), // (21,48): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F18<T, U>() where U : class, T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(21, 48), // (21,48): warning CS8603: Possible null reference return. // static U F18<T, U>() where U : class, T => (U)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)default(T)").WithLocation(21, 48), // (22,49): warning CS8605: Unboxing a possibly null value. // static U F19<T, U>() where U : struct, T => (U)default(T); Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)default(T)").WithLocation(22, 49), // (23,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F20<T, U>() where U : notnull, T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(23, 50), // (23,50): warning CS8603: Possible null reference return. // static U F20<T, U>() where U : notnull, T => (U)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)default(T)").WithLocation(23, 50), // (24,29): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>() => (U)(object)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)default(T)").WithLocation(24, 29), // (24,29): warning CS8603: Possible null reference return. // static U F21<T, U>() => (U)(object)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)(object)default(T)").WithLocation(24, 29), // (24,32): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>() => (U)(object)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)default(T)").WithLocation(24, 32)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_02() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F01<T>() => default(T); [return: MaybeNull]static T F02<T>() where T : class => default(T); [return: MaybeNull]static T F03<T>() where T : struct => default(T); [return: MaybeNull]static T F04<T>() where T : notnull => default(T); [return: MaybeNull]static T F05<T, U>() where U : T => default(U); [return: MaybeNull]static T F06<T, U>() where U : class, T => default(U); [return: MaybeNull]static T F07<T, U>() where U : struct, T => default(U); [return: MaybeNull]static T F08<T, U>() where U : notnull, T => default(U); [return: MaybeNull]static T F09<T>() => (T)default(T); [return: MaybeNull]static T F10<T>() where T : class => (T)default(T); [return: MaybeNull]static T F11<T>() where T : struct => (T)default(T); [return: MaybeNull]static T F12<T>() where T : notnull => (T)default(T); [return: MaybeNull]static T F13<T, U>() where U : T => (T)default(U); [return: MaybeNull]static T F14<T, U>() where U : class, T => (T)default(U); [return: MaybeNull]static T F15<T, U>() where U : struct, T => (T)default(U); [return: MaybeNull]static T F16<T, U>() where U : notnull, T => (T)default(U); [return: MaybeNull]static U F17<T, U>() where U : T => (U)default(T); [return: MaybeNull]static U F18<T, U>() where U : class, T => (U)default(T); [return: MaybeNull]static U F19<T, U>() where U : struct, T => (U)default(T); [return: MaybeNull]static U F20<T, U>() where U : notnull, T => (U)default(T); [return: MaybeNull]static U F21<T, U>() => (U)(object)default(T); }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (14,61): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F10<T>() where T : class => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(14, 61), // (22,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F18<T, U>() where U : class, T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(22, 67), // (23,68): warning CS8605: Unboxing a possibly null value. // [return: MaybeNull]static U F19<T, U>() where U : struct, T => (U)default(T); Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)default(T)").WithLocation(23, 68), // (25,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>() => (U)(object)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)default(T)").WithLocation(25, 51)); comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,45): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F09<T>() => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(13, 45), // (14,61): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F10<T>() where T : class => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(14, 61), // (16,63): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F12<T>() where T : notnull => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(16, 63), // (17,60): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F13<T, U>() where U : T => (T)default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(U)").WithLocation(17, 60), // (18,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F14<T, U>() where U : class, T => (T)default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(U)").WithLocation(18, 67), // (20,69): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F16<T, U>() where U : notnull, T => (T)default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(U)").WithLocation(20, 69), // (21,60): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F17<T, U>() where U : T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(21, 60), // (22,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F18<T, U>() where U : class, T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(22, 67), // (23,68): warning CS8605: Unboxing a possibly null value. // [return: MaybeNull]static U F19<T, U>() where U : struct, T => (U)default(T); Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)default(T)").WithLocation(23, 68), // (24,69): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F20<T, U>() where U : notnull, T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(24, 69), // (25,48): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>() => (U)(object)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)default(T)").WithLocation(25, 48), // (25,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>() => (U)(object)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)default(T)").WithLocation(25, 51)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_02A() { var source = @"#nullable enable class Program { static T? F02<T>() where T : class => default(T); static T? F10<T>() where T : class => (T)default(T); static U? F18<T, U>() where U : class, T => (U)default(T); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,43): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T? F10<T>() where T : class => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(5, 43), // (6,49): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U? F18<T, U>() where U : class, T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(6, 49)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_03() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static T F01<T>([AllowNull]T t) => t; static T F02<T>([AllowNull]T t) where T : class => t; static T F03<T>([AllowNull]T t) where T : struct => t; static T F04<T>([AllowNull]T t) where T : notnull => t; static T F05<T, U>([AllowNull]U u) where U : T => u; static T F06<T, U>([AllowNull]U u) where U : class, T => u; static T F07<T, U>([AllowNull]U u) where U : struct, T => u; static T F08<T, U>([AllowNull]U u) where U : notnull, T => u; static T F09<T>([AllowNull]T t) => (T)t; static T F10<T>([AllowNull]T t) where T : class => (T)t; static T F11<T>([AllowNull]T t) where T : struct => (T)t; static T F12<T>([AllowNull]T t) where T : notnull => (T)t; static T F13<T, U>([AllowNull]U u) where U : T => (T)u; static T F14<T, U>([AllowNull]U u) where U : class, T => (T)u; static T F15<T, U>([AllowNull]U u) where U : struct, T => (T)u; static T F16<T, U>([AllowNull]U u) where U : notnull, T => (T)u; static U F17<T, U>([AllowNull]T t) where U : T => (U)t; static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; static U F19<T, U>([AllowNull]T t) where U : struct, T => (U)t; static U F20<T, U>([AllowNull]T t) where U : notnull, T => (U)t; static U F21<T, U>([AllowNull]T t) => (U)(object)t; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,40): warning CS8603: Possible null reference return. // static T F01<T>([AllowNull]T t) => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(5, 40), // (6,56): warning CS8603: Possible null reference return. // static T F02<T>([AllowNull]T t) where T : class => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 56), // (8,58): warning CS8603: Possible null reference return. // static T F04<T>([AllowNull]T t) where T : notnull => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(8, 58), // (9,55): warning CS8603: Possible null reference return. // static T F05<T, U>([AllowNull]U u) where U : T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 55), // (10,62): warning CS8603: Possible null reference return. // static T F06<T, U>([AllowNull]U u) where U : class, T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 62), // (12,64): warning CS8603: Possible null reference return. // static T F08<T, U>([AllowNull]U u) where U : notnull, T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(12, 64), // (13,40): warning CS8603: Possible null reference return. // static T F09<T>([AllowNull]T t) => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(13, 40), // (14,56): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>([AllowNull]T t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(14, 56), // (14,56): warning CS8603: Possible null reference return. // static T F10<T>([AllowNull]T t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(14, 56), // (16,58): warning CS8603: Possible null reference return. // static T F12<T>([AllowNull]T t) where T : notnull => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(16, 58), // (17,55): warning CS8603: Possible null reference return. // static T F13<T, U>([AllowNull]U u) where U : T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(17, 55), // (18,62): warning CS8603: Possible null reference return. // static T F14<T, U>([AllowNull]U u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(18, 62), // (20,64): warning CS8603: Possible null reference return. // static T F16<T, U>([AllowNull]U u) where U : notnull, T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(20, 64), // (21,55): warning CS8603: Possible null reference return. // static U F17<T, U>([AllowNull]T t) where U : T => (U)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(21, 55), // (22,62): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 62), // (22,62): warning CS8603: Possible null reference return. // static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(22, 62), // (23,63): warning CS8605: Unboxing a possibly null value. // static U F19<T, U>([AllowNull]T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(23, 63), // (24,64): warning CS8603: Possible null reference return. // static U F20<T, U>([AllowNull]T t) where U : notnull, T => (U)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(24, 64), // (25,43): warning CS8603: Possible null reference return. // static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)(object)t").WithLocation(25, 43), // (25,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(25, 46)); comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,40): warning CS8603: Possible null reference return. // static T F01<T>([AllowNull]T t) => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(5, 40), // (6,56): warning CS8603: Possible null reference return. // static T F02<T>([AllowNull]T t) where T : class => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 56), // (8,58): warning CS8603: Possible null reference return. // static T F04<T>([AllowNull]T t) where T : notnull => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(8, 58), // (9,55): warning CS8603: Possible null reference return. // static T F05<T, U>([AllowNull]U u) where U : T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 55), // (10,62): warning CS8603: Possible null reference return. // static T F06<T, U>([AllowNull]U u) where U : class, T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 62), // (12,64): warning CS8603: Possible null reference return. // static T F08<T, U>([AllowNull]U u) where U : notnull, T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(12, 64), // (13,40): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F09<T>([AllowNull]T t) => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(13, 40), // (13,40): warning CS8603: Possible null reference return. // static T F09<T>([AllowNull]T t) => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(13, 40), // (14,56): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>([AllowNull]T t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(14, 56), // (14,56): warning CS8603: Possible null reference return. // static T F10<T>([AllowNull]T t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(14, 56), // (16,58): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F12<T>([AllowNull]T t) where T : notnull => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(16, 58), // (16,58): warning CS8603: Possible null reference return. // static T F12<T>([AllowNull]T t) where T : notnull => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(16, 58), // (17,55): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F13<T, U>([AllowNull]U u) where U : T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(17, 55), // (17,55): warning CS8603: Possible null reference return. // static T F13<T, U>([AllowNull]U u) where U : T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(17, 55), // (18,62): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F14<T, U>([AllowNull]U u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(18, 62), // (18,62): warning CS8603: Possible null reference return. // static T F14<T, U>([AllowNull]U u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(18, 62), // (20,64): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F16<T, U>([AllowNull]U u) where U : notnull, T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(20, 64), // (20,64): warning CS8603: Possible null reference return. // static T F16<T, U>([AllowNull]U u) where U : notnull, T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(20, 64), // (21,55): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F17<T, U>([AllowNull]T t) where U : T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(21, 55), // (21,55): warning CS8603: Possible null reference return. // static U F17<T, U>([AllowNull]T t) where U : T => (U)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(21, 55), // (22,62): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 62), // (22,62): warning CS8603: Possible null reference return. // static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(22, 62), // (23,63): warning CS8605: Unboxing a possibly null value. // static U F19<T, U>([AllowNull]T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(23, 63), // (24,64): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F20<T, U>([AllowNull]T t) where U : notnull, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(24, 64), // (24,64): warning CS8603: Possible null reference return. // static U F20<T, U>([AllowNull]T t) where U : notnull, T => (U)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(24, 64), // (25,43): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)t").WithLocation(25, 43), // (25,43): warning CS8603: Possible null reference return. // static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)(object)t").WithLocation(25, 43), // (25,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(25, 46)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_03A() { var source = @"#nullable enable class Program { static T F02<T>(T? t) where T : class => t; static T F06<T, U>(U? u) where U : class, T => u; static T F10<T>(T? t) where T : class => (T)t; static T F14<T, U>(U? u) where U : class, T => (T)u; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,46): warning CS8603: Possible null reference return. // static T F02<T>(T? t) where T : class => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(4, 46), // (5,52): warning CS8603: Possible null reference return. // static T F06<T, U>(U? u) where U : class, T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 52), // (6,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>(T? t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(6, 46), // (6,46): warning CS8603: Possible null reference return. // static T F10<T>(T? t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(6, 46), // (7,52): warning CS8603: Possible null reference return. // static T F14<T, U>(U? u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(7, 52)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,46): warning CS8603: Possible null reference return. // static T F02<T>(T? t) where T : class => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(4, 46), // (5,52): warning CS8603: Possible null reference return. // static T F06<T, U>(U? u) where U : class, T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 52), // (6,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>(T? t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(6, 46), // (6,46): warning CS8603: Possible null reference return. // static T F10<T>(T? t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(6, 46), // (7,52): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F14<T, U>(U? u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(7, 52), // (7,52): warning CS8603: Possible null reference return. // static T F14<T, U>(U? u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(7, 52)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_04() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F01<T>(T t) => t; [return: MaybeNull]static T F02<T>(T t) where T : class => t; [return: MaybeNull]static T F03<T>(T t) where T : struct => t; [return: MaybeNull]static T F04<T>(T t) where T : notnull => t; [return: MaybeNull]static T F05<T, U>(U u) where U : T => u; [return: MaybeNull]static T F06<T, U>(U u) where U : class, T => u; [return: MaybeNull]static T F07<T, U>(U u) where U : struct, T => u; [return: MaybeNull]static T F08<T, U>(U u) where U : notnull, T => u; [return: MaybeNull]static T F09<T>(T t) => (T)t; [return: MaybeNull]static T F10<T>(T t) where T : class => (T)t; [return: MaybeNull]static T F11<T>(T t) where T : struct => (T)t; [return: MaybeNull]static T F12<T>(T t) where T : notnull => (T)t; [return: MaybeNull]static T F13<T, U>(U u) where U : T => (T)u; [return: MaybeNull]static T F14<T, U>(U u) where U : class, T => (T)u; [return: MaybeNull]static T F15<T, U>(U u) where U : struct, T => (T)u; [return: MaybeNull]static T F16<T, U>(U u) where U : notnull, T => (T)u; [return: MaybeNull]static U F17<T, U>(T t) where U : T => (U)t; [return: MaybeNull]static U F18<T, U>(T t) where U : class, T => (U)t; [return: MaybeNull]static U F19<T, U>(T t) where U : struct, T => (U)t; [return: MaybeNull]static U F20<T, U>(T t) where U : notnull, T => (U)t; [return: MaybeNull]static U F21<T, U>(T t) => (U)(object)t; }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (22,70): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F18<T, U>(T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 70), // (23,71): warning CS8605: Unboxing a possibly null value. // [return: MaybeNull]static U F19<T, U>(T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(23, 71), // (25,54): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>(T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(25, 54)); comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (21,63): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F17<T, U>(T t) where U : T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(21, 63), // (22,70): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F18<T, U>(T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 70), // (23,71): warning CS8605: Unboxing a possibly null value. // [return: MaybeNull]static U F19<T, U>(T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(23, 71), // (24,72): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F20<T, U>(T t) where U : notnull, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(24, 72), // (25,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>(T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)t").WithLocation(25, 51), // (25,54): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>(T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(25, 54)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_04A() { var source = @"#nullable enable class Program { static T? F02<T>(T t) where T : class => t; static T? F10<T>(T t) where T : class => (T)t; static U? F18<T, U>(T t) where U : class, T => (U)t; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,52): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U? F18<T, U>(T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(6, 52)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_05() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F01<T>([AllowNull]T t) => t; [return: MaybeNull]static T F02<T>([AllowNull]T t) where T : class => t; [return: MaybeNull]static T F03<T>([AllowNull]T t) where T : struct => t; [return: MaybeNull]static T F04<T>([AllowNull]T t) where T : notnull => t; [return: MaybeNull]static T F05<T, U>([AllowNull]U u) where U : T => u; [return: MaybeNull]static T F06<T, U>([AllowNull]U u) where U : class, T => u; [return: MaybeNull]static T F07<T, U>([AllowNull]U u) where U : struct, T => u; [return: MaybeNull]static T F08<T, U>([AllowNull]U u) where U : notnull, T => u; [return: MaybeNull]static T F09<T>([AllowNull]T t) => (T)t; [return: MaybeNull]static T F10<T>([AllowNull]T t) where T : class => (T)t; [return: MaybeNull]static T F11<T>([AllowNull]T t) where T : struct => (T)t; [return: MaybeNull]static T F12<T>([AllowNull]T t) where T : notnull => (T)t; [return: MaybeNull]static T F13<T, U>([AllowNull]U u) where U : T => (T)u; [return: MaybeNull]static T F14<T, U>([AllowNull]U u) where U : class, T => (T)u; [return: MaybeNull]static T F15<T, U>([AllowNull]U u) where U : struct, T => (T)u; [return: MaybeNull]static T F16<T, U>([AllowNull]U u) where U : notnull, T => (T)u; [return: MaybeNull]static U F17<T, U>([AllowNull]T t) where U : T => (U)t; [return: MaybeNull]static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; [return: MaybeNull]static U F19<T, U>([AllowNull]T t) where U : struct, T => (U)t; [return: MaybeNull]static U F20<T, U>([AllowNull]T t) where U : notnull, T => (U)t; [return: MaybeNull]static U F21<T, U>([AllowNull]T t) => (U)(object)t; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (14,75): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F10<T>([AllowNull]T t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(14, 75), // (22,81): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 81), // (23,82): warning CS8605: Unboxing a possibly null value. // [return: MaybeNull]static U F19<T, U>([AllowNull]T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(23, 82), // (25,65): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(25, 65)); comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,59): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F09<T>([AllowNull]T t) => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(13, 59), // (14,75): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F10<T>([AllowNull]T t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(14, 75), // (16,77): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F12<T>([AllowNull]T t) where T : notnull => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(16, 77), // (17,74): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F13<T, U>([AllowNull]U u) where U : T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(17, 74), // (18,81): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F14<T, U>([AllowNull]U u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(18, 81), // (20,83): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F16<T, U>([AllowNull]U u) where U : notnull, T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(20, 83), // (21,74): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F17<T, U>([AllowNull]T t) where U : T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(21, 74), // (22,81): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 81), // (23,82): warning CS8605: Unboxing a possibly null value. // [return: MaybeNull]static U F19<T, U>([AllowNull]T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(23, 82), // (24,83): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F20<T, U>([AllowNull]T t) where U : notnull, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(24, 83), // (25,62): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)t").WithLocation(25, 62), // (25,65): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(25, 65)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_05A() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static T? F02<T>(T? t) where T : class => t; static T? F10<T>(T? t) where T : class => (T)t; static U? F18<T, U>([AllowNull]T t) where U : class, T => (U)t; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (6,47): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T? F10<T>(T? t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(6, 47), // (7,63): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U? F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(7, 63)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_06() { var source = @"#nullable enable class Program { static T F01<T>(dynamic? d) => d; static T F02<T>(dynamic? d) where T : class => d; static T F03<T>(dynamic? d) where T : struct => d; static T F04<T>(dynamic? d) where T : notnull => d; static T F09<T>(dynamic? d) => (T)d; static T F10<T>(dynamic? d) where T : class => (T)d; static T F11<T>(dynamic? d) where T : struct => (T)d; static T F12<T>(dynamic? d) where T : notnull => (T)d; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,36): warning CS8603: Possible null reference return. // static T F01<T>(dynamic? d) => d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "d").WithLocation(4, 36), // (5,52): warning CS8603: Possible null reference return. // static T F02<T>(dynamic? d) where T : class => d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "d").WithLocation(5, 52), // (7,54): warning CS8603: Possible null reference return. // static T F04<T>(dynamic? d) where T : notnull => d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "d").WithLocation(7, 54), // (8,36): warning CS8603: Possible null reference return. // static T F09<T>(dynamic? d) => (T)d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)d").WithLocation(8, 36), // (9,52): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>(dynamic? d) where T : class => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(9, 52), // (9,52): warning CS8603: Possible null reference return. // static T F10<T>(dynamic? d) where T : class => (T)d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)d").WithLocation(9, 52), // (11,54): warning CS8603: Possible null reference return. // static T F12<T>(dynamic? d) where T : notnull => (T)d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)d").WithLocation(11, 54)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,36): warning CS8603: Possible null reference return. // static T F01<T>(dynamic? d) => d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "d").WithLocation(4, 36), // (5,52): warning CS8603: Possible null reference return. // static T F02<T>(dynamic? d) where T : class => d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "d").WithLocation(5, 52), // (7,54): warning CS8603: Possible null reference return. // static T F04<T>(dynamic? d) where T : notnull => d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "d").WithLocation(7, 54), // (8,36): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F09<T>(dynamic? d) => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(8, 36), // (8,36): warning CS8603: Possible null reference return. // static T F09<T>(dynamic? d) => (T)d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)d").WithLocation(8, 36), // (9,52): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>(dynamic? d) where T : class => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(9, 52), // (9,52): warning CS8603: Possible null reference return. // static T F10<T>(dynamic? d) where T : class => (T)d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)d").WithLocation(9, 52), // (11,54): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F12<T>(dynamic? d) where T : notnull => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(11, 54), // (11,54): warning CS8603: Possible null reference return. // static T F12<T>(dynamic? d) where T : notnull => (T)d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)d").WithLocation(11, 54)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_07() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F01<T>(dynamic? d) => d; [return: MaybeNull]static T F02<T>(dynamic? d) where T : class => d; [return: MaybeNull]static T F03<T>(dynamic? d) where T : struct => d; [return: MaybeNull]static T F04<T>(dynamic? d) where T : notnull => d; [return: MaybeNull]static T F09<T>(dynamic? d) => (T)d; [return: MaybeNull]static T F10<T>(dynamic? d) where T : class => (T)d; [return: MaybeNull]static T F11<T>(dynamic? d) where T : struct => (T)d; [return: MaybeNull]static T F12<T>(dynamic? d) where T : notnull => (T)d; }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,71): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F10<T>(dynamic? d) where T : class => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(10, 71)); comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,55): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F09<T>(dynamic? d) => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(9, 55), // (10,71): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F10<T>(dynamic? d) where T : class => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(10, 71), // (12,73): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F12<T>(dynamic? d) where T : notnull => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(12, 73)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_08() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static dynamic F01<T>([AllowNull]T t) => t; static dynamic F02<T>([AllowNull]T t) where T : class => t; static dynamic F03<T>([AllowNull]T t) where T : struct => t; static dynamic F04<T>([AllowNull]T t) where T : notnull => t; static dynamic F09<T>([AllowNull]T t) => (dynamic)t; static dynamic F10<T>([AllowNull]T t) where T : class => (dynamic)t; static dynamic F11<T>([AllowNull]T t) where T : struct => (dynamic)t; static dynamic F12<T>([AllowNull]T t) where T : notnull => (dynamic)t; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,46): warning CS8603: Possible null reference return. // static dynamic F01<T>([AllowNull]T t) => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(5, 46), // (6,62): warning CS8603: Possible null reference return. // static dynamic F02<T>([AllowNull]T t) where T : class => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 62), // (8,64): warning CS8603: Possible null reference return. // static dynamic F04<T>([AllowNull]T t) where T : notnull => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(8, 64), // (9,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // static dynamic F09<T>([AllowNull]T t) => (dynamic)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(dynamic)t").WithLocation(9, 46), // (9,46): warning CS8603: Possible null reference return. // static dynamic F09<T>([AllowNull]T t) => (dynamic)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(dynamic)t").WithLocation(9, 46), // (10,62): warning CS8600: Converting null literal or possible null value to non-nullable type. // static dynamic F10<T>([AllowNull]T t) where T : class => (dynamic)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(dynamic)t").WithLocation(10, 62), // (10,62): warning CS8603: Possible null reference return. // static dynamic F10<T>([AllowNull]T t) where T : class => (dynamic)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(dynamic)t").WithLocation(10, 62), // (12,64): warning CS8600: Converting null literal or possible null value to non-nullable type. // static dynamic F12<T>([AllowNull]T t) where T : notnull => (dynamic)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(dynamic)t").WithLocation(12, 64), // (12,64): warning CS8603: Possible null reference return. // static dynamic F12<T>([AllowNull]T t) where T : notnull => (dynamic)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(dynamic)t").WithLocation(12, 64)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_09() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static dynamic? F01<T>([AllowNull]T t) => t; static dynamic? F02<T>([AllowNull]T t) where T : class => t; static dynamic? F03<T>([AllowNull]T t) where T : struct => t; static dynamic? F04<T>([AllowNull]T t) where T : notnull => t; static dynamic? F09<T>([AllowNull]T t) => (dynamic?)t; static dynamic? F10<T>([AllowNull]T t) where T : class => (dynamic?)t; static dynamic? F11<T>([AllowNull]T t) where T : struct => (dynamic?)t; static dynamic? F12<T>([AllowNull]T t) where T : notnull => (dynamic?)t; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_01() { var source = @"#nullable enable using System; using System.Diagnostics.CodeAnalysis; class C<T> where T : class? { public C(T x) => f = x; T f; T P1 { get => f; set => f = value; } [AllowNull] T P2 { get => f; set => f = value ?? throw new ArgumentNullException(); } [MaybeNull] T P3 { get => default!; set => f = value; } void M1() { P1 = null; // 1 P2 = null; P3 = null; // 2 } void M2() { f = P1; f = P2; f = P3; // 3 } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // P1 = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 14), // (15,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // P3 = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 14), // (21,13): warning CS8601: Possible null reference assignment. // f = P3; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "P3").WithLocation(21, 13)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_02() { var source = @"#nullable enable class C<T> { internal T F = default!; static C<T> F0() => throw null!; static T F1() { T t = default(T); return t; // 1 } static void F2() { var t = default(T); F0().F = t; // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t = default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(T)").WithLocation(8, 15), // (9,16): warning CS8603: Possible null reference return. // return t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(9, 16), // (14,18): warning CS8601: Possible null reference assignment. // F0().F = t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(14, 18)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_03() { var source = @"#nullable enable class Program { static void M<T>() where T : notnull { if (default(T) == null) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_04() { var source = @"#nullable enable #pragma warning disable 649 using System.Diagnostics.CodeAnalysis; class C<T> { [MaybeNull]T F = default!; static void M(C<T> x, C<T> y) { if (x.F == null) return; x.F.ToString(); y.F.ToString(); // 1 } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(11, 9)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_05() { var source = @"#nullable enable class Program { static void M<T>() where T : notnull { var t = default(T); t.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(7, 9)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_06() { var source = @"#nullable enable class Program { static void M<T>() where T : notnull { T t = default; t.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(6, 15), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(7, 9)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_07() { var source = @"#nullable enable class Program { static void M<T>(T t) where T : notnull { if (t == null) { } t.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(7, 9)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_08() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F<T>() => throw null!; static T1 F1<T1>() { return F<T1>(); // 1 } static T2 F2<T2>() where T2 : notnull { return F<T2>(); // 2 } static T3 F3<T3>() where T3 : class { return F<T3>(); // 3 } static T4 F4<T4>() where T4 : class? { return F<T4>(); // 4 } static T5 F5<T5>() where T5 : struct { return F<T5>(); } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (8,16): warning CS8603: Possible null reference return. // return F<T1>(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "F<T1>()").WithLocation(8, 16), // (12,16): warning CS8603: Possible null reference return. // return F<T2>(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "F<T2>()").WithLocation(12, 16), // (16,16): warning CS8603: Possible null reference return. // return F<T3>(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "F<T3>()").WithLocation(16, 16), // (20,16): warning CS8603: Possible null reference return. // return F<T4>(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "F<T4>()").WithLocation(20, 16)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_09() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F<T>() => throw null!; [return: MaybeNull]static T1 F1<T1>() { return F<T1>(); } [return: MaybeNull]static T2 F2<T2>() where T2 : notnull { return F<T2>(); } [return: MaybeNull]static T3 F3<T3>() where T3 : class { return F<T3>(); } [return: MaybeNull]static T4 F4<T4>() where T4 : class? { return F<T4>(); } [return: MaybeNull]static T5 F5<T5>() where T5 : struct { return F<T5>(); } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_10() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F<T>() => throw null!; static T1 F1<T1>() { T1 t1 = F<T1>(); return t1; } static T2 F2<T2>() where T2 : notnull { T2 t2 = F<T2>(); return t2; } static T3 F3<T3>() where T3 : class { T3 t3 = F<T3>(); return t3; } static T4 F4<T4>() where T4 : class? { T4 t4 = F<T4>(); return t4; } static T5 F5<T5>() where T5 : struct { T5 t5 = F<T5>(); return t5; } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (8,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T1 t1 = F<T1>(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F<T1>()").WithLocation(8, 17), // (9,16): warning CS8603: Possible null reference return. // return t1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(9, 16), // (13,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T2 t2 = F<T2>(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F<T2>()").WithLocation(13, 17), // (14,16): warning CS8603: Possible null reference return. // return t2; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(14, 16), // (18,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T3 t3 = F<T3>(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F<T3>()").WithLocation(18, 17), // (19,16): warning CS8603: Possible null reference return. // return t3; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t3").WithLocation(19, 16), // (23,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T4 t4 = F<T4>(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F<T4>()").WithLocation(23, 17), // (24,16): warning CS8603: Possible null reference return. // return t4; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t4").WithLocation(24, 16)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_11() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F<T>() => throw null!; static T M<T>() where T : notnull { var t = F<T>(); return t; // 1 } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,16): warning CS8603: Possible null reference return. // return t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(9, 16)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_12() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static T Identity<T>(T t) => t; [return: MaybeNull]static T F<T>() => throw null!; static T F1<T>() => Identity(F<T>()); // 1 static T F2<T>() where T : notnull => Identity(F<T>()); // 2 static T F3<T>() where T : class => Identity(F<T>()); // 3 static T F4<T>() where T : class? => Identity(F<T>()); // 4 static T F5<T>() where T : struct => Identity(F<T>()); }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (7,25): warning CS8603: Possible null reference return. // static T F1<T>() => Identity(F<T>()); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Identity(F<T>())").WithLocation(7, 25), // (8,43): warning CS8603: Possible null reference return. // static T F2<T>() where T : notnull => Identity(F<T>()); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Identity(F<T>())").WithLocation(8, 43), // (9,41): warning CS8603: Possible null reference return. // static T F3<T>() where T : class => Identity(F<T>()); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Identity(F<T>())").WithLocation(9, 41), // (10,42): warning CS8603: Possible null reference return. // static T F4<T>() where T : class? => Identity(F<T>()); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Identity(F<T>())").WithLocation(10, 42)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_13() { var source = @"#nullable enable class Program { static void F1<T>(object? x1) { var y1 = (T)x1; _ = y1.ToString(); // 1 } static void F2<T>(object? x2) { var y2 = (T)x2!; _ = y2.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // var y1 = (T)x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)x1").WithLocation(6, 18), // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = y1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(7, 13)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_14() { var source = @"#nullable enable #pragma warning disable 414 using System.Diagnostics.CodeAnalysis; class C<T> { T F1 = default; [AllowNull]T F2 = default; [MaybeNull]T F3 = default; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (6,12): warning CS8601: Possible null reference assignment. // T F1 = default; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(6, 12), // (8,23): warning CS8601: Possible null reference assignment. // [MaybeNull]T F3 = default; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(8, 23)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_15() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class C<T> { T F1 = default!; [AllowNull]T F2 = default!; [MaybeNull]T F3 = default!; void M1(T x, [AllowNull]T y) { F1 = x; F2 = x; F3 = x; F1 = y; // 1 F2 = y; F3 = y; // 2 } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,14): warning CS8601: Possible null reference assignment. // F1 = y; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(13, 14), // (15,14): warning CS8601: Possible null reference assignment. // F3 = y; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(15, 14)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_16() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static T F1<T, U>(bool b, T t, U u) where U : T => b ? t : u; static T F2<T, U>(bool b, T t, [AllowNull]U u) where U : T => b ? t : u; static T F3<T, U>(bool b, [AllowNull]T t, U u) where U : T => b ? t : u; static T F4<T, U>(bool b, [AllowNull]T t, [AllowNull]U u) where U : T => b ? t : u; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (6,67): warning CS8603: Possible null reference return. // static T F2<T, U>(bool b, T t, [AllowNull]U u) where U : T => b ? t : u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? t : u").WithLocation(6, 67), // (7,67): warning CS8603: Possible null reference return. // static T F3<T, U>(bool b, [AllowNull]T t, U u) where U : T => b ? t : u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? t : u").WithLocation(7, 67), // (8,78): warning CS8603: Possible null reference return. // static T F4<T, U>(bool b, [AllowNull]T t, [AllowNull]U u) where U : T => b ? t : u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? t : u").WithLocation(8, 78)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_17() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static T F0<T>(T t) => t ?? default; static T F1<T>(T t) => t ?? default(T); static T F2<T, U>(T t) where U : T => t ?? default(U); static T F3<T, U>(T t, U u) where U : T => t ?? u; static T F4<T, U>(T t, [AllowNull]U u) where U : T => t ?? u; static T F5<T, U>([AllowNull]T t, U u) where U : T => t ?? u; static T F6<T, U>([AllowNull]T t, [AllowNull]U u) where U : T => t ?? u; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,28): warning CS8603: Possible null reference return. // static T F0<T>(T t) => t ?? default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ?? default").WithLocation(5, 28), // (6,28): warning CS8603: Possible null reference return. // static T F1<T>(T t) => t ?? default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ?? default(T)").WithLocation(6, 28), // (7,43): warning CS8603: Possible null reference return. // static T F2<T, U>(T t) where U : T => t ?? default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ?? default(U)").WithLocation(7, 43), // (9,59): warning CS8603: Possible null reference return. // static T F4<T, U>(T t, [AllowNull]U u) where U : T => t ?? u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ?? u").WithLocation(9, 59), // (11,70): warning CS8603: Possible null reference return. // static T F6<T, U>([AllowNull]T t, [AllowNull]U u) where U : T => t ?? u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ?? u").WithLocation(11, 70)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_18() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static T F0<T>(T t) => t ??= default; static T F1<T>(T t) => t ??= default(T); static T F2<T, U>(T t) where U : T => t ??= default(U); static T F3<T, U>(T t, U u) where U : T => t ??= u; static T F4<T, U>(T t, [AllowNull]U u) where U : T => t ??= u; static T F5<T, U>([AllowNull]T t, U u) where U : T => t ??= u; static T F6<T, U>([AllowNull]T t, [AllowNull]U u) where U : T => t ??= u; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,28): warning CS8603: Possible null reference return. // static T F0<T>(T t) => t ??= default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ??= default").WithLocation(5, 28), // (5,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F0<T>(T t) => t ??= default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(5, 34), // (6,28): warning CS8603: Possible null reference return. // static T F1<T>(T t) => t ??= default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ??= default(T)").WithLocation(6, 28), // (6,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F1<T>(T t) => t ??= default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(T)").WithLocation(6, 34), // (7,43): warning CS8603: Possible null reference return. // static T F2<T, U>(T t) where U : T => t ??= default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ??= default(U)").WithLocation(7, 43), // (7,49): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F2<T, U>(T t) where U : T => t ??= default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(U)").WithLocation(7, 49), // (9,59): warning CS8603: Possible null reference return. // static T F4<T, U>(T t, [AllowNull]U u) where U : T => t ??= u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ??= u").WithLocation(9, 59), // (9,65): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F4<T, U>(T t, [AllowNull]U u) where U : T => t ??= u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(9, 65), // (11,70): warning CS8603: Possible null reference return. // static T F6<T, U>([AllowNull]T t, [AllowNull]U u) where U : T => t ??= u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ??= u").WithLocation(11, 70), // (11,76): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F6<T, U>([AllowNull]T t, [AllowNull]U u) where U : T => t ??= u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(11, 76)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_19() { var source = @"#nullable enable using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; class Program { static IEnumerable<T> F<T>(T t1, [AllowNull]T t2) { yield return default(T); yield return t1; yield return t2; } static IEnumerator<T> F<T, U>(U u1, [AllowNull]U u2) where U : T { yield return default(U); yield return u1; yield return u2; } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (8,22): warning CS8603: Possible null reference return. // yield return default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(8, 22), // (10,22): warning CS8603: Possible null reference return. // yield return t2; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(10, 22), // (14,22): warning CS8603: Possible null reference return. // yield return default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(U)").WithLocation(14, 22), // (16,22): warning CS8603: Possible null reference return. // yield return u2; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u2").WithLocation(16, 22)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_20() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull] static T F<T>() => default; static void F1<T>() { _ = F<T>(); } static void F2<T>() where T : class { _ = F<T>(); } static void F3<T>() where T : struct { _ = F<T>(); } static void F4<T>() where T : notnull { _ = F<T>(); } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] [WorkItem(39888, "https://github.com/dotnet/roslyn/issues/39888")] public void MaybeNullT_21() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F1<T>(bool b, T t) => b switch { false => t, _ => default }; [return: MaybeNull]static T F2<T>(bool b, T t) => b switch { false => default, _ => t }; [return: MaybeNull]static T F3<T>(bool b, T t) where T : class => b switch { false => t, _ => default }; [return: MaybeNull]static T F4<T>(bool b, T t) where T : class => b switch { false => default, _ => t }; [return: MaybeNull]static T F5<T>(bool b, T t) where T : struct => b switch { false => t, _ => default }; [return: MaybeNull]static T F6<T>(bool b, T t) where T : struct => b switch { false => default, _ => t }; [return: MaybeNull]static T F7<T>(bool b, T t) where T : notnull => b switch { false => t, _ => default }; [return: MaybeNull]static T F8<T>(bool b, T t) where T : notnull => b switch { false => default, _ => t }; }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] [WorkItem(39888, "https://github.com/dotnet/roslyn/issues/39888")] public void MaybeNullT_21A() { var source = @"#nullable enable class Program { static T F1<T>(bool b, T t) => b switch { false => t, _ => default }; static T F2<T>(bool b, T t) => b switch { false => default, _ => t }; static T F3<T>(bool b, T t) where T : class => b switch { false => t, _ => default }; static T F4<T>(bool b, T t) where T : class => b switch { false => default, _ => t }; static T F5<T>(bool b, T t) where T : struct => b switch { false => t, _ => default }; static T F6<T>(bool b, T t) where T : struct => b switch { false => default, _ => t }; static T F7<T>(bool b, T t) where T : notnull => b switch { false => t, _ => default }; static T F8<T>(bool b, T t) where T : notnull => b switch { false => default, _ => t }; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,36): warning CS8603: Possible null reference return. // static T F1<T>(bool b, T t) => b switch { false => t, _ => default }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { false => t, _ => default }").WithLocation(4, 36), // (5,36): warning CS8603: Possible null reference return. // static T F2<T>(bool b, T t) => b switch { false => default, _ => t }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { false => default, _ => t }").WithLocation(5, 36), // (6,52): warning CS8603: Possible null reference return. // static T F3<T>(bool b, T t) where T : class => b switch { false => t, _ => default }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { false => t, _ => default }").WithLocation(6, 52), // (7,52): warning CS8603: Possible null reference return. // static T F4<T>(bool b, T t) where T : class => b switch { false => default, _ => t }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { false => default, _ => t }").WithLocation(7, 52), // (10,54): warning CS8603: Possible null reference return. // static T F7<T>(bool b, T t) where T : notnull => b switch { false => t, _ => default }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { false => t, _ => default }").WithLocation(10, 54), // (11,54): warning CS8603: Possible null reference return. // static T F8<T>(bool b, T t) where T : notnull => b switch { false => default, _ => t }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { false => default, _ => t }").WithLocation(11, 54)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_21B() { var source = @"#nullable enable class Program { static T F1<T>(T t) => new[] { t, default }[0]; static T F2<T>(T t) => new[] { default, t }[0]; static T F3<T>(T t) where T : class => new[] { t, default }[0]; static T F4<T>(T t) where T : class => new[] { default, t }[0]; static T F5<T>(T t) where T : struct => new[] { t, default }[0]; static T F6<T>(T t) where T : struct => new[] { default, t }[0]; static T F7<T>(T t) where T : notnull => new[] { t, default }[0]; static T F8<T>(T t) where T : notnull => new[] { default, t }[0]; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,28): warning CS8603: Possible null reference return. // static T F1<T>(T t) => new[] { t, default }[0]; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { t, default }[0]").WithLocation(4, 28), // (5,28): warning CS8603: Possible null reference return. // static T F2<T>(T t) => new[] { default, t }[0]; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { default, t }[0]").WithLocation(5, 28), // (6,44): warning CS8603: Possible null reference return. // static T F3<T>(T t) where T : class => new[] { t, default }[0]; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { t, default }[0]").WithLocation(6, 44), // (7,44): warning CS8603: Possible null reference return. // static T F4<T>(T t) where T : class => new[] { default, t }[0]; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { default, t }[0]").WithLocation(7, 44), // (10,46): warning CS8603: Possible null reference return. // static T F7<T>(T t) where T : notnull => new[] { t, default }[0]; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { t, default }[0]").WithLocation(10, 46), // (11,46): warning CS8603: Possible null reference return. // static T F8<T>(T t) where T : notnull => new[] { default, t }[0]; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { default, t }[0]").WithLocation(11, 46)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_21C() { var source = @"#nullable enable class Program { static T F1<T>(bool b, T t) => b ? t : default; static T F2<T>(bool b, T t) => b ? default : t; static T F3<T>(bool b, T t) where T : class => b ? t : default; static T F4<T>(bool b, T t) where T : class => b ? default : t; static T F5<T>(bool b, T t) where T : struct => b ? t : default; static T F6<T>(bool b, T t) where T : struct => b ? default : t; static T F7<T>(bool b, T t) where T : notnull => b ? t : default; static T F8<T>(bool b, T t) where T : notnull => b ? default : t; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,36): warning CS8603: Possible null reference return. // static T F1<T>(bool b, T t) => b ? t : default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? t : default").WithLocation(4, 36), // (5,36): warning CS8603: Possible null reference return. // static T F2<T>(bool b, T t) => b ? default : t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? default : t").WithLocation(5, 36), // (6,52): warning CS8603: Possible null reference return. // static T F3<T>(bool b, T t) where T : class => b ? t : default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? t : default").WithLocation(6, 52), // (7,52): warning CS8603: Possible null reference return. // static T F4<T>(bool b, T t) where T : class => b ? default : t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? default : t").WithLocation(7, 52), // (10,54): warning CS8603: Possible null reference return. // static T F7<T>(bool b, T t) where T : notnull => b ? t : default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? t : default").WithLocation(10, 54), // (11,54): warning CS8603: Possible null reference return. // static T F8<T>(bool b, T t) where T : notnull => b ? default : t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? default : t").WithLocation(11, 54)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_21D() { var source = @"#nullable enable using System; class Program { static Func<T> F1<T>(bool b, T t) => () => { if (b) return t; return default; }; static Func<T> F2<T>(bool b, T t) => () => { if (b) return default; return t; }; static Func<T> F3<T>(bool b, T t) where T : class => () => { if (b) return t; return default; }; static Func<T> F4<T>(bool b, T t) where T : class => () => { if (b) return default; return t; }; static Func<T> F5<T>(bool b, T t) where T : struct => () => { if (b) return t; return default; }; static Func<T> F6<T>(bool b, T t) where T : struct => () => { if (b) return default; return t; }; static Func<T> F7<T>(bool b, T t) where T : notnull => () => { if (b) return t; return default; }; static Func<T> F8<T>(bool b, T t) where T : notnull => () => { if (b) return default; return t; }; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,74): warning CS8603: Possible null reference return. // static Func<T> F1<T>(bool b, T t) => () => { if (b) return t; return default; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(5, 74), // (6,64): warning CS8603: Possible null reference return. // static Func<T> F2<T>(bool b, T t) => () => { if (b) return default; return t; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(6, 64), // (7,90): warning CS8603: Possible null reference return. // static Func<T> F3<T>(bool b, T t) where T : class => () => { if (b) return t; return default; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(7, 90), // (8,80): warning CS8603: Possible null reference return. // static Func<T> F4<T>(bool b, T t) where T : class => () => { if (b) return default; return t; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(8, 80), // (11,92): warning CS8603: Possible null reference return. // static Func<T> F7<T>(bool b, T t) where T : notnull => () => { if (b) return t; return default; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(11, 92), // (12,82): warning CS8603: Possible null reference return. // static Func<T> F8<T>(bool b, T t) where T : notnull => () => { if (b) return default; return t; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(12, 82)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_22() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; class Program { static async Task<T> F<T>(int i, T x, [AllowNull]T y) { await Task.Delay(0); switch (i) { case 0: return default(T); case 1: return x; default: return y; } } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,24): warning CS8603: Possible null reference return. // case 0: return default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(11, 24), // (13,25): warning CS8603: Possible null reference return. // default: return y; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y").WithLocation(13, 25)); } [Fact] [WorkItem(37362, "https://github.com/dotnet/roslyn/issues/37362")] public void MaybeNullT_23() { var source = @"#nullable enable class Program { static T Get<T>() { throw new System.NotImplementedException(); } static T F1<T>(bool b) => b ? Get<T>() : default; static T F2<T>(bool b) => b ? default : Get<T>(); static T F3<T>() => false ? Get<T>() : default; static T F4<T>() => true ? Get<T>() : default; static T F5<T>() => false ? default : Get<T>(); static T F6<T>() => true ? default : Get<T>(); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,31): warning CS8603: Possible null reference return. // static T F1<T>(bool b) => b ? Get<T>() : default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? Get<T>() : default").WithLocation(8, 31), // (9,31): warning CS8603: Possible null reference return. // static T F2<T>(bool b) => b ? default : Get<T>(); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? default : Get<T>()").WithLocation(9, 31), // (10,25): warning CS8603: Possible null reference return. // static T F3<T>() => false ? Get<T>() : default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "false ? Get<T>() : default").WithLocation(10, 25), // (13,25): warning CS8603: Possible null reference return. // static T F6<T>() => true ? default : Get<T>(); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "true ? default : Get<T>()").WithLocation(13, 25)); } [Fact] [WorkItem(39926, "https://github.com/dotnet/roslyn/issues/39926")] public void MaybeNullT_24() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class C<T> { [MaybeNull]T P1 { get; } = default; // 1 [AllowNull]T P2 { get; } = default; [MaybeNull, AllowNull]T P3 { get; } = default; [MaybeNull]T P4 { get; set; } = default; // 2 [AllowNull]T P5 { get; set; } = default; [MaybeNull, AllowNull]T P6 { get; set; } = default; C([AllowNull]T t) { P1 = t; // 3 P2 = t; P3 = t; P4 = t; // 4 P5 = t; P6 = t; } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,32): warning CS8601: Possible null reference assignment. // [MaybeNull]T P1 { get; } = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(5, 32), // (8,37): warning CS8601: Possible null reference assignment. // [MaybeNull]T P4 { get; set; } = default; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(8, 37), // (13,14): warning CS8601: Possible null reference assignment. // P1 = t; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(13, 14), // (16,14): warning CS8601: Possible null reference assignment. // P4 = t; // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(16, 14)); } [Fact] public void MaybeNullT_25() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class C<T> { [NotNull]T P1 { get; } = default; // 1 [DisallowNull]T P2 { get; } = default; // 2 [NotNull, DisallowNull]T P3 { get; } = default; // 3 [NotNull]T P4 { get; set; } = default; // 4 [DisallowNull]T P5 { get; set; } = default; // 5 [NotNull, DisallowNull]T P6 { get; set; } = default; // 6 C([AllowNull]T t) { P1 = t; // 7 P2 = t; // 8 P3 = t; // 9 P4 = t; // 10 P5 = t; // 11 P6 = t; // 12 } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,30): warning CS8601: Possible null reference assignment. // [NotNull]T P1 { get; } = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(5, 30), // (6,35): warning CS8601: Possible null reference assignment. // [DisallowNull]T P2 { get; } = default; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(6, 35), // (7,44): warning CS8601: Possible null reference assignment. // [NotNull, DisallowNull]T P3 { get; } = default; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(7, 44), // (8,35): warning CS8601: Possible null reference assignment. // [NotNull]T P4 { get; set; } = default; // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(8, 35), // (9,40): warning CS8601: Possible null reference assignment. // [DisallowNull]T P5 { get; set; } = default; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(9, 40), // (10,49): warning CS8601: Possible null reference assignment. // [NotNull, DisallowNull]T P6 { get; set; } = default; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(10, 49), // (13,14): warning CS8601: Possible null reference assignment. // P1 = t; // 7 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(13, 14), // (14,14): warning CS8601: Possible null reference assignment. // P2 = t; // 8 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(14, 14), // (15,14): warning CS8601: Possible null reference assignment. // P3 = t; // 9 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(15, 14), // (16,14): warning CS8601: Possible null reference assignment. // P4 = t; // 10 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(16, 14), // (17,14): warning CS8601: Possible null reference assignment. // P5 = t; // 11 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(17, 14), // (18,14): warning CS8601: Possible null reference assignment. // P6 = t; // 12 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(18, 14)); } [Fact] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void MaybeNullT_26() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>( [AllowNull]T x, T y) { y = x; } static void F2<T>( [AllowNull]T x, [AllowNull]T y) { y = x; } static void F3<T>( [AllowNull]T x, [DisallowNull]T y) { y = x; } static void F4<T>( [AllowNull]T x, [MaybeNull]T y) { y = x; } static void F5<T>( [AllowNull]T x, [NotNull]T y) { y = x; } // 1 static void F6<T>( T x, T y) { y = x; } static void F7<T>( T x, [AllowNull]T y) { y = x; } static void F8<T>( T x, [DisallowNull]T y) { y = x; } static void F9<T>( T x, [MaybeNull]T y) { y = x; } static void FA<T>( T x, [NotNull]T y) { y = x; } // 2 static void FB<T>([DisallowNull]T x, T y) { y = x; } static void FC<T>([DisallowNull]T x, [AllowNull]T y) { y = x; } static void FD<T>([DisallowNull]T x, [DisallowNull]T y) { y = x; } static void FE<T>([DisallowNull]T x, [MaybeNull]T y) { y = x; } static void FF<T>([DisallowNull]T x, [NotNull]T y) { y = x; } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }); // DisallowNull on a parameter also means null is disallowed in that parameter on the inside of the method comp.VerifyDiagnostics( // (5,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F1<T>( [AllowNull]T x, T y) { y = x; } Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(5, 67), // (6,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F2<T>( [AllowNull]T x, [AllowNull]T y) { y = x; } Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(6, 67), // (7,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F3<T>( [AllowNull]T x, [DisallowNull]T y) { y = x; } Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(7, 67), // (9,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F5<T>( [AllowNull]T x, [NotNull]T y) { y = x; } // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(9, 67), // (9,70): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F5<T>( [AllowNull]T x, [NotNull]T y) { y = x; } // 1 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(9, 70), // (14,70): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void FA<T>( T x, [NotNull]T y) { y = x; } // 2 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(14, 70)); } [Fact] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void MaybeNullT_27() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>( [AllowNull]T x, out T y) { y = x; } // 1 static void F2<T>( [AllowNull]T x, [AllowNull]out T y) { y = x; } // 2 static void F3<T>( [AllowNull]T x, [DisallowNull]out T y) { y = x; } // 3 static void F4<T>( [AllowNull]T x, [MaybeNull]out T y) { y = x; } static void F5<T>( [AllowNull]T x, [NotNull]out T y) { y = x; } // 4 static void F6<T>( T x, out T y) { y = x; } static void F7<T>( T x, [AllowNull]out T y) { y = x; } static void F8<T>( T x, [DisallowNull]out T y) { y = x; } static void F9<T>( T x, [MaybeNull]out T y) { y = x; } static void FA<T>( T x, [NotNull]out T y) { y = x; } // 5 static void FB<T>([DisallowNull]T x, out T y) { y = x; } static void FC<T>([DisallowNull]T x, [AllowNull]out T y) { y = x; } static void FD<T>([DisallowNull]T x, [DisallowNull]out T y) { y = x; } static void FE<T>([DisallowNull]T x, [MaybeNull]out T y) { y = x; } static void FF<T>([DisallowNull]T x, [NotNull]out T y) { y = x; } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,71): warning CS8601: Possible null reference assignment. // static void F1<T>( [AllowNull]T x, out T y) { y = x; } // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(5, 71), // (6,71): warning CS8601: Possible null reference assignment. // static void F2<T>( [AllowNull]T x, [AllowNull]out T y) { y = x; } // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(6, 71), // (7,71): warning CS8601: Possible null reference assignment. // static void F3<T>( [AllowNull]T x, [DisallowNull]out T y) { y = x; } // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(7, 71), // (9,71): warning CS8601: Possible null reference assignment. // static void F5<T>( [AllowNull]T x, [NotNull]out T y) { y = x; } // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(9, 71), // (9,74): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F5<T>( [AllowNull]T x, [NotNull]out T y) { y = x; } // 4 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(9, 74), // (14,74): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void FA<T>( T x, [NotNull]out T y) { y = x; } // 5 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(14, 74)); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void NotNullOutParameterWithVariousTypes() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static void F1(string? x, [NotNull]out string? y) { y = x; } // 1 static void F2(string? x, [NotNull]out string y) { y = x; } // 2, 3 static void F3<T>(T x, [NotNull]out T y) { y = x; } // 4 static void F4<T>([DisallowNull]T x, [NotNull]out T y) { y = x; } static void F5(int? x, [NotNull]out int? y) { y = x; } // 5 }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,64): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F1(string? x, [NotNull]out string? y) { y = x; } // 1 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(5, 64), // (6,60): warning CS8601: Possible null reference assignment. // static void F2(string? x, [NotNull]out string y) { y = x; } // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(6, 60), // (6,63): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F2(string? x, [NotNull]out string y) { y = x; } // 2, 3 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(6, 63), // (7,55): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F3<T>(T x, [NotNull]out T y) { y = x; } // 4 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(7, 55), // (9,58): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F5(int? x, [NotNull]out int? y) { y = x; } // 5 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(9, 58) ); } [Fact] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void MaybeNullT_28() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>( [AllowNull]T x, ref T y) { y = x; } // 1 static void F2<T>( [AllowNull]T x, [AllowNull]ref T y) { y = x; } // 2 static void F3<T>( [AllowNull]T x, [DisallowNull]ref T y) { y = x; } // 3 static void F4<T>( [AllowNull]T x, [MaybeNull]ref T y) { y = x; } static void F5<T>( [AllowNull]T x, [NotNull]ref T y) { y = x; } // 4 static void F6<T>( T x, ref T y) { y = x; } static void F7<T>( T x, [AllowNull]ref T y) { y = x; } static void F8<T>( T x, [DisallowNull]ref T y) { y = x; } static void F9<T>( T x, [MaybeNull]ref T y) { y = x; } static void FA<T>( T x, [NotNull]ref T y) { y = x; } // 5 static void FB<T>([DisallowNull]T x, ref T y) { y = x; } static void FC<T>([DisallowNull]T x, [AllowNull]ref T y) { y = x; } static void FD<T>([DisallowNull]T x, [DisallowNull]ref T y) { y = x; } static void FE<T>([DisallowNull]T x, [MaybeNull]ref T y) { y = x; } static void FF<T>([DisallowNull]T x, [NotNull]ref T y) { y = x; } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,71): warning CS8601: Possible null reference assignment. // static void F1<T>( [AllowNull]T x, ref T y) { y = x; } // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(5, 71), // (6,71): warning CS8601: Possible null reference assignment. // static void F2<T>( [AllowNull]T x, [AllowNull]ref T y) { y = x; } // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(6, 71), // (7,71): warning CS8601: Possible null reference assignment. // static void F3<T>( [AllowNull]T x, [DisallowNull]ref T y) { y = x; } // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(7, 71), // (9,71): warning CS8601: Possible null reference assignment. // static void F5<T>( [AllowNull]T x, [NotNull]ref T y) { y = x; } // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(9, 71), // (9,74): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F5<T>( [AllowNull]T x, [NotNull]ref T y) { y = x; } // 4 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(9, 74), // (14,74): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void FA<T>( T x, [NotNull]ref T y) { y = x; } // 5 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(14, 74)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_29() { var source = @"#nullable enable class Program { static T F1<T>() { (T t1, T t2) = (default, default); return t1; // 1 } static T F2<T>() { T t2; (_, t2) = (default(T), default(T)); return t2; // 2 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,16): warning CS8603: Possible null reference return. // return t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(7, 16), // (13,16): warning CS8603: Possible null reference return. // return t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(13, 16)); } [Fact] public void UnconstrainedTypeParameter_01() { var source = @"#nullable enable class Program { static void F<T, U>(U? u) where U : T { T? t = u; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F<T, U>(U? u) where U : T Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(4, 25), // (6,9): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? t = u; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(6, 9)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_02(bool useCompilationReference) { var sourceA = @"#nullable enable public abstract class A { public abstract void F<T>(T? t); }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public abstract void F<T>(T? t); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 31)); comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable enable abstract class B : A { public abstract override void F<T>(T? t) where T : default; }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,40): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public abstract override void F<T>(T? t) where T : default; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 40), // (4,56): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // public abstract override void F<T>(T? t) where T : default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(4, 56)); verifyMethod(comp); comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); verifyMethod(comp); static void verifyMethod(CSharpCompilation comp) { var method = comp.GetMember<MethodSymbol>("B.F"); Assert.Equal("void B.F<T>(T? t)", method.ToTestDisplayString(includeNonNullable: true)); var parameterType = method.Parameters[0].TypeWithAnnotations; Assert.Equal(NullableAnnotation.Annotated, parameterType.NullableAnnotation); } } [Fact] public void UnconstrainedTypeParameter_03() { var source = @"interface I { } abstract class A { internal abstract void F1<T>() where T : default; internal abstract void F2<T>() where T : default, default; internal abstract void F3<T>() where T : struct, default; static void F4<T>() where T : default, class, new() { } static void F5<T, U>() where U : T, default { } static void F6<T>() where T : default, A { } static void F6<T>() where T : default, notnull { } static void F6<T>() where T : unmanaged, default { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,46): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // internal abstract void F1<T>() where T : default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(4, 46), // (4,46): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F1<T>() where T : default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(4, 46), // (5,46): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(5, 46), // (5,46): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(5, 46), // (5,55): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(5, 55), // (5,55): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(5, 55), // (5,55): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(5, 55), // (6,54): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // internal abstract void F3<T>() where T : struct, default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(6, 54), // (6,54): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F3<T>() where T : struct, default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(6, 54), // (6,54): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal abstract void F3<T>() where T : struct, default; Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(6, 54), // (7,35): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F4<T>() where T : default, class, new() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(7, 35), // (7,35): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F4<T>() where T : default, class, new() { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(7, 35), // (7,44): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F4<T>() where T : default, class, new() { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(7, 44), // (8,41): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F5<T, U>() where U : T, default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(8, 41), // (8,41): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F5<T, U>() where U : T, default { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(8, 41), // (8,41): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F5<T, U>() where U : T, default { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(8, 41), // (9,35): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F6<T>() where T : default, A { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(9, 35), // (9,35): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F6<T>() where T : default, A { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(9, 35), // (10,17): error CS0111: Type 'A' already defines a member called 'F6' with the same parameter types // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "F6").WithArguments("F6", "A").WithLocation(10, 17), // (10,35): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(10, 35), // (10,35): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(10, 35), // (10,44): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(10, 44), // (11,17): error CS0111: Type 'A' already defines a member called 'F6' with the same parameter types // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "F6").WithArguments("F6", "A").WithLocation(11, 17), // (11,46): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(11, 46), // (11,46): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(11, 46), // (11,46): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(11, 46)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,46): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F1<T>() where T : default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(4, 46), // (5,46): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(5, 46), // (5,55): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(5, 55), // (5,55): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(5, 55), // (6,54): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F3<T>() where T : struct, default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(6, 54), // (6,54): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal abstract void F3<T>() where T : struct, default; Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(6, 54), // (7,35): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F4<T>() where T : default, class, new() { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(7, 35), // (7,44): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F4<T>() where T : default, class, new() { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(7, 44), // (8,41): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F5<T, U>() where U : T, default { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(8, 41), // (8,41): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F5<T, U>() where U : T, default { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(8, 41), // (9,35): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F6<T>() where T : default, A { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(9, 35), // (10,17): error CS0111: Type 'A' already defines a member called 'F6' with the same parameter types // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "F6").WithArguments("F6", "A").WithLocation(10, 17), // (10,35): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(10, 35), // (10,44): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(10, 44), // (11,17): error CS0111: Type 'A' already defines a member called 'F6' with the same parameter types // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "F6").WithArguments("F6", "A").WithLocation(11, 17), // (11,46): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(11, 46), // (11,46): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(11, 46)); } [Fact] public void UnconstrainedTypeParameter_04() { var source = @"#nullable enable abstract class A { internal abstract void F1<T>(T? t) where T : struct; internal abstract void F2<T>(T? t) where T : class; } class B0 : A { internal override void F1<T>(T? t) { } internal override void F2<T>(T? t) { } } class B1 : A { internal override void F1<T>(T? t) where T : default { } internal override void F2<T>(T? t) where T : default { } } class B2 : A { internal override void F1<T>(T? t) where T : struct, default { } internal override void F2<T>(T? t) where T : class, default { } } class B3 : A { internal override void F1<T>(T? t) where T : default, struct { } internal override void F2<T>(T? t) where T : default, class { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,7): error CS0534: 'B0' does not implement inherited abstract member 'A.F2<T>(T?)' // class B0 : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B0").WithArguments("B0", "A.F2<T>(T?)").WithLocation(7, 7), // (10,28): error CS0115: 'B0.F2<T>(T?)': no suitable method found to override // internal override void F2<T>(T? t) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B0.F2<T>(T?)").WithLocation(10, 28), // (10,37): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // internal override void F2<T>(T? t) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(10, 37), // (12,7): error CS0534: 'B1' does not implement inherited abstract member 'A.F1<T>(T?)' // class B1 : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B1").WithArguments("B1", "A.F1<T>(T?)").WithLocation(12, 7), // (14,28): error CS0115: 'B1.F1<T>(T?)': no suitable method found to override // internal override void F1<T>(T? t) where T : default { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B1.F1<T>(T?)").WithLocation(14, 28), // (15,31): error CS8822: Method 'B1.F2<T>(T?)' specifies a 'default' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F2<T>(T?)' is constrained to a reference type or a value type. // internal override void F2<T>(T? t) where T : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "T").WithArguments("B1.F2<T>(T?)", "T", "T", "A.F2<T>(T?)").WithLocation(15, 31), // (19,58): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal override void F1<T>(T? t) where T : struct, default { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(19, 58), // (20,57): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal override void F2<T>(T? t) where T : class, default { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(20, 57), // (22,7): error CS0534: 'B3' does not implement inherited abstract member 'A.F1<T>(T?)' // class B3 : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B3").WithArguments("B3", "A.F1<T>(T?)").WithLocation(22, 7), // (24,28): error CS0115: 'B3.F1<T>(T?)': no suitable method found to override // internal override void F1<T>(T? t) where T : default, struct { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B3.F1<T>(T?)").WithLocation(24, 28), // (24,59): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal override void F1<T>(T? t) where T : default, struct { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(24, 59), // (25,59): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal override void F2<T>(T? t) where T : default, class { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(25, 59)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_05(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I { } public abstract class A { public abstract T? F1<T>(); public abstract T? F2<T>() where T : class; public abstract T? F3<T>() where T : class?; public abstract T? F4<T>() where T : struct; public abstract T? F5<T>() where T : notnull; public abstract T? F6<T>() where T : unmanaged; public abstract T? F7<T>() where T : I; public abstract T? F8<T>() where T : I?; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB0 = @"#nullable enable class B : A { public override T? F1<T>() where T : default => default; public override T? F2<T>() where T : class => default; public override T? F3<T>() where T : class => default; public override T? F4<T>() => default; public override T? F5<T>() where T : default => default; public override T? F6<T>() => default; public override T? F7<T>() where T : default => default; public override T? F8<T>() where T : default => default; }"; comp = CreateCompilation(sourceB0, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var sourceB1 = @"#nullable enable class B : A { public override T? F1<T>() => default; public override T? F2<T>() => default; public override T? F3<T>() => default; public override T? F4<T>() => default; public override T? F5<T>() => default; public override T? F6<T>() => default; public override T? F7<T>() => default; public override T? F8<T>() => default; }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,24): error CS0508: 'B.F1<T>()': return type must be 'T' to match overridden member 'A.F1<T>()' // public override T? F1<T>() => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F1").WithArguments("B.F1<T>()", "A.F1<T>()", "T").WithLocation(4, 24), // (4,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F1<T>() => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F1").WithArguments("System.Nullable<T>", "T", "T").WithLocation(4, 24), // (5,24): error CS0508: 'B.F2<T>()': return type must be 'T' to match overridden member 'A.F2<T>()' // public override T? F2<T>() => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F2").WithArguments("B.F2<T>()", "A.F2<T>()", "T").WithLocation(5, 24), // (5,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F2<T>() => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F2").WithArguments("System.Nullable<T>", "T", "T").WithLocation(5, 24), // (6,24): error CS0508: 'B.F3<T>()': return type must be 'T' to match overridden member 'A.F3<T>()' // public override T? F3<T>() => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F3").WithArguments("B.F3<T>()", "A.F3<T>()", "T").WithLocation(6, 24), // (6,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F3<T>() => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F3").WithArguments("System.Nullable<T>", "T", "T").WithLocation(6, 24), // (8,24): error CS0508: 'B.F5<T>()': return type must be 'T' to match overridden member 'A.F5<T>()' // public override T? F5<T>() => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F5").WithArguments("B.F5<T>()", "A.F5<T>()", "T").WithLocation(8, 24), // (8,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F5<T>() => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F5").WithArguments("System.Nullable<T>", "T", "T").WithLocation(8, 24), // (10,24): error CS0508: 'B.F7<T>()': return type must be 'T' to match overridden member 'A.F7<T>()' // public override T? F7<T>() => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F7").WithArguments("B.F7<T>()", "A.F7<T>()", "T").WithLocation(10, 24), // (10,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F7<T>() => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F7").WithArguments("System.Nullable<T>", "T", "T").WithLocation(10, 24), // (11,24): error CS0508: 'B.F8<T>()': return type must be 'T' to match overridden member 'A.F8<T>()' // public override T? F8<T>() => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F8").WithArguments("B.F8<T>()", "A.F8<T>()", "T").WithLocation(11, 24), // (11,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F8<T>() => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F8").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 24)); var sourceB2 = @"#nullable enable class B : A { public override T? F1<T>() where T : default => default; public override T? F2<T>() where T : default => default; public override T? F3<T>() where T : default => default; public override T? F4<T>() where T : default => default; public override T? F5<T>() where T : default => default; public override T? F6<T>() where T : default => default; public override T? F7<T>() where T : default => default; public override T? F8<T>() where T : default => default; }"; comp = CreateCompilation(sourceB2, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,27): error CS8822: Method 'B.F2<T>()' specifies a 'default' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F2<T>()' is constrained to a reference type or a value type. // public override T? F2<T>() where T : default => default; Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "T").WithArguments("B.F2<T>()", "T", "T", "A.F2<T>()").WithLocation(5, 27), // (6,27): error CS8822: Method 'B.F3<T>()' specifies a 'default' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F3<T>()' is constrained to a reference type or a value type. // public override T? F3<T>() where T : default => default; Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "T").WithArguments("B.F3<T>()", "T", "T", "A.F3<T>()").WithLocation(6, 27), // (7,24): error CS0508: 'B.F4<T>()': return type must be 'T?' to match overridden member 'A.F4<T>()' // public override T? F4<T>() where T : default => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F4").WithArguments("B.F4<T>()", "A.F4<T>()", "T?").WithLocation(7, 24), // (7,27): error CS8822: Method 'B.F4<T>()' specifies a 'default' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F4<T>()' is constrained to a reference type or a value type. // public override T? F4<T>() where T : default => default; Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "T").WithArguments("B.F4<T>()", "T", "T", "A.F4<T>()").WithLocation(7, 27), // (9,24): error CS0508: 'B.F6<T>()': return type must be 'T?' to match overridden member 'A.F6<T>()' // public override T? F6<T>() where T : default => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F6").WithArguments("B.F6<T>()", "A.F6<T>()", "T?").WithLocation(9, 24), // (9,27): error CS8822: Method 'B.F6<T>()' specifies a 'default' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F6<T>()' is constrained to a reference type or a value type. // public override T? F6<T>() where T : default => default; Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "T").WithArguments("B.F6<T>()", "T", "T", "A.F6<T>()").WithLocation(9, 27)); var sourceB3 = @"#nullable enable class B : A { public override T? F1<T>() where T : class => default; public override T? F2<T>() where T : class => default; public override T? F3<T>() where T : class => default; public override T? F4<T>() where T : class => default; public override T? F5<T>() where T : class => default; public override T? F6<T>() where T : class => default; public override T? F7<T>() where T : class => default; public override T? F8<T>() where T : class => default; }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,27): error CS8665: Method 'B.F1<T>()' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F1<T>()' is not a reference type. // public override T? F1<T>() where T : class => default; Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("B.F1<T>()", "T", "T", "A.F1<T>()").WithLocation(4, 27), // (7,24): error CS0508: 'B.F4<T>()': return type must be 'T?' to match overridden member 'A.F4<T>()' // public override T? F4<T>() where T : class => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F4").WithArguments("B.F4<T>()", "A.F4<T>()", "T?").WithLocation(7, 24), // (7,27): error CS8665: Method 'B.F4<T>()' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F4<T>()' is not a reference type. // public override T? F4<T>() where T : class => default; Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("B.F4<T>()", "T", "T", "A.F4<T>()").WithLocation(7, 27), // (8,27): error CS8665: Method 'B.F5<T>()' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F5<T>()' is not a reference type. // public override T? F5<T>() where T : class => default; Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("B.F5<T>()", "T", "T", "A.F5<T>()").WithLocation(8, 27), // (9,24): error CS0508: 'B.F6<T>()': return type must be 'T?' to match overridden member 'A.F6<T>()' // public override T? F6<T>() where T : class => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F6").WithArguments("B.F6<T>()", "A.F6<T>()", "T?").WithLocation(9, 24), // (9,27): error CS8665: Method 'B.F6<T>()' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F6<T>()' is not a reference type. // public override T? F6<T>() where T : class => default; Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("B.F6<T>()", "T", "T", "A.F6<T>()").WithLocation(9, 27), // (10,27): error CS8665: Method 'B.F7<T>()' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F7<T>()' is not a reference type. // public override T? F7<T>() where T : class => default; Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("B.F7<T>()", "T", "T", "A.F7<T>()").WithLocation(10, 27), // (11,27): error CS8665: Method 'B.F8<T>()' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F8<T>()' is not a reference type. // public override T? F8<T>() where T : class => default; Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("B.F8<T>()", "T", "T", "A.F8<T>()").WithLocation(11, 27)); var sourceB4 = @"#nullable enable class B : A { public override T? F1<T>() where T : struct => default; public override T? F2<T>() where T : struct => default; public override T? F3<T>() where T : struct => default; public override T? F4<T>() where T : struct => default; public override T? F5<T>() where T : struct => default; public override T? F6<T>() where T : struct => default; public override T? F7<T>() where T : struct => default; public override T? F8<T>() where T : struct => default; }"; comp = CreateCompilation(sourceB4, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,24): error CS0508: 'B.F1<T>()': return type must be 'T' to match overridden member 'A.F1<T>()' // public override T? F1<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F1").WithArguments("B.F1<T>()", "A.F1<T>()", "T").WithLocation(4, 24), // (4,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F1<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F1").WithArguments("System.Nullable<T>", "T", "T").WithLocation(4, 24), // (4,27): error CS8666: Method 'B.F1<T>()' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F1<T>()' is not a non-nullable value type. // public override T? F1<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("B.F1<T>()", "T", "T", "A.F1<T>()").WithLocation(4, 27), // (5,24): error CS0508: 'B.F2<T>()': return type must be 'T' to match overridden member 'A.F2<T>()' // public override T? F2<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F2").WithArguments("B.F2<T>()", "A.F2<T>()", "T").WithLocation(5, 24), // (5,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F2<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F2").WithArguments("System.Nullable<T>", "T", "T").WithLocation(5, 24), // (5,27): error CS8666: Method 'B.F2<T>()' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F2<T>()' is not a non-nullable value type. // public override T? F2<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("B.F2<T>()", "T", "T", "A.F2<T>()").WithLocation(5, 27), // (6,24): error CS0508: 'B.F3<T>()': return type must be 'T' to match overridden member 'A.F3<T>()' // public override T? F3<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F3").WithArguments("B.F3<T>()", "A.F3<T>()", "T").WithLocation(6, 24), // (6,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F3<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F3").WithArguments("System.Nullable<T>", "T", "T").WithLocation(6, 24), // (6,27): error CS8666: Method 'B.F3<T>()' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F3<T>()' is not a non-nullable value type. // public override T? F3<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("B.F3<T>()", "T", "T", "A.F3<T>()").WithLocation(6, 27), // (8,24): error CS0508: 'B.F5<T>()': return type must be 'T' to match overridden member 'A.F5<T>()' // public override T? F5<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F5").WithArguments("B.F5<T>()", "A.F5<T>()", "T").WithLocation(8, 24), // (8,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F5<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F5").WithArguments("System.Nullable<T>", "T", "T").WithLocation(8, 24), // (8,27): error CS8666: Method 'B.F5<T>()' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F5<T>()' is not a non-nullable value type. // public override T? F5<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("B.F5<T>()", "T", "T", "A.F5<T>()").WithLocation(8, 27), // (10,24): error CS0508: 'B.F7<T>()': return type must be 'T' to match overridden member 'A.F7<T>()' // public override T? F7<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F7").WithArguments("B.F7<T>()", "A.F7<T>()", "T").WithLocation(10, 24), // (10,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F7<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F7").WithArguments("System.Nullable<T>", "T", "T").WithLocation(10, 24), // (10,27): error CS8666: Method 'B.F7<T>()' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F7<T>()' is not a non-nullable value type. // public override T? F7<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("B.F7<T>()", "T", "T", "A.F7<T>()").WithLocation(10, 27), // (11,24): error CS0508: 'B.F8<T>()': return type must be 'T' to match overridden member 'A.F8<T>()' // public override T? F8<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F8").WithArguments("B.F8<T>()", "A.F8<T>()", "T").WithLocation(11, 24), // (11,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F8<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F8").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 24), // (11,27): error CS8666: Method 'B.F8<T>()' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F8<T>()' is not a non-nullable value type. // public override T? F8<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("B.F8<T>()", "T", "T", "A.F8<T>()").WithLocation(11, 27)); } // All pairs of methods "static void F<T>(T[?] t) [where T : _constraint_] { }". [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_06( [CombinatorialValues(null, "class", "class?", "struct", "notnull", "unmanaged", "I", "I?")] string constraintA, bool annotatedA, [CombinatorialValues(null, "class", "class?", "struct", "notnull", "unmanaged", "I", "I?")] string constraintB, bool annotatedB) { var source = $@"#nullable enable class C {{ {getMethod(constraintA, annotatedA)} {getMethod(constraintB, annotatedB)} }} interface I {{ }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expectedDiagnostics = (isNullableOfT(constraintA, annotatedA) == isNullableOfT(constraintB, annotatedB)) ? new[] { // (5,17): error CS0111: Type 'C' already defines a member called 'F' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "F").WithArguments("F", "C").WithLocation(5, 17), } : Array.Empty<DiagnosticDescription>(); comp.VerifyDiagnostics(expectedDiagnostics); static string getMethod(string constraint, bool annotated) => $"static void F<T>(T{(annotated ? "?" : "")} t) {(constraint is null ? "" : $"where T : {constraint}")} {{ }}"; static bool isNullableOfT(string constraint, bool annotated) => (constraint == "struct" || constraint == "unmanaged") && annotated; } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_07( [CombinatorialValues(null, "notnull", "I", "I?")] string constraint, bool useCompilationReference) { var sourceA = $@"#nullable enable public interface I {{ }} public abstract class A {{ public abstract void F<T>(T? t) {(constraint is null ? "" : $"where T : {constraint}")}; public abstract void F<T>(T? t) where T : struct; }}"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable enable class B1 : A { public override void F<T>(T? t) { } } class B2 : A { public override void F<T>(T? t) where T : default { } } class B3 : A { public override void F<T>(T? t) where T : struct { } } class B4 : A { public override void F<T>(T? t) where T : default { } public override void F<T>(T? t) where T : struct { } }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,7): error CS0534: 'B1' does not implement inherited abstract member 'A.F<T>(T?)' // class B1 : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B1").WithArguments("B1", "A.F<T>(T?)").WithLocation(2, 7), // (6,7): error CS0534: 'B2' does not implement inherited abstract member 'A.F<T>(T?)' // class B2 : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A.F<T>(T?)").WithLocation(6, 7), // (10,7): error CS0534: 'B3' does not implement inherited abstract member 'A.F<T>(T?)' // class B3 : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B3").WithArguments("B3", "A.F<T>(T?)").WithLocation(10, 7)); Assert.True(comp.GetMember<MethodSymbol>("B1.F").TypeParameters[0].IsValueType); Assert.False(comp.GetMember<MethodSymbol>("B2.F").TypeParameters[0].IsValueType); Assert.True(comp.GetMember<MethodSymbol>("B3.F").TypeParameters[0].IsValueType); } [Fact] public void UnconstrainedTypeParameter_08() { var source = @"abstract class A<T> { public abstract void F1<U>(T t); public abstract void F1<U>(object o) where U : class; public abstract void F2<U>(T t) where U : struct; public abstract void F2<U>(object o); } abstract class B1 : A<object> { public override void F1<U>(object o) { } public override void F2<U>(object o) { } } abstract class B2 : A<object> { public override void F1<U>(object o) where U : class { } public override void F2<U>(object o) where U : struct { } } abstract class B3 : A<object> { public override void F1<U>(object o) where U : default { } public override void F2<U>(object o) where U : default { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (3,26): warning CS1957: Member 'B1.F1<U>(object)' overrides 'A<object>.F1<U>(object)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. // public abstract void F1<U>(T t); Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F1").WithArguments("A<object>.F1<U>(object)", "B1.F1<U>(object)").WithLocation(3, 26), // (3,26): warning CS1957: Member 'B2.F1<U>(object)' overrides 'A<object>.F1<U>(object)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. // public abstract void F1<U>(T t); Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F1").WithArguments("A<object>.F1<U>(object)", "B2.F1<U>(object)").WithLocation(3, 26), // (3,26): warning CS1957: Member 'B3.F1<U>(object)' overrides 'A<object>.F1<U>(object)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. // public abstract void F1<U>(T t); Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F1").WithArguments("A<object>.F1<U>(object)", "B3.F1<U>(object)").WithLocation(3, 26), // (5,26): warning CS1957: Member 'B1.F2<U>(object)' overrides 'A<object>.F2<U>(object)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. // public abstract void F2<U>(T t) where U : struct; Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F2").WithArguments("A<object>.F2<U>(object)", "B1.F2<U>(object)").WithLocation(5, 26), // (5,26): warning CS1957: Member 'B2.F2<U>(object)' overrides 'A<object>.F2<U>(object)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. // public abstract void F2<U>(T t) where U : struct; Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F2").WithArguments("A<object>.F2<U>(object)", "B2.F2<U>(object)").WithLocation(5, 26), // (5,26): warning CS1957: Member 'B3.F2<U>(object)' overrides 'A<object>.F2<U>(object)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. // public abstract void F2<U>(T t) where U : struct; Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F2").WithArguments("A<object>.F2<U>(object)", "B3.F2<U>(object)").WithLocation(5, 26), // (10,26): error CS0462: The inherited members 'A<T>.F1<U>(T)' and 'A<T>.F1<U>(object)' have the same signature in type 'B1', so they cannot be overridden // public override void F1<U>(object o) { } Diagnostic(ErrorCode.ERR_AmbigOverride, "F1").WithArguments("A<T>.F1<U>(T)", "A<T>.F1<U>(object)", "B1").WithLocation(10, 26), // (11,26): error CS0462: The inherited members 'A<T>.F2<U>(T)' and 'A<T>.F2<U>(object)' have the same signature in type 'B1', so they cannot be overridden // public override void F2<U>(object o) { } Diagnostic(ErrorCode.ERR_AmbigOverride, "F2").WithArguments("A<T>.F2<U>(T)", "A<T>.F2<U>(object)", "B1").WithLocation(11, 26), // (15,26): error CS0462: The inherited members 'A<T>.F1<U>(T)' and 'A<T>.F1<U>(object)' have the same signature in type 'B2', so they cannot be overridden // public override void F1<U>(object o) where U : class { } Diagnostic(ErrorCode.ERR_AmbigOverride, "F1").WithArguments("A<T>.F1<U>(T)", "A<T>.F1<U>(object)", "B2").WithLocation(15, 26), // (15,29): error CS8665: Method 'B2.F1<U>(object)' specifies a 'class' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<object>.F1<U>(object)' is not a reference type. // public override void F1<U>(object o) where U : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "U").WithArguments("B2.F1<U>(object)", "U", "U", "A<object>.F1<U>(object)").WithLocation(15, 29), // (16,26): error CS0462: The inherited members 'A<T>.F2<U>(T)' and 'A<T>.F2<U>(object)' have the same signature in type 'B2', so they cannot be overridden // public override void F2<U>(object o) where U : struct { } Diagnostic(ErrorCode.ERR_AmbigOverride, "F2").WithArguments("A<T>.F2<U>(T)", "A<T>.F2<U>(object)", "B2").WithLocation(16, 26), // (20,26): error CS0462: The inherited members 'A<T>.F1<U>(T)' and 'A<T>.F1<U>(object)' have the same signature in type 'B3', so they cannot be overridden // public override void F1<U>(object o) where U : default { } Diagnostic(ErrorCode.ERR_AmbigOverride, "F1").WithArguments("A<T>.F1<U>(T)", "A<T>.F1<U>(object)", "B3").WithLocation(20, 26), // (21,26): error CS0462: The inherited members 'A<T>.F2<U>(T)' and 'A<T>.F2<U>(object)' have the same signature in type 'B3', so they cannot be overridden // public override void F2<U>(object o) where U : default { } Diagnostic(ErrorCode.ERR_AmbigOverride, "F2").WithArguments("A<T>.F2<U>(T)", "A<T>.F2<U>(object)", "B3").WithLocation(21, 26), // (21,29): error CS8822: Method 'B3.F2<U>(object)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<object>.F2<U>(object)' is constrained to a reference type or a value type. // public override void F2<U>(object o) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B3.F2<U>(object)", "U", "U", "A<object>.F2<U>(object)").WithLocation(21, 29)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_09(bool useCompilationReference) { var sourceA = @"#nullable enable public abstract class A<T> { public abstract void F1<U>(U u) where U : T; public abstract void F2<U>(U? u) where U : T; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable class B1<T> : A<T> { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2<T> : A<T> { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3<T> : A<T?> { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4<T> : A<T?> { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5<T> : A<T?> { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6<T> : A<T?> { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(5, 26), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F1<U>(U)' // class B2<T> : A<T> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F2<U>(U?)' // class B2<T> : A<T> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F2<U>(U?)").WithLocation(7, 7), // (9,26): error CS0115: 'B2<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2<T>.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2<T>.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (15,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(15, 26), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F1<U>(U)' // class B4<T> : A<T?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F2<U>(U?)' // class B4<T> : A<T?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F2<U>(U?)").WithLocation(17, 7), // (19,26): error CS0115: 'B4<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4<T>.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4<T>.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (25,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(25, 26)); comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(5, 26), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F1<U>(U)' // class B2<T> : A<T> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F2<U>(U?)' // class B2<T> : A<T> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F2<U>(U?)").WithLocation(7, 7), // (9,26): error CS0115: 'B2<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2<T>.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2<T>.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (15,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(15, 26), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F1<U>(U)' // class B4<T> : A<T?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F2<U>(U?)' // class B4<T> : A<T?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F2<U>(U?)").WithLocation(17, 7), // (19,26): error CS0115: 'B4<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4<T>.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4<T>.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (25,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(25, 26)); var sourceB2 = @"#nullable enable class B1<T> : A<T> where T : class { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2<T> : A<T> where T : class { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3<T> : A<T?> where T : class { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4<T> : A<T?> where T : class { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5<T> : A<T?> where T : class { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6<T> : A<T?> where T : class { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(5, 26), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F1<U>(U)' // class B2<T> : A<T> where T : class Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F2<U>(U?)' // class B2<T> : A<T> where T : class Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F2<U>(U?)").WithLocation(7, 7), // (9,26): error CS0115: 'B2<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2<T>.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2<T>.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (15,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(15, 26), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F1<U>(U)' // class B4<T> : A<T?> where T : class Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F2<U>(U?)' // class B4<T> : A<T?> where T : class Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F2<U>(U?)").WithLocation(17, 7), // (19,26): error CS0115: 'B4<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4<T>.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4<T>.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (25,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(25, 26)); var sourceB3 = @"#nullable enable class B1<T> : A<T> where T : class? { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2<T> : A<T> where T : class? { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3<T> : A<T?> where T : class? { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4<T> : A<T?> where T : class? { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5<T> : A<T?> where T : class? { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6<T> : A<T?> where T : class? { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(5, 26), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F1<U>(U)' // class B2<T> : A<T> where T : class? Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F2<U>(U?)' // class B2<T> : A<T> where T : class? Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F2<U>(U?)").WithLocation(7, 7), // (9,26): error CS0115: 'B2<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2<T>.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2<T>.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (15,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(15, 26), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F1<U>(U)' // class B4<T> : A<T?> where T : class? Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F2<U>(U?)' // class B4<T> : A<T?> where T : class? Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F2<U>(U?)").WithLocation(17, 7), // (19,26): error CS0115: 'B4<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4<T>.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4<T>.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (25,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(25, 26)); var sourceB4 = @"#nullable enable class B1<T> : A<T> where T : struct { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2<T> : A<T> where T : struct { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3<T> : A<T?> where T : struct { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4<T> : A<T?> where T : struct { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5<T> : A<T?> where T : struct { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6<T> : A<T?> where T : struct { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB4, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F1<U>(U)' // class B2<T> : A<T> where T : struct Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F2<U>(U)' // class B2<T> : A<T> where T : struct Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F2<U>(U)").WithLocation(7, 7), // (9,26): error CS0115: 'B2<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2<T>.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2<T>.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F1<U>(U)' // class B4<T> : A<T?> where T : struct Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F2<U>(U)' // class B4<T> : A<T?> where T : struct Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F2<U>(U)").WithLocation(17, 7), // (19,26): error CS0115: 'B4<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4<T>.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4<T>.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (24,29): error CS8822: Method 'B5<T>.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<T?>.F1<U>(U)' is constrained to a reference type or a value type. // public override void F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B5<T>.F1<U>(U)", "U", "U", "A<T?>.F1<U>(U)").WithLocation(24, 29), // (25,29): error CS8822: Method 'B5<T>.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<T?>.F2<U>(U)' is constrained to a reference type or a value type. // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B5<T>.F2<U>(U)", "U", "U", "A<T?>.F2<U>(U)").WithLocation(25, 29), // (29,29): error CS8822: Method 'B6<T>.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<T?>.F1<U>(U)' is constrained to a reference type or a value type. // public override void F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B6<T>.F1<U>(U)", "U", "U", "A<T?>.F1<U>(U)").WithLocation(29, 29), // (30,29): error CS8822: Method 'B6<T>.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<T?>.F2<U>(U)' is constrained to a reference type or a value type. // public override void F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B6<T>.F2<U>(U)", "U", "U", "A<T?>.F2<U>(U)").WithLocation(30, 29)); var sourceB5 = @"#nullable enable class B1<T> : A<T> where T : notnull { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2<T> : A<T> where T : notnull { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3<T> : A<T?> where T : notnull { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4<T> : A<T?> where T : notnull { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5<T> : A<T?> where T : notnull { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6<T> : A<T?> where T : notnull { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB5, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(5, 26), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F1<U>(U)' // class B2<T> : A<T> where T : notnull Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F2<U>(U?)' // class B2<T> : A<T> where T : notnull Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F2<U>(U?)").WithLocation(7, 7), // (9,26): error CS0115: 'B2<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2<T>.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2<T>.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (15,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(15, 26), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F1<U>(U)' // class B4<T> : A<T?> where T : notnull Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F2<U>(U?)' // class B4<T> : A<T?> where T : notnull Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F2<U>(U?)").WithLocation(17, 7), // (19,26): error CS0115: 'B4<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4<T>.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4<T>.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (25,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(25, 26)); var sourceB6 = @"#nullable enable class B1 : A<string> { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2 : A<string> { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3 : A<string?> { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4 : A<string?> { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5 : A<string?> { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6 : A<string?> { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB6, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(5, 26), // (7,7): error CS0534: 'B2' does not implement inherited abstract member 'A<string>.F1<U>(U)' // class B2 : A<string> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A<string>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2' does not implement inherited abstract member 'A<string>.F2<U>(U?)' // class B2 : A<string> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A<string>.F2<U>(U?)").WithLocation(7, 7), // (9,26): error CS0115: 'B2.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (15,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(15, 26), // (17,7): error CS0534: 'B4' does not implement inherited abstract member 'A<string?>.F1<U>(U)' // class B4 : A<string?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4", "A<string?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4' does not implement inherited abstract member 'A<string?>.F2<U>(U?)' // class B4 : A<string?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4", "A<string?>.F2<U>(U?)").WithLocation(17, 7), // (19,26): error CS0115: 'B4.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (24,29): error CS8822: Method 'B5.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<string?>.F1<U>(U)' is constrained to a reference type or a value type. // public override void F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B5.F1<U>(U)", "U", "U", "A<string?>.F1<U>(U)").WithLocation(24, 29), // (25,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(25, 26), // (25,29): error CS8822: Method 'B5.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<string?>.F2<U>(U?)' is constrained to a reference type or a value type. // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B5.F2<U>(U)", "U", "U", "A<string?>.F2<U>(U?)").WithLocation(25, 29), // (29,29): error CS8822: Method 'B6.F1<U>(U?)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<string?>.F1<U>(U)' is constrained to a reference type or a value type. // public override void F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B6.F1<U>(U?)", "U", "U", "A<string?>.F1<U>(U)").WithLocation(29, 29), // (30,29): error CS8822: Method 'B6.F2<U>(U?)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<string?>.F2<U>(U?)' is constrained to a reference type or a value type. // public override void F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B6.F2<U>(U?)", "U", "U", "A<string?>.F2<U>(U?)").WithLocation(30, 29)); var sourceB7 = @"#nullable enable class B1 : A<int> { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2 : A<int> { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3 : A<int?> { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4 : A<int?> { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5 : A<int?> { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6 : A<int?> { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB7, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,7): error CS0534: 'B2' does not implement inherited abstract member 'A<int>.F1<U>(U)' // class B2 : A<int> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A<int>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2' does not implement inherited abstract member 'A<int>.F2<U>(U)' // class B2 : A<int> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A<int>.F2<U>(U)").WithLocation(7, 7), // (9,26): error CS0115: 'B2.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (17,7): error CS0534: 'B4' does not implement inherited abstract member 'A<int?>.F1<U>(U)' // class B4 : A<int?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4", "A<int?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4' does not implement inherited abstract member 'A<int?>.F2<U>(U)' // class B4 : A<int?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4", "A<int?>.F2<U>(U)").WithLocation(17, 7), // (19,26): error CS0115: 'B4.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (24,29): error CS8822: Method 'B5.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<int?>.F1<U>(U)' is constrained to a reference type or a value type. // public override void F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B5.F1<U>(U)", "U", "U", "A<int?>.F1<U>(U)").WithLocation(24, 29), // (25,29): error CS8822: Method 'B5.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<int?>.F2<U>(U)' is constrained to a reference type or a value type. // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B5.F2<U>(U)", "U", "U", "A<int?>.F2<U>(U)").WithLocation(25, 29), // (29,29): error CS8822: Method 'B6.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<int?>.F1<U>(U)' is constrained to a reference type or a value type. // public override void F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B6.F1<U>(U)", "U", "U", "A<int?>.F1<U>(U)").WithLocation(29, 29), // (30,29): error CS8822: Method 'B6.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<int?>.F2<U>(U)' is constrained to a reference type or a value type. // public override void F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B6.F2<U>(U)", "U", "U", "A<int?>.F2<U>(U)").WithLocation(30, 29)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_10(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I<T> { void F1<U>(U u) where U : T; void F2<U>(U? u) where U : T; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable class C1<T> : I<T> { void I<T>.F1<U>(U u) { } void I<T>.F2<U>(U u) { } } class C2<T> : I<T> { void I<T>.F1<U>(U? u) { } void I<T>.F2<U>(U? u) { } } class C3<T> : I<T?> { void I<T?>.F1<U>(U u) { } void I<T?>.F2<U>(U u) { } } class C4<T> : I<T?> { void I<T?>.F1<U>(U? u) { } void I<T?>.F2<U>(U? u) { } } class C5<T> : I<T?> { void I<T?>.F1<U>(U u) where U : default { } void I<T?>.F2<U>(U u) where U : default { } } class C6<T> : I<T?> { void I<T?>.F1<U>(U? u) where U : default { } void I<T?>.F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,15): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<T>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<T>.F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<T>.F2<U>(U? u)").WithLocation(5, 15), // (7,15): error CS0535: 'C2<T>' does not implement interface member 'I<T>.F2<U>(U?)' // class C2<T> : I<T> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T>").WithArguments("C2<T>", "I<T>.F2<U>(U?)").WithLocation(7, 15), // (7,15): error CS0535: 'C2<T>' does not implement interface member 'I<T>.F1<U>(U)' // class C2<T> : I<T> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T>").WithArguments("C2<T>", "I<T>.F1<U>(U)").WithLocation(7, 15), // (9,15): error CS0539: 'C2<T>.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C2<T>.F1<U>(U?)").WithLocation(9, 15), // (9,24): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 24), // (10,15): error CS0539: 'C2<T>.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C2<T>.F2<U>(U?)").WithLocation(10, 15), // (10,24): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 24), // (12,17): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C3<T> : I<T?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(12, 17), // (14,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F1<U>(U u) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(14, 12), // (15,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F2<U>(U u) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(15, 12), // (15,16): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<T?>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<T?>.F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<T?>.F2<U>(U? u)").WithLocation(15, 16), // (17,15): error CS0535: 'C4<T>' does not implement interface member 'I<T?>.F2<U>(U?)' // class C4<T> : I<T?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T?>").WithArguments("C4<T>", "I<T?>.F2<U>(U?)").WithLocation(17, 15), // (17,15): error CS0535: 'C4<T>' does not implement interface member 'I<T?>.F1<U>(U)' // class C4<T> : I<T?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T?>").WithArguments("C4<T>", "I<T?>.F1<U>(U)").WithLocation(17, 15), // (17,17): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C4<T> : I<T?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(17, 17), // (19,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(19, 12), // (19,16): error CS0539: 'C4<T>.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C4<T>.F1<U>(U?)").WithLocation(19, 16), // (19,25): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 25), // (20,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(20, 12), // (20,16): error CS0539: 'C4<T>.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C4<T>.F2<U>(U?)").WithLocation(20, 16), // (20,25): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 25), // (22,17): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C5<T> : I<T?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(22, 17), // (24,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(24, 12), // (24,37): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // void I<T?>.F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(24, 37), // (25,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(25, 12), // (25,16): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<T?>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<T?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<T?>.F2<U>(U? u)").WithLocation(25, 16), // (25,37): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // void I<T?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(25, 37), // (27,17): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C6<T> : I<T?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(27, 17), // (29,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(29, 12), // (29,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(29, 22), // (29,38): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // void I<T?>.F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(29, 38), // (30,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(30, 12), // (30,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(30, 22), // (30,38): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // void I<T?>.F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(30, 38)); comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,15): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<T>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<T>.F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<T>.F2<U>(U? u)").WithLocation(5, 15), // (7,15): error CS0535: 'C2<T>' does not implement interface member 'I<T>.F2<U>(U?)' // class C2<T> : I<T> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T>").WithArguments("C2<T>", "I<T>.F2<U>(U?)").WithLocation(7, 15), // (7,15): error CS0535: 'C2<T>' does not implement interface member 'I<T>.F1<U>(U)' // class C2<T> : I<T> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T>").WithArguments("C2<T>", "I<T>.F1<U>(U)").WithLocation(7, 15), // (9,15): error CS0539: 'C2<T>.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C2<T>.F1<U>(U?)").WithLocation(9, 15), // (9,24): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 24), // (10,15): error CS0539: 'C2<T>.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C2<T>.F2<U>(U?)").WithLocation(10, 15), // (10,24): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 24), // (15,16): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<T?>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<T?>.F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<T?>.F2<U>(U? u)").WithLocation(15, 16), // (17,15): error CS0535: 'C4<T>' does not implement interface member 'I<T?>.F2<U>(U?)' // class C4<T> : I<T?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T?>").WithArguments("C4<T>", "I<T?>.F2<U>(U?)").WithLocation(17, 15), // (17,15): error CS0535: 'C4<T>' does not implement interface member 'I<T?>.F1<U>(U)' // class C4<T> : I<T?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T?>").WithArguments("C4<T>", "I<T?>.F1<U>(U)").WithLocation(17, 15), // (19,16): error CS0539: 'C4<T>.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C4<T>.F1<U>(U?)").WithLocation(19, 16), // (19,25): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 25), // (20,16): error CS0539: 'C4<T>.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C4<T>.F2<U>(U?)").WithLocation(20, 16), // (20,25): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 25), // (25,16): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<T?>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<T?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<T?>.F2<U>(U? u)").WithLocation(25, 16)); var sourceB2 = @"#nullable enable class C1 : I<string> { void I<string>.F1<U>(U u) { } void I<string>.F2<U>(U u) { } } class C2 : I<string> { void I<string>.F1<U>(U? u) { } void I<string>.F2<U>(U? u) { } } class C3 : I<string?> { void I<string?>.F1<U>(U u) { } void I<string?>.F2<U>(U u) { } } class C4 : I<string?> { void I<string?>.F1<U>(U? u) { } void I<string?>.F2<U>(U? u) { } } class C5 : I<string?> { void I<string?>.F1<U>(U u) where U : default { } void I<string?>.F2<U>(U u) where U : default { } } class C6 : I<string?> { void I<string?>.F1<U>(U? u) where U : default { } void I<string?>.F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,20): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<string>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<string>.F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<string>.F2<U>(U? u)").WithLocation(5, 20), // (7,12): error CS0535: 'C2' does not implement interface member 'I<string>.F2<U>(U?)' // class C2 : I<string> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<string>").WithArguments("C2", "I<string>.F2<U>(U?)").WithLocation(7, 12), // (7,12): error CS0535: 'C2' does not implement interface member 'I<string>.F1<U>(U)' // class C2 : I<string> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<string>").WithArguments("C2", "I<string>.F1<U>(U)").WithLocation(7, 12), // (9,20): error CS0539: 'C2.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<string>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C2.F1<U>(U?)").WithLocation(9, 20), // (9,29): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<string>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 29), // (10,20): error CS0539: 'C2.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<string>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C2.F2<U>(U?)").WithLocation(10, 20), // (10,29): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<string>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 29), // (15,21): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<string?>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<string?>.F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<string?>.F2<U>(U? u)").WithLocation(15, 21), // (17,12): error CS0535: 'C4' does not implement interface member 'I<string?>.F2<U>(U?)' // class C4 : I<string?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<string?>").WithArguments("C4", "I<string?>.F2<U>(U?)").WithLocation(17, 12), // (17,12): error CS0535: 'C4' does not implement interface member 'I<string?>.F1<U>(U)' // class C4 : I<string?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<string?>").WithArguments("C4", "I<string?>.F1<U>(U)").WithLocation(17, 12), // (19,21): error CS0539: 'C4.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<string?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C4.F1<U>(U?)").WithLocation(19, 21), // (19,30): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<string?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 30), // (20,21): error CS0539: 'C4.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<string?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C4.F2<U>(U?)").WithLocation(20, 21), // (20,30): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<string?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 30), // (24,24): error CS8822: Method 'C5.I<string?>.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<string?>.F1<U>(U)' is constrained to a reference type or a value type. // void I<string?>.F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C5.I<string?>.F1<U>(U)", "U", "U", "I<string?>.F1<U>(U)").WithLocation(24, 24), // (25,21): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<string?>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<string?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<string?>.F2<U>(U? u)").WithLocation(25, 21), // (25,24): error CS8822: Method 'C5.I<string?>.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<string?>.F2<U>(U?)' is constrained to a reference type or a value type. // void I<string?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C5.I<string?>.F2<U>(U)", "U", "U", "I<string?>.F2<U>(U?)").WithLocation(25, 24), // (29,24): error CS8822: Method 'C6.I<string?>.F1<U>(U?)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<string?>.F1<U>(U)' is constrained to a reference type or a value type. // void I<string?>.F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C6.I<string?>.F1<U>(U?)", "U", "U", "I<string?>.F1<U>(U)").WithLocation(29, 24), // (30,24): error CS8822: Method 'C6.I<string?>.F2<U>(U?)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<string?>.F2<U>(U?)' is constrained to a reference type or a value type. // void I<string?>.F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C6.I<string?>.F2<U>(U?)", "U", "U", "I<string?>.F2<U>(U?)").WithLocation(30, 24)); var sourceB3 = @"#nullable enable class C1 : I<int> { void I<int>.F1<U>(U u) { } void I<int>.F2<U>(U u) { } } class C2 : I<int> { void I<int>.F1<U>(U? u) { } void I<int>.F2<U>(U? u) { } } class C3 : I<int?> { void I<int?>.F1<U>(U u) { } void I<int?>.F2<U>(U u) { } } class C4 : I<int?> { void I<int?>.F1<U>(U? u) { } void I<int?>.F2<U>(U? u) { } } class C5 : I<int?> { void I<int?>.F1<U>(U u) where U : default { } void I<int?>.F2<U>(U u) where U : default { } } class C6 : I<int?> { void I<int?>.F1<U>(U? u) where U : default { } void I<int?>.F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,12): error CS0535: 'C2' does not implement interface member 'I<int>.F2<U>(U)' // class C2 : I<int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<int>").WithArguments("C2", "I<int>.F2<U>(U)").WithLocation(7, 12), // (7,12): error CS0535: 'C2' does not implement interface member 'I<int>.F1<U>(U)' // class C2 : I<int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<int>").WithArguments("C2", "I<int>.F1<U>(U)").WithLocation(7, 12), // (9,17): error CS0539: 'C2.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<int>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C2.F1<U>(U?)").WithLocation(9, 17), // (9,26): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<int>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 26), // (10,17): error CS0539: 'C2.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<int>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C2.F2<U>(U?)").WithLocation(10, 17), // (10,26): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<int>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 26), // (17,12): error CS0535: 'C4' does not implement interface member 'I<int?>.F2<U>(U)' // class C4 : I<int?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<int?>").WithArguments("C4", "I<int?>.F2<U>(U)").WithLocation(17, 12), // (17,12): error CS0535: 'C4' does not implement interface member 'I<int?>.F1<U>(U)' // class C4 : I<int?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<int?>").WithArguments("C4", "I<int?>.F1<U>(U)").WithLocation(17, 12), // (19,18): error CS0539: 'C4.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<int?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C4.F1<U>(U?)").WithLocation(19, 18), // (19,27): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<int?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 27), // (20,18): error CS0539: 'C4.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<int?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C4.F2<U>(U?)").WithLocation(20, 18), // (20,27): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<int?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 27), // (24,21): error CS8822: Method 'C5.I<int?>.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<int?>.F1<U>(U)' is constrained to a reference type or a value type. // void I<int?>.F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C5.I<int?>.F1<U>(U)", "U", "U", "I<int?>.F1<U>(U)").WithLocation(24, 21), // (25,21): error CS8822: Method 'C5.I<int?>.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<int?>.F2<U>(U)' is constrained to a reference type or a value type. // void I<int?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C5.I<int?>.F2<U>(U)", "U", "U", "I<int?>.F2<U>(U)").WithLocation(25, 21), // (29,21): error CS8822: Method 'C6.I<int?>.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<int?>.F1<U>(U)' is constrained to a reference type or a value type. // void I<int?>.F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C6.I<int?>.F1<U>(U)", "U", "U", "I<int?>.F1<U>(U)").WithLocation(29, 21), // (30,21): error CS8822: Method 'C6.I<int?>.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<int?>.F2<U>(U)' is constrained to a reference type or a value type. // void I<int?>.F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C6.I<int?>.F2<U>(U)", "U", "U", "I<int?>.F2<U>(U)").WithLocation(30, 21)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_11(bool useCompilationReference) { var sourceA = @"#nullable enable public class A { public static T F1<T>(T t) => default!; public static T? F2<T>(T t) => default; public static T F3<T>(T? t) => default!; public static T? F4<T>(T? t) => default; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3 F4(x).ToString(); // 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); // 7 F4(y).ToString(); // 8 F1(default(T)).ToString(); // 9 F2(default(T?)).ToString(); // 10 F3(default(T)).ToString(); // 11 F4(default(T?)).ToString(); // 12 } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB2 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : class { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); // 3 F2(y).ToString(); // 4 F3(y).ToString(); F4(y).ToString(); // 5 F1(default(T)).ToString(); // 6 F2(default(T?)).ToString(); // 7 F3(default(T)).ToString(); F4(default(T?)).ToString(); // 8 } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB3 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : class? { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3 F4(x).ToString(); // 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); // 7 F4(y).ToString(); // 8 F1(default(T)).ToString(); // 9 F2(default(T?)).ToString(); // 10 F3(default(T)).ToString(); // 11 F4(default(T?)).ToString(); // 12 } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB4 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : struct { F1(x).ToString(); F2(x).ToString(); F3(x).ToString(); F4(x).ToString(); F1(y).Value.ToString(); // 1 F2(y).Value.ToString(); // 2 F3(y).Value.ToString(); // 3 F4(y).Value.ToString(); // 4 F1(default(T)).ToString(); F2(default(T?)).Value.ToString(); // 5 F3(default(T?)).Value.ToString(); // 6 F4(default(T?)).Value.ToString(); // 7 } }"; comp = CreateCompilation(sourceB4, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y)").WithLocation(14, 9), // (16,9): warning CS8629: Nullable value type may be null. // F2(default(T?)).Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8629: Nullable value type may be null. // F3(default(T?)).Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(default(T?))").WithLocation(17, 9), // (18,9): warning CS8629: Nullable value type may be null. // F4(default(T?)).Value.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(default(T?))").WithLocation(18, 9)); var sourceB5 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : notnull { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); F2(y).ToString(); // 3 F3(y).ToString(); F4(y).ToString(); // 4 F1(default(T)).ToString(); // 5 F2(default(T?)).ToString(); // 6 F3(default(T)).ToString(); F4(default(T?)).ToString(); // 7 } }"; comp = CreateCompilation(sourceB5, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB6 = @"#nullable enable using static A; class B { static void M(string x, string? y) { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); // 3 F2(y).ToString(); // 4 F3(y).ToString(); F4(y).ToString(); // 5 F1(default(string)).ToString(); // 6 F2(default(string?)).ToString(); // 7 F3(default(string)).ToString(); F4(default(string?)).ToString(); // 8 } }"; comp = CreateCompilation(sourceB6, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(string)).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(string))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(string?)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(string?))").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(string?)).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(string?))").WithLocation(18, 9)); var sourceB7 = @"#nullable enable using static A; class B { static void M(int x, int? y) { F1(x).ToString(); F2(x).ToString(); F3(x).ToString(); F4(x).ToString(); F1(y).Value.ToString(); // 1 F2(y).Value.ToString(); // 2 F3(y).Value.ToString(); // 3 F4(y).Value.ToString(); // 4 F1(default(int)).ToString(); F2(default(int?)).Value.ToString(); // 5 F3(default(int?)).Value.ToString(); // 6 F4(default(int?)).Value.ToString(); // 7 } }"; comp = CreateCompilation(sourceB7, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y)").WithLocation(14, 9), // (16,9): warning CS8629: Nullable value type may be null. // F2(default(int?)).Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(default(int?))").WithLocation(16, 9), // (17,9): warning CS8629: Nullable value type may be null. // F3(default(int?)).Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(default(int?))").WithLocation(17, 9), // (18,9): warning CS8629: Nullable value type may be null. // F4(default(int?)).Value.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(default(int?))").WithLocation(18, 9)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_12(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I<T> { T P { get; } } public class A { public static I<T> F1<T>(T t) => default!; public static I<T?> F2<T>(T t) => default!; public static I<T> F3<T>(T? t) => default!; public static I<T?> F4<T>(T? t) => default!; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) { F1(x).P.ToString(); // 1 F2(x).P.ToString(); // 2 F3(x).P.ToString(); // 3 F4(x).P.ToString(); // 4 F1(y).P.ToString(); // 5 F2(y).P.ToString(); // 6 F3(y).P.ToString(); // 7 F4(y).P.ToString(); // 8 F1(default(T)).P.ToString(); // 9 F2(default(T?)).P.ToString(); // 10 F3(default(T)).P.ToString(); // 11 F4(default(T?)).P.ToString(); // 12 } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x).P").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x).P").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x).P").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x).P").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).P.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y).P").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).P.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y).P").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).P.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y).P").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).P.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T)).P").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).P.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?)).P").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).P.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T)).P").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).P.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?)).P").WithLocation(18, 9)); var sourceB2 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : class { F1(x).P.ToString(); F2(x).P.ToString(); // 1 F3(x).P.ToString(); F4(x).P.ToString(); // 2 F1(y).P.ToString(); // 3 F2(y).P.ToString(); // 4 F3(y).P.ToString(); F4(y).P.ToString(); // 5 F1(default(T)).P.ToString(); // 6 F2(default(T?)).P.ToString(); // 7 F3(default(T)).P.ToString(); F4(default(T?)).P.ToString(); // 8 } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x).P").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x).P").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y).P").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).P.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y).P").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T)).P").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).P.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?)).P").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).P.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?)).P").WithLocation(18, 9)); var sourceB3 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : class? { F1(x).P.ToString(); // 1 F2(x).P.ToString(); // 2 F3(x).P.ToString(); // 3 F4(x).P.ToString(); // 4 F1(y).P.ToString(); // 5 F2(y).P.ToString(); // 6 F3(y).P.ToString(); // 7 F4(y).P.ToString(); // 8 F1(default(T)).P.ToString(); // 9 F2(default(T?)).P.ToString(); // 10 F3(default(T)).P.ToString(); // 11 F4(default(T?)).P.ToString(); // 12 } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x).P").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x).P").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x).P").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x).P").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).P.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y).P").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).P.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y).P").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).P.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y).P").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).P.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T)).P").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).P.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?)).P").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).P.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T)).P").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).P.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?)).P").WithLocation(18, 9)); var sourceB4 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : struct { F1(x).P.ToString(); F2(x).P.ToString(); F3(x).P.ToString(); F4(x).P.ToString(); F1(y).P.Value.ToString(); // 1 F2(y).P.Value.ToString(); // 2 F3(y).P.Value.ToString(); // 3 F4(y).P.Value.ToString(); // 4 F1(default(T)).P.ToString(); F2(default(T?)).P.Value.ToString(); // 5 F3(default(T?)).P.Value.ToString(); // 6 F4(default(T?)).P.Value.ToString(); // 7 } }"; comp = CreateCompilation(sourceB4, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).P.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).P.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y).P").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).P.Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y).P").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).P.Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y).P").WithLocation(14, 9), // (16,9): warning CS8629: Nullable value type may be null. // F2(default(T?)).P.Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(default(T?)).P").WithLocation(16, 9), // (17,9): warning CS8629: Nullable value type may be null. // F3(default(T?)).P.Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(default(T?)).P").WithLocation(17, 9), // (18,9): warning CS8629: Nullable value type may be null. // F4(default(T?)).P.Value.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(default(T?)).P").WithLocation(18, 9)); var sourceB5 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : notnull { F1(x).P.ToString(); F2(x).P.ToString(); // 1 F3(x).P.ToString(); F4(x).P.ToString(); // 2 F1(y).P.ToString(); F2(y).P.ToString(); // 3 F3(y).P.ToString(); F4(y).P.ToString(); // 4 F1(default(T)).P.ToString(); // 5 F2(default(T?)).P.ToString(); // 6 F3(default(T)).P.ToString(); F4(default(T?)).P.ToString(); // 7 } }"; comp = CreateCompilation(sourceB5, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x).P").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x).P").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y).P").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y).P").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).P.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T)).P").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?)).P").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).P.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?)).P").WithLocation(18, 9)); var sourceB6 = @"#nullable enable using static A; class B { static void M(string x, string? y) { F1(x).P.ToString(); F2(x).P.ToString(); // 1 F3(x).P.ToString(); F4(x).P.ToString(); // 2 F1(y).P.ToString(); // 3 F2(y).P.ToString(); // 4 F3(y).P.ToString(); F4(y).P.ToString(); // 5 F1(default(string)).P.ToString(); // 6 F2(default(string?)).P.ToString(); // 7 F3(default(string)).P.ToString(); F4(default(string?)).P.ToString(); // 8 } }"; comp = CreateCompilation(sourceB6, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x).P").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x).P").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y).P").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).P.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y).P").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(string)).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(string)).P").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(string?)).P.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(string?)).P").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(string?)).P.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(string?)).P").WithLocation(18, 9)); var sourceB7 = @"#nullable enable using static A; class B { static void M(int x, int? y) { F1(x).P.ToString(); F2(x).P.ToString(); F3(x).P.ToString(); F4(x).P.ToString(); F1(y).P.Value.ToString(); // 1 F2(y).P.Value.ToString(); // 2 F3(y).P.Value.ToString(); // 3 F4(y).P.Value.ToString(); // 4 F1(default(int)).P.ToString(); F2(default(int?)).P.Value.ToString(); // 5 F3(default(int?)).P.Value.ToString(); // 6 F4(default(int?)).P.Value.ToString(); // 7 } }"; comp = CreateCompilation(sourceB7, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).P.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).P.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y).P").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).P.Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y).P").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).P.Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y).P").WithLocation(14, 9), // (16,9): warning CS8629: Nullable value type may be null. // F2(default(int?)).P.Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(default(int?)).P").WithLocation(16, 9), // (17,9): warning CS8629: Nullable value type may be null. // F3(default(int?)).P.Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(default(int?)).P").WithLocation(17, 9), // (18,9): warning CS8629: Nullable value type may be null. // F4(default(int?)).P.Value.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(default(int?)).P").WithLocation(18, 9)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_13(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I<T> { } public class A { public static T F1<T>(I<T> t) => default!; public static T? F2<T>(I<T> t) => default; public static T F3<T>(I<T?> t) => default!; public static T? F4<T>(I<T?> t) => default; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable using static A; class B { static void M<T>(I<T> x, I<T?> y) { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3, 4 F4(x).ToString(); // 5, 6 F1(y).ToString(); // 7 F2(y).ToString(); // 8 F3(y).ToString(); // 9 F4(y).ToString(); // 10 } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(9, 9), // (9,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T A.F3<T>(I<T?> t)' due to differences in the nullability of reference types. // F3(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T A.F3<T>(I<T?> t)").WithLocation(9, 12), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 5, 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (10,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T? A.F4<T>(I<T?> t)' due to differences in the nullability of reference types. // F4(x).ToString(); // 5, 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T? A.F4<T>(I<T?> t)").WithLocation(10, 12), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9)); var sourceB2 = @"#nullable enable using static A; class B { static void M<T>(I<T> x, I<T?> y) where T : class { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); // 2 F4(x).ToString(); // 3, 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); F4(y).ToString(); // 7 } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T A.F3<T>(I<T?> t)' due to differences in the nullability of reference types. // F3(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T A.F3<T>(I<T?> t)").WithLocation(9, 12), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (10,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T? A.F4<T>(I<T?> t)' due to differences in the nullability of reference types. // F4(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T? A.F4<T>(I<T?> t)").WithLocation(10, 12), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9)); var sourceB3 = @"#nullable enable using static A; class B { static void M<T>(I<T> x, I<T?> y) where T : class? { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3, 4 F4(x).ToString(); // 5, 6 F1(y).ToString(); // 7 F2(y).ToString(); // 8 F3(y).ToString(); // 9 F4(y).ToString(); // 10 } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(9, 9), // (9,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T A.F3<T>(I<T?> t)' due to differences in the nullability of reference types. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T A.F3<T>(I<T?> t)").WithLocation(9, 12), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (10,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T? A.F4<T>(I<T?> t)' due to differences in the nullability of reference types. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T? A.F4<T>(I<T?> t)").WithLocation(10, 12), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9)); var sourceB4 = @"#nullable enable using static A; class B { static void M<T>(I<T> x, I<T?> y) where T : struct { F1(x).ToString(); F2(x).ToString(); F3(x).ToString(); F4(x).ToString(); F1(y).Value.ToString(); // 1 F2(y).Value.ToString(); // 2 F3(y).Value.ToString(); // 3 F4(y).Value.ToString(); // 4 } }"; comp = CreateCompilation(sourceB4, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y)").WithLocation(14, 9)); var sourceB5 = @"#nullable enable using static A; class B { static void M<T>(I<T> x, I<T?> y) where T : notnull { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); // 2 F4(x).ToString(); // 3, 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); F4(y).ToString(); // 7 } }"; comp = CreateCompilation(sourceB5, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T A.F3<T>(I<T?> t)' due to differences in the nullability of reference types. // F3(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T A.F3<T>(I<T?> t)").WithLocation(9, 12), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (10,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T? A.F4<T>(I<T?> t)' due to differences in the nullability of reference types. // F4(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T? A.F4<T>(I<T?> t)").WithLocation(10, 12), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9)); var sourceB6 = @"#nullable enable using static A; class B { static void M(I<string> x, I<string?> y) { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); // 2 F4(x).ToString(); // 3, 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); F4(y).ToString(); // 7 } }"; comp = CreateCompilation(sourceB6, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,12): warning CS8620: Argument of type 'I<string>' cannot be used for parameter 't' of type 'I<string?>' in 'string A.F3<string>(I<string?> t)' due to differences in the nullability of reference types. // F3(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<string>", "I<string?>", "t", "string A.F3<string>(I<string?> t)").WithLocation(9, 12), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (10,12): warning CS8620: Argument of type 'I<string>' cannot be used for parameter 't' of type 'I<string?>' in 'string? A.F4<string>(I<string?> t)' due to differences in the nullability of reference types. // F4(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<string>", "I<string?>", "t", "string? A.F4<string>(I<string?> t)").WithLocation(10, 12), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9)); var sourceB7 = @"#nullable enable using static A; class B { static void M(I<int> x, I<int?> y) { F1(x).ToString(); F2(x).ToString(); F3(x).ToString(); F4(x).ToString(); F1(y).Value.ToString(); // 1 F2(y).Value.ToString(); // 2 F3(y).Value.ToString(); // 3 F4(y).Value.ToString(); // 4 } }"; comp = CreateCompilation(sourceB7, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y)").WithLocation(14, 9)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_14(bool useCompilationReference) { var sourceA = @"#nullable enable using System.Diagnostics.CodeAnalysis; public class A { public static T F1<T>(T t) => default!; [return: MaybeNull] public static T F2<T>(T t) => default; public static T F3<T>([AllowNull]T t) => default!; [return: MaybeNull] public static T F4<T>([AllowNull]T t) => default; }"; var comp = CreateCompilation(new[] { sourceA, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3 F4(x).ToString(); // 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); // 7 F4(y).ToString(); // 8 F1(default(T)).ToString(); // 9 F2(default(T?)).ToString(); // 10 F3(default(T)).ToString(); // 11 F4(default(T?)).ToString(); // 12 } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB2 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : class { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); // 3 F2(y).ToString(); // 4 F3(y).ToString(); // 5 F4(y).ToString(); // 6 F1(default(T)).ToString(); // 7 F2(default(T?)).ToString(); // 8 F3(default(T)).ToString(); // 9 F4(default(T?)).ToString(); // 10 } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB3 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : class? { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3 F4(x).ToString(); // 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); // 7 F4(y).ToString(); // 8 F1(default(T)).ToString(); // 9 F2(default(T?)).ToString(); // 10 F3(default(T)).ToString(); // 11 F4(default(T?)).ToString(); // 12 } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB4 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : struct { F1(x).ToString(); F2(x).ToString(); F3(x).ToString(); F4(x).ToString(); F1(y).Value.ToString(); // 1 F2(y).Value.ToString(); // 2 F3(y).Value.ToString(); // 3 F4(y).Value.ToString(); // 4 F1(default(T)).ToString(); F2(default(T?)).Value.ToString(); // 5 F3(default(T?)).Value.ToString(); // 6 F4(default(T?)).Value.ToString(); // 7 } }"; comp = CreateCompilation(sourceB4, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y)").WithLocation(14, 9), // (16,9): warning CS8629: Nullable value type may be null. // F2(default(T?)).Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8629: Nullable value type may be null. // F3(default(T?)).Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(default(T?))").WithLocation(17, 9), // (18,9): warning CS8629: Nullable value type may be null. // F4(default(T?)).Value.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(default(T?))").WithLocation(18, 9)); var sourceB5 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : notnull { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); F2(y).ToString(); // 3 F3(y).ToString(); // 4 F4(y).ToString(); // 5 F1(default(T)).ToString(); // 6 F2(default(T?)).ToString(); // 7 F3(default(T)).ToString(); // 8 F4(default(T?)).ToString(); // 9 } }"; comp = CreateCompilation(sourceB5, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_15(bool useCompilationReference) { var sourceA = @"#nullable enable public class A { public static T F1<T>(T t) => default!; public static T? F2<T>(T t) => default; public static T F3<T>(T? t) => default!; public static T? F4<T>(T? t) => default; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable using System.Diagnostics.CodeAnalysis; using static A; class B { static void M<T>(T x, [AllowNull]T y) { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3 F4(x).ToString(); // 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); // 7 F4(y).ToString(); // 8 F1(default(T)).ToString(); // 9 F2(default(T)).ToString(); // 10 F3(default(T)).ToString(); // 11 F4(default(T)).ToString(); // 12 } }"; comp = CreateCompilation(new[] { sourceB1, AllowNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T)).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T))").WithLocation(19, 9)); var sourceB3 = @"#nullable enable using System.Diagnostics.CodeAnalysis; using static A; class B { static void M<T>(T x, [AllowNull]T y) where T : class? { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3 F4(x).ToString(); // 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); // 7 F4(y).ToString(); // 8 F1(default(T)).ToString(); // 9 F2(default(T)).ToString(); // 10 F3(default(T)).ToString(); // 11 F4(default(T)).ToString(); // 12 } }"; comp = CreateCompilation(new[] { sourceB3, AllowNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T)).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T))").WithLocation(19, 9)); var sourceB5 = @"#nullable enable using System.Diagnostics.CodeAnalysis; using static A; class B { static void M<T>(T x, [AllowNull]T y) where T : notnull { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); F2(y).ToString(); // 3 F3(y).ToString(); F4(y).ToString(); // 4 F1(default(T)).ToString(); // 5 F2(default(T)).ToString(); // 6 F3(default(T)).ToString(); F4(default(T)).ToString(); // 7 } }"; comp = CreateCompilation(new[] { sourceB5, AllowNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T)).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T))").WithLocation(17, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T))").WithLocation(19, 9)); var sourceB6 = @"#nullable enable using System.Diagnostics.CodeAnalysis; using static A; class B { static void M(string x, [AllowNull]string y) { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); // 3 F2(y).ToString(); // 4 F3(y).ToString(); F4(y).ToString(); // 5 F1(default(string)).ToString(); // 6 F2(default(string)).ToString(); // 7 F3(default(string)).ToString(); F4(default(string)).ToString(); // 8 } }"; comp = CreateCompilation(new[] { sourceB6, AllowNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F1(default(string)).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(string))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F2(default(string)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(string))").WithLocation(17, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // F4(default(string)).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(string))").WithLocation(19, 9)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_16(bool useCompilationReference) { var sourceA = @"#nullable enable using System.Diagnostics.CodeAnalysis; public interface I { } public abstract class A1 { [return: MaybeNull] public abstract T F1<T>(); [return: MaybeNull] public abstract T F2<T>() where T : class; [return: MaybeNull] public abstract T F3<T>() where T : class?; [return: MaybeNull] public abstract T F4<T>() where T : notnull; [return: MaybeNull] public abstract T F5<T>() where T : I; [return: MaybeNull] public abstract T F6<T>() where T : I?; } public abstract class A2 { public abstract void F1<T>([AllowNull] T t); public abstract void F2<T>([AllowNull] T t) where T : class; public abstract void F3<T>([AllowNull] T t) where T : class?; public abstract void F4<T>([AllowNull] T t) where T : notnull; public abstract void F5<T>([AllowNull] T t) where T : I; public abstract void F6<T>([AllowNull] T t) where T : I?; }"; var comp = CreateCompilation(new[] { sourceA, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable class B1 : A1 { public override T F1<T>() => default!; public override T F2<T>() => default!; public override T F3<T>() => default!; public override T F4<T>() => default!; public override T F5<T>() => default!; public override T F6<T>() => default!; } class B2 : A2 { public override void F1<T>(T t) { } // 1 public override void F2<T>(T t) { } // 2 public override void F3<T>(T t) { } // 3 public override void F4<T>(T t) { } // 4 public override void F5<T>(T t) { } // 5 public override void F6<T>(T t) { } // 6 }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>(T t) { } // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t").WithLocation(13, 26), // (14,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<T>(T t) { } // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t").WithLocation(14, 26), // (15,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F3<T>(T t) { } // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t").WithLocation(15, 26), // (16,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F4<T>(T t) { } // 4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t").WithLocation(16, 26), // (17,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F5<T>(T t) { } // 5 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t").WithLocation(17, 26), // (18,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F6<T>(T t) { } // 6 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t").WithLocation(18, 26)); var sourceB2 = @"#nullable enable class B1 : A1 { public override T? F1<T>() => default; // 1 public override T? F2<T>() => default; // 2 public override T? F3<T>() => default; // 3 public override T? F4<T>() => default; // 4 public override T? F5<T>() => default; // 5 public override T? F6<T>() => default; // 6 } class B2 : A2 { public override void F1<T>(T? t) { } // 7 public override void F2<T>(T? t) { } // 8 public override void F3<T>(T? t) { } // 9 public override void F4<T>(T? t) { } // 10 public override void F5<T>(T? t) { } // 11 public override void F6<T>(T? t) { } // 12 }"; comp = CreateCompilation(sourceB2, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,24): error CS0508: 'B1.F1<T>()': return type must be 'T' to match overridden member 'A1.F1<T>()' // public override T? F1<T>() => default; // 1 Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F1").WithArguments("B1.F1<T>()", "A1.F1<T>()", "T").WithLocation(4, 24), // (4,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F1<T>() => default; // 1 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F1").WithArguments("System.Nullable<T>", "T", "T").WithLocation(4, 24), // (5,24): error CS0508: 'B1.F2<T>()': return type must be 'T' to match overridden member 'A1.F2<T>()' // public override T? F2<T>() => default; // 2 Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F2").WithArguments("B1.F2<T>()", "A1.F2<T>()", "T").WithLocation(5, 24), // (5,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F2<T>() => default; // 2 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F2").WithArguments("System.Nullable<T>", "T", "T").WithLocation(5, 24), // (6,24): error CS0508: 'B1.F3<T>()': return type must be 'T' to match overridden member 'A1.F3<T>()' // public override T? F3<T>() => default; // 3 Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F3").WithArguments("B1.F3<T>()", "A1.F3<T>()", "T").WithLocation(6, 24), // (6,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F3<T>() => default; // 3 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F3").WithArguments("System.Nullable<T>", "T", "T").WithLocation(6, 24), // (7,24): error CS0508: 'B1.F4<T>()': return type must be 'T' to match overridden member 'A1.F4<T>()' // public override T? F4<T>() => default; // 4 Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F4").WithArguments("B1.F4<T>()", "A1.F4<T>()", "T").WithLocation(7, 24), // (7,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F4<T>() => default; // 4 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F4").WithArguments("System.Nullable<T>", "T", "T").WithLocation(7, 24), // (8,24): error CS0508: 'B1.F5<T>()': return type must be 'T' to match overridden member 'A1.F5<T>()' // public override T? F5<T>() => default; // 5 Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F5").WithArguments("B1.F5<T>()", "A1.F5<T>()", "T").WithLocation(8, 24), // (8,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F5<T>() => default; // 5 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F5").WithArguments("System.Nullable<T>", "T", "T").WithLocation(8, 24), // (9,24): error CS0508: 'B1.F6<T>()': return type must be 'T' to match overridden member 'A1.F6<T>()' // public override T? F6<T>() => default; // 6 Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F6").WithArguments("B1.F6<T>()", "A1.F6<T>()", "T").WithLocation(9, 24), // (9,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F6<T>() => default; // 6 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F6").WithArguments("System.Nullable<T>", "T", "T").WithLocation(9, 24), // (11,7): error CS0534: 'B2' does not implement inherited abstract member 'A2.F5<T>(T)' // class B2 : A2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A2.F5<T>(T)").WithLocation(11, 7), // (11,7): error CS0534: 'B2' does not implement inherited abstract member 'A2.F4<T>(T)' // class B2 : A2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A2.F4<T>(T)").WithLocation(11, 7), // (11,7): error CS0534: 'B2' does not implement inherited abstract member 'A2.F6<T>(T)' // class B2 : A2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A2.F6<T>(T)").WithLocation(11, 7), // (11,7): error CS0534: 'B2' does not implement inherited abstract member 'A2.F1<T>(T)' // class B2 : A2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A2.F1<T>(T)").WithLocation(11, 7), // (11,7): error CS0534: 'B2' does not implement inherited abstract member 'A2.F3<T>(T)' // class B2 : A2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A2.F3<T>(T)").WithLocation(11, 7), // (11,7): error CS0534: 'B2' does not implement inherited abstract member 'A2.F2<T>(T)' // class B2 : A2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A2.F2<T>(T)").WithLocation(11, 7), // (13,26): error CS0115: 'B2.F1<T>(T?)': no suitable method found to override // public override void F1<T>(T? t) { } // 7 Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2.F1<T>(T?)").WithLocation(13, 26), // (13,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<T>(T? t) { } // 7 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(13, 35), // (14,26): error CS0115: 'B2.F2<T>(T?)': no suitable method found to override // public override void F2<T>(T? t) { } // 8 Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2.F2<T>(T?)").WithLocation(14, 26), // (14,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<T>(T? t) { } // 8 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(14, 35), // (15,26): error CS0115: 'B2.F3<T>(T?)': no suitable method found to override // public override void F3<T>(T? t) { } // 9 Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F3").WithArguments("B2.F3<T>(T?)").WithLocation(15, 26), // (15,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F3<T>(T? t) { } // 9 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(15, 35), // (16,26): error CS0115: 'B2.F4<T>(T?)': no suitable method found to override // public override void F4<T>(T? t) { } // 10 Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F4").WithArguments("B2.F4<T>(T?)").WithLocation(16, 26), // (16,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F4<T>(T? t) { } // 10 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(16, 35), // (17,26): error CS0115: 'B2.F5<T>(T?)': no suitable method found to override // public override void F5<T>(T? t) { } // 11 Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F5").WithArguments("B2.F5<T>(T?)").WithLocation(17, 26), // (17,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F5<T>(T? t) { } // 11 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(17, 35), // (18,26): error CS0115: 'B2.F6<T>(T?)': no suitable method found to override // public override void F6<T>(T? t) { } // 12 Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F6").WithArguments("B2.F6<T>(T?)").WithLocation(18, 26), // (18,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F6<T>(T? t) { } // 12 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(18, 35)); var sourceB3 = @"#nullable enable class B1 : A1 { public override T? F1<T>() where T : default => default; public override T? F2<T>() where T : class => default; public override T? F3<T>() where T : class => default; public override T? F4<T>() where T : default => default; public override T? F5<T>() where T : default => default; public override T? F6<T>() where T : default => default; } class B2 : A2 { public override void F1<T>(T? t) where T : default { } public override void F2<T>(T? t) where T : class { } public override void F3<T>(T? t) where T : class { } public override void F4<T>(T? t) where T : default { } public override void F5<T>(T? t) where T : default { } public override void F6<T>(T? t) where T : default { } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_17(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I { } public abstract class A1 { public abstract T? F1<T>(); public abstract T? F2<T>() where T : class; public abstract T? F3<T>() where T : class?; public abstract T? F4<T>() where T : notnull; public abstract T? F5<T>() where T : I; public abstract T? F6<T>() where T : I?; } public abstract class A2 { public abstract void F1<T>(T? t); public abstract void F2<T>(T? t) where T : class; public abstract void F3<T>(T? t) where T : class?; public abstract void F4<T>(T? t) where T : notnull; public abstract void F5<T>(T? t) where T : I; public abstract void F6<T>(T? t) where T : I?; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable class B1 : A1 { public override T F1<T>() => default!; public override T F2<T>() => default!; public override T F3<T>() => default!; public override T F4<T>() => default!; public override T F5<T>() => default!; public override T F6<T>() => default!; } class B2 : A2 { public override void F1<T>(T t) { } public override void F2<T>(T t) { } public override void F3<T>(T t) { } public override void F4<T>(T t) { } public override void F5<T>(T t) { } public override void F6<T>(T t) { } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }); comp.VerifyDiagnostics( // (13,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>(T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t").WithLocation(13, 26), // (14,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<T>(T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t").WithLocation(14, 26), // (15,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F3<T>(T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t").WithLocation(15, 26), // (16,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F4<T>(T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t").WithLocation(16, 26), // (17,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F5<T>(T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t").WithLocation(17, 26), // (18,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F6<T>(T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t").WithLocation(18, 26)); var sourceB2 = @"#nullable enable using System.Diagnostics.CodeAnalysis; class B1 : A1 { [return: MaybeNull] public override T F1<T>() => default; [return: MaybeNull] public override T F2<T>() => default; [return: MaybeNull] public override T F3<T>() => default; [return: MaybeNull] public override T F4<T>() => default; [return: MaybeNull] public override T F5<T>() => default; [return: MaybeNull] public override T F6<T>() => default; } class B2 : A2 { public override void F1<T>([AllowNull] T t) { } public override void F2<T>([AllowNull] T t) { } public override void F3<T>([AllowNull] T t) { } public override void F4<T>([AllowNull] T t) { } public override void F5<T>([AllowNull] T t) { } public override void F6<T>([AllowNull] T t) { } }"; comp = CreateCompilation(new[] { sourceB2, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics(); } [Fact] public void UnconstrainedTypeParameter_18() { var source = @"#nullable enable class Program { static void F<T>(T t) { } static void F1<T1>() { F<T1>(default); // 1 F<T1?>(default); } static void F2<T2>() where T2 : class { F<T2>(default); // 2 F<T2?>(default); } static void F3<T3>() where T3 : class? { F<T3>(default); // 3 F<T3?>(default); } static void F4<T4>() where T4 : struct { F<T4>(default); F<T4?>(default); } static void F5<T5>() where T5 : notnull { F<T5>(default); // 4 F<T5?>(default); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F<T1>(T1 t)'. // F<T1>(default); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void Program.F<T1>(T1 t)").WithLocation(9, 15), // (14,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F<T2>(default); // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(14, 15), // (19,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F<T3>(default); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(19, 15), // (29,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F<T5>(T5 t)'. // F<T5>(default); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void Program.F<T5>(T5 t)").WithLocation(29, 15)); } [Fact] public void UnconstrainedTypeParameter_19() { var source1 = @"#nullable enable class Program { static T1 F1<T1>() => default(T1); // 1 static T2 F2<T2>() where T2 : class => default(T2); // 2 static T3 F3<T3>() where T3 : class? => default(T3); // 3 static T4 F4<T4>() where T4 : notnull => default(T4); // 4 }"; var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,27): warning CS8603: Possible null reference return. // static T1 F1<T1>() => default(T1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T1)").WithLocation(4, 27), // (5,44): warning CS8603: Possible null reference return. // static T2 F2<T2>() where T2 : class => default(T2); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T2)").WithLocation(5, 44), // (6,45): warning CS8603: Possible null reference return. // static T3 F3<T3>() where T3 : class? => default(T3); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T3)").WithLocation(6, 45), // (7,46): warning CS8603: Possible null reference return. // static T4 F4<T4>() where T4 : notnull => default(T4); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T4)").WithLocation(7, 46)); var source2 = @"#nullable enable class Program { static T1? F1<T1>() => default(T1); static T2? F2<T2>() where T2 : class => default(T2); static T3? F3<T3>() where T3 : class? => default(T3); static T4? F4<T4>() where T4 : notnull => default(T4); }"; comp = CreateCompilation(source2, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var source3 = @"#nullable enable class Program { static T1 F1<T1>() => default(T1?); // 1 static T2 F2<T2>() where T2 : class => default(T2?); // 2 static T3 F3<T3>() where T3 : class? => default(T3?); // 3 static T4 F4<T4>() where T4 : notnull => default(T4?); // 4 }"; comp = CreateCompilation(source3, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,27): warning CS8603: Possible null reference return. // static T1 F1<T1>() => default(T1?); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T1?)").WithLocation(4, 27), // (5,44): warning CS8603: Possible null reference return. // static T2 F2<T2>() where T2 : class => default(T2?); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T2?)").WithLocation(5, 44), // (6,45): warning CS8603: Possible null reference return. // static T3 F3<T3>() where T3 : class? => default(T3?); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T3?)").WithLocation(6, 45), // (7,46): warning CS8603: Possible null reference return. // static T4 F4<T4>() where T4 : notnull => default(T4?); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T4?)").WithLocation(7, 46)); var source4 = @"#nullable enable class Program { static T1? F1<T1>() => default(T1?); static T2? F2<T2>() where T2 : class => default(T2?); static T3? F3<T3>() where T3 : class? => default(T3?); static T4? F4<T4>() where T4 : notnull => default(T4?); }"; comp = CreateCompilation(source4, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void UnconstrainedTypeParameter_20() { var source = @"#nullable enable delegate T D1<T>(); delegate T? D2<T>(); class Program { static T F1<T>(D1<T> d) => default!; static T F2<T>(D2<T> d) => default!; static void M1<T>() { var x1 = F1<T>(() => default); // 1 var x2 = F2<T>(() => default); var x3 = F1<T?>(() => default); var x4 = F2<T?>(() => default); x1.ToString(); // 2 x2.ToString(); // 3 x3.ToString(); // 4 x4.ToString(); // 5 } static void M2<T>() { var x1 = F1(() => default(T)); // 6 var x2 = F2(() => default(T)); var y1 = F1(() => default(T?)); var y2 = F2(() => default(T?)); x1.ToString(); // 7 x2.ToString(); // 8 y1.ToString(); // 9 y2.ToString(); // 10 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,30): warning CS8603: Possible null reference return. // var x1 = F1<T>(() => default); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(10, 30), // (14,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // x4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(17, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(25, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(26, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(27, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(28, 9)); } [WorkItem(46044, "https://github.com/dotnet/roslyn/issues/46044")] [Fact] public void UnconstrainedTypeParameter_21() { var source = @"#nullable enable class C<T> { static void F1(T t) { } static void F2(T? t) { } static void M(bool b, T x, T? y) { if (b) F2(x); if (b) F2((T)x); if (b) F2((T?)x); if (b) F1(y); // 1 if (b) F1((T)y); // 2, 3 if (b) F1((T?)y); // 4 if (b) F1(default); // 5 if (b) F1(default(T)); // 6 if (b) F2(default); if (b) F2(default(T)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,19): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F1(T t)'. // if (b) F1(y); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("t", "void C<T>.F1(T t)").WithLocation(11, 19), // (12,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (b) F1((T)y); // 2, 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)y").WithLocation(12, 19), // (12,19): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F1(T t)'. // if (b) F1((T)y); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(T)y").WithArguments("t", "void C<T>.F1(T t)").WithLocation(12, 19), // (13,19): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F1(T t)'. // if (b) F1((T?)y); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(T?)y").WithArguments("t", "void C<T>.F1(T t)").WithLocation(13, 19), // (14,19): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F1(T t)'. // if (b) F1(default); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void C<T>.F1(T t)").WithLocation(14, 19), // (15,19): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F1(T t)'. // if (b) F1(default(T)); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default(T)").WithArguments("t", "void C<T>.F1(T t)").WithLocation(15, 19)); } [Fact] public void UnconstrainedTypeParameter_22() { var source = @"#nullable enable using System.Collections.Generic; class C<T> { static void F1(IEnumerable<T> e) { } static void F2(IEnumerable<T?> e) { } static void M1(IEnumerable<T> x1, IEnumerable<T?> y1) { F1(x1); F1(y1); // 1 F2(x1); F2(y1); } static void M2(List<T> x2, List<T?> y2) { F1(x2); F1(y2); // 2 F2(x2); F2(y2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,12): warning CS8620: Argument of type 'IEnumerable<T?>' cannot be used for parameter 'e' of type 'IEnumerable<T>' in 'void C<T>.F1(IEnumerable<T> e)' due to differences in the nullability of reference types. // F1(y1); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("System.Collections.Generic.IEnumerable<T?>", "System.Collections.Generic.IEnumerable<T>", "e", "void C<T>.F1(IEnumerable<T> e)").WithLocation(10, 12), // (17,12): warning CS8620: Argument of type 'List<T?>' cannot be used for parameter 'e' of type 'IEnumerable<T>' in 'void C<T>.F1(IEnumerable<T> e)' due to differences in the nullability of reference types. // F1(y2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y2").WithArguments("System.Collections.Generic.List<T?>", "System.Collections.Generic.IEnumerable<T>", "e", "void C<T>.F1(IEnumerable<T> e)").WithLocation(17, 12)); } [Fact] public void UnconstrainedTypeParameter_23() { var source = @"#nullable enable using System.Collections.Generic; class C<T> { static void F(T t) { } static void M1(IEnumerable<T?> e) { foreach (var o in e) F(o); // 1 } static void M2(T?[] a) { foreach (var o in a) F(o); // 2 } static void M3(List<T?> l) { foreach (var o in l) F(o); // 3 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,15): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F(T t)'. // F(o); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("t", "void C<T>.F(T t)").WithLocation(11, 15), // (16,15): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F(T t)'. // F(o); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("t", "void C<T>.F(T t)").WithLocation(16, 15), // (21,15): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F(T t)'. // F(o); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("t", "void C<T>.F(T t)").WithLocation(21, 15)); } [Fact] public void UnconstrainedTypeParameter_24() { var source = @"#nullable enable using System.Collections.Generic; static class E { internal static IEnumerable<T> GetEnumerable<T>(this T t) => new[] { t }; } class C<T> { static void F(T t) { } static void M1(T x) { foreach (var ix in x.GetEnumerable()) F(ix); // 1 } static void M2(T? y) { foreach (var iy in y.GetEnumerable()) F(iy); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (20,15): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F(T t)'. // F(iy); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "iy").WithArguments("t", "void C<T>.F(T t)").WithLocation(20, 15)); } [Fact] public void UnconstrainedTypeParameter_25() { var source = @"#nullable enable interface I<out T> { } class Program { static void F1<T>(bool b, T x1, T? y1) { T? t1 = b ? x1 : x1; T? t2 = b ? x1 : y1; T? t3 = b ? y1 : x1; T? t4 = b ? y1 : y1; } static void F2<T>(bool b, T x2, T? y2) { ref T t1 = ref b ? ref x2 : ref x2; ref T? t2 = ref b ? ref x2 : ref y2; // 1 ref T? t3 = ref b ? ref y2 : ref x2; // 2 ref T? t4 = ref b ? ref y2 : ref y2; } static void F3<T>(bool b, I<T> x3, I<T?> y3) { I<T?> t1 = b ? x3 : x3; I<T?> t2 = b ? x3 : y3; I<T?> t3 = b ? y3 : x3; I<T?> t4 = b ? y3 : y3; } static void F4<T>(bool b, I<T> x4, I<T?> y4) { ref I<T> t1 = ref b ? ref x4 : ref x4; ref I<T?> t2 = ref b ? ref x4 : ref y4; // 3 ref I<T?> t3 = ref b ? ref y4 : ref x4; // 4 ref I<T?> t4 = ref b ? ref y4 : ref y4; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (15,25): warning CS8619: Nullability of reference types in value of type 'T' doesn't match target type 'T?'. // ref T? t2 = ref b ? ref x2 : ref y2; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x2 : ref y2").WithArguments("T", "T?").WithLocation(15, 25), // (15,25): warning CS8619: Nullability of reference types in value of type 'T' doesn't match target type 'T?'. // ref T? t2 = ref b ? ref x2 : ref y2; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x2 : ref y2").WithArguments("T", "T?").WithLocation(15, 25), // (16,25): warning CS8619: Nullability of reference types in value of type 'T?' doesn't match target type 'T'. // ref T? t3 = ref b ? ref y2 : ref x2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y2 : ref x2").WithArguments("T?", "T").WithLocation(16, 25), // (16,25): warning CS8619: Nullability of reference types in value of type 'T' doesn't match target type 'T?'. // ref T? t3 = ref b ? ref y2 : ref x2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y2 : ref x2").WithArguments("T", "T?").WithLocation(16, 25), // (29,28): warning CS8619: Nullability of reference types in value of type 'I<T>' doesn't match target type 'I<T?>'. // ref I<T?> t2 = ref b ? ref x4 : ref y4; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x4 : ref y4").WithArguments("I<T>", "I<T?>").WithLocation(29, 28), // (30,28): warning CS8619: Nullability of reference types in value of type 'I<T?>' doesn't match target type 'I<T>'. // ref I<T?> t3 = ref b ? ref y4 : ref x4; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y4 : ref x4").WithArguments("I<T?>", "I<T>").WithLocation(30, 28)); } [Fact] public void UnconstrainedTypeParameter_26() { var source = @"#nullable enable interface I<out T> { } class Program { static void FA<T>(ref T x, ref T? y) { } static void FB<T>(ref I<T> x, ref I<T?> y) { } static void F1<T>(T x1, T? y1) { FA(ref x1, ref y1); } static void F2<T>(T x2, T? y2) { FA(ref y2, ref x2); // 1 } static void F3<T>(T x3, T? y3) { FA<T>(ref x3, ref y3); } static void F4<T>(T x4, T? y4) { FA<T?>(ref x4, ref y4); } static void F5<T>(I<T> x5, I<T?> y5) { FB(ref x5, ref y5); } static void F6<T>(I<T> x6, I<T?> y6) { FB(ref y6, ref x6); // 2, 3 } static void F7<T>(I<T> x7, I<T?> y7) { FB<T>(ref x7, ref y7); } static void F8<T>(I<T> x8, I<T?> y8) { FB<T?>(ref x8, ref y8); // 4 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,16): warning CS8601: Possible null reference assignment. // FA(ref y2, ref x2); // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y2").WithLocation(13, 16), // (13,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // FA(ref y2, ref x2); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(13, 24), // (21,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // FA<T?>(ref x4, ref y4); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x4").WithLocation(21, 20), // (29,16): warning CS8620: Argument of type 'I<T?>' cannot be used for parameter 'x' of type 'I<T>' in 'void Program.FB<T>(ref I<T> x, ref I<T?> y)' due to differences in the nullability of reference types. // FB(ref y6, ref x6); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y6").WithArguments("I<T?>", "I<T>", "x", "void Program.FB<T>(ref I<T> x, ref I<T?> y)").WithLocation(29, 16), // (29,24): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 'y' of type 'I<T?>' in 'void Program.FB<T>(ref I<T> x, ref I<T?> y)' due to differences in the nullability of reference types. // FB(ref y6, ref x6); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x6").WithArguments("I<T>", "I<T?>", "y", "void Program.FB<T>(ref I<T> x, ref I<T?> y)").WithLocation(29, 24), // (37,20): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 'x' of type 'I<T?>' in 'void Program.FB<T?>(ref I<T?> x, ref I<T?> y)' due to differences in the nullability of reference types. // FB<T?>(ref x8, ref y8); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x8").WithArguments("I<T>", "I<T?>", "x", "void Program.FB<T?>(ref I<T?> x, ref I<T?> y)").WithLocation(37, 20)); } [Fact] [WorkItem(46150, "https://github.com/dotnet/roslyn/issues/46150")] public void UnconstrainedTypeParameter_27() { var source1 = @"#nullable enable class A<T> { static T F1<U>(U u) where U : T => u; static T F2<U>(U u) where U : T? => u; // 1 static T? F3<U>(U u) where U : T => u; static T? F4<U>(U u) where U : T? => u; static T F5<U>(U? u) where U : T => u; // 2 static T F6<U>(U? u) where U : T? => u; // 3 static T? F7<U>(U? u) where U : T => u; static T? F8<U>(U? u) where U : T? => u; }"; var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,41): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 41), // (8,41): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 41), // (9,42): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 42)); var source2 = @"#nullable enable class A<T> where T : class { static T F1<U>(U u) where U : T => u; static T F2<U>(U u) where U : T? => u; // 1 static T? F3<U>(U u) where U : T => u; static T? F4<U>(U u) where U : T? => u; static T F5<U>(U? u) where U : T => u; // 2 static T F6<U>(U? u) where U : T? => u; // 3 static T? F7<U>(U? u) where U : T => u; static T? F8<U>(U? u) where U : T? => u; }"; comp = CreateCompilation(source2, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,41): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 41), // (8,41): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 41), // (9,42): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 42)); var source3 = @"#nullable enable class A<T> where T : class? { static T F1<U>(U u) where U : T => u; static T F2<U>(U u) where U : T? => u; // 1 static T? F3<U>(U u) where U : T => u; static T? F4<U>(U u) where U : T? => u; static T F5<U>(U? u) where U : T => u; // 2 static T F6<U>(U? u) where U : T? => u; // 3 static T? F7<U>(U? u) where U : T => u; static T? F8<U>(U? u) where U : T? => u; }"; comp = CreateCompilation(source3, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,41): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 41), // (8,41): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 41), // (9,42): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 42)); var source4 = @"#nullable enable class A<T> where T : notnull { static T F1<U>(U u) where U : T => u; static T F2<U>(U u) where U : T? => u; // 1 static T? F3<U>(U u) where U : T => u; static T? F4<U>(U u) where U : T? => u; static T F5<U>(U? u) where U : T => u; // 2 static T F6<U>(U? u) where U : T? => u; // 3 static T? F7<U>(U? u) where U : T => u; static T? F8<U>(U? u) where U : T? => u; }"; comp = CreateCompilation(source4, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,41): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 41), // (8,41): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 41), // (9,42): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 42)); var source5 = @"#nullable enable interface I { } class A<T> where T : I { static T F1<U>(U u) where U : T => u; static T F2<U>(U u) where U : T? => u; // 1 static T? F3<U>(U u) where U : T => u; static T? F4<U>(U u) where U : T? => u; static T F5<U>(U? u) where U : T => u; // 2 static T F6<U>(U? u) where U : T? => u; // 3 static T? F7<U>(U? u) where U : T => u; static T? F8<U>(U? u) where U : T? => u; }"; comp = CreateCompilation(source5, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,41): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(6, 41), // (9,41): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 41), // (10,42): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 42)); var source6 = @"#nullable enable interface I { } class A<T> where T : I? { static T F1<U>(U u) where U : T => u; static T F2<U>(U u) where U : T? => u; // 1 static T? F3<U>(U u) where U : T => u; static T? F4<U>(U u) where U : T? => u; static T F5<U>(U? u) where U : T => u; // 2 static T F6<U>(U? u) where U : T? => u; // 3 static T? F7<U>(U? u) where U : T => u; static T? F8<U>(U? u) where U : T? => u; }"; comp = CreateCompilation(source6, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,41): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(6, 41), // (9,41): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 41), // (10,42): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 42)); } [Fact] [WorkItem(46150, "https://github.com/dotnet/roslyn/issues/46150")] public void UnconstrainedTypeParameter_28() { var source = @"#nullable disable class A<T, U> where U : T #nullable enable { static T F1(U u) => u; static T? F2(U u) => u; static T F3(U? u) => u; // 1 static T? F4(U? u) => u; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,26): warning CS8603: Possible null reference return. // static T F3(U? u) => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(7, 26)); } [Fact] [WorkItem(46150, "https://github.com/dotnet/roslyn/issues/46150")] public void UnconstrainedTypeParameter_29() { var source1 = @"#nullable enable class A { static object F1<T>(T t) => t; // 1 static object? F2<T>(T t) => t; static object F3<T>(T? t) => t; // 2 static object? F4<T>(T? t) => t; }"; var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,33): warning CS8603: Possible null reference return. // static object F1<T>(T t) => t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(4, 33), // (6,34): warning CS8603: Possible null reference return. // static object F3<T>(T? t) => t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 34)); var source2 = @"#nullable enable class A { static object F1<T>(T t) where T : class => t; static object? F2<T>(T t) where T : class => t; static object F3<T>(T? t) where T : class => t; // 1 static object? F4<T>(T? t) where T : class => t; }"; comp = CreateCompilation(source2); comp.VerifyDiagnostics( // (6,50): warning CS8603: Possible null reference return. // static object F3<T>(T? t) where T : class => t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 50)); var source3 = @"#nullable enable class A { static object F1<T>(T t) where T : class? => t; // 1 static object? F2<T>(T t) where T : class? => t; static object F3<T>(T? t) where T : class? => t; // 2 static object? F4<T>(T? t) where T : class? => t; }"; comp = CreateCompilation(source3, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,50): warning CS8603: Possible null reference return. // static object F1<T>(T t) where T : class? => t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(4, 50), // (6,51): warning CS8603: Possible null reference return. // static object F3<T>(T? t) where T : class? => t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 51)); var source4 = @"#nullable enable class A { static object F1<T>(T t) where T : struct => t; static object? F2<T>(T t) where T : struct => t; static object F3<T>(T? t) where T : struct => t; // 1 static object? F4<T>(T? t) where T : struct => t; }"; comp = CreateCompilation(source4); comp.VerifyDiagnostics( // (6,51): warning CS8603: Possible null reference return. // static object F3<T>(T? t) where T : struct => t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 51)); var source5 = @"#nullable enable class A { static object F1<T>(T t) where T : notnull => t; static object? F2<T>(T t) where T : notnull => t; static object F3<T>(T? t) where T : notnull => t; // 1 static object? F4<T>(T? t) where T : notnull => t; }"; comp = CreateCompilation(source5, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,52): warning CS8603: Possible null reference return. // static object F3<T>(T? t) where T : notnull => t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 52)); } [Fact] public void UnconstrainedTypeParameter_30() { var source1 = @"#nullable enable interface I { } class Program { static I F1<T>(T t) where T : I => t; static I F2<T>(T t) where T : I? => t; // 1 static I? F3<T>(T t) where T : I => t; static I? F4<T>(T t) where T : I? => t; static I F5<T>(T? t) where T : I => t; // 2 static I F6<T>(T? t) where T : I? => t; // 3 static I? F7<T>(T? t) where T : I => t; static I? F8<T>(T? t) where T : I? => t; }"; var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,41): warning CS8603: Possible null reference return. // static I F2<T>(T t) where T : I? => t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 41), // (9,41): warning CS8603: Possible null reference return. // static I F5<T>(T? t) where T : I => t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(9, 41), // (10,42): warning CS8603: Possible null reference return. // static I F6<T>(T? t) where T : I? => t; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(10, 42)); } [Fact] [WorkItem(46150, "https://github.com/dotnet/roslyn/issues/46150")] public void UnconstrainedTypeParameter_31() { var source1 = @"#nullable enable class A<T> { static T F1<U>(U u) where U : class, T => u; static T F2<U>(U u) where U : class, T? => u; static T? F3<U>(U u) where U : class, T => u; static T? F4<U>(U u) where U : class, T? => u; static T F5<U>(U? u) where U : class, T => u; // 1 static T F6<U>(U? u) where U : class, T? => u; // 2 static T? F7<U>(U? u) where U : class, T => u; static T? F8<U>(U? u) where U : class, T? => u; }"; var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,48): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : class, T => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 48), // (9,49): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : class, T? => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 49)); var source2 = @"#nullable enable class A<T> { static T F1<U>(U u) where U : class?, T => u; static T F2<U>(U u) where U : class?, T? => u; // 1 static T? F3<U>(U u) where U : class?, T => u; static T? F4<U>(U u) where U : class?, T? => u; static T F5<U>(U? u) where U : class?, T => u; // 2 static T F6<U>(U? u) where U : class?, T? => u; // 3 static T? F7<U>(U? u) where U : class?, T => u; static T? F8<U>(U? u) where U : class?, T? => u; }"; comp = CreateCompilation(source2, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,49): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : class?, T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 49), // (8,49): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : class?, T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 49), // (9,50): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : class?, T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 50)); var source3 = @"#nullable enable class A<T> { static T F1<U>(U u) where U : notnull, T => u; static T F2<U>(U u) where U : notnull, T? => u; static T? F3<U>(U u) where U : notnull, T => u; static T? F4<U>(U u) where U : notnull, T? => u; static T F5<U>(U? u) where U : notnull, T => u; // 1 static T F6<U>(U? u) where U : notnull, T? => u; // 2 static T? F7<U>(U? u) where U : notnull, T => u; static T? F8<U>(U? u) where U : notnull, T? => u; }"; comp = CreateCompilation(source3, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,50): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : notnull, T => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 50), // (9,51): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : notnull, T? => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 51)); var source4 = @"#nullable enable interface I { } class A<T> { static T F1<U>(U u) where U : I, T => u; static T F2<U>(U u) where U : I, T? => u; static T? F3<U>(U u) where U : I, T => u; static T? F4<U>(U u) where U : I, T? => u; static T F5<U>(U? u) where U : I, T => u; // 1 static T F6<U>(U? u) where U : I, T? => u; // 2 static T? F7<U>(U? u) where U : I, T => u; static T? F8<U>(U? u) where U : I, T? => u; }"; comp = CreateCompilation(source4, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,44): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : I, T => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 44), // (10,45): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : I, T? => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 45)); var source5 = @"#nullable enable interface I { } class A<T> { static T F1<U>(U u) where U : I?, T => u; static T F2<U>(U u) where U : I?, T? => u; // 1 static T? F3<U>(U u) where U : I?, T => u; static T? F4<U>(U u) where U : I?, T? => u; static T F5<U>(U? u) where U : I?, T => u; // 2 static T F6<U>(U? u) where U : I?, T? => u; // 3 static T? F7<U>(U? u) where U : I?, T => u; static T? F8<U>(U? u) where U : I?, T? => u; }"; comp = CreateCompilation(source5, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,45): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : I?, T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(6, 45), // (9,45): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : I?, T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 45), // (10,46): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : I?, T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 46)); } [Fact] [WorkItem(46150, "https://github.com/dotnet/roslyn/issues/46150")] public void UnconstrainedTypeParameter_32() { var source = @"#nullable enable class A<T> { static T F1<U, V>(V v) where U : T where V : U => v; static T F2<U, V>(V v) where U : T? where V : U => v; // 1 static T F3<U, V>(V v) where U : T where V : U? => v; // 2 static T F4<U, V>(V v) where U : T? where V : U? => v; // 3 static T? F5<U, V>(V v) where U : T where V : U => v; static T? F6<U, V>(V v) where U : T? where V : U => v; static T? F7<U, V>(V v) where U : T where V : U? => v; static T? F8<U, V>(V v) where U : T? where V : U? => v; static T F9<U, V>(V? v) where U : T where V : U => v; // 4 static T F10<U, V>(V? v) where U : T? where V : U => v; // 5 static T F11<U, V>(V? v) where U : T where V : U? => v; // 6 static T F12<U, V>(V? v) where U : T? where V : U? => v; // 7 static T? F13<U, V>(V? v) where U : T where V : U => v; static T? F14<U, V>(V? v) where U : T? where V : U => v; static T? F15<U, V>(V? v) where U : T where V : U? => v; static T? F16<U, V>(V? v) where U : T? where V : U? => v; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,56): warning CS8603: Possible null reference return. // static T F2<U, V>(V v) where U : T? where V : U => v; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(5, 56), // (6,56): warning CS8603: Possible null reference return. // static T F3<U, V>(V v) where U : T where V : U? => v; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(6, 56), // (7,57): warning CS8603: Possible null reference return. // static T F4<U, V>(V v) where U : T? where V : U? => v; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(7, 57), // (12,56): warning CS8603: Possible null reference return. // static T F9<U, V>(V? v) where U : T where V : U => v; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(12, 56), // (13,58): warning CS8603: Possible null reference return. // static T F10<U, V>(V? v) where U : T? where V : U => v; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(13, 58), // (14,58): warning CS8603: Possible null reference return. // static T F11<U, V>(V? v) where U : T where V : U? => v; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(14, 58), // (15,59): warning CS8603: Possible null reference return. // static T F12<U, V>(V? v) where U : T? where V : U? => v; // 7 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(15, 59)); } [Fact] [WorkItem(46150, "https://github.com/dotnet/roslyn/issues/46150")] public void UnconstrainedTypeParameter_33() { var source = @"#nullable enable class A<T> { static T F1<U, V>(V v) where U : T where V : U, T => v; static T F2<U, V>(V v) where U : T where V : U, T? => v; static T F3<U, V>(V v) where U : T where V : U?, T => v; static T F4<U, V>(V v) where U : T where V : U?, T? => v; // 1 static T F5<U, V>(V? v) where U : T where V : U, T => v; // 2 static T F6<U, V>(V? v) where U : T where V : U, T? => v; // 3 static T F7<U, V>(V? v) where U : T where V : U?, T => v; // 4 static T F8<U, V>(V? v) where U : T where V : U?, T? => v; // 5 static T F9<U, V>(V v) where U : T? where V : U, T => v; static T F10<U, V>(V v) where U : T? where V : U, T? => v; // 6 static T F11<U, V>(V v) where U : T? where V : U?, T => v; static T F12<U, V>(V v) where U : T? where V : U?, T? => v; // 7 static T F13<U, V>(V? v) where U : T? where V : U, T => v; // 8 static T F14<U, V>(V? v) where U : T? where V : U, T? => v; // 9 static T F15<U, V>(V? v) where U : T? where V : U?, T => v; // 10 static T F16<U, V>(V? v) where U : T? where V : U?, T? => v; // 11 }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,60): warning CS8603: Possible null reference return. // static T F4<U, V>(V v) where U : T where V : U?, T? => v; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(7, 60), // (8,59): warning CS8603: Possible null reference return. // static T F5<U, V>(V? v) where U : T where V : U, T => v; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(8, 59), // (9,60): warning CS8603: Possible null reference return. // static T F6<U, V>(V? v) where U : T where V : U, T? => v; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(9, 60), // (10,60): warning CS8603: Possible null reference return. // static T F7<U, V>(V? v) where U : T where V : U?, T => v; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(10, 60), // (11,61): warning CS8603: Possible null reference return. // static T F8<U, V>(V? v) where U : T where V : U?, T? => v; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(11, 61), // (13,61): warning CS8603: Possible null reference return. // static T F10<U, V>(V v) where U : T? where V : U, T? => v; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(13, 61), // (15,62): warning CS8603: Possible null reference return. // static T F12<U, V>(V v) where U : T? where V : U?, T? => v; // 7 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(15, 62), // (16,61): warning CS8603: Possible null reference return. // static T F13<U, V>(V? v) where U : T? where V : U, T => v; // 8 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(16, 61), // (17,62): warning CS8603: Possible null reference return. // static T F14<U, V>(V? v) where U : T? where V : U, T? => v; // 9 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(17, 62), // (18,62): warning CS8603: Possible null reference return. // static T F15<U, V>(V? v) where U : T? where V : U?, T => v; // 10 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(18, 62), // (19,63): warning CS8603: Possible null reference return. // static T F16<U, V>(V? v) where U : T? where V : U?, T? => v; // 11 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(19, 63)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_34([CombinatorialValues(null, "class", "class?", "notnull")] string constraint, bool useCompilationReference) { var sourceA = @"#nullable enable public class A<T> { public static void F<U>(U u) where U : T { } }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var fullConstraint = constraint is null ? "" : ("where T : " + constraint); var sourceB = $@"#nullable enable class B {{ static void M1<T, U>(bool b, U x, U? y) {fullConstraint} where U : T {{ if (b) A<T>.F<U>(x); if (b) A<T>.F<U>(y); // 1 if (b) A<T>.F<U?>(x); // 2 if (b) A<T>.F<U?>(y); // 3 A<T>.F(x); A<T>.F(y); // 4 }} static void M2<T, U>(bool b, U x, U? y) {fullConstraint} where U : T? {{ if (b) A<T>.F<U>(x); // 5 if (b) A<T>.F<U>(y); // 6 if (b) A<T>.F<U?>(x); // 7 if (b) A<T>.F<U?>(y); // 8 if (b) A<T>.F(x); // 9 if (b) A<T>.F(y); // 10 }} }}"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,26): warning CS8604: Possible null reference argument for parameter 'u' in 'void A<T>.F<U>(U u)'. // if (b) A<T>.F<U>(y); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("u", "void A<T>.F<U>(U u)").WithLocation(7, 26), // (8,16): warning CS8631: The type 'U?' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U?' doesn't match constraint type 'T'. // if (b) A<T>.F<U?>(x); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F<U?>").WithArguments("A<T>.F<U>(U)", "T", "U", "U?").WithLocation(8, 16), // (9,16): warning CS8631: The type 'U?' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U?' doesn't match constraint type 'T'. // if (b) A<T>.F<U?>(y); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F<U?>").WithArguments("A<T>.F<U>(U)", "T", "U", "U?").WithLocation(9, 16), // (11,9): warning CS8631: The type 'U?' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U?' doesn't match constraint type 'T'. // A<T>.F(y); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F").WithArguments("A<T>.F<U>(U)", "T", "U", "U?").WithLocation(11, 9), // (15,16): warning CS8631: The type 'U' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U' doesn't match constraint type 'T'. // if (b) A<T>.F<U>(x); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F<U>").WithArguments("A<T>.F<U>(U)", "T", "U", "U").WithLocation(15, 16), // (16,16): warning CS8631: The type 'U' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U' doesn't match constraint type 'T'. // if (b) A<T>.F<U>(y); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F<U>").WithArguments("A<T>.F<U>(U)", "T", "U", "U").WithLocation(16, 16), // (16,26): warning CS8604: Possible null reference argument for parameter 'u' in 'void A<T>.F<U>(U u)'. // if (b) A<T>.F<U>(y); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("u", "void A<T>.F<U>(U u)").WithLocation(16, 26), // (17,16): warning CS8631: The type 'U?' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U?' doesn't match constraint type 'T'. // if (b) A<T>.F<U?>(x); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F<U?>").WithArguments("A<T>.F<U>(U)", "T", "U", "U?").WithLocation(17, 16), // (18,16): warning CS8631: The type 'U?' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U?' doesn't match constraint type 'T'. // if (b) A<T>.F<U?>(y); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F<U?>").WithArguments("A<T>.F<U>(U)", "T", "U", "U?").WithLocation(18, 16), // (19,16): warning CS8631: The type 'U' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U' doesn't match constraint type 'T'. // if (b) A<T>.F(x); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F").WithArguments("A<T>.F<U>(U)", "T", "U", "U").WithLocation(19, 16), // (20,16): warning CS8631: The type 'U?' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U?' doesn't match constraint type 'T'. // if (b) A<T>.F(y); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F").WithArguments("A<T>.F<U>(U)", "T", "U", "U?").WithLocation(20, 16)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_35(bool useCompilationReference) { var sourceA = @"#nullable enable public abstract class A<T> { public abstract U? F1<U>(U u) where U : T; public abstract U F2<U>(U? u) where U : T; public abstract U? F3<U>(U u) where U : T?; public abstract U F4<U>(U? u) where U : T?; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable enable class B1<T> : A<T> { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B2<T> : A<T?> { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B3<T> : A<T> where T : class { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B4<T> : A<T?> where T : class { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B5<T> : A<T> where T : class? { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B6<T> : A<T?> where T : class? { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B7<T> : A<T> where T : struct { public override U F1<U>(U u) where U : struct => default; public override U F2<U>(U u) where U : struct => default!; public override U F3<U>(U u) where U : struct => default; public override U F4<U>(U u) where U : struct => default!; } class B8<T> : A<T?> where T : struct { public override U F1<U>(U u) => default; public override U F2<U>(U u) => default!; public override U F3<U>(U u) => default; public override U F4<U>(U u) => default!; } class B9<T> : A<T> where T : notnull { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B10<T> : A<T?> where T : notnull { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B11 : A<string> { public override U? F1<U>(U u) where U : class => default; public override U F2<U>(U? u) where U : class => default!; public override U? F3<U>(U u) where U : class => default; public override U F4<U>(U? u) where U : class => default!; } class B12 : A<string?> { public override U? F1<U>(U u) where U : class => default; public override U F2<U>(U? u) where U : class => default!; public override U? F3<U>(U u) where U : class => default; public override U F4<U>(U? u) where U : class => default!; } class B13 : A<int> { public override U F1<U>(U u) where U : struct => default; public override U F2<U>(U u) where U : struct => default; public override U F3<U>(U u) where U : struct => default; public override U F4<U>(U u) where U : struct => default; } class B14 : A<int?> { public override U F1<U>(U u) => default; public override U F2<U>(U u) => default; public override U F3<U>(U u) => default; public override U F4<U>(U u) => default; }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void UnconstrainedTypeParameter_36() { var source = @"#nullable enable class Program { static void F<T1, T2, T3, T4, T5>() where T2 : class where T3 : class? where T4 : notnull where T5 : T1? { default(T1).ToString(); // 1 default(T1?).ToString(); // 2 default(T2).ToString(); // 3 default(T2?).ToString(); // 4 default(T3).ToString(); // 5 default(T3?).ToString(); // 6 default(T4).ToString(); // 7 default(T4?).ToString(); // 8 default(T5).ToString(); // 9 default(T5?).ToString(); // 10 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // default(T1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T1)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // default(T1?).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T1?)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // default(T2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T2)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // default(T2?).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T2?)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // default(T3).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T3)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // default(T3?).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T3?)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // default(T4).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T4)").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // default(T4?).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T4?)").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // default(T5).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T5)").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // default(T5?).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T5?)").WithLocation(19, 9)); } [Fact] public void UnconstrainedTypeParameter_37() { var source = @"#nullable enable class Program { static T F1<T>() { T? t1 = default(T); return t1; // 1 } static T F2<T>() where T : class { T? t2 = default(T); return t2; // 2 } static T F3<T>() where T : class? { T? t3 = default(T); return t3; // 3 } static T F4<T>() where T : notnull { T? t4 = default(T); return t4; // 4 } static T F5<T, U>() where U : T? { T? t5 = default(U); return t5; // 5 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,16): warning CS8603: Possible null reference return. // return t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(7, 16), // (12,16): warning CS8603: Possible null reference return. // return t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(12, 16), // (17,16): warning CS8603: Possible null reference return. // return t3; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t3").WithLocation(17, 16), // (22,16): warning CS8603: Possible null reference return. // return t4; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t4").WithLocation(22, 16), // (27,16): warning CS8603: Possible null reference return. // return t5; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t5").WithLocation(27, 16)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var locals = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); Assert.Equal(5, locals.Length); VerifyVariableAnnotation(model, locals[0], "T? t1", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[1], "T? t2", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[2], "T? t3", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[3], "T? t4", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[4], "T? t5", NullableAnnotation.Annotated); } [Fact] [WorkItem(46236, "https://github.com/dotnet/roslyn/issues/46236")] public void UnconstrainedTypeParameter_38() { var source = @"#nullable enable class Program { static T F1<T>(T x1) { var y1 = x1; y1 = default(T); return y1; // 1 } static T F2<T>(T x2) where T : class { var y2 = x2; y2 = default(T); return y2; // 2 } static T F3<T>(T x3) where T : class? { var y3 = x3; y3 = default(T); return y3; // 3 } static T F4<T>(T x4) where T : notnull { var y4 = x4; y4 = default(T); return y4; // 4 } static T F5<T, U>(U x5) where U : T? { var y5 = x5; y5 = default(U); return y5; // 5 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,16): warning CS8603: Possible null reference return. // return y1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y1").WithLocation(8, 16), // (14,16): warning CS8603: Possible null reference return. // return y2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y2").WithLocation(14, 16), // (20,16): warning CS8603: Possible null reference return. // return y3; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y3").WithLocation(20, 16), // (26,16): warning CS8603: Possible null reference return. // return y4; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y4").WithLocation(26, 16), // (32,16): warning CS8603: Possible null reference return. // return y5; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y5").WithLocation(32, 16)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var locals = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); Assert.Equal(5, locals.Length); // https://github.com/dotnet/roslyn/issues/46236: Locals should be treated as annotated. VerifyVariableAnnotation(model, locals[0], "T? y1", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[1], "T? y2", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[2], "T? y3", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[3], "T? y4", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[4], "U? y5", NullableAnnotation.Annotated); } private static void VerifyVariableAnnotation(SemanticModel model, VariableDeclaratorSyntax syntax, string expectedDisplay, NullableAnnotation expectedAnnotation) { var symbol = (ILocalSymbol)model.GetDeclaredSymbol(syntax); Assert.Equal(expectedDisplay, symbol.ToTestDisplayString(includeNonNullable: true)); Assert.Equal( (expectedAnnotation == NullableAnnotation.Annotated) ? CodeAnalysis.NullableAnnotation.Annotated : CodeAnalysis.NullableAnnotation.NotAnnotated, symbol.Type.NullableAnnotation); Assert.Equal(expectedAnnotation, symbol.GetSymbol<LocalSymbol>().TypeWithAnnotations.NullableAnnotation); } [Fact] public void UnconstrainedTypeParameter_39() { var source = @"#nullable enable class Program { static T F1<T>(T t1) { return (T?)t1; // 1 } static T F2<T>(T t2) where T : class { return (T?)t2; // 2 } static T F3<T>(T t3) where T : class? { return (T?)t3; // 3 } static T F4<T>(T t4) where T : notnull { return (T?)t4; // 4 } static T F5<T, U>(U t5) where U : T? { return (T?)t5; // 5 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,16): warning CS8603: Possible null reference return. // return (T?)t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T?)t1").WithLocation(6, 16), // (10,16): warning CS8603: Possible null reference return. // return (T?)t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T?)t2").WithLocation(10, 16), // (14,16): warning CS8603: Possible null reference return. // return (T?)t3; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T?)t3").WithLocation(14, 16), // (18,16): warning CS8603: Possible null reference return. // return (T?)t4; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T?)t4").WithLocation(18, 16), // (22,16): warning CS8603: Possible null reference return. // return (T?)t5; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T?)t5").WithLocation(22, 16)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_40(bool useCompilationReference) { var sourceA = @"#nullable enable using System.Diagnostics.CodeAnalysis; public interface I { } public abstract class A1 { [return: NotNull] public abstract T F1<T>(); [return: NotNull] public abstract T F2<T>() where T : class; [return: NotNull] public abstract T F3<T>() where T : class?; [return: NotNull] public abstract T F4<T>() where T : notnull; [return: NotNull] public abstract T F5<T>() where T : I; [return: NotNull] public abstract T F6<T>() where T : I?; } public abstract class A2 { public abstract void F1<T>([DisallowNull] T t); public abstract void F2<T>([DisallowNull] T t) where T : class; public abstract void F3<T>([DisallowNull] T t) where T : class?; public abstract void F4<T>([DisallowNull] T t) where T : notnull; public abstract void F5<T>([DisallowNull] T t) where T : I; public abstract void F6<T>([DisallowNull] T t) where T : I?; }"; var comp = CreateCompilation(new[] { sourceA, DisallowNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable class B1 : A1 { public override T F1<T>() where T : default => default!; public override T F2<T>() where T : class => default!; public override T F3<T>() where T : class => default!; public override T F4<T>() where T : default => default!; public override T F5<T>() where T : default => default!; public override T F6<T>() where T : default => default!; } class B2 : A2 { public override void F1<T>(T t) where T : default { } public override void F2<T>(T t) where T : class { } public override void F3<T>(T t) where T : class { } public override void F4<T>(T t) where T : default { } public override void F5<T>(T t) where T : default { } public override void F6<T>(T t) where T : default { } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,23): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T F1<T>() where T : default => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F1").WithLocation(4, 23), // (9,23): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T F6<T>() where T : default => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F6").WithLocation(9, 23)); var sourceB2 = @"#nullable enable class B1 : A1 { public override T? F1<T>() where T : default => default!; public override T? F2<T>() where T : class => default!; public override T? F3<T>() where T : class => default!; public override T? F4<T>() where T : default => default!; public override T? F5<T>() where T : default => default!; public override T? F6<T>() where T : default => default!; } class B2 : A2 { public override void F1<T>(T? t) where T : default { } public override void F2<T>(T? t) where T : class { } public override void F3<T>(T? t) where T : class { } public override void F4<T>(T? t) where T : default { } public override void F5<T>(T? t) where T : default { } public override void F6<T>(T? t) where T : default { } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F1<T>() where T : default => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F1").WithLocation(4, 24), // (5,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F2<T>() where T : class => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F2").WithLocation(5, 24), // (6,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F3<T>() where T : class => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F3").WithLocation(6, 24), // (7,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F4<T>() where T : default => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F4").WithLocation(7, 24), // (8,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F5<T>() where T : default => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F5").WithLocation(8, 24), // (9,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F6<T>() where T : default => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F6").WithLocation(9, 24)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_41(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I { } public abstract class A1 { public abstract T F1<T>(); public abstract T F2<T>() where T : class; public abstract T F3<T>() where T : class?; public abstract T F4<T>() where T : notnull; public abstract T F5<T>() where T : I; public abstract T F6<T>() where T : I?; } public abstract class A2 { public abstract void F1<T>(T t); public abstract void F2<T>(T t) where T : class; public abstract void F3<T>(T t) where T : class?; public abstract void F4<T>(T t) where T : notnull; public abstract void F5<T>(T t) where T : I; public abstract void F6<T>(T t) where T : I?; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable enable using System.Diagnostics.CodeAnalysis; class B1 : A1 { [return: NotNull] public override T F1<T>() => default!; [return: NotNull] public override T F2<T>() => default!; [return: NotNull] public override T F3<T>() => default!; [return: NotNull] public override T F4<T>() => default!; [return: NotNull] public override T F5<T>() => default!; [return: NotNull] public override T F6<T>() => default!; } class B2 : A2 { public override void F1<T>([DisallowNull] T t) { } public override void F2<T>([DisallowNull] T t) { } public override void F3<T>([DisallowNull] T t) { } public override void F4<T>([DisallowNull] T t) { } public override void F5<T>([DisallowNull] T t) { } public override void F6<T>([DisallowNull] T t) { } }"; comp = CreateCompilation(new[] { sourceB, DisallowNullAttributeDefinition, NotNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics( // (14,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t").WithLocation(14, 26), // (19,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F6<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t").WithLocation(19, 26) ); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_42(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I { } public abstract class A1 { public abstract T? F1<T>(); public abstract T? F2<T>() where T : class; public abstract T? F3<T>() where T : class?; public abstract T? F4<T>() where T : notnull; public abstract T? F5<T>() where T : I; public abstract T? F6<T>() where T : I?; } public abstract class A2 { public abstract void F1<T>(T? t); public abstract void F2<T>(T? t) where T : class; public abstract void F3<T>(T? t) where T : class?; public abstract void F4<T>(T? t) where T : notnull; public abstract void F5<T>(T? t) where T : I; public abstract void F6<T>(T? t) where T : I?; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable enable using System.Diagnostics.CodeAnalysis; class B1 : A1 { [return: NotNull] public override T F1<T>() => default!; [return: NotNull] public override T F2<T>() => default!; [return: NotNull] public override T F3<T>() => default!; [return: NotNull] public override T F4<T>() => default!; [return: NotNull] public override T F5<T>() => default!; [return: NotNull] public override T F6<T>() => default!; } class B2 : A2 { public override void F1<T>([DisallowNull] T t) { } public override void F2<T>([DisallowNull] T t) { } public override void F3<T>([DisallowNull] T t) { } public override void F4<T>([DisallowNull] T t) { } public override void F5<T>([DisallowNull] T t) { } public override void F6<T>([DisallowNull] T t) { } }"; comp = CreateCompilation(new[] { sourceB, DisallowNullAttributeDefinition, NotNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics( // (14,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t").WithLocation(14, 26), // (15,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t").WithLocation(15, 26), // (16,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F3<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t").WithLocation(16, 26), // (17,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F4<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t").WithLocation(17, 26), // (18,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F5<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t").WithLocation(18, 26), // (19,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F6<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t").WithLocation(19, 26)); } [Fact] public void UnconstrainedTypeParameter_43() { var source = @"#nullable enable class Program { static T F1<T>(bool b, T x1, T? y1) { if (b) return new[] { y1, x1 }[0]; // 1 return new[] { x1, y1 }[0]; // 2 } static T F2<T>(bool b, T x2, T? y2) where T : class? { if (b) return new[] { y2, x2 }[0]; // 3 return new[] { x2, y2 }[0]; // 4 } static T F3<T>(bool b, T x3, T? y3) where T : notnull { if (b) return new[] { y3, x3 }[0]; // 5 return new[] { x3, y3 }[0]; // 6 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,23): warning CS8603: Possible null reference return. // if (b) return new[] { y1, x1 }[0]; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { y1, x1 }[0]").WithLocation(6, 23), // (7,16): warning CS8603: Possible null reference return. // return new[] { x1, y1 }[0]; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { x1, y1 }[0]").WithLocation(7, 16), // (11,23): warning CS8603: Possible null reference return. // if (b) return new[] { y2, x2 }[0]; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { y2, x2 }[0]").WithLocation(11, 23), // (12,16): warning CS8603: Possible null reference return. // return new[] { x2, y2 }[0]; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { x2, y2 }[0]").WithLocation(12, 16), // (16,23): warning CS8603: Possible null reference return. // if (b) return new[] { y3, x3 }[0]; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { y3, x3 }[0]").WithLocation(16, 23), // (17,16): warning CS8603: Possible null reference return. // return new[] { x3, y3 }[0]; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { x3, y3 }[0]").WithLocation(17, 16)); } [Fact] public void UnconstrainedTypeParameter_44() { var source = @"class Program { static void F1<T>(T? t) { } static void F2<T>(T? t) where T : class? { } static void F3<T>(T? t) where T : notnull { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (3,23): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F1<T>(T? t) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(3, 23), // (3,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F1<T>(T? t) { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 24), // (4,23): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F2<T>(T? t) where T : class? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 23), // (4,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F2<T>(T? t) where T : class? { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 24), // (4,44): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F2<T>(T? t) where T : class? { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 44), // (5,23): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F3<T>(T? t) where T : notnull { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 23), // (5,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F3<T>(T? t) where T : notnull { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 24)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (3,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F1<T>(T? t) { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 24), // (4,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F2<T>(T? t) where T : class? { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 24), // (4,44): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F2<T>(T? t) where T : class? { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 44), // (5,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F3<T>(T? t) where T : notnull { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 24)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_45(bool useCompilationReference) { var sourceA = @"#nullable disable public interface I { } public abstract class A1 { public abstract T F1<T>(); public abstract T F2<T>() where T : class; public abstract T F4<T>() where T : notnull; public abstract T F5<T>() where T : I; } public abstract class A2 { public abstract void F1<T>(T t); public abstract void F2<T>(T t) where T : class; public abstract void F4<T>(T t) where T : notnull; public abstract void F5<T>(T t) where T : I; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable enable class B1 : A1 { public override T? F1<T>() where T : default => default!; public override T? F2<T>() where T : class => default!; public override T? F4<T>() where T : default => default!; public override T? F5<T>() where T : default => default!; } class B2 : A2 { public override void F1<T>(T? t) where T : default { } public override void F2<T>(T? t) where T : class { } public override void F4<T>(T? t) where T : default { } public override void F5<T>(T? t) where T : default { } }"; comp = CreateCompilation(sourceB, references: new[] { refA }); comp.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_46(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I { } public abstract class A1 { public abstract T? F1<T>(); public abstract T? F2<T>() where T : class; public abstract T? F3<T>() where T : class?; public abstract T? F4<T>() where T : notnull; public abstract T? F5<T>() where T : I; public abstract T? F6<T>() where T : I?; } public abstract class A2 { public abstract void F1<T>(T? t); public abstract void F2<T>(T? t) where T : class; public abstract void F3<T>(T? t) where T : class?; public abstract void F4<T>(T? t) where T : notnull; public abstract void F5<T>(T? t) where T : I; public abstract void F6<T>(T? t) where T : I?; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable disable class B1 : A1 { public override T F1<T>() => default!; public override T F2<T>() => default!; public override T F3<T>() => default!; public override T F4<T>() => default!; public override T F5<T>() => default!; public override T F6<T>() => default!; } class B2 : A2 { public override void F1<T>(T t) { } public override void F2<T>(T t) { } public override void F3<T>(T t) { } public override void F4<T>(T t) { } public override void F5<T>(T t) { } public override void F6<T>(T t) { } }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [WorkItem(49131, "https://github.com/dotnet/roslyn/issues/49131")] [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_47(bool useCompilationReference) { var sourceA = @"public abstract class A { #nullable disable public abstract void F1<T>(out T t); #nullable enable public abstract void F2<T>(out T t); public abstract void F3<T>(out T? t); }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable disable class B : A { public override void F1<T>(out T t) => throw null; public override void F2<T>(out T t) => throw null; public override void F3<T>(out T t) => throw null; }"; comp = CreateCompilation(sourceB1, references: new[] { refA }); comp.VerifyDiagnostics(); var sourceB2 = @"#nullable enable class B : A { public override void F1<T>(out T t) => throw null!; public override void F2<T>(out T t) => throw null!; public override void F3<T>(out T t) => throw null!; }"; comp = CreateCompilation(sourceB2, references: new[] { refA }); comp.VerifyDiagnostics(); var sourceB3 = @"#nullable enable class B : A { public override void F1<T>(out T t) where T : default => throw null!; public override void F2<T>(out T t) where T : default => throw null!; public override void F3<T>(out T t) where T : default => throw null!; }"; comp = CreateCompilation(sourceB3, references: new[] { refA }); comp.VerifyDiagnostics(); var sourceB4 = @"#nullable enable class B : A { public override void F1<T>(out T? t) where T : default => throw null!; public override void F2<T>(out T? t) where T : default => throw null!; public override void F3<T>(out T? t) where T : default => throw null!; }"; comp = CreateCompilation(sourceB4, references: new[] { refA }); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<T>(out T? t) where T : default => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t").WithLocation(5, 26) ); } [Theory] [InlineData("")] [InlineData("where T : class")] [InlineData("where T : class?")] [InlineData("where T : notnull")] [InlineData("where T : I")] [InlineData("where T : I?")] public void UnconstrainedTypeParameter_48(string constraint) { var source = $@"#pragma warning disable 219 #nullable enable interface I {{ }} class A<T> {constraint} {{ static void F1() {{ T t = default; }} // 1 static void F2() {{ T? t = default; }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F1() { T t = default; } // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(6, 30)); } [Theory] [InlineData("")] [InlineData("where T : class")] [InlineData("where T : class?")] [InlineData("where T : notnull")] [InlineData("where T : I")] [InlineData("where T : I?")] public void UnconstrainedTypeParameter_49(string constraint) { var source = $@"#nullable enable interface I {{ }} class A<T> {constraint} {{ static void F1(T x) {{ T y = x; }} static void F2(T? x) {{ T y = x; }} // 1 static void F3(T x) {{ T? y = x; }} static void F4(T? x) {{ T? y = x; }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F2(T? x) { T y = x; } // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(6, 34)); } [Theory] [InlineData("")] [InlineData("where T : class")] [InlineData("where T : class?")] [InlineData("where T : notnull")] [InlineData("where T : I")] [InlineData("where T : I?")] public void UnconstrainedTypeParameter_50(string constraint) { var source = $@"#pragma warning disable 219 #nullable enable interface I {{ }} class A<T> {constraint} {{ static void F1<U>() where U : T {{ T t = default(U); }} // 1 static void F2<U>() where U : T? {{ T t = default(U); }} // 2 static void F3<U>() where U : T {{ T? t = default(U); }} static void F4<U>() where U : T? {{ T? t = default(U); }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,45): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F1<U>() where U : T { T t = default(U); } // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(U)").WithLocation(6, 45), // (7,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F2<U>() where U : T? { T t = default(U); } // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(U)").WithLocation(7, 46)); } [Theory] [InlineData("")] [InlineData("where T : class")] [InlineData("where T : class?")] [InlineData("where T : notnull")] [InlineData("where T : I")] [InlineData("where T : I?")] public void UnconstrainedTypeParameter_51(string constraint) { var source = $@"#nullable enable interface I {{ }} class A<T> {constraint} {{ static void F1<U>(U u) where U : T {{ T t = u; }} static void F2<U>(U u) where U : T? {{ T t = u; }} // 1 static void F3<U>(U u) where U : T {{ T? t = u; }} static void F4<U>(U u) where U : T? {{ T? t = u; }} static void F5<U>(U? u) where U : T {{ T t = u; }} // 2 static void F6<U>(U? u) where U : T? {{ T t = u; }} // 3 static void F7<U>(U? u) where U : T {{ T? t = u; }} static void F8<U>(U? u) where U : T? {{ T? t = u; }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,49): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F2<U>(U u) where U : T? { T t = u; } // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(6, 49), // (9,49): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F5<U>(U? u) where U : T { T t = u; } // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(9, 49), // (10,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F6<U>(U? u) where U : T? { T t = u; } // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(10, 50)); } [Fact] public void UnconstrainedTypeParameter_52() { var source = @"#nullable enable class Program { static T F1<T>() { T t = default; // 1 return t; // 2 } static T F2<T>(object? o) { T t = (T)o; // 3 return t; // 4 } static U F3<T, U>(T t) where U : T { U u = (U)t; // 5 return u; // 6 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,16): warning CS8603: Possible null reference return. // return t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(7, 16), // (12,16): warning CS8603: Possible null reference return. // return t; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(12, 16), // (17,16): warning CS8603: Possible null reference return. // return u; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(17, 16)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t = default; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(6, 15), // (7,16): warning CS8603: Possible null reference return. // return t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(7, 16), // (11,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t = (T)o; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)o").WithLocation(11, 15), // (12,16): warning CS8603: Possible null reference return. // return t; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(12, 16), // (16,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // U u = (U)t; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(16, 15), // (17,16): warning CS8603: Possible null reference return. // return u; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(17, 16)); } [Fact] public void UnconstrainedTypeParameter_53() { var source = @"#nullable enable class Pair<T, U> { internal void Deconstruct(out T x, out U y) => throw null!; } class Program { static T F2<T>(T x) { T y; (y, _) = (x, x); return y; } static T F3<T>() { var p = new Pair<T, T>(); T t; (t, _) = p; return t; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(39540, "https://github.com/dotnet/roslyn/issues/39540")] public void IsObjectAndNotIsNull() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C { void F0(int? i) { _ = i.Value; // 1 } void F1(int? i) { MyAssert(i is object); _ = i.Value; } void F2(int? i) { MyAssert(i is object); MyAssert(!(i is null)); _ = i.Value; } void F3(int? i) { MyAssert(!(i is null)); _ = i.Value; } void F5(object? o) { _ = o.ToString(); // 2 } void F6(object? o) { MyAssert(o is object); _ = o.ToString(); } void F7(object? o) { MyAssert(o is object); MyAssert(!(o is null)); _ = o.ToString(); } void F8(object? o) { MyAssert(!(o is null)); _ = o.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; }"; var comp = CreateCompilation(new[] { source, DoesNotReturnIfAttributeDefinition }); comp.VerifyDiagnostics( // (10,13): warning CS8629: Nullable value type may be null. // _ = i.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(10, 13), // (34,13): warning CS8602: Dereference of a possibly null reference. // _ = o.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(34, 13) ); } [Fact, WorkItem(38030, "https://github.com/dotnet/roslyn/issues/38030")] public void CastOnDefault() { string source = @" #nullable enable public struct S { public string field; public S(string s) => throw null!; public static void M() { S s = (S) (S) default; s.field.ToString(); // 1 S s2 = (S) default; s2.field.ToString(); // 2 S s3 = (S) (S) default(S); s3.field.ToString(); // 3 S s4 = (S) default(S); s4.field.ToString(); // 4 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // s.field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.field").WithLocation(12, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // s2.field.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2.field").WithLocation(15, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // s3.field.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3.field").WithLocation(18, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // s4.field.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4.field").WithLocation(21, 9) ); } [Fact] [WorkItem(38586, "https://github.com/dotnet/roslyn/issues/38586")] public void SuppressSwitchExpressionInput() { var source = @"#nullable enable public class C { public int M0(C a) => a switch { C _ => 0 }; // ok public int M1(C? a) => a switch { C _ => 0 }; // warns public int M2(C? a) => a! switch { C _ => 0 }; // ok public int M3(C a) => (1, a) switch { (_, C _) => 0 }; // ok public int M4(C? a) => (1, a) switch { (_, C _) => 0 }; // warns public int M5(C? a) => (1, a!) switch { (_, C _) => 0 }; // warns public void M6(C? a, bool b) { if (a == null) return; switch (a!) { case C _: break; case null: // does not affect knowledge of 'a' break; } a.ToString(); } public void M7(C? a, bool b) { if (a == null) return; switch (a) { case C _: break; case null: // affects knowledge of a break; } a.ToString(); // warns } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,30): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern 'null' is not covered. // public int M1(C? a) => a switch { C _ => 0 }; // warns Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("null").WithLocation(4, 30), // (8,35): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(_, null)' is not covered. // public int M4(C? a) => (1, a) switch { (_, C _) => 0 }; // warns Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(_, null)").WithLocation(8, 35), // (9,36): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(_, null)' is not covered. // public int M5(C? a) => (1, a!) switch { (_, C _) => 0 }; // warns Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(_, null)").WithLocation(9, 36), // (36,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // warns Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(36, 9) ); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(40430, "https://github.com/dotnet/roslyn/issues/40430")] public void DecodingWithMissingNullableAttribute(bool useImageReference) { var nullableAttrComp = CreateCompilation(NullableAttributeDefinition); nullableAttrComp.VerifyDiagnostics(); var nullableAttrRef = useImageReference ? nullableAttrComp.EmitToImageReference() : nullableAttrComp.ToMetadataReference(); var lib_cs = @" #nullable enable public class C3<T1, T2, T3> { } public class SelfReferencing : C3<SelfReferencing, string?, string> { public SelfReferencing() { System.Console.Write(""ran""); } } "; var lib = CreateCompilation(lib_cs, references: new[] { nullableAttrRef }); lib.VerifyDiagnostics(); var libRef = useImageReference ? lib.EmitToImageReference() : lib.ToMetadataReference(); var source_cs = @" public class C2 { public static void M() { _ = new SelfReferencing(); } } "; var comp = CreateCompilation(source_cs, references: new[] { libRef }); comp.VerifyEmitDiagnostics(); var executable_cs = @" public class C { public static void Main() { C2.M(); } }"; var executeComp = CreateCompilation(executable_cs, references: new[] { comp.EmitToImageReference(), libRef, nullableAttrRef }, options: TestOptions.DebugExe); CompileAndVerify(executeComp, expectedOutput: "ran"); } [Fact, WorkItem(41437, "https://github.com/dotnet/roslyn/issues/41437")] public void CannotAssignMaybeNullToTNotNull() { var source = @" class C { TNotNull M<TNotNull>(TNotNull t) where TNotNull : notnull { if (t is null) System.Console.WriteLine(); return t; // 1 } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,16): warning CS8603: Possible null reference return. // return t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(8, 16) ); } [Fact, WorkItem(41437, "https://github.com/dotnet/roslyn/issues/41437")] public void CanAssignMaybeNullToMaybeNullTNotNull() { var source = @" using System.Diagnostics.CodeAnalysis; class C { [return: MaybeNull] TNotNull M<TNotNull>(TNotNull t) where TNotNull : notnull { if (t is null) System.Console.WriteLine(); return t; } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(35602, "https://github.com/dotnet/roslyn/issues/35602")] public void PureNullTestOnUnconstrainedType() { var source = @" class C { static T GetGeneric<T>(T t) { if (t is null) return t; return Id(t); } static T Id<T>(T t) => throw null!; } "; // If the null test changed the state of the variable to MaybeDefault // we would introduce an annoying warning var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void VarLocalUsedInLocalFunction() { var source = @"#nullable enable public class C { void M() { var x = """"; var y = """"; System.Action z = local; void local() => x.ToString(); void local2() => y.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,14): warning CS8321: The local function 'local2' is declared but never used // void local2() => y.ToString(); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local2").WithArguments("local2").WithLocation(11, 14), // (11,26): warning CS8602: Dereference of a possibly null reference. // void local2() => y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 26) ); } [Fact] public void ExplicitNullableLocalUsedInLocalFunction() { var source = @"#nullable enable public class C { void M() { string? x = """"; string? y = """"; System.Action z = local; void local() => x.ToString(); void local2() => y.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,14): warning CS8321: The local function 'local2' is declared but never used // void local2() => y.ToString(); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local2").WithArguments("local2").WithLocation(11, 14), // (11,26): warning CS8602: Dereference of a possibly null reference. // void local2() => y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 26) ); } [Fact, WorkItem(40925, "https://github.com/dotnet/roslyn/issues/40925")] public void GetTypeInfoOnNullableType() { var source = @"#nullable enable #nullable enable class Program2 { } class Program { void Method(Program x) { (global::Program y1, global::Program? y2) = (x, x); global::Program y3 = x; global::Program? y4 = x; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var identifiers = tree.GetRoot().DescendantNodes().Where(n => n.ToString() == "global::Program").ToArray(); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, model.GetTypeInfo(identifiers[0]).Nullability.Annotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfo(identifiers[1]).Nullability.Annotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, model.GetTypeInfo(identifiers[2]).Nullability.Annotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfo(identifiers[3]).Nullability.Annotation); // Note: this discrepancy causes some issues with type simplification in the IDE layer } [Fact, WorkItem(39417, "https://github.com/dotnet/roslyn/issues/39417")] public void ConfigureAwait_DetectSettingNullableToNonNullableType() { var source = @"using System.Threading.Tasks; #nullable enable class Request { public string? Name { get; } public Task<string?> GetName() => Task.FromResult(Name); } class Handler { public async Task Handle(Request request) { string a = request.Name; string b = await request.GetName().ConfigureAwait(false); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "request.Name").WithLocation(12, 20), Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "await request.GetName().ConfigureAwait(false)").WithLocation(13, 20) ); } [Fact] [WorkItem(44049, "https://github.com/dotnet/roslyn/issues/44049")] public void MemberNotNull_InstanceMemberOnStaticMethod() { var source = @"using System.Diagnostics.CodeAnalysis; class C { public string? field; [MemberNotNull(""field"")] public static void M() { } public void Test() { M(); field.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,20): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null // public string? field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null").WithLocation(5, 20), // (15,9): warning CS8602: Dereference of a possibly null reference. // field.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field").WithLocation(15, 9)); } [Fact, WorkItem(39417, "https://github.com/dotnet/roslyn/issues/39417")] public void CustomAwaitable_DetectSettingNullableToNonNullableType() { var source = @"using System.Runtime.CompilerServices; using System.Threading.Tasks; #nullable enable static class TaskExtensions { public static ConfiguredTaskAwaitable<TResult> NoSync<TResult>(this Task<TResult> task) { return task.ConfigureAwait(false); } } class Request { public string? Name { get; } public Task<string?> GetName() => Task.FromResult(Name); } class Handler { public async Task Handle(Request request) { string a = await request.GetName().NoSync(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "await request.GetName().NoSync()").WithLocation(20, 20) ); } [Fact] [WorkItem(39220, "https://github.com/dotnet/roslyn/issues/39220")] public void GotoMayCauseAnotherAnalysisPass_01() { var source = @"#nullable enable class Program { static void Test(string? s) { if (s == null) return; heck: var c = GetC(s); var prop = c.Property; prop.ToString(); // Dereference of null value (after goto) s = null; goto heck; } static void Main() { Test(""""); } public static C<T> GetC<T>(T t) => new C<T>(t); } class C<T> { public C(T t) => Property = t; public T Property { get; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // prop.ToString(); // BOOM (after goto) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "prop").WithLocation(11, 9) ); } [Fact] [WorkItem(40904, "https://github.com/dotnet/roslyn/issues/40904")] public void GotoMayCauseAnotherAnalysisPass_02() { var source = @"#nullable enable public class C { public void M(bool b) { string? s = ""x""; if (b) goto L2; L1: var x = Create(s); x.F.ToString(); // warning: x.F might be null. L2: s = null; goto L1; } private G<T> Create<T>(T t) where T : class? => new G<T>(t); } class G<T> where T : class? { public G(T f) => F = f; public T F; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x.F.ToString(); // warning: x.F might be null. Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(8, 9) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/40904")] [WorkItem(40904, "https://github.com/dotnet/roslyn/issues/40904")] public void GotoMayCauseAnotherAnalysisPass_03() { var source = @"#nullable enable public class C { public void M(bool b) { string? s = ""x""; if (b) goto L2; L1: _ = Create(s) is var x; x.F.ToString(); // warning: x.F might be null. L2: s = null; goto L1; } private G<T> Create<T>(T t) where T : class? => new G<T>(t); } class G<T> where T : class? { public G(T f) => F = f; public T F; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x.F.ToString(); // warning: x.F might be null. Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(8, 9) ); } [Fact] public void FunctionPointerSubstitutedGenericNullableWarning() { var comp = CreateCompilation(@" #nullable enable unsafe class C { static void M<T>(delegate*<T, void> ptr1, delegate*<T> ptr2) { T t = default; ptr1(t); ptr2().ToString(); } }", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(7, 15), // (8,14): warning CS8604: Possible null reference argument for parameter '' in 'delegate*<T, void>'. // ptr1(t); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("", "delegate*<T, void>").WithLocation(8, 14), // (9,9): warning CS8602: Dereference of a possibly null reference. // ptr2().ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ptr2()").WithLocation(9, 9) ); } [Fact, WorkItem(44438, "https://github.com/dotnet/roslyn/issues/44438")] public void BadOverride_NestedNullableTypeParameter() { var comp = CreateNullableCompilation(@" class A { public virtual void M1<T>(C<System.Nullable<T>> x) where T : struct { } } class B : A { public override void M1<T>(C<System.Nullable<T?> x) { } } class C<T> {} "); comp.VerifyDiagnostics( // (11,32): error CS0305: Using the generic type 'C<T>' requires 1 type arguments // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_BadArity, "C<System.Nullable<T?> x").WithArguments("C<T>", "type", "1").WithLocation(11, 32), // (11,54): error CS1003: Syntax error, ',' expected // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_SyntaxError, "x").WithArguments(",", "").WithLocation(11, 54), // (11,54): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?) // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(11, 54), // (11,55): error CS1003: Syntax error, '>' expected // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(">", ")").WithLocation(11, 55), // (11,55): error CS1001: Identifier expected // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(11, 55), // (11,55): error CS0453: The type 'T?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "").WithArguments("System.Nullable<T>", "T", "T?").WithLocation(11, 55), // (11,55): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 55) ); } [Fact, WorkItem(44438, "https://github.com/dotnet/roslyn/issues/44438")] public void Override_NestedNullableTypeParameter() { var comp = CreateNullableCompilation(@" class A { public virtual void M1<T>(int x) { } } class B : A { public override void M1<T>(System.Nullable<T?> x) { } } "); comp.VerifyDiagnostics( // (11,26): error CS0115: 'B.M1<T>(T??)': no suitable method found to override // public override void M1<T>(System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("B.M1<T>(T??)").WithLocation(11, 26), // (11,52): error CS0453: The type 'T?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T?").WithLocation(11, 52), // (11,52): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 52) ); } [Fact, WorkItem(44438, "https://github.com/dotnet/roslyn/issues/44438")] public void Hide_NestedNullableTypeParameter() { var comp = CreateNullableCompilation(@" class A { public virtual void M1<T>(int x) { } } class B : A { public new void M1<T>(System.Nullable<T?> x) { } } ", parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,21): warning CS0109: The member 'B.M1<T>(T??)' does not hide an accessible member. The new keyword is not required. // public new void M1<T>(System.Nullable<T?> x) Diagnostic(ErrorCode.WRN_NewNotRequired, "M1").WithArguments("B.M1<T>(T??)").WithLocation(11, 21), // (11,43): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public new void M1<T>(System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(11, 43), // (11,47): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public new void M1<T>(System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 47) ); } [Fact, WorkItem(43071, "https://github.com/dotnet/roslyn/issues/43071")] public void LocalFunctionInLambdaWithReturnStatement() { var source = @" using System; using System.Collections.Generic; public class C<T> { public static C<string> ReproFunction(C<string> collection) { return collection .SelectMany(allStrings => { return new[] { getSomeString(""custard"") }; string getSomeString(string substring) { return substring; } }); } } public static class Extension { public static C<TResult> SelectMany<TSource, TResult>(this C<TSource> source, Func<TSource, IEnumerable<TResult>> selector) { throw null!; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44348, "https://github.com/dotnet/roslyn/issues/44348")] public void NestedTypeConstraints_01() { var source = @"class A<T, U> { internal interface IA { } internal class C { } } #nullable enable class B<T, U> : A<T, U> where T : B<T, U>.IB where U : A<T, U>.C { internal interface IB : IA { } }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(45713, "https://github.com/dotnet/roslyn/issues/45713")] public void NestedTypeConstraints_02() { var source = @"class A<T> { internal interface IA { } } #nullable enable class B<T> : A<T> where T : B<T>.IA { }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(45713, "https://github.com/dotnet/roslyn/issues/45713")] public void NestedTypeConstraints_03() { var source = @"class A<T> { internal interface IA { } } #nullable enable class B<T> : A<T> where T : B<T?>.IA { }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(45713, "https://github.com/dotnet/roslyn/issues/45713")] public void NestedTypeConstraints_04() { var source = @"class A<T> { internal interface IA { } } #nullable enable class B<T> : A<T> #nullable disable where T : B<T>.IA { }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(45713, "https://github.com/dotnet/roslyn/issues/45713")] public void NestedTypeConstraints_05() { var source = @"class A<T> { internal interface IA { } } #nullable enable class B<T> : A<T> #nullable disable where T : B<T?>.IA { }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (8,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // where T : B<T?>.IA Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 18)); } [Fact] [WorkItem(45713, "https://github.com/dotnet/roslyn/issues/45713")] public void NestedTypeConstraints_06() { var source0 = @"public class A<T> { public interface IA { } } #nullable enable public class B<T> : A<T> where T : B<T>.IA { }"; var comp = CreateCompilation(source0); var ref0 = comp.EmitToImageReference(); var source1 = @"class A : A<A>.IA { } class Program { static B<A> F() => new(); static void Main() { System.Console.WriteLine(F()); } }"; CompileAndVerify(source1, references: new[] { ref0 }, expectedOutput: "B`1[A]"); } [Fact] [WorkItem(45863, "https://github.com/dotnet/roslyn/issues/45863")] public void NestedTypeConstraints_07() { var source = @"#nullable enable interface IA<T> { } interface IB<T, U> : IA<T> where U : IB<T, U>.IC { interface IC { } }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(45863, "https://github.com/dotnet/roslyn/issues/45863")] public void NestedTypeConstraints_08() { var source0 = @"#nullable enable public interface IA<T> { } public interface IB<T, U> : IA<T> where U : IB<T, U>.IC { public interface IC { } }"; var comp = CreateCompilation(source0); var ref0 = comp.EmitToImageReference(); var source1 = @"class C : IB<object, C>.IC { } class Program { static C F() => new(); static void Main() { System.Console.WriteLine(F()); } }"; CompileAndVerify(source1, references: new[] { ref0 }, expectedOutput: "C"); } [Fact] [WorkItem(46342, "https://github.com/dotnet/roslyn/issues/46342")] public void LambdaNullReturn_01() { var source = @"#nullable enable using System; class Program { static void F<T>(Func<T> f) { } static void M1<T>(bool b, T t) where T : class { F(() => { if (b) return null; return t; }); } static void M2<T>(bool b, T t) where T : class? { F(() => { if (b) return null; return t; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(46342, "https://github.com/dotnet/roslyn/issues/46342")] public void LambdaNullReturn_02() { var source = @"#nullable enable using System; class Program { static void F<T>(Func<T> f) { } static void M1<T>(T? t) where T : class { F(() => { if (t is null) return null; return t; }); } static void M2<T>(T? t) where T : class? { F(() => { if (t is null) return null; return t; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(46342, "https://github.com/dotnet/roslyn/issues/46342")] public void LambdaNullReturn_03() { var source = @"#nullable enable using System; using System.Threading.Tasks; class Program { static void F<T>(Func<Task<T>> f) { } static void M1<T>(T? t) where T : class { F(async () => { await Task.Yield(); if (t is null) return null; return t; }); } static void M2<T>(T? t) where T : class? { F(async () => { await Task.Yield(); if (t is null) return null; return t; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] public void LambdaNullReturn_04() { var source = @"#nullable enable using System; class Program { static void F<T>(Func<T> f) { } static void M1<T>(bool b, T t) where T : class { F(() => { if (b) return default; return t; }); } static void M2<T>(bool b, T t) where T : class? { F(() => { if (b) return default; return t; }); } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("void Program.F<T?>(System.Func<T?> f)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); var invocationNode2 = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Last(); Assert.Equal("void Program.F<T?>(System.Func<T?> f)", model.GetSymbolInfo(invocationNode2).Symbol.ToTestDisplayString()); comp.VerifyEmitDiagnostics(); } [Fact] public void LambdaNullReturn_05() { var source = @"#nullable enable using System; class Program { static void F<T>(Func<T> f) { } static void M1<T>(bool b, T t) where T : class { F(() => { if (b) return default(T); return t; }); } static void M2<T>(bool b, T t) where T : class? { F(() => { if (b) return default(T); return t; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(45862, "https://github.com/dotnet/roslyn/issues/45862")] public void Issue_45862() { var source = @"#nullable enable class C { void M() { _ = 0 switch { 0 = _ = null, }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,15): error CS1003: Syntax error, '=>' expected // 0 = Diagnostic(ErrorCode.ERR_SyntaxError, "=").WithArguments("=>", "=").WithLocation(9, 15), // (9,15): error CS1525: Invalid expression term '=' // 0 = Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(9, 15), // (10,13): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = null, Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(10, 13)); } [Fact, WorkItem(48126, "https://github.com/dotnet/roslyn/issues/48126")] public void EnforcedInMethodBody_MaybeNullWhen_Issue_48126() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C { static bool NullWhenFalseA(bool a, [MaybeNullWhen(false)] out string s1) { s1 = null; return a; } static bool NullWhenFalseNotA(bool a, [MaybeNullWhen(false)] out string s1) { s1 = null; return !a; } static bool NullWhenTrueA(bool a, [MaybeNullWhen(true)] out string s1) { s1 = null; return a; } static bool NullWhenTrueNotA(bool a, [MaybeNullWhen(true)] out string s1) { s1 = null; return !a; } }"; var comp = CreateCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(48126, "https://github.com/dotnet/roslyn/issues/48126")] public void EnforcedInMethodBody_MaybeNullWhen_Issue_48126_2() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C { static bool M1([MaybeNullWhen(false)] out string s1) { const bool b = true; s1 = null; return b; // 1 } static bool M2([MaybeNullWhen(false)] out string s1) { s1 = null; return (bool)true; // 2 } }"; var comp = CreateCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyEmitDiagnostics( // (12,9): warning CS8762: Parameter 's1' must have a non-null value when exiting with 'true'. // return b; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return b;").WithArguments("s1", "true").WithLocation(12, 9), // (18,9): warning CS8762: Parameter 's1' must have a non-null value when exiting with 'true'. // return (bool)true; // 2 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return (bool)true;").WithArguments("s1", "true").WithLocation(18, 9) ); } [Fact, WorkItem(48126, "https://github.com/dotnet/roslyn/issues/48126")] public void EnforcedInMethodBody_MaybeNullWhen_Issue_48126_3() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C { static bool M1([MaybeNullWhen(false)] out string s1) { const bool b = true; s1 = null; return b; // 1 } static bool M2([MaybeNullWhen(false)] out string s1) { const bool b = true; s1 = null; return b && true; // 2 } static bool M3([MaybeNullWhen(false)] out string s1) { const bool b = false; s1 = null; return b; } }"; var comp = CreateCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyEmitDiagnostics( // (12,9): warning CS8762: Parameter 's1' must have a non-null value when exiting with 'true'. // return b; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return b;").WithArguments("s1", "true").WithLocation(12, 9), // (19,9): warning CS8762: Parameter 's1' must have a non-null value when exiting with 'true'. // return b && true; // 2 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return b && true;").WithArguments("s1", "true").WithLocation(19, 9) ); } [Fact, WorkItem(48126, "https://github.com/dotnet/roslyn/issues/48126")] public void EnforcedInMethodBody_MaybeNullWhen_Issue_48126_4() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C { static bool M1([MaybeNullWhen(false)] out string s1) { return M1(out s1); } static bool M2([MaybeNullWhen(false)] out string s1) { return !M1(out s1); // 1 } static bool M3([MaybeNullWhen(true)] out string s1) { return !M1(out s1); } }"; var comp = CreateCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyEmitDiagnostics( // (15,9): warning CS8762: Parameter 's1' must have a non-null value when exiting with 'true'. // return !M1(out s1); // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return !M1(out s1);").WithArguments("s1", "true").WithLocation(15, 9) ); } [Fact, WorkItem(48126, "https://github.com/dotnet/roslyn/issues/48126")] public void EnforcedInMethodBody_MaybeNullWhen_Issue_48126_5() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable internal static class Program { public static bool M1([MaybeNullWhen(true)] out string s) { s = null; return HasAnnotation(out _); } public static bool M2([MaybeNullWhen(true)] out string s) { s = null; return NoAnnotations(); } private static bool HasAnnotation([MaybeNullWhen(true)] out string s) { s = null; return true; } private static bool NoAnnotations() => true; }"; var comp = CreateCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(47221, "https://github.com/dotnet/roslyn/issues/47221")] public void PropertyAccessorWithNullableContextAttribute_01() { var source0 = @"#nullable enable public class A { public object? this[object x, object? y] => null; public static A F(object x) => new A(); public static A F(object x, object? y) => new A(); }"; var comp = CreateCompilation(source0); var ref0 = comp.EmitToImageReference(); var source1 = @"#nullable enable class B { static void F(object x, object? y) { var a = A.F(x, y); var b = a[x, y]; b.ToString(); // 1 } }"; comp = CreateCompilation(source1, references: new[] { ref0 }); comp.VerifyEmitDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(8, 9)); } [Fact] [WorkItem(47221, "https://github.com/dotnet/roslyn/issues/47221")] public void PropertyAccessorWithNullableContextAttribute_02() { var source0 = @"#nullable enable public class A { public object this[object? x, object y] => new object(); public static A? F0; public static A? F1; public static A? F2; public static A? F3; public static A? F4; }"; var comp = CreateCompilation(source0); var ref0 = comp.EmitToImageReference(); var source1 = @"#nullable enable class B { static void F(object x, object? y) { var a = new A(); var b = a[x, y]; // 1 b.ToString(); } }"; comp = CreateCompilation(source1, references: new[] { ref0 }); comp.VerifyEmitDiagnostics( // (7,22): warning CS8604: Possible null reference argument for parameter 'y' in 'object A.this[object? x, object y]'. // var b = a[x, y]; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("y", "object A.this[object? x, object y]").WithLocation(7, 22)); } [Fact] [WorkItem(49754, "https://github.com/dotnet/roslyn/issues/49754")] public void Issue49754() { var source0 = @" using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; #nullable enable namespace Repro { public class Test { public void Test(IEnumerable<(int test, int score)> scores) { scores.Select(s => (s.test, s.score switch { })); } } }" ; var comp = CreateCompilation(source0); comp.VerifyEmitDiagnostics( // (12,15): error CS0542: 'Test': member names cannot be the same as their enclosing type // public void Test(IEnumerable<(int test, int score)> scores) Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Test").WithArguments("Test").WithLocation(12, 15), // (14,11): error CS0411: The type arguments for method 'Enumerable.Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // scores.Select(s => (s.test, s.score switch Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Select").WithArguments("System.Linq.Enumerable.Select<TSource, TResult>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource, TResult>)").WithLocation(14, 11) ); } [Fact] [WorkItem(48992, "https://github.com/dotnet/roslyn/issues/48992")] public void TryGetValue_GenericMethod() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Collection { public bool TryGetValue<T>(object key, [MaybeNullWhen(false)] out T value) { value = default; return false; } } class Program { static string GetValue1(Collection c, object key) { // out string if (c.TryGetValue(key, out string s1)) // 1 { return s1; } // out string? if (c.TryGetValue(key, out string? s2)) { return s2; // 2 } // out string?, explicit type argument if (c.TryGetValue<string>(key, out string? s3)) { return s3; } // out var, explicit type argument if (c.TryGetValue<string>(key, out var s4)) { return s4; } return string.Empty; } static T GetValue2<T>(Collection c, object key) { // out T if (c.TryGetValue(key, out T s1)) // 3 { return s1; } // out T? if (c.TryGetValue(key, out T? s2)) { return s2; // 4 } // out T?, explicit type argument if (c.TryGetValue<T>(key, out T? s3)) { return s3; } // out var, explicit type argument if (c.TryGetValue<T>(key, out var s4)) { return s4; } return default!; } }"; var comp = CreateCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyEmitDiagnostics( // (16,36): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (c.TryGetValue(key, out string s1)) // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "string s1").WithLocation(16, 36), // (23,20): warning CS8603: Possible null reference return. // return s2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s2").WithLocation(23, 20), // (40,36): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (c.TryGetValue(key, out T s1)) // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T s1").WithLocation(40, 36), // (47,20): warning CS8603: Possible null reference return. // return s2; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s2").WithLocation(47, 20)); } [Theory, WorkItem(41368, "https://github.com/dotnet/roslyn/issues/41368")] [CombinatorialData] public void TypeSubstitution(bool useCompilationReference) { var sourceA = @" #nullable enable public class C { public static TQ? FTQ<TQ>(TQ? t) => throw null!; // T-question public static T FT<T>(T t) => throw null!; // plain-T public static TC FTC<TC>(TC t) where TC : class => throw null!; // T-class #nullable disable public static TO FTO<TO>(TO t) => throw null!; // T-oblivious public static TCO FTCO<TCO>(TCO t) where TCO : class => throw null!; // T-class-oblivious }"; var comp = CreateCompilation(sourceA); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB2 = @" #nullable enable class CTQ<TQ> { void M() { var x0 = C.FTQ<TQ?>(default); x0.ToString(); // 1 var x1 = C.FT<TQ?>(default); x1.ToString(); // 2 C.FTC<TQ?>(default).ToString(); // illegal var x2 = C.FTO<TQ?>(default); x2.ToString(); // 3 var x3 = C.FTCO<TQ?>(default); // illegal x3.ToString(); } } class CT<T> { void M() { var x0 = C.FTQ<T>(default); x0.ToString(); // 4 var x1 = C.FT<T>(default); // 5 x1.ToString(); // 6 C.FTC<T>(default).ToString(); // illegal var x2 = C.FTO<T>(default); // 7 x2.ToString(); // 8 C.FTCO<T>(default).ToString(); // illegal } } class CTC<TC> where TC : class { void M() { var x0 = C.FTQ<TC>(default); x0.ToString(); // 9 var x1 = C.FT<TC>(default); // 10 x1.ToString(); var x2 = C.FTC<TC>(default); // 11 x2.ToString(); var x3 = C.FTO<TC>(default); // 12 x3.ToString(); var x4 = C.FTCO<TC>(default); // 13 x4.ToString(); } } class CTO<TO> { void M() { #nullable disable C.FTQ<TO> #nullable enable (default).ToString(); #nullable disable C.FT<TO> #nullable enable (default).ToString(); #nullable disable C.FTC<TO> // illegal #nullable enable (default).ToString(); #nullable disable C.FTO<TO> #nullable enable (default).ToString(); #nullable disable C.FTCO<TO> // illegal #nullable enable (default).ToString(); } } class CTCO<TCO> where TCO : class { void M() { var x0 = #nullable disable C.FTQ<TCO> #nullable enable (default); x0.ToString(); // 14 #nullable disable C.FT<TCO> #nullable enable (default).ToString(); var x1 = #nullable disable C.FTC<TCO> #nullable enable (default); // 15 x1.ToString(); #nullable disable C.FTO<TCO> #nullable enable (default).ToString(); #nullable disable C.FTCO<TCO> #nullable enable (default).ToString(); } } "; comp = CreateCompilation(new[] { sourceB2 }, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(8, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 9), // (13,11): error CS0452: The type 'TQ' must be a reference type in order to use it as parameter 'TC' in the generic type or method 'C.FTC<TC>(TC)' // C.FTC<TQ?>(default).ToString(); // illegal Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "FTC<TQ?>").WithArguments("C.FTC<TC>(TC)", "TC", "TQ").WithLocation(13, 11), // (16,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(16, 9), // (18,20): error CS0452: The type 'TQ' must be a reference type in order to use it as parameter 'TCO' in the generic type or method 'C.FTCO<TCO>(TCO)' // var x3 = C.FTCO<TQ?>(default); // illegal Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "FTCO<TQ?>").WithArguments("C.FTCO<TCO>(TCO)", "TCO", "TQ").WithLocation(18, 20), // (28,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(28, 9), // (30,26): warning CS8604: Possible null reference argument for parameter 't' in 'T C.FT<T>(T t)'. // var x1 = C.FT<T>(default); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "T C.FT<T>(T t)").WithLocation(30, 26), // (31,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(31, 9), // (33,11): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'TC' in the generic type or method 'C.FTC<TC>(TC)' // C.FTC<T>(default).ToString(); // illegal Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "FTC<T>").WithArguments("C.FTC<TC>(TC)", "TC", "T").WithLocation(33, 11), // (35,27): warning CS8604: Possible null reference argument for parameter 't' in 'T C.FTO<T>(T t)'. // var x2 = C.FTO<T>(default); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "T C.FTO<T>(T t)").WithLocation(35, 27), // (36,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(36, 9), // (38,11): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'TCO' in the generic type or method 'C.FTCO<TCO>(TCO)' // C.FTCO<T>(default).ToString(); // illegal Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "FTCO<T>").WithArguments("C.FTCO<TCO>(TCO)", "TCO", "T").WithLocation(38, 11), // (46,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(46, 9), // (48,27): warning CS8625: Cannot convert null literal to non-nullable reference type. // var x1 = C.FT<TC>(default); // 10 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(48, 27), // (51,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // var x2 = C.FTC<TC>(default); // 11 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(51, 28), // (54,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // var x3 = C.FTO<TC>(default); // 12 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(54, 28), // (57,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // var x4 = C.FTCO<TC>(default); // 13 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(57, 29), // (76,11): error CS0452: The type 'TO' must be a reference type in order to use it as parameter 'TC' in the generic type or method 'C.FTC<TC>(TC)' // C.FTC<TO> // illegal Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "FTC<TO>").WithArguments("C.FTC<TC>(TC)", "TC", "TO").WithLocation(76, 11), // (86,11): error CS0452: The type 'TO' must be a reference type in order to use it as parameter 'TCO' in the generic type or method 'C.FTCO<TCO>(TCO)' // C.FTCO<TO> // illegal Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "FTCO<TO>").WithArguments("C.FTCO<TCO>(TCO)", "TCO", "TO").WithLocation(86, 11), // (100,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(100, 9), // (111,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // (default); // 15 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(111, 14) ); } [Fact] public void DefaultParameterValue() { var src = @" #nullable enable C<string?> one = new(); C<string?> other = new(); _ = one.SequenceEqual(other); _ = one.SequenceEqual(other, comparer: null); public interface IIn<in t> { } static class Extension { public static bool SequenceEqual<TDerived, TBase>(this C<TBase> one, C<TDerived> other, IIn<TBase>? comparer = null) where TDerived : TBase => throw null!; } public class C<T> { } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); } [Fact] public void IgnoredNullability_CopyTypeModifiers_ImplicitContainingType() { var src = @" #nullable enable var c = new C<string>(); c.Property.Property2 = null; public interface I<T> { T Property { get; set; } } public class C<U> : I<C<U>.Nested> { public Nested Property { get; set; } // implicitly means C<U>.Nested public class Nested { public U Property2 { get; set; } } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (5,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.Property.Property2 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 24), // (13,19): warning CS8618: Non-nullable property 'Property' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public Nested Property { get; set; } // implicitly means C<U>.Nested Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Property").WithArguments("property", "Property").WithLocation(13, 19), // (16,18): warning CS8618: Non-nullable property 'Property2' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public U Property2 { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Property2").WithArguments("property", "Property2").WithLocation(16, 18) ); } [Fact] public void IgnoredNullability_CopyTypeModifiers_ExplicitContainingType() { var src = @" #nullable enable var c = new C<string>(); c.Property.Property2 = null; public interface I<T> { public T Property { get; set; } } public class C<U> : I<C<U>.Nested> { public C<U>.Nested Property { get; set; } public class Nested { public U Property2 { get; set; } } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (5,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.Property.Property2 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 24), // (13,24): warning CS8618: Non-nullable property 'Property' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C<U>.Nested Property { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Property").WithArguments("property", "Property").WithLocation(13, 24), // (16,18): warning CS8618: Non-nullable property 'Property2' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public U Property2 { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Property2").WithArguments("property", "Property2").WithLocation(16, 18) ); } [Fact] public void IgnoredNullability_ConditionalWithThis() { var src = @" #nullable enable internal class C<T> { public C<T> M(bool b) { if (b) return b ? this : new C<T>(); else return b ? new C<T>() : this; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void IgnoredNullability_ImplicitlyTypedArrayWithThis() { var src = @" #nullable enable internal class C<T> { public C<T>[] M(bool b) { if (b) return new[] { this, new C<T>() }; else return new[] { new C<T>(), this }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(49722, "https://github.com/dotnet/roslyn/issues/49722")] public void IgnoredNullability_ImplicitlyTypedArrayWithThis_DifferentNullability() { var src = @" #nullable enable internal class C<T> { public void M(bool b) { _ = b ? this : new C<T?>(); } } "; var comp = CreateCompilation(src); // missing warning comp.VerifyDiagnostics(); } [Fact] public void IgnoredNullability_StaticField() { var src = @" #nullable enable public class C<T> { public static int field; public void M() { var x = field; var y = C<T>.field; #nullable disable var z = C<T>.field; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var declarators = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().ToArray(); Assert.Equal("field", declarators[0].Value.ToString()); var field1 = model.GetSymbolInfo(declarators[0].Value).Symbol; Assert.Equal("C<T>.field", declarators[1].Value.ToString()); var field2 = model.GetSymbolInfo(declarators[1].Value).Symbol; Assert.Equal("C<T>.field", declarators[2].Value.ToString()); var field3 = model.GetSymbolInfo(declarators[2].Value).Symbol; Assert.True(field2.Equals(field3, SymbolEqualityComparer.Default)); Assert.False(field2.Equals(field3, SymbolEqualityComparer.IncludeNullability)); Assert.True(field3.Equals(field2, SymbolEqualityComparer.Default)); Assert.False(field3.Equals(field2, SymbolEqualityComparer.IncludeNullability)); Assert.Equal(field2.GetHashCode(), field3.GetHashCode()); Assert.True(field1.Equals(field2, SymbolEqualityComparer.Default)); Assert.False(field1.Equals(field2, SymbolEqualityComparer.IncludeNullability)); Assert.True(field2.Equals(field1, SymbolEqualityComparer.Default)); Assert.False(field2.Equals(field1, SymbolEqualityComparer.IncludeNullability)); Assert.Equal(field1.GetHashCode(), field2.GetHashCode()); Assert.True(field1.Equals(field3, SymbolEqualityComparer.Default)); Assert.True(field1.Equals(field3, SymbolEqualityComparer.IncludeNullability)); Assert.True(field3.Equals(field1, SymbolEqualityComparer.Default)); Assert.True(field3.Equals(field1, SymbolEqualityComparer.IncludeNullability)); Assert.Equal(field1.GetHashCode(), field3.GetHashCode()); } [Fact, WorkItem(49798, "https://github.com/dotnet/roslyn/issues/49798")] public void IgnoredNullability_MethodSymbol() { var src = @" #nullable enable public class C { public void M<T>(out T x) { M<T>(out x); #nullable disable M<T>(out x); } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method1 = model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single()); Assert.True(method1.IsDefinition); var invocations = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray(); Assert.Equal("M<T>(out x)", invocations[0].ToString()); var method2 = model.GetSymbolInfo(invocations[0]).Symbol; Assert.False(method2.IsDefinition); Assert.Equal("M<T>(out x)", invocations[1].ToString()); var method3 = model.GetSymbolInfo(invocations[1]).Symbol; Assert.True(method3.IsDefinition); // definitions and substituted symbols should be equal when ignoring nullability // Tracked by issue https://github.com/dotnet/roslyn/issues/49798 Assert.False(method2.Equals(method3, SymbolEqualityComparer.Default)); Assert.False(method2.Equals(method3, SymbolEqualityComparer.IncludeNullability)); Assert.False(method3.Equals(method2, SymbolEqualityComparer.Default)); Assert.False(method3.Equals(method2, SymbolEqualityComparer.IncludeNullability)); //Assert.Equal(method2.GetHashCode(), method3.GetHashCode()); Assert.False(method1.Equals(method2, SymbolEqualityComparer.Default)); Assert.False(method1.Equals(method2, SymbolEqualityComparer.IncludeNullability)); Assert.False(method2.Equals(method1, SymbolEqualityComparer.Default)); Assert.False(method2.Equals(method1, SymbolEqualityComparer.IncludeNullability)); //Assert.Equal(method1.GetHashCode(), method2.GetHashCode()); Assert.True(method1.Equals(method3, SymbolEqualityComparer.Default)); Assert.True(method1.Equals(method3, SymbolEqualityComparer.IncludeNullability)); Assert.True(method3.Equals(method1, SymbolEqualityComparer.Default)); Assert.True(method3.Equals(method1, SymbolEqualityComparer.IncludeNullability)); Assert.Equal(method1.GetHashCode(), method3.GetHashCode()); } [Fact] public void IgnoredNullability_OverrideReturnType_WithoutConstraint() { var src = @" #nullable enable public class C { public virtual T M<T>() => throw null!; } public class D : C { public override T? M<T>() where T : default => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? M<T>() where T : class => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M").WithLocation(10, 24) ); } [Fact] public void IgnoredNullability_OverrideReturnType_WithClassConstraint() { var src = @" #nullable enable public class C { public virtual T M<T>() where T : class => throw null!; } public class D : C { public override T? M<T>() where T : class => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? M<T>() where T : class => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M").WithLocation(10, 24) ); } [Fact, WorkItem(49131, "https://github.com/dotnet/roslyn/issues/49131")] public void IgnoredNullability_OverrideOutParameterType_WithoutConstraint() { var src = @" #nullable enable public class C { public virtual void M<T>(out T t) => throw null!; } public class D : C { public override void M<T>(out T? t) where T : default => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void M<T>(out T? t) where T : default => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("t").WithLocation(10, 26) ); } [Fact, WorkItem(49131, "https://github.com/dotnet/roslyn/issues/49131")] public void IgnoredNullability_OverrideOutParameterType_WithClassConstraint() { var src = @" #nullable enable public class C { public virtual void M<T>(out T t) where T : class => throw null!; } public class D : C { public override void M<T>(out T? t) where T : class => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void M<T>(out T? t) where T : class => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("t").WithLocation(10, 26) ); } [Fact] public void IgnoredNullability_ImplementationReturnType_WithoutConstraint() { var src = @" #nullable enable public interface I { T M<T>(); } public class D : I { public T? M<T>() => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,15): warning CS8766: Nullability of reference types in return type of 'T? D.M<T>()' doesn't match implicitly implemented member 'T I.M<T>()' (possibly because of nullability attributes). // public T? M<T>() => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M").WithArguments("T? D.M<T>()", "T I.M<T>()").WithLocation(10, 15) ); } [Fact] public void IgnoredNullability_ImplementationReturnType_WithClassConstraint() { var src = @" #nullable enable public interface I { T M<T>() where T : class; } public class D : I { public T? M<T>() where T : class => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,15): warning CS8766: Nullability of reference types in return type of 'T? D.M<T>()' doesn't match implicitly implemented member 'T I.M<T>()' (possibly because of nullability attributes). // public T? M<T>() where T : class => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M").WithArguments("T? D.M<T>()", "T I.M<T>()").WithLocation(10, 15) ); } [Fact, WorkItem(49071, "https://github.com/dotnet/roslyn/issues/49071")] public void IgnoredNullability_PartialMethodReturnType_WithoutConstraint() { var src = @" #nullable enable partial class C { public partial T F<T>(); } partial class C { public partial T? F<T>() => default; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,23): warning CS8819: Nullability of reference types in return type doesn't match partial method declaration. // public partial T? F<T>() => default; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial, "F").WithLocation(10, 23) ); } [Fact, WorkItem(49071, "https://github.com/dotnet/roslyn/issues/49071")] public void IgnoredNullability_PartialMethodReturnType_WithClassConstraint() { var src = @" #nullable enable partial class C { public partial T F<T>() where T : class; } partial class C { public partial T? F<T>() where T : class => default; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,23): warning CS8819: Nullability of reference types in return type doesn't match partial method declaration. // public partial T? F<T>() where T : class => default; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial, "F").WithLocation(10, 23) ); } [Fact] [WorkItem(50097, "https://github.com/dotnet/roslyn/issues/50097")] public void Issue50097() { var src = @" using System; public class C { static void Main() { } public record AuditedItem<T>(T Value, string ConcurrencyToken, DateTimeOffset LastChange) where T : class; public record FieldItem(object? Value, string ConcurrencyToken, DateTimeOffset LastChange) : AuditedItem<object?>(Value, ConcurrencyToken, LastChange); } namespace System.Runtime.CompilerServices { public static class IsExternalInit { } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe.WithNullableContextOptions(NullableContextOptions.Enable)); var diagnostics = comp.GetEmitDiagnostics(); diagnostics.Verify( // (13,19): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C.AuditedItem<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // public record FieldItem(object? Value, string ConcurrencyToken, DateTimeOffset LastChange) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "FieldItem").WithArguments("C.AuditedItem<T>", "T", "object?").WithLocation(13, 19), // (13,19): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C.AuditedItem<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // public record FieldItem(object? Value, string ConcurrencyToken, DateTimeOffset LastChange) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "FieldItem").WithArguments("C.AuditedItem<T>", "T", "object?").WithLocation(13, 19), // (13,19): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C.AuditedItem<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // public record FieldItem(object? Value, string ConcurrencyToken, DateTimeOffset LastChange) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "FieldItem").WithArguments("C.AuditedItem<T>", "T", "object?").WithLocation(13, 19) ); var reportedDiagnostics = new HashSet<Diagnostic>(); reportedDiagnostics.AddAll(diagnostics); Assert.Equal(1, reportedDiagnostics.Count); } [Fact] public void AmbigMember_DynamicDifferences() { var src = @" interface I<T> { T Item { get; } } interface I2<T> : I<T> { } interface I3 : I<dynamic>, I2<object> { } public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,11): error CS8779: 'I<object>' is already listed in the interface list on type 'I3' as 'I<dynamic>'. // interface I3 : I<dynamic>, I2<object> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithDifferencesInBaseList, "I3").WithArguments("I<object>", "I<dynamic>", "I3").WithLocation(6, 11), // (6,16): error CS1966: 'I3': cannot implement a dynamic interface 'I<dynamic>' // interface I3 : I<dynamic>, I2<object> { } Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I<dynamic>").WithArguments("I3", "I<dynamic>").WithLocation(6, 16), // (12,15): error CS0229: Ambiguity between 'I<dynamic>.Item' and 'I<object>.Item' // _ = i.Item; Diagnostic(ErrorCode.ERR_AmbigMember, "Item").WithArguments("I<dynamic>.Item", "I<object>.Item").WithLocation(12, 15) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<dynamic>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<dynamic>", "I2<object>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_TupleDifferences() { var src = @" interface I<T> { T Item { get; } } interface I2<T> : I<T> { } interface I3 : I<(int a, int b)>, I2<(int notA, int notB)> { } public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,11): error CS8140: 'I<(int notA, int notB)>' is already listed in the interface list on type 'I3' with different tuple element names, as 'I<(int a, int b)>'. // interface I3 : I<(int a, int b)>, I2<(int notA, int notB)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "I3").WithArguments("I<(int notA, int notB)>", "I<(int a, int b)>", "I3").WithLocation(6, 11), // (12,15): error CS0229: Ambiguity between 'I<(int a, int b)>.Item' and 'I<(int notA, int notB)>.Item' // _ = i.Item; Diagnostic(ErrorCode.ERR_AmbigMember, "Item").WithArguments("I<(int a, int b)>.Item", "I<(int notA, int notB)>.Item").WithLocation(12, 15) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<(int a, int b)>", "I2<(int notA, int notB)>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<(int a, int b)>", "I2<(int notA, int notB)>", "I<(int notA, int notB)>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_TupleAndNullabilityDifferences() { var src = @" #nullable disable interface I<T> { T Item { get; } } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I<(object a, object b)>, I2<(object notA, object notB)> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,11): error CS8140: 'I<(object notA, object notB)>' is already listed in the interface list on type 'I3' with different tuple element names, as 'I<(object a, object b)>'. // interface I3 : I<(object a, object b)>, I2<(object notA, object notB)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "I3").WithArguments("I<(object notA, object notB)>", "I<(object a, object b)>", "I3").WithLocation(9, 11), // (16,15): error CS0229: Ambiguity between 'I<(object a, object b)>.Item' and 'I<(object notA, object notB)>.Item' // _ = i.Item; Diagnostic(ErrorCode.ERR_AmbigMember, "Item").WithArguments("I<(object a, object b)>.Item", "I<(object notA, object notB)>.Item").WithLocation(16, 15) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<(object a, object b)>", "I2<(object notA, object notB)>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<(object a, object b)>", "I2<(object notA, object notB)>", "I<(object notA, object notB)>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_NoDifference() { var src = @" interface I<T> { T Item { get; } } interface I2<T> : I<T> { } interface I3 : I<object>, I2<object> { } public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I2<object>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithoutConstraint() { var src = @" #nullable disable interface I<T> { T Item { get; set; } } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I2<object>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("i.Item", item.ToString()); Assert.Equal("object", ((IPropertySymbol)model.GetSymbolInfo(item).Symbol).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); var found = model.LookupSymbols(item.SpanStart, i3.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithoutConstraint_Indexer() { var src = @" #nullable disable interface I<T> { T this[int i] { get; set; } } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i[0]; i[0] = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().First(); Assert.Equal("i[0]", item.ToString()); Assert.Equal("object", ((IPropertySymbol)model.GetSymbolInfo(item).Symbol).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithoutConstraint_Event() { var src = @" using System; #nullable disable interface I<T> { event Func<T, T> Event; } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i, Func<object, object> f1, Func<object?, object?> f2) { i.Event += f1; i.Event += f2; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithoutConstraint_Nested() { var src = @" #nullable disable interface I<T> { interface Inner { static T Item { get; set; } } } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M() { _ = I3.Inner.Item; I3.Inner.Item = null; } } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithoutConstraint_Method() { var src = @" #nullable disable interface I<T> { ref T Get(); } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Get(); i.Get() = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("i.Get()", item.ToString()); Assert.Equal("object", ((IMethodSymbol)model.GetSymbolInfo(item).Symbol).ReturnType.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithoutConstraint_ReverseOrder() { var src = @" #nullable disable interface I<T> { T Item { get; set; } } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I2<object>, I<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I2<object>", "I<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I2<object>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("i.Item", item.ToString()); Assert.Equal("object", ((IPropertySymbol)model.GetSymbolInfo(item).Symbol).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); var found = model.LookupSymbols(item.SpanStart, i3.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<object>", "I2<object>", "I<object!>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.True(model.LookupNames(item.SpanStart, i3.GetPublicSymbol()).Contains("Item")); var found = model.LookupSymbols(item.SpanStart, i3.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_OnTypeParameter() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M<T>(T i) where T : I3 { _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<object>", "I2<object>", "I<object!>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.True(model.LookupNames(item.SpanStart, i3.GetPublicSymbol()).Contains("Item")); var t = ((MethodSymbol)comp.GetMember("C.M")).TypeParameters.Single(); var found = model.LookupSymbols(item.SpanStart, t.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_OnTypeParameterImplementingBothInterfaces() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } public class C { #nullable disable void M<T>(T i) where T : I<object>, I2<object> { #nullable enable _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); var t = ((MethodSymbol)comp.GetMember("C.M")).TypeParameters.Single(); Assert.True(model.LookupNames(item.SpanStart, t.GetPublicSymbol()).Contains("Item")); var found = model.LookupSymbols(item.SpanStart, t.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_Indexer() { var src = @" #nullable disable interface I<T> where T : class { T this[int i] { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i[0]; i[0] = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().First(); Assert.Equal("i[0]", item.ToString()); Assert.Equal("object", ((IPropertySymbol)model.GetSymbolInfo(item).Symbol).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_Event() { var src = @" using System; #nullable disable interface I<T> where T : class { event Func<T, T> Event; } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i, Func<object, object> f1, Func<object?, object?> f2) { i.Event += f1; i.Event += f2; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_Nested() { var src = @" #nullable disable interface I<T> where T : class { interface Inner { static T Item { get; set; } } } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M() { _ = I3.Inner.Item; I3.Inner.Item = null; } } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_Method() { var src = @" #nullable disable interface I<T> where T : class { ref T Get(); } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Get(); i.Get() = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("i.Get()", item.ToString()); Assert.Equal("object", ((IMethodSymbol)model.GetSymbolInfo(item).Symbol).ReturnType.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); var i3 = comp.GetTypeByMetadataName("I3"); Assert.True(model.LookupNames(item.SpanStart, i3.GetPublicSymbol()).Contains("Get")); var found = model.LookupSymbols(item.SpanStart, i3.GetPublicSymbol()).Single(s => s.Name == "Get"); Assert.Equal("object", ((IMethodSymbol)found).ReturnType.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_ReverseOrder() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I2<object>, I<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (17,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // i.Item = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(17, 18) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I2<object>", "I<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I2<object>", "I<object!>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); var found = model.LookupSymbols(item.SpanStart, i3.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object!", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_ReverseOrder_OnTypeParameter() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I2<object>, I<object> { } #nullable enable public class C { void M<T>(T i) where T : I3 { _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (17,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // i.Item = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(17, 18) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I2<object>", "I<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I2<object>", "I<object!>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); var t = ((MethodSymbol)comp.GetMember("C.M")).TypeParameters.Single(); var found = model.LookupSymbols(item.SpanStart, t.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object!", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_ReverseOrder_OnTypeParameterImplementingBothInterfaces() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } public class C { #nullable disable void M<T>(T i) where T : I2<object>, I<object> { #nullable enable _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (15,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // i.Item = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 18) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); var t = ((MethodSymbol)comp.GetMember("C.M")).TypeParameters.Single(); var found = model.LookupSymbols(item.SpanStart, t.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object!", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNullableAndOblivious_WithConstraint() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; } } #nullable enable interface I2<T> : I<T> where T : class { } interface I3 : I<object?>, #nullable disable I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,11): warning CS8645: 'I<object>' is already listed in the interface list on type 'I3' with different nullability of reference types. // interface I3 : I<object?>, Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I3").WithArguments("I<object>", "I3").WithLocation(8, 11) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object?>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<object?>", "I2<object>", "I<object!>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNullableAndOblivious_WithoutConstraint() { var src = @" #nullable disable interface I<T> { T Item { get; } } #nullable enable interface I2<T> : I<T> { } interface I3 : I<object?>, #nullable disable I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object?>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<object?>", "I2<object>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNullableAndNonnullable() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; } } #nullable enable interface I2<T> : I<T> where T : class { } interface I3 : I<object?>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,11): warning CS8645: 'I<object>' is already listed in the interface list on type 'I3' with different nullability of reference types. // interface I3 : I<object?>, I2<object> { } Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I3").WithArguments("I<object>", "I3").WithLocation(8, 11) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object?>", "I2<object!>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<object?>", "I2<object!>", "I<object!>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void VarPatternDeclaration_TopLevel() { var src = @" #nullable enable public class C { public void M(string? x) { if (Identity(x) is var y) { y.ToString(); // 1 } if (Identity(x) is not null and var z) { z.ToString(); } } public T Identity<T>(T t) => t; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 13) ); } [Fact] public void VarPatternDeclaration_Nested() { var src = @" #nullable enable public class Container<T> { public T Item { get; set; } = default!; } public class C { public void M(Container<string?> x) { if (Identity(x) is { Item: var y }) { y.ToString(); // 1 } if (Identity(x) is { Item: not null and var z }) { z.ToString(); } } public T Identity<T>(T t) => t; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(13, 13) ); } [Theory, WorkItem(52925, "https://github.com/dotnet/roslyn/issues/52925")] [WorkItem(46236, "https://github.com/dotnet/roslyn/issues/46236")] [InlineData("")] [InlineData(" where T : notnull")] [InlineData(" where T : class")] [InlineData(" where T : class?")] public void VarDeclarationWithGenericType(string constraint) { var src = $@" #nullable enable class C<T> {constraint} {{ void M(T initial, System.Func<T, T?> selector) {{ for (var current = initial; current != null; current = selector(current)) {{ }} var current2 = initial; current2 = default; for (T? current3 = initial; current3 != null; current3 = selector(current3)) {{ }} T? current4 = initial; current4 = default; }} }} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var declarations = tree.GetRoot().DescendantNodes().OfType<VariableDeclarationSyntax>(); foreach (var declaration in declarations) { var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration.Variables.Single()); Assert.Equal("T?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); } } [Theory, WorkItem(52925, "https://github.com/dotnet/roslyn/issues/52925")] [InlineData("")] [InlineData(" where T : notnull")] [InlineData(" where T : class")] [InlineData(" where T : class?")] public void VarDeclarationWithGenericType_RefValue(string constraint) { var src = $@" #nullable enable class C<T> {constraint} {{ ref T Passthrough(ref T value) {{ ref var value2 = ref value; return ref value2; }} }} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,20): warning CS8619: Nullability of reference types in value of type 'T?' doesn't match target type 'T'. // return ref value2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "value2").WithArguments("T?", "T").WithLocation(9, 20) ); } [Fact, WorkItem(55227, "https://github.com/dotnet/roslyn/issues/55227")] public void Issue55227_01() { var source = @" #nullable enable static class Program { public static void Main() { } public static object Test(object a) { var isNullCheck = new global::System.Func<object, object>((p) => { switch (p == null) { case var isnull: return isnull; } }); return isNullCheck(a); } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(55227, "https://github.com/dotnet/roslyn/issues/55227")] public void Issue55227_02() { var source = @" #nullable enable static class Program { public static void Main() { } public static object Test(object a) { var isNullCheck = new global::System.Func<object, object>((p) => (p == null) switch { var isnull => isnull } ); return isNullCheck(a); } } "; CreateCompilation(source).VerifyDiagnostics(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CSharp.Symbols.FlowAnalysisAnnotations; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Semantics { [CompilerTrait(CompilerFeature.NullableReferenceTypes)] public class NullableReferenceTypesTests : CSharpTestBase { private const string Tuple2NonNullable = @" namespace System { #nullable enable // struct with two values public struct ValueTuple<T1, T2> where T1 : notnull where T2 : notnull { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return """"; } } }"; private const string TupleRestNonNullable = @" namespace System { #nullable enable public struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> where T1 : notnull where T2 : notnull where T3 : notnull where T4 : notnull where T5 : notnull where T6 : notnull where T7 : notnull { public T1 Item1; public T2 Item2; public T3 Item3; public T4 Item4; public T5 Item5; public T6 Item6; public T7 Item7; public TRest Rest; public ValueTuple(T1 item1, T2 item2, T3 item3, T4 item4, T5 item5, T6 item6, T7 item7, TRest rest) { Item1 = item1; Item2 = item2; Item3 = item3; Item4 = item4; Item5 = item5; Item6 = item6; Item7 = item7; Rest = rest; } public override string ToString() { return base.ToString(); } } }"; private CSharpCompilation CreateNullableCompilation(CSharpTestSource source, IEnumerable<MetadataReference> references = null, CSharpParseOptions parseOptions = null) { return CreateCompilation(source, options: WithNullableEnable(), references: references, parseOptions: parseOptions); } private static bool IsNullableAnalysisEnabled(CSharpCompilation compilation, string methodName) { var method = compilation.GetMember<MethodSymbol>(methodName); return method.IsNullableAnalysisEnabled(); } [Fact] public void DefaultLiteralInConditional() { var comp = CreateNullableCompilation(@" class C { public void M<T>(bool condition, T t) { t = default; _ = condition ? t : default; _ = condition ? default : t; } }"); comp.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // t = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(6, 13)); } [Fact, WorkItem(46461, "https://github.com/dotnet/roslyn/issues/46461")] public void DefaultLiteralInConditional_02() { var comp = CreateNullableCompilation(@" using System; public class C { public void M() { M1(true, b => b ? """" : default); M1<bool, string?>(true, b => b ? """" : default); M1<bool, string>(true, b => b ? """" : default); // 1 M1(true, b => b ? """" : null); M1<bool, string?>(true, b => b ? """" : null); M1<bool, string>(true, b => b ? """" : null); // 2 } public void M1<T,U>(T t, Func<T, U> fn) { fn(t); } }"); comp.VerifyDiagnostics( // (10,37): warning CS8603: Possible null reference return. // M1<bool, string>(true, b => b ? "" : default); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, @"b ? """" : default", isSuppressed: false).WithLocation(10, 37), // (14,37): warning CS8603: Possible null reference return. // M1<bool, string>(true, b => b ? "" : null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, @"b ? """" : null", isSuppressed: false).WithLocation(14, 37)); } [Fact, WorkItem(33982, "https://github.com/dotnet/roslyn/issues/33982")] public void AssigningNullToRefLocalIsSafetyWarning() { var comp = CreateCompilation(@" class C { void M(ref string s1, ref string s2) { s1 = null; // 1 s1.ToString(); // 2 ref string s3 = ref s2; s3 = null; // 3 s3.ToString(); // 4 ref string s4 = ref s2; s4 ??= null; // 5 s4.ToString(); // 6 ref string s5 = ref s2; M2(out s5); // 7 s5.ToString(); // 8 } void M2(out string? x) => throw null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // s1 = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 14), // (7,9): warning CS8602: Possible dereference of a null reference. // s1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(7, 9), // (10,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // s3 = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 14), // (11,9): warning CS8602: Possible dereference of a null reference. // s3.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(11, 9), // (14,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // s4 ??= null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 16), // (15,9): warning CS8602: Possible dereference of a null reference. // s4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(15, 9), // (18,16): warning CS8601: Possible null reference assignment. // M2(out s5); // 7 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s5").WithLocation(18, 16), // (19,9): warning CS8602: Possible dereference of a null reference. // s5.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(19, 9) ); } [Fact, WorkItem(33365, "https://github.com/dotnet/roslyn/issues/33365")] public void AssigningNullToConditionalRefLocal() { var comp = CreateCompilation(@" class C { void M(ref string s1, ref string s2, bool b) { (b ? ref s1 : ref s1) = null; // 1 s1.ToString(); ref string s3 = ref s2; (b ? ref s3 : ref s3) = null; // 2 s3.ToString(); ref string s4 = ref s2; (b ? ref s4 : ref s4) ??= null; // 3 s4.ToString(); ref string s5 = ref s2; M2(out (b ? ref s5 : ref s5)); // 4 s5.ToString(); } void M2(out string? x) => throw null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,33): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref s1 : ref s1) = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 33), // (10,33): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref s3 : ref s3) = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 33), // (14,35): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref s4 : ref s4) ??= null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 35), // (18,17): warning CS8601: Possible null reference assignment. // M2(out (b ? ref s5 : ref s5)); // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "b ? ref s5 : ref s5").WithLocation(18, 17) ); } [Fact, WorkItem(33365, "https://github.com/dotnet/roslyn/issues/33365")] public void AssigningNullToConditionalRefLocal_NullableLocals() { var comp = CreateCompilation(@" class C { void M(ref string? s1, ref string? s2, bool b) { (b ? ref s1 : ref s1) = null; s1.ToString(); // 1 ref string? s3 = ref s2; (b ? ref s3 : ref s3) = null; s3.ToString(); // 2 ref string? s4 = ref s2; (b ? ref s4 : ref s4) ??= null; s4.ToString(); // 3 ref string? s5 = ref s2; M2(out (b ? ref s5 : ref s5)); s5.ToString(); // 4 } void M2(out string? x) => throw null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Possible dereference of a null reference. // s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(7, 9), // (11,9): warning CS8602: Possible dereference of a null reference. // s3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(11, 9), // (15,9): warning CS8602: Possible dereference of a null reference. // s4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(15, 9), // (19,9): warning CS8602: Possible dereference of a null reference. // s5.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(19, 9) ); } [Fact, WorkItem(33365, "https://github.com/dotnet/roslyn/issues/33365")] public void AssigningNullToConditionalRefLocal_NullableLocals_NonNullValues() { var comp = CreateCompilation(@" class C { void M(ref string? s1, ref string? s2, bool b) { (b ? ref s1 : ref s1) = """"; s1.ToString(); // 1 ref string? s3 = ref s2; (b ? ref s3 : ref s3) = """"; s3.ToString(); // 2 ref string? s4 = ref s2; (b ? ref s4 : ref s4) ??= """"; s4.ToString(); // 3 ref string? s5 = ref s2; M2(out (b ? ref s5 : ref s5)); s5.ToString(); // 4 } void M2(out string x) => throw null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Possible dereference of a null reference. // s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(7, 9), // (11,9): warning CS8602: Possible dereference of a null reference. // s3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(11, 9), // (15,9): warning CS8602: Possible dereference of a null reference. // s4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(15, 9), // (19,9): warning CS8602: Possible dereference of a null reference. // s5.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(19, 9) ); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver() { var comp = CreateCompilation(@" public class B { public B? f2; public B? f3; } public class C { public B? f; static void Main() { new C() { f = { f2 = null, f3 = null }}; // 1 } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,23): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C.f'. // new C() { f = { f2 = null, f3 = null }}; // 1 Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ f2 = null, f3 = null }").WithArguments("C.f").WithLocation(12, 23)); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_Generic() { var comp = CreateCompilation(@" public interface IB { object? f2 { get; set; } object? f3 { get; set; } } public struct StructB : IB { public object? f2 { get; set; } public object? f3 { get; set; } } public class ClassB : IB { public object? f2 { get; set; } public object? f3 { get; set; } } public class C<T> where T : IB? { public T f = default!; static void Main() { new C<T>() { f = { f2 = null, f3 = null }}; // 1 new C<ClassB>() { f = { f2 = null, f3 = null }}; new C<ClassB?>() { f = { f2 = null, f3 = null }}; // 2 new C<StructB>() { f = { f2 = null, f3 = null }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (25,26): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C<T>.f'. // new C<T>() { f = { f2 = null, f3 = null }}; // 1 Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ f2 = null, f3 = null }").WithArguments("C<T>.f").WithLocation(25, 26), // (27,32): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C<ClassB?>.f'. // new C<ClassB?>() { f = { f2 = null, f3 = null }}; // 2 Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ f2 = null, f3 = null }").WithArguments("C<ClassB?>.f").WithLocation(27, 32)); } [Fact, WorkItem(38060, "https://github.com/dotnet/roslyn/issues/38060")] public void CheckImplicitObjectInitializerReceiver_EmptyInitializers() { var comp = CreateCompilation(@" public class B { } public class C { public B? f; static void Main() { new C() { f = { }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_CollectionInitializer() { var comp = CreateCompilation(@" using System.Collections; public class B : IEnumerable { public void Add(object o) { } public IEnumerator GetEnumerator() => null!; } public class C { public B? f; static void Main() { new C() { f = { new object(), new object() }}; // 1 } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,23): warning CS8670: Object or collection initializer implicitly dereferences nullable member 'C.f'. // new C() { f = { new object(), new object() }}; // 1 Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ new object(), new object() }").WithArguments("C.f").WithLocation(15, 23)); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_CollectionInitializer_Generic() { var comp = CreateCompilation(@" using System.Collections; public interface IAddable : IEnumerable { void Add(object o); } public class ClassAddable : IAddable { public void Add(object o) { } public IEnumerator GetEnumerator() => null!; } public struct StructAddable : IAddable { public void Add(object o) { } public IEnumerator GetEnumerator() => null!; } public class C<T> where T : IAddable? { public T f = default!; static void Main() { new C<T>() { f = { new object(), new object() }}; // 1 new C<ClassAddable>() { f = { new object(), new object() }}; new C<ClassAddable?>() { f = { new object(), new object() }}; // 2 new C<StructAddable>() { f = { new object(), new object() }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (27,26): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C<T>.f'. // new C<T>() { f = { new object(), new object() }}; // 1 Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ new object(), new object() }").WithArguments("C<T>.f").WithLocation(27, 26), // (29,38): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C<ClassAddable?>.f'. // new C<ClassAddable?>() { f = { new object(), new object() }}; // 2 Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ new object(), new object() }").WithArguments("C<ClassAddable?>.f").WithLocation(29, 38)); } [Fact, WorkItem(38060, "https://github.com/dotnet/roslyn/issues/38060")] public void CheckImplicitObjectInitializerReceiver_EmptyCollectionInitializer() { var comp = CreateCompilation(@" public class B { void Add(object o) { } } public class C { public B? f; static void Main() { new C() { f = { }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_ReceiverNotNullable() { var comp = CreateCompilation(@" public class B { public B? f2; } public class C { public B f; static void Main() { new C() { f = { f2 = null }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8618: Non-nullable field 'f' is uninitialized. Consider declaring the field as nullable. // public B f; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "f").WithArguments("field", "f").WithLocation(8, 14) ); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_ReceiverOblivious() { var comp = CreateCompilation(@" public class B { public B? f2; } public class C { #nullable disable public B f; #nullable enable static void Main() { new C() { f = { f2 = null }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_ReceiverNullableIndexer() { var comp = CreateCompilation(@" public class B { public B? f2; } public class C { static void Main() { new C() { [0] = { f2 = null }}; } public B? this[int i] { get => throw null!; set => throw null!; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,25): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C.this[int]'. // new C() { [0] = { f2 = null }}; Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ f2 = null }").WithArguments("C.this[int]").WithLocation(10, 25)); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_Nested() { var comp = CreateCompilation(@" public class B { public B? f2; } public class C { public C? fc; public B? fb; static void Main() { new C() { fc = { fb = { f2 = null} }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,24): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C.fc'. // new C() { fc = { fb = { f2 = null} }}; Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ fb = { f2 = null} }").WithArguments("C.fc").WithLocation(12, 24), // (12,31): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C.fb'. // new C() { fc = { fb = { f2 = null} }}; Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ f2 = null}").WithArguments("C.fb").WithLocation(12, 31)); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitObjectInitializerReceiver_Index() { var comp = CreateCompilation(@" public class B { public B? this[int i] { get => throw null!; set => throw null!; } } public class C { public B? f; static void Main() { new C() { f = { [0] = null }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,23): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C.f'. // new C() { f = { [0] = null }}; Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ [0] = null }").WithArguments("C.f").WithLocation(11, 23)); } [Fact, WorkItem(32495, "https://github.com/dotnet/roslyn/issues/32495")] public void CheckImplicitCollectionInitializerReceiver() { var comp = CreateCompilation(@" public class B : System.Collections.Generic.IEnumerable<int> { public void Add(int i) { } System.Collections.Generic.IEnumerator<int> System.Collections.Generic.IEnumerable<int>.GetEnumerator() => throw null!; System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => throw null!; } public class C { public B? f; static void Main() { new C() { f = { 1 }}; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,23): warning CS8670: Object or collection initializer implicitly dereferences possibly null member 'C.f'. // new C() { f = { 1 }}; Diagnostic(ErrorCode.WRN_NullReferenceInitializer, "{ 1 }").WithArguments("C.f").WithLocation(13, 23)); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_ReturnType() { var comp = CreateCompilation(@" using System.Collections.Generic; class C { static void M(object? o, object o2) { L(o)[0].ToString(); // 1 foreach (var x in L(o)) { x.ToString(); // 2 } L(o2)[0].ToString(); } static List<T> L<T>(T t) => null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // L(o)[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "L(o)[0]").WithLocation(7, 9), // (10,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 13)); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_ReturnType_Inferred() { var comp = CreateCompilation(@" public class C<T> { public T Field = default!; public C<T> this[T index] { get => throw null!; set => throw null!; } } public class Main { static void M(object? o, object o2) { if (o is null) return; L(o)[0].Field.ToString(); o2 = null; L(o2)[0].Field.ToString(); // 1 } static C<U> L<U>(U u) => null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // o2 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 14), // (15,9): warning CS8602: Dereference of a possibly null reference. // L(o2)[0].Field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "L(o2)[0].Field").WithLocation(15, 9) ); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_ReturnType_NestedNullability_Inferred() { var comp = CreateCompilation(@" public class C<T> { public T this[int index] { get => throw null!; set => throw null!; } } public class Program { static void M(object? x) { var y = L(new[] { x }); y[0][0].ToString(); // warning if (x == null) return; var z = L(new[] { x }); z[0][0].ToString(); // ok } static C<U> L<U>(U u) => null!; } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // y[0][0].ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y[0][0]").WithLocation(11, 9) ); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_SetterArguments() { var comp = CreateCompilation(@" public class C<T> { public int this[T index] { get => throw null!; set => throw null!; } } class Program { static void M(object? o, object o2) { L(o)[o] = 1; L(o)[o2] = 2; L(o2)[o] = 3; // warn L(o2)[o2] = 4; } static C<U> L<U>(U u) => null!; } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,15): warning CS8604: Possible null reference argument for parameter 'index' in 'int C<object>.this[object index]'. // L(o2)[o] = 3; // warn Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("index", "int C<object>.this[object index]").WithLocation(13, 15) ); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_SetterArguments_Inferred() { var comp = CreateCompilation(@" public class C<T> { public int this[T index] { get => throw null!; set => throw null!; } } class Program { static void M(object? o, object o2, object? input, object input2) { if (o is null) return; L(o)[input] = 1; // 1 L(o)[input2] = 2; o2 = null; L(o2)[input] = 3; L(o2)[input2] = 4; } static C<U> L<U>(U u) => null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,14): warning CS8604: Possible null reference argument for parameter 'index' in 'int C<object>.this[object index]'. // L(o)[input] = 1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "input").WithArguments("index", "int C<object>.this[object index]").WithLocation(11, 14), // (14,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // o2 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 14) ); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_GetterArguments() { var comp = CreateCompilation(@" public class C<T> { public int this[T index] { get => throw null!; set => throw null!; } } class Program { static void M(object? o, object o2) { _ = L(o)[o]; _ = L(o)[o2]; _ = L(o2)[o]; // warn _ = L(o2)[o2]; } static C<U> L<U>(U u) => null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,19): warning CS8604: Possible null reference argument for parameter 'index' in 'int C<object>.this[object index]'. // _ = L(o2)[o]; // warn Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("index", "int C<object>.this[object index]").WithLocation(13, 19) ); } [Fact, WorkItem(29964, "https://github.com/dotnet/roslyn/issues/29964")] public void IndexerUpdatedBasedOnReceiver_SetterArguments_NestedNullability() { var comp = CreateCompilation(@" public class C<T> { public int this[C<T> index] { get => throw null!; set => throw null!; } } class Program { static void M(object? o, object o2) { L(o)[L(o)] = 1; L(o)[L(o2)] = 2; // 1 L(o2)[L(o)] = 3; // 2 L(o2)[L(o2)] = 4; } static C<U> L<U>(U u) => null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,14): warning CS8620: Argument of type 'C<object>' cannot be used for parameter 'index' of type 'C<object?>' in 'int C<object?>.this[C<object?> index]' due to differences in the nullability of reference types. // L(o)[L(o2)] = 2; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "L(o2)").WithArguments("C<object>", "C<object?>", "index", "int C<object?>.this[C<object?> index]").WithLocation(11, 14), // (13,15): warning CS8620: Argument of type 'C<object?>' cannot be used for parameter 'index' of type 'C<object>' in 'int C<object>.this[C<object> index]' due to differences in the nullability of reference types. // L(o2)[L(o)] = 3; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "L(o)").WithArguments("C<object?>", "C<object>", "index", "int C<object>.this[C<object> index]").WithLocation(13, 15) ); } [Fact, WorkItem(33289, "https://github.com/dotnet/roslyn/issues/33289")] public void ConditionalReceiver() { var comp = CreateCompilation(@" public class Container<T> { public T Field = default!; } class C { static void M(string? s) { var x = Create(s); _ = x /*T:Container<string?>?*/; x?.Field.ToString(); // 1 } public static Container<U>? Create<U>(U u) => new Container<U>(); }", options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (13,11): warning CS8602: Dereference of a possibly null reference. // x?.Field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, ".Field").WithLocation(13, 11) ); } [Fact, WorkItem(28792, "https://github.com/dotnet/roslyn/issues/28792")] public void ConditionalReceiver_Verify28792() { var comp = CreateNullableCompilation(@" class C { void M<T>(T t) => t?.ToString(); }"); comp.VerifyDiagnostics(); } [Fact, WorkItem(33289, "https://github.com/dotnet/roslyn/issues/33289")] public void ConditionalReceiver_Chained() { var comp = CreateCompilation(@" public class Container<T> { public T Field = default!; } class C { static void M(string? s) { var x = Create(s); if (x is null) return; _ = x /*T:Container<string?>!*/; x?.Field.ToString(); // 1 x = Create(s); if (x is null) return; x.Field?.ToString(); } public static Container<U>? Create<U>(U u) => new Container<U>(); }", options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (14,11): warning CS8602: Dereference of a possibly null reference. // x?.Field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, ".Field").WithLocation(14, 11) ); } [Fact, WorkItem(33289, "https://github.com/dotnet/roslyn/issues/33289")] public void ConditionalReceiver_Chained_Inversed() { var comp = CreateCompilation(@" public class Container<T> { public T Field = default!; } class C { static void M(string s) { var x = Create(s); _ = x /*T:Container<string!>?*/; x?.Field.ToString(); x = Create(s); x.Field?.ToString(); // 1 } public static Container<U>? Create<U>(U u) => new Container<U>(); }", options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (16,9): warning CS8602: Dereference of a possibly null reference. // x.Field?.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 9) ); } [Fact, WorkItem(33289, "https://github.com/dotnet/roslyn/issues/33289")] public void ConditionalReceiver_Nested() { var comp = CreateCompilation(@" public class Container<T> { public T Field = default!; } class C { static void M(string? s1, string s2) { var x = Create(s1); var y = Create(s2); x?.Field /*1*/ .Extension(y?.Field.ToString()); } public static Container<U>? Create<U>(U u) => new Container<U>(); } public static class Extensions { public static void Extension(this string s, object? o) => throw null!; }", options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (13,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Extensions.Extension(string s, object? o)'. // x?.Field /*1*/ Diagnostic(ErrorCode.WRN_NullReferenceArgument, ".Field").WithArguments("s", "void Extensions.Extension(string s, object? o)").WithLocation(13, 11) ); } [Fact, WorkItem(33289, "https://github.com/dotnet/roslyn/issues/33289")] public void ConditionalReceiver_MiscTypes() { var comp = CreateCompilation(@" public class Container<T> { public T M() => default!; } class C { static void M<T>(int i, Missing m, string s, T t) { Create(i)?.M().ToString(); Create(m)?.M().ToString(); Create(s)?.M().ToString(); Create(t)?.M().ToString(); // 1 } public static Container<U>? Create<U>(U u) => new Container<U>(); }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,29): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // static void M<T>(int i, Missing m, string s, T t) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(8, 29), // (13,19): warning CS8602: Dereference of a possibly null reference. // Create(t)?.M().ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, ".M()").WithLocation(13, 19) ); } [Fact, WorkItem(26810, "https://github.com/dotnet/roslyn/issues/26810")] public void LockStatement() { var comp = CreateCompilation(@" class C { void F(object? maybeNull, object nonNull, Missing? annotatedMissing, Missing unannotatedMissing) { lock (maybeNull) { } lock (nonNull) { } lock (annotatedMissing) { } lock (unannotatedMissing) { } } #nullable disable void F(object oblivious, Missing obliviousMissing) #nullable enable { lock (oblivious) { } lock (obliviousMissing) { } } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,47): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // void F(object? maybeNull, object nonNull, Missing? annotatedMissing, Missing unannotatedMissing) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(4, 47), // (4,74): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // void F(object? maybeNull, object nonNull, Missing? annotatedMissing, Missing unannotatedMissing) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(4, 74), // (6,15): warning CS8602: Dereference of a possibly null reference. // lock (maybeNull) { } Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "maybeNull").WithLocation(6, 15), // (8,15): error CS0185: 'Missing?' is not a reference type as required by the lock statement // lock (annotatedMissing) { } Diagnostic(ErrorCode.ERR_LockNeedsReference, "annotatedMissing").WithArguments("Missing?").WithLocation(8, 15), // (12,30): error CS0246: The type or namespace name 'Missing' could not be found (are you missing a using directive or an assembly reference?) // void F(object oblivious, Missing obliviousMissing) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Missing").WithArguments("Missing").WithLocation(12, 30) ); } [Fact, WorkItem(33537, "https://github.com/dotnet/roslyn/issues/33537")] public void SuppressOnNullLiteralInAs() { var comp = CreateCompilation(@" class C { public static void Main() { var x = null! as object; } }"); comp.VerifyDiagnostics(); } [Fact, WorkItem(26654, "https://github.com/dotnet/roslyn/issues/26654")] [WorkItem(27522, "https://github.com/dotnet/roslyn/issues/27522")] public void SuppressNullableWarning_DeclarationExpression() { var source = @" public class C { public void M(out string? x) => throw null!; public void M2() { M(out string y!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // We don't allow suppressions on out-variable-declarations at this point (LDM 2/13/2019) comp.VerifyDiagnostics( // (7,23): error CS1003: Syntax error, ',' expected // M(out string y!); Diagnostic(ErrorCode.ERR_SyntaxError, "!").WithArguments(",", "!").WithLocation(7, 23), // (7,24): error CS1525: Invalid expression term ')' // M(out string y!); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(7, 24) ); } [Fact, WorkItem(26654, "https://github.com/dotnet/roslyn/issues/26654")] public void SuppressNullableWarning_LocalDeclarationAndAssignmentTarget() { var source = @" public class C { public void M2() { object y! = null; object y2; y2! = null; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // We don't allow suppressions in those positions at this point (LDM 2/13/2019) comp.VerifyDiagnostics( // (6,16): warning CS0168: The variable 'y' is declared but never used // object y! = null; Diagnostic(ErrorCode.WRN_UnreferencedVar, "y").WithArguments("y").WithLocation(6, 16), // (6,17): error CS1002: ; expected // object y! = null; Diagnostic(ErrorCode.ERR_SemicolonExpected, "!").WithLocation(6, 17), // (6,19): error CS1525: Invalid expression term '=' // object y! = null; Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(6, 19), // (7,16): warning CS0219: The variable 'y2' is assigned but its value is never used // object y2; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y2").WithArguments("y2").WithLocation(7, 16), // (8,9): error CS8598: The suppression operator is not allowed in this context // y2! = null; Diagnostic(ErrorCode.ERR_IllegalSuppression, "y2").WithLocation(8, 9), // (8,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // y2! = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 15) ); } [Fact] [WorkItem(788968, "https://devdiv.visualstudio.com/DevDiv/_workitems/edit/788968")] public void MissingMethodOnTupleLiteral() { var source = @" #nullable enable class C { void M() { (0, (string?)null).Missing(); _ = (0, (string?)null).Missing; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (7,28): error CS1061: '(int, string)' does not contain a definition for 'Missing' and no accessible extension method 'Missing' accepting a first argument of type '(int, string)' could be found (are you missing a using directive or an assembly reference?) // (0, (string?)null).Missing(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Missing").WithArguments("(int, string)", "Missing").WithLocation(7, 28), // (8,32): error CS1061: '(int, string)' does not contain a definition for 'Missing' and no accessible extension method 'Missing' accepting a first argument of type '(int, string)' could be found (are you missing a using directive or an assembly reference?) // _ = (0, (string?)null).Missing; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Missing").WithArguments("(int, string)", "Missing").WithLocation(8, 32) ); } [Fact, WorkItem(41520, "https://github.com/dotnet/roslyn/issues/41520")] public void WarnInsideTupleLiteral() { var source = @" class C { (int, int) M(string? s) { return (s.Length, 1); } } "; var compilation = CreateNullableCompilation(source); compilation.VerifyDiagnostics( // (6,17): warning CS8602: Dereference of a possibly null reference. // return (s.Length, 1); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 17) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void SuppressNullableWarning_RefSpanReturn() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class C { ref Span<byte> M(bool b) { Span<byte> x = stackalloc byte[10]; ref Span<byte> y = ref x!; if (b) return ref y; // 1 else return ref y!; // 2 } ref Span<string> M2(ref Span<string?> x, bool b) { if (b) return ref x; // 3 else return ref x!; } }", options: WithNullable(TestOptions.ReleaseDll, NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (10,24): error CS8157: Cannot return 'y' by reference because it was initialized to a value that cannot be returned by reference // return ref y; // 1 Diagnostic(ErrorCode.ERR_RefReturnNonreturnableLocal, "y").WithArguments("y").WithLocation(10, 24), // (12,24): error CS8157: Cannot return 'y' by reference because it was initialized to a value that cannot be returned by reference // return ref y!; // 2 Diagnostic(ErrorCode.ERR_RefReturnNonreturnableLocal, "y").WithArguments("y").WithLocation(12, 24), // (17,24): warning CS8619: Nullability of reference types in value of type 'Span<string?>' doesn't match target type 'Span<string>'. // return ref x; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("System.Span<string?>", "System.Span<string>").WithLocation(17, 24) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void SuppressNullableWarning_RefReassignment() { var comp = CreateCompilation(@" class C { void M() { ref string x = ref NullableRef(); // 1 ref string x2 = ref x; // 2 ref string x3 = ref x!; ref string y = ref NullableRef()!; ref string y2 = ref y; ref string y3 = ref y!; } ref string? NullableRef() => throw null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,28): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // ref string x = ref NullableRef(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "NullableRef()").WithArguments("string?", "string").WithLocation(6, 28), // (7,29): warning CS8601: Possible null reference assignment. // ref string x2 = ref x; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(7, 29) ); } [Fact] public void SuppressNullableWarning_This() { var comp = CreateCompilation(@" class C { void M() { this!.M(); } }", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void SuppressNullableWarning_UnaryOperator() { var comp = CreateCompilation(@" class C { void M(C? y) { y++; y!++; y--; } public static C operator++(C x) => throw null!; public static C operator--(C? x) => throw null!; }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8604: Possible null reference argument for parameter 'x' in 'C C.operator ++(C x)'. // y++; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "C C.operator ++(C x)").WithLocation(6, 9) ); } [Fact, WorkItem(30151, "https://github.com/dotnet/roslyn/issues/30151")] public void SuppressNullableWarning_WholeArrayInitializer() { var comp = CreateCompilationWithMscorlibAndSpan(@" class C { unsafe void M() { string[] s = new[] { null, string.Empty }; // expecting a warning string[] s2 = (new[] { null, string.Empty })!; int* s3 = (stackalloc[] { 1 })!; System.Span<string> s4 = (stackalloc[] { null, string.Empty })!; } }", options: TestOptions.UnsafeDebugDll); // Missing warning // Need to confirm whether this suppression should be allowed or be effective // If so, we need to verify the semantic model // Tracked by https://github.com/dotnet/roslyn/issues/30151 comp.VerifyDiagnostics( // (8,20): error CS8346: Conversion of a stackalloc expression of type 'int' to type 'int*' is not possible. // int* s3 = (stackalloc[] { 1 })!; Diagnostic(ErrorCode.ERR_StackAllocConversionNotPossible, "stackalloc[] { 1 }").WithArguments("int", "int*").WithLocation(8, 20), // (9,35): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('string') // System.Span<string> s4 = (stackalloc[] { null, string.Empty })!; Diagnostic(ErrorCode.ERR_ManagedAddr, "stackalloc[] { null, string.Empty }").WithArguments("string").WithLocation(9, 35)); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_NullCoalescingAssignment() { var comp = CreateCompilation(@" class C { void M(int? i, int i2, dynamic d) { i! ??= i2; // 1 i ??= i2!; i! ??= d; // 2 i ??= d!; } void M(string? s, string s2, dynamic d) { s! ??= s2; // 3 s ??= s2!; s! ??= d; // 4 s ??= d!; } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): error CS8598: The suppression operator is not allowed in this context // i! ??= i2; // 1 Diagnostic(ErrorCode.ERR_IllegalSuppression, "i").WithLocation(6, 9), // (8,9): error CS8598: The suppression operator is not allowed in this context // i! ??= d; // 2 Diagnostic(ErrorCode.ERR_IllegalSuppression, "i").WithLocation(8, 9), // (13,9): error CS8598: The suppression operator is not allowed in this context // s! ??= s2; // 3 Diagnostic(ErrorCode.ERR_IllegalSuppression, "s").WithLocation(13, 9), // (15,9): error CS8598: The suppression operator is not allowed in this context // s! ??= d; // 4 Diagnostic(ErrorCode.ERR_IllegalSuppression, "s").WithLocation(15, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_ExpressionTree() { var comp = CreateCompilation(@" using System; using System.Linq.Expressions; class C { void M() { string x = null; Expression<Func<string>> e = () => x!; Expression<Func<string>> e2 = (() => x)!; Expression<Func<Func<string>>> e3 = () => M2!; } string M2() => throw null!; }"); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_QueryReceiver() { string source = @" using System; namespace NS { } static class C { static void Main() { _ = from x in null! select x; _ = from x in default! select x; _ = from x in (y => y)! select x; _ = from x in NS! select x; _ = from x in Main! select x; } static object Select(this object x, Func<int, int> y) { return null; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,29): error CS0186: Use of null is not valid in this context // _ = from x in null! select x; Diagnostic(ErrorCode.ERR_NullNotValid, "select x").WithLocation(8, 29), // (9,23): error CS8716: There is no target type for the default literal. // _ = from x in default! select x; Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(9, 23), // (10,33): error CS1936: Could not find an implementation of the query pattern for source type 'anonymous method'. 'Select' not found. // _ = from x in (y => y)! select x; Diagnostic(ErrorCode.ERR_QueryNoProvider, "select x").WithArguments("anonymous method", "Select").WithLocation(10, 33), // (11,23): error CS8598: The suppression operator is not allowed in this context // _ = from x in NS! select x; Diagnostic(ErrorCode.ERR_IllegalSuppression, "NS").WithLocation(11, 23), // (11,23): error CS0119: 'NS' is a namespace, which is not valid in the given context // _ = from x in NS! select x; Diagnostic(ErrorCode.ERR_BadSKunknown, "NS").WithArguments("NS", "namespace").WithLocation(11, 23), // (12,23): error CS0119: 'C.Main()' is a method, which is not valid in the given context // _ = from x in Main! select x; Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("C.Main()", "method").WithLocation(12, 23) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Query() { string source = @" using System.Linq; class C { static void M(System.Collections.Generic.IEnumerable<int> c) { var q = (from x in c select x)!; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_EventInCompoundAssignment() { var comp = CreateCompilation(@" class C { public event System.Action E; void M() { E! += () => {}; E(); } }"); comp.VerifyDiagnostics( // (7,9): error CS8598: The suppression operator is not allowed in this context // E! += () => {}; Diagnostic(ErrorCode.ERR_IllegalSuppression, "E").WithLocation(7, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void OperationsInNonDeclaringType() { var text = @" class C { public event System.Action E; } class D { void Method(ref System.Action a, C c) { c.E! = a; //CS0070 c.E! += a; a = c.E!; //CS0070 Method(ref c.E!, c); //CS0070 c.E!.Invoke(); //CS0070 bool b1 = c.E! is System.Action; //CS0070 c.E!++; //CS0070 c.E! |= true; //CS0070 } } "; CreateCompilation(text).VerifyDiagnostics( // (11,11): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // c.E! = a; //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(11, 11), // (12,9): error CS8598: The suppression operator is not allowed in this context // c.E! += a; Diagnostic(ErrorCode.ERR_IllegalSuppression, "c.E").WithLocation(12, 9), // (13,15): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // a = c.E!; //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(13, 15), // (14,22): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // Method(ref c.E!, c); //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(14, 22), // (15,11): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // c.E!.Invoke(); //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(15, 11), // (16,21): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // bool b1 = c.E! is System.Action; //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(16, 21), // (17,11): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // c.E!++; //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(17, 11), // (18,9): error CS8598: The suppression operator is not allowed in this context // c.E! |= true; //CS0070 Diagnostic(ErrorCode.ERR_IllegalSuppression, "c.E").WithLocation(18, 9), // (18,11): error CS0070: The event 'C.E' can only appear on the left hand side of += or -= (except when used from within the type 'C') // c.E! |= true; //CS0070 Diagnostic(ErrorCode.ERR_BadEventUsage, "E").WithArguments("C.E", "C").WithLocation(18, 11) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Fixed() { var text = @" public class MyClass { int field = 0; unsafe public void Main() { int i = 45; fixed (int *j = &(i!)) { } fixed (int *k = &(this!.field)) { } int[] a = new int[] {1,2,3}; fixed (int *b = a!) { fixed (int *c = b!) { } } } } "; CreateCompilation(text, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (8,25): error CS0213: You cannot use the fixed statement to take the address of an already fixed expression // fixed (int *j = &(i!)) { } Diagnostic(ErrorCode.ERR_FixedNotNeeded, "&(i!)").WithLocation(8, 25), // (8,27): error CS8598: The suppression operator is not allowed in this context // fixed (int *j = &(i!)) { } Diagnostic(ErrorCode.ERR_IllegalSuppression, "i").WithLocation(8, 27), // (14,29): error CS8385: The given expression cannot be used in a fixed statement // fixed (int *c = b!) { } Diagnostic(ErrorCode.ERR_ExprCannotBeFixed, "b").WithLocation(14, 29) ); } [Fact, WorkItem(31748, "https://github.com/dotnet/roslyn/issues/31748")] public void NullableRangeIndexer() { var text = @" #nullable enable class Program { void M(int[] x, string m) { var y = x[1..3]; var z = m[1..3]; } }" + TestSources.GetSubArray; CreateCompilationWithIndexAndRange(text).VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MemberAccess() { var comp = CreateCompilation(@" namespace NS { public static class C { public static void M() { _ = null!.field; // 1 _ = default!.field; // 2 _ = NS!.C.field; // 3 _ = NS.C!.field; // 4 _ = nameof(C!.M); // 5 _ = nameof(C.M!); // 6 _ = nameof(missing!); // 7 } } public class Base { public virtual void M() { } } public class D : Base { public override void M() { _ = this!.ToString(); // 8 _ = base!.ToString(); // 9 } } }"); // Like cast, suppressions are allowed on `this`, but not on `base` comp.VerifyDiagnostics( // (8,17): error CS0023: Operator '.' cannot be applied to operand of type '<null>' // _ = null!.field; // 1 Diagnostic(ErrorCode.ERR_BadUnaryOp, "null!.field").WithArguments(".", "<null>").WithLocation(8, 17), // (9,17): error CS8716: There is no target type for the default literal. // _ = default!.field; // 2 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(9, 17), // (10,17): error CS8598: The suppression operator is not allowed in this context // _ = NS!.C.field; // 3 Diagnostic(ErrorCode.ERR_IllegalSuppression, "NS").WithLocation(10, 17), // (10,23): error CS0117: 'C' does not contain a definition for 'field' // _ = NS!.C.field; // 3 Diagnostic(ErrorCode.ERR_NoSuchMember, "field").WithArguments("NS.C", "field").WithLocation(10, 23), // (11,17): error CS8598: The suppression operator is not allowed in this context // _ = NS.C!.field; // 4 Diagnostic(ErrorCode.ERR_IllegalSuppression, "NS.C").WithLocation(11, 17), // (11,23): error CS0117: 'C' does not contain a definition for 'field' // _ = NS.C!.field; // 4 Diagnostic(ErrorCode.ERR_NoSuchMember, "field").WithArguments("NS.C", "field").WithLocation(11, 23), // (12,24): error CS8598: The suppression operator is not allowed in this context // _ = nameof(C!.M); // 5 Diagnostic(ErrorCode.ERR_IllegalSuppression, "C").WithLocation(12, 24), // (12,24): error CS8082: Sub-expression cannot be used in an argument to nameof. // _ = nameof(C!.M); // 5 Diagnostic(ErrorCode.ERR_SubexpressionNotInNameof, "C!").WithLocation(12, 24), // (13,24): error CS8081: Expression does not have a name. // _ = nameof(C.M!); // 6 Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "C.M!").WithLocation(13, 24), // (14,24): error CS0103: The name 'missing' does not exist in the current context // _ = nameof(missing!); // 7 Diagnostic(ErrorCode.ERR_NameNotInContext, "missing").WithArguments("missing").WithLocation(14, 24), // (23,17): error CS0175: Use of keyword 'base' is not valid in this context // _ = base!.ToString(); // 9 Diagnostic(ErrorCode.ERR_BaseIllegal, "base").WithLocation(23, 17) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SymbolInfoForMethodGroup03() { var source = @" public class A { public static void M(A a) { _ = nameof(a.Extension!); } } public static class X1 { public static string Extension(this A a) { return null; } }"; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); compilation.VerifyDiagnostics( // (6,20): error CS8081: Expression does not have a name. // _ = nameof(a.Extension!); Diagnostic(ErrorCode.ERR_ExpressionHasNoName, "a.Extension!").WithLocation(6, 20) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_StringInterpolation() { var source = @" public class C { public static void Main() { M(""world"", null); } public static void M(string x, string? y) { System.IFormattable z = $""hello ""!; System.IFormattable z2 = $""{x} {y} {y!}""!; System.Console.Write(z); System.Console.Write(z2); } }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello world"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First(); Assert.Equal(@"$""hello ""!", suppression.ToString()); VerifyTypeInfo(model, suppression, "System.String", "System.IFormattable"); var interpolated = suppression.Operand; Assert.Equal(@"$""hello """, interpolated.ToString()); VerifyTypeInfo(model, interpolated, "System.String", "System.IFormattable"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_StringInterpolation_ExplicitCast() { var source = @" public class C { public static void Main() { M(""world"", null); } public static void M(string x, string? y) { var z = (System.IFormattable)($""hello ""!); var z2 = (System.IFormattable)($""{x} {y} {y!}""!); System.Console.Write(z); System.Console.Write(z2); } }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "hello world"); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First(); Assert.Equal(@"$""hello ""!", suppression.ToString()); VerifyTypeInfo(model, suppression, "System.String", "System.String"); var interpolated = suppression.Operand; Assert.Equal(@"$""hello """, interpolated.ToString()); VerifyTypeInfo(model, interpolated, "System.String", "System.String"); } private static void VerifyTypeInfo(SemanticModel model, ExpressionSyntax expression, string expectedType, string expectedConvertedType) { var type = model.GetTypeInfoAndVerifyIOperation(expression); if (expectedType is null) { Assert.Null(type.Type); } else { var actualType = type.Type.ToTestDisplayString(); Assert.True(expectedType == actualType, $"Unexpected TypeInfo.Type '{actualType}'"); } if (expectedConvertedType is null) { Assert.Null(type.ConvertedType); } else { var actualConvertedType = type.ConvertedType.ToTestDisplayString(); Assert.True(expectedConvertedType == actualConvertedType, $"Unexpected TypeInfo.ConvertedType '{actualConvertedType}'"); } } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Default() { var source = @"class C { static void M() { string s = default!; s.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().Single(); VerifyTypeInfo(model, suppression, "System.String", "System.String"); var literal = suppression.Operand; VerifyTypeInfo(model, literal, "System.String", "System.String"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Constant() { var source = @"class C { static void M() { const int i = 3!; _ = i; const string s = null!; _ = s; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppressions = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().ToArray(); Assert.Equal(3, model.GetConstantValue(suppressions[0]).Value); Assert.Null(model.GetConstantValue(suppressions[1]).Value); } [Fact] public void SuppressNullableWarning_GetTypeInfo() { var source = @"class C<T> { void M(string s, string? s2, C<string> c, C<string?> c2) { _ = s!; _ = s2!; _ = c!; _ = c2!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppressions = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().ToArray(); var s = model.GetTypeInfoAndVerifyIOperation(suppressions[0]); Assert.Equal("System.String", s.Type.ToTestDisplayString()); Assert.Equal("System.String", s.ConvertedType.ToTestDisplayString()); Assert.Equal("System.String s", model.GetSymbolInfo(suppressions[0]).Symbol.ToTestDisplayString()); var s2 = model.GetTypeInfoAndVerifyIOperation(suppressions[1]); Assert.Equal("System.String", s2.Type.ToTestDisplayString()); Assert.Equal("System.String", s2.ConvertedType.ToTestDisplayString()); Assert.Equal("System.String? s2", model.GetSymbolInfo(suppressions[1]).Symbol.ToTestDisplayString()); var c = model.GetTypeInfoAndVerifyIOperation(suppressions[2]); Assert.Equal("C<System.String>", c.Type.ToTestDisplayString()); Assert.Equal("C<System.String>", c.ConvertedType.ToTestDisplayString()); Assert.Equal("C<System.String> c", model.GetSymbolInfo(suppressions[2]).Symbol.ToTestDisplayString()); var c2 = model.GetTypeInfoAndVerifyIOperation(suppressions[3]); Assert.Equal("C<System.String?>", c2.Type.ToTestDisplayString()); Assert.Equal("C<System.String?>", c2.ConvertedType.ToTestDisplayString()); Assert.Equal("C<System.String?> c2", model.GetSymbolInfo(suppressions[3]).Symbol.ToTestDisplayString()); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MethodGroupInNameof() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void M<T>() { _ = nameof(C.M<T>!); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,24): error CS0119: 'T' is a type, which is not valid in the given context // _ = nameof(C.M<T>!); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(6, 24), // (6,27): error CS1525: Invalid expression term ')' // _ = nameof(C.M<T>!); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(6, 27) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MethodGroup() { var source = @"class C { delegate string Copier(string s); static void Main() { Copier c = M2; Copier c2 = M2!; } static string? M2(string? s) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (6,20): warning CS8621: Nullability of reference types in return type of 'string? C.M2(string? s)' doesn't match the target delegate 'C.Copier'. // Copier c = M2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M2").WithArguments("string? C.M2(string? s)", "C.Copier").WithLocation(6, 20) ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First(); Assert.Equal("M2!", suppression.ToString()); VerifyTypeInfo(model, suppression, null, "C.Copier"); var methodGroup = suppression.Operand; VerifyTypeInfo(model, methodGroup, null, "C.Copier"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void InvalidUseOfMethodGroup() { var source = @"class A { internal object E() { return null; } private object F() { return null; } static void M(A a) { object o; a.E! += a.E!; // 1 if (a.E! != null) // 2 { M(a.E!); // 3 a.E!.ToString(); // 4 a.P!.ToString(); // 5 o = !(a.E!); // 6 o = a.E! ?? a.F!; // 7 } a.F! += a.F!; // 8 if (a.F! != null) // 9 { M(a.F!); // 10 a.F!.ToString(); // 11 o = !(a.F!); // 12 o = (o != null) ? a.E! : a.F!; // 13 } } }"; CreateCompilation(source, parseOptions: TestOptions.Regular9).VerifyDiagnostics( // (8,9): error CS1656: Cannot assign to 'E' because it is a 'method group' // a.E! += a.E!; // 1 Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "a.E").WithArguments("E", "method group").WithLocation(8, 9), // (9,13): error CS0019: Operator '!=' cannot be applied to operands of type 'method group' and '<null>' // if (a.E! != null) // 2 Diagnostic(ErrorCode.ERR_BadBinaryOps, "a.E! != null").WithArguments("!=", "method group", "<null>").WithLocation(9, 13), // (11,15): error CS1503: Argument 1: cannot convert from 'method group' to 'A' // M(a.E!); // 3 Diagnostic(ErrorCode.ERR_BadArgType, "a.E").WithArguments("1", "method group", "A").WithLocation(11, 15), // (12,15): error CS0119: 'A.E()' is a method, which is not valid in the given context // a.E!.ToString(); // 4 Diagnostic(ErrorCode.ERR_BadSKunknown, "E").WithArguments("A.E()", "method").WithLocation(12, 15), // (13,15): error CS1061: 'A' does not contain a definition for 'P' and no accessible extension method 'P' accepting a first argument of type 'A' could be found (are you missing a using directive or an assembly reference?) // a.P!.ToString(); // 5 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "P").WithArguments("A", "P").WithLocation(13, 15), // (14,17): error CS0023: Operator '!' cannot be applied to operand of type 'method group' // o = !(a.E!); // 6 Diagnostic(ErrorCode.ERR_BadUnaryOp, "!(a.E!)").WithArguments("!", "method group").WithLocation(14, 17), // (15,17): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // o = a.E! ?? a.F!; // 7 Diagnostic(ErrorCode.ERR_BadBinaryOps, "a.E! ?? a.F!").WithArguments("??", "method group", "method group").WithLocation(15, 17), // (17,9): error CS1656: Cannot assign to 'F' because it is a 'method group' // a.F! += a.F!; // 8 Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "a.F").WithArguments("F", "method group").WithLocation(17, 9), // (18,13): error CS0019: Operator '!=' cannot be applied to operands of type 'method group' and '<null>' // if (a.F! != null) // 9 Diagnostic(ErrorCode.ERR_BadBinaryOps, "a.F! != null").WithArguments("!=", "method group", "<null>").WithLocation(18, 13), // (20,15): error CS1503: Argument 1: cannot convert from 'method group' to 'A' // M(a.F!); // 10 Diagnostic(ErrorCode.ERR_BadArgType, "a.F").WithArguments("1", "method group", "A").WithLocation(20, 15), // (21,15): error CS0119: 'A.F()' is a method, which is not valid in the given context // a.F!.ToString(); // 11 Diagnostic(ErrorCode.ERR_BadSKunknown, "F").WithArguments("A.F()", "method").WithLocation(21, 15), // (22,17): error CS0023: Operator '!' cannot be applied to operand of type 'method group' // o = !(a.F!); // 12 Diagnostic(ErrorCode.ERR_BadUnaryOp, "!(a.F!)").WithArguments("!", "method group").WithLocation(22, 17), // (23,33): error CS0428: Cannot convert method group 'E' to non-delegate type 'object'. Did you intend to invoke the method? // o = (o != null) ? a.E! : a.F!; // 13 Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "E").WithArguments("E", "object").WithLocation(23, 33), // (23,40): error CS0428: Cannot convert method group 'F' to non-delegate type 'object'. Did you intend to invoke the method? // o = (o != null) ? a.E! : a.F!; // 13 Diagnostic(ErrorCode.ERR_MethGrpToNonDel, "F").WithArguments("F", "object").WithLocation(23, 40) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_AccessPropertyWithoutArguments() { string source1 = @" Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface IB Property Value(Optional index As Object = Nothing) As Object End Interface "; var reference = BasicCompilationUtils.CompileToMetadata(source1); string source2 = @" class CIB : IB { public dynamic get_Value(object index = null) { return ""Test""; } public void set_Value(object index = null, object Value = null) { } } class Test { static void Main() { IB x = new CIB(); System.Console.WriteLine(x.Value!.Length); } } "; var compilation2 = CreateCompilation(source2, new[] { reference.WithEmbedInteropTypes(true), CSharpRef }, options: TestOptions.ReleaseExe); CompileAndVerify(compilation2, expectedOutput: @"4"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_CollectionInitializerProperty() { var source = @" public class C { public string P { get; set; } = null!; void M() { _ = new C() { P! = null }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,21): error CS1922: Cannot initialize type 'C' with a collection initializer because it does not implement 'System.Collections.IEnumerable' // _ = new C() { P! = null }; Diagnostic(ErrorCode.ERR_CollectionInitRequiresIEnumerable, "{ P! = null }").WithArguments("C").WithLocation(7, 21), // (7,23): error CS0747: Invalid initializer member declarator // _ = new C() { P! = null }; Diagnostic(ErrorCode.ERR_InvalidInitializerElementInitializer, "P! = null").WithLocation(7, 23), // (7,23): error CS8598: The suppression operator is not allowed in this context // _ = new C() { P! = null }; Diagnostic(ErrorCode.ERR_IllegalSuppression, "P").WithLocation(7, 23), // (7,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // _ = new C() { P! = null }; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 28) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_InInvocation() { var source = @" public class C { public System.Action? field = null; void M() { this.M!(); nameof!(M); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): error CS8598: The suppression operator is not allowed in this context // this.M!(); Diagnostic(ErrorCode.ERR_IllegalSuppression, "this.M").WithLocation(7, 9), // (8,9): error CS0103: The name 'nameof' does not exist in the current context // nameof!(M); Diagnostic(ErrorCode.ERR_NameNotInContext, "nameof").WithArguments("nameof").WithLocation(8, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_InInvocation2() { var source = @" public class C { public System.Action? field = null; void M() { this!.field!(); } }"; var comp = CreateCompilationWithCSharp(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); CompileAndVerify(comp); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_InInvocationAndDynamic() { var source = @" public class C { void M() { dynamic? d = new object(); d.M!(); // 1 int z = d.y.z; d = null; d!.M(); d = null; int y = d.y; // 2 d = null; d.M!(); // 3 d += null; d += null!; } }"; // What warnings should we produce on dynamic? // Should `!` be allowed on members/invocations on dynamic? // See https://github.com/dotnet/roslyn/issues/32364 var comp = CreateCompilationWithCSharp(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): error CS8598: The suppression operator is not allowed in this context // d.M!(); // 1 Diagnostic(ErrorCode.ERR_IllegalSuppression, "d.M").WithLocation(7, 9), // (14,17): warning CS8602: Dereference of a possibly null reference. // int y = d.y; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d").WithLocation(14, 17), // (17,9): error CS8598: The suppression operator is not allowed in this context // d.M!(); // 3 Diagnostic(ErrorCode.ERR_IllegalSuppression, "d.M").WithLocation(17, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // d.M!(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d").WithLocation(17, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Stackalloc() { var comp = CreateCompilationWithMscorlibAndSpan(@" class Test { void M() { System.Span<int> a3 = stackalloc[] { 1, 2, 3 }!; var x3 = true ? stackalloc[] { 1, 2, 3 }! : a3; } }", TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MethodGroup2() { var source = @"class C { delegate string? Copier(string? s); static void Main() { Copier c = M2; Copier c2 = M2!; } static string M2(string s) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (6,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'string C.M2(string s)' doesn't match the target delegate 'C.Copier'. // Copier c = M2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M2").WithArguments("s", "string C.M2(string s)", "C.Copier").WithLocation(6, 20) ); CompileAndVerify(comp); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Lambda() { var source = @"class C { delegate string Copier(string s); static void Main() { Copier c = (string? x) => { return null; }!; Copier c2 = (string? x) => { return null; }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (6,44): warning CS8603: Possible null reference return. // Copier c = (string? x) => { return null; }!; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 44), // (7,21): warning CS8622: Nullability of reference types in type of parameter 'x' of 'lambda expression' doesn't match the target delegate 'C.Copier'. // Copier c2 = (string? x) => { return null; }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(string? x) => { return null; }").WithArguments("x", "lambda expression", "C.Copier").WithLocation(7, 21), // (7,45): warning CS8603: Possible null reference return. // Copier c2 = (string? x) => { return null; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(7, 45) ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().Single(); Assert.Equal("(string? x) => { return null; }!", suppression.ToString()); VerifyTypeInfo(model, suppression, null, "C.Copier"); var lambda = suppression.Operand; Assert.Equal("(string? x) => { return null; }", lambda.ToString()); VerifyTypeInfo(model, lambda, null, "C.Copier"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Lambda_ExplicitCast() { var source = @"class C { delegate string Copier(string s); static void M() { var c = (Copier)((string? x) => { return null; }!); var c2 = (Copier)((string? x) => { return null; }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,50): warning CS8603: Possible null reference return. // var c = (Copier)((string? x) => { return null; }!); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 50), // (7,18): warning CS8622: Nullability of reference types in type of parameter 'x' of 'lambda expression' doesn't match the target delegate 'C.Copier'. // var c2 = (Copier)((string? x) => { return null; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(Copier)((string? x) => { return null; })").WithArguments("x", "lambda expression", "C.Copier").WithLocation(7, 18), // (7,51): warning CS8603: Possible null reference return. // var c2 = (Copier)((string? x) => { return null; }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(7, 51) ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().Single(); Assert.Equal("(string? x) => { return null; }!", suppression.ToString()); VerifyTypeInfo(model, suppression, null, "C.Copier"); var lambda = suppression.Operand; Assert.Equal("(string? x) => { return null; }", lambda.ToString()); VerifyTypeInfo(model, lambda, null, "C.Copier"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Lambda2() { var source = @"class C { delegate string? Copier(string? s); static void Main() { Copier c = (string x) => { return string.Empty; }!; Copier c2 = (string x) => { return string.Empty; }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (7,21): warning CS8622: Nullability of reference types in type of parameter 'x' of 'lambda expression' doesn't match the target delegate 'C.Copier'. // Copier c2 = (string x) => { return string.Empty; }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(string x) => { return string.Empty; }").WithArguments("x", "lambda expression", "C.Copier").WithLocation(7, 21) ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().Single(); Assert.Equal("(string x) => { return string.Empty; }!", suppression.ToString()); VerifyTypeInfo(model, suppression, null, "C.Copier"); var lambda = suppression.Operand; Assert.Equal("(string x) => { return string.Empty; }", lambda.ToString()); VerifyTypeInfo(model, lambda, null, "C.Copier"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Lambda2_ExplicitCast() { var source = @"class C { delegate string? Copier(string? s); static void Main() { var c = (Copier)((string x) => { return string.Empty; }!); var c2 = (Copier)((string x) => { return string.Empty; }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (7,18): warning CS8622: Nullability of reference types in type of parameter 'x' of 'lambda expression' doesn't match the target delegate 'C.Copier'. // var c2 = (Copier)((string x) => { return string.Empty; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(Copier)((string x) => { return string.Empty; })").WithArguments("x", "lambda expression", "C.Copier").WithLocation(7, 18) ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().Single(); Assert.Equal("(string x) => { return string.Empty; }!", suppression.ToString()); VerifyTypeInfo(model, suppression, null, "C.Copier"); var lambda = suppression.Operand; Assert.Equal("(string x) => { return string.Empty; }", lambda.ToString()); VerifyTypeInfo(model, lambda, null, "C.Copier"); } [Fact, WorkItem(32697, "https://github.com/dotnet/roslyn/issues/32697")] public void SuppressNullableWarning_LambdaInOverloadResolution() { var source = @"class C { static void Main(string? x) { var s = M(() => { return x; }); s /*T:string?*/ .ToString(); // 1 var s2 = M(() => { return x; }!); // suppressed s2 /*T:string?*/ .ToString(); // 2 var s3 = M(M2); s3 /*T:string?*/ .ToString(); // 3 var s4 = M(M2!); // suppressed s4 /*T:string?*/ .ToString(); // 4 } static T M<T>(System.Func<T> x) => throw null!; static string? M2() => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s /*T:string?*/ .ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // s2 /*T:string?*/ .ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(9, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // s3 /*T:string?*/ .ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(12, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // s4 /*T:string?*/ .ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(15, 9)); CompileAndVerify(comp); } [Fact, WorkItem(32698, "https://github.com/dotnet/roslyn/issues/32698")] public void SuppressNullableWarning_DelegateCreation() { var source = @"class C { static void Main() { _ = new System.Func<string, string>((string? x) => { return null; }!); _ = new System.Func<string?, string?>((string x) => { return string.Empty; }!); _ = new System.Func<string, string>(M1!); _ = new System.Func<string?, string?>(M2!); // without suppression _ = new System.Func<string, string>((string? x) => { return null; }); // 1 _ = new System.Func<string?, string?>((string x) => { return string.Empty; }); // 2 _ = new System.Func<string, string>(M1); // 3 _ = new System.Func<string?, string?>(M2); // 4 } static string? M1(string? x) => throw null!; static string M2(string x) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (5,69): warning CS8603: Possible null reference return. // _ = new System.Func<string, string>((string? x) => { return null; }!); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(5, 69), // (11,57): warning CS8622: Nullability of reference types in type of parameter 'x' of 'lambda expression' doesn't match the target delegate 'Func<string, string>'. // _ = new System.Func<string, string>((string? x) => { return null; }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("x", "lambda expression", "System.Func<string, string>").WithLocation(11, 57), // (11,69): warning CS8603: Possible null reference return. // _ = new System.Func<string, string>((string? x) => { return null; }); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(11, 69), // (12,58): warning CS8622: Nullability of reference types in type of parameter 'x' of 'lambda expression' doesn't match the target delegate 'Func<string?, string?>'. // _ = new System.Func<string?, string?>((string x) => { return string.Empty; }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("x", "lambda expression", "System.Func<string?, string?>").WithLocation(12, 58), // (13,45): warning CS8621: Nullability of reference types in return type of 'string? C.M1(string? x)' doesn't match the target delegate 'Func<string, string>'. // _ = new System.Func<string, string>(M1); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M1").WithArguments("string? C.M1(string? x)", "System.Func<string, string>").WithLocation(13, 45), // (14,47): warning CS8622: Nullability of reference types in type of parameter 'x' of 'string C.M2(string x)' doesn't match the target delegate 'Func<string?, string?>'. // _ = new System.Func<string?, string?>(M2); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M2").WithArguments("x", "string C.M2(string x)", "System.Func<string?, string?>").WithLocation(14, 47)); CompileAndVerify(comp); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var suppression = tree.GetRoot().DescendantNodes().OfType<PostfixUnaryExpressionSyntax>().First(); Assert.Equal(@"(string? x) => { return null; }!", suppression.ToString()); VerifyTypeInfo(model, suppression, null, "System.Func<System.String, System.String>"); VerifyTypeInfo(model, suppression.Operand, null, "System.Func<System.String, System.String>"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MethodGroupInOverloadResolution_NoReceiver() { var source = @"using System; using System.Collections.Generic; class A { class B { void F() { IEnumerable<string?> c = null!; c.S(G); c.S(G!); IEnumerable<string> c2 = null!; c2.S(G); c2.S(G2); } } object G(string s) => throw null!; object G2(string? s) => throw null!; } static class E { internal static IEnumerable<U> S<T, U>(this IEnumerable<T> c, Func<T, U> f) { throw new NotImplementedException(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,17): error CS0120: An object reference is required for the non-static field, method, or property 'A.G(string)' // c.S(G); Diagnostic(ErrorCode.ERR_ObjectRequired, "G").WithArguments("A.G(string)").WithLocation(10, 17), // (11,17): error CS0120: An object reference is required for the non-static field, method, or property 'A.G(string)' // c.S(G!); Diagnostic(ErrorCode.ERR_ObjectRequired, "G").WithArguments("A.G(string)").WithLocation(11, 17), // (14,18): error CS0120: An object reference is required for the non-static field, method, or property 'A.G(string)' // c2.S(G); Diagnostic(ErrorCode.ERR_ObjectRequired, "G").WithArguments("A.G(string)").WithLocation(14, 18), // (15,18): error CS0120: An object reference is required for the non-static field, method, or property 'A.G2(string?)' // c2.S(G2); Diagnostic(ErrorCode.ERR_ObjectRequired, "G2").WithArguments("A.G2(string?)").WithLocation(15, 18) ); } [Fact] [WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] [WorkItem(33635, "https://github.com/dotnet/roslyn/issues/33635")] public void SuppressNullableWarning_MethodGroupInOverloadResolution() { var source = @"using System; using System.Collections.Generic; class A { void M() { IEnumerable<string?> c = null!; c.S(G)/*T:System.Collections.Generic.IEnumerable<object!>!*/; // 1 c.S(G!)/*T:System.Collections.Generic.IEnumerable<object!>!*/; IEnumerable<string> c2 = null!; c2.S(G)/*T:System.Collections.Generic.IEnumerable<object!>!*/; c2.S(G2)/*T:System.Collections.Generic.IEnumerable<object!>!*/; } static object G(string s) => throw null!; static object G2(string? s) => throw null!; } static class E { internal static IEnumerable<U> S<T, U>(this IEnumerable<T> c, Func<T, U> f) { throw new NotImplementedException(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8622: Nullability of reference types in type of parameter 's' of 'object A.G(string s)' doesn't match the target delegate 'Func<string?, object>'. // c.S(G)/*T:IEnumerable<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "G").WithArguments("s", "object A.G(string s)", "System.Func<string?, object>").WithLocation(8, 13) ); comp.VerifyTypes(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void ErrorInLambdaArgumentList() { var source = @" class Program { public Program(string x) : this((() => x)!) { } }"; CreateCompilation(source).VerifyDiagnostics( // (4,38): error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type // public Program(string x) : this((() => x)!) { } Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "() => x").WithArguments("lambda expression", "string").WithLocation(4, 38) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void CS1113ERR_ValueTypeExtDelegate01() { var source = @"class C { public void M() { } } interface I { void M(); } enum E { } struct S { public void M() { } } static class SC { static void Test(C c, I i, E e, S s, double d) { System.Action cm = c.M!; // OK -- instance method System.Action cm1 = c.M1!; // OK -- extension method on ref type System.Action im = i.M!; // OK -- instance method System.Action im2 = i.M2!; // OK -- extension method on ref type System.Action em3 = e.M3!; // BAD -- extension method on value type System.Action sm = s.M!; // OK -- instance method System.Action sm4 = s.M4!; // BAD -- extension method on value type System.Action dm5 = d.M5!; // BAD -- extension method on value type } static void M1(this C c) { } static void M2(this I i) { } static void M3(this E e) { } static void M4(this S s) { } static void M5(this double d) { } }"; CreateCompilationWithMscorlib40(source, references: new[] { TestMetadata.Net40.SystemCore }).VerifyDiagnostics( // (24,29): error CS1113: Extension methods 'SC.M3(E)' defined on value type 'E' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "e.M3").WithArguments("SC.M3(E)", "E").WithLocation(24, 29), // (26,29): error CS1113: Extension methods 'SC.M4(S)' defined on value type 'S' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "s.M4").WithArguments("SC.M4(S)", "S").WithLocation(26, 29), // (27,29): error CS1113: Extension methods 'SC.M5(double)' defined on value type 'double' cannot be used to create delegates Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "d.M5").WithArguments("SC.M5(double)", "double").WithLocation(27, 29)); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void BugCodePlex_30_01() { string source1 = @" using System; class C { static void Main() { Goo(() => { return () => 0; ; }!); Goo(() => { return () => 0; }!); } static void Goo(Func<Func<short>> x) { Console.Write(1); } static void Goo(Func<Func<int>> x) { Console.Write(2); } } "; CompileAndVerify(source1, expectedOutput: @"22"); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_AddressOfWithLambdaOrMethodGroup() { var source = @" unsafe class C { static void M() { _ = &(() => {}!); _ = &(M!); } }"; var comp = CreateCompilation(source, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (6,15): error CS0211: Cannot take the address of the given expression // _ = &(() => {}!); Diagnostic(ErrorCode.ERR_InvalidAddrOp, "() => {}").WithLocation(6, 15), // (7,9): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = &(M!); Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(7, 9), // (7,15): error CS8598: The suppression operator is not allowed in this context // _ = &(M!); Diagnostic(ErrorCode.ERR_IllegalSuppression, "M").WithLocation(7, 15) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void SuppressNullableWarning_AddressOf() { var source = @" unsafe class C<T> { static void M(C<string> x) { C<string?>* y1 = &x; C<string?>* y2 = &x!; } }"; var comp = CreateCompilation(source, options: WithNullable(TestOptions.UnsafeReleaseDll, NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (6,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C<string?>') // C<string?>* y1 = &x; Diagnostic(ErrorCode.ERR_ManagedAddr, "C<string?>*").WithArguments("C<string?>").WithLocation(6, 9), // (6,26): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C<string>') // C<string?>* y1 = &x; Diagnostic(ErrorCode.ERR_ManagedAddr, "&x").WithArguments("C<string>").WithLocation(6, 26), // (6,26): warning CS8619: Nullability of reference types in value of type 'C<string>*' doesn't match target type 'C<string?>*'. // C<string?>* y1 = &x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "&x").WithArguments("C<string>*", "C<string?>*").WithLocation(6, 26), // (7,9): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C<string?>') // C<string?>* y2 = &x!; Diagnostic(ErrorCode.ERR_ManagedAddr, "C<string?>*").WithArguments("C<string?>").WithLocation(7, 9), // (7,26): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C<string>') // C<string?>* y2 = &x!; Diagnostic(ErrorCode.ERR_ManagedAddr, "&x!").WithArguments("C<string>").WithLocation(7, 26), // (7,26): warning CS8619: Nullability of reference types in value of type 'C<string>*' doesn't match target type 'C<string?>*'. // C<string?>* y2 = &x!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "&x!").WithArguments("C<string>*", "C<string?>*").WithLocation(7, 26), // (7,27): error CS8598: The suppression operator is not allowed in this context // C<string?>* y2 = &x!; Diagnostic(ErrorCode.ERR_IllegalSuppression, "x").WithLocation(7, 27) ); } [Fact] public void SuppressNullableWarning_Invocation() { var source = @" class C { void M() { _ = nameof!(M); _ = typeof!(C); this.M!(); dynamic d = null!; d.M2!(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): error CS0103: The name 'nameof' does not exist in the current context // _ = nameof!(M); Diagnostic(ErrorCode.ERR_NameNotInContext, "nameof").WithArguments("nameof").WithLocation(6, 13), // (7,19): error CS1003: Syntax error, '(' expected // _ = typeof!(C); Diagnostic(ErrorCode.ERR_SyntaxError, "!").WithArguments("(", "!").WithLocation(7, 19), // (7,19): error CS1031: Type expected // _ = typeof!(C); Diagnostic(ErrorCode.ERR_TypeExpected, "!").WithLocation(7, 19), // (7,19): error CS1026: ) expected // _ = typeof!(C); Diagnostic(ErrorCode.ERR_CloseParenExpected, "!").WithLocation(7, 19), // (7,21): error CS0119: 'C' is a type, which is not valid in the given context // _ = typeof!(C); Diagnostic(ErrorCode.ERR_BadSKunknown, "C").WithArguments("C", "type").WithLocation(7, 21), // (8,9): error CS8598: The suppression operator is not allowed in this context // this.M!(); Diagnostic(ErrorCode.ERR_IllegalSuppression, "this.M").WithLocation(8, 9), // (10,9): error CS8598: The suppression operator is not allowed in this context // d.M2!(); Diagnostic(ErrorCode.ERR_IllegalSuppression, "d.M2").WithLocation(10, 9) ); } [Fact, WorkItem(31584, "https://github.com/dotnet/roslyn/issues/31584")] public void Verify31584() { var comp = CreateCompilation(@" using System; using System.Linq; class C { void M<T>(Func<T, bool>? predicate) { var items = Enumerable.Empty<T>(); if (predicate != null) items = items.Where(x => predicate(x)); } }", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(32463, "https://github.com/dotnet/roslyn/issues/32463")] public void Verify32463() { var comp = CreateCompilation(@" using System.Linq; class C { public void F(string? param) { if (param != null) _ = new[] { 0 }.Select(_ => param.Length); string? local = """"; if (local != null) _ = new[] { 0 }.Select(_ => local.Length); } }", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(32701, "https://github.com/dotnet/roslyn/issues/32701")] public void Verify32701() { var source = @" class C { static void M<T>(ref T t, dynamic? d) { t = d; // 1 } static void M2<T>(T t, dynamic? d) { t = d; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,13): warning CS8601: Possible null reference assignment. // t = d; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "d").WithLocation(6, 13)); comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8601: Possible null reference assignment. // t = d; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "d").WithLocation(6, 13), // (10,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // t = d; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "d").WithLocation(10, 13)); source = @" class C { static void M<T>(ref T? t, dynamic? d) { t = d; } static void M2<T>(T? t, dynamic? d) { t = d; } }"; comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(26696, "https://github.com/dotnet/roslyn/issues/26696")] public void Verify26696() { var source = @" interface I { object this[int i] { get; } } class C<T> : I { T this[int i] => throw null!; object I.this[int i] => this[i]!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefReturn() { var source = @" struct S<T> { ref S<string?> M(ref S<string> x) { return ref x; // 1 } ref S<string?> M2(ref S<string> x) { return ref x!; } } class C<T> { ref C<string>? M3(ref C<string> x) { return ref x; // 2 } ref C<string> M4(ref C<string>? x) { return ref x; // 3 } ref C<string>? M5(ref C<string> x) { return ref x!; } ref C<string> M6(ref C<string>? x) { return ref x!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,20): warning CS8619: Nullability of reference types in value of type 'S<string>' doesn't match target type 'S<string?>'. // return ref x; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("S<string>", "S<string?>").WithLocation(6, 20), // (17,20): warning CS8619: Nullability of reference types in value of type 'C<string>' doesn't match target type 'C<string>?'. // return ref x; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<string>", "C<string>?").WithLocation(17, 20), // (21,20): warning CS8619: Nullability of reference types in value of type 'C<string>?' doesn't match target type 'C<string>'. // return ref x; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<string>?", "C<string>").WithLocation(21, 20) ); } [Fact, WorkItem(33982, "https://github.com/dotnet/roslyn/issues/33982")] public void RefReturn_Lambda() { var comp = CreateCompilation(@" delegate ref V D<T, U, V>(ref T t, ref U u); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static V F<T, U, V>(D<T, U, V> d) => throw null!; void M(bool b) { F((ref object? x, ref object y) => { if (b) return ref x; return ref y; }); // 1 F((ref object? x, ref object y) => { if (b) return ref y; return ref x; }); // 2 F((ref I<object?> x, ref I<object> y) => { if (b) return ref x; return ref y; }); // 3 F((ref I<object?> x, ref I<object> y) => { if (b) return ref y; return ref x; }); // 4 F((ref IOut<object?> x, ref IOut<object> y) => { if (b) return ref x; return ref y; }); // 5 F((ref IOut<object?> x, ref IOut<object> y) => { if (b) return ref y; return ref x; }); // 6 F((ref IIn<object?> x, ref IIn<object> y) => { if (b) return ref x; return ref y; }); // 7 F((ref IIn<object?> x, ref IIn<object> y) => { if (b) return ref y; return ref x; }); // 8 } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,47): warning CS8619: Nullability of reference types in value of type 'object' doesn't match target type 'object?'. // { if (b) return ref x; return ref y; }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("object", "object?").WithLocation(12, 47), // (14,33): warning CS8619: Nullability of reference types in value of type 'object' doesn't match target type 'object?'. // { if (b) return ref y; return ref x; }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("object", "object?").WithLocation(14, 33), // (17,33): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // { if (b) return ref x; return ref y; }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object?>", "I<object>").WithLocation(17, 33), // (19,47): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // { if (b) return ref y; return ref x; }); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object?>", "I<object>").WithLocation(19, 47), // (22,47): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'IOut<object?>'. // { if (b) return ref x; return ref y; }); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("IOut<object>", "IOut<object?>").WithLocation(22, 47), // (24,33): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'IOut<object?>'. // { if (b) return ref y; return ref x; }); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("IOut<object>", "IOut<object?>").WithLocation(24, 33), // (27,33): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'IIn<object>'. // { if (b) return ref x; return ref y; }); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object?>", "IIn<object>").WithLocation(27, 33), // (29,47): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'IIn<object>'. // { if (b) return ref y; return ref x; }); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object?>", "IIn<object>").WithLocation(29, 47) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefReturn_State() { var source = @" class C { ref C M1(ref C? w) { return ref w; // 1 } ref C? M2(ref C w) { return ref w; // 2 } ref C M3(ref C w) { return ref w; } ref C? M4(ref C? w) { return ref w; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,20): warning CS8619: Nullability of reference types in value of type 'C?' doesn't match target type 'C'. // return ref w; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("C?", "C").WithLocation(6, 20), // (10,20): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'C?'. // return ref w; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("C", "C?").WithLocation(10, 20) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefAssignment() { var source = @" class C { void M1(C? x) { ref C y = ref x; // 1 y.ToString(); // 2 } void M2(C x) { ref C? y = ref x; // 3 y.ToString(); } void M3(C? x, C nonNull) { x = nonNull; ref C y = ref x; // 4 y.ToString(); y = null; // 5 } void M4(C x, C? nullable) { x = nullable; // 6 ref C? y = ref x; // 7 y.ToString(); // 8 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,23): warning CS8619: Nullability of reference types in value of type 'C?' doesn't match target type 'C'. // ref C y = ref x; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C?", "C").WithLocation(6, 23), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9), // (11,24): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'C?'. // ref C? y = ref x; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C", "C?").WithLocation(11, 24), // (17,23): warning CS8619: Nullability of reference types in value of type 'C?' doesn't match target type 'C'. // ref C y = ref x; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C?", "C").WithLocation(17, 23), // (19,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // y = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 13), // (23,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = nullable; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "nullable").WithLocation(23, 13), // (24,24): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'C?'. // ref C? y = ref x; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C", "C?").WithLocation(24, 24), // (25,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(25, 9) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefAssignment_WithSuppression() { var source = @" class C { void M1(C? x) { ref C y = ref x!; y.ToString(); } void M2(C x) { ref C? y = ref x!; y.ToString(); } void M3(C? x, C nonNull) { x = nonNull; ref C y = ref x!; y.ToString(); } void M4(C x, C? nullable) { x = nullable; // 1 ref C? y = ref x!; y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (22,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = nullable; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "nullable").WithLocation(22, 13) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefAssignment_Nested() { var source = @" struct S<T> { void M(ref S<string> x) { S<string?> y = default; ref S<string> y2 = ref y; // 1 y2 = ref y; // 2 y2 = ref y!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,32): warning CS8619: Nullability of reference types in value of type 'S<string?>' doesn't match target type 'S<string>'. // ref S<string> y2 = ref y; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("S<string?>", "S<string>").WithLocation(7, 32), // (8,18): warning CS8619: Nullability of reference types in value of type 'S<string?>' doesn't match target type 'S<string>'. // y2 = ref y; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("S<string?>", "S<string>").WithLocation(8, 18) ); } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefAssignment_Foreach() { verify(variableType: "string?", itemType: "string", // (6,18): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // foreach (ref string? item in collection) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ref string?").WithArguments("string", "string?").WithLocation(6, 18)); verify("string", "string?", // (6,18): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // foreach (ref string item in collection) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ref string").WithArguments("string?", "string").WithLocation(6, 18), // (8,13): warning CS8602: Dereference of a possibly null reference. // item.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(8, 13)); verify("string", "string"); verify("string?", "string?", // (8,13): warning CS8602: Dereference of a possibly null reference. // item.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(8, 13)); verify("C<string?>", "C<string>", // (6,18): warning CS8619: Nullability of reference types in value of type 'C<string>' doesn't match target type 'C<string?>'. // foreach (ref C<string?> item in collection) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ref C<string?>").WithArguments("C<string>", "C<string?>").WithLocation(6, 18)); verify("C<string>", "C<string?>", // (6,18): warning CS8619: Nullability of reference types in value of type 'C<string?>' doesn't match target type 'C<string>'. // foreach (ref C<string> item in collection) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ref C<string>").WithArguments("C<string?>", "C<string>").WithLocation(6, 18)); verify("C<object?>", "C<dynamic>?", // (6,18): warning CS8619: Nullability of reference types in value of type 'C<dynamic>?' doesn't match target type 'C<object?>'. // foreach (ref C<object?> item in collection) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "ref C<object?>").WithArguments("C<dynamic>?", "C<object?>").WithLocation(6, 18), // (8,13): warning CS8602: Dereference of a possibly null reference. // item.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(8, 13)); verify("C<object>", "C<dynamic>"); verify("var", "string"); verify("var", "string?", // (8,13): warning CS8602: Dereference of a possibly null reference. // item.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(8, 13)); verify("T", "T", // (8,13): warning CS8602: Dereference of a possibly null reference. // item.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(8, 13)); void verify(string variableType, string itemType, params DiagnosticDescription[] expected) { var source = @" class C<T> { void M(RefEnumerable collection) { foreach (ref VARTYPE item in collection) { item.ToString(); } } class RefEnumerable { public StructEnum GetEnumerator() => throw null!; public struct StructEnum { public ref ITEMTYPE Current => throw null!; public bool MoveNext() => throw null!; } } }"; var comp = CreateCompilation(source.Replace("VARTYPE", variableType).Replace("ITEMTYPE", itemType), options: WithNullableEnable()); comp.VerifyDiagnostics(expected); } } [Fact, WorkItem(31297, "https://github.com/dotnet/roslyn/issues/31297")] public void RefAssignment_Foreach_Nested() { verify(fieldType: "string?", // (9,13): warning CS8602: Dereference of a possibly null reference. // item.Field.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item.Field").WithLocation(9, 13)); verify(fieldType: "string", // (4,19): warning CS8618: Non-nullable field 'Field' is uninitialized. Consider declaring the field as nullable. // public string Field; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Field").WithArguments("field", "Field").WithLocation(4, 19)); void verify(string fieldType, params DiagnosticDescription[] expected) { var source = @" class C { public FIELDTYPE Field; void M(RefEnumerable collection) { foreach (ref C item in collection) { item.Field.ToString(); } } class RefEnumerable { public StructEnum GetEnumerator() => throw null!; public struct StructEnum { public ref C Current => throw null!; public bool MoveNext() => throw null!; } } }"; var comp = CreateCompilation(source.Replace("FIELDTYPE", fieldType), options: WithNullableEnable()); comp.VerifyDiagnostics(expected); } } [Fact] public void RefAssignment_Inferred() { var source = @" class C { void M1(C x) { ref var y = ref x; y = null; x.ToString(); y.ToString(); // 1 } void M2(C? x) { ref var y = ref x; y = null; x.ToString(); // 2 y.ToString(); // 3 } void M3(C? x) { ref var y = ref x; x.ToString(); // 4 y.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(17, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(23, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(24, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void TestLambdaWithError19() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { Ma(string.Empty, ((x, y) => x.ToString())!); Mb(string.Empty, ((x, y) => x.ToString())!); Mc(string.Empty, ((x, y) => x.ToString())!); } static void Ma<T>(T t, Expression<Action<T, T, int>> action) { } static void Mb<T>(T t, Expression<Action<T, T, int>> action) { } static void Mb<T>(T t, Action<T, T, int> action) { } static void Mc<T>(T t, Expression<Action<T, T, int>> action) { } static void Mc() { } } "; var compilation = CreateCompilationWithMscorlib40AndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfoAndVerifyIOperation(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_DelegateComparison() { var source = @" class C { static void M() { System.Func<int> x = null; _ = x == (() => 1)!; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '==' cannot be applied to operands of type 'Func<int>' and 'lambda expression' // _ = x == (() => 1)!; Diagnostic(ErrorCode.ERR_BadBinaryOps, "x == (() => 1)!").WithArguments("==", "System.Func<int>", "lambda expression").WithLocation(7, 13) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_ArgList() { var source = @" class C { static void M() { _ = __arglist!; M(__arglist(__arglist()!)); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0190: The __arglist construct is valid only within a variable argument method // _ = __arglist!; Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist").WithLocation(6, 13), // (7,21): error CS0226: An __arglist expression may only appear inside of a call or new expression // M(__arglist(__arglist()!)); Diagnostic(ErrorCode.ERR_IllegalArglist, "__arglist()").WithLocation(7, 21) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void BadInvocationInLambda() { var src = @" using System; using System.Linq.Expressions; class C { Expression<Action<dynamic>> e = x => new object[](x); Expression<Action<dynamic>> e2 = x => new object[](x)!; }"; // Suppressed expression cannot be used as a statement var comp = CreateCompilationWithMscorlib40AndSystemCore(src); comp.VerifyDiagnostics( // (7,52): error CS1586: Array creation must have array size or array initializer // Expression<Action<dynamic>> e = x => new object[](x); Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(7, 52), // (8,43): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // Expression<Action<dynamic>> e2 = x => new object[](x)!; Diagnostic(ErrorCode.ERR_IllegalStatement, "new object[](x)!").WithLocation(8, 43), // (8,53): error CS1586: Array creation must have array size or array initializer // Expression<Action<dynamic>> e2 = x => new object[](x)!; Diagnostic(ErrorCode.ERR_MissingArraySize, "[]").WithLocation(8, 53) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_AsStatement() { var src = @" class C { void M2(string x) { x!; M2(x)!; } string M(string x) { x!; M(x)!; throw null!; } }"; // Suppressed expression cannot be used as a statement var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,9): error CS8598: The suppression operator is not allowed in this context // x!; Diagnostic(ErrorCode.ERR_IllegalSuppression, "x").WithLocation(6, 9), // (6,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x!; Diagnostic(ErrorCode.ERR_IllegalStatement, "x!").WithLocation(6, 9), // (7,9): error CS8598: The suppression operator is not allowed in this context // M2(x)!; Diagnostic(ErrorCode.ERR_IllegalSuppression, "M2(x)").WithLocation(7, 9), // (7,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // M2(x)!; Diagnostic(ErrorCode.ERR_IllegalStatement, "M2(x)!").WithLocation(7, 9), // (11,9): error CS8598: The suppression operator is not allowed in this context // x!; Diagnostic(ErrorCode.ERR_IllegalSuppression, "x").WithLocation(11, 9), // (11,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // x!; Diagnostic(ErrorCode.ERR_IllegalStatement, "x!").WithLocation(11, 9), // (12,9): error CS8598: The suppression operator is not allowed in this context // M(x)!; Diagnostic(ErrorCode.ERR_IllegalSuppression, "M(x)").WithLocation(12, 9), // (12,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // M(x)!; Diagnostic(ErrorCode.ERR_IllegalStatement, "M(x)!").WithLocation(12, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_VoidInvocation() { var src = @" class C { void M() { _ = M()!; } }"; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,9): error CS8209: A value of type 'void' may not be assigned. // _ = M()!; Diagnostic(ErrorCode.ERR_VoidAssignment, "_").WithLocation(6, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void CS0023ERR_BadUnaryOp_lambdaExpression() { var text = @" class X { static void Main() { System.Func<int, int> f = (arg => { arg = 2; return arg; } !).ToString(); var x = (delegate { } !).ToString(); } } "; CreateCompilation(text).VerifyDiagnostics( // (6,35): error CS0023: Operator '.' cannot be applied to operand of type 'lambda expression' // System.Func<int, int> f = (arg => { arg = 2; return arg; } !).ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(arg => { arg = 2; return arg; } !).ToString").WithArguments(".", "lambda expression").WithLocation(6, 35), // (8,17): error CS0023: Operator '.' cannot be applied to operand of type 'anonymous method' // var x = (delegate { } !).ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(delegate { } !).ToString").WithArguments(".", "anonymous method").WithLocation(8, 17) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void ConditionalMemberAccess001() { var text = @" class Program { static void Main(string[] args) { var x4 = (()=> { return 1; } !) ?.ToString(); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (6,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression' // var x4 = (()=> { return 1; } !) ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(()=> { return 1; } !) ?.ToString()").WithArguments("?", "lambda expression").WithLocation(6, 18), // (6,18): error CS0023: Operator '?' cannot be applied to operand of type 'lambda expression' // var x4 = (()=> { return 1; } !) ?.ToString(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "(()=> { return 1; } !) ?.ToString()").WithArguments("?", "lambda expression").WithLocation(6, 18) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void DynamicCollectionInitializer_Errors() { string source = @" using System; unsafe class C { public dynamic X; public static int* ptr = null; static void M() { var c = new C { X = { M!, ptr!, () => {}!, default(TypedReference)!, M()!, __arglist } }; } } "; // Should `!` be disallowed on arguments to dynamic? // See https://github.com/dotnet/roslyn/issues/32364 CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics( // (15,17): error CS1976: Cannot use a method group as an argument to a dynamically dispatched operation. Did you intend to invoke the method? // M!, Diagnostic(ErrorCode.ERR_BadDynamicMethodArgMemgrp, "M").WithLocation(15, 17), // (16,17): error CS1978: Cannot use an expression of type 'int*' as an argument to a dynamically dispatched operation. // ptr!, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "ptr").WithArguments("int*").WithLocation(16, 17), // (17,17): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // () => {}!, Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, "() => {}").WithLocation(17, 17), // (18,17): error CS1978: Cannot use an expression of type 'TypedReference' as an argument to a dynamically dispatched operation. // default(TypedReference)!, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "default(TypedReference)").WithArguments("System.TypedReference").WithLocation(18, 17), // (19,17): error CS1978: Cannot use an expression of type 'void' as an argument to a dynamically dispatched operation. // M()!, Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "M()").WithArguments("void").WithLocation(19, 17), // (20,17): error CS0190: The __arglist construct is valid only within a variable argument method // __arglist Diagnostic(ErrorCode.ERR_ArgsInvalid, "__arglist").WithLocation(20, 17), // (20,17): error CS1978: Cannot use an expression of type 'RuntimeArgumentHandle' as an argument to a dynamically dispatched operation. // __arglist Diagnostic(ErrorCode.ERR_BadDynamicMethodArg, "__arglist").WithArguments("System.RuntimeArgumentHandle").WithLocation(20, 17) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void TestNullCoalesceWithMethodGroup() { var source = @" using System; class Program { static void Main() { Action a = Main! ?? Main; Action a2 = Main ?? Main!; } } "; CreateCompilation(source).VerifyDiagnostics( // (8,20): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // Action a = Main! ?? Main; Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main! ?? Main").WithArguments("??", "method group", "method group").WithLocation(8, 20), // (9,21): error CS0019: Operator '??' cannot be applied to operands of type 'method group' and 'method group' // Action a2 = Main ?? Main!; Diagnostic(ErrorCode.ERR_BadBinaryOps, "Main ?? Main!").WithArguments("??", "method group", "method group").WithLocation(9, 21) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_IsAsOperatorWithBadSuppressedExpression() { var source = @" class C { void M() { _ = (() => {}!) is null; // 1 _ = (M!) is null; // 2 _ = (null, null)! is object; // 3 _ = null! is object; // 4 _ = default! is object; // 5 _ = (() => {}!) as object; // 6 _ = (M!) as object; // 7 _ = (null, null)! as object; // 8 _ = null! as object; // ok _ = default! as string; // 10 } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // _ = (() => {}!) is null; // 1 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(() => {}!) is null").WithLocation(6, 13), // (7,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // _ = (M!) is null; // 2 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(M!) is null").WithLocation(7, 13), // (8,13): error CS0023: Operator 'is' cannot be applied to operand of type '(<null>, <null>)' // _ = (null, null)! is object; // 3 Diagnostic(ErrorCode.ERR_BadUnaryOp, "(null, null)! is object").WithArguments("is", "(<null>, <null>)").WithLocation(8, 13), // (9,13): warning CS0184: The given expression is never of the provided ('object') type // _ = null! is object; // 4 Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null! is object").WithArguments("object").WithLocation(9, 13), // (10,13): error CS8716: There is no target type for the default literal. // _ = default! is object; // 5 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(10, 13), // (12,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // _ = (() => {}!) as object; // 6 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(() => {}!) as object").WithLocation(12, 13), // (13,13): error CS0837: The first operand of an 'is' or 'as' operator may not be a lambda expression, anonymous method, or method group. // _ = (M!) as object; // 7 Diagnostic(ErrorCode.ERR_LambdaInIsAs, "(M!) as object").WithLocation(13, 13), // (14,13): error CS8307: The first operand of an 'as' operator may not be a tuple literal without a natural type. // _ = (null, null)! as object; // 8 Diagnostic(ErrorCode.ERR_TypelessTupleInAs, "(null, null)! as object").WithLocation(14, 13), // (16,13): error CS8716: There is no target type for the default literal. // _ = default! as string; // 10 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(16, 13) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void ImplicitDelegateCreationWithIncompleteLambda() { var source = @" using System; class C { public void F() { Action<int> x = (i => i.)! } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,33): error CS1001: Identifier expected // Action<int> x = (i => i.)! Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(7, 33), // (7,35): error CS1002: ; expected // Action<int> x = (i => i.)! Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 35), // (7,31): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // Action<int> x = (i => i.)! Diagnostic(ErrorCode.ERR_IllegalStatement, "i.").WithLocation(7, 31) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var lambda = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SimpleLambdaExpression)).Single(); var param = lambda.ChildNodes().Where(n => n.IsKind(SyntaxKind.Parameter)).Single(); var symbol1 = model.GetDeclaredSymbol(param); Assert.Equal("System.Int32 i", symbol1.ToTestDisplayString()); var id = lambda.DescendantNodes().First(n => n.IsKind(SyntaxKind.IdentifierName)); var symbol2 = model.GetSymbolInfo(id).Symbol; Assert.Equal("System.Int32 i", symbol2.ToTestDisplayString()); Assert.Same(symbol1, symbol2); } [Fact, WorkItem(32179, "https://github.com/dotnet/roslyn/issues/32179")] public void SuppressNullableWarning_DefaultStruct() { var source = @"public struct S { public string field; } public class C { public S field; void M() { S s = default; // assigns null to S.field _ = s; _ = new C(); // assigns null to C.S.field } }"; // We should probably warn for such scenarios (either in the definition of S, or in the usage of S) // Tracked by https://github.com/dotnet/roslyn/issues/32179 var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_ThrowNull() { var source = @"class C { void M() { throw null!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_ThrowExpression() { var source = @"class C { void M() { (throw null!)!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS0201: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement // (throw null!)!; Diagnostic(ErrorCode.ERR_IllegalStatement, "(throw null!)!").WithLocation(5, 9), // (5,10): error CS8115: A throw expression is not allowed in this context. // (throw null!)!; Diagnostic(ErrorCode.ERR_ThrowMisplaced, "throw").WithLocation(5, 10) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_IsNull() { var source = @"class C { bool M(object o) { return o is null!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,21): error CS8598: The suppression operator is not allowed in this context // return o is null!; Diagnostic(ErrorCode.ERR_IllegalSuppression, "null!").WithLocation(5, 21)); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MiscNull() { var source = @" using System.Linq.Expressions; class C { void M<T>(object o, int? i) { _ = null is object; // 1 _ = null! is object; // 2 int i2 = null!; // 3 var i3 = (int)null!; // 4 T t = null!; // 5 var t2 = (T)null!; // 6 _ = null == null!; _ = (null!, null) == (null, null!); (null)++; // 9 (null!)++; // 10 _ = !null; // 11 _ = !(null!); // 12 Expression<System.Func<object>> testExpr = () => null! ?? ""hello""; // 13 _ = o == null; _ = o == null!; // 14 _ = null ?? o; _ = null! ?? o; _ = i == null; _ = i == null!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS0184: The given expression is never of the provided ('object') type // _ = null is object; // 1 Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null is object").WithArguments("object").WithLocation(7, 13), // (8,13): warning CS0184: The given expression is never of the provided ('object') type // _ = null! is object; // 2 Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null! is object").WithArguments("object").WithLocation(8, 13), // (10,18): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // int i2 = null!; // 3 Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(10, 18), // (11,18): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // var i3 = (int)null!; // 4 Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(int)null!").WithArguments("int").WithLocation(11, 18), // (12,15): error CS0403: Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead. // T t = null!; // 5 Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T").WithLocation(12, 15), // (13,18): error CS0037: Cannot convert null to 'T' because it is a non-nullable value type // var t2 = (T)null!; // 6 Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(T)null!").WithArguments("T").WithLocation(13, 18), // (16,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer // (null)++; // 9 Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "null").WithLocation(16, 10), // (17,10): error CS1059: The operand of an increment or decrement operator must be a variable, property or indexer // (null!)++; // 10 Diagnostic(ErrorCode.ERR_IncrementLvalueExpected, "null").WithLocation(17, 10), // (18,13): error CS8310: Operator '!' cannot be applied to operand '<null>' // _ = !null; // 11 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "!null").WithArguments("!", "<null>").WithLocation(18, 13), // (19,13): error CS8310: Operator '!' cannot be applied to operand '<null>' // _ = !(null!); // 12 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "!(null!)").WithArguments("!", "<null>").WithLocation(19, 13), // (20,58): error CS0845: An expression tree lambda may not contain a coalescing operator with a null or default literal left-hand side // Expression<System.Func<object>> testExpr = () => null! ?? "hello"; // 13 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsBadCoalesce, "null").WithLocation(20, 58) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_MiscDefault() { var source = @"class C { void M(dynamic d, int? i) { d.M(null!, default!, null, default); // 1 _ = default == default!; // 2 _ = default! == default!; // 3 _ = 1 + default!; // 4 _ = default ?? d; // 5 _ = default! ?? d; // 6 _ = i ?? default; _ = i ?? default!; } void M2(object o) { _ = o == default; _ = o == default!; } }"; // Should `!` be disallowed on arguments to dynamic (line // 1) ? // See https://github.com/dotnet/roslyn/issues/32364 var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): error CS8716: There is no target type for the default literal. // d.M(null!, default!, null, default); // 1 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(5, 20), // (5,36): error CS8716: There is no target type for the default literal. // d.M(null!, default!, null, default); // 1 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(5, 36), // (6,13): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // _ = default == default!; // 2 Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "default == default!").WithArguments("==", "default", "default").WithLocation(6, 13), // (7,13): error CS8315: Operator '==' is ambiguous on operands 'default' and 'default' // _ = default! == default!; // 3 Diagnostic(ErrorCode.ERR_AmbigBinaryOpsOnDefault, "default! == default!").WithArguments("==", "default", "default").WithLocation(7, 13), // (8,13): error CS8310: Operator '+' cannot be applied to operand 'default' // _ = 1 + default!; // 4 Diagnostic(ErrorCode.ERR_BadOpOnNullOrDefaultOrNew, "1 + default!").WithArguments("+", "default").WithLocation(8, 13), // (9,13): error CS8716: There is no target type for the default literal. // _ = default ?? d; // 5 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(9, 13), // (10,13): error CS8716: There is no target type for the default literal. // _ = default! ?? d; // 6 Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(10, 13) ); } [Fact, WorkItem(32879, "https://github.com/dotnet/roslyn/issues/32879")] public void ThrowExpressionInNullCoalescingOperator() { var source = @" class C { string Field = string.Empty; void M(C? c) { _ = c ?? throw new System.ArgumentNullException(nameof(c)); c.ToString(); } void M2(C? c) { _ = c?.Field ?? throw new System.ArgumentNullException(nameof(c)); c.ToString(); c.Field.ToString(); } void M3(C? c) { _ = c ?? throw new System.ArgumentNullException(c.ToString()); // 1 } void M4(string? s) { _ = s ?? s.ToString(); // 2 s.ToString(); } void M5(string s) { _ = s ?? s.ToString(); // 3 } #nullable disable void M6(string s) { #nullable enable _ = s ?? s.ToString(); // 4 } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (18,57): warning CS8602: Dereference of a possibly null reference. // _ = c ?? throw new System.ArgumentNullException(c.ToString()); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(18, 57), // (22,18): warning CS8602: Dereference of a possibly null reference. // _ = s ?? s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(22, 18), // (27,18): warning CS8602: Dereference of a possibly null reference. // _ = s ?? s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(27, 18), // (33,18): warning CS8602: Dereference of a possibly null reference. // _ = s ?? s.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(33, 18)); } [Fact, WorkItem(32877, "https://github.com/dotnet/roslyn/issues/32877")] public void CheckReceiverOfThrow() { var source = @" class C { void M(System.Exception? e, C? c) { _ = c ?? throw e; // 1 _ = c ?? throw null; // 2 throw null; // 3 } void M2(System.Exception? e, bool b) { if (b) throw e; // 4 else throw e!; } void M3() { throw this; // 5 } public static implicit operator System.Exception?(C c) => throw null!; void M4<TException>(TException? e) where TException : System.Exception { throw e; // 6 } void M5<TException>(TException e) where TException : System.Exception? { throw e; // 7 } void M6<TException>(TException? e) where TException : Interface { throw e; // 8 } void M7<TException>(TException e) where TException : Interface? { throw e; // 9 } void M8<TException>(TException e) where TException : Interface { throw e; // 10 } void M9<T>(T e) { throw e; // 11 } void M10() { try { } catch { throw; } } interface Interface { } }"; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (6,24): warning CS8597: Thrown value may be null. // _ = c ?? throw e; // 1 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "e").WithLocation(6, 24), // (7,24): warning CS8597: Thrown value may be null. // _ = c ?? throw null; // 2 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "null").WithLocation(7, 24), // (8,15): warning CS8597: Thrown value may be null. // throw null; // 3 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "null").WithLocation(8, 15), // (13,19): warning CS8597: Thrown value may be null. // throw e; // 4 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "e").WithLocation(13, 19), // (19,15): warning CS8597: Thrown value may be null. // throw this; // 5 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "this").WithLocation(19, 15), // (24,15): warning CS8597: Thrown value may be null. // throw e; // 6 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "e").WithLocation(24, 15), // (28,15): warning CS8597: Thrown value may be null. // throw e; // 7 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "e").WithLocation(28, 15), // (30,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void M6<TException>(TException? e) where TException : Interface Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "TException?").WithArguments("9.0").WithLocation(30, 25), // (32,15): error CS0029: Cannot implicitly convert type 'TException' to 'System.Exception' // throw e; // 8 Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("TException", "System.Exception").WithLocation(32, 15), // (36,15): error CS0029: Cannot implicitly convert type 'TException' to 'System.Exception' // throw e; // 9 Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("TException", "System.Exception").WithLocation(36, 15), // (40,15): error CS0029: Cannot implicitly convert type 'TException' to 'System.Exception' // throw e; // 10 Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("TException", "System.Exception").WithLocation(40, 15), // (44,15): error CS0029: Cannot implicitly convert type 'T' to 'System.Exception' // throw e; // 11 Diagnostic(ErrorCode.ERR_NoImplicitConv, "e").WithArguments("T", "System.Exception").WithLocation(44, 15) ); } [Fact, WorkItem(32877, "https://github.com/dotnet/roslyn/issues/32877")] public void CatchClause() { var source = @" class C { void M() { try { } catch (System.Exception? e) { throw e; } } void M2() { try { } catch (System.Exception? e) { throw; } } void M3() { try { } catch (System.Exception? e) { e = null; throw e; // 1 } } void M4() { try { } catch (System.Exception e) { e = null; // 2 throw e; // 3 } } void M5() { try { } catch (System.Exception e) { e = null; // 4 throw; // this rethrows the original exception, not an NRE } } }"; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,34): warning CS0168: The variable 'e' is declared but never used // catch (System.Exception? e) { throw; } Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(12, 34), // (20,19): error CS8597: Thrown value may be null. // throw e; // 1 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "e").WithLocation(20, 19), // (28,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // e = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(28, 17), // (29,19): error CS8597: Thrown value may be null. // throw e; // 3 Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "e").WithLocation(29, 19), // (35,33): warning CS0168: The variable 'e' is declared but never used // catch (System.Exception e) Diagnostic(ErrorCode.WRN_UnreferencedVar, "e").WithArguments("e").WithLocation(35, 33), // (37,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // e = null; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(37, 17) ); } [Fact] public void Test0() { var source = @" class C { static void Main() { string? x = null; } } "; var c = CreateCompilation(source, parseOptions: TestOptions.Regular7); c.VerifyDiagnostics( // (6,15): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // string? x = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(6, 15), // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used // string? x = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 17) ); var c2 = CreateCompilation(source, parseOptions: TestOptions.Regular8); c2.VerifyDiagnostics( // (6,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? x = null; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 15), // (6,17): warning CS0219: The variable 'x' is assigned but its value is never used // string? x = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 17) ); } [Fact] public void SpeakableInference_MethodTypeInference() { var source = @"class Program { void M<T>(T t) { if (t == null) throw null!; t.ToString(); var t2 = Copy(t); t2.ToString(); // warn } static T Copy<T>(T t) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(8, 9) ); } [Fact] public void SpeakableInference_MethodTypeInference_WithTuple() { var source = @"class Program { void M<T>(T t) { if (t == null) throw null!; var tuple = (t, t); tuple.Item1.ToString(); tuple.Item2.ToString(); var tuple2 = Copy(tuple); tuple2.Item1.ToString(); // warn tuple2.Item2.ToString(); // warn var tuple3 = Copy<T, T>(tuple); tuple3.Item1.ToString(); // warn tuple3.Item2.ToString(); // warn } static (T, U) Copy<T, U>((T, U) t) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // tuple2.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "tuple2.Item1").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // tuple2.Item2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "tuple2.Item2").WithLocation(12, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // tuple3.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "tuple3.Item1").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // tuple3.Item2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "tuple3.Item2").WithLocation(16, 9) ); } [Fact] public void SpeakableInference_MethodTypeInference_WithNull() { var source = @"class Program { void M<T>(T t) where T : class? { if (t == null) throw null!; t.ToString(); var t2 = Copy(t, null); t2.ToString(); // warn } static T Copy<T, U>(T t, U t) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,18): error CS0411: The type arguments for method 'Program.Copy<T, U>(T, U)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // var t2 = Copy(t, null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Copy").WithArguments("Program.Copy<T, U>(T, U)").WithLocation(7, 18), // (10,32): error CS0100: The parameter name 't' is a duplicate // static T Copy<T, U>(T t, U t) => throw null!; Diagnostic(ErrorCode.ERR_DuplicateParamName, "t").WithArguments("t").WithLocation(10, 32) ); } [Fact] public void SpeakableInference_MethodTypeInference_NullAssigned() { var source = @"class Program { void M<T>(T t) where T : class { t = null; var t2 = Copy(t); t2 /*T:T?*/ .ToString(); // warn } static T Copy<T>(T t) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (5,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // t = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // t2 /*T:T?*/ .ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(7, 9) ); } [Fact] public void SpeakableInference_MethodTypeInference_NullableValueType() { var source = @"class Program { void M(int? t) { if (t == null) throw null!; t.Value.ToString(); var t2 = Copy(t); t2.Value.ToString(); // warn } void M2<T>(T? t) where T : struct { if (t == null) throw null!; t.Value.ToString(); var t2 = Copy(t); t2.Value.ToString(); // warn } static T Copy<T>(T t) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8629: Nullable value type may be null. // t2.Value.ToString(); // warn Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(8, 9), // (15,9): warning CS8629: Nullable value type may be null. // t2.Value.ToString(); // warn Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(15, 9) ); } [Fact] public void SpeakableInference_ArrayTypeInference() { var source = @"class Program { void M<T>(T t) { if (t == null) throw null!; t.ToString(); var t2 = new[] { t }; t2[0].ToString(); // warn } }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t2[0].ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2[0]").WithLocation(8, 9) ); } [Fact] public void SpeakableInference_ArrayTypeInference_WithTuple() { var source = @"class Program { void M<T>(T t) { if (t == null) throw null!; var a = new[] { (t, t) }; a[0].Item1.ToString(); a[0].Item2.ToString(); var b = new (T, T)[] { (t, t) }; b[0].Item1.ToString(); b[0].Item2.ToString(); } }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // a[0].Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a[0].Item1").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // a[0].Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a[0].Item2").WithLocation(8, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // b[0].Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0].Item1").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // b[0].Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0].Item2").WithLocation(12, 9) ); } [Fact] public void SpeakableInference_ArrayTypeInference_WithNull() { var source = @"class Program { void M<T>(T t) where T : class? { if (t == null) throw null!; t.ToString(); var t2 = new[] { t, null }; t2[0].ToString(); // 1 } }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t2[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2[0]").WithLocation(8, 9) ); } [Fact, WorkItem(30941, "https://github.com/dotnet/roslyn/issues/30941")] public void Verify30941() { var source = @" class Outer : Base { void M1(Base? x1) { Outer y = x1; } } class Base { } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,19): error CS0266: Cannot implicitly convert type 'Base' to 'Outer'. An explicit conversion exists (are you missing a cast?) // Outer y = x1; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x1").WithArguments("Base", "Outer").WithLocation(6, 19), // (6,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer y = x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(6, 19) ); } [Fact, WorkItem(31958, "https://github.com/dotnet/roslyn/issues/31958")] public void Verify31958() { var source = @" class C { string? M1(string s) { var d = (D)M1; // 1 d(null).ToString(); return null; } string M2(string s) { var d = (D)M2; // 2 d(null).ToString(); return s; } delegate string D(string? s); } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,17): warning CS8621: Nullability of reference types in return type of 'string? C.M1(string s)' doesn't match the target delegate 'C.D' (possibly because of nullability attributes). // var d = (D)M1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "(D)M1").WithArguments("string? C.M1(string s)", "C.D").WithLocation(6, 17), // (14,17): warning CS8622: Nullability of reference types in type of parameter 's' of 'string C.M2(string s)' doesn't match the target delegate 'C.D' (possibly because of nullability attributes). // var d = (D)M2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(D)M2").WithArguments("s", "string C.M2(string s)", "C.D").WithLocation(14, 17) ); } [Fact, WorkItem(28377, "https://github.com/dotnet/roslyn/issues/28377")] public void Verify28377() { var source = @" class C { void M() { object x; x! = null; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS0219: The variable 'x' is assigned but its value is never used // object x; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(6, 16), // (7,9): error CS8598: The suppression operator is not allowed in this context // x! = null; Diagnostic(ErrorCode.ERR_IllegalSuppression, "x").WithLocation(7, 9), // (7,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x! = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 14) ); } [Fact, WorkItem(31295, "https://github.com/dotnet/roslyn/issues/31295")] public void Verify31295() { var source = @" class C { void M() { for (var x = 0; ; x!++) { } } }"; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact, WorkItem(26654, "https://github.com/dotnet/roslyn/issues/26654")] public void Verify26654() { var source = @" public class C { public void M(out string? x) => throw null!; public void M2() { string y; M(out y!); } }"; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact, WorkItem(33782, "https://github.com/dotnet/roslyn/issues/33782")] public void AnnotationInXmlDoc_TwoDeclarations() { var source = @" /// <summary /> public class C { void M<T>(T? t) where T : struct { } void M<T>(T t) where T : class { } /// <summary> /// See <see cref=""M{T}(T?)""/> /// </summary> void M2() { } /// <summary> /// See <see cref=""M{T}(T)""/> /// </summary> void M3() { } }"; // In cref, `T?` always binds to `Nullable<T>` var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, options: WithNullableEnable()); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var firstCref = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<NameMemberCrefSyntax>().First(); var firstCrefSymbol = model.GetSymbolInfo(firstCref).Symbol; Assert.Equal("void C.M<T>(T? t)", firstCrefSymbol.ToTestDisplayString()); var lastCref = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<NameMemberCrefSyntax>().Last(); var lastCrefSymbol = model.GetSymbolInfo(lastCref).Symbol; Assert.Equal("void C.M<T>(T t)", lastCrefSymbol.ToTestDisplayString()); } [Fact, WorkItem(33782, "https://github.com/dotnet/roslyn/issues/33782")] public void AnnotationInXmlDoc_DeclaredAsNonNullableReferenceType() { var source = @" /// <summary /> public class C { void M<T>(T t) where T : class { } /// <summary> /// <see cref=""M{T}(T?)""/> warn 1 /// </summary> void M2() { } /// <summary> /// <see cref=""M{T}(T)""/> /// </summary> void M3() { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,20): warning CS1574: XML comment has cref attribute 'M{T}(T?)' that could not be resolved // /// <see cref="M{T}(T?)"/> warn 1 Diagnostic(ErrorCode.WRN_BadXMLRef, "M{T}(T?)").WithArguments("M{T}(T?)").WithLocation(8, 20)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var lastCref = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<NameMemberCrefSyntax>().Last(); var lastCrefSymbol = model.GetSymbolInfo(lastCref).Symbol; Assert.Equal("void C.M<T>(T t)", lastCrefSymbol.ToTestDisplayString()); } [Fact, WorkItem(33782, "https://github.com/dotnet/roslyn/issues/33782")] public void AnnotationInXmlDoc_DeclaredAsNullableReferenceType() { var source = @" /// <summary /> public class C { void M<T>(T? t) where T : class { } /// <summary> /// <see cref=""M{T}(T?)""/> warn 1 /// </summary> void M2() { } /// <summary> /// <see cref=""M{T}(T)""/> /// </summary> void M3() { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithDocumentationComments, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,20): warning CS1574: XML comment has cref attribute 'M{T}(T?)' that could not be resolved // /// <see cref="M{T}(T?)"/> warn 1 Diagnostic(ErrorCode.WRN_BadXMLRef, "M{T}(T?)").WithArguments("M{T}(T?)").WithLocation(8, 20)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var lastCref = tree.GetRoot().DescendantNodes(descendIntoTrivia: true).OfType<NameMemberCrefSyntax>().Last(); var lastCrefSymbol = model.GetSymbolInfo(lastCref).Symbol; Assert.Equal("void C.M<T>(T? t)", lastCrefSymbol.ToTestDisplayString()); } [Fact, WorkItem(30955, "https://github.com/dotnet/roslyn/issues/30955")] public void ArrayTypeInference_Verify30955() { var source = @" class Outer { void M0(object x0, object? y0) { var a = new[] { x0, 1 }; a[0] = y0; var b = new[] { x0, x0 }; b[0] = y0; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8601: Possible null reference assignment. // a[0] = y0; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y0").WithLocation(7, 16), // (9,16): warning CS8601: Possible null reference assignment. // b[0] = y0; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y0").WithLocation(9, 16) ); } [Fact, WorkItem(30598, "https://github.com/dotnet/roslyn/issues/30598")] public void Verify30598() { var source = @" class Program { static object F(object[]? x) { return x[ // warning: possibly null x.Length - 1]; // no warning } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8602: Dereference of a possibly null reference. // return x[ // warning: possibly null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 16) ); } [Fact, WorkItem(30925, "https://github.com/dotnet/roslyn/issues/30925")] public void Verify30925() { var source = @" class Outer { void M1<T>(T x1, object? y1) where T : class? { x1 = (T)y1; } void M2<T>(T x2, object? y2) where T : class? { x2 = y2; } void M3(string x3, object? y3) { x3 = (string)y3; } void M4(string x4, object? y4) { x4 = y4; } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (11,14): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // x2 = y2; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y2").WithArguments("object", "T").WithLocation(11, 14), // (16,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = (string)y3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)y3").WithLocation(16, 14), // (21,14): error CS0266: Cannot implicitly convert type 'object' to 'string'. An explicit conversion exists (are you missing a cast?) // x4 = y4; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y4").WithArguments("object", "string").WithLocation(21, 14), // (21,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = y4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y4").WithLocation(21, 14)); } [Fact] public void SpeakableInference_ArrayTypeInference_NullableValueType() { var source = @"class Program { void M(int? t) { if (t == null) throw null!; t.Value.ToString(); var t2 = new[] { t }; t2[0].Value.ToString(); // warn } void M2<T>(T? t) where T : struct { if (t == null) throw null!; t.Value.ToString(); var t2 = new[] { t }; t2[0].Value.ToString(); // warn } }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8629: Nullable value type may be null. // t2[0].Value.ToString(); // warn Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2[0]").WithLocation(8, 9), // (15,9): warning CS8629: Nullable value type may be null. // t2[0].Value.ToString(); // warn Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2[0]").WithLocation(15, 9) ); } [Fact] public void SpeakableInference_ArrayTypeInference_ConversionWithNullableOutput_WithNestedMismatch() { var source = @"class A<T> { public static implicit operator C<T>?(A<T> a) => throw null!; } class B<T> : A<T> { } class C<T> { void M(B<string> x, C<string?> y) { var a = new[] { x, y }; a[0].ToString(); var b = new[] { y, x }; b[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,25): warning CS8619: Nullability of reference types in value of type 'C<string>' doesn't match target type 'C<string?>'. // var a = new[] { x, y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<string>", "C<string?>").WithLocation(12, 25), // (13,9): warning CS8602: Dereference of a possibly null reference. // a[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a[0]").WithLocation(13, 9), // (15,28): warning CS8619: Nullability of reference types in value of type 'C<string>' doesn't match target type 'C<string?>'. // var b = new[] { y, x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<string>", "C<string?>").WithLocation(15, 28), // (16,9): warning CS8602: Dereference of a possibly null reference. // b[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0]").WithLocation(16, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference() { var source = @"class Program { void M<T>(T t) { var x1 = F(() => { if (t == null) throw null!; bool b = true; if (b) return t; return t; }); x1.ToString(); var x2 = F<T>(() => { if (t == null) throw null!; bool b = true; if (b) return t; return t; }); x2.ToString(); } T F<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(12, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(21, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference2() { var source = @"class Program { void M<T>(T t, T t2) { var x1 = F(() => { if (t == null) throw null!; bool b = true; if (b) return t; return t2; }); x1.ToString(); var x2 = F<T>(() => { if (t == null) throw null!; bool b = true; if (b) return t; return t2; }); x2.ToString(); } T F<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(12, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(21, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_WithSingleReturn() { var source = @"class Program { void M<T>() { var x1 = Copy(() => """"); x1.ToString(); } void M2<T>(T t) { if (t == null) throw null!; var x1 = Copy(() => t); x1.ToString(); // 1 } T Copy<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(12, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_WithTuple() { var source = @"class Program { void M<T>(T t) { var x1 = Copy(() => { if (t == null) throw null!; bool b = true; if (b) return (t, t); return (t, t); }); x1.Item1.ToString(); x1.Item2.ToString(); } T Copy<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x1.Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1.Item1").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // x1.Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1.Item2").WithLocation(13, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_ConversionWithNullableOutput() { var source = @"class A { public static implicit operator C?(A a) => new C(); } class B : A { } class C { void M(B x, C y) { var x1 = F(() => { bool b = true; if (b) return x; return y; }); x1.ToString(); var x2 = F(() => { bool b = true; if (b) return y; return x; }); x2.ToString(); } T F<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(18, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(26, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_ConversionWithNullableOutput2() { var source = @"class A<T> { public static implicit operator C<T>?(A<T> a) => throw null!; } class B<T> : A<T> { } class C<T> { void M(B<string?> x, C<string?> y) { var x1 = F(() => { bool b = true; if (b) return x; return y; }); x1.ToString(); var x2 = F(() => { bool b = true; if (b) return y; return x; }); x2.ToString(); } U F<U>(System.Func<U> f) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(18, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(26, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_ConversionWithNullableOutput_WithNestedMismatch() { var source = @"class A<T> { public static implicit operator C<T>?(A<T> a) => throw null!; } class B<T> : A<T> { } class C<T> { void M(B<string> x, C<string?> y) { var x1 = F(() => { bool b = true; if (b) return x; return y; }); x1.ToString(); var x2 = F(() => { bool b = true; if (b) return y; return x; }); x2.ToString(); } U F<U>(System.Func<U> f) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,27): warning CS8619: Nullability of reference types in value of type 'C<string>' doesn't match target type 'C<string?>'. // if (b) return x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<string>", "C<string?>").WithLocation(15, 27), // (18,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(18, 9), // (24,20): warning CS8619: Nullability of reference types in value of type 'C<string>' doesn't match target type 'C<string?>'. // return x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<string>", "C<string?>").WithLocation(24, 20), // (26,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(26, 9) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_ConversionWithNullableInput() { var source = @"class A { public static implicit operator C(A? a) => null; // warn } class B : A { } class C { void M(B? x, C y) { var x1 = F(() => { bool b = true; if (b) return x; return y; }); x1.ToString(); var x2 = F(() => { bool b = true; if (b) return y; return x; }); x2.ToString(); } T F<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,48): warning CS8603: Possible null reference return. // public static implicit operator C(A? a) => null; // warn Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(3, 48) ); } [Fact] public void SpeakableInference_LambdaReturnTypeInference_WithNullabilityMismatch() { var source = @" class C<T> { void M(C<object>? x, C<object?> y) { var x1 = F(() => { bool b = true; if (b) return x; return y; }); _ = x1 /*T:C<object!>?*/; x1.ToString(); var x2 = F(() => { bool b = true; if (b) return y; return x; }); _ = x2 /*T:C<object!>?*/; x2.ToString(); } U F<U>(System.Func<U> f) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (10,20): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // return y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(10, 20), // (13,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(13, 9), // (18,27): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // if (b) return y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(18, 27), // (22,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(22, 9) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] [WorkItem(32006, "https://github.com/dotnet/roslyn/issues/32006")] public void SpeakableInference_LambdaReturnTypeInference_NonNullableTypelessOuptut() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @" class C { void M(C? c) { var x1 = F(() => { bool b = true; if (b) return (c, c); return (null, null); }); x1.ToString(); x1.Item1.ToString(); } T F<T>(System.Func<T> f) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // x1.Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1.Item1").WithLocation(13, 9) ); } [Fact] public void SpeakableInference_VarInference() { var source = @"class Program { void M<T>(T t) { if (t == null) throw null!; var t2 = t; t2.ToString(); } }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); var syntaxTree = comp.SyntaxTrees[0]; var declaration = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(syntaxTree); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("T? t2", local.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); Assert.Equal("T?", local.Type.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void Directive_Qualifiers() { var source = @"#nullable #nullable enable #nullable disable #nullable restore #nullable safeonly #nullable yes "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (1,10): error CS8637: Expected 'enable', 'disable', or 'restore' // #nullable Diagnostic(ErrorCode.ERR_NullableDirectiveQualifierExpected, "").WithLocation(1, 10), // (5,11): error CS8637: Expected 'enable', 'disable', or 'restore' // #nullable safeonly Diagnostic(ErrorCode.ERR_NullableDirectiveQualifierExpected, "safeonly").WithLocation(5, 11), // (6,11): error CS8637: Expected 'enable', 'disable', or 'restore' // #nullable yes Diagnostic(ErrorCode.ERR_NullableDirectiveQualifierExpected, "yes").WithLocation(6, 11) ); comp.VerifyTypes(); } [Fact] public void Directive_NullableDefault() { var source = @"#pragma warning disable 0649, 8618 class A<T, U> { } class B { static A<object, string?> F1; static void G1() { object o1; o1 = F1/*T:A<object, string?>!*/; o1 = F2/*T:A<object, string?>!*/; o1 = F3/*T:A<object!, string?>!*/; } #nullable disable static A<object, string?> F2; static void G2() { object o2; o2 = F1/*T:A<object, string?>!*/; o2 = F2/*T:A<object, string?>!*/; o2 = F3/*T:A<object!, string?>!*/; } #nullable enable static A<object, string?> F3; static void G3() { object o3; o3 = F1/*T:A<object, string?>!*/; o3 = F2/*T:A<object, string?>!*/; o3 = F3/*T:A<object!, string?>!*/; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (5,28): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static A<object, string?> F1; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 28), // (14,28): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static A<object, string?> F2; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 28)); comp.VerifyTypes(); } [Fact] public void Directive_NullableFalse() { var source = @"#pragma warning disable 0649, 8618 class A<T, U> { } class B { static A<object, string?> F1; static void G1() { object o1; o1 = F1/*T:A<object, string?>!*/; o1 = F2/*T:A<object, string?>!*/; o1 = F3/*T:A<object!, string?>!*/; } #nullable disable static A<object, string?> F2; static void G2() { object o2; o2 = F1/*T:A<object, string?>!*/; o2 = F2/*T:A<object, string?>!*/; o2 = F3/*T:A<object!, string?>!*/; } #nullable enable static A<object, string?> F3; static void G3() { object o3; o3 = F1/*T:A<object, string?>!*/; o3 = F2/*T:A<object, string?>!*/; o3 = F3/*T:A<object!, string?>!*/; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Disable)); comp.VerifyDiagnostics( // (5,28): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static A<object, string?> F1; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 28), // (14,28): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static A<object, string?> F2; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 28)); comp.VerifyTypes(); } [Fact] public void Directive_NullableTrue() { var source = @"#pragma warning disable 0649, 8618 class A<T, U> { } class B { static A<object, string?> F1; static void G1() { object o1; o1 = F1/*T:A<object!, string?>!*/; o1 = F2/*T:A<object, string?>!*/; o1 = F3/*T:A<object!, string?>!*/; } #nullable disable static A<object, string?> F2; static void G2() { object o2; o2 = F1/*T:A<object!, string?>!*/; o2 = F2/*T:A<object, string?>!*/; o2 = F3/*T:A<object!, string?>!*/; } #nullable enable static A<object, string?> F3; static void G3() { object o3; o3 = F1/*T:A<object!, string?>!*/; o3 = F2/*T:A<object, string?>!*/; o3 = F3/*T:A<object!, string?>!*/; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (14,28): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static A<object, string?> F2; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 28)); comp.VerifyTypes(); } [Fact] public void Directive_PartialClasses() { var source0 = @"class Base<T> { } class Program { #nullable enable static void F(Base<object?> b) { } static void Main() { F(new C1()); F(new C2()); F(new C3()); F(new C4()); F(new C5()); F(new C6()); F(new C7()); F(new C8()); F(new C9()); } }"; var source1 = @"#pragma warning disable 8632 partial class C1 : Base<object> { } partial class C2 { } partial class C3 : Base<object> { } #nullable disable partial class C4 { } partial class C5 : Base<object> { } partial class C6 { } #nullable enable partial class C7 : Base<object> { } partial class C8 { } partial class C9 : Base<object> { } "; var source2 = @"#pragma warning disable 8632 partial class C1 { } partial class C4 : Base<object> { } partial class C7 { } #nullable disable partial class C2 : Base<object> { } partial class C5 { } partial class C8 : Base<object> { } #nullable enable partial class C3 { } partial class C6 : Base<object> { } partial class C9 { } "; // -nullable (default): var comp = CreateCompilation(new[] { source0, source1, source2 }, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (15,11): warning CS8620: Nullability of reference types in argument of type 'C6' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C6()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C6()").WithArguments("C6", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(15, 11), // (16,11): warning CS8620: Nullability of reference types in argument of type 'C7' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C7()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C7()").WithArguments("C7", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(16, 11), // (18,11): warning CS8620: Nullability of reference types in argument of type 'C9' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C9()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C9()").WithArguments("C9", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(18, 11)); // -nullable-: comp = CreateCompilation(new[] { source0, source1, source2 }, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Disable)); comp.VerifyDiagnostics( // (15,11): warning CS8620: Nullability of reference types in argument of type 'C6' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C6()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C6()").WithArguments("C6", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(15, 11), // (16,11): warning CS8620: Nullability of reference types in argument of type 'C7' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C7()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C7()").WithArguments("C7", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(16, 11), // (18,11): warning CS8620: Nullability of reference types in argument of type 'C9' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C9()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C9()").WithArguments("C9", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(18, 11)); // -nullable+: comp = CreateCompilation(new[] { source0, source1, source2 }, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (10,11): warning CS8620: Nullability of reference types in argument of type 'C1' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C1()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C1()").WithArguments("C1", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(10, 11), // (12,11): warning CS8620: Nullability of reference types in argument of type 'C3' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C3()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C3()").WithArguments("C3", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(12, 11), // (13,11): warning CS8620: Nullability of reference types in argument of type 'C4' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C4()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C4()").WithArguments("C4", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(13, 11), // (15,11): warning CS8620: Nullability of reference types in argument of type 'C6' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C6()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C6()").WithArguments("C6", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(15, 11), // (16,11): warning CS8620: Nullability of reference types in argument of type 'C7' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C7()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C7()").WithArguments("C7", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(16, 11), // (18,11): warning CS8620: Nullability of reference types in argument of type 'C9' doesn't match target type 'Base<object?>' for parameter 'b' in 'void Program.F(Base<object?> b)'. // F(new C9()); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new C9()").WithArguments("C9", "Base<object?>", "b", "void Program.F(Base<object?> b)").WithLocation(18, 11)); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void Directive_EnableAndDisable_01() { var source = @"#nullable enable class Program { static void F(object x) { object? y = null; F(y); // warning } #nullable disable static void G() { F(null); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void Program.F(object x)'. // F(y); // warning Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void Program.F(object x)").WithLocation(7, 11)); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void Directive_EnableAndDisable_02() { var source = @"class Program { #nullable disable static void G() { F(null); } #nullable enable static void F(object x) { object? y = null; F(y); // warning } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void Program.F(object x)'. // F(y); // warning Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void Program.F(object x)").WithLocation(12, 11)); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void Directive_EnableAndDisable_03() { var source = @"class Program { static void F(object x) { object? y = null; F(y); // warning } #nullable disable static void G() { F(null); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void Program.F(object x)'. // F(y); // warning Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void Program.F(object x)").WithLocation(6, 11)); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void Directive_EnableAndDisable_04() { var source = @"class Program { static void G() { F(null); } #nullable enable static void F(object x) { object? y = null; F(y); // warning } }"; var comp = CreateCompilation(source, options: WithNullableDisable()); comp.VerifyDiagnostics( // (11,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void Program.F(object x)'. // F(y); // warning Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void Program.F(object x)").WithLocation(11, 11)); } [Fact] public void Directive_GloballyEnabled_GeneratedCode_DisabledByDefault() { var source = @" // <autogenerated /> class Program { static void F(object x) { x = null; // no warning, generated file } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics(); } [Theory] [InlineData("")] [InlineData("#nullable enable warnings")] [InlineData("#nullable disable")] public void Directive_GloballyEnabled_GeneratedCode_Annotations_Disabled(string nullableDirective) { var source = $@" // <autogenerated /> {nullableDirective} class Program {{ static void F(string? s) {{ }} }}"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (6,25): error CS8669: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. Auto-generated code requires an explicit '#nullable enable' directive in source. // static void F(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotationInGeneratedCode, "?").WithLocation(6, 25)); } [Theory] [InlineData("#nullable enable")] [InlineData("#nullable enable annotations")] public void Directive_GloballyEnabled_GeneratedCode_Annotations_Enabled(string nullableDirective) { var source = $@" // <autogenerated /> {nullableDirective} class Program {{ static void F(string? s) {{ }} }}"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics(); } [Fact] public void Directive_GloballyEnabled_GeneratedCode_Enabled() { var source = @" // <autogenerated /> #nullable enable class Program { static void F(object x) { x = null; // warning } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 13) ); } [Fact] public void Directive_GloballyEnabled_GeneratedCode_RestoreToProjectDefault() { var source = @" // <autogenerated /> partial class Program { #nullable restore static void F(object x) { x = null; // warning, restored to project default } }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 13) ); } [Fact] public void Directive_GloballyEnabled_GeneratedCode_WarningsAreDisabledByDefault() { var source = @" // <autogenerated /> partial class Program { static void G(object x) { x = null; // no warning F = null; // no warning #nullable enable warnings x = null; // no warning - declared out of nullable context F = null; // warning - declared in a nullable context } #nullable enable static object F = new object(); }"; var comp = CreateCompilation(source, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (12,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // warning - declared in a nullable context Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 13) ); } [Fact] public void Directive_GloballyEnabled_GeneratedCode_PartialClasses() { var source1 = @" // <autogenerated /> partial class Program { static void G(object x) { x = null; // no warning F = null; // no warning } }"; var source2 = @" partial class Program { static object F = new object(); static void H() { F = null; // warning } }"; var comp = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (8,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // warning Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 13) ); } [Fact] public void Directive_GloballyEnabled_GeneratedCode_PartialClasses2() { var source1 = @" // <autogenerated /> partial class Program { #nullable enable warnings static void G(object x) { x = null; // no warning F = null; // warning } }"; var source2 = @" partial class Program { static object F = new object(); static void H() { F = null; // warning } }"; var comp = CreateCompilation(new[] { source1, source2 }, options: TestOptions.DebugDll.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (8,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // warning Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 13), // (9,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // warning Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 13) ); } [Fact] [WorkItem(3705, "https://github.com/dotnet/roslyn/issues/3705")] public void GeneratedSyntaxTrees_Nullable() { #pragma warning disable CS0618 // This test is intentionally calling the obsolete method to assert it's isGeneratedCode input is now ignored var source1 = CSharpSyntaxTree.ParseText(@" partial class Program { static void G(object x) { x = null; // no warning F = null; // no warning } }", options: null, path: "", encoding: null, diagnosticOptions: null, isGeneratedCode: true, cancellationToken: default); Assert.False(((CSharpSyntaxTree)source1).IsGeneratedCode(null, cancellationToken: default)); var source2 = CSharpSyntaxTree.ParseText(@" partial class Program { static object F = new object(); static void H(object x) { x = null; // warning 1 F = null; // warning 2 } }", options: null, path: "", encoding: null, diagnosticOptions: null, isGeneratedCode: false, cancellationToken: default); Assert.False(((CSharpSyntaxTree)source2).IsGeneratedCode(null, cancellationToken: default)); var source3 = CSharpSyntaxTree.ParseText( @" partial class Program { static void I(object x) { x = null; // warning 3 F = null; // warning 4 } }", options: null, path: "", encoding: null, diagnosticOptions: null, isGeneratedCode: null /* use heuristic */, cancellationToken: default); Assert.False(((CSharpSyntaxTree)source3).IsGeneratedCode(null, cancellationToken: default)); var source4 = SyntaxFactory.ParseSyntaxTree(@" partial class Program { static void J(object x) { x = null; // no warning F = null; // no warning } }", options: null, path: "", encoding: null, diagnosticOptions: null, isGeneratedCode: true, cancellationToken: default); Assert.False(((CSharpSyntaxTree)source4).IsGeneratedCode(null, cancellationToken: default)); #pragma warning restore CS0618 var syntaxOptions = new TestSyntaxTreeOptionsProvider( (source1, GeneratedKind.MarkedGenerated), (source2, GeneratedKind.NotGenerated), (source3, GeneratedKind.Unknown), (source4, GeneratedKind.MarkedGenerated) ); var comp = CreateCompilation(new[] { source1, source2, source3, source4 }, options: TestOptions.DebugDll .WithNullableContextOptions(NullableContextOptions.Enable) .WithSyntaxTreeOptionsProvider(syntaxOptions)); comp.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // warning 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (7,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // warning 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 13), // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // warning 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 13), // (9,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // warning 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 13) ); } [WorkItem(30862, "https://github.com/dotnet/roslyn/issues/30862")] [Fact] public void DirectiveDisableWarningEnable() { var source = @"#nullable enable class Program { static void F(object x) { } #nullable disable static void F1(object? y, object? z) { F(y); #pragma warning restore 8604 F(z); // 1 } static void F2(object? w) { F(w); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static void F1(object? y, object? z) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 26), // (8,37): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static void F1(object? y, object? z) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 37), // (14,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static void F2(object? w) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 26)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void PragmaNullable_NoEffect() { var source = @" #pragma warning disable nullable class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_Enable_01() { var source = @" #nullable enable annotations class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_Enable_02() { var source = @" #nullable enable #nullable disable warnings class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_Enable_03() { var source = @" #nullable enable #nullable restore warnings class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_Enable_04() { var source = @" class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullable(NullableContextOptions.Annotations)); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_Enable_05() { var source = @" #nullable enable #nullable restore warnings class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableDisable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_Enable_06() { var source = @" #nullable disable #nullable restore warnings class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void M(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 25), // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_NonFlowAnalysisWarning_01() { var source = @" #nullable enable annotations public partial class C { partial void M(string? s); } public partial class C { partial void M(string s) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_NonFlowAnalysisWarning_02() { var source = @" using System.Collections.Generic; #nullable enable annotations class Base { internal virtual void M(List<string> list) { } } class Derived : Base { internal override void M(List<string?> list) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_NonFlowAnalysisWarning_03() { var source = @" using System.Collections.Generic; class Base { internal virtual void M(List<string> list) { } } #nullable enable annotations class Derived : Base { internal override void M(List<string?> list) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_NonFlowAnalysisWarning_04() { var source = @" #nullable enable annotations public interface I { void M(string? s); } public class C : I { public void M(string s) => throw null!; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Annotations_NonFlowAnalysisWarning_05() { var source = @" #nullable enable annotations public interface I { string M(); } public class C : I { public string? M() => throw null!; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Enable_NonFlowAnalysisWarning_01() { var source = @" #nullable enable public partial class C { partial void M(string? s); } public partial class C { partial void M(string s) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,18): warning CS8611: Nullability of reference types in type of parameter 's' doesn't match partial method declaration. // partial void M(string s) { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M").WithArguments("s").WithLocation(10, 18)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Enable_NonFlowAnalysisWarning_02() { var source = @" using System.Collections.Generic; #nullable enable class Base { internal virtual void M(List<string> list) { } } class Derived : Base { internal override void M(List<string?> list) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,28): warning CS8610: Nullability of reference types in type of parameter 'list' doesn't match overridden member. // internal override void M(List<string?> list) { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("list").WithLocation(11, 28)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Enable_NonFlowAnalysisWarning_03() { var source = @" using System.Collections.Generic; class Base { internal virtual void M(List<string> list) { } } #nullable enable class Derived : Base { // No warning because the base method's parameter type is oblivious internal override void M(List<string?> list) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Enable_NonFlowAnalysisWarning_04() { var source = @" #nullable enable public interface I { void M(string? s); } public class C : I { public void M(string s) => throw null!; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,17): warning CS8767: Nullability of reference types in type of parameter 's' of 'void C.M(string s)' doesn't match implicitly implemented member 'void I.M(string? s)' (possibly because of nullability attributes). // public void M(string s) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M").WithArguments("s", "void C.M(string s)", "void I.M(string? s)").WithLocation(10, 17) ); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Enable_NonFlowAnalysisWarning_05() { var source = @" #nullable enable public interface I { string M(); } public class C : I { public string? M() => throw null!; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,20): warning CS8766: Nullability of reference types in return type of 'string? C.M()' doesn't match implicitly implemented member 'string I.M()' (possibly because of nullability attributes). // public string? M() => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M").WithArguments("string? C.M()", "string I.M()").WithLocation(10, 20) ); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Warnings_Enable_01() { var source = @" #nullable enable warnings class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void M(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 25), // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Warnings_Enable_02() { var source = @" #nullable enable #nullable disable annotations class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void M(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 25), // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Warnings_Enable_03() { var source = @" #nullable enable #nullable restore annotations class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void M(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 25), // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Warnings_Enable_04() { var source = @" class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullable(NullableContextOptions.Warnings)); comp.VerifyDiagnostics( // (4,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void M(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 25), // (6,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Warnings_Enable_05() { var source = @" #nullable enable #nullable restore annotations class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableDisable()); comp.VerifyDiagnostics( // (6,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void M(string? s) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 25), // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13)); } [Fact, WorkItem(35748, "https://github.com/dotnet/roslyn/issues/35748")] public void Directive_Warnings_Enable_06() { var source = @" #nullable disable #nullable restore annotations class Program { static void M(string? s) { _ = s.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(35730, "https://github.com/dotnet/roslyn/issues/35730")] public void Directive_ProjectNoWarn() { var source = @" #nullable enable class Program { void M1(string? s) { _ = s.ToString(); } } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13)); var id = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullReferenceReceiver); var comp2 = CreateCompilation(source, options: TestOptions.DebugDll.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress)); comp2.VerifyDiagnostics(); } [Fact, WorkItem(31740, "https://github.com/dotnet/roslyn/issues/31740")] public void Attribute_ArrayWithDifferentNullability() { var source = @" public class MyAttribute : System.Attribute { public MyAttribute(string[] x) { } } #nullable enable [My(new string[] { ""hello"" })] class C { } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); } [Fact, WorkItem(31740, "https://github.com/dotnet/roslyn/issues/31740")] public void Attribute_ArrayWithDifferentNullability2() { var source = @" public class MyAttribute : System.Attribute { public MyAttribute(string[] x) { } } #nullable enable [My(new string[] { null })] class C { } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (7,20): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [My(new string[] { null })] Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 20) ); } [Fact, WorkItem(31740, "https://github.com/dotnet/roslyn/issues/31740")] public void Attribute_ArrayWithDifferentNullability_DynamicAndTupleNames() { var source = @" public class MyAttribute : System.Attribute { public MyAttribute((string alice, string)[] x, dynamic[] y, object[] z) { } } #nullable enable [My(new (string, string bob)[] { }, new object[] { }, new dynamic[] { })] class C { } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (7,2): error CS0181: Attribute constructor parameter 'x' has type '(string alice, string)[]', which is not a valid attribute parameter type // [My(new (string, string bob)[] { }, new object[] { }, new dynamic[] { })] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("x", "(string alice, string)[]").WithLocation(7, 2), // (7,2): error CS0181: Attribute constructor parameter 'y' has type 'dynamic[]', which is not a valid attribute parameter type // [My(new (string, string bob)[] { }, new object[] { }, new dynamic[] { })] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("y", "dynamic[]").WithLocation(7, 2) ); } [Fact, WorkItem(31740, "https://github.com/dotnet/roslyn/issues/31740")] public void Attribute_ArrayWithDifferentNullability_Dynamic() { var source = @" public class MyAttribute : System.Attribute { public MyAttribute(dynamic[] y) { } } #nullable enable [My(new object[] { })] class C { } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (7,2): error CS0181: Attribute constructor parameter 'y' has type 'dynamic[]', which is not a valid attribute parameter type // [My(new object[] { })] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("y", "dynamic[]").WithLocation(7, 2) ); } [Fact, WorkItem(36974, "https://github.com/dotnet/roslyn/issues/36974")] public void Attribute_Params() { var source = @" using System; [My(new object[] { new string[] { ""a"" } })] public class C { } #nullable enable public class MyAttribute : Attribute { public MyAttribute(params object[] o) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); var c = comp.GetTypeByMetadataName("C"); var attribute = c.GetAttributes().Single(); Assert.Equal(@"{{""a""}}", attribute.CommonConstructorArguments.Single().ToCSharpString()); } [Fact, WorkItem(36974, "https://github.com/dotnet/roslyn/issues/36974")] public void Attribute_Params_Disabled() { var source = @" using System; [My(new object[] { new string[] { ""a"" } })] public class C { } #nullable disable public class MyAttribute : Attribute { public MyAttribute(params object[] o) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics(); var c = comp.GetTypeByMetadataName("C"); var attribute = c.GetAttributes().Single(); Assert.Equal(@"{{""a""}}", attribute.CommonConstructorArguments.Single().ToCSharpString()); } [Fact, WorkItem(37155, "https://github.com/dotnet/roslyn/issues/37155")] public void Attribute_Params_DifferentNullability() { var source = @" using System; #nullable enable [My(new object?[] { null })] public class C { } public class MyAttribute : Attribute { public MyAttribute(params object[] o) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (5,5): warning CS8620: Argument of type 'object?[]' cannot be used for parameter 'o' of type 'object[]' in 'MyAttribute.MyAttribute(params object[] o)' due to differences in the nullability of reference types. // [My(new object?[] { null })] Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new object?[] { null }").WithArguments("object?[]", "object[]", "o", "MyAttribute.MyAttribute(params object[] o)").WithLocation(5, 5) ); } [Fact, WorkItem(37155, "https://github.com/dotnet/roslyn/issues/37155")] public void Attribute_DifferentNullability() { var source = @" using System; #nullable enable [My(new object?[] { null })] public class C { } public class MyAttribute : Attribute { public MyAttribute(object[] o) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (5,5): warning CS8620: Argument of type 'object?[]' cannot be used for parameter 'o' of type 'object[]' in 'MyAttribute.MyAttribute(object[] o)' due to differences in the nullability of reference types. // [My(new object?[] { null })] Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new object?[] { null }").WithArguments("object?[]", "object[]", "o", "MyAttribute.MyAttribute(object[] o)").WithLocation(5, 5) ); } [Fact, WorkItem(36974, "https://github.com/dotnet/roslyn/issues/36974")] public void Attribute_Params_TupleNames() { var source = @" using System; [My(new (int a, int b)[] { (1, 2) })] public class C { } public class MyAttribute : Attribute { public MyAttribute(params (int c, int)[] o) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (4,2): error CS0181: Attribute constructor parameter 'o' has type '(int c, int)[]', which is not a valid attribute parameter type // [My(new (int a, int b)[] { (1, 2) })] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("o", "(int c, int)[]").WithLocation(4, 2) ); } [Fact, WorkItem(36974, "https://github.com/dotnet/roslyn/issues/36974")] public void Attribute_Params_Dynamic() { var source = @" using System; [My(new object[] { 1 })] public class C { } public class MyAttribute : Attribute { public MyAttribute(params dynamic[] o) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (4,2): error CS0181: Attribute constructor parameter 'o' has type 'dynamic[]', which is not a valid attribute parameter type // [My(new object[] { 1 })] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "My").WithArguments("o", "dynamic[]").WithLocation(4, 2) ); } [Fact] public void AttributeArgument_Constructor_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s) { } } [MyAttribute(null)] //1 class C { } [MyAttribute(""str"")] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 14) ); } [Fact] public void AttributeArgument_Constructor_NullLiteral_Suppressed() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s) { } } [MyAttribute(null!)] class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void AttributeArgument_Constructor_NullLiteral_CSharp7_3() { var source = @" class MyAttribute : System.Attribute { public MyAttribute(string s) { } } [MyAttribute(null)] class C { } [MyAttribute(""str"")] class D { } "; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(); } [Fact] public void AttributeArgument_Constructor_NullLiteral_WithDefaultArgument() { var source = @"#nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s, string s2 = ""str"") { } } [MyAttribute(null)] //1 class C { } [MyAttribute(null, null)] // 2, 3 class D { } [MyAttribute(null, ""str"")] // 4 class E { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 14), // (10,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, null)] // 2, 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 14), // (10,20): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, null)] // 2, 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 20), // (13,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, "str")] // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 14) ); } [Fact] public void AttributeArgument_Constructor_NullLiteral_WithNullDefaultArgument() { var source = @"#nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s, string s2 = null) { } // 1 } [MyAttribute(""str"")] class C { } [MyAttribute(""str"", null)] // 2 class D { } [MyAttribute(""str"", ""str"")] class E { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,46): warning CS8625: Cannot convert null literal to non-nullable reference type. // public MyAttribute(string s, string s2 = null) { } // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 46), // (10,21): warning CS8625: Cannot convert null literal to non-nullable reference type. // [MyAttribute("str", null)] // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 21) ); } [Fact] public void AttributeArgument_Constructor_NullLiteral_WithNamedArguments() { var source = @"#nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s, string s2 = ""str"", string? s3 = ""str"") { } } [MyAttribute(""str"", s2: null, s3: null)] //1 class C { } [MyAttribute(s3: null, s2: null, s: ""str"")] // 2 class D { } [MyAttribute(s3: null, s2: ""str"", s: ""str"")] class E { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,25): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute("str", s2: null, s3: null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 25), // (10,28): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(s3: null, s2: null, s: "str")] // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 28) ); } [Fact] public void AttributeArgument_Constructor_NullLiteral_DisabledEnabled() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s, string s2) { } } [MyAttribute(null, //1 #nullable disable null #nullable enable )] class C { } [MyAttribute( #nullable disable null, #nullable enable null //2 )] class D { } [MyAttribute(null, //3 s2: #nullable disable null #nullable enable )] class E { } [MyAttribute( #nullable disable null, s2: #nullable enable null //4 )] class F { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 14), // (19,1): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // null //2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 1), // (23,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, //3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(23, 14), // (36,1): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // null //4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(36, 1) ); } [Fact] public void AttributeArgument_Constructor_NullLiteral_WarningDisabledEnabled() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s, string s2) { } } #nullable disable #nullable enable warnings [MyAttribute(null, //1 #nullable disable warnings null #nullable enable warnings )] class C { } [MyAttribute( #nullable disable warnings null, #nullable enable warnings null //2 )] class D { } [MyAttribute(null, //3 s2: #nullable disable warnings null #nullable enable warnings )] class E { } [MyAttribute( #nullable disable warnings null, s2: #nullable enable warnings null //4 )] class F { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 14), // (21,1): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // null //2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 1), // (25,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, //3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(25, 14), // (38,1): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // null //4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(38, 1) ); } [Fact] public void AttributeArgument_Constructor_Array_LiteralNull() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string[] s) { } } [MyAttribute(null)] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 14) ); } [Fact] public void AttributeArgument_Constructor_Array_LiteralNull_Suppressed() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string[] s) { } } [MyAttribute(null!)] class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void AttributeArgument_Constructor_Array_ArrayOfNullable() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string[] s) { } } [MyAttribute(new string?[]{ null })] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,14): warning CS8620: Argument of type 'string?[]' cannot be used as an input of type 'string[]' for parameter 's' in 'MyAttribute.MyAttribute(string[] s)' due to differences in the nullability of reference types. // [MyAttribute(new string?[]{ null })] //1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new string?[]{ null }").WithArguments("string?[]", "string[]", "s", "MyAttribute.MyAttribute(string[] s)").WithLocation(8, 14) ); } [Fact] public void AttributeArgument_Constructor_Array_ArrayOfNullable_Suppressed() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string[] s) { } } [MyAttribute(new string?[]{ null }!)] class C { } [MyAttribute(new string[]{ null! })] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void AttributeArgument_Constructor_Array_ArrayOfNullable_ImplicitType() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string[] s) { } } [MyAttribute(new []{ ""str"", null })] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,14): warning CS8620: Argument of type 'string?[]' cannot be used as an input of type 'string[]' for parameter 's' in 'MyAttribute.MyAttribute(string[] s)' due to differences in the nullability of reference types. // [MyAttribute(new []{ "str", null })] //1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, @"new []{ ""str"", null }").WithArguments("string?[]", "string[]", "s", "MyAttribute.MyAttribute(string[] s)").WithLocation(8, 14) ); } [Fact] public void AttributeArgument_Constructor_Array_NullValueInInitializer() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string[] s) { } } [MyAttribute(new string[]{ ""str"", null, ""str"" })] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,35): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(new string[]{ "str", null, "str" })] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 35) ); } [Fact] public void AttributeArgument_Constructor_Array_NullValueInNestedInitializer() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(object[] s) { } } [MyAttribute(new object[] { new string[] { ""str"", null }, //1 new string[] { null }, //2 new string?[] { null } })] class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,27): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // new string[] { "str", null }, //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 27), // (11,20): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // new string[] { null }, //2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 20) ); } [Fact] public void AttributeArgument_Constructor_ParamsArrayOfNullable_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(params object?[] s) { } } [MyAttribute(null)] //1 class C { } [MyAttribute(null, null)] class D { } [MyAttribute((object?)null)] class E { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 14) ); } [Fact] public void AttributeArgument_Constructor_ParamsArray_NullItem() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute(string s1, params object[] s) { } } [MyAttribute(""str"", null, ""str"", ""str"")] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,21): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute("str", null, "str", "str")] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 21) ); } [Fact] public void AttributeArgument_PropertyAssignment_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute() { } public string MyValue { get; set; } = ""str""; } [MyAttribute(MyValue = null)] //1 class C { } [MyAttribute(MyValue = ""str"")] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,24): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(MyValue = null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 24) ); } [Fact] public void AttributeArgument_PropertyAssignment_Array_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute() { } public string[] PropertyArray { get; set; } = new string[] { }; public string[]? NullablePropertyArray { get; set; } = null; } [MyAttribute(PropertyArray = null)] //1 class C { } [MyAttribute(NullablePropertyArray = null)] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,30): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(PropertyArray = null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 30) ); } [Fact] public void AttributeArgument_PropertyAssignment_Array_ArrayOfNullable() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute() { } public string[] PropertyArray { get; set; } = new string[] { ""str"" }; public string[]? PropertyNullableArray { get; set; } = new string[] { ""str"" }; } [MyAttribute(PropertyArray = new string?[]{ null })] //1 class C { } [MyAttribute(PropertyNullableArray = null)] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,30): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'. // [MyAttribute(PropertyArray = new string?[]{ null })] //1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new string?[]{ null }").WithArguments("string?[]", "string[]").WithLocation(12, 30) ); } [Fact] public void AttributeArgument_FieldAssignment_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute() { } public string myValue = ""str""; } [MyAttribute(myValue = null)] //1 class C { } [MyAttribute(myValue = ""str"")] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,24): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(myValue = null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 24) ); } [Fact] public void AttributeArgument_FieldAssignment_Array_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute() { } public string[] fieldArray = new string[] { }; public string[]? nullableFieldArray = null; } [MyAttribute(fieldArray = null)] //1 class C { } [MyAttribute(nullableFieldArray = null)] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,27): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(fieldArray = null)] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 27) ); } [Fact] public void AttributeArgument_FieldAssignment_Array_ArrayOfNullable() { var source = @" #nullable enable class MyAttribute : System.Attribute { public MyAttribute() { } public string[] fieldArray = new string[] { }; public string?[] fieldArrayOfNullable = new string?[] { }; } [MyAttribute(fieldArray = new string?[]{ null })] //1 class C { } [MyAttribute(fieldArrayOfNullable = new string?[]{ null })] class D { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,27): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'. // [MyAttribute(fieldArray = new string?[]{ null })] //1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new string?[]{ null }").WithArguments("string?[]", "string[]").WithLocation(12, 27) ); } [Fact] public void AttributeArgument_NoMatchingConstructor_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { } [MyAttribute(null)] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,2): error CS1729: 'MyAttribute' does not contain a constructor that takes 1 arguments // [MyAttribute(null)] //1 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "MyAttribute(null)").WithArguments("MyAttribute", "1").WithLocation(7, 2) ); } [Fact] public void AttributeArgument_NoMatchingConstructor_Array_NullValueInInitializer() { var source = @" #nullable enable class MyAttribute : System.Attribute { } [MyAttribute(new string[] { null })] //1 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,2): error CS1729: 'MyAttribute' does not contain a constructor that takes 1 arguments // [MyAttribute(new string[] { null })] //1 Diagnostic(ErrorCode.ERR_BadCtorArgCount, "MyAttribute(new string[] { null })").WithArguments("MyAttribute", "1").WithLocation(7, 2), // (7,29): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(new string[] { null })] //1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 29) ); } [Fact] public void AttributeArgument_NoMatchingConstructor_PropertyAssignment_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public string[] PropertyArray { get; set; } = new string[] { ""str"" }; public string[]? PropertyNullableArray { get; set; } = new string[] { ""str"" }; } [MyAttribute( // 1 new string[] { null }, // 2 PropertyArray = null, // 3 PropertyNullableArray = new string[] { null } // 4 )] class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,2): error CS1729: 'MyAttribute' does not contain a constructor that takes 1 arguments // [MyAttribute( // 1 Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"MyAttribute( // 1 new string[] { null }, // 2 PropertyArray = null, // 3 PropertyNullableArray = new string[] { null } // 4 )").WithArguments("MyAttribute", "1").WithLocation(10, 2), // (11,20): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // new string[] { null }, // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 20), // (12,21): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // PropertyArray = null, // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 21), // (13,44): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // PropertyNullableArray = new string[] { null } // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 44) ); } [Fact] public void AttributeArgument_NoMatchingConstructor_FieldAssignment_NullLiteral() { var source = @" #nullable enable class MyAttribute : System.Attribute { public string[] fieldArray = new string[] { }; public string?[] fieldArrayOfNullable = new string?[] { }; } [MyAttribute( // 1 new string[] { null }, // 2 fieldArray = null, // 3 fieldArrayOfNullable = new string[] { null } // 4 )] class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,2): error CS1729: 'MyAttribute' does not contain a constructor that takes 1 arguments // [MyAttribute( // 1 Diagnostic(ErrorCode.ERR_BadCtorArgCount, @"MyAttribute( // 1 new string[] { null }, // 2 fieldArray = null, // 3 fieldArrayOfNullable = new string[] { null } // 4 )").WithArguments("MyAttribute", "1").WithLocation(10, 2), // (11,20): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // new string[] { null }, // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 20), // (12,18): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // fieldArray = null, // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 18), // (13,43): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // fieldArrayOfNullable = new string[] { null } // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 43) ); } [Fact] public void AttributeArgument_ComplexAssignment() { var source = @" #nullable enable [System.AttributeUsage(System.AttributeTargets.All, AllowMultiple = true)] class MyAttribute : System.Attribute { public MyAttribute(string s, string s2 = ""str"", string s3 = ""str"") { } public string[] fieldArray = new string[] { }; public string?[] fieldArrayOfNullable = new string[] { }; public string[]? nullableFieldArray = null; public string[] PropertyArray { get; set; } = new string[] { }; public string?[] PropertyArrayOfNullable { get; set; } = new string[] { }; public string[]? NullablePropertyArray { get; set; } = null; } [MyAttribute(""s1"")] [MyAttribute(""s1"", s3: ""s3"", fieldArray = new string[]{})] [MyAttribute(""s1"", s2: ""s2"", fieldArray = new string[]{}, PropertyArray = new string[]{})] [MyAttribute(""s1"", fieldArrayOfNullable = new string?[]{ null }, NullablePropertyArray = null)] [MyAttribute(null)] // 1 [MyAttribute(""s1"", s3: null, fieldArray = new string[]{})] // 2 [MyAttribute(""s1"", s2: ""s2"", fieldArray = new string?[]{ null }, PropertyArray = new string[]{})] // 3 [MyAttribute(""s1"", PropertyArrayOfNullable = null)] // 4 [MyAttribute(""s1"", NullablePropertyArray = new string?[]{ null })] // 5 [MyAttribute(""s1"", fieldArrayOfNullable = null)] // 6 [MyAttribute(""s1"", nullableFieldArray = new string[]{ null })] // 7 [MyAttribute(null, //8 s2: null, //9 fieldArrayOfNullable = null, //10 NullablePropertyArray = new string?[]{ null })] // 11 [MyAttribute(null, // 12 #nullable disable s2: null, #nullable enable fieldArrayOfNullable = null, //13 #nullable disable warnings NullablePropertyArray = new string?[]{ null }, #nullable enable warnings nullableFieldArray = new string?[]{ null })] //14 class C { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (26,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null)] // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(26, 14), // (27,24): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute("s1", s3: null, fieldArray = new string[]{})] // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(27, 24), // (28,43): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'. // [MyAttribute("s1", s2: "s2", fieldArray = new string?[]{ null }, PropertyArray = new string[]{})] // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new string?[]{ null }").WithArguments("string?[]", "string[]").WithLocation(28, 43), // (29,46): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute("s1", PropertyArrayOfNullable = null)] // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(29, 46), // (30,44): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'. // [MyAttribute("s1", NullablePropertyArray = new string?[]{ null })] // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new string?[]{ null }").WithArguments("string?[]", "string[]").WithLocation(30, 44), // (31,43): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute("s1", fieldArrayOfNullable = null)] // 6 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(31, 43), // (32,55): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute("s1", nullableFieldArray = new string[]{ null })] // 7 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(32, 55), // (33,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, //8 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(33, 14), // (34,17): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // s2: null, //9 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(34, 17), // (35,36): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // fieldArrayOfNullable = null, //10 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(35, 36), // (36,37): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'. // NullablePropertyArray = new string?[]{ null })] // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new string?[]{ null }").WithArguments("string?[]", "string[]").WithLocation(36, 37), // (37,14): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // [MyAttribute(null, // 12 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(37, 14), // (41,36): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // fieldArrayOfNullable = null, //13 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(41, 36), // (45,34): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'string[]'. // nullableFieldArray = new string?[]{ null })] //14 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new string?[]{ null }").WithArguments("string?[]", "string[]").WithLocation(45, 34) ); } [Fact, WorkItem(40136, "https://github.com/dotnet/roslyn/issues/40136")] public void SelfReferencingAttribute() { var source = @" using System; [AttributeUsage(AttributeTargets.All)] [ExplicitCrossPackageInternal(ExplicitCrossPackageInternalAttribute.s)] internal sealed class ExplicitCrossPackageInternalAttribute : Attribute { internal const string s = """"; [ExplicitCrossPackageInternal(s)] internal ExplicitCrossPackageInternalAttribute([ExplicitCrossPackageInternal(s)] string prop) { } [return: ExplicitCrossPackageInternal(s)] [ExplicitCrossPackageInternal(s)] internal void Method() { } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void NullableAndConditionalOperators() { var source = @"class Program { static void F1(object x) { _ = x is string? 1 : 2; _ = x is string? ? 1 : 2; // error 1: is a nullable reference type _ = x is string ? ? 1 : 2; // error 2: is a nullable reference type _ = x as string?? x; _ = x as string ? ?? x; // error 3: as a nullable reference type } static void F2(object y) { _ = y is object[]? 1 : 2; _ = y is object[]? ? 1 : 2; // error 4 _ = y is object[] ? ? 1 : 2; // error 5 _ = y as object[]?? y; _ = y as object[] ? ?? y; // error 6 } static void F3<T>(object z) { _ = z is T[][]? 1 : 2; _ = z is T[]?[] ? 1 : 2; _ = z is T[] ? [] ? 1 : 2; _ = z as T[][]?? z; _ = z as T[] ? [] ?? z; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (6,18): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead. // _ = x is string? ? 1 : 2; // error 1: is a nullable reference type Diagnostic(ErrorCode.ERR_IsNullableType, "string?").WithArguments("string").WithLocation(6, 18), // (6,24): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = x is string? ? 1 : 2; // error 1: is a nullable reference type Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(6, 24), // (7,18): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead. // _ = x is string ? ? 1 : 2; // error 2: is a nullable reference type Diagnostic(ErrorCode.ERR_IsNullableType, "string ?").WithArguments("string").WithLocation(7, 18), // (7,25): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = x is string ? ? 1 : 2; // error 2: is a nullable reference type Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(7, 25), // (9,18): error CS8651: It is not legal to use nullable reference type 'string?' in an as expression; use the underlying type 'string' instead. // _ = x as string ? ?? x; // error 3: as a nullable reference type Diagnostic(ErrorCode.ERR_AsNullableType, "string ?").WithArguments("string").WithLocation(9, 18), // (9,25): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = x as string ? ?? x; // error 3: as a nullable reference type Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(9, 25), // (14,18): error CS8650: It is not legal to use nullable reference type 'object[]?' in an is-type expression; use the underlying type 'object[]' instead. // _ = y is object[]? ? 1 : 2; // error 4 Diagnostic(ErrorCode.ERR_IsNullableType, "object[]?").WithArguments("object[]").WithLocation(14, 18), // (14,26): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = y is object[]? ? 1 : 2; // error 4 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(14, 26), // (15,18): error CS8650: It is not legal to use nullable reference type 'object[]?' in an is-type expression; use the underlying type 'object[]' instead. // _ = y is object[] ? ? 1 : 2; // error 5 Diagnostic(ErrorCode.ERR_IsNullableType, "object[] ?").WithArguments("object[]").WithLocation(15, 18), // (15,27): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = y is object[] ? ? 1 : 2; // error 5 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(15, 27), // (17,18): error CS8651: It is not legal to use nullable reference type 'object[]?' in an as expression; use the underlying type 'object[]' instead. // _ = y as object[] ? ?? y; // error 6 Diagnostic(ErrorCode.ERR_AsNullableType, "object[] ?").WithArguments("object[]").WithLocation(17, 18), // (17,27): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = y as object[] ? ?? y; // error 6 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(17, 27), // (22,21): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = z is T[]?[] ? 1 : 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(22, 21), // (23,22): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = z is T[] ? [] ? 1 : 2; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(23, 22), // (25,22): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = z as T[] ? [] ?? z; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(25, 22) ); comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead. // _ = x is string? ? 1 : 2; // error 1: is a nullable reference type Diagnostic(ErrorCode.ERR_IsNullableType, "string?").WithArguments("string").WithLocation(6, 18), // (7,18): error CS8650: It is not legal to use nullable reference type 'string?' in an is-type expression; use the underlying type 'string' instead. // _ = x is string ? ? 1 : 2; // error 2: is a nullable reference type Diagnostic(ErrorCode.ERR_IsNullableType, "string ?").WithArguments("string").WithLocation(7, 18), // (9,18): error CS8651: It is not legal to use nullable reference type 'string?' in an as expression; use the underlying type 'string' instead. // _ = x as string ? ?? x; // error 3: as a nullable reference type Diagnostic(ErrorCode.ERR_AsNullableType, "string ?").WithArguments("string").WithLocation(9, 18), // (14,18): error CS8650: It is not legal to use nullable reference type 'object[]?' in an is-type expression; use the underlying type 'object[]' instead. // _ = y is object[]? ? 1 : 2; // error 4 Diagnostic(ErrorCode.ERR_IsNullableType, "object[]?").WithArguments("object[]").WithLocation(14, 18), // (15,18): error CS8650: It is not legal to use nullable reference type 'object[]?' in an is-type expression; use the underlying type 'object[]' instead. // _ = y is object[] ? ? 1 : 2; // error 5 Diagnostic(ErrorCode.ERR_IsNullableType, "object[] ?").WithArguments("object[]").WithLocation(15, 18), // (17,18): error CS8651: It is not legal to use nullable reference type 'object[]?' in an as expression; use the underlying type 'object[]' instead. // _ = y as object[] ? ?? y; // error 6 Diagnostic(ErrorCode.ERR_AsNullableType, "object[] ?").WithArguments("object[]").WithLocation(17, 18) ); } [Fact, WorkItem(29318, "https://github.com/dotnet/roslyn/issues/29318")] public void IsOperatorOnNonNullExpression() { var source = @" class C { void M(object o) { if (o is string) { o.ToString(); } else { o.ToString(); } } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); c.VerifyDiagnostics(); } [Fact, WorkItem(29318, "https://github.com/dotnet/roslyn/issues/29318")] public void IsOperatorOnMaybeNullExpression() { var source = @" class C { static void Main(object? o) { if (o is string) { o.ToString(); } else { o.ToString(); // 1 } } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(12, 13) ); } [Fact, WorkItem(29318, "https://github.com/dotnet/roslyn/issues/29318")] public void IsOperatorOnUnconstrainedType() { var source = @" class C { static void M<T>(T t) { if (t is string) { t.ToString(); } else { t.ToString(); // 1 } } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(12, 13) ); } [Fact] public void IsOperator_AffectsNullConditionalOperator() { var source = @" class C { public object? field = null; static void M(C? c) { if (c?.field is string) { c.ToString(); c.field.ToString(); } else { c.ToString(); // 1 } } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(14, 13) ); } [Fact] public void OmittedCall() { var source = @" partial class C { void M(string? x) { OmittedMethod(x); } partial void OmittedMethod(string x); } "; var c = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,23): warning CS8604: Possible null reference argument for parameter 'x' in 'void C.OmittedMethod(string x)'. // OmittedMethod(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "void C.OmittedMethod(string x)").WithLocation(6, 23) ); } [Fact] public void OmittedInitializerCall() { var source = @" using System.Collections; partial class Collection : IEnumerable { void M(string? x) { _ = new Collection() { x }; } IEnumerator IEnumerable.GetEnumerator() => throw null!; partial void Add(string x); } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,32): warning CS8604: Possible null reference argument for parameter 'x' in 'void Collection.Add(string x)'. // _ = new Collection() { x }; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "void Collection.Add(string x)").WithLocation(7, 32) ); } [Fact] public void UpdateArrayRankSpecifier() { var source = @" class C { static void Main() { object[]? x = null; } } "; var tree = Parse(source); var specifier = tree.GetRoot().DescendantNodes().OfType<ArrayRankSpecifierSyntax>().Single(); Assert.Equal("[]", specifier.ToString()); var newSpecifier = specifier.Update( specifier.OpenBracketToken, SyntaxFactory.SeparatedList<ExpressionSyntax>( new[] { SyntaxFactory.LiteralExpression(SyntaxKind.NumericLiteralExpression, SyntaxFactory.Literal(3)) }), specifier.CloseBracketToken); Assert.Equal("[3]", newSpecifier.ToString()); } [Fact] public void TestUnaryNegation() { // This test verifies that we no longer crash hitting an assertion var source = @" public class C<T> { C(C<object> c) => throw null!; void M(bool b) { _ = new C<object>(!b); } public static implicit operator C<T>(T x) => throw null!; } "; var c = CreateCompilation(source, parseOptions: TestOptions.Regular8); c.VerifyDiagnostics(); } [Fact] public void UnconstrainedAndErrorNullableFields() { var source = @" public class C<T> { public T? field; public Unknown? field2; } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (5,12): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // public Unknown? field2; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(5, 12), // (4,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public T? field; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 12)); } [Fact] public void NoNullableAnalysisWithoutNonNullTypes() { var source = @" class C { void M(string z) { z = null; z.ToString(); } } #nullable enable class C2 { void M(string z) { z = null; // 1 z.ToString(); // 2 } } "; var expected = new[] { // (15,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // z = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(15, 13), // (16,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(16, 9) }; var c = CreateCompilation(new[] { source }); c.VerifyDiagnostics(expected); c = CreateCompilation(source, parseOptions: TestOptions.Regular8); c.VerifyDiagnostics(expected); expected = new[] { // (10,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(10, 2) }; var c2 = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); c2.VerifyDiagnostics(expected); } [Fact] public void NonNullTypesOnPartialSymbol() { var source = @" #nullable enable partial class C { #nullable disable partial void M(); } #nullable enable partial class C { #nullable disable partial void M() { } } "; var c = CreateCompilation(new[] { source }); c.VerifyDiagnostics( ); } [Fact] public void SuppressionAsLValue() { var source = @" class C { void M(string? x) { ref string y = ref x; ref string y2 = ref x; (y2! = ref y) = ref y; } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,28): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // ref string y = ref x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("string?", "string").WithLocation(6, 28), // (7,29): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // ref string y2 = ref x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("string?", "string").WithLocation(7, 29), // (8,10): error CS8598: The suppression operator is not allowed in this context // (y2! = ref y) = ref y; Diagnostic(ErrorCode.ERR_IllegalSuppression, "y2").WithLocation(8, 10), // (8,20): warning CS8601: Possible null reference assignment. // (y2! = ref y) = ref y; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(8, 20), // (8,29): warning CS8601: Possible null reference assignment. // (y2! = ref y) = ref y; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(8, 29) ); } [Fact] [WorkItem(31732, "https://github.com/dotnet/roslyn/issues/31732")] public void SuppressionOnUnconstrainedTypeParameter() { var source = @" class C { void M<T>(T t) { t!.ToString(); t.ToString(); } } "; var c = CreateCompilation(new[] { source }); c.VerifyDiagnostics(); c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(31732, "https://github.com/dotnet/roslyn/issues/31732")] public void SuppressionOnNullableValueType() { var source = @" class C { void M(int? i) { i!.Value.ToString(); i.Value.ToString(); } } "; var c = CreateCompilation(new[] { source }); c.VerifyDiagnostics(); c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(31732, "https://github.com/dotnet/roslyn/issues/31732")] public void SuppressionOnNullableValueType_AppliedOnField() { var source = @" public struct S { public string? field; } class C { void M(S? s) { s.Value.field!.ToString(); } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,9): warning CS8629: Nullable value type may be null. // s.Value.field!.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s").WithLocation(10, 9) ); } [Fact] [WorkItem(31732, "https://github.com/dotnet/roslyn/issues/31732")] public void SuppressionOnNullableReferenceType_AppliedOnField() { var source = @" public class C { public string? field; void M(C? c) { c.field!.ToString(); } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // c.field!.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(7, 9) ); } [Fact] [WorkItem(31732, "https://github.com/dotnet/roslyn/issues/31732")] public void SuppressionOnNullableReferenceType_AppliedOnField2() { var source = @" public class C { public string? field; void M1(C? c) { c?.field!.ToString(); c.ToString(); // 1 } void M2(C? c) { c!?.field!.ToString(); c.ToString(); // 2 } void M3(C? c) { _ = c?.field!.ToString()!; c.ToString(); // 3 } void M4(C? c) { (c?.field!.ToString()!).ToString(); c.ToString(); // no warning because 'c' was part of a call receiver in previous line } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c", isSuppressed: false).WithLocation(8, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c", isSuppressed: false).WithLocation(14, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c", isSuppressed: false).WithLocation(20, 9)); } [Fact] [WorkItem(43659, "https://github.com/dotnet/roslyn/issues/43659")] public void SuppressionOnNullableReferenceType_AppliedOnField3() { var source = @" public class C { public string[]? F1; public System.Func<object>? F2; static void M1(C? c) { c?.F1![0].ToString(); c.ToString(); // 1 } static void M2(C? c) { c?.F2!().ToString(); c.ToString(); // 2 } } "; var c = CreateNullableCompilation(source); c.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c", isSuppressed: false).WithLocation(9, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c", isSuppressed: false).WithLocation(14, 9)); } [Fact] [WorkItem(31732, "https://github.com/dotnet/roslyn/issues/31732")] public void SuppressionOnArgument() { var source = @" class C { void M(string? s) { NonNull(s!); s.ToString(); // warn } void NonNull(string s) => throw null!; } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void SuppressionWithoutNonNullTypes() { var source = @" [System.Obsolete("""", true!)] // 1, 2 class C { string x = null!; // 3, 4 static void Main(string z = null!) // 5 { string y = null!; // 6, 7 } } "; var c = CreateCompilation(source); c.VerifyEmitDiagnostics( // (8,16): warning CS0219: The variable 'y' is assigned but its value is never used // string y = null!; // 6, 7 Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "y").WithArguments("y").WithLocation(8, 16), // (5,12): warning CS0414: The field 'C.x' is assigned but its value is never used // string x = null!; // 3, 4 Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "x").WithArguments("C.x").WithLocation(5, 12) ); } [Fact, WorkItem(26812, "https://github.com/dotnet/roslyn/issues/26812")] public void DoubleAssignment() { CSharpCompilation c = CreateCompilation(new[] { @" using static System.Console; class C { static void Main() { string? x; x = x = """"; WriteLine(x.Length); string? y; x = y = """"; WriteLine(x.Length); WriteLine(y.Length); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact, WorkItem(26746, "https://github.com/dotnet/roslyn/issues/26746")] public void TernaryWithConversionFromExpression() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void M() { uint a = 0; uint x = true ? a : 1; uint y = true ? 1 : a; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact, WorkItem(26746, "https://github.com/dotnet/roslyn/issues/26746")] public void TernaryWithImplicitUsedDefinedConversion_ConstantTrue() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void M() { C c = new C(); C x = true ? c : 1; C y = true ? 1 : c; } public static implicit operator C?(int i) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // C y = true ? 1 : c; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "true ? 1 : c").WithLocation(8, 15) ); } [Fact, WorkItem(26746, "https://github.com/dotnet/roslyn/issues/26746")] public void TernaryWithImplicitUsedDefinedConversion_ConstantFalse() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void M() { C c = new C(); C x = false ? c : 1; C y = false ? 1 : c; } public static implicit operator C?(int i) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // C x = false ? c : 1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "false ? c : 1").WithLocation(7, 15) ); } [Fact, WorkItem(26746, "https://github.com/dotnet/roslyn/issues/26746")] public void TernaryWithImplicitUsedDefinedConversion_NotConstant() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void M(bool b) { C c = new C(); C x = b ? c : 1; C y = b ? 1 : c; } public static implicit operator C?(int i) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // C x = b ? c : 1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b ? c : 1").WithLocation(7, 15), // (8,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // C y = b ? 1 : c; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b ? 1 : c").WithLocation(8, 15) ); } [Fact, WorkItem(26746, "https://github.com/dotnet/roslyn/issues/26746")] public void TernaryWithImplicitUsedDefinedConversion2() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void M() { C c = null!; int x = true ? c : 1; int y = true ? 1 : c; C? c2 = null; int x2 = true ? c2 : 1; int y2 = true ? 1 : c2; } public static implicit operator int(C i) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,25): warning CS8604: Possible null reference argument for parameter 'i' in 'C.implicit operator int(C i)'. // int x2 = true ? c2 : 1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c2").WithArguments("i", "C.implicit operator int(C i)").WithLocation(11, 25) ); } [Fact] public void AnnotationWithoutNonNullTypes() { var source = @" class C<T> where T : class { static string? field = M2(out string? x1); // warn 1 and 2 static string? P // warn 3 { get { string? x2 = null; // warn 4 return x2; } } static string? MethodWithLocalFunction() // warn 5 { string? x3 = local(null); // warn 6 return x3; string? local(C<string?>? x) // warn 7, 8 and 9 { string? x4 = null; // warn 10 return x4; } } static string? Lambda() // warn 11 { System.Func<string?, string?> x5 = (string? x) => // warn 12, 13 and 14 { string? x6 = null; // warn 15 return x6; }; return x5(null); } static string M2(out string? x4) => throw null!; // warn 16 static string M3(C<string?> x, C<string> y) => throw null!; // warn 17 delegate string? MyDelegate(C<string?> x); // warn 18 and 19 event MyDelegate? Event; // warn 20 void M4() { Event(new C<string?>()); } // warn 21 class D<T2> where T2 : T? { } // warn 22 class D2 : C<string?> { } // warn 23 public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 class D3 { D3(C<T?> x) => throw null!; // warn 26 } public string? this[C<string?> x] { get => throw null!; } // warn 27 and 28 } "; var expectedDiagnostics = new[] { // (36,21): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // event MyDelegate? Event; // warn 20 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(36, 21), // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string? P // warn 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18), // (13,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string? MethodWithLocalFunction() // warn 5 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 18), // (24,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string? Lambda() // warn 11 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(24, 18), // (33,32): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string M2(out string? x4) => throw null!; // warn 16 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(33, 32), // (34,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string M3(C<string?> x, C<string> y) => throw null!; // warn 17 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(34, 30), // (40,47): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(40, 47), // (40,46): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(40, 46), // (40,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(40, 22), // (40,21): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(40, 21), // (45,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public string? this[C<string?> x] { get => throw null!; } // warn 27 and 28 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(45, 33), // (45,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public string? this[C<string?> x] { get => throw null!; } // warn 27 and 28 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(45, 18), // (43,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // D3(C<T?> x) => throw null!; // warn 26 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(43, 15), // (43,14): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // D3(C<T?> x) => throw null!; // warn 26 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(43, 14), // (35,20): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // delegate string? MyDelegate(C<string?> x); // warn 18 and 19 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(35, 20), // (35,41): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // delegate string? MyDelegate(C<string?> x); // warn 18 and 19 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(35, 41), // (38,29): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // class D<T2> where T2 : T? { } // warn 22 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(38, 29), // (38,28): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class D<T2> where T2 : T? { } // warn 22 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(38, 28), // (39,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // class D2 : C<string?> { } // warn 23 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(39, 24), // (4,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string? field = M2(out string? x1); // warn 1 and 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 18), // (4,41): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static string? field = M2(out string? x1); // warn 1 and 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 41), // (9,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? x2 = null; // warn 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 19), // (15,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? x3 = local(null); // warn 6 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(15, 15), // (20,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? x4 = null; // warn 10 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(20, 19), // (18,31): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? local(C<string?>? x) // warn 7, 8 and 9 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 31), // (18,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? local(C<string?>? x) // warn 7, 8 and 9 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 33), // (18,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? local(C<string?>? x) // warn 7, 8 and 9 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 15), // (26,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // System.Func<string?, string?> x5 = (string? x) => // warn 12, 13 and 14 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(26, 27), // (26,36): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // System.Func<string?, string?> x5 = (string? x) => // warn 12, 13 and 14 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(26, 36), // (26,51): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // System.Func<string?, string?> x5 = (string? x) => // warn 12, 13 and 14 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(26, 51), // (28,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string? x6 = null; // warn 15 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(28, 19), // (37,35): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M4() { Event(new C<string?>()); } // warn 21 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(37, 35) }; var c = CreateCompilation(source, parseOptions: TestOptions.Regular8); c.VerifyDiagnostics(expectedDiagnostics); var c2 = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); c2.VerifyDiagnostics( // (18,25): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // string? local(C<string?>? x) // warn 7, 8 and 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("C<T>", "T", "string?").WithLocation(18, 25), // (34,33): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // static string M3(C<string?> x, C<string> y) => throw null!; // warn 17 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "x").WithArguments("C<T>", "T", "string?").WithLocation(34, 33), // (35,35): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // delegate string? MyDelegate(C<string?> x); // warn 18 and 19 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("C<T>", "T", "string?").WithLocation(35, 35), // (37,17): warning CS8602: Dereference of a possibly null reference. // void M4() { Event(new C<string?>()); } // warn 21 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Event").WithLocation(37, 17), // (37,29): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // void M4() { Event(new C<string?>()); } // warn 21 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("C<T>", "T", "string?").WithLocation(37, 29), // (39,11): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // class D2 : C<string?> { } // warn 23 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "D2").WithArguments("C<T>", "T", "string?").WithLocation(39, 11), // (40,34): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "+").WithArguments("C<T>", "T", "T?").WithLocation(40, 34), // (40,50): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // public static C<T?> operator +(C<T> x, C<T?> y) => throw null!; // warn 24 and 25 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "y").WithArguments("C<T>", "T", "T?").WithLocation(40, 50), // (43,18): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // D3(C<T?> x) => throw null!; // warn 26 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "x").WithArguments("C<T>", "T", "T?").WithLocation(43, 18), // (45,36): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // public string? this[C<string?> x] { get => throw null!; } // warn 27 and 28 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "x").WithArguments("C<T>", "T", "string?").WithLocation(45, 36) ); var c3 = CreateCompilation(new[] { source }, options: WithNullableDisable(), parseOptions: TestOptions.Regular8); c3.VerifyDiagnostics(expectedDiagnostics); } [Fact] public void AnnotationWithoutNonNullTypes_GenericType() { var source = @" public class C<T> where T : class { public T? M(T? x1) // warn 1 and 2 { T? y1 = x1; // warn 3 return y1; } } public class E<T> where T : struct { public T? M(T? x2) { T? y2 = x2; return y2; } } "; CSharpCompilation c = CreateCompilation(source, parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (4,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public T? M(T? x1) // warn 1 and 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 18), // (4,17): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public T? M(T? x1) // warn 1 and 2 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 17), // (4,13): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public T? M(T? x1) // warn 1 and 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 13), // (4,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public T? M(T? x1) // warn 1 and 2 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 12), // (6,10): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? y1 = x1; // warn 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 10), // (6,9): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? y1 = x1; // warn 3 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(6, 9) ); var client = @" class Client { void M(C<string> c) { c.M("""").ToString(); } } "; var comp2 = CreateCompilation(new[] { client }, options: WithNullableEnable(), references: new[] { c.ToMetadataReference() }); comp2.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // c.M("").ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"c.M("""")").WithLocation(6, 9) ); c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics(); comp2 = CreateCompilation(new[] { client }, options: WithNullableEnable(), references: new[] { c.EmitToImageReference() }); comp2.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // c.M("").ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"c.M("""")").WithLocation(6, 9) ); comp2 = CreateCompilation(new[] { client }, options: WithNullableEnable(), references: new[] { c.ToMetadataReference() }); comp2.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // c.M("").ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"c.M("""")").WithLocation(6, 9) ); } [Fact] public void AnnotationWithoutNonNullTypes_AttributeArgument() { var source = @"class AAttribute : System.Attribute { internal AAttribute(object o) { } } class B<T> { } [A(typeof(object?))] // 1 class C1 { } [A(typeof(int?))] class C2 { } [A(typeof(B<object?>))] // 2 class C3 { } [A(typeof(B<int?>))] class C4 { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,4): error CS8639: The typeof operator cannot be used on a nullable reference type // [A(typeof(object?))] // 1 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(object?)").WithLocation(6, 4), // (6,17): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // [A(typeof(object?))] // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 17), // (10,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // [A(typeof(B<object?>))] // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 19)); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,4): error CS8639: The typeof operator cannot be used on a nullable reference type // [A(typeof(object?))] // 1 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(object?)").WithLocation(6, 4)); } [Fact] public void Nullable_False_InCSharp7() { var comp = CreateCompilation("", options: WithNullableDisable(), parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); } [Fact] public void NullableOption() { var comp = CreateCompilation("", options: WithNullable(NullableContextOptions.Enable), parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.3", "8.0").WithLocation(1, 1) ); comp = CreateCompilation("", options: WithNullable(NullableContextOptions.Warnings), parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // error CS8630: Invalid 'NullableContextOptions' value: 'Warnings' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Warnings", "7.3", "8.0").WithLocation(1, 1) ); comp = CreateCompilation("", options: WithNullable(NullableContextOptions.Disable), parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(); comp = CreateCompilation("", options: WithNullable(NullableContextOptions.Enable), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation("", options: WithNullable(NullableContextOptions.Warnings), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation("", options: WithNullable(NullableContextOptions.Disable), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(new string[] { }, options: WithNullable(NullableContextOptions.Enable), parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(); comp = CreateCompilation(new string[] { }, options: WithNullable(NullableContextOptions.Enable), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(new string[] { }, options: WithNullable(NullableContextOptions.Warnings), parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(); comp = CreateCompilation(new string[] { }, options: WithNullable(NullableContextOptions.Warnings), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(new string[] { }, options: WithNullable(NullableContextOptions.Disable), parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(); comp = CreateCompilation(new string[] { }, options: WithNullable(NullableContextOptions.Disable), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void NullableAttribute_NotRequiredCSharp7_01() { var source = @"using System.Threading.Tasks; class C { static async Task<string> F() { return await Task.FromResult(default(string)); } }"; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Regular7); comp.VerifyEmitDiagnostics(); } [Fact] public void NullableAttribute_NotRequiredCSharp7_02() { var source = @"using System; using System.Threading.Tasks; class C { static async Task F<T>(Func<Task> f) { await G(async () => { await f(); return default(object); }); } static async Task<TResult> G<TResult>(Func<Task<TResult>> f) { throw new NotImplementedException(); } }"; var comp = CreateCompilationWithMscorlib45(source, parseOptions: TestOptions.Regular7); comp.VerifyEmitDiagnostics( // (13,32): 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<TResult> G<TResult>(Func<Task<TResult>> f) Diagnostic(ErrorCode.WRN_AsyncLacksAwaits, "G").WithLocation(13, 32)); } [Fact, WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26618")] public void SuppressionOnNullConvertedToConstrainedTypeParameterType() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public T M<T>() where T : C { return null!; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void MissingInt() { var source0 = @"namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Enum { } public class Attribute { } }"; var comp0 = CreateEmptyCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"enum E { A } class C { int F() => (int)E.A; }"; var comp = CreateEmptyCompilation( source, references: new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyEmitDiagnostics( // (1,6): error CS0518: Predefined type 'System.Int32' is not defined or imported // enum E { A } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "E").WithArguments("System.Int32").WithLocation(1, 6), // (4,5): error CS0518: Predefined type 'System.Int32' is not defined or imported // int F() => (int)E.A; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(4, 5), // (4,17): error CS0518: Predefined type 'System.Int32' is not defined or imported // int F() => (int)E.A; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "int").WithArguments("System.Int32").WithLocation(4, 17)); } [Fact] public void MissingNullable() { var source = @" namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Boolean { } public struct Enum { } public class Attribute { } }"; var source2 = @" class C<T> where T : struct { void M() { T? local = null; _ = local; } } "; var comp = CreateEmptyCompilation(new[] { source, source2 }); comp.VerifyDiagnostics( // (6,9): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // T? local = null; Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T?").WithArguments("System.Nullable`1").WithLocation(6, 9) ); var source3 = @" class C<T> where T : struct { void M(T? nullable) { } } "; var comp2 = CreateEmptyCompilation(new[] { source, source3 }); comp2.VerifyDiagnostics( // (4,12): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // void M(T? nullable) { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T?").WithArguments("System.Nullable`1").WithLocation(4, 12) ); var source4 = @" class C<T> where T : struct { void M<U>() where U : T? { } } "; var comp3 = CreateEmptyCompilation(new[] { source, source4 }); comp3.VerifyDiagnostics( // (4,27): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // void M<U>() where U : T? { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "T?").WithArguments("System.Nullable`1").WithLocation(4, 27), // (4,12): error CS0518: Predefined type 'System.Nullable`1' is not defined or imported // void M<U>() where U : T? { } Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound, "U").WithArguments("System.Nullable`1").WithLocation(4, 12) ); } [Fact] public void UnannotatedAssemblies_01() { var source0 = @"public class A { public static void F(string s) { } }"; var source1 = @"class B { static void Main() { A.F(string.Empty); A.F(null); } }"; TypeWithAnnotations getParameterType(CSharpCompilation c) => c.GetMember<MethodSymbol>("A.F").Parameters[0].TypeWithAnnotations; // 7.0 library var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var compRefs0 = new MetadataReference[] { new CSharpCompilationReference(comp0) }; var metadataRefs0 = new[] { comp0.EmitToImageReference() }; Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp0).NullableAnnotation); // ... used in 7.0. var comp1 = CreateCompilation(source1, references: compRefs0, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(source1, references: metadataRefs0, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); // ... used in 8.0. comp1 = CreateCompilation(source1, references: compRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(source1, references: metadataRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); // 8.0 library comp0 = CreateCompilation(source0); comp0.VerifyDiagnostics(); compRefs0 = new MetadataReference[] { new CSharpCompilationReference(comp0) }; metadataRefs0 = new[] { comp0.EmitToImageReference() }; Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp0).NullableAnnotation); // ... used in 7.0. comp1 = CreateCompilation(source1, references: compRefs0, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(source1, references: metadataRefs0, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); // ... used in 8.0. comp1 = CreateCompilation(source1, references: compRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(source1, references: metadataRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: compRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: metadataRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, getParameterType(comp1).NullableAnnotation); // 8.0 library comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); comp0.VerifyDiagnostics(); compRefs0 = new MetadataReference[] { new CSharpCompilationReference(comp0) }; metadataRefs0 = new[] { comp0.EmitToImageReference() }; Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp0).NullableAnnotation); // ... used in 7.0. comp1 = CreateCompilation(source1, references: compRefs0, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(source1, references: metadataRefs0, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp1).NullableAnnotation); // ... used in 8.0. comp1 = CreateCompilation(source1, references: compRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(source1, references: metadataRefs0); comp1.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: compRefs0); comp1.VerifyDiagnostics( // (6,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // A.F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 13)); Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp1).NullableAnnotation); comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: metadataRefs0); comp1.VerifyDiagnostics( // (6,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // A.F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 13)); Assert.Equal(NullableAnnotation.NotAnnotated, getParameterType(comp1).NullableAnnotation); } [Fact] public void UnannotatedAssemblies_02() { var source0 = @"#pragma warning disable 67 public delegate void D(); public class C { public object F; public event D E; public object P => null; public object this[object o] => null; public object M(object o) => null; }"; var source1 = @"class P { static void F(C c) { object o; o = c.F; c.E += null; o = c.P; o = c[null]; o = c.M(null); } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); void verify(CSharpCompilation c) { c.VerifyDiagnostics(); Assert.Equal(NullableAnnotation.Oblivious, c.GetMember<FieldSymbol>("C.F").TypeWithAnnotations.NullableAnnotation); Assert.Equal(NullableAnnotation.Oblivious, c.GetMember<EventSymbol>("C.E").TypeWithAnnotations.NullableAnnotation); Assert.Equal(NullableAnnotation.Oblivious, c.GetMember<PropertySymbol>("C.P").TypeWithAnnotations.NullableAnnotation); var indexer = c.GetMember<PropertySymbol>("C.this[]"); Assert.Equal(NullableAnnotation.Oblivious, indexer.TypeWithAnnotations.NullableAnnotation); Assert.Equal(NullableAnnotation.Oblivious, indexer.Parameters[0].TypeWithAnnotations.NullableAnnotation); var method = c.GetMember<MethodSymbol>("C.M"); Assert.Equal(NullableAnnotation.Oblivious, method.ReturnTypeWithAnnotations.NullableAnnotation); Assert.Equal(NullableAnnotation.Oblivious, method.Parameters[0].TypeWithAnnotations.NullableAnnotation); } var comp1A = CreateCompilation(source1, references: new MetadataReference[] { new CSharpCompilationReference(comp0) }); verify(comp1A); var comp1B = CreateCompilation(source1, references: new[] { comp0.EmitToImageReference() }); verify(comp1B); } [Fact] public void UnannotatedAssemblies_03() { var source0 = @"#pragma warning disable 67 public class C { public (object, object) F; public (object, object) P => (null, null); public (object, object) M((object, object) o) => o; }"; var source1 = @"class P { static void F(C c) { (object, object) t; t = c.F; t = c.P; t = c.M((null, null)); } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); void verifyTuple(TypeWithAnnotations type) { var tuple = (NamedTypeSymbol)type.Type; Assert.Equal(NullableAnnotation.Oblivious, tuple.TupleElements[0].TypeWithAnnotations.NullableAnnotation); Assert.Equal(NullableAnnotation.Oblivious, tuple.TupleElements[1].TypeWithAnnotations.NullableAnnotation); } void verify(CSharpCompilation c) { c.VerifyDiagnostics(); verifyTuple(c.GetMember<FieldSymbol>("C.F").TypeWithAnnotations); verifyTuple(c.GetMember<PropertySymbol>("C.P").TypeWithAnnotations); var method = c.GetMember<MethodSymbol>("C.M"); verifyTuple(method.ReturnTypeWithAnnotations); verifyTuple(method.Parameters[0].TypeWithAnnotations); } var comp1A = CreateCompilation(source1, references: new[] { new CSharpCompilationReference(comp0) }); verify(comp1A); var comp1B = CreateCompilation(source1, references: new[] { comp0.EmitToImageReference() }); verify(comp1B); } [Fact] public void UnannotatedAssemblies_04() { var source = @"class A { } class B : A { } interface I<T> where T : A { } abstract class C<T> where T : A { internal abstract void M<U>() where U : T; } class D : C<B>, I<B> { internal override void M<T>() { } }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var derivedType = comp.GetMember<NamedTypeSymbol>("D"); var baseType = derivedType.BaseTypeNoUseSiteDiagnostics; var constraintType = baseType.TypeParameters.Single().ConstraintTypesNoUseSiteDiagnostics.Single(); Assert.Equal(NullableAnnotation.Oblivious, constraintType.NullableAnnotation); var interfaceType = derivedType.Interfaces().Single(); constraintType = interfaceType.TypeParameters.Single().ConstraintTypesNoUseSiteDiagnostics.Single(); Assert.Equal(NullableAnnotation.Oblivious, constraintType.NullableAnnotation); var method = baseType.GetMember<MethodSymbol>("M"); constraintType = method.TypeParameters.Single().ConstraintTypesNoUseSiteDiagnostics.Single(); Assert.Equal(NullableAnnotation.Oblivious, constraintType.NullableAnnotation); } [Fact] public void UnannotatedAssemblies_05() { var source = @"interface I<T> { I<object[]> F(I<T> t); } class C : I<string> { I<object[]> I<string>.F(I<string> s) => null; }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var type = comp.GetMember<NamedTypeSymbol>("C"); var interfaceType = type.Interfaces().Single(); var typeArg = interfaceType.TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); Assert.Equal(NullableAnnotation.Oblivious, typeArg.NullableAnnotation); var method = type.GetMember<MethodSymbol>("I<System.String>.F"); Assert.Equal(NullableAnnotation.Oblivious, method.ReturnTypeWithAnnotations.NullableAnnotation); typeArg = ((NamedTypeSymbol)method.ReturnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); Assert.Equal(NullableAnnotation.Oblivious, typeArg.NullableAnnotation); var parameter = method.Parameters.Single(); Assert.Equal(NullableAnnotation.Oblivious, parameter.TypeWithAnnotations.NullableAnnotation); typeArg = ((NamedTypeSymbol)parameter.Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics.Single(); Assert.Equal(NullableAnnotation.Oblivious, typeArg.NullableAnnotation); } [Fact] public void UnannotatedAssemblies_06() { var source0 = @"public class C<T> { public T F; } public class C { public static C<T> Create<T>(T t) => new C<T>(); }"; var source1 = @"class P { static void F(object x, object? y) { object z; z = C.Create(x).F; z = C.Create(y).F; } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { comp0.EmitToImageReference() }); comp1.VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // z = C.Create(y).F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "C.Create(y).F").WithLocation(7, 13)); } [Fact] public void UnannotatedAssemblies_07() { var source0 = @"public interface I { object F(object o); }"; var source1 = @"class A1 : I { object I.F(object? o) => new object(); } class A2 : I { object? I.F(object o) => o; } class B1 : I { public object F(object? o) => new object(); } class B2 : I { public object? F(object o) => o; } class C1 { public object F(object? o) => new object(); } class C2 { public object? F(object o) => o; } class D1 : C1, I { } class D2 : C2, I { } class P { static void F(object? x, A1 a1, A2 a2) { object y; y = ((I)a1).F(x); y = ((I)a2).F(x); } static void F(object? x, B1 b1, B2 b2) { object y; y = b1.F(x); y = b2.F(x); y = ((I)b1).F(x); y = ((I)b2).F(x); } static void F(object? x, D1 d1, D2 d2) { object y; y = d1.F(x); y = d2.F(x); y = ((I)d1).F(x); y = ((I)d2).F(x); } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new MetadataReference[] { new CSharpCompilationReference(comp0) }); comp1.VerifyDiagnostics( // (43,18): warning CS8604: Possible null reference argument for parameter 'o' in 'object? B2.F(object o)'. // y = b2.F(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("o", "object? B2.F(object o)").WithLocation(43, 18), // (43,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = b2.F(x); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b2.F(x)").WithLocation(43, 13), // (51,18): warning CS8604: Possible null reference argument for parameter 'o' in 'object? C2.F(object o)'. // y = d2.F(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("o", "object? C2.F(object o)").WithLocation(51, 18), // (51,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = d2.F(x); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "d2.F(x)").WithLocation(51, 13)); comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { comp0.EmitToImageReference() }); comp1.VerifyDiagnostics( // (43,18): warning CS8604: Possible null reference argument for parameter 'o' in 'object? B2.F(object o)'. // y = b2.F(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("o", "object? B2.F(object o)").WithLocation(43, 18), // (43,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = b2.F(x); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b2.F(x)").WithLocation(43, 13), // (51,18): warning CS8604: Possible null reference argument for parameter 'o' in 'object? C2.F(object o)'. // y = d2.F(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("o", "object? C2.F(object o)").WithLocation(51, 18), // (51,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = d2.F(x); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "d2.F(x)").WithLocation(51, 13)); } [Fact] public void UnannotatedAssemblies_08() { var source0 = @"public interface I { object? F(object? o); object G(object o); }"; var source1 = @"public class A : I { object I.F(object o) => null; object I.G(object o) => null; } public class B : I { public object F(object o) => null; public object G(object o) => null; } public class C { public object F(object o) => null; public object G(object o) => null; } public class D : C { }"; var source2 = @"class P { static void F(object o, A a) { ((I)a).F(o).ToString(); ((I)a).G(null).ToString(); } static void F(object o, B b) { b.F(o).ToString(); b.G(null).ToString(); ((I)b).F(o).ToString(); ((I)b).G(null).ToString(); } static void F(object o, D d) { d.F(o).ToString(); d.G(null).ToString(); ((I)d).F(o).ToString(); ((I)d).G(null).ToString(); } }"; var comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var comp1 = CreateCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var comp2A = CreateCompilation(source2, references: new[] { ref0, ref1 }, parseOptions: TestOptions.Regular7); comp2A.VerifyDiagnostics(); var comp2B = CreateCompilation(source2, references: new[] { ref0, ref1 }); comp2B.VerifyDiagnostics(); var comp2C = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { ref0, ref1 }); comp2C.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // ((I)a).F(o).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((I)a).F(o)").WithLocation(5, 9), // (6,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((I)a).G(null).ToString(); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 18), // (12,9): warning CS8602: Dereference of a possibly null reference. // ((I)b).F(o).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((I)b).F(o)").WithLocation(12, 9), // (13,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((I)b).G(null).ToString(); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 18), // (19,9): warning CS8602: Dereference of a possibly null reference. // ((I)d).F(o).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((I)d).F(o)").WithLocation(19, 9), // (20,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((I)d).G(null).ToString(); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 18)); var comp2D = CreateCompilation(new[] { source2 }, options: WithNullableDisable(), references: new[] { ref0, ref1 }); comp2D.VerifyDiagnostics(); } [Fact] public void UnannotatedAssemblies_09() { var source0 = @"public abstract class A { public abstract object? F(object x, object? y); }"; var source1 = @"public abstract class B : A { public abstract override object F(object x, object y); public abstract object G(object x, object y); }"; var source2 = @"class C1 : B { public override object F(object x, object y) => x; public override object G(object x, object y) => x; } class C2 : B { public override object? F(object? x, object? y) => x; public override object? G(object? x, object? y) => x; } class P { static void F(bool b, object? x, object y, C1 c) { if (b) c.F(x, y).ToString(); if (b) c.G(x, y).ToString(); ((B)c).F(x, y).ToString(); ((B)c).G(x, y).ToString(); ((A)c).F(x, y).ToString(); } static void F(object? x, object y, C2 c) { c.F(x, y).ToString(); c.G(x, y).ToString(); ((B)c).F(x, y).ToString(); ((B)c).G(x, y).ToString(); ((A)c).F(x, y).ToString(); } }"; var comp0 = CreateCompilation(source0); comp0.VerifyDiagnostics( // (3,47): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public abstract object? F(object x, object? y); Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 47), // (3,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public abstract object? F(object x, object? y); Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 27) ); var ref0 = comp0.EmitToImageReference(); var comp1 = CreateCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var comp2 = CreateCompilation(source2, references: new[] { ref0, ref1 }); comp2.VerifyDiagnostics( // (9,37): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override object? G(object? x, object? y) => x; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 37), // (9,48): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override object? G(object? x, object? y) => x; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 48), // (9,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override object? G(object? x, object? y) => x; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 27), // (21,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F(object? x, object y, C2 c) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 25), // (13,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F(bool b, object? x, object y, C1 c) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 33), // (8,37): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override object? F(object? x, object? y) => x; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 37), // (8,48): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override object? F(object? x, object? y) => x; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 48), // (8,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override object? F(object? x, object? y) => x; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 27) ); comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); comp0.VerifyDiagnostics(); ref0 = comp0.EmitToImageReference(); comp1 = CreateCompilation(source1, references: new[] { ref0 }, parseOptions: TestOptions.Regular7); comp1.VerifyDiagnostics(); ref1 = comp1.EmitToImageReference(); comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { ref0, ref1 }); comp2.VerifyDiagnostics( // (15,20): warning CS8604: Possible null reference argument for parameter 'x' in 'object C1.F(object x, object y)'. // if (b) c.F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "object C1.F(object x, object y)").WithLocation(15, 20), // (16,20): warning CS8604: Possible null reference argument for parameter 'x' in 'object C1.G(object x, object y)'. // if (b) c.G(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "object C1.G(object x, object y)").WithLocation(16, 20), // (19,18): warning CS8604: Possible null reference argument for parameter 'x' in 'object? A.F(object x, object? y)'. // ((A)c).F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "object? A.F(object x, object? y)").WithLocation(19, 18), // (19,9): warning CS8602: Dereference of a possibly null reference. // ((A)c).F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((A)c).F(x, y)").WithLocation(19, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // c.F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F(x, y)").WithLocation(23, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // c.G(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.G(x, y)").WithLocation(24, 9), // (27,18): warning CS8604: Possible null reference argument for parameter 'x' in 'object? A.F(object x, object? y)'. // ((A)c).F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "object? A.F(object x, object? y)").WithLocation(27, 18), // (27,9): warning CS8602: Dereference of a possibly null reference. // ((A)c).F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((A)c).F(x, y)").WithLocation(27, 9)); } [Fact] public void UnannotatedAssemblies_10() { var source0 = @"public abstract class A<T> { public T F; } public sealed class B : A<object> { }"; var source1 = @"class C { static void Main() { B b = new B(); b.F = null; } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var comp1 = CreateCompilation(source1, references: new MetadataReference[] { new CSharpCompilationReference(comp0) }); comp1.VerifyDiagnostics(); comp1 = CreateCompilation(source1, references: new[] { comp0.EmitToImageReference() }); comp1.VerifyDiagnostics(); } [Fact] public void Embedded_WithObsolete() { string source = @" namespace Microsoft.CodeAnalysis { [Embedded] [System.Obsolete(""obsolete"")] class EmbeddedAttribute : System.Attribute { public EmbeddedAttribute() { } } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); Assert.False(comp.GetMember("Microsoft.CodeAnalysis.EmbeddedAttribute").IsImplicitlyDeclared); } [Fact] public void NonNullTypes_Cycle5() { string source = @" namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] class SomeAttribute : Attribute { public SomeAttribute() { } public int Property { get; set; } } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NonNullTypes_Cycle12() { string source = @" [System.Flags] enum E { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NonNullTypes_Cycle13() { string source = @" interface I { } [System.Obsolete(nameof(I2))] interface I2 : I { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NonNullTypes_Cycle15() { string lib_cs = "public class Base { }"; var lib = CreateCompilation(lib_cs, assemblyName: "lib"); string lib2_cs = "public class C : Base { }"; var lib2 = CreateCompilation(lib2_cs, references: new[] { lib.EmitToImageReference() }, assemblyName: "lib2"); string source_cs = @" [D] class DAttribute : C { } "; var comp = CreateCompilation(source_cs, references: new[] { lib2.EmitToImageReference() }); comp.VerifyDiagnostics( // (3,20): error CS0012: The type 'Base' is defined in an assembly that is not referenced. You must add a reference to assembly 'lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // class DAttribute : C { } Diagnostic(ErrorCode.ERR_NoTypeDef, "C").WithArguments("Base", "lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(3, 20), // (2,2): error CS0012: The type 'Base' is defined in an assembly that is not referenced. You must add a reference to assembly 'lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // [D] Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("Base", "lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 2), // (2,2): error CS0012: The type 'Base' is defined in an assembly that is not referenced. You must add a reference to assembly 'lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // [D] Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("Base", "lib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(2, 2) ); } [Fact] public void NonNullTypes_Cycle16() { string source = @" using System; [AttributeUsage(AttributeTargets.Property)] class AttributeWithProperty : System.ComponentModel.DisplayNameAttribute { public override string DisplayName { get => throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NonNullTypes_OnFields() { var obliviousLib = @" public class Oblivious { public static string s; } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); var lib = @" #nullable enable #pragma warning disable 8618 public class External { public static string s; public static string? ns; #nullable disable public static string fs; #nullable disable public static string? fns; } "; var libComp = CreateCompilation(new[] { lib }, options: WithNullableEnable()); libComp.VerifyDiagnostics( // (13,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static string? fns; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 25) ); var source = @" #nullable disable public class OuterA { #nullable enable public class A { public static string s; public static string? ns; } } // NonNullTypes(true) by default public class B { public static string s; public static string? ns; } #nullable disable public class C { #nullable enable public static string s; #nullable enable public static string? ns; } #nullable disable public class OuterD { public class D { #nullable enable public static string s; #nullable enable public static string? ns; } } public class Oblivious2 { #nullable disable public static string s; #nullable disable public static string? ns; } #nullable enable class E { public void M() { Oblivious.s /*T:string!*/ = null; External.s /*T:string!*/ = null; // warn 1 External.ns /*T:string?*/ = null; External.fs /*T:string!*/ = null; External.fns /*T:string?*/ = null; OuterA.A.s /*T:string!*/ = null; // warn 2 OuterA.A.ns /*T:string?*/ = null; B.s /*T:string!*/ = null; // warn 3 B.ns /*T:string?*/ = null; C.s /*T:string!*/ = null; // warn 4 C.ns /*T:string?*/ = null; OuterD.D.s /*T:string!*/ = null; // warn 5 OuterD.D.ns /*T:string?*/ = null; Oblivious2.s /*T:string!*/ = null; Oblivious2.ns /*T:string?*/ = null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference(), libComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (10,30): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(10, 30), // (18,26): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(18, 26), // (26,26): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(26, 26), // (38,30): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(38, 30), // (49,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static string? ns; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(49, 25), // (58,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // External.s /*T:string!*/ = null; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(58, 36), // (64,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterA.A.s /*T:string!*/ = null; // warn 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(64, 36), // (67,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // B.s /*T:string!*/ = null; // warn 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(67, 29), // (70,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // C.s /*T:string!*/ = null; // warn 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(70, 29), // (73,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterD.D.s /*T:string!*/ = null; // warn 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(73, 36) ); } [Fact] public void SuppressedNullConvertedToUnconstrainedT() { var source = @" public class List2<T> { public T Item { get; set; } = null!; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (2,55): error CS0403: Cannot convert null to type parameter 'T' because it could be a non-nullable value type. Consider using 'default(T)' instead. // public class List2<T> { public T Item { get; set; } = null!; } Diagnostic(ErrorCode.ERR_TypeVarCantBeNull, "null").WithArguments("T").WithLocation(2, 55) ); } [Fact] public void NonNullTypes_OnFields_Nested() { var obliviousLib = @" public class List1<T> { public T Item { get; set; } = default(T); } public class Oblivious { public static List1<string> s; } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); var lib = @" #pragma warning disable 8618 using System.Diagnostics.CodeAnalysis; public class List2<T> { public T Item { get; set; } = default!; } public class External { public static List2<string> s; public static List2<string?> ns; #nullable disable public static List2<string> fs; #nullable disable public static List2<string?> fns; } "; var libComp = CreateCompilation(new[] { lib }, options: WithNullableEnable()); var source = @" public class List3<T> { public T Item { get; set; } = default!; } #nullable disable public class OuterA { #nullable enable public class A { public static List3<string> s; public static List3<string?> ns; } } // NonNullTypes(true) by default public class B { public static List3<string> s; public static List3<string?> ns; } #nullable disable public class OuterD { public class D { #nullable enable public static List3<string> s; #nullable enable public static List3<string?> ns; } } #nullable disable public class Oblivious2 { public static List3<string> s; public static List3<string?> ns; } #nullable enable class E { public void M() { Oblivious.s.Item /*T:string!*/ = null; External.s.Item /*T:string!*/ = null; // warn 1 External.ns.Item /*T:string?*/ = null; External.fs.Item /*T:string!*/ = null; External.fns.Item /*T:string?*/ = null; OuterA.A.s.Item /*T:string!*/ = null; // warn 2 OuterA.A.ns.Item /*T:string?*/ = null; B.s.Item /*T:string!*/ = null; // warn 3 B.ns.Item /*T:string?*/ = null; OuterD.D.s.Item /*T:string!*/ = null; // warn 4 OuterD.D.ns.Item /*T:string?*/ = null; Oblivious2.s.Item /*T:string!*/ = null; Oblivious2.ns.Item /*T:string?*/ = null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference(), libComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (11,37): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static List3<string> s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(11, 37), // (12,38): warning CS8618: Non-nullable field 'ns' is uninitialized. Consider declaring the field as nullable. // public static List3<string?> ns; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "ns").WithArguments("field", "ns").WithLocation(12, 38), // (19,33): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static List3<string> s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(19, 33), // (20,34): warning CS8618: Non-nullable field 'ns' is uninitialized. Consider declaring the field as nullable. // public static List3<string?> ns; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "ns").WithArguments("field", "ns").WithLocation(20, 34), // (29,37): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static List3<string> s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(29, 37), // (31,38): warning CS8618: Non-nullable field 'ns' is uninitialized. Consider declaring the field as nullable. // public static List3<string?> ns; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "ns").WithArguments("field", "ns").WithLocation(31, 38), // (39,31): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public static List3<string?> ns; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(39, 31), // (48,41): warning CS8625: Cannot convert null literal to non-nullable reference type. // External.s.Item /*T:string!*/ = null; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(48, 41), // (54,41): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterA.A.s.Item /*T:string!*/ = null; // warn 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(54, 41), // (57,34): warning CS8625: Cannot convert null literal to non-nullable reference type. // B.s.Item /*T:string!*/ = null; // warn 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(57, 34), // (60,41): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterD.D.s.Item /*T:string!*/ = null; // warn 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(60, 41)); } [Fact] public void NonNullTypes_OnFields_Tuples() { var obliviousLib = @" public class Oblivious { public static (string s, string s2) t; } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); var lib = @" public class External { public static (string s, string? ns) t; } "; var libComp = CreateCompilation(new[] { lib }, options: WithNullableEnable()); var source = @" #nullable disable public class OuterA { #nullable enable public class A { public static (string s, string? ns) t; } } // NonNullTypes(true) by default public class B { public static (string s, string? ns) t; } #nullable disable public class OuterD { public class D { #nullable enable public static (string s, string? ns) t; } } #nullable disable public class Oblivious2 { public static (string s, string? ns) t; } #nullable enable class E { public void M() { Oblivious.t.s /*T:string!*/ = null; External.t.s /*T:string!*/ = null; // warn 1 External.t.ns /*T:string?*/ = null; OuterA.A.t.s /*T:string!*/ = null; // warn 2 OuterA.A.t.ns /*T:string?*/ = null; B.t.s /*T:string!*/ = null; // warn 3 B.t.ns /*T:string?*/ = null; OuterD.D.t.s /*T:string!*/ = null; // warn 4 OuterD.D.t.ns /*T:string?*/ = null; Oblivious2.t.s /*T:string!*/ = null; Oblivious2.t.ns /*T:string?*/ = null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference(), libComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (33,36): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static (string s, string? ns) t; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(33, 36), // (42,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // External.t.s /*T:string!*/ = null; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(42, 38), // (45,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterA.A.t.s /*T:string!*/ = null; // warn 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(45, 38), // (48,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // B.t.s /*T:string!*/ = null; // warn 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(48, 31), // (51,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterD.D.t.s /*T:string!*/ = null; // warn 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(51, 38) ); } [Fact] public void NonNullTypes_OnFields_Arrays() { var obliviousLib = @" public class Oblivious { public static string[] s; } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); var lib = @" #pragma warning disable 8618 public class External { public static string[] s; public static string?[] ns; } "; var libComp = CreateCompilation(new[] { lib }, options: WithNullableEnable()); var source = @" #nullable disable public class OuterA { #nullable enable public class A { public static string[] s; public static string?[] ns; } } // NonNullTypes(true) by default public class B { public static string[] s; public static string?[] ns; } #nullable disable public class OuterD { public class D { #nullable enable public static string[] s; #nullable enable public static string?[] ns; } } #nullable disable public class Oblivious2 { public static string[] s; public static string?[] ns; } #nullable enable class E { public void M() { Oblivious.s[0] /*T:string!*/ = null; External.s[0] /*T:string!*/ = null; // warn 1 External.ns[0] /*T:string?*/ = null; OuterA.A.s[0] /*T:string!*/ = null; // warn 2 OuterA.A.ns[0] /*T:string?*/ = null; B.s[0] /*T:string!*/ = null; // warn 3 B.ns[0] /*T:string?*/ = null; OuterD.D.s[0] /*T:string!*/ = null; // warn 4 OuterD.D.ns[0] /*T:string?*/ = null; Oblivious2.s[0] /*T:string!*/ = null; Oblivious2.ns[0] /*T:string?*/ = null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference(), libComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (10,32): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string[] s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(10, 32), // (11,33): warning CS8618: Non-nullable field 'ns' is uninitialized. Consider declaring the field as nullable. // public static string?[] ns; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "ns").WithArguments("field", "ns").WithLocation(11, 33), // (18,28): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string[] s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(18, 28), // (19,29): warning CS8618: Non-nullable field 'ns' is uninitialized. Consider declaring the field as nullable. // public static string?[] ns; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "ns").WithArguments("field", "ns").WithLocation(19, 29), // (28,32): warning CS8618: Non-nullable field 's' is uninitialized. Consider declaring the field as nullable. // public static string[] s; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("field", "s").WithLocation(28, 32), // (30,33): warning CS8618: Non-nullable field 'ns' is uninitialized. Consider declaring the field as nullable. // public static string?[] ns; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "ns").WithArguments("field", "ns").WithLocation(30, 33), // (38,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static string?[] ns; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(38, 25), // (47,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // External.s[0] /*T:string!*/ = null; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(47, 39), // (50,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterA.A.s[0] /*T:string!*/ = null; // warn 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(50, 39), // (53,32): warning CS8625: Cannot convert null literal to non-nullable reference type. // B.s[0] /*T:string!*/ = null; // warn 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(53, 32), // (56,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterD.D.s[0] /*T:string!*/ = null; // warn 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(56, 39) ); } [Fact] public void NonNullTypes_OnProperties() { var obliviousLib = @" public class Oblivious { public static string s { get; set; } } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); obliviousComp.VerifyDiagnostics(); var lib = @" #pragma warning disable 8618 public class External { public static string s { get; set; } public static string? ns { get; set; } } "; var libComp = CreateCompilation(new[] { lib }, options: WithNullableEnable()); var source = @" #nullable disable public class OuterA { public class A { #nullable enable public static string s { get; set; } #nullable enable public static string? ns { get; set; } } } // NonNullTypes(true) by default public class B { public static string s { get; set; } public static string? ns { get; set; } } #nullable disable public class OuterD { #nullable enable public class D { public static string s { get; set; } public static string? ns { get; set; } } } public class Oblivious2 { #nullable disable public static string s { get; set; } #nullable disable public static string? ns { get; set; } } #nullable enable class E { public void M() { Oblivious.s /*T:string!*/ = null; External.s /*T:string!*/ = null; // warn 1 External.ns /*T:string?*/ = null; OuterA.A.s /*T:string!*/ = null; // warn 2 OuterA.A.ns /*T:string?*/ = null; B.s /*T:string!*/ = null; // warn 3 B.ns /*T:string?*/ = null; OuterD.D.s /*T:string!*/ = null; // warn 4 OuterD.D.ns /*T:string?*/ = null; Oblivious2.s /*T:string!*/ = null; Oblivious2.ns /*T:string?*/ = null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference(), libComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (10,30): warning CS8618: Non-nullable property 's' is uninitialized. Consider declaring the property as nullable. // public static string s { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("property", "s").WithLocation(10, 30), // (19,26): warning CS8618: Non-nullable property 's' is uninitialized. Consider declaring the property as nullable. // public static string s { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("property", "s").WithLocation(19, 26), // (29,30): warning CS8618: Non-nullable property 's' is uninitialized. Consider declaring the property as nullable. // public static string s { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "s").WithArguments("property", "s").WithLocation(29, 30), // (39,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public static string? ns { get; set; } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(39, 25), // (48,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // External.s /*T:string!*/ = null; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(48, 36), // (51,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterA.A.s /*T:string!*/ = null; // warn 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(51, 36), // (54,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // B.s /*T:string!*/ = null; // warn 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(54, 29), // (57,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterD.D.s /*T:string!*/ = null; // warn 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(57, 36) ); } [Fact] public void NonNullTypes_OnMethods() { var obliviousLib = @" public class Oblivious { public static string Method(string s) => throw null; } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); var lib = @" public class External { public static string Method(string s) => throw null!; public static string? NMethod(string? ns) => throw null!; } "; var libComp = CreateCompilation(new[] { lib }, options: WithNullableEnable()); var source = @" #nullable disable public class OuterA { #nullable enable public class A { public static string Method(string s) => throw null!; public static string? NMethod(string? ns) => throw null!; } } // NonNullTypes(true) by default public class B { public static string Method(string s) => throw null!; public static string? NMethod(string? ns) => throw null!; } #nullable disable public class OuterD { public class D { #nullable enable public static string Method(string s) => throw null!; #nullable enable public static string? NMethod(string? ns) => throw null!; } } #nullable disable public class Oblivious2 { public static string Method(string s) => throw null!; public static string? NMethod(string? ns) => throw null!; } #nullable enable class E { public void M() { Oblivious.Method(null) /*T:string!*/; External.Method(null) /*T:string!*/; // warn 1 External.NMethod(null) /*T:string?*/; OuterA.A.Method(null) /*T:string!*/; // warn 2 OuterA.A.NMethod(null) /*T:string?*/; B.Method(null) /*T:string!*/; // warn 3 B.NMethod(null) /*T:string?*/; OuterD.D.Method(null) /*T:string!*/; // warn 4 OuterD.D.NMethod(null) /*T:string?*/; Oblivious2.Method(null) /*T:string!*/; Oblivious2.NMethod(null) /*T:string?*/; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference(), libComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (38,41): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static string? NMethod(string? ns) => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(38, 41), // (38,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static string? NMethod(string? ns) => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(38, 25), // (47,25): warning CS8625: Cannot convert null literal to non-nullable reference type. // External.Method(null) /*T:string!*/; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(47, 25), // (50,25): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterA.A.Method(null) /*T:string!*/; // warn 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(50, 25), // (53,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // B.Method(null) /*T:string!*/; // warn 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(53, 18), // (56,25): warning CS8625: Cannot convert null literal to non-nullable reference type. // OuterD.D.Method(null) /*T:string!*/; // warn 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(56, 25) ); } [Fact] public void NonNullTypes_OnModule() { var obliviousLib = @"#nullable disable public class Oblivious { } "; var obliviousComp = CreateCompilation(new[] { obliviousLib }); obliviousComp.VerifyDiagnostics(); var compilation = CreateCompilation("", options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference() }); compilation.VerifyDiagnostics(); } [Fact] public void NonNullTypes_ValueTypeArgument() { var source = @"#nullable disable class A<T> { } class B { A<byte> P { get; } }"; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); } [WorkItem(28324, "https://github.com/dotnet/roslyn/issues/28324")] [Fact] public void NonNullTypes_GenericOverriddenMethod_ValueType() { var source = @"#nullable disable class C<T> { } abstract class A { internal abstract C<T> F<T>() where T : struct; } class B : A { internal override C<T> F<T>() => throw null!; }"; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); var method = comp.GetMember<MethodSymbol>("A.F"); var typeArg = ((NamedTypeSymbol)method.ReturnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; Assert.True(typeArg.Type.IsValueType); Assert.Equal(NullableAnnotation.Oblivious, typeArg.NullableAnnotation); method = comp.GetMember<MethodSymbol>("B.F"); typeArg = ((NamedTypeSymbol)method.ReturnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0]; Assert.True(typeArg.Type.IsValueType); Assert.Equal(NullableAnnotation.Oblivious, typeArg.NullableAnnotation); // https://github.com/dotnet/roslyn/issues/29843: Test all combinations of base and derived // including explicit Nullable<T>. } // BoundExpression.Type for Task.FromResult(_f[0]) is Task<T!> // but the inferred type is Task<T~>. [Fact] public void CompareUnannotatedAndNonNullableTypeParameter() { var source = @"#pragma warning disable 0649 using System.Threading.Tasks; class C<T> { T[] _f; Task<T> F() => Task.FromResult(_f[0]); }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8618: Non-nullable field '_f' is uninitialized. Consider declaring the field as nullable. // T[] _f; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "_f").WithArguments("field", "_f").WithLocation(5, 9) ); } [Fact] public void CircularConstraints() { var source = @"class A<T> where T : B<T>.I { internal interface I { } } class B<T> : A<T> where T : A<T>.I { }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular7, skipUsesIsNullable: true); comp.VerifyDiagnostics( // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.0", "8.0").WithLocation(1, 1) ); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(27686, "https://github.com/dotnet/roslyn/issues/27686")] public void AssignObliviousIntoLocals() { var obliviousLib = @" public class Oblivious { public static string f; } "; var obliviousComp = CreateCompilation(obliviousLib, parseOptions: TestOptions.Regular7); var source = @" class C { void M() { string s = Oblivious.f; s /*T:string!*/ .ToString(); string ns = Oblivious.f; ns /*T:string!*/ .ToString(); } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { obliviousComp.EmitToImageReference() }); compilation.VerifyTypes(); compilation.VerifyDiagnostics(); } [Fact] public void NonNullTypesTrue_Foreach() { var source = @" class C { #nullable enable public void M2() { foreach (string s in Collection()) { s /*T:string!*/ .ToString(); } foreach (string? ns in NCollection()) { ns /*T:string?*/ .ToString(); // 1 } foreach (var s1 in Collection()) { s1 /*T:string!*/ .ToString(); } foreach (var ns1 in NCollection()) { ns1 /*T:string?*/ .ToString(); // 2 } foreach (string s in FalseCollection()) { s /*T:string!*/ .ToString(); } foreach (string? ns in FalseNCollection()) { ns /*T:string?*/ .ToString(); // 3 } foreach (var s1 in FalseCollection()) { s1 /*T:string!*/ .ToString(); } foreach (var ns1 in FalseNCollection()) { ns1 /*T:string?*/ .ToString(); // 4 } } #nullable enable string[] Collection() => throw null!; #nullable enable string?[] NCollection() => throw null!; #nullable disable string[] FalseCollection() => throw null!; #nullable disable string?[] FalseNCollection() => throw null!; // 5 } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (60,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string?[] FalseNCollection() => throw null!; // 5 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(60, 11), // (16,13): warning CS8602: Dereference of a possibly null reference. // ns /*T:string?*/ .ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns").WithLocation(16, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // ns1 /*T:string?*/ .ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns1").WithLocation(26, 13), // (36,13): warning CS8602: Dereference of a possibly null reference. // ns /*T:string?*/ .ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns").WithLocation(36, 13), // (46,13): warning CS8602: Dereference of a possibly null reference. // ns1 /*T:string?*/ .ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns1").WithLocation(46, 13) ); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypesFalse_Foreach() { var source = @" class C { #nullable disable public void M2() { foreach (string s in Collection()) { s /*T:string!*/ .ToString(); } foreach (string? ns in NCollection()) // 1 { ns /*T:string?*/ .ToString(); } foreach (var s1 in Collection()) { s1 /*T:string!*/ .ToString(); } foreach (var ns1 in NCollection()) { ns1 /*T:string?*/ .ToString(); } foreach (string s in FalseCollection()) { s /*T:string!*/ .ToString(); } foreach (string? ns in FalseNCollection()) // 2 { ns /*T:string?*/ .ToString(); } foreach (var s1 in FalseCollection()) { s1 /*T:string!*/ .ToString(); } foreach (var ns1 in FalseNCollection()) { ns1 /*T:string?*/ .ToString(); } } #nullable enable string[] Collection() => throw null!; #nullable enable string?[] NCollection() => throw null!; #nullable disable string[] FalseCollection() => throw null!; #nullable disable string?[] FalseNCollection() => throw null!; // 3 } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (60,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string?[] FalseNCollection() => throw null!; // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(60, 11), // (14,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // foreach (string? ns in NCollection()) // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 24), // (34,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // foreach (string? ns in FalseNCollection()) // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(34, 24) ); } [Fact] public void NonNullTypesTrue_OutVars() { var source = @" class C { #nullable enable public void M() { Out(out string s2); s2 /*T:string!*/ .ToString(); s2 = null; // 1 NOut(out string? ns2); ns2 /*T:string?*/ .ToString(); // 2 ns2 = null; FalseOut(out string s3); s3 /*T:string!*/ .ToString(); s3 = null; // 3 FalseNOut(out string? ns3); ns3 /*T:string?*/ .ToString(); // 4 ns3 = null; Out(out var s4); s4 /*T:string!*/ .ToString(); s4 = null; NOut(out var ns4); ns4 /*T:string?*/ .ToString(); // 5 ns4 = null; FalseOut(out var s5); s5 /*T:string!*/ .ToString(); s5 = null; FalseNOut(out var ns5); ns5 /*T:string?*/ .ToString(); // 6 ns5 = null; } #nullable enable void Out(out string s) => throw null!; #nullable enable void NOut(out string? ns) => throw null!; #nullable disable void FalseOut(out string s) => throw null!; #nullable disable void FalseNOut(out string? ns) => throw null!; // 7 } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (52,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void FalseNOut(out string? ns) => throw null!; // 7 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(52, 30), // (11,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // s2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 14), // (14,9): warning CS8602: Dereference of a possibly null reference. // ns2 /*T:string?*/ .ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns2").WithLocation(14, 9), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // s3 = null; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 14), // (22,9): warning CS8602: Dereference of a possibly null reference. // ns3 /*T:string?*/ .ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns3").WithLocation(22, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // ns4 /*T:string?*/ .ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns4").WithLocation(30, 9), // (38,9): warning CS8602: Dereference of a possibly null reference. // ns5 /*T:string?*/ .ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns5").WithLocation(38, 9) ); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypesFalse_OutVars() { var source = @" class C { #nullable disable public void M() { Out(out string s2); s2 /*T:string!*/ .ToString(); s2 = null; NOut(out string? ns2); // 1 ns2 /*T:string?*/ .ToString(); // 2 ns2 = null; FalseOut(out string s3); s3 /*T:string!*/ .ToString(); s3 = null; FalseNOut(out string? ns3); // 3 ns3 /*T:string?*/ .ToString(); // 4 ns3 = null; Out(out var s4); s4 /*T:string!*/ .ToString(); s4 = null; // 5 NOut(out var ns4); ns4 /*T:string?*/ .ToString(); // 6 ns4 = null; FalseOut(out var s5); s5 /*T:string!*/ .ToString(); s5 = null; FalseNOut(out var ns5); ns5 /*T:string?*/ .ToString(); // 7 ns5 = null; } #nullable enable void Out(out string s) => throw null!; #nullable enable void NOut(out string? ns) => throw null!; #nullable disable void FalseOut(out string s) => throw null!; #nullable disable void FalseNOut(out string? ns) => throw null!; // 8 } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (52,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void FalseNOut(out string? ns) => throw null!; // 8 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(52, 30), // (13,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // NOut(out string? ns2); // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 24), // (21,29): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // FalseNOut(out string? ns3); // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 29) ); } [Fact] public void NonNullTypesTrue_LocalDeclarations() { var source = @" #nullable enable public class C : Base { public void M() { string s2 = Method(); s2 /*T:string!*/ .ToString(); s2 = null; // warn 1 string? ns2 = NMethod(); ns2 /*T:string?*/ .ToString(); // warn 2 ns2 = null; string s3 = FalseMethod(); s3 /*T:string!*/ .ToString(); s3 = null; // warn 3 string? ns3 = FalseNMethod(); ns3 /*T:string?*/ .ToString(); // warn 4 ns3 = null; var s4 = Method(); s4 /*T:string!*/ .ToString(); s4 = null; var ns4 = NMethod(); ns4 /*T:string?*/ .ToString(); // warn 5 ns4 = null; var s5 = FalseMethod(); s5 /*T:string!*/ .ToString(); s5 = null; var ns5 = FalseNMethod(); ns5 /*T:string?*/ .ToString(); // warn 6 ns5 = null; } } public class Base { #nullable enable public string Method() => throw null!; #nullable enable public string? NMethod() => throw null!; #nullable disable public string FalseMethod() => throw null!; #nullable disable public string? FalseNMethod() => throw null!; // warn 7 } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (54,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public string? FalseNMethod() => throw null!; // warn 7 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(54, 18), // (11,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // s2 = null; // warn 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 14), // (14,9): warning CS8602: Dereference of a possibly null reference. // ns2 /*T:string?*/ .ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns2").WithLocation(14, 9), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // s3 = null; // warn 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 14), // (22,9): warning CS8602: Dereference of a possibly null reference. // ns3 /*T:string?*/ .ToString(); // warn 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns3").WithLocation(22, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // ns4 /*T:string?*/ .ToString(); // warn 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns4").WithLocation(30, 9), // (38,9): warning CS8602: Dereference of a possibly null reference. // ns5 /*T:string?*/ .ToString(); // warn 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ns5").WithLocation(38, 9) ); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypesFalse_LocalDeclarations() { var source = @" #nullable disable public class C : Base { public void M() { string s2 = Method(); s2 /*T:string!*/ .ToString(); s2 = null; string? ns2 = NMethod(); // 1 ns2 /*T:string?*/ .ToString(); ns2 = null; string s3 = FalseMethod(); s3 /*T:string!*/ .ToString(); s3 = null; string? ns3 = FalseNMethod(); // 2 ns3 /*T:string?*/ .ToString(); ns3 = null; var s4 = Method(); s4 /*T:string!*/ .ToString(); s4 = null; var ns4 = NMethod(); ns4 /*T:string?*/ .ToString(); ns4 = null; var s5 = FalseMethod(); s5 /*T:string!*/ .ToString(); s5 = null; var ns5 = FalseNMethod(); ns5 /*T:string?*/ .ToString(); ns5 = null; } } public class Base { #nullable enable public string Method() => throw null!; #nullable enable public string? NMethod() => throw null!; #nullable disable public string FalseMethod() => throw null!; #nullable disable public string? FalseNMethod() => throw null!; // 3 } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (54,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public string? FalseNMethod() => throw null!; // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(54, 18), // (13,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? ns2 = NMethod(); // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 15), // (21,15): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? ns3 = FalseNMethod(); // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 15) ); } [Fact] public void NonNullTypes_Constraint() { var source = @" public class S { } #nullable enable public struct C<T> where T : S { public void M(T t) { t.ToString(); t = null; // warn } } #nullable disable public struct D<T> where T : S { public void M(T t) { t.ToString(); t = null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (11,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // t = null; // warn Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 13) ); } [Fact] public void NonNullTypes_Delegate() { var source = @" #nullable enable public delegate string[] MyDelegate(string[] x); #nullable disable public delegate string[] MyFalseDelegate(string[] x); #nullable enable public delegate string[]? MyNullableDelegate(string[]? x); class C { void M() { MyDelegate x1 = Method; MyDelegate x2 = FalseMethod; MyDelegate x4 = NullableReturnMethod; // warn 1 MyDelegate x5 = NullableParameterMethod; MyFalseDelegate y1 = Method; MyFalseDelegate y2 = FalseMethod; MyFalseDelegate y4 = NullableReturnMethod; MyFalseDelegate y5 = NullableParameterMethod; MyNullableDelegate z1 = Method; // warn 2 MyNullableDelegate z2 = FalseMethod; MyNullableDelegate z4 = NullableReturnMethod; // warn 3 MyNullableDelegate z5 = NullableParameterMethod; } #nullable enable public string[] Method(string[] x) => throw null!; #nullable disable public string[] FalseMethod(string[] x) => throw null!; #nullable enable public string[]? NullableReturnMethod(string[] x) => throw null!; public string[] NullableParameterMethod(string[]? x) => throw null!; } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (18,25): warning CS8621: Nullability of reference types in return type of 'string[]? C.NullableReturnMethod(string[] x)' doesn't match the target delegate 'MyDelegate'. // MyDelegate x4 = NullableReturnMethod; // warn 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "NullableReturnMethod").WithArguments("string[]? C.NullableReturnMethod(string[] x)", "MyDelegate").WithLocation(18, 25), // (24,33): warning CS8622: Nullability of reference types in type of parameter 'x' of 'string[] C.Method(string[] x)' doesn't match the target delegate 'MyNullableDelegate'. // MyNullableDelegate z1 = Method; // warn 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Method").WithArguments("x", "string[] C.Method(string[] x)", "MyNullableDelegate").WithLocation(24, 33), // (26,33): warning CS8622: Nullability of reference types in type of parameter 'x' of 'string[]? C.NullableReturnMethod(string[] x)' doesn't match the target delegate 'MyNullableDelegate'. // MyNullableDelegate z4 = NullableReturnMethod; // warn 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "NullableReturnMethod").WithArguments("x", "string[]? C.NullableReturnMethod(string[] x)", "MyNullableDelegate").WithLocation(26, 33) ); } [Fact] public void NonNullTypes_Constructor() { var source = @" public class C { #nullable enable public C(string[] x) => throw null!; } public class D { #nullable disable public D(string[] x) => throw null!; } #nullable enable public class E { public string[] field = null!; #nullable disable public string[] obliviousField; #nullable enable public string[]? nullableField; void M() { new C(field); new C(obliviousField); new C(nullableField); // warn new D(field); new D(obliviousField); new D(nullableField); } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (27,15): warning CS8604: Possible null reference argument for parameter 'x' in 'C.C(string[] x)'. // new C(nullableField); // warn Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nullableField").WithArguments("x", "C.C(string[] x)").WithLocation(27, 15) ); } [Fact] public void NonNullTypes_Constraint_Nested() { var source = @" public class S { } public class List<T> { public T Item { get; set; } = default!; } #nullable enable public struct C<T, NT> where T : List<S> where NT : List<S?> { public void M(T t, NT nt) { t.Item /*T:S!*/ .ToString(); t.Item = null; // warn 1 nt.Item /*T:S?*/ .ToString(); // warn 2 nt.Item = null; } } #nullable disable public struct D<T, NT> where T : List<S> where NT : List<S?> // warn 3 { public void M(T t, NT nt) { t.Item /*T:S!*/ .ToString(); t.Item = null; nt.Item /*T:S?*/ .ToString(); nt.Item = null; } } "; var compilation = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: WithNullableEnable()); compilation.VerifyTypes(); compilation.VerifyDiagnostics( // (14,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // t.Item = null; // warn 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 18), // (15,9): warning CS8602: Dereference of a possibly null reference. // nt.Item /*T:S?*/ .ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "nt.Item").WithLocation(15, 9), // (23,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // where NT : List<S?> // warn 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(23, 22)); } [Fact] public void IsAnnotated_01() { var source = @"using System; class C1 { string F1() => throw null!; string? F2() => throw null!; int F3() => throw null!; int? F4() => throw null!; Nullable<int> F5() => throw null!; } #nullable disable class C2 { string F1() => throw null!; string? F2() => throw null!; int F3() => throw null!; int? F4() => throw null!; Nullable<int> F5() => throw null!; } #nullable enable class C3 { string F1() => throw null!; string? F2() => throw null!; int F3() => throw null!; int? F4() => throw null!; Nullable<int> F5() => throw null!; }"; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (6,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? F2() => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 11), // (15,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // string? F2() => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(15, 11) ); verify("C1.F1", "System.String", NullableAnnotation.Oblivious); verify("C1.F2", "System.String?", NullableAnnotation.Annotated); verify("C1.F3", "System.Int32", NullableAnnotation.Oblivious); verify("C1.F4", "System.Int32?", NullableAnnotation.Annotated); verify("C1.F5", "System.Int32?", NullableAnnotation.Annotated); verify("C2.F1", "System.String", NullableAnnotation.Oblivious); verify("C2.F2", "System.String?", NullableAnnotation.Annotated); verify("C2.F3", "System.Int32", NullableAnnotation.Oblivious); verify("C2.F4", "System.Int32?", NullableAnnotation.Annotated); verify("C2.F5", "System.Int32?", NullableAnnotation.Annotated); verify("C3.F1", "System.String!", NullableAnnotation.NotAnnotated); verify("C3.F2", "System.String?", NullableAnnotation.Annotated); verify("C3.F3", "System.Int32", NullableAnnotation.NotAnnotated); verify("C3.F4", "System.Int32?", NullableAnnotation.Annotated); verify("C3.F5", "System.Int32?", NullableAnnotation.Annotated); // https://github.com/dotnet/roslyn/issues/29845: Test nested nullability. void verify(string methodName, string displayName, NullableAnnotation nullableAnnotation) { var method = comp.GetMember<MethodSymbol>(methodName); var type = method.ReturnTypeWithAnnotations; Assert.Equal(displayName, type.ToTestDisplayString(true)); Assert.Equal(nullableAnnotation, type.NullableAnnotation); } } [Fact] public void IsAnnotated_02() { var source = @"using System; class C1 { T F1<T>() => throw null!; T? F2<T>() => throw null!; T F3<T>() where T : class => throw null!; T? F4<T>() where T : class => throw null!; T F5<T>() where T : struct => throw null!; T? F6<T>() where T : struct => throw null!; Nullable<T> F7<T>() where T : struct => throw null!; } #nullable disable class C2 { T F1<T>() => throw null!; T? F2<T>() => throw null!; T F3<T>() where T : class => throw null!; T? F4<T>() where T : class => throw null!; T F5<T>() where T : struct => throw null!; T? F6<T>() where T : struct => throw null!; Nullable<T> F7<T>() where T : struct => throw null!; } #nullable enable class C3 { T F1<T>() => throw null!; T? F2<T>() => throw null!; T F3<T>() where T : class => throw null!; T? F4<T>() where T : class => throw null!; T F5<T>() where T : struct => throw null!; T? F6<T>() where T : struct => throw null!; Nullable<T> F7<T>() where T : struct => throw null!; }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (28,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? F2<T>() => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(28, 5), // (17,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? F2<T>() => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 6), // (17,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? F2<T>() => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(17, 5), // (6,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? F2<T>() => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 6), // (6,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? F2<T>() => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(6, 5), // (19,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? F4<T>() where T : class => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(19, 6), // (19,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? F4<T>() where T : class => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(19, 5), // (8,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? F4<T>() where T : class => throw null!; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 6), // (8,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? F4<T>() where T : class => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 5) ); verify("C1.F1", "T", NullableAnnotation.Oblivious); verify("C1.F2", "T?", NullableAnnotation.Annotated); verify("C1.F3", "T", NullableAnnotation.Oblivious); verify("C1.F4", "T?", NullableAnnotation.Annotated); verify("C1.F5", "T", NullableAnnotation.Oblivious); verify("C1.F6", "T?", NullableAnnotation.Annotated); verify("C1.F7", "T?", NullableAnnotation.Annotated); verify("C2.F1", "T", NullableAnnotation.Oblivious); verify("C2.F2", "T?", NullableAnnotation.Annotated); verify("C2.F3", "T", NullableAnnotation.Oblivious); verify("C2.F4", "T?", NullableAnnotation.Annotated); verify("C2.F5", "T", NullableAnnotation.Oblivious); verify("C2.F6", "T?", NullableAnnotation.Annotated); verify("C2.F7", "T?", NullableAnnotation.Annotated); verify("C3.F1", "T", NullableAnnotation.NotAnnotated); verify("C3.F2", "T?", NullableAnnotation.Annotated); verify("C3.F3", "T!", NullableAnnotation.NotAnnotated); verify("C3.F4", "T?", NullableAnnotation.Annotated); verify("C3.F5", "T", NullableAnnotation.NotAnnotated); verify("C3.F6", "T?", NullableAnnotation.Annotated); verify("C3.F7", "T?", NullableAnnotation.Annotated); // https://github.com/dotnet/roslyn/issues/29845: Test nested nullability. // https://github.com/dotnet/roslyn/issues/29845: Test all combinations of overrides. void verify(string methodName, string displayName, NullableAnnotation nullableAnnotation) { var method = comp.GetMember<MethodSymbol>(methodName); var type = method.ReturnTypeWithAnnotations; Assert.Equal(displayName, type.ToTestDisplayString(true)); Assert.Equal(nullableAnnotation, type.NullableAnnotation); } } [Fact] public void InheritedValueConstraintForNullable1_01() { var source = @" class A { public virtual T? Goo<T>() where T : struct { return null; } } class B : A { public override T? Goo<T>() { return null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); //var a = compilation.GetTypeByMetadataName("A"); //var aGoo = a.GetMember<MethodSymbol>("Goo"); //Assert.Equal("T? A.Goo<T>()", aGoo.ToTestDisplayString()); //var b = compilation.GetTypeByMetadataName("B"); //var bGoo = b.GetMember<MethodSymbol>("Goo"); //Assert.Equal("T? A.Goo<T>()", bGoo.OverriddenMethod.ToTestDisplayString()); compilation.VerifyDiagnostics(); } [Fact] public void InheritedValueConstraintForNullable1_02() { var source = @" class A { public virtual void Goo<T>(T? x) where T : struct { } } class B : A { public override void Goo<T>(T? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); } [Fact] public void InheritedValueConstraintForNullable1_03() { var source = @" class A { public virtual System.Nullable<T> Goo<T>() where T : struct { return null; } } class B : A { public override T? Goo<T>() { return null; } } "; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void InheritedValueConstraintForNullable1_04() { var source = @" class A { public virtual void Goo<T>(System.Nullable<T> x) where T : struct { } } class B : A { public override void Goo<T>(T? x) { } } "; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void InheritedValueConstraintForNullable1_05() { var source = @" class A { public virtual T? Goo<T>() where T : struct { return null; } } class B : A { public override System.Nullable<T> Goo<T>() { return null; } } "; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void InheritedValueConstraintForNullable1_06() { var source = @" class A { public virtual void M1<T>(T? x) where T : struct { } } class B : A { public override void M1<T>(System.Nullable<T> x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.True(m1.Parameters[0].Type.IsValueType); Assert.True(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); } [Fact] public void Overriding_03() { var source = @" class A { public virtual void M1<T>(T? x) where T : class { } public virtual T? M2<T>() where T : class { return null; } } class B : A { public override void M1<T>(T? x) { } public override T? M2<T>() { return null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (16,26): error CS0115: 'B.M1<T>(T?)': no suitable method found to override // public override void M1<T>(T? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("B.M1<T>(T?)").WithLocation(16, 26), // (16,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(T? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(16, 35), // (20,24): error CS0508: 'B.M2<T>()': return type must be 'T' to match overridden member 'A.M2<T>()' // public override T? M2<T>() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("B.M2<T>()", "A.M2<T>()", "T").WithLocation(20, 24), // (20,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? M2<T>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M2").WithArguments("System.Nullable<T>", "T", "T").WithLocation(20, 24)); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.False(m1.Parameters[0].Type.IsReferenceType); Assert.Null(m1.OverriddenMethod); var m2 = b.GetMember<MethodSymbol>("M2"); Assert.True(m2.ReturnType.IsNullableType()); Assert.False(m2.ReturnType.IsReferenceType); Assert.False(m2.OverriddenMethod.ReturnType.IsNullableType()); } [Fact] [WorkItem(29846, "https://github.com/dotnet/roslyn/issues/29846")] public void Overriding_04() { var source = @" class A { public virtual void M1<T>(T? x) where T : struct { } public virtual void M1<T>(T x) { } public virtual void M2<T>(T? x) where T : struct { } public virtual void M2<T>(T x) { } public virtual void M3<T>(T x) { } public virtual void M3<T>(T? x) where T : struct { } } class B : A { public override void M1<T>(T? x) { } public override void M2<T>(T x) { } public override void M3<T>(T? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.True(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); var m2 = b.GetMember<MethodSymbol>("M2"); Assert.False(m2.Parameters[0].Type.IsNullableType()); Assert.False(m2.OverriddenMethod.Parameters[0].Type.IsNullableType()); var m3 = b.GetMember<MethodSymbol>("M3"); Assert.True(m3.Parameters[0].Type.IsNullableType()); Assert.True(m3.OverriddenMethod.Parameters[0].Type.IsNullableType()); } [Fact] [WorkItem(29847, "https://github.com/dotnet/roslyn/issues/29847")] public void Overriding_05() { var source = @" class A { public virtual void M1<T>(T? x) where T : struct { } public virtual void M1<T>(T? x) where T : class { } } class B : A { public override void M1<T>(T? x) { } } class C { public virtual void M2<T>(T? x) where T : class { } public virtual void M2<T>(T? x) where T : struct { } } class D : C { public override void M2<T>(T? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.True(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); var d = compilation.GetTypeByMetadataName("D"); var m2 = d.GetMember<MethodSymbol>("M2"); Assert.True(m2.Parameters[0].Type.IsNullableType()); Assert.True(m2.OverriddenMethod.Parameters[0].Type.IsNullableType()); } [Fact] public void Overriding_06() { var source = @" class A { public virtual void M1<T>(System.Nullable<T> x) where T : struct { } public virtual void M2<T>(T? x) where T : struct { } public virtual void M3<T>(C<T?> x) where T : struct { } public virtual void M4<T>(C<System.Nullable<T>> x) where T : struct { } public virtual void M5<T>(C<T?> x) where T : class { } } class B : A { public override void M1<T>(T? x) { } public override void M2<T>(T? x) { } public override void M3<T>(C<T?> x) { } public override void M4<T>(C<T?> x) { } public override void M5<T>(C<T?> x) { } } class C<T> {} "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (43,26): error CS0115: 'B.M5<T>(C<T?>)': no suitable method found to override // public override void M5<T>(C<T?> x) where T : class Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M5").WithArguments("B.M5<T>(C<T?>)").WithLocation(43, 26), // (43,38): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M5<T>(C<T?> x) where T : class Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(43, 38)); var b = compilation.GetTypeByMetadataName("B"); var m3 = b.GetMember<MethodSymbol>("M3"); var m4 = b.GetMember<MethodSymbol>("M4"); var m5 = b.GetMember<MethodSymbol>("M5"); Assert.True(((NamedTypeSymbol)m3.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m3.OverriddenMethod.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m4.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m4.OverriddenMethod.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m5.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.Null(m5.OverriddenMethod); } [Fact] public void Overriding_07() { var source = @" class A { public void M1<T>(T x) { } } class B : A { public void M1<T>(T? x) where T : struct { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.True(m1.Parameters[0].Type.StrippedType().IsValueType); Assert.Null(m1.OverriddenMethod); } [Fact] public void Overriding_08() { var source = @" class A { public void M1<T>(T x) { } } class B : A { public override void M1<T>(T? x) where T : struct { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (11,26): error CS0115: 'B.M1<T>(T?)': no suitable method found to override // public override void M1<T>(T? x) where T : struct Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("B.M1<T>(T?)").WithLocation(11, 26), // (11,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(T? x) where T : struct Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 35) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.False(m1.Parameters[0].Type.StrippedType().IsValueType); Assert.False(m1.Parameters[0].Type.StrippedType().IsReferenceType); Assert.Null(m1.OverriddenMethod); } [Fact] public void Overriding_09() { var source = @" class A { public void M1<T>(T x) { } public void M2<T>(T? x) { } public void M3<T>(T? x) where T : class { } public void M4<T>(T? x) where T : struct { } } class B : A { public override void M1<T>(T? x) { } public override void M2<T>(T? x) { } public override void M3<T>(T? x) { } public override void M4<T>(T? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (8,23): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void M2<T>(T? x) Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 23), // (27,26): error CS0115: 'B.M2<T>(T?)': no suitable method found to override // public override void M2<T>(T? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M2").WithArguments("B.M2<T>(T?)").WithLocation(27, 26), // (31,26): error CS0115: 'B.M3<T>(T?)': no suitable method found to override // public override void M3<T>(T? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("B.M3<T>(T?)").WithLocation(31, 26), // (35,26): error CS0506: 'B.M4<T>(T?)': cannot override inherited member 'A.M4<T>(T?)' because it is not marked virtual, abstract, or override // public override void M4<T>(T? x) Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M4").WithArguments("B.M4<T>(T?)", "A.M4<T>(T?)").WithLocation(35, 26), // (23,26): error CS0115: 'B.M1<T>(T?)': no suitable method found to override // public override void M1<T>(T? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("B.M1<T>(T?)").WithLocation(23, 26), // (27,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M2<T>(T? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(27, 35), // (31,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M3<T>(T? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(31, 35), // (35,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M4<T>(T? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(35, 35), // (23,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(T? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(23, 35) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); var m2 = b.GetMember<MethodSymbol>("M2"); var m3 = b.GetMember<MethodSymbol>("M3"); var m4 = b.GetMember<MethodSymbol>("M4"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.True(m2.Parameters[0].Type.IsNullableType()); Assert.True(m3.Parameters[0].Type.IsNullableType()); Assert.True(m4.Parameters[0].Type.IsNullableType()); Assert.Null(m1.OverriddenMethod); Assert.Null(m2.OverriddenMethod); Assert.Null(m3.OverriddenMethod); Assert.Null(m4.OverriddenMethod); } [Fact] public void Overriding_10() { var source = @" class A { public virtual void M1<T>(System.Nullable<T> x) where T : class { } } class B : A { public override void M1<T>(T? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (4,50): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public virtual void M1<T>(System.Nullable<T> x) where T : class Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(4, 50), // (11,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(T? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 35) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.NotNull(m1.OverriddenMethod); } [Fact] public void Overriding_11() { var source = @" class A { public virtual C<System.Nullable<T>> M1<T>() where T : class { throw new System.NotImplementedException(); } } class B : A { public override C<T?> M1<T>() { throw new System.NotImplementedException(); } } class C<T> {} "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (4,42): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public virtual C<System.Nullable<T>> M1<T>() where T : class Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M1").WithArguments("System.Nullable<T>", "T", "T").WithLocation(4, 42), // (12,27): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override C<T?> M1<T>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M1").WithArguments("System.Nullable<T>", "T", "T").WithLocation(12, 27) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(((NamedTypeSymbol)m1.ReturnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m1.OverriddenMethod.ReturnType).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); } [Fact] public void Overriding_12() { var source = @" class A { public virtual string M1() { throw new System.NotImplementedException(); } public virtual string? M2() { throw new System.NotImplementedException(); } public virtual string? M3() { throw new System.NotImplementedException(); } public virtual System.Nullable<string> M4() { throw new System.NotImplementedException(); } public System.Nullable<string> M5() { throw new System.NotImplementedException(); } } class B : A { public override string? M1() { throw new System.NotImplementedException(); } public override string? M2() { throw new System.NotImplementedException(); } public override string M3() { throw new System.NotImplementedException(); } public override string? M4() { throw new System.NotImplementedException(); } public override string? M5() { throw new System.NotImplementedException(); } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (47,29): error CS0508: 'B.M4()': return type must be 'string?' to match overridden member 'A.M4()' // public override string? M4() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M4").WithArguments("B.M4()", "A.M4()", "string?").WithLocation(47, 29), // (52,29): error CS0506: 'B.M5()': cannot override inherited member 'A.M5()' because it is not marked virtual, abstract, or override // public override string? M5() Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M5").WithArguments("B.M5()", "A.M5()").WithLocation(52, 29), // (32,29): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override string? M1() Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M1").WithLocation(32, 29), // (19,44): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public virtual System.Nullable<string> M4() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M4").WithArguments("System.Nullable<T>", "T", "string").WithLocation(19, 44), // (24,36): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public System.Nullable<string> M5() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M5").WithArguments("System.Nullable<T>", "T", "string").WithLocation(24, 36) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.False(m1.ReturnType.IsNullableType()); Assert.False(m1.OverriddenMethod.ReturnType.IsNullableType()); var m4 = b.GetMember<MethodSymbol>("M4"); Assert.False(m4.ReturnType.IsNullableType()); Assert.True(m4.OverriddenMethod.ReturnType.IsNullableType()); var m5 = b.GetMember<MethodSymbol>("M4"); Assert.False(m5.ReturnType.IsNullableType()); } [Fact] public void Overriding_13() { var source = @" class A { public virtual void M1(string x) { } public virtual void M2(string? x) { } public virtual void M3(string? x) { } public virtual void M4(System.Nullable<string> x) { } public void M5(System.Nullable<string> x) { } } class B : A { public override void M1(string? x) { } public override void M2(string? x) { } public override void M3(string x) { } public override void M4(string? x) { } public override void M5(string? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (16,52): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public virtual void M4(System.Nullable<string> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "string").WithLocation(16, 52), // (20,44): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public void M5(System.Nullable<string> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "string").WithLocation(20, 44), // (35,26): warning CS8765: Type of parameter 'x' doesn't match overridden member because of nullability attributes. // public override void M3(string x) Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("x").WithLocation(35, 26), // (39,26): error CS0115: 'B.M4(string?)': no suitable method found to override // public override void M4(string? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M4").WithArguments("B.M4(string?)").WithLocation(39, 26), // (43,26): error CS0115: 'B.M5(string?)': no suitable method found to override // public override void M5(string? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M5").WithArguments("B.M5(string?)").WithLocation(43, 26) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.False(m1.Parameters[0].Type.IsNullableType()); Assert.Equal(NullableAnnotation.Annotated, m1.Parameters[0].TypeWithAnnotations.NullableAnnotation); Assert.True(m1.Parameters[0].Type.IsReferenceType); Assert.False(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); var m4 = b.GetMember<MethodSymbol>("M4"); Assert.False(m4.Parameters[0].Type.IsNullableType()); Assert.Null(m4.OverriddenMethod); var m5 = b.GetMember<MethodSymbol>("M4"); Assert.False(m5.Parameters[0].Type.IsNullableType()); } [Fact] public void Overriding_14() { var source = @" class A { public virtual int M1() { throw new System.NotImplementedException(); } public virtual int? M2() { throw new System.NotImplementedException(); } public virtual int? M3() { throw new System.NotImplementedException(); } public virtual System.Nullable<int> M4() { throw new System.NotImplementedException(); } public System.Nullable<int> M5() { throw new System.NotImplementedException(); } } class B : A { public override int? M1() { throw new System.NotImplementedException(); } public override int? M2() { throw new System.NotImplementedException(); } public override int M3() { throw new System.NotImplementedException(); } public override int? M4() { throw new System.NotImplementedException(); } public override int? M5() { throw new System.NotImplementedException(); } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (42,25): error CS0508: 'B.M3()': return type must be 'int?' to match overridden member 'A.M3()' // public override int M3() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M3").WithArguments("B.M3()", "A.M3()", "int?").WithLocation(42, 25), // (52,26): error CS0506: 'B.M5()': cannot override inherited member 'A.M5()' because it is not marked virtual, abstract, or override // public override int? M5() Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M5").WithArguments("B.M5()", "A.M5()").WithLocation(52, 26), // (32,26): error CS0508: 'B.M1()': return type must be 'int' to match overridden member 'A.M1()' // public override int? M1() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M1").WithArguments("B.M1()", "A.M1()", "int").WithLocation(32, 26) ); var b = compilation.GetTypeByMetadataName("B"); Assert.True(b.GetMember<MethodSymbol>("M1").ReturnType.IsNullableType()); Assert.True(b.GetMember<MethodSymbol>("M2").ReturnType.IsNullableType()); Assert.False(b.GetMember<MethodSymbol>("M3").ReturnType.IsNullableType()); Assert.True(b.GetMember<MethodSymbol>("M4").ReturnType.IsNullableType()); Assert.True(b.GetMember<MethodSymbol>("M5").ReturnType.IsNullableType()); } [Fact] public void Overriding_15() { var source = @" class A { public virtual void M1(int x) { } public virtual void M2(int? x) { } public virtual void M3(int? x) { } public virtual void M4(System.Nullable<int> x) { } public void M5(System.Nullable<int> x) { } } class B : A { public override void M1(int? x) { } public override void M2(int? x) { } public override void M3(int x) { } public override void M4(int? x) { } public override void M5(int? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (35,26): error CS0115: 'B.M3(int)': no suitable method found to override // public override void M3(int x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("B.M3(int)").WithLocation(35, 26), // (43,26): error CS0506: 'B.M5(int?)': cannot override inherited member 'A.M5(int?)' because it is not marked virtual, abstract, or override // public override void M5(int? x) Diagnostic(ErrorCode.ERR_CantOverrideNonVirtual, "M5").WithArguments("B.M5(int?)", "A.M5(int?)").WithLocation(43, 26), // (27,26): error CS0115: 'B.M1(int?)': no suitable method found to override // public override void M1(int? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("B.M1(int?)").WithLocation(27, 26) ); var b = compilation.GetTypeByMetadataName("B"); Assert.True(b.GetMember<MethodSymbol>("M1").Parameters[0].Type.IsNullableType()); Assert.True(b.GetMember<MethodSymbol>("M2").Parameters[0].Type.IsNullableType()); Assert.False(b.GetMember<MethodSymbol>("M3").Parameters[0].Type.IsNullableType()); Assert.True(b.GetMember<MethodSymbol>("M4").Parameters[0].Type.IsNullableType()); Assert.True(b.GetMember<MethodSymbol>("M5").Parameters[0].Type.IsNullableType()); } [Fact] public void Overriding_16() { var source = @" class C { public static void Main() { } } abstract class A { public abstract event System.Action<string> E1; public abstract event System.Action<string>? E2; public abstract event System.Action<string?>? E3; } class B1 : A { public override event System.Action<string?> E1 {add {} remove{}} public override event System.Action<string> E2 {add {} remove{}} public override event System.Action<string?>? E3 {add {} remove{}} } class B2 : A { public override event System.Action<string?> E1; // 2 public override event System.Action<string> E2; // 2 public override event System.Action<string?>? E3; // 2 void Dummy() { var e1 = E1; var e2 = E2; var e3 = E3; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (18,50): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event System.Action<string?> E1 {add {} remove{}} Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E1").WithLocation(18, 50), // (19,49): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event System.Action<string> E2 {add {} remove{}} Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E2").WithLocation(19, 49), // (25,50): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event System.Action<string?> E1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E1").WithLocation(25, 50), // (25,50): warning CS8618: Non-nullable event 'E1' is uninitialized. Consider declaring the event as nullable. // public override event System.Action<string?> E1; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(25, 50), // (26,49): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event System.Action<string> E2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E2").WithLocation(26, 49), // (26,49): warning CS8618: Non-nullable event 'E2' is uninitialized. Consider declaring the event as nullable. // public override event System.Action<string> E2; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E2").WithArguments("event", "E2").WithLocation(26, 49) ); foreach (string typeName in new[] { "B1", "B2" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (string memberName in new[] { "E1", "E2" }) { var member = type.GetMember<EventSymbol>(memberName); Assert.False(member.TypeWithAnnotations.Equals(member.OverriddenEvent.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } var e3 = type.GetMember<EventSymbol>("E3"); Assert.True(e3.TypeWithAnnotations.Equals(e3.OverriddenEvent.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "A", "B1", "B2" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var ev in type.GetMembers().OfType<EventSymbol>()) { Assert.True(ev.TypeWithAnnotations.Equals(ev.AddMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(ev.TypeWithAnnotations.Equals(ev.RemoveMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] [WorkItem(29851, "https://github.com/dotnet/roslyn/issues/29851")] public void Overriding_Methods() { var source = @" public abstract class A { #nullable disable public abstract System.Action<string> Oblivious1(System.Action<string> x); #nullable enable public abstract System.Action<string> Oblivious2(System.Action<string> x); public abstract System.Action<string> M3(System.Action<string> x); public abstract System.Action<string> M4(System.Action<string> x); public abstract System.Action<string>? M5(System.Action<string>? x); } public class B1 : A { public override System.Action<string?> Oblivious1(System.Action<string?> x) => throw null!; public override System.Action<string?> Oblivious2(System.Action<string?> x) => throw null!; // warn 3 and 4 // https://github.com/dotnet/roslyn/issues/29851: Should not warn public override System.Action<string?> M3(System.Action<string?> x) => throw null!; // warn 5 and 6 public override System.Action<string?> M4(System.Action<string?> x) => throw null!; // warn 7 and 8 public override System.Action<string?> M5(System.Action<string?> x) => throw null!; // warn 9 and 10 } public class B2 : A { public override System.Action<string> Oblivious1(System.Action<string> x) => throw null!; public override System.Action<string> Oblivious2(System.Action<string> x) => throw null!; #nullable disable public override System.Action<string> M3(System.Action<string> x) => throw null!; #nullable enable public override System.Action<string> M4(System.Action<string> x) => throw null!; #nullable disable public override System.Action<string> M5(System.Action<string> x) => throw null!; } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (18,44): warning CS8610: Nullability of reference types in type of parameter 'x' doesn't match overridden member. // public override System.Action<string?> Oblivious2(System.Action<string?> x) => throw null!; // warn 3 and 4 // https://github.com/dotnet/roslyn/issues/29851: Should not warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "Oblivious2").WithArguments("x").WithLocation(18, 44), // (19,44): warning CS8610: Nullability of reference types in type of parameter 'x' doesn't match overridden member. // public override System.Action<string?> M3(System.Action<string?> x) => throw null!; // warn 5 and 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("x").WithLocation(19, 44), // (20,44): warning CS8610: Nullability of reference types in type of parameter 'x' doesn't match overridden member. // public override System.Action<string?> M4(System.Action<string?> x) => throw null!; // warn 7 and 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M4").WithArguments("x").WithLocation(20, 44), // (21,44): warning CS8610: Nullability of reference types in type of parameter 'x' doesn't match overridden member. // public override System.Action<string?> M5(System.Action<string?> x) => throw null!; // warn 9 and 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M5").WithArguments("x").WithLocation(21, 44) ); var b1 = compilation.GetTypeByMetadataName("B1"); verifyMethodMatchesOverridden(expectMatch: false, b1, "Oblivious1"); verifyMethodMatchesOverridden(expectMatch: false, b1, "Oblivious2"); verifyMethodMatchesOverridden(expectMatch: false, b1, "M3"); verifyMethodMatchesOverridden(expectMatch: false, b1, "M4"); verifyMethodMatchesOverridden(expectMatch: false, b1, "M5"); var b2 = compilation.GetTypeByMetadataName("B2"); verifyMethodMatchesOverridden(expectMatch: false, b2, "Oblivious1"); // https://github.com/dotnet/roslyn/issues/29851: They should match verifyMethodMatchesOverridden(expectMatch: true, b2, "Oblivious2"); // https://github.com/dotnet/roslyn/issues/29851: They should not match verifyMethodMatchesOverridden(expectMatch: false, b2, "M3"); verifyMethodMatchesOverridden(expectMatch: true, b2, "M4"); // https://github.com/dotnet/roslyn/issues/29851: They should not match verifyMethodMatchesOverridden(expectMatch: false, b2, "M5"); void verifyMethodMatchesOverridden(bool expectMatch, NamedTypeSymbol type, string methodName) { var member = type.GetMember<MethodSymbol>(methodName); Assert.Equal(expectMatch, member.ReturnTypeWithAnnotations.Equals(member.OverriddenMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.Equal(expectMatch, member.Parameters.Single().TypeWithAnnotations.Equals(member.OverriddenMethod.Parameters.Single().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } [Fact] public void Overriding_Properties_WithNullableTypeArgument() { var source = @" #nullable enable public class List<T> { } public class Base<T> { public virtual List<T?> P { get; set; } = default; } public class Class<T> : Base<T> { #nullable disable public override List<T?> P { get; set; } = default; } "; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public virtual List<T?> P { get; set; } = default; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 25), // (7,47): warning CS8625: Cannot convert null literal to non-nullable reference type. // public virtual List<T?> P { get; set; } = default; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(7, 47), // (12,26): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public override List<T?> P { get; set; } = default; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(12, 26), // (12,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public override List<T?> P { get; set; } = default; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(12, 27) ); } [Fact] public void Overriding_Properties_WithNullableTypeArgument_WithClassConstraint() { var source = @" #nullable enable public class List<T> { } public class Base<T> where T : class { public virtual List<T?> P { get; set; } = default; } public class Class<T> : Base<T> where T : class { #nullable disable public override List<T?> P { get; set; } = default; } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (7,47): warning CS8625: Cannot convert null literal to non-nullable reference type. // public virtual List<T?> P { get; set; } = default; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(7, 47), // (12,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override List<T?> P { get; set; } = default; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(12, 27) ); } [Fact] public void Overriding_Properties_WithNullableTypeArgument_WithStructConstraint() { var source = @" public class List<T> { } public class Base<T> where T : struct { public virtual List<T?> P { get; set; } = default; } public class Class<T> : Base<T> where T : struct { #nullable disable public override List<T?> P { get; set; } = default; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,47): warning CS8625: Cannot convert null literal to non-nullable reference type. // public virtual List<T?> P { get; set; } = default; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(6, 47)); } [Fact] public void Overriding_Indexer() { var source = @" public class List<T> { } public class Base { public virtual List<string[]> this[List<string[]> x] { get => throw null!; set => throw null!; } } public class Class : Base { #nullable disable public override List<string[]> this[List<string[]> x] { get => throw null!; set => throw null!; } } public class Class2 : Base { #nullable enable public override List<string[]> this[List<string[]> x] { get => throw null!; set => throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Overriding_Indexer2() { var source = @" #nullable enable public class List<T> { } public class Oblivious { #nullable disable public virtual List<string[]> this[List<string[]> x] { get => throw null!; set => throw null!; } } #nullable enable public class Class : Oblivious { public override List<string[]> this[List<string[]> x] { get => throw null!; set => throw null!; } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); } [Fact] public void Overriding_21() { var source = @" class C { public static void Main() { } } abstract class A { public abstract event System.Action<string> E1; public abstract event System.Action<string>? E2; } class B1 : A { #nullable disable annotations public override event System.Action<string?> E1 {add {} remove{}} // 1 #nullable disable annotations public override event System.Action<string> E2 {add {} remove{}} } #nullable enable class B2 : A { #nullable disable annotations public override event System.Action<string?> E1; // 3 #nullable disable annotations public override event System.Action<string> E2; #nullable enable void Dummy() { var e1 = E1; var e2 = E2; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (19,47): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override event System.Action<string?> E1 {add {} remove{}} // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(19, 47), // (19,50): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event System.Action<string?> E1 {add {} remove{}} // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E1").WithLocation(19, 50), // (27,47): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override event System.Action<string?> E1; // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(27, 47), // (27,50): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event System.Action<string?> E1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E1").WithLocation(27, 50) ); } [Fact] public void Implementing_01() { var source = @" class C { public static void Main() { } } interface IA { event System.Action<string> E1; event System.Action<string>? E2; event System.Action<string?>? E3; } class B1 : IA { public event System.Action<string?> E1 {add {} remove{}} public event System.Action<string> E2 {add {} remove{}} public event System.Action<string?>? E3 {add {} remove{}} } class B2 : IA { public event System.Action<string?> E1; // 2 public event System.Action<string> E2; // 2 public event System.Action<string?>? E3; // 2 void Dummy() { var e1 = E1; var e2 = E2; var e3 = E3; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (26,40): warning CS8612: Nullability of reference types in type of 'event Action<string> B2.E2' doesn't match implicitly implemented member 'event Action<string>? IA.E2'. // public event System.Action<string> E2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "E2").WithArguments("event Action<string> B2.E2", "event Action<string>? IA.E2").WithLocation(26, 40), // (25,41): warning CS8612: Nullability of reference types in type of 'event Action<string?> B2.E1' doesn't match implicitly implemented member 'event Action<string> IA.E1'. // public event System.Action<string?> E1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "E1").WithArguments("event Action<string?> B2.E1", "event Action<string> IA.E1").WithLocation(25, 41), // (19,40): warning CS8612: Nullability of reference types in type of 'event Action<string> B1.E2' doesn't match implicitly implemented member 'event Action<string>? IA.E2'. // public event System.Action<string> E2 {add {} remove{}} Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "E2").WithArguments("event Action<string> B1.E2", "event Action<string>? IA.E2").WithLocation(19, 40), // (18,41): warning CS8612: Nullability of reference types in type of 'event Action<string?> B1.E1' doesn't match implicitly implemented member 'event Action<string> IA.E1'. // public event System.Action<string?> E1 {add {} remove{}} Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "E1").WithArguments("event Action<string?> B1.E1", "event Action<string> IA.E1").WithLocation(18, 41), // (25,41): warning CS8618: Non-nullable event 'E1' is uninitialized. Consider declaring the event as nullable. // public event System.Action<string?> E1; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(25, 41), // (26,40): warning CS8618: Non-nullable event 'E2' is uninitialized. Consider declaring the event as nullable. // public event System.Action<string> E2; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E2").WithArguments("event", "E2").WithLocation(26, 40) ); var ia = compilation.GetTypeByMetadataName("IA"); foreach (string memberName in new[] { "E1", "E2" }) { var member = ia.GetMember<EventSymbol>(memberName); foreach (string typeName in new[] { "B1", "B2" }) { var type = compilation.GetTypeByMetadataName(typeName); var impl = (EventSymbol)type.FindImplementationForInterfaceMember(member); Assert.False(impl.TypeWithAnnotations.Equals(member.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } var e3 = ia.GetMember<EventSymbol>("E3"); foreach (string typeName in new[] { "B1", "B2" }) { var type = compilation.GetTypeByMetadataName(typeName); var impl = (EventSymbol)type.FindImplementationForInterfaceMember(e3); Assert.True(impl.TypeWithAnnotations.Equals(e3.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA", "B1", "B2" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var ev in type.GetMembers().OfType<EventSymbol>()) { Assert.True(ev.TypeWithAnnotations.Equals(ev.AddMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(ev.TypeWithAnnotations.Equals(ev.RemoveMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Implementing_02() { var source = @" class C { public static void Main() { } } interface IA { event System.Action<string> E1; event System.Action<string>? E2; event System.Action<string?>? E3; } class B1 : IA { event System.Action<string?> IA.E1 {add {} remove{}} event System.Action<string> IA.E2 {add {} remove{}} event System.Action<string?>? IA.E3 {add {} remove{}} } interface IB { //event System.Action<string> E1; //event System.Action<string>? E2; event System.Action<string?>? E3; } class B2 : IB { //event System.Action<string?> IB.E1; // 2 //event System.Action<string> IB.E2; // 2 event System.Action<string?>? IB.E3; // 2 } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (34,38): error CS0071: An explicit interface implementation of an event must use event accessor syntax // event System.Action<string?>? IB.E3; // 2 Diagnostic(ErrorCode.ERR_ExplicitEventFieldImpl, "E3").WithLocation(34, 38), // (30,12): error CS0535: 'B2' does not implement interface member 'IB.E3.remove' // class B2 : IB Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IB").WithArguments("B2", "IB.E3.remove").WithLocation(30, 12), // (30,12): error CS0535: 'B2' does not implement interface member 'IB.E3.add' // class B2 : IB Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IB").WithArguments("B2", "IB.E3.add").WithLocation(30, 12), // (19,36): warning CS8615: Nullability of reference types in type doesn't match implemented member 'event Action<string>? IA.E2'. // event System.Action<string> IA.E2 {add {} remove{}} Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, "E2").WithArguments("event Action<string>? IA.E2").WithLocation(19, 36), // (18,37): warning CS8615: Nullability of reference types in type doesn't match implemented member 'event Action<string> IA.E1'. // event System.Action<string?> IA.E1 {add {} remove{}} Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, "E1").WithArguments("event Action<string> IA.E1").WithLocation(18, 37) ); var ia = compilation.GetTypeByMetadataName("IA"); var b1 = compilation.GetTypeByMetadataName("B1"); foreach (string memberName in new[] { "E1", "E2" }) { var member = ia.GetMember<EventSymbol>(memberName); var impl = (EventSymbol)b1.FindImplementationForInterfaceMember(member); Assert.False(impl.TypeWithAnnotations.Equals(member.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } var e3 = ia.GetMember<EventSymbol>("E3"); { var impl = (EventSymbol)b1.FindImplementationForInterfaceMember(e3); Assert.True(impl.TypeWithAnnotations.Equals(e3.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA", "B1" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var ev in type.GetMembers().OfType<EventSymbol>()) { Assert.True(ev.TypeWithAnnotations.Equals(ev.AddMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(ev.TypeWithAnnotations.Equals(ev.RemoveMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Overriding_17() { var source = @"#pragma warning disable 8618 class C { public static void Main() { } } abstract class A1 { public abstract string?[] P1 {get; set;} public abstract string[] P2 {get; set;} public abstract string?[] this[int x] {get; set;} public abstract string[] this[short x] {get; set;} } abstract class A2 { public abstract string?[]? P3 {get; set;} public abstract string?[]? this[long x] {get; set;} } class B1 : A1 { public override string[] P1 {get; set;} public override string[]? P2 {get; set;} public override string[] this[int x] // 1 { get {throw new System.NotImplementedException();} set {} } public override string[]? this[short x] // 2 { get {throw new System.NotImplementedException();} set {} } } class B2 : A2 { public override string?[]? P3 {get; set;} public override string?[]? this[long x] // 3 { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (27,39): warning CS8610: Nullability of reference types in type of parameter 'value' doesn't match overridden member. // public override string[] P1 {get; set;} Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(27, 39), // (28,35): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override string[]? P2 {get; set;} Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(28, 35), // (33,9): warning CS8610: Nullability of reference types in type of parameter 'value' doesn't match overridden member. // set {} Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(33, 9), // (38,9): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // get {throw new System.NotImplementedException();} Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(38, 9) ); foreach (var member in compilation.GetTypeByMetadataName("B1").GetMembers().OfType<PropertySymbol>()) { Assert.False(member.TypeWithAnnotations.Equals(member.OverriddenProperty.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (var member in compilation.GetTypeByMetadataName("B2").GetMembers().OfType<PropertySymbol>()) { Assert.True(member.TypeWithAnnotations.Equals(member.OverriddenProperty.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "A1", "B1", "A2", "B2" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var property in type.GetMembers().OfType<PropertySymbol>()) { Assert.True(property.TypeWithAnnotations.Equals(property.GetMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(property.TypeWithAnnotations.Equals(property.SetMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Overriding_22() { var source = @"#pragma warning disable 8618 class C { public static void Main() { } } abstract class A1 { public abstract string?[] P1 {get; set;} // 1 public abstract string[] P2 {get; set;} public abstract string?[] this[int x] {get; set;} // 2 public abstract string[] this[short x] {get; set;} } class B1 : A1 { #nullable disable public override string[] P1 {get; set;} #nullable disable public override string[]? P2 {get; set;} // 3 #nullable disable public override string[] this[int x] { get {throw new System.NotImplementedException();} set {} } #nullable disable public override string[]? this[short x] // 4 { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }); compilation.VerifyDiagnostics( // (14,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public abstract string?[] this[int x] {get; set;} // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(14, 27), // (11,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public abstract string?[] P1 {get; set;} // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 27), // (23,29): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override string[]? P2 {get; set;} // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(23, 29), // (33,29): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override string[]? this[short x] // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(33, 29) ); } [Fact] public void Implementing_03() { var source = @"#pragma warning disable 8618 class C { public static void Main() { } } interface IA { string?[] P1 {get; set;} string[] P2 {get; set;} string?[] this[int x] {get; set;} string[] this[short x] {get; set;} } interface IA2 { string?[]? P3 {get; set;} string?[]? this[long x] {get; set;} } class B : IA, IA2 { public string[] P1 {get; set;} public string[]? P2 {get; set;} public string?[]? P3 {get; set;} public string[] this[int x] { get {throw new System.NotImplementedException();} set {} // 1 } public string[]? this[short x] { get {throw new System.NotImplementedException();} // 2 set {} } public string?[]? this[long x] { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (23,26): warning CS8766: Nullability of reference types in return type of 'string[]? B.P2.get' doesn't match implicitly implemented member 'string[] IA.P2.get' (possibly because of nullability attributes). // public string[]? P2 {get; set;} Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("string[]? B.P2.get", "string[] IA.P2.get").WithLocation(23, 26), // (29,9): warning CS8614: Nullability of reference types in type of parameter 'value' of 'void B.this[int x].set' doesn't match implicitly implemented member 'void IA.this[int x].set'. // set {} // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void B.this[int x].set", "void IA.this[int x].set").WithLocation(29, 9), // (34,9): warning CS8766: Nullability of reference types in return type of 'string[]? B.this[short x].get' doesn't match implicitly implemented member 'string[] IA.this[short x].get' (possibly because of nullability attributes). // get {throw new System.NotImplementedException();} // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("string[]? B.this[short x].get", "string[] IA.this[short x].get").WithLocation(34, 9), // (22,30): warning CS8614: Nullability of reference types in type of parameter 'value' of 'void B.P1.set' doesn't match implicitly implemented member 'void IA.P1.set'. // public string[] P1 {get; set;} Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void B.P1.set", "void IA.P1.set").WithLocation(22, 30) ); var b = compilation.GetTypeByMetadataName("B"); foreach (var member in compilation.GetTypeByMetadataName("IA").GetMembers().OfType<PropertySymbol>()) { var impl = (PropertySymbol)b.FindImplementationForInterfaceMember(member); Assert.False(impl.TypeWithAnnotations.Equals(member.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (var member in compilation.GetTypeByMetadataName("IA2").GetMembers().OfType<PropertySymbol>()) { var impl = (PropertySymbol)b.FindImplementationForInterfaceMember(member); Assert.True(impl.TypeWithAnnotations.Equals(member.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA", "IA2", "B" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var property in type.GetMembers().OfType<PropertySymbol>()) { Assert.True(property.TypeWithAnnotations.Equals(property.GetMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(property.TypeWithAnnotations.Equals(property.SetMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Implementing_04() { var source = @"#pragma warning disable 8618 class C { public static void Main() { } } interface IA { string?[] P1 {get; set;} string[] P2 {get; set;} string?[] this[int x] {get; set;} string[] this[short x] {get; set;} } interface IA2 { string?[]? P3 {get; set;} string?[]? this[long x] {get; set;} } class B : IA, IA2 { string[] IA.P1 {get; set;} string[]? IA.P2 {get; set;} string?[]? IA2.P3 {get; set;} string[] IA.this[int x] { get {throw new System.NotImplementedException();} set {} // 1 } string[]? IA.this[short x] { get {throw new System.NotImplementedException();} // 2 set {} } string?[]? IA2.this[long x] { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (22,26): warning CS8617: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void IA.P1.set'. // string[] IA.P1 {get; set;} Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void IA.P1.set").WithLocation(22, 26), // (23,22): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'string[] IA.P2.get' (possibly because of nullability attributes). // string[]? IA.P2 {get; set;} Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("string[] IA.P2.get").WithLocation(23, 22), // (29,9): warning CS8617: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void IA.this[int x].set'. // set {} // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void IA.this[int x].set").WithLocation(29, 9), // (34,9): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'string[] IA.this[short x].get' (possibly because of nullability attributes). // get {throw new System.NotImplementedException();} // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("string[] IA.this[short x].get").WithLocation(34, 9) ); var b = compilation.GetTypeByMetadataName("B"); foreach (var member in compilation.GetTypeByMetadataName("IA").GetMembers().OfType<PropertySymbol>()) { var impl = (PropertySymbol)b.FindImplementationForInterfaceMember(member); Assert.False(impl.TypeWithAnnotations.Equals(member.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (var member in compilation.GetTypeByMetadataName("IA2").GetMembers().OfType<PropertySymbol>()) { var impl = (PropertySymbol)b.FindImplementationForInterfaceMember(member); Assert.True(impl.TypeWithAnnotations.Equals(member.TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA", "IA2", "B" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var property in type.GetMembers().OfType<PropertySymbol>()) { Assert.True(property.TypeWithAnnotations.Equals(property.GetMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(property.TypeWithAnnotations.Equals(property.SetMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Overriding_18() { var source = @" class C { public static void Main() { } } abstract class A { public abstract string[] M1(); public abstract T[] M2<T>() where T : class; public abstract T?[]? M3<T>() where T : class; } class B : A { public override string?[] M1() { return new string?[] {}; } public override S?[] M2<S>() { return new S?[] {}; } public override S?[]? M3<S>() { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (23,26): error CS0508: 'B.M2<S>()': return type must be 'S[]' to match overridden member 'A.M2<T>()' // public override S?[] M2<S>() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("B.M2<S>()", "A.M2<T>()", "S[]").WithLocation(23, 26), // (28,27): error CS0508: 'B.M3<S>()': return type must be 'S?[]' to match overridden member 'A.M3<T>()' // public override S?[]? M3<S>() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M3").WithArguments("B.M3<S>()", "A.M3<T>()", "S?[]").WithLocation(28, 27), // (18,31): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override string?[] M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M1").WithLocation(18, 31), // (23,26): error CS0453: The type 'S' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override S?[] M2<S>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M2").WithArguments("System.Nullable<T>", "T", "S").WithLocation(23, 26), // (28,27): error CS0453: The type 'S' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override S?[]? M3<S>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M3").WithArguments("System.Nullable<T>", "T", "S").WithLocation(28, 27)); var b = compilation.GetTypeByMetadataName("B"); foreach (string memberName in new[] { "M1", "M2", "M3" }) { var member = b.GetMember<MethodSymbol>(memberName); Assert.False(member.ReturnTypeWithAnnotations.Equals(member.OverriddenMethod.ConstructIfGeneric(member.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))).ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } [Fact] [WorkItem(28684, "https://github.com/dotnet/roslyn/issues/28684")] public void Overriding_23() { var source = @" class C { public static void Main() { } } abstract class A { public abstract string[] M1(); public abstract T[] M2<T>() where T : class; } class B : A { #nullable disable annotations public override string?[] M1() { return new string?[] {}; } #nullable disable annotations public override S?[] M2<S>() { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (24,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override S?[] M2<S>() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(24, 22), // (18,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override string?[] M1() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 27), // (24,26): error CS0508: 'B.M2<S>()': return type must be 'S[]' to match overridden member 'A.M2<T>()' // public override S?[] M2<S>() Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "M2").WithArguments("B.M2<S>()", "A.M2<T>()", "S[]").WithLocation(24, 26), // (18,31): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override string?[] M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M1").WithLocation(18, 31), // (24,26): error CS0453: The type 'S' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override S?[] M2<S>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M2").WithArguments("System.Nullable<T>", "T", "S").WithLocation(24, 26), // (20,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // return new string?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(20, 26), // (26,21): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // return new S?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(26, 21) ); } [Fact] public void Implementing_05() { var source = @" class C { public static void Main() { } } interface IA { string[] M1(); T[] M2<T>() where T : class; T?[]? M3<T>() where T : class; } class B : IA { public string?[] M1() { return new string?[] {}; } public S?[] M2<S>() where S : class { return new S?[] {}; } public S?[]? M3<S>() where S : class { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (23,17): warning CS8613: Nullability of reference types in return type of 'S?[] B.M2<S>()' doesn't match implicitly implemented member 'T[] IA.M2<T>()'. // public S?[] M2<S>() where S : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "M2").WithArguments("S?[] B.M2<S>()", "T[] IA.M2<T>()").WithLocation(23, 17), // (18,22): warning CS8613: Nullability of reference types in return type of 'string?[] B.M1()' doesn't match implicitly implemented member 'string[] IA.M1()'. // public string?[] M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "M1").WithArguments("string?[] B.M1()", "string[] IA.M1()").WithLocation(18, 22) ); var ia = compilation.GetTypeByMetadataName("IA"); var b = compilation.GetTypeByMetadataName("B"); foreach (var memberName in new[] { "M1", "M2" }) { var member = ia.GetMember<MethodSymbol>(memberName); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.False(implementing.ReturnTypeWithAnnotations.Equals(implemented.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var member = ia.GetMember<MethodSymbol>("M3"); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.True(implementing.ReturnTypeWithAnnotations.Equals(implemented.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } [Fact] public void Implementing_06() { var source = @" class C { public static void Main() { } } interface IA { string[] M1(); T[] M2<T>() where T : class; T?[]? M3<T>() where T : class; } class B : IA { string?[] IA.M1() { return new string?[] {}; } S?[] IA.M2<S>() { return new S?[] {}; } S?[]? IA.M3<S>() { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (23,13): error CS0539: 'B.M2<S>()' in explicit interface declaration is not found among members of the interface that can be implemented // S?[] IA.M2<S>() Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M2").WithArguments("B.M2<S>()").WithLocation(23, 13), // (28,14): error CS0539: 'B.M3<S>()' in explicit interface declaration is not found among members of the interface that can be implemented // S?[]? IA.M3<S>() Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M3").WithArguments("B.M3<S>()").WithLocation(28, 14), // (18,18): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'string[] IA.M1()'. // string?[] IA.M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M1").WithArguments("string[] IA.M1()").WithLocation(18, 18), // (16,11): error CS0535: 'B' does not implement interface member 'IA.M3<T>()' // class B : IA Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IA").WithArguments("B", "IA.M3<T>()").WithLocation(16, 11), // (16,11): error CS0535: 'B' does not implement interface member 'IA.M2<T>()' // class B : IA Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IA").WithArguments("B", "IA.M2<T>()").WithLocation(16, 11), // (23,13): error CS0453: The type 'S' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // S?[] IA.M2<S>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M2").WithArguments("System.Nullable<T>", "T", "S").WithLocation(23, 13), // (28,14): error CS0453: The type 'S' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // S?[]? IA.M3<S>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M3").WithArguments("System.Nullable<T>", "T", "S").WithLocation(28, 14), // (25,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // return new S?[] {}; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "S?").WithArguments("9.0").WithLocation(25, 20), // (30,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // return new S?[] {}; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "S?").WithArguments("9.0").WithLocation(30, 20) ); var ia = compilation.GetTypeByMetadataName("IA"); var b = compilation.GetTypeByMetadataName("B"); var member = ia.GetMember<MethodSymbol>("M1"); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.False(implementing.ReturnTypeWithAnnotations.Equals(implemented.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); member = ia.GetMember<MethodSymbol>("M2"); Assert.Null(b.FindImplementationForInterfaceMember(member)); member = ia.GetMember<MethodSymbol>("M3"); Assert.Null(b.FindImplementationForInterfaceMember(member)); } [Fact] public void ImplementingNonNullWithNullable_01() { var source = @" interface IA { string[] M1(); T[] M2<T>() where T : class; } class B : IA { #nullable disable annotations string?[] IA.M1() { return new string?[] {}; } #nullable disable annotations S?[] IA.M2<S>() { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (17,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // S?[] IA.M2<S>() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 6), // (17,13): error CS0539: 'B.M2<S>()' in explicit interface declaration is not found among members of the interface that can be implemented // S?[] IA.M2<S>() Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M2").WithArguments("B.M2<S>()").WithLocation(17, 13), // (11,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string?[] IA.M1() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 11), // (11,18): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'string[] IA.M1()'. // string?[] IA.M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M1").WithArguments("string[] IA.M1()").WithLocation(11, 18), // (8,11): error CS0535: 'B' does not implement interface member 'IA.M2<T>()' // class B : IA Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IA").WithArguments("B", "IA.M2<T>()").WithLocation(8, 11), // (17,13): error CS0453: The type 'S' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // S?[] IA.M2<S>() Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "M2").WithArguments("System.Nullable<T>", "T", "S").WithLocation(17, 13), // (13,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // return new string?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 26), // (19,21): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // return new S?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(19, 21), // (19,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // return new S?[] {}; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "S?").WithArguments("9.0").WithLocation(19, 20) ); } [Fact] [WorkItem(28684, "https://github.com/dotnet/roslyn/issues/28684")] public void ImplementingNonNullWithNullable_02() { var source = @" interface IA { string[] M1(); T[] M2<T>() where T : class; } class B : IA { #nullable disable annotations string?[] IA.M1() { return new string?[] {}; } #nullable disable annotations S?[] IA.M2<S>() where S : class { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var returnStatement = tree.GetRoot().DescendantNodes().OfType<ReturnStatementSyntax>().Skip(1).Single(); AssertEx.Equal("S?[]", model.GetTypeInfo(returnStatement.Expression).Type.ToTestDisplayString()); compilation.VerifyDiagnostics( // (17,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // S?[] IA.M2<S>() where S : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 6), // (17,13): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'T[] IA.M2<T>()'. // S?[] IA.M2<S>() where S : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M2").WithArguments("T[] IA.M2<T>()").WithLocation(17, 13), // (11,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string?[] IA.M1() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 11), // (11,18): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'string[] IA.M1()'. // string?[] IA.M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M1").WithArguments("string[] IA.M1()").WithLocation(11, 18), // (13,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // return new string?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 26), // (19,21): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // return new S?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(19, 21) ); } [Fact] public void ImplementingNullableWithNonNull_ReturnType() { var source = @" interface IA { #nullable disable string?[] M1(); #nullable disable T?[] M2<T>() where T : class; } #nullable enable class B : IA { string[] IA.M1() => throw null!; S[] IA.M2<S>() => throw null!; } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (7,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T?[] M2<T>() where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 6), // (7,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T?[] M2<T>() where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 5), // (5,11): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // string?[] M1(); Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 11) ); } [Fact] public void ImplementingNullableWithNonNull_Parameter() { var source = @" interface IA { #nullable disable void M1(string?[] x); #nullable disable void M2<T>(T?[] x) where T : class; } #nullable enable class B : IA { void IA.M1(string[] x) => throw null!; void IA.M2<S>(S[] x) => throw null!; } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (5,19): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M1(string?[] x); Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 19), // (7,16): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void M2<T>(T?[] x) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 16), // (7,17): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M2<T>(T?[] x) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 17), // (12,13): warning CS8617: Nullability of reference types in type of parameter 'x' doesn't match implemented member 'void IA.M1(string?[] x)'. // void IA.M1(string[] x) => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "M1").WithArguments("x", "void IA.M1(string?[] x)").WithLocation(12, 13), // (13,13): warning CS8617: Nullability of reference types in type of parameter 'x' doesn't match implemented member 'void IA.M2<T>(T?[] x)'. // void IA.M2<S>(S[] x) Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "M2").WithArguments("x", "void IA.M2<T>(T?[] x)").WithLocation(13, 13) ); } [Fact] public void ImplementingObliviousWithNonNull() { var source = @" interface IA { #nullable disable string[] M1(); #nullable disable T[] M2<T>() where T : class; } #nullable enable class B : IA { string[] IA.M1() => throw null!; S[] IA.M2<S>() => throw null!; } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); } [Fact] public void Overriding_19() { var source = @" class C { public static void Main() { } } abstract class A { public abstract void M1(string[] x); public abstract void M2<T>(T[] x) where T : class; public abstract void M3<T>(T?[]? x) where T : class; } class B : A { public override void M1(string?[] x) { } public override void M2<T>(T?[] x) { } public override void M3<T>(T?[]? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (22,26): error CS0115: 'B.M2<T>(T?[])': no suitable method found to override // public override void M2<T>(T?[] x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M2").WithArguments("B.M2<T>(T?[])").WithLocation(22, 26), // (26,26): error CS0115: 'B.M3<T>(T?[]?)': no suitable method found to override // public override void M3<T>(T?[]? x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M3").WithArguments("B.M3<T>(T?[]?)").WithLocation(26, 26), // (16,7): error CS0534: 'B' does not implement inherited abstract member 'A.M3<T>(T?[]?)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.M3<T>(T?[]?)").WithLocation(16, 7), // (16,7): error CS0534: 'B' does not implement inherited abstract member 'A.M2<T>(T[])' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.M2<T>(T[])").WithLocation(16, 7), // (22,37): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M2<T>(T?[] x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(22, 37), // (26,38): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M3<T>(T?[]? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(26, 38) ); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.False(m1.Parameters[0].TypeWithAnnotations.Equals(m1.OverriddenMethod.ConstructIfGeneric(m1.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))).Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); var m2 = b.GetMember<MethodSymbol>("M2"); Assert.Null(m2.OverriddenMethod); var m3 = b.GetMember<MethodSymbol>("M3"); Assert.Null(m3.OverriddenMethod); } [Fact] [WorkItem(28684, "https://github.com/dotnet/roslyn/issues/28684")] public void Overriding_24() { var source = @" #nullable enable abstract class A { public abstract void M1(string[] x); public abstract void M2<T>(T[] x) where T : class; } class B : A { #nullable disable public override void M1(string?[] x) { } #nullable disable public override void M2<T>(T?[] x) { } } "; var compilation = CreateCompilation(new[] { source }); compilation.VerifyDiagnostics( // (18,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override void M2<T>(T?[] x) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 33), // (13,35): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override void M1(string?[] x) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 35), // (18,26): error CS0115: 'B.M2<T>(T?[])': no suitable method found to override // public override void M2<T>(T?[] x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M2").WithArguments("B.M2<T>(T?[])").WithLocation(18, 26), // (10,7): error CS0534: 'B' does not implement inherited abstract member 'A.M2<T>(T[])' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.M2<T>(T[])").WithLocation(10, 7), // (18,37): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M2<T>(T?[] x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(18, 37) ); } [Fact] public void Overriding_25() { var ilSource = @" .assembly extern mscorlib { .publickeytoken = (B7 7A 5C 56 19 34 E0 89 ) // .z\V.4.. .ver 4:0:0:0 } .assembly '<<GeneratedFileName>>' { } .module '<<GeneratedFileName>>.dll' .class public auto ansi beforefieldinit C`2<T,S> extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method C`2::.ctor } // end of class C`2 .class public abstract auto ansi beforefieldinit A extends [mscorlib]System.Object { .method public hidebysig newslot abstract virtual instance class C`2<string modopt([mscorlib]System.Runtime.CompilerServices.IsConst),string> M1() cil managed { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 01 02 01 00 00 ) } // end of method A::M1 .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method A::.ctor } // end of class A .class public auto ansi beforefieldinit System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 86 6B 00 00 01 00 54 02 0D 41 6C 6C 6F 77 // ...k....T..Allow 4D 75 6C 74 69 70 6C 65 00 ) // Multiple. .method public hidebysig specialname rtspecialname instance void .ctor(uint8 transformFlag) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method NullableAttribute::.ctor .method public hidebysig specialname rtspecialname instance void .ctor(uint8[] transformFlags) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method NullableAttribute::.ctor } // end of class System.Runtime.CompilerServices.NullableAttribute "; var source = @" class C { public static void Main() { } } class B : A { public override C<string, string?> M1() { return new C<string, string?>(); } } "; var compilation = CreateCompilation(new[] { source }, new[] { CompileIL(ilSource, prependDefaultHeader: false) }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); var m1 = compilation.GetTypeByMetadataName("B").GetMember<MethodSymbol>("M1"); Assert.Equal("C<System.String? modopt(System.Runtime.CompilerServices.IsConst), System.String>", m1.OverriddenMethod.ReturnTypeWithAnnotations.ToTestDisplayString()); Assert.Equal("C<System.String modopt(System.Runtime.CompilerServices.IsConst), System.String?>", m1.ReturnTypeWithAnnotations.ToTestDisplayString()); compilation.VerifyDiagnostics( // (11,40): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override C<string, string?> M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M1").WithLocation(11, 40) ); } [Fact] public void Overriding_26() { var source = @" class A { public virtual void M1<T>(T? x) where T : class { } public virtual T? M2<T>() where T : class { return null; } } class B : A { public override void M1<T>(T? x) where T : class { } public override T? M2<T>() where T : class { return null; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.False(m1.Parameters[0].Type.IsNullableType()); Assert.Equal(NullableAnnotation.Annotated, m1.Parameters[0].TypeWithAnnotations.NullableAnnotation); Assert.True(m1.Parameters[0].Type.IsReferenceType); Assert.False(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); var m2 = b.GetMember<MethodSymbol>("M2"); Assert.False(m2.ReturnType.IsNullableType()); Assert.Equal(NullableAnnotation.Annotated, m2.ReturnTypeWithAnnotations.NullableAnnotation); Assert.True(m2.ReturnType.IsReferenceType); Assert.False(m2.OverriddenMethod.ReturnType.IsNullableType()); } [Fact] public void Overriding_27() { var source = @" class A { public virtual void M1<T>(System.Nullable<T> x) where T : struct { } public virtual void M2<T>(T? x) where T : struct { } public virtual void M3<T>(C<T?> x) where T : struct { } public virtual void M4<T>(C<System.Nullable<T>> x) where T : struct { } public virtual void M5<T>(C<T?> x) where T : class { } } class B : A { public override void M1<T>(T? x) { } public override void M2<T>(T? x) { } public override void M3<T>(C<T?> x) { } public override void M4<T>(C<T?> x) { } public override void M5<T>(C<T?> x) where T : class { } } class C<T> {} "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m3 = b.GetMember<MethodSymbol>("M3"); var m4 = b.GetMember<MethodSymbol>("M4"); var m5 = b.GetMember<MethodSymbol>("M5"); Assert.True(((NamedTypeSymbol)m3.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m3.OverriddenMethod.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m4.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.True(((NamedTypeSymbol)m4.OverriddenMethod.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.False(((NamedTypeSymbol)m5.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); Assert.False(((NamedTypeSymbol)m5.OverriddenMethod.Parameters[0].Type).TypeArgumentsWithAnnotationsNoUseSiteDiagnostics[0].IsNullableType()); } [Fact] public void Overriding_28() { var source = @" class C { public static void Main() { } } abstract class A { public abstract string[] M1(); public abstract T[] M2<T>() where T : class; public abstract T?[]? M3<T>() where T : class; } class B : A { public override string?[] M1() { return new string?[] {}; } public override S?[] M2<S>() where S : class { return new S?[] {}; } public override S?[]? M3<S>() where S : class { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (23,26): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override S?[] M2<S>() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(23, 26), // (18,31): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override string?[] M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M1").WithLocation(18, 31) ); var b = compilation.GetTypeByMetadataName("B"); foreach (string memberName in new[] { "M1", "M2" }) { var member = b.GetMember<MethodSymbol>(memberName); Assert.False(member.ReturnTypeWithAnnotations.Equals(member.OverriddenMethod.ConstructIfGeneric(member.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))).ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } var m3 = b.GetMember<MethodSymbol>("M3"); Assert.True(m3.ReturnTypeWithAnnotations.Equals(m3.OverriddenMethod.ConstructIfGeneric(m3.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))).ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } [Fact] [WorkItem(28684, "https://github.com/dotnet/roslyn/issues/28684")] public void Overriding_29() { var source = @" class C { public static void Main() { } } abstract class A { public abstract string[] M1(); public abstract T[] M2<T>() where T : class; } class B : A { #nullable disable annotations public override string?[] M1() { return new string?[] {}; } #nullable disable annotations public override S?[] M2<S>() where S : class { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (18,31): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override string?[] M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M1").WithLocation(18, 31), // (24,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override S?[] M2<S>() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(24, 22), // (24,26): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override S?[] M2<S>() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(24, 26), // (18,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override string?[] M1() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 27), // (20,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // return new string?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(20, 26), // (26,21): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // return new S?[] {}; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(26, 21) ); } [Fact] public void Overriding_30() { var source = @" class C { public static void Main() { } } abstract class A { public abstract void M1(string[] x); public abstract void M2<T>(T[] x) where T : class; public abstract void M3<T>(T?[]? x) where T : class; } class B : A { public override void M1(string?[] x) { } public override void M2<T>(T?[] x) where T : class { } public override void M3<T>(T?[]? x) where T : class { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( ); var b = compilation.GetTypeByMetadataName("B"); foreach (string memberName in new[] { "M1", "M2" }) { var member = b.GetMember<MethodSymbol>(memberName); Assert.False(member.Parameters[0].TypeWithAnnotations.Equals(member.OverriddenMethod.ConstructIfGeneric(member.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))).Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } var m3 = b.GetMember<MethodSymbol>("M3"); Assert.True(m3.Parameters[0].TypeWithAnnotations.Equals(m3.OverriddenMethod.ConstructIfGeneric(m3.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))).Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } [Fact] [WorkItem(28684, "https://github.com/dotnet/roslyn/issues/28684")] public void Overriding_31() { var source = @" #nullable enable abstract class A { public abstract void M1(string[] x); public abstract void M2<T>(T[] x) where T : class; } class B : A { #nullable disable public override void M1(string?[] x) { } #nullable disable public override void M2<T>(T?[] x) where T : class { } } "; var compilation = CreateCompilation(new[] { source }); compilation.VerifyDiagnostics( // (18,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override void M2<T>(T?[] x) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 33), // (13,35): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public override void M1(string?[] x) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 35) ); } [Fact] [WorkItem(29847, "https://github.com/dotnet/roslyn/issues/29847")] public void Overriding_32() { var source = @" class A { public virtual void M1<T>(T? x) where T : struct { } public virtual void M1<T>(T? x) where T : class { } } class B : A { public override void M1<T>(T? x) where T : class { } } class C { public virtual void M2<T>(T? x) where T : class { } public virtual void M2<T>(T? x) where T : struct { } } class D : C { public override void M2<T>(T? x) where T : class { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.False(m1.Parameters[0].Type.IsNullableType()); Assert.False(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); var d = compilation.GetTypeByMetadataName("D"); var m2 = d.GetMember<MethodSymbol>("M2"); Assert.False(m2.Parameters[0].Type.IsNullableType()); Assert.False(m2.OverriddenMethod.Parameters[0].Type.IsNullableType()); } [Fact] [WorkItem(29847, "https://github.com/dotnet/roslyn/issues/29847")] public void Overriding_33() { var source = @" class A { public virtual void M1<T>(T? x) where T : struct { } public virtual void M1<T>(T? x) where T : class { } } class B : A { public override void M1<T>(T? x) where T : struct { } } class C { public virtual void M2<T>(T? x) where T : class { } public virtual void M2<T>(T? x) where T : struct { } } class D : C { public override void M2<T>(T? x) where T : struct { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var b = compilation.GetTypeByMetadataName("B"); var m1 = b.GetMember<MethodSymbol>("M1"); Assert.True(m1.Parameters[0].Type.IsNullableType()); Assert.True(m1.OverriddenMethod.Parameters[0].Type.IsNullableType()); var d = compilation.GetTypeByMetadataName("D"); var m2 = d.GetMember<MethodSymbol>("M2"); Assert.True(m2.Parameters[0].Type.IsNullableType()); Assert.True(m2.OverriddenMethod.Parameters[0].Type.IsNullableType()); } [Fact] [WorkItem(33276, "https://github.com/dotnet/roslyn/issues/33276")] public void Overriding_34() { var source1 = @" public class MyEntity { } public abstract class BaseController<T> where T : MyEntity { public abstract void SomeMethod<R>(R? lite) where R : MyEntity; } "; var source2 = @" class DerivedController<T> : BaseController<T> where T : MyEntity { Table<T> table = null!; public override void SomeMethod<R>(R? lite) where R : class { table.OtherMethod(lite); } } class Table<T> where T : MyEntity { public void OtherMethod<R>(R? lite) where R : MyEntity { lite?.ToString(); } } "; var compilation1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { var compilation2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { reference }); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2); } } [Fact] [WorkItem(31676, "https://github.com/dotnet/roslyn/issues/31676")] public void Overriding_35() { var source1 = @" using System; namespace Microsoft.EntityFrameworkCore.TestUtilities { public abstract class QueryAsserterBase { public abstract void AssertQueryScalar<TItem1, TResult>( Func<IQueryable<TItem1>, IQueryable<Nullable<TResult>>> actualQuery) where TResult : struct; } } public interface IQueryable<out T> { } "; var source2 = @" using System; namespace Microsoft.EntityFrameworkCore.TestUtilities { public class QueryAsserter<TContext> : QueryAsserterBase { public override void AssertQueryScalar<TItem1, TResult>( Func<IQueryable<TItem1>, IQueryable<TResult?>> actualQuery) { } } } "; foreach (var options1 in new[] { WithNullableEnable(), WithNullableDisable() }) { var compilation1 = CreateCompilation(new[] { source1 }, options: options1); compilation1.VerifyDiagnostics(); foreach (var reference in new[] { compilation1.ToMetadataReference(), compilation1.EmitToImageReference() }) { foreach (var options2 in new[] { WithNullableEnable(), WithNullableDisable() }) { var compilation2 = CreateCompilation(new[] { source2 }, options: options2, references: new[] { reference }); compilation2.VerifyDiagnostics(); CompileAndVerify(compilation2); } } var compilation3 = CreateCompilation(new[] { source1, source2 }, options: options1); compilation3.VerifyDiagnostics(); CompileAndVerify(compilation3); var compilation4 = CreateCompilation(new[] { source2, source1 }, options: options1); compilation4.VerifyDiagnostics(); CompileAndVerify(compilation4); } } [Fact] [WorkItem(38403, "https://github.com/dotnet/roslyn/issues/38403")] public void Overriding_36() { var source = @" #nullable enable using System; using System.Collections.Generic; using System.Text; public abstract class QueryAsserterBase { public abstract void AssertQueryScalar<TItem1, TResult>( Func<IQueryable<TItem1>, IQueryable<Nullable<TResult>>> actualQuery) where TResult : struct; } public class QueryAsserter<TContext> : QueryAsserterBase { public override void AssertQueryScalar<TItem1, TResult>( Func<IQueryable<TItem1>, IQueryable<TResult?>> actualQuery) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (4,1): hidden CS8019: Unnecessary using directive. // using System.Collections.Generic; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;").WithLocation(4, 1), // (5,1): hidden CS8019: Unnecessary using directive. // using System.Text; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Text;").WithLocation(5, 1), // (10,14): error CS0246: The type or namespace name 'IQueryable<>' could not be found (are you missing a using directive or an assembly reference?) // Func<IQueryable<TItem1>, IQueryable<Nullable<TResult>>> actualQuery) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IQueryable<TItem1>").WithArguments("IQueryable<>").WithLocation(10, 14), // (10,34): error CS0246: The type or namespace name 'IQueryable<>' could not be found (are you missing a using directive or an assembly reference?) // Func<IQueryable<TItem1>, IQueryable<Nullable<TResult>>> actualQuery) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IQueryable<Nullable<TResult>>").WithArguments("IQueryable<>").WithLocation(10, 34), // (17,14): error CS0246: The type or namespace name 'IQueryable<>' could not be found (are you missing a using directive or an assembly reference?) // Func<IQueryable<TItem1>, IQueryable<TResult?>> actualQuery) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IQueryable<TItem1>").WithArguments("IQueryable<>").WithLocation(17, 14), // (17,34): error CS0246: The type or namespace name 'IQueryable<>' could not be found (are you missing a using directive or an assembly reference?) // Func<IQueryable<TItem1>, IQueryable<TResult?>> actualQuery) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IQueryable<TResult?>").WithArguments("IQueryable<>").WithLocation(17, 34) ); } [Fact] [WorkItem(38403, "https://github.com/dotnet/roslyn/issues/38403")] public void Overriding_37() { var source = @" #nullable enable using System; using System.Collections.Generic; using System.Text; using System.Linq; public abstract class QueryAsserterBase { public abstract void AssertQueryScalar<TItem1, TResult>( Func<IQueryable<TItem1>, IQueryable<Nullable<TResult>>> actualQuery) where TResult : struct; } public class QueryAsserter<TContext> : QueryAsserterBase { public override void AssertQueryScalar<TItem1, TResult>( Func<IQueryable<TItem1>, IQueryable<TResult?>> actualQuery) { } } "; var comp = CreateCompilation(source, options: TestOptions.DebugDll); CompileAndVerify(comp); } [Fact] public void Override_NullabilityCovariance_01() { var src = @" using System; interface I<out T> {} class A { public virtual object? M() => null; public virtual (object?, object?) M2() => throw null!; public virtual I<object?> M3() => throw null!; public virtual ref object? M4() => throw null!; public virtual ref readonly object? M5() => throw null!; public virtual Func<object>? P1 { get; set; } = null!; public virtual Func<object?> P2 { get; set; } = null!; public virtual object? P3 => null!; public virtual event Func<object>? E1 { add {} remove {} } public virtual event Func<object?> E2 { add {} remove {} } } class B : A { public override object M() => null!; public override (object, object) M2() => throw null!; public override I<object> M3() => throw null!; public override ref object M4() => throw null!; // warn public override ref readonly object M5() => throw null!; public override Func<object> P1 { get; set; } = null!; // warn public override Func<object> P2 { get; set; } = null!; // warn public override object P3 => null!; // ok public override event Func<object> E1 { add {} remove {} } // warn public override event Func<object> E2 { add {} remove {} } // warn } class C : B { public override object? M() => null; // warn public override (object?, object?) M2() => throw null!; // warn public override I<object?> M3() => throw null!; // warn public override ref object? M4() => throw null!; // warn public override ref readonly object? M5() => throw null!; // warn public override Func<object>? P1 { get; set; } = null!; // warn public override Func<object?> P2 { get; set; } = null!; // warn public override object? P3 => null!; // warn public override event Func<object>? E1 { add {} remove {} } // ok public override event Func<object?> E2 { add {} remove {} } // ok } class D : C { public override object M() => null!; public override (object, object) M2() => throw null!; public override I<object> M3() => throw null!; public override ref object M4() => throw null!; // warn public override ref readonly object M5() => throw null!; public override Func<object> P1 { get; set; } = null!; // warn public override Func<object> P2 { get; set; } = null!; // warn public override object P3 => null!; // ok public override event Func<object> E1 { add {} remove {} } // ok public override event Func<object> E2 { add {} remove {} } // ok } class E : D { public override object? M() => null; // warn public override (object?, object?) M2() => throw null!; // warn public override I<object?> M3() => throw null!; // warn public override ref object? M4() => throw null!; // warn public override ref readonly object? M5() => throw null!; // warn public override Func<object>? P1 { get; set; } = null!; // warn public override Func<object?> P2 { get; set; } = null!; // warn public override object? P3 => null!; // warn public override event Func<object>? E1 { add {} remove {} } // warn public override event Func<object?> E2 { add {} remove {} } // warn }"; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,32): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override ref object M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(23, 32), // (25,44): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // public override Func<object> P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(25, 44), // (26,44): warning CS8610: Nullability of reference types in type of parameter 'value' doesn't match overridden member. // public override Func<object> P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(26, 44), // (28,40): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event Func<object> E1 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E1").WithLocation(28, 40), // (29,40): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event Func<object> E2 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E2").WithLocation(29, 40), // (33,29): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override object? M() => null; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M").WithLocation(33, 29), // (34,40): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override (object?, object?) M2() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(34, 40), // (35,32): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override I<object?> M3() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M3").WithLocation(35, 32), // (36,33): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override ref object? M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(36, 33), // (37,42): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override ref readonly object? M5() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M5").WithLocation(37, 42), // (38,40): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override Func<object>? P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(38, 40), // (39,40): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override Func<object?> P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(39, 40), // (40,35): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override object? P3 => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "null!").WithLocation(40, 35), // (49,32): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override ref object M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(49, 32), // (51,44): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // public override Func<object> P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(51, 44), // (52,44): warning CS8610: Nullability of reference types in type of parameter 'value' doesn't match overridden member. // public override Func<object> P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(52, 44), // (54,40): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event Func<object> E1 { add {} remove {} } // ok Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E1").WithLocation(54, 40), // (55,40): warning CS8608: Nullability of reference types in type doesn't match overridden member. // public override event Func<object> E2 { add {} remove {} } // ok Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnOverride, "E2").WithLocation(55, 40), // (59,29): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override object? M() => null; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M").WithLocation(59, 29), // (60,40): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override (object?, object?) M2() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M2").WithLocation(60, 40), // (61,32): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override I<object?> M3() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "M3").WithLocation(61, 32), // (62,33): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override ref object? M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M4").WithLocation(62, 33), // (63,42): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override ref readonly object? M5() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M5").WithLocation(63, 42), // (64,40): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override Func<object>? P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(64, 40), // (65,40): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override Func<object?> P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(65, 40), // (66,35): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override object? P3 => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "null!").WithLocation(66, 35) ); } [Fact] public void Override_NullabilityCovariance_02() { var src = @" using System; class A { public virtual Func<object>? P1 { get; set; } = null!; } class B : A { public override Func<object> P1 { get => null!; } } class C : B { public override Func<object> P1 { get; set; } = null!; // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,44): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // public override Func<object> P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(14, 44) ); } [Fact] public void Override_NullabilityCovariance_03() { var src = @" using System; class B { public virtual Func<object> P1 { get; set; } = null!; } class C : B { public override Func<object>? P1 { set {} } } class D : C { public override Func<object>? P1 { get; set; } = null!; // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,40): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override Func<object>? P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(14, 40) ); } [Fact] public void Override_NullabilityContravariance_01() { var src = @" interface I<out T> {} class A { public virtual void M(object o) { } public virtual void M2((object, object) t) { } public virtual void M3(I<object> i) { } public virtual void M4(ref object o) { } public virtual void M5(out object o) => throw null!; public virtual void M6(in object o) { } public virtual object this[object o] { get => null!; set { } } public virtual string this[string s] => null!; public virtual string this[int[] a] { set { } } } class B : A { public override void M(object? o) { } public override void M2((object?, object?) t) { } public override void M3(I<object?> i) { } public override void M4(ref object? o) { } // warn public override void M5(out object? o) => throw null!; // warn public override void M6(in object? o) { } public override object? this[object? o] { get => null!; set { } } public override string this[string? s] => null!; public override string this[int[]? a] { set { } } } class C : B { public override void M(object o) { } // warn public override void M2((object, object) t) { } // warn public override void M3(I<object> i) { } // warn public override void M4(ref object o) { } // warn public override void M5(out object o) => throw null!; public override void M6(in object o) { } // warn public override object this[object o] { get => null!; set { } } public override string this[string s] => null!; public override string this[int[] a] { set { } } } class D : C { public override void M(object? o) { } public override void M2((object?, object?) t) { } public override void M3(I<object?> i) { } public override void M4(ref object? o) { } // warn public override void M5(out object? o) => throw null!; // warn public override void M6(in object? o) { } public override object? this[object? o] { get => null!; set { } } public override string this[string? s] => null!; public override string this[int[]? a] { set { } } } class E : D { public override void M(object o) { } // warn public override void M2((object, object) t) { } // warn public override void M3(I<object> i) { } // warn public override void M4(ref object o) { } // warn public override void M5(out object o) => throw null!; public override void M6(in object o) { } // warn public override object this[object o] { get => null!; set { } } public override string this[string s] => null!; public override string this[int[] a] { set { } } }"; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M4(ref object? o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M4").WithArguments("o").WithLocation(20, 26), // (21,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M5(out object? o) => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M5").WithArguments("o").WithLocation(21, 26), // (23,47): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override object? this[object? o] { get => null!; set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(23, 47), // (29,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M(object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("o").WithLocation(29, 26), // (30,26): warning CS8610: Nullability of reference types in type of parameter 't' doesn't match overridden member. // public override void M2((object, object) t) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M2").WithArguments("t").WithLocation(30, 26), // (31,26): warning CS8610: Nullability of reference types in type of parameter 'i' doesn't match overridden member. // public override void M3(I<object> i) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("i").WithLocation(31, 26), // (32,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M4(ref object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M4").WithArguments("o").WithLocation(32, 26), // (34,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M6(in object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M6").WithArguments("o").WithLocation(34, 26), // (35,59): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override object this[object o] { get => null!; set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("o").WithLocation(35, 59), // (35,59): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // public override object this[object o] { get => null!; set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(35, 59), // (36,46): warning CS8765: Type of parameter 's' doesn't match overridden member because of nullability attributes. // public override string this[string s] => null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "null!").WithArguments("s").WithLocation(36, 46), // (37,44): warning CS8765: Type of parameter 'a' doesn't match overridden member because of nullability attributes. // public override string this[int[] a] { set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("a").WithLocation(37, 44), // (44,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M4(ref object? o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M4").WithArguments("o").WithLocation(44, 26), // (45,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M5(out object? o) => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M5").WithArguments("o").WithLocation(45, 26), // (47,47): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override object? this[object? o] { get => null!; set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(47, 47), // (53,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M(object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("o").WithLocation(53, 26), // (54,26): warning CS8610: Nullability of reference types in type of parameter 't' doesn't match overridden member. // public override void M2((object, object) t) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M2").WithArguments("t").WithLocation(54, 26), // (55,26): warning CS8610: Nullability of reference types in type of parameter 'i' doesn't match overridden member. // public override void M3(I<object> i) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "M3").WithArguments("i").WithLocation(55, 26), // (56,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M4(ref object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M4").WithArguments("o").WithLocation(56, 26), // (58,26): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override void M6(in object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M6").WithArguments("o").WithLocation(58, 26), // (59,59): warning CS8765: Type of parameter 'o' doesn't match overridden member because of nullability attributes. // public override object this[object o] { get => null!; set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("o").WithLocation(59, 59), // (59,59): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // public override object this[object o] { get => null!; set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(59, 59), // (60,46): warning CS8765: Type of parameter 's' doesn't match overridden member because of nullability attributes. // public override string this[string s] => null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "null!").WithArguments("s").WithLocation(60, 46), // (61,44): warning CS8765: Type of parameter 'a' doesn't match overridden member because of nullability attributes. // public override string this[int[] a] { set { } } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("a").WithLocation(61, 44) ); } [Fact] public void Override_NullabilityContravariance_02() { var src = @" class B { public virtual object? this[object? o] { get => null!; set { } } } class C : B { #nullable disable public override object this[object o] { set { } } #nullable enable } class D : C { public override object this[object? o] { get => null!; } } class E : D { public override object this[object o] { get => null!; set { } } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,45): warning CS8765: Nullability of type of parameter 'o' doesn't match overridden member (possibly because of nullability attributes). // public override object this[object o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "get").WithArguments("o").WithLocation(18, 45) ); } [Fact] public void Override_NullabilityContravariance_03() { var src = @" class B { public virtual object? this[object? o] { get => null!; set { } } } class C : B { public override object this[object? o] { get => null!; } } class D : C { #nullable disable public override object this[object o] { set { } } #nullable enable } class E : D { public override object this[object o] { get => null!; set { } } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,45): warning CS8765: Nullability of type of parameter 'o' doesn't match overridden member (possibly because of nullability attributes). // public override object this[object o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "get").WithArguments("o").WithLocation(18, 45) ); } [Fact] public void OverrideConstraintVariance() { var src = @" using System.Collections.Generic; class A { public virtual List<T>? M<T>(List<T>? t) => null!; } class B : A { public override List<T> M<T>(List<T> t) => null!; } class C : B { public override List<T>? M<T>(List<T>? t) => null!; } class D : C { public override List<T> M<T>(List<T> t) => null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,29): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override List<T> M<T>(List<T> t) => null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("t").WithLocation(9, 29), // (13,30): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override List<T>? M<T>(List<T>? t) => null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M").WithLocation(13, 30), // (17,29): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override List<T> M<T>(List<T> t) => null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("t").WithLocation(17, 29)); } [Fact] public void OverrideVarianceGenericBase() { var comp = CreateCompilation(@" class A<T> { public virtual T M(T t) => default!; } #nullable enable class B : A<object> { public override object? M(object? o) => null!; // warn } class C : A<object?> { public override object M(object o) => null!; // warn } #nullable disable class D : A<object> { #nullable enable public override object? M(object? o) => null!; } class E : A<object> { #nullable disable public override object M(object o) => null!; } #nullable enable class F : A<object?> { #nullable disable public override object M(object o) => null; } "); comp.VerifyDiagnostics( // (9,29): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override object? M(object? o) => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M").WithLocation(9, 29), // (13,28): warning CS8765: Nullability of type of parameter 'o' doesn't match overridden member (possibly because of nullability attributes). // public override object M(object o) => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("o").WithLocation(13, 28)); } [Fact] public void NullableVarianceConsumer() { var comp = CreateCompilation(@" class A { public virtual object? M() => null; } class B : A { public override object M() => null; // warn } class C { void M() { var b = new B(); b.M().ToString(); A a = b; a.M().ToString(); // warn } }", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,35): warning CS8603: Possible null reference return. // public override object M() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 35), // (17,9): warning CS8602: Dereference of a possibly null reference. // a.M().ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.M()").WithLocation(17, 9)); } [Fact] public void Implement_NullabilityCovariance_Implicit_01() { var src = @" using System; interface I<out T> {} interface A { object? M(); (object?, object?) M2(); I<object?> M3(); ref object? M4(); ref readonly object? M5(); Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } object? P3 {get;} event Func<object>? E1; event Func<object?> E2; } class B : A { public object M() => null!; public (object, object) M2() => throw null!; public I<object> M3() => throw null!; public ref object M4() => throw null!; // warn public ref readonly object M5() => throw null!; public Func<object> P1 { get; set; } = null!; // warn public Func<object> P2 { get; set; } = null!; // warn public object P3 => null!; // ok public event Func<object> E1 { add {} remove {} } // warn public event Func<object> E2 { add {} remove {} } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,23): warning CS8766: Nullability of reference types in return type of 'ref object B.M4()' doesn't match implicitly implemented member 'ref object? A.M4()' (possibly because of nullability attributes). // public ref object M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M4").WithArguments("ref object B.M4()", "ref object? A.M4()").WithLocation(23, 23), // (25,35): warning CS8767: Nullability of reference types in type of parameter 'value' of 'void B.P1.set' doesn't match implicitly implemented member 'void A.P1.set' (possibly because of nullability attributes). // public Func<object> P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void B.P1.set", "void A.P1.set").WithLocation(25, 35), // (26,35): warning CS8614: Nullability of reference types in type of parameter 'value' of 'void B.P2.set' doesn't match implicitly implemented member 'void A.P2.set'. // public Func<object> P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void B.P2.set", "void A.P2.set").WithLocation(26, 35), // (28,31): warning CS8612: Nullability of reference types in type of 'event Func<object> B.E1' doesn't match implicitly implemented member 'event Func<object>? A.E1'. // public event Func<object> E1 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "E1").WithArguments("event Func<object> B.E1", "event Func<object>? A.E1").WithLocation(28, 31), // (29,31): warning CS8612: Nullability of reference types in type of 'event Func<object> B.E2' doesn't match implicitly implemented member 'event Func<object?> A.E2'. // public event Func<object> E2 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "E2").WithArguments("event Func<object> B.E2", "event Func<object?> A.E2").WithLocation(29, 31) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_02() { var src = @" using System; interface I<out T> {} interface B { object M(); (object, object) M2(); I<object> M3(); ref object M4(); ref readonly object M5(); Func<object> P1 { get; set; } Func<object> P2 { get; set; } object P3 { get; } event Func<object> E1; event Func<object> E2; } class C : B { public object? M() => null; // warn public (object?, object?) M2() => throw null!; // warn public I<object?> M3() => throw null!; // warn public ref object? M4() => throw null!; // warn public ref readonly object? M5() => throw null!; // warn public Func<object>? P1 { get; set; } = null!; // warn public Func<object?> P2 { get; set; } = null!; // warn public object? P3 => null!; // warn public event Func<object>? E1 { add {} remove {} } // ok public event Func<object?> E2 { add {} remove {} } // ok } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,20): warning CS8766: Nullability of reference types in return type of 'object? C.M()' doesn't match implicitly implemented member 'object B.M()' (possibly because of nullability attributes). // public object? M() => null; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M").WithArguments("object? C.M()", "object B.M()").WithLocation(20, 20), // (21,31): warning CS8613: Nullability of reference types in return type of '(object?, object?) C.M2()' doesn't match implicitly implemented member '(object, object) B.M2()'. // public (object?, object?) M2() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "M2").WithArguments("(object?, object?) C.M2()", "(object, object) B.M2()").WithLocation(21, 31), // (22,23): warning CS8613: Nullability of reference types in return type of 'I<object?> C.M3()' doesn't match implicitly implemented member 'I<object> B.M3()'. // public I<object?> M3() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "M3").WithArguments("I<object?> C.M3()", "I<object> B.M3()").WithLocation(22, 23), // (23,24): warning CS8766: Nullability of reference types in return type of 'ref object? C.M4()' doesn't match implicitly implemented member 'ref object B.M4()' (possibly because of nullability attributes). // public ref object? M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M4").WithArguments("ref object? C.M4()", "ref object B.M4()").WithLocation(23, 24), // (24,33): warning CS8766: Nullability of reference types in return type of 'ref readonly object? C.M5()' doesn't match implicitly implemented member 'ref readonly object B.M5()' (possibly because of nullability attributes). // public ref readonly object? M5() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M5").WithArguments("ref readonly object? C.M5()", "ref readonly object B.M5()").WithLocation(24, 33), // (25,31): warning CS8766: Nullability of reference types in return type of 'Func<object>? C.P1.get' doesn't match implicitly implemented member 'Func<object> B.P1.get' (possibly because of nullability attributes). // public Func<object>? P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("Func<object>? C.P1.get", "Func<object> B.P1.get").WithLocation(25, 31), // (26,31): warning CS8613: Nullability of reference types in return type of 'Func<object?> C.P2.get' doesn't match implicitly implemented member 'Func<object> B.P2.get'. // public Func<object?> P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("Func<object?> C.P2.get", "Func<object> B.P2.get").WithLocation(26, 31), // (27,26): warning CS8766: Nullability of reference types in return type of 'object? C.P3.get' doesn't match implicitly implemented member 'object B.P3.get' (possibly because of nullability attributes). // public object? P3 => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "null!").WithArguments("object? C.P3.get", "object B.P3.get").WithLocation(27, 26) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_05() { var src = @" using System; interface I<out T> {} interface A { object? M(); (object?, object?) M2(); I<object?> M3(); ref object? M4(); ref readonly object? M5(); Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } object? P3 {get;} event Func<object>? E1; event Func<object?> E2; } class B { public object M() => null!; public (object, object) M2() => throw null!; public I<object> M3() => throw null!; public ref object M4() => throw null!; // warn public ref readonly object M5() => throw null!; public Func<object> P1 { get; set; } = null!; // warn public Func<object> P2 { get; set; } = null!; // warn public object P3 => null!; // ok public event Func<object> E1 { add {} remove {} } // warn public event Func<object> E2 { add {} remove {} } // warn } class C : B, A {} "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (31,14): warning CS8766: Nullability of reference types in return type of 'ref object B.M4()' doesn't match implicitly implemented member 'ref object? A.M4()' (possibly because of nullability attributes). // class C : B, A Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "A").WithArguments("ref object B.M4()", "ref object? A.M4()").WithLocation(31, 14), // (31,14): warning CS8767: Nullability of reference types in type of parameter 'value' of 'void B.P1.set' doesn't match implicitly implemented member 'void A.P1.set' (possibly because of nullability attributes). // class C : B, A Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "A").WithArguments("value", "void B.P1.set", "void A.P1.set").WithLocation(31, 14), // (31,14): warning CS8614: Nullability of reference types in type of parameter 'value' of 'void B.P2.set' doesn't match implicitly implemented member 'void A.P2.set'. // class C : B, A Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "A").WithArguments("value", "void B.P2.set", "void A.P2.set").WithLocation(31, 14), // (31,14): warning CS8612: Nullability of reference types in type of 'event Func<object> B.E1' doesn't match implicitly implemented member 'event Func<object>? A.E1'. // class C : B, A Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "A").WithArguments("event Func<object> B.E1", "event Func<object>? A.E1").WithLocation(31, 14), // (31,14): warning CS8612: Nullability of reference types in type of 'event Func<object> B.E2' doesn't match implicitly implemented member 'event Func<object?> A.E2'. // class C : B, A Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnImplicitImplementation, "A").WithArguments("event Func<object> B.E2", "event Func<object?> A.E2").WithLocation(31, 14) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_06() { var src = @" using System; interface A { Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } } class B { public virtual Func<object> P1 { get; set; } = null!; // warn public virtual Func<object> P2 { get; set; } = null!; // warn } class C : B, A { public override Func<object> P1 { get => null!;} public override Func<object> P2 => null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,14): warning CS8614: Nullability of reference types in type of parameter 'value' of 'void B.P2.set' doesn't match implicitly implemented member 'void A.P2.set'. // class C : B, A Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "A").WithArguments("value", "void B.P2.set", "void A.P2.set").WithLocation(14, 14), // (14,14): warning CS8767: Nullability of reference types in type of parameter 'value' of 'void B.P1.set' doesn't match implicitly implemented member 'void A.P1.set' (possibly because of nullability attributes). // class C : B, A Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "A").WithArguments("value", "void B.P1.set", "void A.P1.set").WithLocation(14, 14) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_07() { var src = @" using System; interface A { Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } } class B { public virtual Func<object>? P1 { get; set; } = null!; public virtual Func<object?> P2 { get; set; } = null!; } class C : B, A { public override Func<object> P1 { get => null!;} public override Func<object> P2 => null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_08() { var src = @" using System; interface A { Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } } class B { public virtual Func<object>? P1 { get; set; } = null!; public virtual Func<object?> P2 { get; set; } = null!; } class C : B, A { public override Func<object> P1 { set {} } // warn public override Func<object> P2 { set; } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,39): warning CS8765: Nullability of type of parameter 'value' doesn't match overridden member (possibly because of nullability attributes). // public override Func<object> P1 { set {} } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(15, 39), // (15,39): warning CS8767: Nullability of reference types in type of parameter 'value' of 'void C.P1.set' doesn't match implicitly implemented member 'void A.P1.set' (possibly because of nullability attributes). // public override Func<object> P1 { set {} } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void C.P1.set", "void A.P1.set").WithLocation(15, 39), // (16,39): error CS8051: Auto-implemented properties must have get accessors. // public override Func<object> P2 { set; } // warn Diagnostic(ErrorCode.ERR_AutoPropertyMustHaveGetAccessor, "set").WithArguments("C.P2.set").WithLocation(16, 39), // (16,39): warning CS8610: Nullability of reference types in type of parameter 'value' doesn't match overridden member. // public override Func<object> P2 { set; } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(16, 39), // (16,39): warning CS8614: Nullability of reference types in type of parameter 'value' of 'void C.P2.set' doesn't match implicitly implemented member 'void A.P2.set'. // public override Func<object> P2 { set; } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void C.P2.set", "void A.P2.set").WithLocation(16, 39) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_09() { var src = @" using System; interface A { Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } } class B { public virtual Func<object> P1 { get; set; } = null!; public virtual Func<object> P2 { get; set; } = null!; } class C : B, A { public override Func<object>? P1 { set {} } public override Func<object?> P2 { set {} } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_10() { var src = @" using System; interface A { Func<object>? P1 { get => null!; private set {} } Func<object?> P2 { get => null!; private set {} } } class B : A { public Func<object> P1 { get; set; } = null!; public Func<object> P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_11() { var src = @" using System; interface A { Func<object>? P1 { get => null!; private set {} } Func<object?> P2 { get => null!; private set {} } } class B : A { public Func<object> P1 { get; } = null!; public Func<object> P2 { get; } = null!; } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_12() { var src = @" using System; interface A { Func<object>? P1 { get; } Func<object?> P2 { get; } } class B : A { public Func<object> P1 { get; set; } = null!; public Func<object> P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_13() { var src = @" using System; interface A { Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } } class B : A { public Func<object> P1 { get; } = null!; public Func<object> P2 { get; } = null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): error CS0535: 'B' does not implement interface member 'A.P2.set' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.P2.set").WithLocation(9, 11), // (9,11): error CS0535: 'B' does not implement interface member 'A.P1.set' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.P1.set").WithLocation(9, 11) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_14() { var src = @" using System; interface B { Func<object> P1 { get; set; } Func<object> P2 { get; set; } } class C { public virtual Func<object>? P1 { get; set; } = null!; // warn public virtual Func<object?> P2 { get; set; } = null!; // warn } class D : C, B { public override Func<object>? P1 { set {} } public override Func<object?> P2 { set {} } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,14): warning CS8613: Nullability of reference types in return type of 'Func<object?> C.P2.get' doesn't match implicitly implemented member 'Func<object> B.P2.get'. // class D : C, B Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "B").WithArguments("Func<object?> C.P2.get", "Func<object> B.P2.get").WithLocation(14, 14), // (14,14): warning CS8766: Nullability of reference types in return type of 'Func<object>? C.P1.get' doesn't match implicitly implemented member 'Func<object> B.P1.get' (possibly because of nullability attributes). // class D : C, B Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "B").WithArguments("Func<object>? C.P1.get", "Func<object> B.P1.get").WithLocation(14, 14) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_15() { var src = @" using System; interface B { Func<object> P1 { get; set; } Func<object> P2 { get; set; } } class C { public virtual Func<object> P1 { get; set; } = null!; public virtual Func<object> P2 { get; set; } = null!; } class D : C, B { public override Func<object>? P1 { set {} } public override Func<object?> P2 { set {} } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_16() { var src = @" using System; interface B { Func<object> P1 { get; set; } Func<object> P2 { get; set; } } class C { public virtual Func<object> P1 { get; set; } = null!; public virtual Func<object> P2 { get; set; } = null!; } class D : C, B { public override Func<object>? P1 { get; } = null!; // warn public override Func<object?> P2 { get => null!; } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,35): error CS8080: Auto-implemented properties must override all accessors of the overridden property. // public override Func<object>? P1 { get; } = null!; // warn Diagnostic(ErrorCode.ERR_AutoPropertyMustOverrideSet, "P1").WithArguments("D.P1").WithLocation(16, 35), // (16,40): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override Func<object>? P1 { get; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(16, 40), // (16,40): warning CS8766: Nullability of reference types in return type of 'Func<object>? D.P1.get' doesn't match implicitly implemented member 'Func<object> B.P1.get' (possibly because of nullability attributes). // public override Func<object>? P1 { get; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("Func<object>? D.P1.get", "Func<object> B.P1.get").WithLocation(16, 40), // (17,40): warning CS8609: Nullability of reference types in return type doesn't match overridden member. // public override Func<object?> P2 { get => null!; } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(17, 40), // (17,40): warning CS8613: Nullability of reference types in return type of 'Func<object?> D.P2.get' doesn't match implicitly implemented member 'Func<object> B.P2.get'. // public override Func<object?> P2 { get => null!; } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("Func<object?> D.P2.get", "Func<object> B.P2.get").WithLocation(17, 40) ); } [Fact] public void Implement_NullabilityCovariance_Implicit_17() { var src = @" using System; interface B { Func<object> P1 { get; set; } Func<object> P2 { get; set; } } class C { public virtual Func<object>? P1 { get; set; } = null!; public virtual Func<object?> P2 { get; set; } = null!; } class D : C, B { public override Func<object> P1 { get => null!; } public override Func<object> P2 { get => null!; } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_18() { var src = @" using System; interface B { Func<object> P1 { private get => null!; set{} } Func<object> P2 { private get => null!; set{} } } class C : B { public Func<object>? P1 { get; set; } = null!; public Func<object?> P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_19() { var src = @" using System; interface B { Func<object> P1 { private get => null!; set{} } Func<object> P2 { private get => null!; set{} } } class C : B { public Func<object>? P1 { set{} } public Func<object?> P2 { set{} } } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_20() { var src = @" using System; interface B { Func<object> P1 { set; } Func<object> P2 { set; } } class C : B { public Func<object>? P1 { get; set; } public Func<object?> P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Implicit_21() { var src = @" using System; interface B { Func<object> P1 { get; set; } Func<object> P2 { get; set; } } class C : B { public Func<object>? P1 { set {} } public Func<object?> P2 { set {} } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): error CS0535: 'C' does not implement interface member 'B.P1.get' // class C : B Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "B").WithArguments("C", "B.P1.get").WithLocation(9, 11), // (9,11): error CS0535: 'C' does not implement interface member 'B.P2.get' // class C : B Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "B").WithArguments("C", "B.P2.get").WithLocation(9, 11) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_01() { var src = @" using System; interface I<out T> {} interface A { object? M(); (object?, object?) M2(); I<object?> M3(); ref object? M4(); ref readonly object? M5(); Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } object? P3 {get;} event Func<object>? E1; event Func<object?> E2; } class B : A { object A.M() => null!; (object, object) A.M2() => throw null!; I<object> A.M3() => throw null!; ref object A.M4() => throw null!; // warn ref readonly object A.M5() => throw null!; Func<object> A.P1 { get; set; } = null!; // warn Func<object> A.P2 { get; set; } = null!; // warn object A.P3 => null!; // ok event Func<object> A.E1 { add {} remove {} } // warn event Func<object> A.E2 { add {} remove {} } // warn } class C : B, A {} "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,18): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'ref object? A.M4()' (possibly because of nullability attributes). // ref object A.M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M4").WithArguments("ref object? A.M4()").WithLocation(23, 18), // (25,30): warning CS8769: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void A.P1.set' (possibly because of nullability attributes). // Func<object> A.P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void A.P1.set").WithLocation(25, 30), // (26,30): warning CS8617: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void A.P2.set'. // Func<object> A.P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void A.P2.set").WithLocation(26, 30), // (28,26): warning CS8615: Nullability of reference types in type doesn't match implemented member 'event Func<object>? A.E1'. // event Func<object> A.E1 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, "E1").WithArguments("event Func<object>? A.E1").WithLocation(28, 26), // (29,26): warning CS8615: Nullability of reference types in type doesn't match implemented member 'event Func<object?> A.E2'. // event Func<object> A.E2 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, "E2").WithArguments("event Func<object?> A.E2").WithLocation(29, 26) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_02() { var src = @" using System; interface I<out T> {} interface B { object M(); (object, object) M2(); I<object> M3(); ref object M4(); ref readonly object M5(); Func<object> P1 { get; set; } Func<object> P2 { get; set; } object P3 { get; } event Func<object> E1; event Func<object> E2; } class C : B { object? B.M() => null; // warn (object?, object?) B.M2() => throw null!; // warn I<object?> B.M3() => throw null!; // warn ref object? B.M4() => throw null!; // warn ref readonly object? B.M5() => throw null!; // warn Func<object>? B.P1 { get; set; } = null!; // warn Func<object?> B.P2 { get; set; } = null!; // warn object? B.P3 => null!; // warn event Func<object>? B.E1 { add {} remove {} } // ok event Func<object?> B.E2 { add {} remove {} } // ok } class D : C, B {} "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,15): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'object B.M()' (possibly because of nullability attributes). // object? B.M() => null; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M").WithArguments("object B.M()").WithLocation(20, 15), // (21,26): warning CS8616: Nullability of reference types in return type doesn't match implemented member '(object, object) B.M2()'. // (object?, object?) B.M2() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M2").WithArguments("(object, object) B.M2()").WithLocation(21, 26), // (22,18): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'I<object> B.M3()'. // I<object?> B.M3() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M3").WithArguments("I<object> B.M3()").WithLocation(22, 18), // (23,19): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'ref object B.M4()' (possibly because of nullability attributes). // ref object? B.M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M4").WithArguments("ref object B.M4()").WithLocation(23, 19), // (24,28): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'ref readonly object B.M5()' (possibly because of nullability attributes). // ref readonly object? B.M5() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M5").WithArguments("ref readonly object B.M5()").WithLocation(24, 28), // (25,26): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'Func<object> B.P1.get' (possibly because of nullability attributes). // Func<object>? B.P1 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("Func<object> B.P1.get").WithLocation(25, 26), // (26,26): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'Func<object> B.P2.get'. // Func<object?> B.P2 { get; set; } = null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("Func<object> B.P2.get").WithLocation(26, 26), // (27,21): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'object B.P3.get' (possibly because of nullability attributes). // object? B.P3 => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "null!").WithArguments("object B.P3.get").WithLocation(27, 21) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_03() { var src = @" using System; interface I<out T> {} interface A { object? M(); (object?, object?) M2(); I<object?> M3(); ref object? M4(); ref readonly object? M5(); Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } object? P3 {get;} event Func<object>? E1; event Func<object?> E2; } interface B : A { object A.M() => null!; (object, object) A.M2() => throw null!; I<object> A.M3() => throw null!; ref object A.M4() => throw null!; // warn ref readonly object A.M5() => throw null!; Func<object> A.P1 { get => null!; set {} } // warn Func<object> A.P2 { get => null!; set {} } // warn object A.P3 => null!; // ok event Func<object> A.E1 { add {} remove {} } // warn event Func<object> A.E2 { add {} remove {} } // warn } class C : B, A {} interface D : B, A {} "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,18): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'ref object? A.M4()' (possibly because of nullability attributes). // ref object A.M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M4").WithArguments("ref object? A.M4()").WithLocation(23, 18), // (25,39): warning CS8769: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void A.P1.set' (possibly because of nullability attributes). // Func<object> A.P1 { get => null!; set {} } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void A.P1.set").WithLocation(25, 39), // (26,39): warning CS8617: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void A.P2.set'. // Func<object> A.P2 { get => null!; set {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void A.P2.set").WithLocation(26, 39), // (28,26): warning CS8615: Nullability of reference types in type doesn't match implemented member 'event Func<object>? A.E1'. // event Func<object> A.E1 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, "E1").WithArguments("event Func<object>? A.E1").WithLocation(28, 26), // (29,26): warning CS8615: Nullability of reference types in type doesn't match implemented member 'event Func<object?> A.E2'. // event Func<object> A.E2 { add {} remove {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeOnExplicitImplementation, "E2").WithArguments("event Func<object?> A.E2").WithLocation(29, 26) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_04() { var src = @" using System; interface I<out T> {} interface B { object M(); (object, object) M2(); I<object> M3(); ref object M4(); ref readonly object M5(); Func<object> P1 { get; set; } Func<object> P2 { get; set; } object P3 { get; } event Func<object> E1; event Func<object> E2; } interface C : B { object? B.M() => null; // warn (object?, object?) B.M2() => throw null!; // warn I<object?> B.M3() => throw null!; // warn ref object? B.M4() => throw null!; // warn ref readonly object? B.M5() => throw null!; // warn Func<object>? B.P1 { get => null!; set {} } // warn Func<object?> B.P2 { get => null!; set {} } // warn object? B.P3 => null!; // warn event Func<object>? B.E1 { add {} remove {} } // ok event Func<object?> B.E2 { add {} remove {} } // ok } class D : C, B {} interface E : C, B {} "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,15): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'object B.M()' (possibly because of nullability attributes). // object? B.M() => null; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M").WithArguments("object B.M()").WithLocation(20, 15), // (21,26): warning CS8616: Nullability of reference types in return type doesn't match implemented member '(object, object) B.M2()'. // (object?, object?) B.M2() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M2").WithArguments("(object, object) B.M2()").WithLocation(21, 26), // (22,18): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'I<object> B.M3()'. // I<object?> B.M3() => throw null!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M3").WithArguments("I<object> B.M3()").WithLocation(22, 18), // (23,19): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'ref object B.M4()' (possibly because of nullability attributes). // ref object? B.M4() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M4").WithArguments("ref object B.M4()").WithLocation(23, 19), // (24,28): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'ref readonly object B.M5()' (possibly because of nullability attributes). // ref readonly object? B.M5() => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M5").WithArguments("ref readonly object B.M5()").WithLocation(24, 28), // (25,26): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'Func<object> B.P1.get' (possibly because of nullability attributes). // Func<object>? B.P1 { get => null!; set {} } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("Func<object> B.P1.get").WithLocation(25, 26), // (26,26): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'Func<object> B.P2.get'. // Func<object?> B.P2 { get => null!; set {} } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("Func<object> B.P2.get").WithLocation(26, 26), // (27,21): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'object B.P3.get' (possibly because of nullability attributes). // object? B.P3 => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "null!").WithArguments("object B.P3.get").WithLocation(27, 21) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_05() { var src = @" using System; interface A { Func<object>? P1 { get => null!; private set {} } Func<object?> P2 { get => null!; private set {} } } class B : A { Func<object> A.P1 { get; set; } = null!; Func<object> A.P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,30): error CS0550: 'B.A.P1.set' adds an accessor not found in interface member 'A.P1' // Func<object> A.P1 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("B.A.P1.set", "A.P1").WithLocation(11, 30), // (12,30): error CS0550: 'B.A.P2.set' adds an accessor not found in interface member 'A.P2' // Func<object> A.P2 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("B.A.P2.set", "A.P2").WithLocation(12, 30) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_06() { var src = @" using System; interface A { Func<object>? P1 { get => null!; private set {} } Func<object?> P2 { get => null!; private set {} } } class B : A { Func<object> A.P1 { get; } = null!; Func<object> A.P2 { get; } = null!; } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Explicit_07() { var src = @" using System; interface A { Func<object>? P1 { get; set; } Func<object?> P2 { get; set; } } class B : A { Func<object> A.P1 { get; } = null!; Func<object> A.P2 { get; } = null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): error CS0535: 'B' does not implement interface member 'A.P2.set' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.P2.set").WithLocation(9, 11), // (9,11): error CS0535: 'B' does not implement interface member 'A.P1.set' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "A").WithArguments("B", "A.P1.set").WithLocation(9, 11), // (11,20): error CS0551: Explicit interface implementation 'B.A.P1' is missing accessor 'A.P1.set' // Func<object> A.P1 { get; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P1").WithArguments("B.A.P1", "A.P1.set").WithLocation(11, 20), // (12,20): error CS0551: Explicit interface implementation 'B.A.P2' is missing accessor 'A.P2.set' // Func<object> A.P2 { get; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P2").WithArguments("B.A.P2", "A.P2.set").WithLocation(12, 20) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_08() { var src = @" using System; interface A { Func<object>? P1 { get; } Func<object?> P2 { get; } } class B : A { Func<object> A.P1 { get; set; } = null!; Func<object> A.P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,30): error CS0550: 'B.A.P1.set' adds an accessor not found in interface member 'A.P1' // Func<object> A.P1 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("B.A.P1.set", "A.P1").WithLocation(11, 30), // (12,30): error CS0550: 'B.A.P2.set' adds an accessor not found in interface member 'A.P2' // Func<object> A.P2 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "set").WithArguments("B.A.P2.set", "A.P2").WithLocation(12, 30) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_09() { var src = @" using System; interface B { Func<object> P1 { private get => null!; set{} } Func<object> P2 { private get => null!; set{} } } class C : B { Func<object>? B.P1 { get; set; } = null!; Func<object?> B.P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,26): error CS0550: 'C.B.P1.get' adds an accessor not found in interface member 'B.P1' // Func<object>? B.P1 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C.B.P1.get", "B.P1").WithLocation(11, 26), // (12,26): error CS0550: 'C.B.P2.get' adds an accessor not found in interface member 'B.P2' // Func<object?> B.P2 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C.B.P2.get", "B.P2").WithLocation(12, 26) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_10() { var src = @" using System; interface B { Func<object> P1 { private get => null!; set{} } Func<object> P2 { private get => null!; set{} } } class C : B { Func<object>? B.P1 { set{} } Func<object?> B.P2 { set{} } } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Implement_NullabilityCovariance_Explicit_11() { var src = @" using System; interface B { Func<object> P1 { set; } Func<object> P2 { set; } } class C : B { Func<object>? B.P1 { get; set; } Func<object?> B.P2 { get; set; } = null!; } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,26): error CS0550: 'C.B.P1.get' adds an accessor not found in interface member 'B.P1' // Func<object>? B.P1 { get; set; } Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C.B.P1.get", "B.P1").WithLocation(11, 26), // (12,26): error CS0550: 'C.B.P2.get' adds an accessor not found in interface member 'B.P2' // Func<object?> B.P2 { get; set; } = null!; Diagnostic(ErrorCode.ERR_ExplicitPropertyAddingAccessor, "get").WithArguments("C.B.P2.get", "B.P2").WithLocation(12, 26) ); } [Fact] public void Implement_NullabilityCovariance_Explicit_12() { var src = @" using System; interface B { Func<object> P1 { get; set; } Func<object> P2 { get; set; } } class C : B { Func<object>? B.P1 { set {} } Func<object?> B.P2 { set {} } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): error CS0535: 'C' does not implement interface member 'B.P1.get' // class C : B Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "B").WithArguments("C", "B.P1.get").WithLocation(9, 11), // (9,11): error CS0535: 'C' does not implement interface member 'B.P2.get' // class C : B Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "B").WithArguments("C", "B.P2.get").WithLocation(9, 11), // (11,21): error CS0551: Explicit interface implementation 'C.B.P1' is missing accessor 'B.P1.get' // Func<object>? B.P1 { set {} } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P1").WithArguments("C.B.P1", "B.P1.get").WithLocation(11, 21), // (12,21): error CS0551: Explicit interface implementation 'C.B.P2' is missing accessor 'B.P2.get' // Func<object?> B.P2 { set {} } Diagnostic(ErrorCode.ERR_ExplicitPropertyMissingAccessor, "P2").WithArguments("C.B.P2", "B.P2.get").WithLocation(12, 21) ); } [Fact] public void Implement_NullabilityContravariance_Implicit_01() { var src = @" interface I<out T> {} interface A { void M(object o); void M2((object, object) t); void M3(I<object> i); void M4(ref object o); void M5(out object o); void M6(in object o); object this[object o] { get; set; } string this[string s] { get; } string this[int[] a] { set; } } class B : A { public void M(object? o) { } public void M2((object?, object?) t) { } public void M3(I<object?> i) { } public void M4(ref object? o) { } // warn public void M5(out object? o) => throw null!; // warn public void M6(in object? o) { } public object? this[object? o] { get => null!; set { } } // warn public string this[string? s] => null!; public string this[int[]? a] { set { } } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,17): warning CS8767: Nullability of reference types in type of parameter 'o' of 'void B.M4(ref object? o)' doesn't match implicitly implemented member 'void A.M4(ref object o)' (possibly because of nullability attributes). // public void M4(ref object? o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M4").WithArguments("o", "void B.M4(ref object? o)", "void A.M4(ref object o)").WithLocation(20, 17), // (21,17): warning CS8767: Nullability of reference types in type of parameter 'o' of 'void B.M5(out object? o)' doesn't match implicitly implemented member 'void A.M5(out object o)' (possibly because of nullability attributes). // public void M5(out object? o) => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M5").WithArguments("o", "void B.M5(out object? o)", "void A.M5(out object o)").WithLocation(21, 17), // (23,38): warning CS8766: Nullability of reference types in return type of 'object? B.this[object? o].get' doesn't match implicitly implemented member 'object A.this[object o].get' (possibly because of nullability attributes). // public object? this[object? o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "get").WithArguments("object? B.this[object? o].get", "object A.this[object o].get").WithLocation(23, 38) ); } [Fact] public void Implement_NullabilityContravariance_Implicit_02() { var src = @" interface I<out T> {} interface B { void M(object? o); void M2((object?, object?) t); void M3(I<object?> i); void M4(ref object? o); void M5(out object? o); void M6(in object? o); object? this[object? o] { get; set; } string this[string? s] { get; } string this[int[]? a] { set; } } class C : B { public void M(object o) { } // warn public void M2((object, object) t) { } // warn public void M3(I<object> i) { } // warn public void M4(ref object o) { } // warn public void M5(out object o) => throw null!; public void M6(in object o) { } // warn public object this[object o] { get => null!; set { } } // warn public string this[string s] => null!; // warn public string this[int[] a] { set { } } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,17): warning CS8767: Nullability of reference types in type of parameter 'o' of 'void C.M(object o)' doesn't match implicitly implemented member 'void B.M(object? o)' (possibly because of nullability attributes). // public void M(object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M").WithArguments("o", "void C.M(object o)", "void B.M(object? o)").WithLocation(17, 17), // (18,17): warning CS8614: Nullability of reference types in type of parameter 't' of 'void C.M2((object, object) t)' doesn't match implicitly implemented member 'void B.M2((object?, object?) t)'. // public void M2((object, object) t) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "M2").WithArguments("t", "void C.M2((object, object) t)", "void B.M2((object?, object?) t)").WithLocation(18, 17), // (19,17): warning CS8614: Nullability of reference types in type of parameter 'i' of 'void C.M3(I<object> i)' doesn't match implicitly implemented member 'void B.M3(I<object?> i)'. // public void M3(I<object> i) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "M3").WithArguments("i", "void C.M3(I<object> i)", "void B.M3(I<object?> i)").WithLocation(19, 17), // (20,17): warning CS8767: Nullability of reference types in type of parameter 'o' of 'void C.M4(ref object o)' doesn't match implicitly implemented member 'void B.M4(ref object? o)' (possibly because of nullability attributes). // public void M4(ref object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M4").WithArguments("o", "void C.M4(ref object o)", "void B.M4(ref object? o)").WithLocation(20, 17), // (22,17): warning CS8767: Nullability of reference types in type of parameter 'o' of 'void C.M6(in object o)' doesn't match implicitly implemented member 'void B.M6(in object? o)' (possibly because of nullability attributes). // public void M6(in object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M6").WithArguments("o", "void C.M6(in object o)", "void B.M6(in object? o)").WithLocation(22, 17), // (23,50): warning CS8767: Nullability of reference types in type of parameter 'o' of 'void C.this[object o].set' doesn't match implicitly implemented member 'void B.this[object? o].set' (possibly because of nullability attributes). // public object this[object o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("o", "void C.this[object o].set", "void B.this[object? o].set").WithLocation(23, 50), // (23,50): warning CS8767: Nullability of reference types in type of parameter 'value' of 'void C.this[object o].set' doesn't match implicitly implemented member 'void B.this[object? o].set' (possibly because of nullability attributes). // public object this[object o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("value", "void C.this[object o].set", "void B.this[object? o].set").WithLocation(23, 50), // (24,37): warning CS8767: Nullability of reference types in type of parameter 's' of 'string C.this[string s].get' doesn't match implicitly implemented member 'string B.this[string? s].get' (possibly because of nullability attributes). // public string this[string s] => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "null!").WithArguments("s", "string C.this[string s].get", "string B.this[string? s].get").WithLocation(24, 37), // (25,35): warning CS8767: Nullability of reference types in type of parameter 'a' of 'void C.this[int[] a].set' doesn't match implicitly implemented member 'void B.this[int[]? a].set' (possibly because of nullability attributes). // public string this[int[] a] { set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("a", "void C.this[int[] a].set", "void B.this[int[]? a].set").WithLocation(25, 35) ); } [Fact] public void Implement_NullabilityContravariance_Implicit_03() { var src = @" interface B { object? this[object? o] { get; set; } } class C { #nullable disable public virtual object this[object o] { get => null!; set { } } #nullable enable } class D : C, B { public override object this[object o] { get => null!; } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,45): warning CS8767: Nullability of reference types in type of parameter 'o' of 'object D.this[object o].get' doesn't match implicitly implemented member 'object? B.this[object? o].get' (possibly because of nullability attributes). // public override object this[object o] { get => null!; } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "get").WithArguments("o", "object D.this[object o].get", "object? B.this[object? o].get").WithLocation(14, 45) ); } [Fact] public void Implement_NullabilityContravariance_Implicit_04() { var src = @" interface B { object? this[object? o] { get; set; } } class C { public virtual object this[object o] { get => null!; set { } } } class D : C, B { #nullable disable public override object this[object o #nullable enable ] { set {} } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,14): warning CS8767: Nullability of reference types in type of parameter 'o' of 'object C.this[object o].get' doesn't match implicitly implemented member 'object? B.this[object? o].get' (possibly because of nullability attributes). // class D : C, B Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "B").WithArguments("o", "object C.this[object o].get", "object? B.this[object? o].get").WithLocation(10, 14) ); } [Fact] public void Implement_NullabilityContravariance_Explicit_01() { var src = @" interface I<out T> {} interface A { void M(object o); void M2((object, object) t); void M3(I<object> i); void M4(ref object o); void M5(out object o); void M6(in object o); object this[object o] { get; set; } string this[string s] { get; } string this[int[] a] { set; } } class B : A { void A.M(object? o) { } void A.M2((object?, object?) t) { } void A.M3(I<object?> i) { } void A.M4(ref object? o) { } // warn void A.M5(out object? o) => throw null!; // warn void A.M6(in object? o) { } object? A.this[object? o] { get => null!; set { } } // warn string A.this[string? s] => null!; string A.this[int[]? a] { set { } } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,12): warning CS8769: Nullability of reference types in type of parameter 'o' doesn't match implemented member 'void A.M4(ref object o)' (possibly because of nullability attributes). // void A.M4(ref object? o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "M4").WithArguments("o", "void A.M4(ref object o)").WithLocation(20, 12), // (21,12): warning CS8769: Nullability of reference types in type of parameter 'o' doesn't match implemented member 'void A.M5(out object o)' (possibly because of nullability attributes). // void A.M5(out object? o) => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "M5").WithArguments("o", "void A.M5(out object o)").WithLocation(21, 12), // (23,33): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'object A.this[object o].get' (possibly because of nullability attributes). // object? A.this[object? o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "get").WithArguments("object A.this[object o].get").WithLocation(23, 33) ); } [Fact] public void Implement_NullabilityContravariance_Explicit_02() { var src = @" interface I<out T> {} interface B { void M(object? o); void M2((object?, object?) t); void M3(I<object?> i); void M4(ref object? o); void M5(out object? o); void M6(in object? o); object? this[object? o] { get; set; } string this[string? s] { get; } string this[int[]? a] { set; } } class C : B { void B.M(object o) { } // warn void B.M2((object, object) t) { } // warn void B.M3(I<object> i) { } // warn void B.M4(ref object o) { } // warn void B.M5(out object o) => throw null!; void B.M6(in object o) { } // warn object B.this[object o] { get => null!; set { } } // warn string B.this[string s] => null!; // warn string B.this[int[] a] { set { } } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,12): warning CS8769: Nullability of reference types in type of parameter 'o' doesn't match implemented member 'void B.M(object? o)' (possibly because of nullability attributes). // void B.M(object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "M").WithArguments("o", "void B.M(object? o)").WithLocation(17, 12), // (18,12): warning CS8617: Nullability of reference types in type of parameter 't' doesn't match implemented member 'void B.M2((object?, object?) t)'. // void B.M2((object, object) t) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "M2").WithArguments("t", "void B.M2((object?, object?) t)").WithLocation(18, 12), // (19,12): warning CS8617: Nullability of reference types in type of parameter 'i' doesn't match implemented member 'void B.M3(I<object?> i)'. // void B.M3(I<object> i) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "M3").WithArguments("i", "void B.M3(I<object?> i)").WithLocation(19, 12), // (20,12): warning CS8769: Nullability of reference types in type of parameter 'o' doesn't match implemented member 'void B.M4(ref object? o)' (possibly because of nullability attributes). // void B.M4(ref object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "M4").WithArguments("o", "void B.M4(ref object? o)").WithLocation(20, 12), // (22,12): warning CS8769: Nullability of reference types in type of parameter 'o' doesn't match implemented member 'void B.M6(in object? o)' (possibly because of nullability attributes). // void B.M6(in object o) { } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "M6").WithArguments("o", "void B.M6(in object? o)").WithLocation(22, 12), // (23,45): warning CS8769: Nullability of reference types in type of parameter 'o' doesn't match implemented member 'void B.this[object? o].set' (possibly because of nullability attributes). // object B.this[object o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("o", "void B.this[object? o].set").WithLocation(23, 45), // (23,45): warning CS8769: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void B.this[object? o].set' (possibly because of nullability attributes). // object B.this[object o] { get => null!; set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("value", "void B.this[object? o].set").WithLocation(23, 45), // (24,32): warning CS8769: Nullability of reference types in type of parameter 's' doesn't match implemented member 'string B.this[string? s].get' (possibly because of nullability attributes). // string B.this[string s] => null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "null!").WithArguments("s", "string B.this[string? s].get").WithLocation(24, 32), // (25,30): warning CS8769: Nullability of reference types in type of parameter 'a' doesn't match implemented member 'void B.this[int[]? a].set' (possibly because of nullability attributes). // string B.this[int[] a] { set { } } // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("a", "void B.this[int[]? a].set").WithLocation(25, 30) ); } [Fact] public void Partial_NullabilityContravariance_01() { var src = @" interface I<out T> {} partial class A { partial void M(object o); partial void M2((object, object) t); partial void M3(I<object> i); partial void M4(ref object o); partial void M6(in object o); } partial class A { partial void M(object? o) { } partial void M2((object?, object?) t) { } partial void M3(I<object?> i) { } partial void M4(ref object? o) { } // warn partial void M6(in object? o) { } } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,18): warning CS8826: Partial method declarations 'void A.M(object o)' and 'void A.M(object? o)' have signature differences. // partial void M(object? o) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M").WithArguments("void A.M(object o)", "void A.M(object? o)").WithLocation(13, 18), // (14,18): warning CS8826: Partial method declarations 'void A.M2((object, object) t)' and 'void A.M2((object?, object?) t)' have signature differences. // partial void M2((object?, object?) t) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M2").WithArguments("void A.M2((object, object) t)", "void A.M2((object?, object?) t)").WithLocation(14, 18), // (15,18): warning CS8826: Partial method declarations 'void A.M3(I<object> i)' and 'void A.M3(I<object?> i)' have signature differences. // partial void M3(I<object?> i) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M3").WithArguments("void A.M3(I<object> i)", "void A.M3(I<object?> i)").WithLocation(15, 18), // (16,18): warning CS8611: Nullability of reference types in type of parameter 'o' doesn't match partial method declaration. // partial void M4(ref object? o) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M4").WithArguments("o").WithLocation(16, 18), // (17,18): warning CS8826: Partial method declarations 'void A.M6(in object o)' and 'void A.M6(in object? o)' have signature differences. // partial void M6(in object? o) { } Diagnostic(ErrorCode.WRN_PartialMethodTypeDifference, "M6").WithArguments("void A.M6(in object o)", "void A.M6(in object? o)").WithLocation(17, 18) ); } [Fact] public void Partial_NullabilityContravariance_02() { var src = @" interface I<out T> {} partial class B { partial void M(object? o); partial void M2((object?, object?) t); partial void M3(I<object?> i); partial void M4(ref object? o); partial void M6(in object? o); } partial class B { partial void M(object o) { } // warn partial void M2((object, object) t) { } // warn partial void M3(I<object> i) { } // warn partial void M4(ref object o) { } // warn partial void M6(in object o) { } // warn } "; var comp = CreateCompilation(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,18): warning CS8611: Nullability of reference types in type of parameter 'o' doesn't match partial method declaration. // partial void M(object o) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M").WithArguments("o").WithLocation(13, 18), // (14,18): warning CS8611: Nullability of reference types in type of parameter 't' doesn't match partial method declaration. // partial void M2((object, object) t) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M2").WithArguments("t").WithLocation(14, 18), // (15,18): warning CS8611: Nullability of reference types in type of parameter 'i' doesn't match partial method declaration. // partial void M3(I<object> i) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M3").WithArguments("i").WithLocation(15, 18), // (16,18): warning CS8611: Nullability of reference types in type of parameter 'o' doesn't match partial method declaration. // partial void M4(ref object o) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M4").WithArguments("o").WithLocation(16, 18), // (17,18): warning CS8611: Nullability of reference types in type of parameter 'o' doesn't match partial method declaration. // partial void M6(in object o) { } // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M6").WithArguments("o").WithLocation(17, 18) ); } [Fact] public void Implementing_07() { var source = @" class C { public static void Main() { } } interface IA { void M1(string[] x); void M2<T>(T[] x) where T : class; void M3<T>(T?[]? x) where T : class; } class B : IA { public void M1(string?[] x) { } public void M2<T>(T?[] x) where T : class { } public void M3<T>(T?[]? x) where T : class { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var ia = compilation.GetTypeByMetadataName("IA"); var b = compilation.GetTypeByMetadataName("B"); foreach (var memberName in new[] { "M1", "M2" }) { var member = ia.GetMember<MethodSymbol>(memberName); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.False(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var member = ia.GetMember<MethodSymbol>("M3"); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.True(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } [Fact] public void Implementing_08() { var source = @" class C { public static void Main() { } } interface IA { void M1(string[] x); void M2<T>(T[] x) where T : class; void M3<T>(T?[]? x) where T : class; } class B : IA { void IA.M1(string?[] x) { } void IA.M2<T>(T?[] x) { } void IA.M3<T>(T?[]? x) { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (20,13): error CS0539: 'B.M2<T>(T?[])' in explicit interface declaration is not found among members of the interface that can be implemented // void IA.M2<T>(T?[] x) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M2").WithArguments("B.M2<T>(T?[])").WithLocation(20, 13), // (24,13): error CS0539: 'B.M3<T>(T?[]?)' in explicit interface declaration is not found among members of the interface that can be implemented // void IA.M3<T>(T?[]? x) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M3").WithArguments("B.M3<T>(T?[]?)").WithLocation(24, 13), // (14,11): error CS0535: 'B' does not implement interface member 'IA.M3<T>(T?[]?)' // class B : IA Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IA").WithArguments("B", "IA.M3<T>(T?[]?)").WithLocation(14, 11), // (14,11): error CS0535: 'B' does not implement interface member 'IA.M2<T>(T[])' // class B : IA Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "IA").WithArguments("B", "IA.M2<T>(T[])").WithLocation(14, 11), // (20,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void IA.M2<T>(T?[] x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(20, 24), // (24,25): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void IA.M3<T>(T?[]? x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(24, 25)); } [Fact] public void Overriding_20() { var source = @" class C { public static void Main() { } } abstract class A1 { public abstract int this[string?[] x] {get; set;} } abstract class A2 { public abstract int this[string[] x] {get; set;} } abstract class A3 { public abstract int this[string?[]? x] {get; set;} } class B1 : A1 { public override int this[string[] x] { get {throw new System.NotImplementedException();} set {} // 1 } } class B2 : A2 { public override int this[string[]? x] { get {throw new System.NotImplementedException();} set {} } } class B3 : A3 { public override int this[string?[]? x] { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (27,9): warning CS8610: Nullability of reference types in type of parameter 'x' doesn't match overridden member. // set {} // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("x").WithLocation(27, 9) ); foreach (string typeName in new[] { "B1", "B2" }) { foreach (var member in compilation.GetTypeByMetadataName(typeName).GetMembers().OfType<PropertySymbol>()) { Assert.False(member.Parameters[0].TypeWithAnnotations.Equals(member.OverriddenProperty.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } foreach (var member in compilation.GetTypeByMetadataName("B3").GetMembers().OfType<PropertySymbol>()) { Assert.True(member.Parameters[0].TypeWithAnnotations.Equals(member.OverriddenProperty.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "A1", "A2", "A3", "B1", "B2", "B3" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var property in type.GetMembers().OfType<PropertySymbol>()) { Assert.True(property.TypeWithAnnotations.Equals(property.GetMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(property.TypeWithAnnotations.Equals(property.SetMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Implementing_09() { var source = @" class C { public static void Main() { } } interface IA1 { int this[string?[] x] {get; set;} } interface IA2 { int this[string[] x] {get; set;} } interface IA3 { int this[string?[]? x] {get; set;} } class B1 : IA1 { public int this[string[] x] { get {throw new System.NotImplementedException();} set {} // 1 } } class B2 : IA2 { public int this[string[]? x] // 2 { get {throw new System.NotImplementedException();} set {} } } class B3 : IA3 { public int this[string?[]? x] // 3 { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (27,9): warning CS8614: Nullability of reference types in type of parameter 'x' of 'void B1.this[string[] x].set' doesn't match implicitly implemented member 'void IA1.this[string?[] x].set'. // set {} // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnImplicitImplementation, "set").WithArguments("x", "void B1.this[string[] x].set", "void IA1.this[string?[] x].set").WithLocation(27, 9) ); foreach (string[] typeName in new[] { new[] { "IA1", "B1" }, new[] { "IA2", "B2" } }) { var implemented = compilation.GetTypeByMetadataName(typeName[0]).GetMembers().OfType<PropertySymbol>().Single(); var implementing = (PropertySymbol)compilation.GetTypeByMetadataName(typeName[1]).FindImplementationForInterfaceMember(implemented); Assert.False(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var implemented = compilation.GetTypeByMetadataName("IA3").GetMembers().OfType<PropertySymbol>().Single(); var implementing = (PropertySymbol)compilation.GetTypeByMetadataName("B3").FindImplementationForInterfaceMember(implemented); Assert.True(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA1", "IA2", "IA3", "B1", "B2", "B3" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var property in type.GetMembers().OfType<PropertySymbol>()) { Assert.True(property.TypeWithAnnotations.Equals(property.GetMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(property.TypeWithAnnotations.Equals(property.SetMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Implementing_10() { var source = @" class C { public static void Main() { } } interface IA1 { int this[string?[] x] {get; set;} } interface IA2 { int this[string[] x] {get; set;} } interface IA3 { int this[string?[]? x] {get; set;} } class B1 : IA1 { int IA1.this[string[] x] { get {throw new System.NotImplementedException();} set {} // 1 } } class B2 : IA2 { int IA2.this[string[]? x] // 2 { get {throw new System.NotImplementedException();} set {} } } class B3 : IA3 { int IA3.this[string?[]? x] // 3 { get {throw new System.NotImplementedException();} set {} } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (27,9): warning CS8617: Nullability of reference types in type of parameter 'x' doesn't match implemented member 'void IA1.this[string?[] x].set'. // set {} // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnExplicitImplementation, "set").WithArguments("x", "void IA1.this[string?[] x].set").WithLocation(27, 9) ); foreach (string[] typeName in new[] { new[] { "IA1", "B1" }, new[] { "IA2", "B2" } }) { var implemented = compilation.GetTypeByMetadataName(typeName[0]).GetMembers().OfType<PropertySymbol>().Single(); var implementing = (PropertySymbol)compilation.GetTypeByMetadataName(typeName[1]).FindImplementationForInterfaceMember(implemented); Assert.False(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var implemented = compilation.GetTypeByMetadataName("IA3").GetMembers().OfType<PropertySymbol>().Single(); var implementing = (PropertySymbol)compilation.GetTypeByMetadataName("B3").FindImplementationForInterfaceMember(implemented); Assert.True(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } foreach (string typeName in new[] { "IA1", "IA2", "IA3", "B1", "B2", "B3" }) { var type = compilation.GetTypeByMetadataName(typeName); foreach (var property in type.GetMembers().OfType<PropertySymbol>()) { Assert.True(property.TypeWithAnnotations.Equals(property.GetMethod.ReturnTypeWithAnnotations, TypeCompareKind.ConsiderEverything)); Assert.True(property.TypeWithAnnotations.Equals(property.SetMethod.Parameters.Last().TypeWithAnnotations, TypeCompareKind.ConsiderEverything)); } } } [Fact] public void Implementing_11() { var source = @" public interface I1<T> { void M(); } public class A {} public interface I2 : I1<A?> { } public interface I3 : I1<A> { } public class C1 : I2, I1<A> { void I1<A?>.M(){} void I1<A>.M(){} } public class C2 : I1<A>, I2 { void I1<A?>.M(){} void I1<A>.M(){} } public class C3 : I1<A>, I1<A?> { void I1<A?>.M(){} void I1<A>.M(){} } public class C4 : I2, I3 { void I1<A?>.M(){} void I1<A>.M(){} } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,14): warning CS8645: 'I1<A>' is already listed in the interface list on type 'C1' with different nullability of reference types. // public class C1 : I2, I1<A> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C1").WithArguments("I1<A>", "C1").WithLocation(11, 14), // (11,14): error CS8646: 'I1<A?>.M()' is explicitly implemented more than once. // public class C1 : I2, I1<A> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<A?>.M()").WithLocation(11, 14), // (11,14): error CS8646: 'I1<A>.M()' is explicitly implemented more than once. // public class C1 : I2, I1<A> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<A>.M()").WithLocation(11, 14), // (17,14): warning CS8645: 'I1<A?>' is already listed in the interface list on type 'C2' with different nullability of reference types. // public class C2 : I1<A>, I2 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C2").WithArguments("I1<A?>", "C2").WithLocation(17, 14), // (17,14): error CS8646: 'I1<A>.M()' is explicitly implemented more than once. // public class C2 : I1<A>, I2 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<A>.M()").WithLocation(17, 14), // (17,14): error CS8646: 'I1<A?>.M()' is explicitly implemented more than once. // public class C2 : I1<A>, I2 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<A?>.M()").WithLocation(17, 14), // (23,14): warning CS8645: 'I1<A?>' is already listed in the interface list on type 'C3' with different nullability of reference types. // public class C3 : I1<A>, I1<A?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C3").WithArguments("I1<A?>", "C3").WithLocation(23, 14), // (23,14): error CS8646: 'I1<A>.M()' is explicitly implemented more than once. // public class C3 : I1<A>, I1<A?> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<A>.M()").WithLocation(23, 14), // (23,14): error CS8646: 'I1<A?>.M()' is explicitly implemented more than once. // public class C3 : I1<A>, I1<A?> Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<A?>.M()").WithLocation(23, 14), // (29,14): warning CS8645: 'I1<A>' is already listed in the interface list on type 'C4' with different nullability of reference types. // public class C4 : I2, I3 Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C4").WithArguments("I1<A>", "C4").WithLocation(29, 14), // (29,14): error CS8646: 'I1<A?>.M()' is explicitly implemented more than once. // public class C4 : I2, I3 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<A?>.M()").WithLocation(29, 14), // (29,14): error CS8646: 'I1<A>.M()' is explicitly implemented more than once. // public class C4 : I2, I3 Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<A>.M()").WithLocation(29, 14) ); var c1 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C1"); var c1Interfaces = c1.Interfaces(); var c1AllInterfaces = c1.AllInterfaces(); Assert.Equal(2, c1Interfaces.Length); Assert.Equal(3, c1AllInterfaces.Length); Assert.Equal("I2", c1Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c1Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2", c1AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c1AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c1AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c1); var c2 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C2"); var c2Interfaces = c2.Interfaces(); var c2AllInterfaces = c2.AllInterfaces(); Assert.Equal(2, c2Interfaces.Length); Assert.Equal(3, c2AllInterfaces.Length); Assert.Equal("I1<A!>", c2Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2", c2Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c2AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2", c2AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c2AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c2); var c3 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C3"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<A!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c3); var c4 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C4"); var c4Interfaces = c4.Interfaces(); var c4AllInterfaces = c4.AllInterfaces(); Assert.Equal(2, c4Interfaces.Length); Assert.Equal(4, c4AllInterfaces.Length); Assert.Equal("I2", c4Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I3", c4Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2", c4AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c4AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I3", c4AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c4AllInterfaces[3].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c4); void assertExplicitInterfaceImplementations(NamedTypeSymbol c) { var members = c.GetMembers("I1<A>.M"); Assert.Equal(2, members.Length); var cMabImplementations = ((MethodSymbol)members[0]).ExplicitInterfaceImplementations; Assert.Equal(1, cMabImplementations.Length); Assert.Equal("void I1<A?>.M()", cMabImplementations[0].ToTestDisplayString(includeNonNullable: true)); var cMcdImplementations = ((MethodSymbol)members[1]).ExplicitInterfaceImplementations; Assert.Equal(1, cMcdImplementations.Length); Assert.Equal("void I1<A!>.M()", cMcdImplementations[0].ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void Implementing_12() { var source = @" public interface I1<T> { void M1(); void M2(); } public class A {} public class C1 : I1<A?> { public void M1() => System.Console.Write(""C1.M1 ""); void I1<A?>.M2() => System.Console.Write(""C1.M2 ""); } public class C2 : C1, I1<A> { new public void M1() => System.Console.Write(""C2.M1 ""); void I1<A>.M2() => System.Console.Write(""C2.M2 ""); static void Main() { var x = (C1)new C2(); var y = (I1<A?>)x; y.M1(); y.M2(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics(); Action<ModuleSymbol> validate = (m) => { bool isMetadata = m is PEModuleSymbol; var c1 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C1"); var c1Interfaces = c1.Interfaces(); var c1AllInterfaces = c1.AllInterfaces(); Assert.Equal(1, c1Interfaces.Length); Assert.Equal(1, c1AllInterfaces.Length); Assert.Equal("I1<A?>", c1Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c1AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); var c2 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C2"); var c2Interfaces = c2.Interfaces(); var c2AllInterfaces = c2.AllInterfaces(); Assert.Equal(1, c2Interfaces.Length); Assert.Equal(2, c2AllInterfaces.Length); Assert.Equal("I1<A!>", c2Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c2AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c2AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("void C2.M1()", c2.FindImplementationForInterfaceMember(((TypeSymbol)c2Interfaces[0]).GetMember("M1")).ToTestDisplayString(includeNonNullable: true)); Assert.Equal("void C2.M1()", c2.FindImplementationForInterfaceMember(((TypeSymbol)c1Interfaces[0]).GetMember("M1")).ToTestDisplayString(includeNonNullable: true)); var m2 = (MethodSymbol)((TypeSymbol)c2).GetMember("I1<A>.M2"); var m2Implementations = m2.ExplicitInterfaceImplementations; Assert.Equal(1, m2Implementations.Length); Assert.Equal(isMetadata ? "void I1<A>.M2()" : "void I1<A!>.M2()", m2Implementations[0].ToTestDisplayString(includeNonNullable: true)); Assert.Same(m2, c2.FindImplementationForInterfaceMember(((TypeSymbol)c2Interfaces[0]).GetMember("M2"))); Assert.Same(m2, c2.FindImplementationForInterfaceMember(((TypeSymbol)c1Interfaces[0]).GetMember("M2"))); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C2.M1 C2.M2"); } [Fact] public void Implementing_13() { var source = @" public interface I1<T> { void M1(); void M2(); } public class A {} public class C1 : I1<A?> { public void M1() => System.Console.Write(""C1.M1 ""); void I1<A?>.M2() => System.Console.Write(""C1.M2 ""); public virtual void M2() {} } public class C2 : C1, I1<A> { static void Main() { var x = (C1)new C2(); var y = (I1<A>)x; y.M1(); y.M2(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (17,23): warning CS8644: 'C2' does not implement interface member 'I1<A>.M2()'. Nullability of reference types in interface implemented by the base type doesn't match. // public class C2 : C1, I1<A> Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I1<A>").WithArguments("C2", "I1<A>.M2()").WithLocation(17, 23) ); Action<ModuleSymbol> validate = (m) => { bool isMetadata = m is PEModuleSymbol; var c1 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C1"); var c1Interfaces = c1.Interfaces(); var c1AllInterfaces = c1.AllInterfaces(); Assert.Equal(1, c1Interfaces.Length); Assert.Equal(1, c1AllInterfaces.Length); Assert.Equal("I1<A?>", c1Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c1AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); var c2 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C2"); var c2Interfaces = c2.Interfaces(); var c2AllInterfaces = c2.AllInterfaces(); Assert.Equal(1, c2Interfaces.Length); Assert.Equal(2, c2AllInterfaces.Length); Assert.Equal("I1<A!>", c2Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c2AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c2AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("void C1.M1()", c2.FindImplementationForInterfaceMember(((TypeSymbol)c2Interfaces[0]).GetMember("M1")).ToTestDisplayString(includeNonNullable: true)); Assert.Equal("void C1.M1()", c2.FindImplementationForInterfaceMember(((TypeSymbol)c1Interfaces[0]).GetMember("M1")).ToTestDisplayString(includeNonNullable: true)); var m2 = (MethodSymbol)((TypeSymbol)c1).GetMember("I1<A>.M2"); var m2Implementations = m2.ExplicitInterfaceImplementations; Assert.Equal(1, m2Implementations.Length); Assert.Equal(isMetadata ? "void I1<A>.M2()" : "void I1<A?>.M2()", m2Implementations[0].ToTestDisplayString(includeNonNullable: true)); Assert.Same(m2, c2.FindImplementationForInterfaceMember(((TypeSymbol)c2Interfaces[0]).GetMember("M2"))); Assert.Same(m2, c2.FindImplementationForInterfaceMember(((TypeSymbol)c1Interfaces[0]).GetMember("M2"))); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C1.M1 C1.M2"); } [Fact] public void Implementing_14() { var source = @" public interface I1<T> { void M1(); } public class A {} public class C1 : I1<A?> { } public class C2 : C1, I1<A> { } public class C3 : C1, I1<A?> { } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,19): error CS0535: 'C1' does not implement interface member 'I1<A?>.M1()' // public class C1 : I1<A?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<A?>").WithArguments("C1", "I1<A?>.M1()").WithLocation(9, 19), // (13,23): warning CS8644: 'C2' does not implement interface member 'I1<A>.M1()'. Nullability of reference types in interface implemented by the base type doesn't match. // public class C2 : C1, I1<A> Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I1<A>").WithArguments("C2", "I1<A>.M1()").WithLocation(13, 23) ); } [Fact] public void Implementing_15() { var source1 = @" public interface I1<T> { void M1(); } public class A {} public class C1 : I1<A?> { } "; var comp1 = CreateCompilation(source1, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (9,19): error CS0535: 'C1' does not implement interface member 'I1<A?>.M1()' // public class C1 : I1<A?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I1<A?>").WithArguments("C1", "I1<A?>.M1()").WithLocation(9, 19) ); var source2 = @" public class C2 : C1, I1<A> { } public class C3 : C1, I1<A?> { } "; var comp2 = CreateCompilation(source2, references: new[] { comp1.ToMetadataReference() }, options: WithNullableEnable()); comp2.VerifyDiagnostics( // (2,23): warning CS8644: 'C2' does not implement interface member 'I1<A>.M1()'. Nullability of reference types in interface implemented by the base type doesn't match. // public class C2 : C1, I1<A> Diagnostic(ErrorCode.WRN_NullabilityMismatchInInterfaceImplementedByBase, "I1<A>").WithArguments("C2", "I1<A>.M1()").WithLocation(2, 23) ); } [Fact] public void Implementing_16() { var source = @" public interface I1<T> { void M(); } public interface I2<I2T> : I1<I2T?> where I2T : class { } public interface I3<I3T> : I1<I3T> where I3T : class { } public class C1<T> : I2<T>, I1<T> where T : class { void I1<T?>.M(){} void I1<T>.M(){} } public class C2<T> : I1<T>, I2<T> where T : class { void I1<T?>.M(){} void I1<T>.M(){} } public class C3<T> : I1<T>, I1<T?> where T : class { void I1<T?>.M(){} void I1<T>.M(){} } public class C4<T> : I2<T>, I3<T> where T : class { void I1<T?>.M(){} void I1<T>.M(){} } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,14): warning CS8645: 'I1<T>' is already listed in the interface list on type 'C1<T>' with different nullability of reference types. // public class C1<T> : I2<T>, I1<T> where T : class Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C1").WithArguments("I1<T>", "C1<T>").WithLocation(10, 14), // (10,14): error CS8646: 'I1<T?>.M()' is explicitly implemented more than once. // public class C1<T> : I2<T>, I1<T> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<T?>.M()").WithLocation(10, 14), // (10,14): error CS8646: 'I1<T>.M()' is explicitly implemented more than once. // public class C1<T> : I2<T>, I1<T> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C1").WithArguments("I1<T>.M()").WithLocation(10, 14), // (16,14): warning CS8645: 'I1<T?>' is already listed in the interface list on type 'C2<T>' with different nullability of reference types. // public class C2<T> : I1<T>, I2<T> where T : class Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C2").WithArguments("I1<T?>", "C2<T>").WithLocation(16, 14), // (16,14): error CS8646: 'I1<T>.M()' is explicitly implemented more than once. // public class C2<T> : I1<T>, I2<T> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<T>.M()").WithLocation(16, 14), // (16,14): error CS8646: 'I1<T?>.M()' is explicitly implemented more than once. // public class C2<T> : I1<T>, I2<T> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I1<T?>.M()").WithLocation(16, 14), // (22,14): warning CS8645: 'I1<T?>' is already listed in the interface list on type 'C3<T>' with different nullability of reference types. // public class C3<T> : I1<T>, I1<T?> where T : class Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C3").WithArguments("I1<T?>", "C3<T>").WithLocation(22, 14), // (22,14): error CS8646: 'I1<T>.M()' is explicitly implemented more than once. // public class C3<T> : I1<T>, I1<T?> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<T>.M()").WithLocation(22, 14), // (22,14): error CS8646: 'I1<T?>.M()' is explicitly implemented more than once. // public class C3<T> : I1<T>, I1<T?> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C3").WithArguments("I1<T?>.M()").WithLocation(22, 14), // (28,14): warning CS8645: 'I1<T>' is already listed in the interface list on type 'C4<T>' with different nullability of reference types. // public class C4<T> : I2<T>, I3<T> where T : class Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C4").WithArguments("I1<T>", "C4<T>").WithLocation(28, 14), // (28,14): error CS8646: 'I1<T?>.M()' is explicitly implemented more than once. // public class C4<T> : I2<T>, I3<T> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<T?>.M()").WithLocation(28, 14), // (28,14): error CS8646: 'I1<T>.M()' is explicitly implemented more than once. // public class C4<T> : I2<T>, I3<T> where T : class Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C4").WithArguments("I1<T>.M()").WithLocation(28, 14) ); var c1 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C1`1"); var c1Interfaces = c1.Interfaces(); var c1AllInterfaces = c1.AllInterfaces(); Assert.Equal(2, c1Interfaces.Length); Assert.Equal(3, c1AllInterfaces.Length); Assert.Equal("I2<T!>", c1Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T!>", c1Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2<T!>", c1AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T?>", c1AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T!>", c1AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c1); var c2 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C2`1"); var c2Interfaces = c2.Interfaces(); var c2AllInterfaces = c2.AllInterfaces(); Assert.Equal(2, c2Interfaces.Length); Assert.Equal(3, c2AllInterfaces.Length); Assert.Equal("I1<T!>", c2Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2<T!>", c2Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T!>", c2AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2<T!>", c2AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T?>", c2AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c2); var c3 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C3`1"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<T!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T?>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c3); var c4 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C4`1"); var c4Interfaces = c4.Interfaces(); var c4AllInterfaces = c4.AllInterfaces(); Assert.Equal(2, c4Interfaces.Length); Assert.Equal(4, c4AllInterfaces.Length); Assert.Equal("I2<T!>", c4Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I3<T!>", c4Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2<T!>", c4AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T?>", c4AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I3<T!>", c4AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T!>", c4AllInterfaces[3].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c4); void assertExplicitInterfaceImplementations(NamedTypeSymbol c) { var members = c.GetMembers("I1<T>.M"); Assert.Equal(2, members.Length); var cMabImplementations = ((MethodSymbol)members[0]).ExplicitInterfaceImplementations; Assert.Equal(1, cMabImplementations.Length); Assert.Equal("void I1<T?>.M()", cMabImplementations[0].ToTestDisplayString(includeNonNullable: true)); var cMcdImplementations = ((MethodSymbol)members[1]).ExplicitInterfaceImplementations; Assert.Equal(1, cMcdImplementations.Length); Assert.Equal("void I1<T!>.M()", cMcdImplementations[0].ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void Implementing_17() { var source = @" public interface I1<T> { void M(); } public class C3<T, U> : I1<T>, I1<U?> where T : class where U : class { void I1<U?>.M(){} void I1<T>.M(){} } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,14): error CS0695: 'C3<T, U>' cannot implement both 'I1<T>' and 'I1<U?>' because they may unify for some type parameter substitutions // public class C3<T, U> : I1<T>, I1<U?> where T : class where U : class Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I1<T>", "I1<U?>").WithLocation(7, 14) ); var c3 = (NamedTypeSymbol)comp.GetTypeByMetadataName("C3`2"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<T!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<U?>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<T!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<U?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); assertExplicitInterfaceImplementations(c3); void assertExplicitInterfaceImplementations(NamedTypeSymbol c) { var cMabImplementations = ((MethodSymbol)((TypeSymbol)c).GetMember("I1<T>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMabImplementations.Length); Assert.Equal("void I1<T!>.M()", cMabImplementations[0].ToTestDisplayString(includeNonNullable: true)); var cMcdImplementations = ((MethodSymbol)((TypeSymbol)c).GetMember("I1<U>.M")).ExplicitInterfaceImplementations; Assert.Equal(1, cMcdImplementations.Length); Assert.Equal("void I1<U?>.M()", cMcdImplementations[0].ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void Implementing_18() { var source = @" public interface I1<T> { void M(); } public class A {} public class C3 : I1<A> { void I1<A?>.M() { System.Console.Write(""C3.M ""); } static void Main() { var x = new C3(); ((I1<A>)x).M(); ((I1<A?>)x).M(); } } public class C4 : I1<A?> { void I1<A?>.M(){} } "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (11,10): warning CS8643: Nullability of reference types in explicit interface specifier doesn't match interface implemented by the type. // void I1<A?>.M() Diagnostic(ErrorCode.WRN_NullabilityMismatchInExplicitlyImplementedInterface, "I1<A?>").WithLocation(11, 10) ); Action<ModuleSymbol> validate = (ModuleSymbol m) => { bool isMetadata = m is PEModuleSymbol; var c3 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C3"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); Assert.Equal(1, c3Interfaces.Length); Assert.Equal(1, c3AllInterfaces.Length); Assert.Equal("I1<A!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); var method = (MethodSymbol)((TypeSymbol)c3).GetMember("I1<A>.M"); Assert.Equal("I1<A>.M", method.Name); var mImplementations = method.ExplicitInterfaceImplementations; Assert.Equal(1, mImplementations.Length); Assert.Equal(isMetadata ? "void I1<A>.M()" : "void I1<A?>.M()", mImplementations[0].ToTestDisplayString(includeNonNullable: true)); Assert.Same(method, c3.FindImplementationForInterfaceMember(((TypeSymbol)c3Interfaces[0]).GetMember("M"))); Assert.Same(method, c3.FindImplementationForInterfaceMember(mImplementations[0])); Assert.Same(method, c3.FindImplementationForInterfaceMember(m.GlobalNamespace.GetTypeMember("C4").InterfacesNoUseSiteDiagnostics()[0].GetMember("M"))); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C3.M C3.M"); } [Fact] public void Implementing_19() { var source = @" public interface I1<T> { void M(); } public class A {} public class C3 : I1<A>, I1<A?> { void I1<A?>.M() { System.Console.Write(""C3.M ""); } static void Main() { var x = new C3(); ((I1<A>)x).M(); ((I1<A?>)x).M(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (9,14): warning CS8645: 'I1<A?>' is already listed in the interface list on type 'C3' with different nullability of reference types. // public class C3 : I1<A>, I1<A?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C3").WithArguments("I1<A?>", "C3").WithLocation(9, 14) ); Action<ModuleSymbol> validate = (ModuleSymbol m) => { bool isMetadata = m is PEModuleSymbol; var c3 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C3"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); if (isMetadata) { Assert.Equal(1, c3Interfaces.Length); Assert.Equal(1, c3AllInterfaces.Length); Assert.Equal("I1<A!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); } else { Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<A!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); } var method = (MethodSymbol)((TypeSymbol)c3).GetMember("I1<A>.M"); Assert.Equal("I1<A>.M", method.Name); var mImplementations = method.ExplicitInterfaceImplementations; Assert.Equal(1, mImplementations.Length); Assert.Equal(isMetadata ? "void I1<A>.M()" : "void I1<A?>.M()", mImplementations[0].ToTestDisplayString(includeNonNullable: true)); Assert.Same(method, c3.FindImplementationForInterfaceMember(((TypeSymbol)c3Interfaces[0]).GetMember("M"))); Assert.Same(method, c3.FindImplementationForInterfaceMember(mImplementations[0])); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C3.M C3.M"); } [Fact] public void Implementing_20() { var source = @" public interface I1<T> { void M(); } public class A {} public interface I2 : I1<A?> {} public class C3 : I2, I1<A> { void I1<A?>.M() { System.Console.Write(""C3.M ""); } static void Main() { var x = new C3(); ((I1<A>)x).M(); ((I1<A?>)x).M(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (12,14): warning CS8645: 'I1<A>' is already listed in the interface list on type 'C3' with different nullability of reference types. // public class C3 : I2, I1<A> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C3").WithArguments("I1<A>", "C3").WithLocation(12, 14) ); Action<ModuleSymbol> validate = (ModuleSymbol m) => { bool isMetadata = m is PEModuleSymbol; var c3 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C3"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); if (isMetadata) { Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I2", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); } else { Assert.Equal(2, c3Interfaces.Length); Assert.Equal(3, c3AllInterfaces.Length); Assert.Equal("I2", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I2", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[2].ToTestDisplayString(includeNonNullable: true)); } var method = (MethodSymbol)((TypeSymbol)c3).GetMember("I1<A>.M"); Assert.Equal("I1<A>.M", method.Name); var mImplementations = method.ExplicitInterfaceImplementations; Assert.Equal(1, mImplementations.Length); Assert.Equal(isMetadata ? "void I1<A>.M()" : "void I1<A?>.M()", mImplementations[0].ToTestDisplayString(includeNonNullable: true)); Assert.Same(method, c3.FindImplementationForInterfaceMember(((TypeSymbol)c3Interfaces[1]).GetMember("M"))); Assert.Same(method, c3.FindImplementationForInterfaceMember(mImplementations[0])); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C3.M C3.M"); } [Fact] public void Implementing_21() { var source = @" public interface I1<T> { void M(); } public class A {} public partial class C3 : I1<A> { void I1<A?>.M() { System.Console.Write(""C3.M ""); } static void Main() { var x = new C3(); ((I1<A>)x).M(); ((I1<A?>)x).M(); } } public partial class C3 : I1<A?> {} "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics( // (9,22): warning CS8645: 'I1<A?>' is already listed in the interface list on type 'C3' with different nullability of reference types. // public partial class C3 : I1<A> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C3").WithArguments("I1<A?>", "C3").WithLocation(9, 22) ); Action<ModuleSymbol> validate = (ModuleSymbol m) => { bool isMetadata = m is PEModuleSymbol; var c3 = (NamedTypeSymbol)m.GlobalNamespace.GetTypeMember("C3"); var c3Interfaces = c3.Interfaces(); var c3AllInterfaces = c3.AllInterfaces(); if (isMetadata) { Assert.Equal(1, c3Interfaces.Length); Assert.Equal(1, c3AllInterfaces.Length); Assert.Equal("I1<A!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); } else { Assert.Equal(2, c3Interfaces.Length); Assert.Equal(2, c3AllInterfaces.Length); Assert.Equal("I1<A!>", c3Interfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3Interfaces[1].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A!>", c3AllInterfaces[0].ToTestDisplayString(includeNonNullable: true)); Assert.Equal("I1<A?>", c3AllInterfaces[1].ToTestDisplayString(includeNonNullable: true)); } var method = (MethodSymbol)((TypeSymbol)c3).GetMember("I1<A>.M"); Assert.Equal("I1<A>.M", method.Name); var mImplementations = method.ExplicitInterfaceImplementations; Assert.Equal(1, mImplementations.Length); Assert.Equal(isMetadata ? "void I1<A>.M()" : "void I1<A?>.M()", mImplementations[0].ToTestDisplayString(includeNonNullable: true)); Assert.Same(method, c3.FindImplementationForInterfaceMember(((TypeSymbol)c3Interfaces[0]).GetMember("M"))); Assert.Same(method, c3.FindImplementationForInterfaceMember(mImplementations[0])); }; CompileAndVerify(comp, sourceSymbolValidator: validate, symbolValidator: validate, expectedOutput: @"C3.M C3.M"); } [Fact] public void Implementing_23() { var source = @" class C { public static void Main() { } } interface IA { void M1(string[] x); void M2<T>(T[] x) where T : class; void M3<T>(T?[]? x) where T : class; } class B : IA { void IA.M1(string?[] x) { } void IA.M2<T>(T?[] x) where T : class { } void IA.M3<T>(T?[]? x) where T : class { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); var ia = compilation.GetTypeByMetadataName("IA"); var b = compilation.GetTypeByMetadataName("B"); foreach (var memberName in new[] { "M1", "M2" }) { var member = ia.GetMember<MethodSymbol>(memberName); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.False(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var member = ia.GetMember<MethodSymbol>("M3"); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.True(implementing.Parameters[0].TypeWithAnnotations.Equals(implemented.Parameters[0].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } [Fact] public void Implementing_24() { var source = @" class C { public static void Main() { } } interface IA { string[] M1(); T[] M2<T>() where T : class; T?[]? M3<T>() where T : class; } class B : IA { string?[] IA.M1() { return new string?[] {}; } S?[] IA.M2<S>() where S : class { return new S?[] {}; } S?[]? IA.M3<S>() where S : class { return new S?[] {}; } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (23,13): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'T[] IA.M2<T>()'. // S?[] IA.M2<S>() where S : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M2").WithArguments("T[] IA.M2<T>()").WithLocation(23, 13), // (18,18): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'string[] IA.M1()'. // string?[] IA.M1() Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "M1").WithArguments("string[] IA.M1()").WithLocation(18, 18) ); var ia = compilation.GetTypeByMetadataName("IA"); var b = compilation.GetTypeByMetadataName("B"); foreach (var memberName in new[] { "M1", "M2" }) { var member = ia.GetMember<MethodSymbol>(memberName); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.False(implementing.ReturnTypeWithAnnotations.Equals(implemented.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } { var member = ia.GetMember<MethodSymbol>("M3"); var implementing = (MethodSymbol)b.FindImplementationForInterfaceMember(member); var implemented = member.ConstructIfGeneric(implementing.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); Assert.True(implementing.ReturnTypeWithAnnotations.Equals(implemented.ReturnTypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } } [Fact] public void Implementing_25() { var source = @" #nullable enable interface I { void M<T>(T value) where T : class; } class C : I { void I.M<T>(T value) { T? x = value; } } "; var compilation = CreateCompilation(source).VerifyDiagnostics(); var c = compilation.GetTypeByMetadataName("C"); var member = c.GetMember<MethodSymbol>("I.M"); var tp = member.GetMemberTypeParameters()[0]; Assert.True(tp.IsReferenceType); Assert.False(tp.IsNullableType()); } [Fact] public void PartialMethods_01() { var source = @" class C { public static void Main() { } } partial class C1 { partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; } partial class C1 { partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class { } }"; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (16,18): warning CS8611: Nullability of reference types in type of parameter 'y' doesn't match partial method declaration. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M1").WithArguments("y").WithLocation(16, 18), // (16,18): warning CS8611: Nullability of reference types in type of parameter 'z' doesn't match partial method declaration. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M1").WithArguments("z").WithLocation(16, 18) ); var c1 = compilation.GetTypeByMetadataName("C1"); var m1 = c1.GetMember<MethodSymbol>("M1"); var m1Impl = m1.PartialImplementationPart; var m1Def = m1.ConstructIfGeneric(m1Impl.TypeParameters.SelectAsArray(t => TypeWithAnnotations.Create(t))); for (int i = 0; i < 3; i++) { Assert.False(m1Impl.Parameters[i].TypeWithAnnotations.Equals(m1Def.Parameters[i].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); } Assert.True(m1Impl.Parameters[3].TypeWithAnnotations.Equals(m1Def.Parameters[3].TypeWithAnnotations, TypeCompareKind.AllIgnoreOptions & ~TypeCompareKind.AllNullableIgnoreOptions)); compilation = CreateCompilation("", references: new[] { compilation.EmitToImageReference() }, options: TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)); c1 = compilation.GetTypeByMetadataName("C1"); m1 = c1.GetMember<MethodSymbol>("M1"); Assert.Equal("void C1.M1<T>(T! x, T?[]! y, System.Action<T!>! z, System.Action<T?[]?>?[]? u)", m1.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void PartialMethods_02_01() { var source = @" partial class C1 { #nullable disable partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; } partial class C1 { partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class { } }"; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (5,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 30), // (5,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 29), // (5,72): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 72), // (5,71): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 71), // (5,75): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 75), // (5,77): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 77), // (5,80): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 80), // (10,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 25), // (10,24): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(10, 24), // (10,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 33), // (10,53): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 53), // (10,52): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(10, 52), // (10,74): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 74), // (10,73): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(10, 73), // (10,77): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 77), // (10,79): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 79), // (10,82): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 82) ); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void PartialMethods_02_02() { var source = @" partial class C1 { #nullable disable partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; } #nullable enable partial class C1 { partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class { } }"; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (5,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 30), // (5,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 29), // (5,72): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 72), // (5,71): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 71), // (5,75): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 75), // (5,77): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 77), // (5,80): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 80), // (10,18): warning CS8611: Nullability of reference types in type of parameter 'y' doesn't match partial method declaration. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOnPartial, "M1").WithArguments("y").WithLocation(10, 18) ); } [Fact] public void PartialMethods_03() { var source = @" class C { public static void Main() { } } partial class C1 { partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; } partial class C1 { #nullable disable partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class { } }"; var compilation = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); compilation.VerifyDiagnostics( // (11,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 30), // (11,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(11, 29), // (11,72): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 72), // (11,71): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(11, 71), // (11,75): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 75), // (11,77): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 77), // (11,80): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T x, T?[] y, System.Action<T> z, System.Action<T?[]?>?[]? u) where T : class; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 80), // (17,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 25), // (17,24): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(17, 24), // (17,33): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 33), // (17,53): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 53), // (17,52): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(17, 52), // (17,74): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 74), // (17,73): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(17, 73), // (17,77): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 77), // (17,79): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 79), // (17,82): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // partial void M1<T>(T? x, T[]? y, System.Action<T?> z, System.Action<T?[]?>?[]? u) where T : class Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 82) ); } [Fact] public void Overloading_01() { var source = @" class A { void Test1(string? x1) {} void Test1(string x2) {} string Test2(string y1) { return y1; } string? Test2(string y2) { return y2; } } "; CreateCompilation(new[] { source }, options: WithNullableEnable()). VerifyDiagnostics( // (5,10): error CS0111: Type 'A' already defines a member called 'Test1' with the same parameter types // void Test1(string x2) {} Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Test1").WithArguments("Test1", "A").WithLocation(5, 10), // (8,13): error CS0111: Type 'A' already defines a member called 'Test2' with the same parameter types // string? Test2(string y2) { return y2; } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Test2").WithArguments("Test2", "A").WithLocation(8, 13) ); } [Fact] public void Overloading_02() { var source = @" class A { public void M1<T>(T? x) where T : struct { } public void M1<T>(T? x) where T : class { } } "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics(); } [Fact] public void Test1() { CSharpCompilation c = CreateCompilation( new[] { @"#pragma warning disable 8618 class C { static void Main() { } void Test1() { string? x1 = null; string? y1 = x1; string z1 = x1; } void Test2() { string? x2 = """"; string z2 = x2; } void Test3() { string? x3; string z3 = x3; } void Test4() { string x4; string z4 = x4; } void Test5() { string? x5 = """"; x5 = null; string? y5; y5 = x5; string z5; z5 = x5; } void Test6() { string? x6 = """"; string z6; z6 = x6; } void Test7() { CL1? x7 = null; CL1 y7 = x7.P1; CL1 z7 = x7?.P1; x7 = new CL1(); CL1 u7 = x7.P1; } void Test8() { CL1? x8 = new CL1(); CL1 y8 = x8.M1(); x8 = null; CL1 u8 = x8.M1(); CL1 z8 = x8?.M1(); } void Test9(CL1? x9, CL1 y9) { CL1 u9; u9 = x9; u9 = y9; x9 = y9; CL1 v9; v9 = x9; y9 = null; } void Test10(CL1 x10) { CL1 u10; u10 = x10.P1; u10 = x10.P2; u10 = x10.M1(); u10 = x10.M2(); CL1? v10; v10 = x10.P2; v10 = x10.M2(); } void Test11(CL1 x11, CL1? y11) { CL1 u11; u11 = x11.F1; u11 = x11.F2; CL1? v11; v11 = x11.F2; x11.F2 = x11.F1; u11 = x11.F2; v11 = y11.F1; } void Test12(CL1 x12) { S1 y12; CL1 u12; u12 = y12.F3; u12 = y12.F4; } void Test13(CL1 x13) { S1 y13; CL1? u13; u13 = y13.F3; u13 = y13.F4; } void Test14(CL1 x14) { S1 y14; y14.F3 = null; y14.F4 = null; y14.F3 = x14; y14.F4 = x14; } void Test15(CL1 x15) { S1 y15; CL1 u15; y15.F3 = null; y15.F4 = null; u15 = y15.F3; u15 = y15.F4; CL1? v15; v15 = y15.F4; y15.F4 = x15; u15 = y15.F4; } void Test16() { S1 y16; CL1 u16; y16 = new S1(); u16 = y16.F3; u16 = y16.F4; } void Test17(CL1 z17) { S1 x17; x17.F4 = z17; S1 y17 = new S1(); CL1 u17; u17 = y17.F4; y17 = x17; CL1 v17; v17 = y17.F4; } void Test18(CL1 z18) { S1 x18; x18.F4 = z18; S1 y18 = x18; CL1 u18; u18 = y18.F4; } void Test19(S1 x19, CL1 z19) { S1 y19; y19.F4 = null; CL1 u19; u19 = y19.F4; x19.F4 = z19; y19 = x19; CL1 v19; v19 = y19.F4; } void Test20(S1 x20, CL1 z20) { S1 y20; y20.F4 = z20; CL1 u20; u20 = y20.F4; y20 = x20; CL1 v20; v20 = y20.F4; } S1 GetS1() { return new S1(); } void Test21(CL1 z21) { S1 y21; y21.F4 = z21; CL1 u21; u21 = y21.F4; y21 = GetS1(); CL1 v21; v21 = y21.F4; } void Test22() { S1 y22; CL1 u22; u22 = y22.F4; y22 = GetS1(); CL1 v22; v22 = y22.F4; } void Test23(CL1 z23) { S2 y23; y23.F5.F4 = z23; CL1 u23; u23 = y23.F5.F4; y23 = GetS2(); CL1 v23; v23 = y23.F5.F4; } S2 GetS2() { return new S2(); } void Test24() { S2 y24; CL1 u24; u24 = y24.F5.F4; // 1 u24 = y24.F5.F4; // 2 y24 = GetS2(); CL1 v24; v24 = y24.F5.F4; } void Test25(CL1 z25) { S2 y25; S2 x25 = GetS2(); x25.F5.F4 = z25; y25 = x25; CL1 v25; v25 = y25.F5.F4; } void Test26(CL1 x26, CL1? y26, CL1 z26) { x26.P1 = y26; x26.P1 = z26; } void Test27(CL1 x27, CL1? y27, CL1 z27) { x27[x27] = y27; x27[x27] = z27; } void Test28(CL1 x28, CL1? y28, CL1 z28) { x28[y28] = z28; } void Test29(CL1 x29, CL1 y29, CL1 z29) { z29 = x29[y29]; z29 = x29[1]; } void Test30(CL1? x30, CL1 y30, CL1 z30) { z30 = x30[y30]; } void Test31(CL1 x31) { x31 = default(CL1); } void Test32(CL1 x32) { var y32 = new CL1() ?? x32; } void Test33(object x33) { var y33 = new { p = (object)null } ?? x33; } } class CL1 { public CL1() { F1 = this; } public CL1 F1; public CL1? F2; public CL1 P1 { get; set; } public CL1? P2 { get; set; } public CL1 M1() { return new CL1(); } public CL1? M2() { return null; } public CL1 this[CL1 x] { get { return x; } set { } } public CL1? this[int x] { get { return null; } set { } } } struct S1 { public CL1 F3; public CL1? F4; } struct S2 { public S1 F5; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string z1 = x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(12, 21), // (24,21): error CS0165: Use of unassigned local variable 'x3' // string z3 = x3; Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(24, 21), // (24,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string z3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(24, 21), // (30,21): error CS0165: Use of unassigned local variable 'x4' // string z4 = x4; Diagnostic(ErrorCode.ERR_UseDefViolation, "x4").WithArguments("x4").WithLocation(30, 21), // (40,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // z5 = x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5").WithLocation(40, 14), // (53,18): warning CS8602: Dereference of a possibly null reference. // CL1 y7 = x7.P1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x7").WithLocation(53, 18), // (54,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z7 = x7?.P1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x7?.P1").WithLocation(54, 18), // (64,18): warning CS8602: Dereference of a possibly null reference. // CL1 u8 = x8.M1(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x8").WithLocation(64, 18), // (65,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z8 = x8?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x8?.M1()").WithLocation(65, 18), // (71,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // u9 = x9; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x9").WithLocation(71, 14), // (76,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y9 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(76, 14), // (83,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u10 = x10.P2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x10.P2").WithLocation(83, 15), // (85,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u10 = x10.M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x10.M2()").WithLocation(85, 15), // (95,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u11 = x11.F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x11.F2").WithLocation(95, 15), // (101,15): warning CS8602: Dereference of a possibly null reference. // v11 = y11.F1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y11").WithLocation(101, 15), // (108,15): error CS0170: Use of possibly unassigned field 'F3' // u12 = y12.F3; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y12.F3").WithArguments("F3").WithLocation(108, 15), // (109,15): error CS0170: Use of possibly unassigned field 'F4' // u12 = y12.F4; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y12.F4").WithArguments("F4").WithLocation(109, 15), // (109,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u12 = y12.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y12.F4").WithLocation(109, 15), // (116,15): error CS0170: Use of possibly unassigned field 'F3' // u13 = y13.F3; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y13.F3").WithArguments("F3").WithLocation(116, 15), // (117,15): error CS0170: Use of possibly unassigned field 'F4' // u13 = y13.F4; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y13.F4").WithArguments("F4").WithLocation(117, 15), // (123,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // y14.F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(123, 18), // (133,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // y15.F3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(133, 18), // (135,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u15 = y15.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y15.F3").WithLocation(135, 15), // (136,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u15 = y15.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y15.F4").WithLocation(136, 15), // (149,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u16 = y16.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y16.F3").WithLocation(149, 15), // (150,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u16 = y16.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y16.F4").WithLocation(150, 15), // (161,15): error CS0165: Use of unassigned local variable 'x17' // y17 = x17; Diagnostic(ErrorCode.ERR_UseDefViolation, "x17").WithArguments("x17").WithLocation(161, 15), // (159,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u17 = y17.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y17.F4").WithLocation(159, 15), // (170,18): error CS0165: Use of unassigned local variable 'x18' // S1 y18 = x18; Diagnostic(ErrorCode.ERR_UseDefViolation, "x18").WithArguments("x18").WithLocation(170, 18), // (180,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u19 = y19.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y19.F4").WithLocation(180, 15), // (197,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // v20 = y20.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y20.F4").WithLocation(197, 15), // (213,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // v21 = y21.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y21.F4").WithLocation(213, 15), // (220,15): error CS0170: Use of possibly unassigned field 'F4' // u22 = y22.F4; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y22.F4").WithArguments("F4").WithLocation(220, 15), // (220,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u22 = y22.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y22.F4").WithLocation(220, 15), // (224,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // v22 = y22.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y22.F4").WithLocation(224, 15), // (236,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // v23 = y23.F5.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y23.F5.F4").WithLocation(236, 15), // (248,15): error CS0170: Use of possibly unassigned field 'F4' // u24 = y24.F5.F4; // 1 Diagnostic(ErrorCode.ERR_UseDefViolationField, "y24.F5.F4").WithArguments("F4").WithLocation(248, 15), // (248,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u24 = y24.F5.F4; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y24.F5.F4").WithLocation(248, 15), // (249,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // u24 = y24.F5.F4; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y24.F5.F4").WithLocation(249, 15), // (253,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // v24 = y24.F5.F4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y24.F5.F4").WithLocation(253, 15), // (268,18): warning CS8601: Possible null reference assignment. // x26.P1 = y26; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y26").WithLocation(268, 18), // (274,20): warning CS8601: Possible null reference assignment. // x27[x27] = y27; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y27").WithLocation(274, 20), // (280,13): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1 CL1.this[CL1 x]'. // x28[y28] = z28; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y28").WithArguments("x", "CL1 CL1.this[CL1 x]").WithLocation(280, 13), // (286,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // z29 = x29[1]; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x29[1]").WithLocation(286, 15), // (291,15): warning CS8602: Dereference of a possibly null reference. // z30 = x30[y30]; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x30").WithLocation(291, 15), // (296,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // x31 = default(CL1); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(CL1)").WithLocation(296, 15), // (306,29): warning CS8600: Converting null literal or possible null value to non-nullable type. // var y33 = new { p = (object)null } ?? x33; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)null").WithLocation(306, 29) ); } [Fact] public void PassingParameters_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void M1(CL1 p) {} void Test1(CL1? x1, CL1 y1) { M1(x1); M1(y1); } void Test2() { CL1? x2; M1(x2); } void M2(ref CL1? p) {} void Test3() { CL1 x3; M2(ref x3); } void Test4(CL1 x4) { M2(ref x4); } void M3(out CL1? p) { p = null; } void Test5() { CL1 x5; M3(out x5); } void M4(ref CL1 p) {} void Test6() { CL1? x6 = null; M4(ref x6); } void M5(out CL1 p) { p = new CL1(); } void Test7() { CL1? x7 = null; CL1 u7 = x7; M5(out x7); CL1 v7 = x7; } void M6(CL1 p1, CL1? p2) {} void Test8(CL1? x8, CL1? y8) { M6(p2: x8, p1: y8); } void M7(params CL1[] p1) {} void Test9(CL1 x9, CL1? y9) { M7(x9, y9); } void Test10(CL1? x10, CL1 y10) { M7(x10, y10); } void M8(CL1 p1, params CL1[] p2) {} void Test11(CL1? x11, CL1 y11, CL1? z11) { M8(x11, y11, z11); } void Test12(CL1? x12, CL1 y12) { M8(p2: x12, p1: y12); } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,12): warning CS8604: Possible null reference argument for parameter 'p' in 'void C.M1(CL1 p)'. // M1(x1); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("p", "void C.M1(CL1 p)").WithLocation(12, 12), // (19,12): error CS0165: Use of unassigned local variable 'x2' // M1(x2); Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(19, 12), // (19,12): warning CS8604: Possible null reference argument for parameter 'p' in 'void C.M1(CL1 p)'. // M1(x2); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("p", "void C.M1(CL1 p)").WithLocation(19, 12), // (27,16): error CS0165: Use of unassigned local variable 'x3' // M2(ref x3); Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(27, 16), // (27,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // M2(ref x3); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(27, 16), // (32,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // M2(ref x4); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x4").WithLocation(32, 16), // (40,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // M3(out x5); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5").WithLocation(40, 16), // (48,16): warning CS8601: Possible null reference assignment. // M4(ref x6); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x6").WithLocation(48, 16), // (56,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u7 = x7; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x7").WithLocation(56, 18), // (65,24): warning CS8604: Possible null reference argument for parameter 'p1' in 'void C.M6(CL1 p1, CL1? p2)'. // M6(p2: x8, p1: y8); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y8").WithArguments("p1", "void C.M6(CL1 p1, CL1? p2)").WithLocation(65, 24), // (72,16): warning CS8604: Possible null reference argument for parameter 'p1' in 'void C.M7(params CL1[] p1)'. // M7(x9, y9); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y9").WithArguments("p1", "void C.M7(params CL1[] p1)").WithLocation(72, 16), // (77,12): warning CS8604: Possible null reference argument for parameter 'p1' in 'void C.M7(params CL1[] p1)'. // M7(x10, y10); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x10").WithArguments("p1", "void C.M7(params CL1[] p1)").WithLocation(77, 12), // (84,12): warning CS8604: Possible null reference argument for parameter 'p1' in 'void C.M8(CL1 p1, params CL1[] p2)'. // M8(x11, y11, z11); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x11").WithArguments("p1", "void C.M8(CL1 p1, params CL1[] p2)").WithLocation(84, 12), // (84,22): warning CS8604: Possible null reference argument for parameter 'p2' in 'void C.M8(CL1 p1, params CL1[] p2)'. // M8(x11, y11, z11); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "z11").WithArguments("p2", "void C.M8(CL1 p1, params CL1[] p2)").WithLocation(84, 22), // (89,16): warning CS8604: Possible null reference argument for parameter 'p2' in 'void C.M8(CL1 p1, params CL1[] p2)'. // M8(p2: x12, p1: y12); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x12").WithArguments("p2", "void C.M8(CL1 p1, params CL1[] p2)").WithLocation(89, 16) ); } [Fact] public void PassingParameters_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0 x1) { var y1 = new CL0() { [null] = x1 }; } } class CL0 { public CL0 this[CL0 x] { get { return x; } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // var y1 = new CL0() { [null] = x1 }; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 31)); } [Fact] public void PassingParameters_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0 x1) { var y1 = new CL0() { null }; } } class CL0 : System.Collections.IEnumerable { public void Add(CL0 x) { } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw new System.NotImplementedException(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,30): warning CS8625: Cannot convert null literal to non-nullable reference type. // var y1 = new CL0() { null }; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 30)); } [Fact] public void PassingParameters_04() { var source = @"interface I<T> { } class C { static void F(I<object> x, I<object?> y, I<object>? z, I<object?>? w, I<object?>[]? a) { G(x); G(y); // 1 G(x, x, x); // 2, 3 G(x, y, y); G(x, x, y, z, w); // 4, 5, 6, 7 G(y: x, x: y); // 8, 9 G(y: y, x: x); G(x, a); // 10 G(x, new I<object?>[0]); G(x, new[] { x, x }); // 11 G(x, new[] { y, y }); // note that the array type below is reinferred to 'I<object>[]' // due to previous usage of the variables as call arguments. G(x, new[] { x, y, z }); // 12, 13 G(y: new[] { x, x }, x: y); // 14, 15 G(y: new[] { y, y }, x: x); } static void G(I<object> x, params I<object?>[] y) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,11): warning CS8620: Argument of type 'I<object?>' cannot be used for parameter 'x' of type 'I<object>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object?>", "I<object>", "x", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(7, 11), // (8,14): warning CS8620: Argument of type 'I<object>' cannot be used for parameter 'y' of type 'I<object?>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(x, x, x); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(8, 14), // (8,17): warning CS8620: Argument of type 'I<object>' cannot be used for parameter 'y' of type 'I<object?>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(x, x, x); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(8, 17), // (10,14): warning CS8620: Argument of type 'I<object>' cannot be used for parameter 'y' of type 'I<object?>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(x, x, y, z, w); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(10, 14), // (10,20): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.G(I<object> x, params I<object?>[] y)'. // G(x, x, y, z, w); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "z").WithArguments("y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(10, 20), // (10,20): warning CS8620: Argument of type 'I<object>' cannot be used for parameter 'y' of type 'I<object?>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(x, x, y, z, w); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("I<object>", "I<object?>", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(10, 20), // (10,23): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.G(I<object> x, params I<object?>[] y)'. // G(x, x, y, z, w); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "w").WithArguments("y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(10, 23), // (11,14): warning CS8620: Argument of type 'I<object>' cannot be used for parameter 'y' of type 'I<object?>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(y: x, x: y); // 8, 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(11, 14), // (11,20): warning CS8620: Argument of type 'I<object?>' cannot be used for parameter 'x' of type 'I<object>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(y: x, x: y); // 8, 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object?>", "I<object>", "x", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(11, 20), // (13,14): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.G(I<object> x, params I<object?>[] y)'. // G(x, a); // 10 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(13, 14), // (15,14): warning CS8620: Argument of type 'I<object>[]' cannot be used for parameter 'y' of type 'I<object?>[]' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(x, new[] { x, x }); // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new[] { x, x }").WithArguments("I<object>[]", "I<object?>[]", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(15, 14), // (19,14): warning CS8620: Argument of type 'I<object>[]' cannot be used for parameter 'y' of type 'I<object?>[]' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(x, new[] { x, y, z }); // 12, 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new[] { x, y, z }").WithArguments("I<object>[]", "I<object?>[]", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(19, 14), // (19,25): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // G(x, new[] { x, y, z }); // 12, 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(19, 25), // (20,14): warning CS8620: Argument of type 'I<object>[]' cannot be used for parameter 'y' of type 'I<object?>[]' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(y: new[] { x, x }, x: y); // 14, 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new[] { x, x }").WithArguments("I<object>[]", "I<object?>[]", "y", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(20, 14), // (20,33): warning CS8620: Argument of type 'I<object?>' cannot be used for parameter 'x' of type 'I<object>' in 'void C.G(I<object> x, params I<object?>[] y)' due to differences in the nullability of reference types. // G(y: new[] { x, x }, x: y); // 14, 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object?>", "I<object>", "x", "void C.G(I<object> x, params I<object?>[] y)").WithLocation(20, 33) ); } [Fact] public void PassingParameters_DifferentRefKinds() { var source = @" class C { void M(string xNone, ref string xRef, out string xOut) { xNone = null; xRef = null; xOut = null; } } "; var c = CreateCompilation(new[] { source }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // xNone = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 17), // (7,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // xRef = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 16), // (8,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // xOut = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 16) ); var source2 = @" class C { void M(in string xIn) { xIn = null; } } "; var c2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable()); c2.VerifyDiagnostics( // (6,9): error CS8331: Cannot assign to variable 'in string' because it is a readonly variable // xIn = null; Diagnostic(ErrorCode.ERR_AssignReadonlyNotField, "xIn").WithArguments("variable", "in string").WithLocation(6, 9)); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void PassingParameters_UnknownMethod() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static int F(object x) { Missing(F(null)); // 1 Missing(F(x = null)); // 2 x.ToString(); Missing(F(x = this)); // 3 x.ToString(); return 0; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,9): error CS0103: The name 'Missing' does not exist in the current context // Missing(F(null)); // 1 Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(6, 9), // (6,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // Missing(F(null)); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 19), // (7,9): error CS0103: The name 'Missing' does not exist in the current context // Missing(F(x = null)); // 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(7, 9), // (7,19): warning CS8604: Possible null reference argument for parameter 'x' in 'int C.F(object x)'. // Missing(F(x = null)); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x = null").WithArguments("x", "int C.F(object x)").WithLocation(7, 19), // (7,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Missing(F(x = null)); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 23), // (10,9): error CS0103: The name 'Missing' does not exist in the current context // Missing(F(x = this)); // 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(10, 9), // (10,23): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // Missing(F(x = this)); // 3 Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this").WithLocation(10, 23) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void PassingParameters_UnknownMethod_UnknownReceiver() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static int F(object x) { bad.Missing(F(null)); // 1 bad.Missing(F(x = null)); // 2 x.ToString(); bad.Missing(F(x = this)); // 3 x.ToString(); return 0; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,9): error CS0103: The name 'bad' does not exist in the current context // bad.Missing(F(null)); // 1 Diagnostic(ErrorCode.ERR_NameNotInContext, "bad").WithArguments("bad").WithLocation(6, 9), // (6,23): warning CS8625: Cannot convert null literal to non-nullable reference type. // bad.Missing(F(null)); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 23), // (7,9): error CS0103: The name 'bad' does not exist in the current context // bad.Missing(F(x = null)); // 2 Diagnostic(ErrorCode.ERR_NameNotInContext, "bad").WithArguments("bad").WithLocation(7, 9), // (7,23): warning CS8604: Possible null reference argument for parameter 'x' in 'int C.F(object x)'. // bad.Missing(F(x = null)); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x = null").WithArguments("x", "int C.F(object x)").WithLocation(7, 23), // (7,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // bad.Missing(F(x = null)); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 27), // (10,9): error CS0103: The name 'bad' does not exist in the current context // bad.Missing(F(x = this)); // 3 Diagnostic(ErrorCode.ERR_NameNotInContext, "bad").WithArguments("bad").WithLocation(10, 9), // (10,27): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // bad.Missing(F(x = this)); // 3 Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this").WithLocation(10, 27) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void PassingParameters_UnknownMethod_AffectingState() { CSharpCompilation c = CreateCompilation(new[] { @" class C { object F(object x) { Missing( F(x = null) /*warn*/, x.ToString(), F(x = this), x.ToString()); return x; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,9): error CS0103: The name 'Missing' does not exist in the current context // Missing( Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(6, 9), // (7,15): warning CS8604: Possible null reference argument for parameter 'x' in 'object C.F(object x)'. // F(x = null) /*warn*/, Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x = null").WithArguments("x", "object C.F(object x)").WithLocation(7, 15), // (7,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(x = null) /*warn*/, Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 19) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void PassingParameters_UnknownMethod_AffectingConditionalState() { CSharpCompilation c = CreateCompilation(new[] { @" class C { int F(object x) { if (G(F(x = null))) { x.ToString(); } else { x.ToString(); } return 0; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,13): error CS0103: The name 'G' does not exist in the current context // if (G(F(x = null))) Diagnostic(ErrorCode.ERR_NameNotInContext, "G").WithArguments("G").WithLocation(6, 13), // (6,17): warning CS8604: Possible null reference argument for parameter 'x' in 'int C.F(object x)'. // if (G(F(x = null))) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x = null").WithArguments("x", "int C.F(object x)").WithLocation(6, 17), // (6,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (G(F(x = null))) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 21) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void PassingParameters_UnknownMethod_AffectingConditionalState2() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void F(object x) { if (Missing(x) && Missing(x = null)) { x.ToString(); // 1 } else { x.ToString(); // 2 } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,13): error CS0103: The name 'Missing' does not exist in the current context // if (Missing(x) && Missing(x = null)) Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(6, 13), // (6,27): error CS0103: The name 'Missing' does not exist in the current context // if (Missing(x) && Missing(x = null)) Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(6, 27), // (6,39): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (Missing(x) && Missing(x = null)) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 39), // (8,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 13) ); } [Fact] public void DuplicateArguments() { var source = @"class C { static void F(object x, object? y) { // Duplicate x G(x: x, x: y); G(x: y, x: x); G(x: x, x: y, y: y); G(x: y, x: x, y: y); G(y: y, x: x, x: y); G(y: y, x: y, x: x); // Duplicate y G(y: x, y: y); G(y: y, y: x); G(x, y: x, y: y); G(x, y: y, y: x); G(y: x, y: y, x: x); G(y: y, y: x, x: x); } static void G(object x, params object?[] y) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,17): error CS1740: Named argument 'x' cannot be specified multiple times // G(x: x, x: y); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(6, 17), // (7,17): error CS1740: Named argument 'x' cannot be specified multiple times // G(x: y, x: x); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(7, 17), // (8,17): error CS1740: Named argument 'x' cannot be specified multiple times // G(x: x, x: y, y: y); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(8, 17), // (9,17): error CS1740: Named argument 'x' cannot be specified multiple times // G(x: y, x: x, y: y); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(9, 17), // (10,23): error CS1740: Named argument 'x' cannot be specified multiple times // G(y: y, x: x, x: y); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(10, 23), // (11,23): error CS1740: Named argument 'x' cannot be specified multiple times // G(y: y, x: y, x: x); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "x").WithArguments("x").WithLocation(11, 23), // (13,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.G(object, params object?[])' // G(y: x, y: y); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "G").WithArguments("x", "C.G(object, params object?[])").WithLocation(13, 9), // (14,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.G(object, params object?[])' // G(y: y, y: x); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "G").WithArguments("x", "C.G(object, params object?[])").WithLocation(14, 9), // (15,20): error CS1740: Named argument 'y' cannot be specified multiple times // G(x, y: x, y: y); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "y").WithArguments("y").WithLocation(15, 20), // (16,20): error CS1740: Named argument 'y' cannot be specified multiple times // G(x, y: y, y: x); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "y").WithArguments("y").WithLocation(16, 20), // (17,17): error CS1740: Named argument 'y' cannot be specified multiple times // G(y: x, y: y, x: x); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "y").WithArguments("y").WithLocation(17, 17), // (18,17): error CS1740: Named argument 'y' cannot be specified multiple times // G(y: y, y: x, x: x); Diagnostic(ErrorCode.ERR_DuplicateNamedArgument, "y").WithArguments("y").WithLocation(18, 17)); } [Fact] public void MissingArguments() { var source = @"class C { static void F(object? x) { G(y: x); } static void G(object? x = null, object y) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,45): error CS1737: Optional parameters must appear after all required parameters // static void G(object? x = null, object y) Diagnostic(ErrorCode.ERR_DefaultValueBeforeRequiredValue, ")").WithLocation(7, 45), // (5,14): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.G(object? x = null, object y)'. // G(y: x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("y", "void C.G(object? x = null, object y)").WithLocation(5, 14)); } [Fact] public void ParamsArgument_NotLast() { var source = @"class C { static void F(object[]? a, object? b) { G(a, b, a); } static void G(params object[] x, params object[] y) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,19): error CS0231: A params parameter must be the last parameter in a formal parameter list // static void G(params object[] x, params object[] y) Diagnostic(ErrorCode.ERR_ParamsLast, "params object[] x").WithLocation(7, 19), // (5,11): warning CS8604: Possible null reference argument for parameter 'x' in 'void C.G(params object[] x, params object[] y)'. // G(a, b, a); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("x", "void C.G(params object[] x, params object[] y)").WithLocation(5, 11), // (5,14): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.G(params object[] x, params object[] y)'. // G(a, b, a); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b").WithArguments("y", "void C.G(params object[] x, params object[] y)").WithLocation(5, 14), // (5,17): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.G(params object[] x, params object[] y)'. // G(a, b, a); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("y", "void C.G(params object[] x, params object[] y)").WithLocation(5, 17)); } [Fact] public void ParamsArgument_NotArray() { var source = @"class C { static void F1(bool b, object x, object? y) { if (b) F2(y); if (b) F2(x, y); if (b) F3(y, x); if (b) F3(x, y, x); } static void F2(params object x) { } static void F3(params object x, params object[] y) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,20): error CS0225: The params parameter must be a single dimensional array // static void F2(params object x) Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(10, 20), // (13,20): error CS0225: The params parameter must be a single dimensional array // static void F3(params object x, params object[] y) Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(13, 20), // (13,20): error CS0231: A params parameter must be the last parameter in a formal parameter list // static void F3(params object x, params object[] y) Diagnostic(ErrorCode.ERR_ParamsLast, "params object x").WithLocation(13, 20), // (6,16): error CS1501: No overload for method 'F2' takes 2 arguments // if (b) F2(x, y); Diagnostic(ErrorCode.ERR_BadArgCount, "F2").WithArguments("F2", "2").WithLocation(6, 16), // (5,19): warning CS8604: Possible null reference argument for parameter 'x' in 'void C.F2(params object x)'. // if (b) F2(y); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void C.F2(params object x)").WithLocation(5, 19), // (7,19): warning CS8604: Possible null reference argument for parameter 'x' in 'void C.F3(params object x, params object[] y)'. // if (b) F3(y, x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void C.F3(params object x, params object[] y)").WithLocation(7, 19), // (8,22): warning CS8604: Possible null reference argument for parameter 'y' in 'void C.F3(params object x, params object[] y)'. // if (b) F3(x, y, x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("y", "void C.F3(params object x, params object[] y)").WithLocation(8, 22)); } [Fact] public void ParamsArgument_BinaryOperator() { var source = @"class C { public static object operator+(C x, params object?[] y) => x; static object F(C x, object[] y) => x + y; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,41): error CS1670: params is not valid in this context // public static object operator+(C x, params object?[] y) => x; Diagnostic(ErrorCode.ERR_IllegalParams, "params").WithLocation(3, 41)); } [Fact] public void RefOutParameters_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(ref CL1 x1, CL1 y1) { y1 = x1; } void Test2(ref CL1? x2, CL1 y2) { y2 = x2; } void Test3(ref CL1? x3, CL1 y3) { x3 = y3; y3 = x3; } void Test4(out CL1 x4, CL1 y4) { y4 = x4; x4 = y4; } void Test5(out CL1? x5, CL1 y5) { y5 = x5; x5 = y5; } void Test6(out CL1? x6, CL1 y6) { x6 = y6; y6 = x6; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y2 = x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(15, 14), // (26,14): error CS0269: Use of unassigned out parameter 'x4' // y4 = x4; Diagnostic(ErrorCode.ERR_UseDefViolationOut, "x4").WithArguments("x4").WithLocation(26, 14), // (32,14): error CS0269: Use of unassigned out parameter 'x5' // y5 = x5; Diagnostic(ErrorCode.ERR_UseDefViolationOut, "x5").WithArguments("x5").WithLocation(32, 14), // (32,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y5 = x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5").WithLocation(32, 14)); } [Fact] public void RefOutParameters_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(ref S1 x1, CL1 y1) { y1 = x1.F1; } void Test2(ref S1 x2, CL1 y2) { y2 = x2.F2; } void Test3(ref S1 x3, CL1 y3) { x3.F2 = y3; y3 = x3.F2; } void Test4(out S1 x4, CL1 y4) { y4 = x4.F1; x4.F1 = y4; x4.F2 = y4; } void Test5(out S1 x5, CL1 y5) { y5 = x5.F2; x5.F1 = y5; x5.F2 = y5; } void Test6(out S1 x6, CL1 y6) { x6.F1 = y6; x6.F2 = y6; y6 = x6.F2; } } class CL1 { } struct S1 { public CL1 F1; public CL1? F2; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y2 = x2.F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2.F2").WithLocation(15, 14), // (26,14): error CS0170: Use of possibly unassigned field 'F1' // y4 = x4.F1; Diagnostic(ErrorCode.ERR_UseDefViolationField, "x4.F1").WithArguments("F1").WithLocation(26, 14), // (33,14): error CS0170: Use of possibly unassigned field 'F2' // y5 = x5.F2; Diagnostic(ErrorCode.ERR_UseDefViolationField, "x5.F2").WithArguments("F2").WithLocation(33, 14), // (33,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y5 = x5.F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5.F2").WithLocation(33, 14), // (34,17): warning CS8601: Possible null reference assignment. // x5.F1 = y5; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y5").WithLocation(34, 17)); } [Fact] public void RefOutParameters_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test3(ref S1 x3, CL1 y3) { S1 z3; z3.F1 = y3; z3.F2 = y3; x3 = z3; y3 = x3.F2; } void Test6(out S1 x6, CL1 y6) { S1 z6; z6.F1 = y6; z6.F2 = y6; x6 = z6; y6 = x6.F2; } } class CL1 { } struct S1 { public CL1 F1; public CL1? F2; } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void RefOutParameters_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void M1(ref CL0<string> x) {} void Test1(CL0<string?> x1) { M1(ref x1); } void M2(out CL0<string?> x) { throw new System.NotImplementedException(); } void Test2(CL0<string> x2) { M2(out x2); } void M3(CL0<string> x) {} void Test3(CL0<string?> x3) { M3(x3); } } class CL0<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,16): warning CS8620: Argument of type 'CL0<string?>' cannot be used as an input of type 'CL0<string>' for parameter 'x' in 'void C.M1(ref CL0<string> x)' due to differences in the nullability of reference types. // M1(ref x1); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1").WithArguments("CL0<string?>", "CL0<string>", "x", "void C.M1(ref CL0<string> x)").WithLocation(12, 16), // (19,16): warning CS8624: Argument of type 'CL0<string>' cannot be used as an output of type 'CL0<string?>' for parameter 'x' in 'void C.M2(out CL0<string?> x)' due to differences in the nullability of reference types. // M2(out x2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "x2").WithArguments("CL0<string>", "CL0<string?>", "x", "void C.M2(out CL0<string?> x)").WithLocation(19, 16), // (26,12): warning CS8620: Argument of type 'CL0<string?>' cannot be used as an input of type 'CL0<string>' for parameter 'x' in 'void C.M3(CL0<string> x)' due to differences in the nullability of reference types. // M3(x3); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x3").WithArguments("CL0<string?>", "CL0<string>", "x", "void C.M3(CL0<string> x)").WithLocation(26, 12)); } [Fact] public void RefOutParameters_05() { var source = @"class C { static void F(object? x, object? y, object? z) { G(out x, ref y, in z); x.ToString(); y.ToString(); z.ToString(); } static void G(out object x, ref object y, in object z) { x = new object(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,22): warning CS8601: Possible null reference assignment. // G(out x, ref y, in z); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(5, 22), // (5,28): warning CS8604: Possible null reference argument for parameter 'z' in 'void C.G(out object x, ref object y, in object z)'. // G(out x, ref y, in z); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "z").WithArguments("z", "void C.G(out object x, ref object y, in object z)").WithLocation(5, 28) ); } [Fact] public void RefOutParameters_06() { var source = @"class C { static void F(object x, object y, object z) { G(out x, ref y, in z); x.ToString(); y.ToString(); z.ToString(); } static void G(out object? x, ref object? y, in object? z) { x = new object(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // G(out x, ref y, in z); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(5, 15), // (5,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // G(out x, ref y, in z); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(5, 22), // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9)); } [Fact] public void TargetingUnannotatedAPIs_01() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public object F1; public object P1 { get; set;} public object this[object x] { get { return null; } set { } } public S1 M1() { return new S1(); } } public struct S1 { public CL0 F1; } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } bool Test1(string? x1, string y1) { return string.Equals(x1, y1); } object Test2(ref object? x2, object? y2) { System.Threading.Interlocked.Exchange(ref x2, y2); return x2 ?? new object(); } object Test3(ref object? x3, object? y3) { return System.Threading.Interlocked.Exchange(ref x3, y3) ?? new object(); } object Test4(System.Delegate x4) { return x4.Target ?? new object(); } object Test5(CL0 x5) { return x5.F1 ?? new object(); } void Test6(CL0 x6, object? y6) { x6.F1 = y6; } void Test7(CL0 x7, object? y7) { x7.P1 = y7; } void Test8(CL0 x8, object? y8, object? z8) { x8[y8] = z8; } object Test9(CL0 x9) { return x9[1] ?? new object(); } object Test10(CL0 x10) { return x10.M1().F1 ?? new object(); } object Test11(CL0 x11, CL0? z11) { S1 y11 = x11.M1(); y11.F1 = z11; return y11.F1; } object Test12(CL0 x12) { S1 y12 = x12.M1(); y12.F1 = x12; return y12.F1 ?? new object(); } void Test13(CL0 x13, object? y13) { y13 = x13.F1; object z13 = y13; z13 = y13 ?? new object(); } void Test14(CL0 x14) { object? y14 = x14.F1; object z14 = y14; z14 = y14 ?? new object(); } void Test15(CL0 x15) { S2 y15; y15.F2 = x15.F1; object z15 = y15.F2; z15 = y15.F2 ?? new object(); } struct Test16 { object? y16 {get;} public Test16(CL0 x16) { y16 = x16.F1; object z16 = y16; z16 = y16 ?? new object(); } } void Test17(CL0 x17) { var y17 = new { F2 = x17.F1 }; object z17 = y17.F2; z17 = y17.F2 ?? new object(); } } public struct S2 { public object? F2; } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( // (63,16): warning CS8603: Possible null reference return. // return y11.F1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y11.F1").WithLocation(63, 16)); } [Fact] public void TargetingUnannotatedAPIs_02() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public static object M1() { return new object(); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } public static object? M2() { return null; } public static object M3() { return new object(); } void Test1() { object? x1 = CL0.M1() ?? M2(); object y1 = x1; object z1 = x1 ?? new object(); } void Test2() { object? x2 = CL0.M1() ?? M3(); object z2 = x2 ?? new object(); } void Test3() { object? x3 = M3() ?? M2(); object z3 = x3 ?? new object(); } void Test4() { object? x4 = CL0.M1() ?? CL0.M1(); object y4 = x4; object z4 = x4 ?? new object(); } void Test5() { object x5 = M2() ?? M2(); } void Test6() { object? x6 = M3() ?? M3(); object z6 = x6 ?? new object(); } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( // (14,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y1 = x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(14, 21), // (39,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x5 = M2() ?? M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M2() ?? M2()").WithLocation(39, 21)); } [Fact] public void TargetingUnannotatedAPIs_03() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public static object M1() { return new object(); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } public static object? M2() { return null; } public static object M3() { return new object(); } void Test1() { object? x1 = M2() ?? CL0.M1(); object y1 = x1; object z1 = x1 ?? new object(); } void Test2() { object? x2 = M3() ?? CL0.M1(); object z2 = x2 ?? new object(); } void Test3() { object? x3 = M2() ?? M3(); object z3 = x3 ?? new object(); } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( ); } [Fact] public void TargetingUnannotatedAPIs_04() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public static object M1() { return new object(); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } public static object? M2() { return null; } public static object M3() { return new object(); } public static bool M4() {return false;} void Test1() { object x1 = M4() ? CL0.M1() : M2(); } void Test2() { object? x2 = M4() ? CL0.M1() : M3(); object y2 = x2; object z2 = x2 ?? new object(); } void Test3() { object x3 = M4() ? M3() : M2(); } void Test4() { object? x4 = M4() ? CL0.M1() : CL0.M1(); object y4 = x4; object z4 = x4 ?? new object(); } void Test5() { object x5 = M4() ? M2() : M2(); } void Test6() { object? x6 = M4() ? M3() : M3(); object z6 = x6 ?? new object(); } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( // (14,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x1 = M4() ? CL0.M1() : M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M4() ? CL0.M1() : M2()").WithLocation(14, 21), // (26,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x3 = M4() ? M3() : M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M4() ? M3() : M2()").WithLocation(26, 22), // (38,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x5 = M4() ? M2() : M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M4() ? M2() : M2()").WithLocation(38, 22) ); } [Fact] public void TargetingUnannotatedAPIs_05() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public static object M1() { return new object(); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } public static object? M2() { return null; } public static object M3() { return new object(); } public static bool M4() {return false;} void Test1() { object x1 = M4() ? M2() : CL0.M1(); } void Test2() { object? x2 = M4() ? M3() : CL0.M1(); object y2 = x2; object z2 = x2 ?? new object(); } void Test3() { object x3 = M4() ? M2() : M3(); } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( // (14,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x1 = M4() ? M2() : CL0.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M4() ? M2() : CL0.M1()").WithLocation(14, 21), // (26,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x3 = M4() ? M2() : M3(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M4() ? M2() : M3()").WithLocation(26, 22) ); } [Fact] public void TargetingUnannotatedAPIs_06() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public static object M1() { return new object(); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } public static object? M2() { return null; } public static object M3() { return new object(); } public static bool M4() {return false;} void Test1() { object? x1; if (M4()) x1 = CL0.M1(); else x1 = M2(); object y1 = x1; } void Test2() { object? x2; if (M4()) x2 = CL0.M1(); else x2 = M3(); object y2 = x2; object z2 = x2 ?? new object(); } void Test3() { object? x3; if (M4()) x3 = M3(); else x3 = M2(); object y3 = x3; } void Test4() { object? x4; if (M4()) x4 = CL0.M1(); else x4 = CL0.M1(); object y4 = x4; object z4 = x4 ?? new object(); } void Test5() { object? x5; if (M4()) x5 = M2(); else x5 = M2(); object y5 = x5; } void Test6() { object? x6; if (M4()) x6 = M3(); else x6 = M3(); object z6 = x6 ?? new object(); } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( // (16,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y1 = x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(16, 21), // (31,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(31, 21), // (46,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y5 = x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5").WithLocation(46, 21) ); } [Fact] public void TargetingUnannotatedAPIs_07() { CSharpCompilation c0 = CreateCompilation(@" public class CL0 { public static object M1() { return new object(); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } public static object? M2() { return null; } public static object M3() { return new object(); } public static bool M4() {return false;} void Test1() { object? x1; if (M4()) x1 = M2(); else x1 = CL0.M1(); object y1 = x1; } void Test2() { object? x2; if (M4()) x2 = M3(); else x2 = CL0.M1(); object y2 = x2; object z2 = x2 ?? new object(); } void Test3() { object? x3; if (M4()) x3 = M2(); else x3 = M3(); object y3 = x3; } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics( // (16,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y1 = x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(16, 21), // (31,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(31, 21) ); } [Fact] public void TargetingUnannotatedAPIs_08() { CSharpCompilation c0 = CreateCompilation(@" public abstract class A1 { public abstract event System.Action E1; public abstract string P2 { get; set; } public abstract string M3(string x); public abstract event System.Action E4; public abstract string this[string x] { get; set; } } public interface IA2 { event System.Action E5; string P6 { get; set; } string M7(string x); event System.Action E8; string this[string x] { get; set; } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class B1 : A1 { static void Main() { } public override string? P2 { get; set; } public override event System.Action? E1; public override string? M3(string? x) { var dummy = E1; throw new System.NotImplementedException(); } public override event System.Action? E4 { add { } remove { } } public override string? this[string? x] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } } class B2 : IA2 { public string? P6 { get; set; } public event System.Action? E5; public event System.Action? E8 { add { } remove { } } public string? M7(string? x) { var dummy = E5; throw new System.NotImplementedException(); } public string? this[string? x] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } } class B3 : IA2 { string? IA2.P6 { get; set; } event System.Action? IA2.E5 { add { } remove { } } event System.Action? IA2.E8 { add { } remove { } } string? IA2.M7(string? x) { throw new System.NotImplementedException(); } string? IA2.this[string? x] { get { throw new System.NotImplementedException(); } set { throw new System.NotImplementedException(); } } } " }, options: WithNullableEnable(), references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics(); } [Fact] public void ReturningValues_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1 Test1(CL1? x1) { return x1; } CL1? Test2(CL1? x2) { return x2; } CL1? Test3(CL1 x3) { return x3; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,16): warning CS8603: Possible null reference return. // return x1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x1").WithLocation(10, 16) ); } [Fact] public void ReturningValues_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1<string?> Test1(CL1<string> x1) { return x1; } CL1<string> Test2(CL1<string?> x2) { return x2; } } class CL1<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,16): warning CS8619: Nullability of reference types in value of type 'CL1<string>' doesn't match target type 'CL1<string?>'. // return x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("CL1<string>", "CL1<string?>").WithLocation(10, 16), // (15,16): warning CS8619: Nullability of reference types in value of type 'CL1<string?>' doesn't match target type 'CL1<string>'. // return x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("CL1<string?>", "CL1<string>").WithLocation(15, 16) ); } [Fact] public void ReturningValues_BadValue() { CSharpCompilation c = CreateCompilation(new[] { @" class C { string M() { return bad; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,16): error CS0103: The name 'bad' does not exist in the current context // return bad; Diagnostic(ErrorCode.ERR_NameNotInContext, "bad").WithArguments("bad").WithLocation(6, 16) ); } [Fact] public void IdentityConversion_Return_01() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static I<object?> F(I<object> x) => x; static IIn<object?> F(IIn<object> x) => x; static IOut<object?> F(IOut<object> x) => x; static I<object> G(I<object?> x) => x; static IIn<object> G(IIn<object?> x) => x; static IOut<object> G(IOut<object?> x) => x; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,41): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // static I<object?> F(I<object> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object>", "I<object?>").WithLocation(6, 41), // (7,45): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // static IIn<object?> F(IIn<object> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object>", "IIn<object?>").WithLocation(7, 45), // (9,41): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // static I<object> G(I<object?> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object?>", "I<object>").WithLocation(9, 41), // (11,47): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // static IOut<object> G(IOut<object?> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IOut<object?>", "IOut<object>").WithLocation(11, 47)); } [Fact] public void IdentityConversion_Return_02() { var source = @"#pragma warning disable 1998 using System.Threading.Tasks; interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static async Task<I<object?>> F(I<object> x) => x; static async Task<IIn<object?>> F(IIn<object> x) => x; static async Task<IOut<object?>> F(IOut<object> x) => x; static async Task<I<object>> G(I<object?> x) => x; static async Task<IIn<object>> G(IIn<object?> x) => x; static async Task<IOut<object>> G(IOut<object?> x) => x; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,53): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // static async Task<I<object?>> F(I<object> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object>", "I<object?>").WithLocation(8, 53), // (9,57): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // static async Task<IIn<object?>> F(IIn<object> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object>", "IIn<object?>").WithLocation(9, 57), // (11,53): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // static async Task<I<object>> G(I<object?> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object?>", "I<object>").WithLocation(11, 53), // (13,59): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // static async Task<IOut<object>> G(IOut<object?> x) => x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IOut<object?>", "IOut<object>").WithLocation(13, 59)); } [Fact] public void MakeMethodKeyForWhereMethod() { // this test verifies that a bad method symbol doesn't crash when generating a key for external annotations CSharpCompilation c = CreateCompilation(new[] { @" class Test { public void SimpleWhere() { int[] numbers = { 1, 2, 3 }; var lowNums = from n in numbers where n < 5 select n; } }" }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,33): error CS1935: Could not find an implementation of the query pattern for source type 'int[]'. 'Where' not found. Are you missing required assembly references or a using directive for 'System.Linq'? // var lowNums = from n in numbers Diagnostic(ErrorCode.ERR_QueryNoProviderStandard, "numbers").WithArguments("int[]", "Where").WithLocation(7, 33) ); } [Fact] public void MemberNotNull_Simple() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { Init(); field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } [MemberNotNull(nameof(field1), nameof(field2))] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_NullValue() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { Init(); field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 } [MemberNotNull(null!, null!)] [MemberNotNull(members: null!)] [MemberNotNull(member: null!)] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_LocalFunction() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { init(); field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 [MemberNotNull(nameof(field1), nameof(field2))] void init() => throw null!; } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); // Note: the local function is not invoked on this or base c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_Interfaces() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public interface I { string Property1 { get; } string? Property2 { get; } string Property3 { get; } string? Property4 { get; } [MemberNotNull(nameof(Property1), nameof(Property2))] // Note: attribute ineffective void Init(); } public class C : I { public string Property1 { get; set; } public string? Property2 { get; set; } public string Property3 { get; set; } public string? Property4 { get; set; } public void M() { Init(); Property1.ToString(); Property2.ToString(); // 1 Property3.ToString(); Property4.ToString(); // 2 } public void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,19): warning CS8618: Non-nullable property 'Property1' is uninitialized. Consider declaring the property as nullable. // public string Property1 { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Property1").WithArguments("property", "Property1").WithLocation(15, 19), // (17,19): warning CS8618: Non-nullable property 'Property3' is uninitialized. Consider declaring the property as nullable. // public string Property3 { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Property3").WithArguments("property", "Property3").WithLocation(17, 19), // (24,9): warning CS8602: Dereference of a possibly null reference. // Property2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Property2").WithLocation(24, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // Property4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Property4").WithLocation(26, 9) ); } [Fact] public void MemberNotNull_Inheritance() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field0), nameof(field1), nameof(field2))] public virtual void Init() => throw null!; } public class Derived : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override void Init() { field5 = """"; field6 = """"; } // 1, 2, 3 Derived() { Init(); field0.ToString(); // 4 field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 5 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 6 } } public class Derived2 : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override void Init() { base.Init(); field5 = """"; field6 = """"; } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (27,5): warning CS8771: Member 'field0' must have a non-null value when exiting. // } // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field0").WithLocation(27, 5), // (27,5): warning CS8771: Member 'field1' must have a non-null value when exiting. // } // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(27, 5), // (27,5): warning CS8771: Member 'field2' must have a non-null value when exiting. // } // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(27, 5), // (32,9): warning CS8602: Dereference of a possibly null reference. // field0.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field0").WithLocation(32, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(36, 9), // (40,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(40, 9) ); } [Fact] public void MemberNotNull_OnInstance() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; [MemberNotNull(nameof(field1), nameof(field2))] public virtual void Init() => throw null!; } public class Derived : Base { public new string? field0; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field0), nameof(field3), nameof(field4))] public override void Init() => throw null!; } public class C { void M(Derived d, Derived d2) { d.field0.ToString(); // 1 d.field1.ToString(); d.field2.ToString(); // 2 d.field3.ToString(); d.field4.ToString(); // 3 d2.Init(); d2.field0.ToString(); d2.field1.ToString(); d2.field2.ToString(); d2.field3.ToString(); d2.field4.ToString(); } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (25,9): warning CS8602: Dereference of a possibly null reference. // d.field0.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field0").WithLocation(25, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // d.field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field2").WithLocation(27, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // d.field4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field4").WithLocation(29, 9) ); } [Fact] public void MemberNotNull_Property_OnInstance() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; [MemberNotNull(nameof(field1), nameof(field2))] public virtual int Init => throw null!; } public class Derived : Base { public new string? field0; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field0), nameof(field3), nameof(field4))] public override int Init => throw null!; } public class C { void M(Derived d, Derived d2) { d.field0.ToString(); // 1 d.field1.ToString(); d.field2.ToString(); // 2 d.field3.ToString(); d.field4.ToString(); // 3 _ = d2.Init; d2.field0.ToString(); d2.field1.ToString(); d2.field2.ToString(); d2.field3.ToString(); d2.field4.ToString(); } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (25,9): warning CS8602: Dereference of a possibly null reference. // d.field0.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field0").WithLocation(25, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // d.field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field2").WithLocation(27, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // d.field4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field4").WithLocation(29, 9) ); } [Fact] public void MemberNotNull_OnMethodWithConditionalAttribute() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1 = null!; public string? field2; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field1), nameof(field2))] public bool Init([NotNullWhen(true)] string p) // NotNullWhen splits the state before we analyze MemberNotNull { field1 = """"; field2 = """"; return false; } C() { if (Init("""")) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 1 } else { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 2 } } } ", MemberNotNullAttributeDefinition, NotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (25,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(25, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(32, 13) ); } [Fact] public void MemberNotNull_Inheritance_PE() { var libComp = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; public string? field2b; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field0))] [MemberNotNull(nameof(field1), nameof(field2))] [MemberNotNull(nameof(field2b))] public virtual void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); var c = CreateNullableCompilation(@" using System.Diagnostics.CodeAnalysis; public class Derived : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override void Init() { field5 = """"; field6 = """"; } // 1, 2, 3, 4 Derived() { Init(); field0.ToString(); // 5 field1.ToString(); field2.ToString(); field2b.ToString(); field3.ToString(); field4.ToString(); // 6 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 7 } } public class Derived2 : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override void Init() { base.Init(); field5 = """"; field6 = """"; } } ", references: new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,5): warning CS8774: Member 'field1' must have a non-null value when exiting. // } // 1, 2, 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(16, 5), // (16,5): warning CS8774: Member 'field2' must have a non-null value when exiting. // } // 1, 2, 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(16, 5), // (16,5): warning CS8774: Member 'field0' must have a non-null value when exiting. // } // 1, 2, 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field0").WithLocation(16, 5), // (16,5): warning CS8774: Member 'field2b' must have a non-null value when exiting. // } // 1, 2, 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2b").WithLocation(16, 5), // (21,9): warning CS8602: Dereference of a possibly null reference. // field0.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field0").WithLocation(21, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(26, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(30, 9) ); } [Fact] public void MemberNotNull_Inheritance_Property() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field0), nameof(field1), nameof(field2))] public virtual int Init { get => throw null!; set => throw null!; } } public class Derived : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override int Init { get { field5 = """"; field6 = """"; return 0; // 1, 2, 3 } set { field5 = """"; field6 = """"; } // 4, 5, 6 } Derived() { _ = Init; field0.ToString(); // 7 field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 8 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 9 } Derived(int unused) { Init = 42; field0.ToString(); // 10 field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 11 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 12 } } public class Derived2 : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override int Init { get { _ = base.Init; field5 = """"; field6 = """"; return 0; } set { base.Init = value; field5 = """"; field6 = """"; } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (29,13): warning CS8774: Member 'field0' must have a non-null value when exiting. // return 0; // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field0").WithLocation(29, 13), // (29,13): warning CS8774: Member 'field1' must have a non-null value when exiting. // return 0; // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field1").WithLocation(29, 13), // (29,13): warning CS8774: Member 'field2' must have a non-null value when exiting. // return 0; // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field2").WithLocation(29, 13), // (35,9): warning CS8774: Member 'field0' must have a non-null value when exiting. // } // 4, 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field0").WithLocation(35, 9), // (35,9): warning CS8774: Member 'field1' must have a non-null value when exiting. // } // 4, 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(35, 9), // (35,9): warning CS8774: Member 'field2' must have a non-null value when exiting. // } // 4, 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(35, 9), // (41,9): warning CS8602: Dereference of a possibly null reference. // field0.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field0").WithLocation(41, 9), // (45,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(45, 9), // (49,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(49, 9), // (55,9): warning CS8602: Dereference of a possibly null reference. // field0.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field0").WithLocation(55, 9), // (59,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(59, 9), // (63,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(63, 9) ); } [Fact] public void MemberNotNull_Inheritance_Property_PE() { var libComp = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; public string field3 = null!; public string? field4; [MemberNotNull(nameof(field0), nameof(field1), nameof(field2))] public virtual int Init { get => throw null!; set => throw null!; } }", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); var c = CreateNullableCompilation(@" using System.Diagnostics.CodeAnalysis; public class Derived : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field5), nameof(field6))] public override int Init { get { field5 = """"; field6 = """"; return 0; // 1, 2, 3 } set { field5 = """"; field6 = """"; } // 4, 5, 6 } Derived() { _ = Init; field0.ToString(); // 7 field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 8 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 9 } Derived(int unused) { Init = 42; field0.ToString(); // 10 field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 11 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 12 } } ", new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (18,13): warning CS8774: Member 'field0' must have a non-null value when exiting. // return 0; // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field0").WithLocation(18, 13), // (18,13): warning CS8774: Member 'field1' must have a non-null value when exiting. // return 0; // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field1").WithLocation(18, 13), // (18,13): warning CS8774: Member 'field2' must have a non-null value when exiting. // return 0; // 1, 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field2").WithLocation(18, 13), // (24,9): warning CS8774: Member 'field0' must have a non-null value when exiting. // } // 4, 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field0").WithLocation(24, 9), // (24,9): warning CS8774: Member 'field1' must have a non-null value when exiting. // } // 4, 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(24, 9), // (24,9): warning CS8774: Member 'field2' must have a non-null value when exiting. // } // 4, 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(24, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // field0.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field0").WithLocation(30, 9), // (34,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(34, 9), // (38,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(38, 9), // (44,9): warning CS8602: Dereference of a possibly null reference. // field0.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field0").WithLocation(44, 9), // (48,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(48, 9), // (52,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(52, 9) ); } [Fact] public void MemberNotNull_Inheritance_SpecifiedOnDerived() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field0; public string field1 = null!; public string? field2; public string field3 = null!; public string? field4; public virtual void Init() => throw null!; } public class Derived : Base { public new string? field0; public string field5 = null!; public string? field6; public string field7 = null!; public string? field8; [MemberNotNull(nameof(field0), nameof(field1), nameof(field2), nameof(field5), nameof(field6))] // 1, 2 public override void Init() => throw null!; Derived() { Init(); field0.ToString(); field1.ToString(); field2.ToString(); // 3 field3.ToString(); field4.ToString(); // 4 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 5 } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (21,6): error CS8776: Member 'field1' cannot be used in this attribute. // [MemberNotNull(nameof(field0), nameof(field1), nameof(field2), nameof(field5), nameof(field6))] // 1, 2 Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNull(nameof(field0), nameof(field1), nameof(field2), nameof(field5), nameof(field6))").WithArguments("field1").WithLocation(21, 6), // (21,6): error CS8776: Member 'field2' cannot be used in this attribute. // [MemberNotNull(nameof(field0), nameof(field1), nameof(field2), nameof(field5), nameof(field6))] // 1, 2 Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNull(nameof(field0), nameof(field1), nameof(field2), nameof(field5), nameof(field6))").WithArguments("field2").WithLocation(21, 6), // (29,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(29, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(31, 9), // (35,9): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(35, 9) ); } [Fact] public void MemberNotNull_Inheritance_Property_SpecifiedOnDerived_BadMember() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field; public virtual int Init => throw null!; } public class Derived : Base { [MemberNotNull(nameof(field))] public override int Init => 0; } public class Derived2 : Base { [MemberNotNull(nameof(field))] public override int Init { get { field = """"; return 0; } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,6): error CS8776: Member 'field' cannot be used in this attribute. // [MemberNotNull(nameof(field))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNull(nameof(field))").WithArguments("field").WithLocation(10, 6), // (15,6): error CS8776: Member 'field' cannot be used in this attribute. // [MemberNotNull(nameof(field))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNull(nameof(field))").WithArguments("field").WithLocation(15, 6) ); } [Fact] public void MemberNotNull_BadMember() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { [MemberNotNull(nameof(missing))] public int Init => 0; [MemberNotNull(nameof(missing))] public int Init2() => 0; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,27): error CS0103: The name 'missing' does not exist in the current context // [MemberNotNull(nameof(missing))] Diagnostic(ErrorCode.ERR_NameNotInContext, "missing").WithArguments("missing").WithLocation(5, 27), // (8,27): error CS0103: The name 'missing' does not exist in the current context // [MemberNotNull(nameof(missing))] Diagnostic(ErrorCode.ERR_NameNotInContext, "missing").WithArguments("missing").WithLocation(8, 27) ); } [Fact] public void MemberNotNull_BadMember_2() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { [MemberNotNull(nameof(C))] public int Init => 0; [MemberNotNull(nameof(M))] public int Init2() => 0; public void M() { } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,6): warning CS8776: Member 'C' cannot be used in this attribute. // [MemberNotNull(nameof(C))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNull(nameof(C))").WithArguments("C").WithLocation(5, 6), // (8,6): warning CS8776: Member 'M' cannot be used in this attribute. // [MemberNotNull(nameof(M))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNull(nameof(M))").WithArguments("M").WithLocation(8, 6) ); } [Fact] public void MemberNotNull_AppliedInCSharp8() { var libComp = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string? field; [MemberNotNull(nameof(field))] public int Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); libComp.VerifyDiagnostics(); var c = CreateNullableCompilation(new[] { @" public class D { void M(C c, C c2) { c.field.ToString(); c2.Init(); c2.field.ToString(); } } " }, references: new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular8); // Note: attribute honored in C# 8 caller c.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(6, 9) ); } [Fact] public void MemberNotNullWhen_Inheritance_SpecifiedOnDerived_BadMember() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string? field; public string? Property; public virtual bool Init => throw null!; public virtual bool Init2() => throw null!; } public class Derived : Base { [MemberNotNullWhen(true, nameof(field), nameof(Property))] public override bool Init => throw null!; [MemberNotNullWhen(true, nameof(field), nameof(Property))] public override bool Init2() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (12,6): error CS8776: Member 'field' cannot be used in this attribute. // [MemberNotNullWhen(true, nameof(field), nameof(Property))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNullWhen(true, nameof(field), nameof(Property))").WithArguments("field").WithLocation(12, 6), // (12,6): error CS8776: Member 'Property' cannot be used in this attribute. // [MemberNotNullWhen(true, nameof(field), nameof(Property))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNullWhen(true, nameof(field), nameof(Property))").WithArguments("Property").WithLocation(12, 6), // (15,6): error CS8776: Member 'field' cannot be used in this attribute. // [MemberNotNullWhen(true, nameof(field), nameof(Property))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNullWhen(true, nameof(field), nameof(Property))").WithArguments("field").WithLocation(15, 6), // (15,6): error CS8776: Member 'Property' cannot be used in this attribute. // [MemberNotNullWhen(true, nameof(field), nameof(Property))] Diagnostic(ErrorCode.WRN_MemberNotNullBadMember, "MemberNotNullWhen(true, nameof(field), nameof(Property))").WithArguments("Property").WithLocation(15, 6) ); } [Fact] public void MemberNotNull_EnforcementInTryFinally() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public string field5; public string? field6; public C() // 1 { Init(); } [MemberNotNull(nameof(field1), nameof(field2), nameof(field3), nameof(field4))] void Init() { try { bool b = true; if (b) { return; // 2, 3 } else { field3 = """"; field4 = """"; return; } } finally { field1 = """"; field2 = """"; } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (12,12): warning CS8618: Non-nullable field 'field5' is uninitialized. Consider declaring the field as nullable. // public C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field5").WithLocation(12, 12), // (25,17): warning CS8771: Member 'field3' must have a non-null value when exiting. // return; // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return;").WithArguments("field3").WithLocation(25, 17), // (25,17): warning CS8771: Member 'field4' must have a non-null value when exiting. // return; // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "return;").WithArguments("field4").WithLocation(25, 17) ); } [Fact] public void MemberNotNull_LangVersion() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public string? field1; [MemberNotNull(nameof(field1))] void Init() => throw null!; [MemberNotNullWhen(true, nameof(field1))] bool Init2() => throw null!; [MemberNotNull(nameof(field1))] bool IsInit { get { throw null!; } } [MemberNotNullWhen(true, nameof(field1))] bool IsInit2 { get { throw null!; } } } "; var c = CreateCompilation(new[] { source, MemberNotNullAttributeDefinition, MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public string? field1; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18), // (6,6): error CS8400: Feature 'MemberNotNull attribute' is not available in C# 8.0. Please use language version 9.0 or greater. // [MemberNotNull(nameof(field1))] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "MemberNotNull(nameof(field1))").WithArguments("MemberNotNull attribute", "9.0").WithLocation(6, 6), // (9,6): error CS8400: Feature 'MemberNotNull attribute' is not available in C# 8.0. Please use language version 9.0 or greater. // [MemberNotNullWhen(true, nameof(field1))] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "MemberNotNullWhen(true, nameof(field1))").WithArguments("MemberNotNull attribute", "9.0").WithLocation(9, 6), // (12,6): error CS8400: Feature 'MemberNotNull attribute' is not available in C# 8.0. Please use language version 9.0 or greater. // [MemberNotNull(nameof(field1))] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "MemberNotNull(nameof(field1))").WithArguments("MemberNotNull attribute", "9.0").WithLocation(12, 6), // (15,6): error CS8400: Feature 'MemberNotNull attribute' is not available in C# 8.0. Please use language version 9.0 or greater. // [MemberNotNullWhen(true, nameof(field1))] Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "MemberNotNullWhen(true, nameof(field1))").WithArguments("MemberNotNull attribute", "9.0").WithLocation(15, 6) ); var c2 = CreateCompilation(new[] { source, MemberNotNullAttributeDefinition, MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c2.VerifyDiagnostics( // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public string? field1; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18) ); } [Fact] public void MemberNotNull_BoolReturning() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } else { field1.ToString(); field2.ToString(); field3.ToString(); // 3 field4.ToString(); // 4 } } [MemberNotNull(nameof(field1), nameof(field2))] bool Init() => true; // 5, 6 } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (23,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(23, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13), // (29,20): warning CS8774: Member 'field1' must have a non-null value when exiting. // bool Init() => true; // 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "true").WithArguments("field1").WithLocation(29, 20), // (29,20): warning CS8774: Member 'field2' must have a non-null value when exiting. // bool Init() => true; // 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "true").WithArguments("field2").WithLocation(29, 20) ); } [Fact] public void MemberNotNull_OtherType() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void M() { var d = new D(); d.Init(); d.field1.ToString(); d.field2.ToString(); d.field3.ToString(); d.field4.ToString(); // 1 } } public class D { public string field1; // 2 public string? field2; public string field3; // 3 public string? field4; [MemberNotNull(nameof(field1), nameof(field2))] public void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // d.field4.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field4").WithLocation(12, 9), // (17,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(17, 19), // (19,19): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public string field3; // 3 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(19, 19) ); } [Fact] public void MemberNotNull_OtherType_ExtensionMethod() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void M() { var d = new D(); d.Init(); d.field1.ToString(); d.field2.ToString(); d.field3.ToString(); d.field4.ToString(); } } public class D { public string field1; public string? field2; public string field3; public string? field4; } public static class Extension { [MemberNotNull(nameof(field1), nameof(field2))] public static void Init(this D d) => throw null!; } ", MemberNotNullAttributeDefinition }); c.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // d.field2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field2").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // d.field4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d.field4").WithLocation(12, 9), // (17,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(17, 19), // (19,19): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public string field3; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(19, 19), // (24,27): error CS0103: The name 'field1' does not exist in the current context // [MemberNotNull(nameof(field1), nameof(field2))] Diagnostic(ErrorCode.ERR_NameNotInContext, "field1").WithArguments("field1").WithLocation(24, 27), // (24,43): error CS0103: The name 'field2' does not exist in the current context // [MemberNotNull(nameof(field1), nameof(field2))] Diagnostic(ErrorCode.ERR_NameNotInContext, "field2").WithArguments("field2").WithLocation(24, 43) ); } [Fact] public void MemberNotNull_Property_Getter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { _ = Count; field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } public C(int unused) { Count = 42; field1.ToString(); // 3 field2.ToString(); // 4 field3.ToString(); // 5 field4.ToString(); // 6 } int Count { [MemberNotNull(nameof(field1), nameof(field2))] get => throw null!; set { } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9), // (22,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(22, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(23, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(25, 9) ); } [Fact] public void MemberNotNull_Property_Setter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { _ = Count; field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 } public C(int unused) { Count = 1; field1.ToString(); field2.ToString(); field3.ToString(); // 5 field4.ToString(); // 6 } int Count { get { field1 = """"; return 0; } [MemberNotNull(nameof(field1), nameof(field2))] set { field2 = """"; } // 7 } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(25, 9), // (39,9): warning CS8774: Member 'field1' must have a non-null value when exiting. // } // 7 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(39, 9) ); } [Fact] public void MemberNotNull_Property_Getter_Static() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public static class C { public static string field1; public static string? field2; public static string field3; public static string? field4; static C() { _ = Count; field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } static int Count { [MemberNotNull(nameof(field1), nameof(field2))] get => throw null!; set { } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_Property_Getter_Static_2() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public static class C { public static string field1; public static string? field2; public static string field3; public static string? field4; static C() { Count = 42; field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 } static int Count { [MemberNotNull(nameof(field1), nameof(field2))] get => throw null!; set { } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_Property_Setter_Static() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public static class C { public static string field1; public static string? field2; public static string field3; public static string? field4; static C() { _ = Count; field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 } static int Count { get => throw null!; [MemberNotNull(nameof(field1), nameof(field2))] set => throw null!; } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_Property_Setter_Static_2() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public static class C { public static string field1; public static string? field2; public static string field3; public static string? field4; static C() { Count = 1; field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } static int Count { get => throw null!; [MemberNotNull(nameof(field1), nameof(field2))] set => throw null!; } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNull_Branches() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string field2; public string field3; public string field4; public C() { bool b = true; if (b) Init(); else Init2(); } [MemberNotNull(nameof(field1), nameof(field2))] void Init() => throw null!; [MemberNotNull(nameof(field2), nameof(field3))] void Init2() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 12), // (10,12): warning CS8618: Non-nullable field 'field4' is uninitialized. Consider declaring the field as nullable. // public C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field4").WithLocation(10, 12), // (10,12): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field1").WithLocation(10, 12) ); } [Fact] public void MemberNotNull_Static() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static string field1; public static string? field2; public static string field3; public static string? field4; static C() { Init(); field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); } [MemberNotNull(nameof(field1), nameof(field2), nameof(field4))] static void Init() { field2 = """"; } // 2, 3 } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (23,5): warning CS8774: Member 'field1' must have a non-null value when exiting. // } // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(23, 5), // (23,5): warning CS8774: Member 'field4' must have a non-null value when exiting. // } // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field4").WithLocation(23, 5) ); } [Fact] public void MemberNotNull_Multiple() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string field2; public string field3; public string field4; public C() { Init(); } [MemberNotNull(nameof(field1))] [MemberNotNull(nameof(field2), nameof(field3))] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field4' is uninitialized. Consider declaring the field as nullable. // public C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field4").WithLocation(10, 12) ); } [Fact] public void MemberNotNull_Multiple_ParamsConstructor() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string field2; public string field3; public string field4; public C() { Init(); field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); } [MemberNotNull(nameof(field1), nameof(field2))] [MemberNotNull(nameof(field3), nameof(field4))] void Init() { } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (23,5): warning CS8774: Member 'field1' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(23, 5), // (23,5): warning CS8774: Member 'field2' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(23, 5), // (23,5): warning CS8774: Member 'field3' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field3").WithLocation(23, 5), // (23,5): warning CS8774: Member 'field4' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field4").WithLocation(23, 5) ); } [Fact] public void MemberNotNull_Multiple_Property() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string field2; public string field3; public string field4; public C() { _ = Init; } [MemberNotNull(nameof(field1))] [MemberNotNull(nameof(field2), nameof(field3))] int Init { get => 1; set { } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field4' is uninitialized. Consider declaring the field as nullable. // public C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field4").WithLocation(10, 12), // (19,16): warning CS8774: Member 'field1' must have a non-null value when exiting. // get => 1; Diagnostic(ErrorCode.WRN_MemberNotNull, "1").WithArguments("field1").WithLocation(19, 16), // (19,16): warning CS8774: Member 'field2' must have a non-null value when exiting. // get => 1; Diagnostic(ErrorCode.WRN_MemberNotNull, "1").WithArguments("field2").WithLocation(19, 16), // (19,16): warning CS8774: Member 'field3' must have a non-null value when exiting. // get => 1; Diagnostic(ErrorCode.WRN_MemberNotNull, "1").WithArguments("field3").WithLocation(19, 16), // (20,15): warning CS8774: Member 'field1' must have a non-null value when exiting. // set { } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(20, 15), // (20,15): warning CS8774: Member 'field2' must have a non-null value when exiting. // set { } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(20, 15), // (20,15): warning CS8774: Member 'field3' must have a non-null value when exiting. // set { } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field3").WithLocation(20, 15) ); } [Fact] public void MemberNotNull_NotFound() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public C() { Init(); } [MemberNotNull(nameof(field))] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }); c.VerifyDiagnostics( // (10,27): error CS0103: The name 'field' does not exist in the current context // [MemberNotNull(nameof(field))] Diagnostic(ErrorCode.ERR_NameNotInContext, "field").WithArguments("field").WithLocation(10, 27) ); } [Fact] public void MemberNotNull_NotFound_PrivateInBase() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { private string? field; public string? P { get { return field; } set { field = value; } } } public class C : Base { public C() { Init(); } [MemberNotNull(nameof(field))] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }); c.VerifyDiagnostics( // (15,27): error CS0122: 'Base.field' is inaccessible due to its protection level // [MemberNotNull(nameof(field))] Diagnostic(ErrorCode.ERR_BadAccess, "field").WithArguments("Base.field").WithLocation(15, 27) ); } [Fact] public void MemberNotNull_Null() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { [MemberNotNull(members: null)] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // [MemberNotNull(members: null)] Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 29) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() { Init(); } [MemberNotNull(nameof(field1), nameof(field2))] void Init() { } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (16,19): warning CS8771: Member 'field1' must have a non-null value when exiting. // void Init() { } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(16, 19), // (16,19): warning CS8771: Member 'field2' must have a non-null value when exiting. // void Init() { } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(16, 19) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody_AccessedInBody() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() { Init(); } [MemberNotNull(nameof(field1), nameof(field2))] void Init() { field1.ToString(); } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (18,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(18, 9), // (19,5): warning CS8771: Member 'field2' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(19, 5) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody_AccessedInBody_OnlyThisField() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() { Init("""", new C()); } [MemberNotNull(nameof(field1), nameof(field2))] void Init(string field1, C c) { field1.ToString(); c.field1.ToString(); } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (20,5): warning CS8771: Member 'field1' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(20, 5), // (20,5): warning CS8771: Member 'field2' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(20, 5) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody_Throw() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; [MemberNotNull(nameof(field1), nameof(field2))] void Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19), // (7,19): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public string field3; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 19) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody_BranchWithReturn() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; // 1 public string? field2; public string field3; // 2 public string? field4; [MemberNotNull(nameof(field1), nameof(field2))] void Init() { bool b = true; if (b) { return; // 3, 4 } field2 = """"; } // 5 } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19), // (7,19): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public string field3; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 19), // (16,13): warning CS8771: Member 'field1' must have a non-null value when exiting. // return; // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "return;").WithArguments("field1").WithLocation(16, 13), // (16,13): warning CS8771: Member 'field2' must have a non-null value when exiting. // return; // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "return;").WithArguments("field2").WithLocation(16, 13), // (19,5): warning CS8771: Member 'field1' must have a non-null value when exiting. // } // 5 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(19, 5) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody_BranchWithReturn_WithValue() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; // 1 public string? field2; public string field3; // 2 public string? field4; [MemberNotNull(nameof(field1), nameof(field2))] int Init() { bool b = true; if (b) { return 0; // 3, 4 } field2 = """"; return 0; // 5 } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19), // (7,19): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public string field3; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 19), // (16,13): warning CS8771: Member 'field1' must have a non-null value when exiting. // return 0; // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field1").WithLocation(16, 13), // (16,13): warning CS8771: Member 'field2' must have a non-null value when exiting. // return 0; // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field2").WithLocation(16, 13), // (19,9): warning CS8771: Member 'field1' must have a non-null value when exiting. // return 0; // 5 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 0;").WithArguments("field1").WithLocation(19, 9) ); } [Fact] public void MemberNotNull_EnforcedInProperty() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() // 1 { _ = Init; } C(int ignored) // 2 { Init = 42; } [MemberNotNull(nameof(field1), nameof(field2))] int Init { get { return 42; } // 3, 4 set { } // 5, 6 } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (15,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C(int ignored) // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(15, 5), // (23,15): warning CS8774: Member 'field1' must have a non-null value when exiting. // get { return 42; } // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 42;").WithArguments("field1").WithLocation(23, 15), // (23,15): warning CS8774: Member 'field2' must have a non-null value when exiting. // get { return 42; } // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "return 42;").WithArguments("field2").WithLocation(23, 15), // (24,15): warning CS8774: Member 'field1' must have a non-null value when exiting. // set { } // 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field1").WithLocation(24, 15), // (24,15): warning CS8774: Member 'field2' must have a non-null value when exiting. // set { } // 5, 6 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field2").WithLocation(24, 15) ); } [Fact] public void MemberNotNullWhenTrue_Simple() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } else { throw null!; } } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13) ); } [Fact, WorkItem(47667, "https://github.com/dotnet/roslyn/issues/47667")] public void MemberNotNullWhenTrue_Generic_01() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C<T> { public T field1; public T? field2; public T field3; public T? field4; public C() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } else { throw null!; } } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13) ); } [Fact, WorkItem(47667, "https://github.com/dotnet/roslyn/issues/47667")] public void MemberNotNullWhenTrue_Generic_02() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class GetResult<T> { [MemberNotNullWhen(true, ""Value"")] public bool OK { get; set; } public T? Value { get; init; } } record Manager(int Age); class Archive { readonly Dictionary<string, Manager> Dict = new Dictionary<string, Manager>(); public GetResult<Manager> this[string key] => Dict.TryGetValue(key, out var value) ? new GetResult<Manager> { OK = true, Value = value } : new GetResult<Manager> { OK = false, Value = null }; } public class C { public void M() { Archive archive = new Archive(); var result = archive[""John""]; int age1 = result.OK ? result.Value.Age : result.Value.Age; // 1 } } ", MemberNotNullWhenAttributeDefinition, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (33,15): warning CS8602: Dereference of a possibly null reference. // : result.Value.Age; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result.Value", isSuppressed: false).WithLocation(33, 15) ); } [Fact, WorkItem(47667, "https://github.com/dotnet/roslyn/issues/47667")] public void MemberNotNullWhenFalse_Generic_01() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C<T> where T : new() { [MemberNotNullWhen(false, ""Value"")] public bool IsBad { get; set; } public T? Value { get; set; } } public class Program { public void M(C<object> c) { _ = c.IsBad ? c.Value.ToString() // 1 : c.Value.ToString(); } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,15): warning CS8602: Dereference of a possibly null reference. // ? c.Value.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.Value", isSuppressed: false).WithLocation(16, 15) ); } [Fact, WorkItem(47667, "https://github.com/dotnet/roslyn/issues/47667")] public void MemberNotNull_Generic_01() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C<T> where T : new() { [MemberNotNull(""Value"")] public void Init() { Value = new T(); } public T? Value { get; set; } } public class Program { public void M(bool b, C<object> c) { if (b) c.Value.ToString(); // 1 c.Init(); c.Value.ToString(); } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (15,16): warning CS8602: Dereference of a possibly null reference. // if (b) c.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.Value", isSuppressed: false).WithLocation(15, 16) ); } [Fact, WorkItem(47667, "https://github.com/dotnet/roslyn/issues/47667")] public void MemberNotNull_Extension_01() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string? _field; } public static class Ext { public static string? _field; [MemberNotNull(""_field"")] public static void AssertFieldNotNull(this C c) { if (_field == null) throw null!; } } class Program { void M1(C c) { c.AssertFieldNotNull(); Ext._field.ToString(); c._field.ToString(); // 1 } void M2(C c) { Ext.AssertFieldNotNull(c); Ext._field.ToString(); c._field.ToString(); // 2 } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (23,9): warning CS8602: Dereference of a possibly null reference. // c._field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c._field", isSuppressed: false).WithLocation(23, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // c._field.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c._field", isSuppressed: false).WithLocation(30, 9) ); } [Fact, WorkItem(47667, "https://github.com/dotnet/roslyn/issues/47667")] public void MemberNotNullWhen_Extension_01() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string? _field; } public static class Ext { public static string? _field; [MemberNotNullWhen(true, ""_field"")] public static bool IsFieldPresent(this C c) { return _field != null; } [MemberNotNullWhen(false, ""_field"")] public static bool IsFieldAbsent(this C c) { return _field == null; } } class Program { void M1(C c) { _ = c.IsFieldPresent() ? Ext._field.ToString() : Ext._field.ToString(); // 1 _ = c.IsFieldPresent() ? c._field.ToString() // 2 : c._field.ToString(); // 3 } void M2(C c) { _ = c.IsFieldAbsent() ? Ext._field.ToString() // 4 : Ext._field.ToString(); _ = c.IsFieldAbsent() ? c._field.ToString() // 5 : c._field.ToString(); // 6 } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (26,15): warning CS8602: Dereference of a possibly null reference. // : Ext._field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Ext._field", isSuppressed: false).WithLocation(26, 15), // (29,15): warning CS8602: Dereference of a possibly null reference. // ? c._field.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c._field", isSuppressed: false).WithLocation(29, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // : c._field.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c._field", isSuppressed: false).WithLocation(30, 15), // (36,15): warning CS8602: Dereference of a possibly null reference. // ? Ext._field.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Ext._field", isSuppressed: false).WithLocation(36, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // ? c._field.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c._field", isSuppressed: false).WithLocation(40, 15), // (41,15): warning CS8602: Dereference of a possibly null reference. // : c._field.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c._field", isSuppressed: false).WithLocation(41, 15) ); } [Fact] public void MemberNotNullWhenTrue_NonConstantBool() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; // 1 [MemberNotNullWhen(true, nameof(field1))] bool Init() { bool b = true; return b; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19) ); } [Fact] public void MemberNotNullWhenTrue_NullValues() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (Init()) { field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 } else { throw null!; } } [MemberNotNullWhen(true, null!, null!)] [MemberNotNullWhen(true, members: null!)] [MemberNotNullWhen(true, member: null!)] bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(14, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(15, 13), // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13) ); } [Fact] public void MemberNotNullWhenTrue_EnforcementInTryFinally() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (!Init()) { throw null!; } } [MemberNotNullWhen(true, nameof(field1), nameof(field2), nameof(field3), nameof(field4))] bool Init() { try { bool b = true; if (b) { field3 = """"; field4 = """"; return true; // 1, 2 } } finally { field1 = """"; field2 = """"; } return false; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics(); } [Fact] public void MemberNotNullWhenTrue_EnforcementInTryFinally_2() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; [MemberNotNullWhen(true, nameof(field1))] bool Init() { try { return true; } finally { field1 = string.Empty; } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19) ); } [Fact] public void MemberNotNullWhenTrue_EnforcementInTryFinally_2_Reversed() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; [MemberNotNullWhen(true, nameof(field1))] bool Init() { try { return false; } finally { field1 = string.Empty; } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19) ); } [Fact] public void MemberNotNullWhenTrue_EnforcementInTryFinally_Reversed() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (!Init()) { throw null!; } } [MemberNotNullWhen(true, nameof(field1), nameof(field2), nameof(field3), nameof(field4))] bool Init() { try { bool b = true; if (b) { field3 = """"; field4 = """"; return false; } } finally { field1 = """"; field2 = """"; } return true; // 1, 2 } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (37,9): warning CS8772: Member 'field3' must have a non-null value when exiting with 'true'. // return true; // 1, 2 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field3", "true").WithLocation(37, 9), // (37,9): warning CS8772: Member 'field4' must have a non-null value when exiting with 'true'. // return true; // 1, 2 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field4", "true").WithLocation(37, 9) ); } [Fact] public void MemberNotNullWhenFalse_EnforcementInTryFinally() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (NotInit()) { throw null!; } } [MemberNotNullWhen(false, nameof(field1), nameof(field2), nameof(field3), nameof(field4))] bool NotInit() { try { bool b = true; if (b) { field3 = """"; field4 = """"; return false; } } finally { field1 = """"; field2 = """"; } return true; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics(); } [Fact] public void MemberNotNullWhenTrue_Inheritance() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string field1; public string? field2; public string field3; public string? field4; public Base() // 1 { if (!Init()) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] public virtual bool Init() => throw null!; } public class Derived : Base { public string field5; public string? field6; public string field7; public string? field8; public Derived() : base() // 2 { if (!Init()) throw null!; } void M() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 3 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 4 } } [MemberNotNullWhen(true, nameof(field6), nameof(field7))] public override bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public Base() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Base").WithArguments("field", "field3").WithLocation(10, 12), // (26,12): warning CS8618: Non-nullable field 'field5' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field5").WithLocation(26, 12), // (39,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(39, 13), // (43,13): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(43, 13) ); } [Fact] public void MemberNotNullWhenTrue_Inheritance_PE() { var libComp = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string field1; public string? field2; public string? field2b; public string field3; public string? field4; public Base() { if (!Init()) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] [MemberNotNullWhen(true, nameof(field2b))] public virtual bool Init() => throw null!; }", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); var c = CreateNullableCompilation(@" using System.Diagnostics.CodeAnalysis; public class Derived : Base { public string field5; public string? field6; public string field7; public string? field8; public Derived() : base() // 1 { if (!Init()) throw null!; } void M() { if (Init()) { field1.ToString(); field2.ToString(); field2b.ToString(); field3.ToString(); field4.ToString(); // 2 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 3 } } [MemberNotNullWhen(true, nameof(field6), nameof(field7))] public override bool Init() => throw null!; } ", references: new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field5' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field5").WithLocation(10, 12), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13), // (28,13): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(28, 13) ); } [Fact] public void MemberNotNullWhenFalse_Inheritance_PE() { var libComp = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string field1; public string? field2; public string field3; public string? field4; public Base() { if (!NotInit()) throw null!; } [MemberNotNullWhen(false, nameof(field1), nameof(field2))] public virtual bool NotInit() => throw null!; }", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); var c = CreateNullableCompilation(@" using System.Diagnostics.CodeAnalysis; public class Derived : Base { public string field5; public string? field6; public string field7; public string? field8; public Derived() : base() // 1 { if (NotInit()) throw null!; } void M() { if (!NotInit()) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 2 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 3 } } [MemberNotNullWhen(false, nameof(field6), nameof(field7))] public override bool NotInit() => throw null!; } ", references: new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field5' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field5").WithLocation(10, 12), // (23,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(23, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(27, 13) ); } [Fact] public void MemberNotNullWhenTrue_Inheritance_Property() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string field1; public string? field2; public string field3; public string? field4; public Base() // 1 { if (!Init) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] public virtual bool Init => throw null!; } public class Derived : Base { public string field5; public string? field6; public string field7; public string? field8; public Derived() : base() // 3 { if (!Init) throw null!; } void M() { if (Init) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 4 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 5 } } [MemberNotNullWhen(true, nameof(field6), nameof(field7))] public override bool Init => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public Base() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Base").WithArguments("field", "field3").WithLocation(10, 12), // (26,12): warning CS8618: Non-nullable field 'field5' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 3 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field5").WithLocation(26, 12), // (39,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(39, 13), // (43,13): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(43, 13) ); } [Fact] public void MemberNotNullWhenTrue_Inheritance_Property_PE() { var libComp = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string field1; public string? field2; public string field3; public string? field4; public Base() { if (!Init) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] public virtual bool Init => throw null!; }", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); var c = CreateNullableCompilation(@" using System.Diagnostics.CodeAnalysis; public class Derived : Base { public string field5; public string? field6; public string field7; public string? field8; public Derived() : base() // 1 { if (!Init) throw null!; } void M() { if (Init) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 2 field5.ToString(); field6.ToString(); field7.ToString(); field8.ToString(); // 3 } } [MemberNotNullWhen(true, nameof(field6), nameof(field7))] public override bool Init => throw null!; } ", references: new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field5' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field5").WithLocation(10, 12), // (23,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(23, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // field8.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field8").WithLocation(27, 13) ); } [Fact] public void MemberNotNullWhenTrue_Inheritance_New() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Base { public string field1; public string? field2; public string field3; public string? field4; public Base() // 1, 2 { Init(); } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] public virtual bool Init() => throw null!; } public class Derived : Base { public new string field1; public new string? field2; public new string field3; public new string? field4; public Derived() : base() // 3, 4 { Init(); } void M() { Init(); field1.ToString(); field2.ToString(); // 5 field3.ToString(); field4.ToString(); // 6 } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] public override bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,12): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public Base() // 1, 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Base").WithArguments("field", "field3").WithLocation(10, 12), // (10,12): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public Base() // 1, 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Base").WithArguments("field", "field1").WithLocation(10, 12), // (25,12): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 3, 4 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field3").WithLocation(25, 12), // (25,12): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public Derived() : base() // 3, 4 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Derived").WithArguments("field", "field1").WithLocation(25, 12), // (34,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(34, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(36, 9) ); } [Fact] public void MemberNotNull_InstanceMethodValidatingStaticFields() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static string field1; // 1 public static string? field2; public static string field3; // 2 public static string? field4; public void M() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 3 } else { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 4 } } [MemberNotNull(nameof(field1), nameof(field2))] bool Init() => throw null!; } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,26): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public static string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 26), // (7,26): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public static string field3; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 26), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13) ); } [Fact] public void MemberNotNullWhenTrue_InstanceMethodValidatingStaticFields() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static string field1; // 1 public static string? field2; public static string field3; // 2 public static string? field4; public void M() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 3 } else { field1.ToString(); field2.ToString(); // 4 field3.ToString(); field4.ToString(); // 5 } } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,26): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public static string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 26), // (7,26): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public static string field3; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 26), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (22,13): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(22, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13) ); } [Fact] public void MemberNotNullWhenTrue_Property() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (IsInit) { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } else { field1.ToString(); // 3 field2.ToString(); // 4 field3.ToString(); // 5 field4.ToString(); // 6 throw null!; } } public C(bool b) { IsInit = b; field1.ToString(); // 7 field2.ToString(); // 8 field3.ToString(); // 9 field4.ToString(); // 10 } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool IsInit { get => throw null!; set => throw null!; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (21,13): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(21, 13), // (22,13): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(22, 13), // (23,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(23, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13), // (32,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(32, 9), // (33,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(33, 9), // (34,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(34, 9), // (35,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(35, 9) ); } [Fact] public void MemberNotNullWhenTrue_Property_AppliedOnGetter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (IsInit) { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } else { field1.ToString(); // 3 field2.ToString(); // 4 field3.ToString(); // 5 field4.ToString(); // 6 throw null!; } } bool IsInit { [MemberNotNullWhen(true, nameof(field1), nameof(field2))] get => throw null!; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (21,13): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(21, 13), // (22,13): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(22, 13), // (23,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(23, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13) ); } [Fact] public void MemberNotNullWhenTrue_Property_AppliedOnSetter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { IsInit = true; field1.ToString(); // 1 field2.ToString(); // 2 field3.ToString(); // 3 field4.ToString(); // 4 } bool IsInit { get { bool b = true; if (b) { field1 = """"; return true; // 5 } field2 = """"; return false; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] set { } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // field1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field1").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(16, 9) ); } [Fact] public void MemberNotNullWhenTrue_Property_Static() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public static class C { public static string field1; // 1 public static string? field2; public static string field3; // 2 public static string? field4; public static void M() { if (IsInit) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); // 3 } else { field1.ToString(); field2.ToString(); // 4 field3.ToString(); field4.ToString(); // 5 throw null!; } } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] static bool IsInit => true; // 6, 7 } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,26): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public static string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 26), // (7,26): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public static string field3; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 26), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (22,13): warning CS8602: Dereference of a possibly null reference. // field2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field2").WithLocation(22, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(24, 13), // (31,12): error CS8772: Member 'field1' must have a non-null value when exiting with 'true'. // => true; // 6, 7 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "true").WithArguments("field1", "true").WithLocation(31, 12), // (31,12): error CS8772: Member 'field2' must have a non-null value when exiting with 'true'. // => true; // 6, 7 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "true").WithArguments("field2", "true").WithLocation(31, 12) ); } [Fact] public void MemberNotNullWhenTrue_Multiple() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } else { throw null!; } } [MemberNotNullWhen(true, nameof(field1)), MemberNotNullWhen(true, nameof(field2))] bool Init() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13) ); } [Fact] public void MemberNotNullWhenTrue_Multiple_ParamsConstructor() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); } else { throw null!; } } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] [MemberNotNullWhen(true, nameof(field3), nameof(field4))] bool Init() { return true; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (29,9): warning CS8775: Member 'field1' must have a non-null value when exiting with 'true'. // return true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field1", "true").WithLocation(29, 9), // (29,9): warning CS8775: Member 'field2' must have a non-null value when exiting with 'true'. // return true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field2", "true").WithLocation(29, 9), // (29,9): warning CS8775: Member 'field3' must have a non-null value when exiting with 'true'. // return true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field3", "true").WithLocation(29, 9), // (29,9): warning CS8775: Member 'field4' must have a non-null value when exiting with 'true'. // return true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field4", "true").WithLocation(29, 9) ); } [Fact] public void MemberNotNullWhenTrue_Multiple_Property() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string? field3; public string? field4; public C() { if (Init) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); } else { throw null!; } } [MemberNotNullWhen(true, nameof(field1))] [MemberNotNullWhen(true, nameof(field2), nameof(field3))] bool Init { get => true; set { } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (17,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(17, 13), // (29,16): warning CS8775: Member 'field1' must have a non-null value when exiting with 'true'. // get => true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "true").WithArguments("field1", "true").WithLocation(29, 16), // (29,16): warning CS8775: Member 'field2' must have a non-null value when exiting with 'true'. // get => true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "true").WithArguments("field2", "true").WithLocation(29, 16), // (29,16): warning CS8775: Member 'field3' must have a non-null value when exiting with 'true'. // get => true; Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "true").WithArguments("field3", "true").WithLocation(29, 16) ); } [Fact] public void MemberNotNullWhenFalse_Simple() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public C() { if (NotInit()) { throw null!; } else { field1.ToString(); field2.ToString(); field3.ToString(); // 1 field4.ToString(); // 2 } } [MemberNotNullWhen(false, nameof(field1), nameof(field2))] bool NotInit() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (20,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(20, 13), // (21,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(21, 13) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() // 1 { if (!Init()) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init() { bool b = true; if (b) { return true; // 2, 3 } field2 = """"; return false; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (21,13): error CS8772: Member 'field1' must have a non-null value when exiting with 'true'. // return true; // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field1", "true").WithLocation(21, 13), // (21,13): error CS8772: Member 'field2' must have a non-null value when exiting with 'true'. // return true; // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field2", "true").WithLocation(21, 13) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody_NonConstant() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() // 1 { if (!Init()) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init() { bool b = true; if (b) { return b; } if (b) { return !b; } return M(out _); } bool M([MaybeNullWhen(true)]out string s) => throw null!; } ", MemberNotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody_NonConstant_ButAnalyzable() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string field3; C() { if (!Init()) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field3))] bool Init() { bool b = true; if (b) { return field1 == null; // 1 } if (b) { return field1 != null; } if (b) { return Init(); } return !Init(); // 2, 3 } } ", MemberNotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (19,13): warning CS8775: Member 'field1' must have a non-null value when exiting with 'true'. // return field1 == null; // 1 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return field1 == null;").WithArguments("field1", "true").WithLocation(19, 13), // (29,9): warning CS8775: Member 'field1' must have a non-null value when exiting with 'true'. // return !Init(); // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return !Init();").WithArguments("field1", "true").WithLocation(29, 9), // (29,9): warning CS8775: Member 'field3' must have a non-null value when exiting with 'true'. // return !Init(); // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return !Init();").WithArguments("field3", "true").WithLocation(29, 9) ); } [Fact] public void MemberNotNullWhenFalse_EnforcedInMethodBody_NonConstant_ButAnalyzable() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string field3; C() { if (Init()) throw null!; } [MemberNotNullWhen(false, nameof(field1), nameof(field3))] bool Init() { bool b = true; if (b) { return field1 == null; } if (b) { return field1 != null; // 1 } if (b) { return Init(); } return !Init(); // 2, 3 } bool M([MaybeNullWhen(true)]out string s) => throw null!; } ", MemberNotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (23,13): warning CS8775: Member 'field1' must have a non-null value when exiting with 'false'. // return field1 != null; // 1 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return field1 != null;").WithArguments("field1", "false").WithLocation(23, 13), // (29,9): warning CS8775: Member 'field1' must have a non-null value when exiting with 'false'. // return !Init(); // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return !Init();").WithArguments("field1", "false").WithLocation(29, 9), // (29,9): warning CS8775: Member 'field3' must have a non-null value when exiting with 'false'. // return !Init(); // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return !Init();").WithArguments("field3", "false").WithLocation(29, 9) ); } [Fact] public void MemberNotNullWhenTrue_WithMemberNotNull() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; public string field5; public string? field6; C() { if (Init()) { field1.ToString(); field2.ToString(); field3.ToString(); field4.ToString(); field5.ToString(); // 1 field6.ToString(); // 2 } else { field1.ToString(); field2.ToString(); field3.ToString(); // 3 field4.ToString(); // 4 field5.ToString(); // 5 field6.ToString(); // 6 } } [MemberNotNull(nameof(field1), nameof(field2))] [MemberNotNullWhen(true, nameof(field3), nameof(field4))] bool Init() => throw null!; } ", MemberNotNullAttributeDefinition, MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (20,13): warning CS8602: Dereference of a possibly null reference. // field5.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field5").WithLocation(20, 13), // (21,13): warning CS8602: Dereference of a possibly null reference. // field6.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field6").WithLocation(21, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // field3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field3").WithLocation(27, 13), // (28,13): warning CS8602: Dereference of a possibly null reference. // field4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field4").WithLocation(28, 13), // (29,13): warning CS8602: Dereference of a possibly null reference. // field5.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field5").WithLocation(29, 13), // (30,13): warning CS8602: Dereference of a possibly null reference. // field6.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field6").WithLocation(30, 13) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody_UnreachableExit() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init(bool b) { try { if (b) return true; else return false; } finally { throw null!; } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19) ); } [Fact] public void MemberNotNull_EnforcedInMethodBody_UnreachableExit() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; [MemberNotNull(nameof(field1), nameof(field2))] bool Init(bool b) { try { if (b) return true; else return false; } finally { throw null!; } } } ", MemberNotNullAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19) ); } [Fact, WorkItem(44080, "https://github.com/dotnet/roslyn/issues/44080")] public void MemberNotNullWhenTrue_EnforcedInMethodBody_NonConstantBool() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string? field3; [MemberNotNullWhen(true, nameof(field1), nameof(field2), nameof(field3))] bool Init() { field2 = """"; return NonConstantBool(); } bool NonConstantBool() => throw null!; } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody_Property() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() // 1 { if (!IsInit) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool IsInit { get { bool b = true; if (b) { return true; // 2, 3 } field2 = """"; return false; } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (23,17): error CS8772: Member 'field1' must have a non-null value when exiting with 'true'. // return true; // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field1", "true").WithLocation(23, 17), // (23,17): error CS8772: Member 'field2' must have a non-null value when exiting with 'true'. // return true; // 2, 3 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field2", "true").WithLocation(23, 17) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody_Property_NotConstantReturn() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string? field2; [MemberNotNullWhen(true, nameof(field2))] bool IsInit { get { return field2 != null; } } [MemberNotNullWhen(true, nameof(field2))] bool IsInit2 { get { return field2 == null; // 1 } } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (21,13): warning CS8775: Member 'field2' must have a non-null value when exiting with 'true'. // return field2 == null; // 1 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return field2 == null;").WithArguments("field2", "true").WithLocation(21, 13) ); } [Fact] public void MemberNotNullWhenTrue_EnforcedInMethodBody_SwitchedBranches() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() // 1 { if (!Init()) throw null!; } [MemberNotNullWhen(true, nameof(field1), nameof(field2))] bool Init() { bool b = true; if (b) { return false; } field2 = """"; return true; // 2 } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (24,9): error CS8772: Member 'field1' must have a non-null value when exiting with 'true'. // return true; // 2 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return true;").WithArguments("field1", "true").WithLocation(24, 9) ); } [Fact] public void MemberNotNullWhenFalse_EnforcedInMethodBody() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; public string? field2; public string field3; public string? field4; C() // 1, 2 { if (!Init()) throw null!; } [MemberNotNullWhen(false, nameof(field1), nameof(field2), nameof(field4))] bool Init() { bool b = true; if (b) { return true; } field2 = """"; return false; // 3, 4 } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (10,5): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // C() // 1, 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field3").WithLocation(10, 5), // (10,5): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // C() // 1, 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field1").WithLocation(10, 5), // (24,9): error CS8772: Member 'field1' must have a non-null value when exiting with 'false'. // return false; // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return false;").WithArguments("field1", "false").WithLocation(24, 9), // (24,9): error CS8772: Member 'field4' must have a non-null value when exiting with 'false'. // return false; // 3, 4 Diagnostic(ErrorCode.WRN_MemberNotNullWhen, "return false;").WithArguments("field4", "false").WithLocation(24, 9) ); } [Fact] public void MemberNotNullWhenFalse_VoidReturning() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public string field1; // 1 public string? field2; public string field3; // 2 public string? field4; [MemberNotNullWhen(false, nameof(field1), nameof(field2), nameof(field4))] void Init() { bool b = true; if (b) { return; } field2 = """"; return; } } ", MemberNotNullWhenAttributeDefinition }, parseOptions: TestOptions.Regular9); c.VerifyDiagnostics( // (5,19): warning CS8618: Non-nullable field 'field1' is uninitialized. Consider declaring the field as nullable. // public string field1; // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field1").WithArguments("field", "field1").WithLocation(5, 19), // (7,19): warning CS8618: Non-nullable field 'field3' is uninitialized. Consider declaring the field as nullable. // public string field3; // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "field3").WithArguments("field", "field3").WithLocation(7, 19) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void NullableValueType_RecursivePattern() { var c = CreateCompilation(@" #nullable enable public struct Test { public int M(int? i) { switch (i) { case { HasValue: true }: return i.Value; default: return i.Value; } } } "); c.VerifyDiagnostics( // (10,20): error CS0117: 'int' does not contain a definition for 'HasValue' // case { HasValue: true }: Diagnostic(ErrorCode.ERR_NoSuchMember, "HasValue").WithArguments("int", "HasValue").WithLocation(10, 20), // (13,24): warning CS8629: Nullable value type may be null. // return i.Value; Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(13, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: true }: return Value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_Nested() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } } public class Container { public C? Item; public string M() { switch (this) { case { Item: { IsOk: true } }: return this.Item.Value; case { Item: C item }: return item.Value; // 1 default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (22,24): warning CS8603: Possible null reference return. // return item.Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "item.Value").WithLocation(22, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_Nested_WithDeclaration() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } } public class Container { public C? Item; public string M() { switch (this) { case { Item: { IsOk: true } item }: return item.Value; case { Item: C item }: return item.Value; // 1 default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (22,24): warning CS8603: Possible null reference return. // return item.Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "item.Value").WithLocation(22, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithSecondPattern() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public bool IsIrrelevant { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: false }: return Value; // 1 case { IsOk: true, IsIrrelevant: true }: return Value; default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (17,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(17, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_SplitValueIntoVariable() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: var v }: return Value; // 1 default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (16,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(16, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] [WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void MemberNotNullWhenTrue_TupleInSwitchStatement() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M(object? o) { switch (this, o) { case ({ IsOk: true }, null): return Value; case ({ IsOk: true }, not null): return Value; default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] [WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void MemberNotNullWhenTrue_TupleInSwitchExpression() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M(object? o) { return (this, o) switch { ({ IsOk: true }, null) => M2(Value), ({ IsOk: true }, not null) => M2(Value), _ => throw null!, }; } string M2(string s) => throw null!; } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] [WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void MemberNotNullWhenTrue_TupleInIsExpression() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M(object? o) { if ((this, o) is ({ IsOk: true }, null)) { return Value; } throw null!; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] [WorkItem(50980, "https://github.com/dotnet/roslyn/issues/50980")] public void MemberNotNullWhenTrue_TupleEquality() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M(object? o) { if ((IsOk, o) is (true, null)) { return Value; // incorrect warning } if (IsOk is true) { return Value; } throw null!; } } ", MemberNotNullWhenAttributeDefinition }); // We're not learning from tuple equality... // Tracked by https://github.com/dotnet/roslyn/issues/50980 c.VerifyDiagnostics( // (15,20): warning CS8603: Possible null reference return. // return Value; // incorrect warning Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(15, 20) ); } [Fact, WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void PatternOnTuple_IsExpression() { var src = @" #nullable enable public class C { void M(object? o, object o2) { if ((o, o2) is (not null, null)) { o.ToString(); o2.ToString(); // 1 } } void M2(object? o) { if (o is not null) { o.ToString(); } } void M3(object o2) { if (o2 is null) { o2.ToString(); // 2 } } void M4(object? o, object o2) { if ((true, (o, o2)) is (true, (not null, null))) { o.ToString(); // 3 o2.ToString(); } } } "; // Note: we lose track in M4 because any learnings we make on elements of nested tuples // apply to temps, rather than the original expressions/slots. // This is unfortunate, but doesn't seem much of a priority to address. var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // o2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o2").WithLocation(10, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // o2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o2").WithLocation(26, 13), // (34,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(34, 13) ); } [Fact, WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void PatternOnTuple_IsExpression_ContradictoryTests() { var src = @" #nullable enable public class C { void M(object o) { if ((o, o) is (not null, null)) { o.ToString(); // 1 } } void M2(object? o) { if ((o, o) is (null, not null)) { o.ToString(); } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(9, 13) ); } [Fact, WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void PatternOnTuple_IsExpression_LongTuple() { var src = @" #nullable enable public class C { void M(object? o, object o2) { if ((o2, o2, o2, o2, o2, o2, o2, o) is (null, null, null, null, null, null, null, not null)) { o.ToString(); o2.ToString(); // 1 } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // o2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o2").WithLocation(10, 13) ); } [Fact, WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void PatternOnTuple_IsExpression_LearnFromNonNullTest() { var src = @" #nullable enable public class C { int Value { get; set; } void M(C? c, object? o) { if ((c?.Value, o) is (1, not null)) { c.ToString(); } } void M2(C? c) { if (c?.Value is 1) { c.ToString(); } } void M3(C? c, object? o) { if ((true, (o, o, c?.Value)) is (true, (not null, not null, 1))) { c.ToString(); // 1 } } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (27,13): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(27, 13) ); } [Fact, WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void PatternOnTuple_SwitchExpression() { var src = @" #nullable enable public class C { int Test(object o, object o2) => throw null!; void M(object? o, object o2) { _ = (o, o2) switch { (not null, null) => Test(o, o2), // 1 (not null, not null) => Test(o, o2), _ => Test(o, o2), // 2 }; } void M2(object? o, object o2) { _ = (true, (o, o2)) switch { (true, (not null, null)) => Test(o, o2), // 3 (_, (not null, not null)) => Test(o, o2), // 4 _ => Test(o, o2), // 5 }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (11,41): warning CS8604: Possible null reference argument for parameter 'o2' in 'int C.Test(object o, object o2)'. // (not null, null) => Test(o, o2), // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o2").WithArguments("o2", "int C.Test(object o, object o2)").WithLocation(11, 41), // (13,23): warning CS8604: Possible null reference argument for parameter 'o' in 'int C.Test(object o, object o2)'. // _ => Test(o, o2), // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "int C.Test(object o, object o2)").WithLocation(13, 23), // (21,46): warning CS8604: Possible null reference argument for parameter 'o' in 'int C.Test(object o, object o2)'. // (true, (not null, null)) => Test(o, o2), // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "int C.Test(object o, object o2)").WithLocation(21, 46), // (22,47): warning CS8604: Possible null reference argument for parameter 'o' in 'int C.Test(object o, object o2)'. // (_, (not null, not null)) => Test(o, o2), // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "int C.Test(object o, object o2)").WithLocation(22, 47), // (23,23): warning CS8604: Possible null reference argument for parameter 'o' in 'int C.Test(object o, object o2)'. // _ => Test(o, o2), // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "int C.Test(object o, object o2)").WithLocation(23, 23) ); } [Fact, WorkItem(51020, "https://github.com/dotnet/roslyn/issues/51020")] public void PatternOnTuple_SwitchStatement() { var src = @" #nullable enable public class C { void Test(object o, object o2) => throw null!; void M(object? o, object o2) { switch (o, o2) { case (not null, null): Test(o, o2); // 1 break; case (not null, not null): Test(o, o2); break; default: Test(o, o2); // 2 break; } } void M2(object? o, object o2) { switch (true, (o, o2)) { case (true, (not null, null)): Test(o, o2); // 3 break; case (_, (not null, not null)): Test(o, o2); // 4 break; default: Test(o, o2); // 5 break; }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (12,25): warning CS8604: Possible null reference argument for parameter 'o2' in 'void C.Test(object o, object o2)'. // Test(o, o2); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o2").WithArguments("o2", "void C.Test(object o, object o2)").WithLocation(12, 25), // (18,22): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.Test(object o, object o2)'. // Test(o, o2); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.Test(object o, object o2)").WithLocation(18, 22), // (28,22): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.Test(object o, object o2)'. // Test(o, o2); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.Test(object o, object o2)").WithLocation(28, 22), // (31,22): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.Test(object o, object o2)'. // Test(o, o2); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.Test(object o, object o2)").WithLocation(31, 22), // (34,22): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.Test(object o, object o2)'. // Test(o, o2); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.Test(object o, object o2)").WithLocation(34, 22) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_TypeTest() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: bool }: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (16,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(16, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_StateAfterSwitch() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: true }: break; default: throw null!; } return Value; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithBoolPattern() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public bool IsIrrelevant { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: true, IsIrrelevant: true }: return Value; case { IsOk: true, IsIrrelevant: not true }: return Value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (21,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(21, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_OnSetter() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { set { } } public string? Value { get; } public string M() { switch (this) { case { IsOk: true }: // 1 return Value; // 2 default: return Value; // 3 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (15,20): error CS0154: The property or indexer 'C.IsOk' cannot be used in this context because it lacks the get accessor // case { IsOk: true }: // 1 Diagnostic(ErrorCode.ERR_PropertyLacksGet, "IsOk:").WithArguments("C.IsOk").WithLocation(15, 20), // (16,24): warning CS8603: Possible null reference return. // return Value; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(16, 24), // (18,24): warning CS8603: Possible null reference return. // return Value; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_AttributeOnBase() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Base { [MemberNotNullWhen(true, nameof(Value))] public virtual bool IsOk { get; } public string? Value { get; } } public class C : Base { public override bool IsOk { get; } public string M() { switch (this) { case { IsOk: true }: return Value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (22,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(22, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_NotFalse() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: not false }: return Value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenFalse_RecursivePattern() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(false, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: false }: return Value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithNestedDeclaration() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: true, Value: var value }: return value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithNestedDeclaration_ReverseOrder_Struct() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { Value: var value, IsOk: true }: return value; case { Value: var value }: return value; // 1 default: return Value; // 2 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "value").WithLocation(18, 24), // (20,17): warning CS0162: Unreachable code detected // return Value; // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(20, 17) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_Struct() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: true }: return Value; default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); // Analysis of patterns assumes that they are pure, so testing a copy of a struct is // as good as testing the original instance c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithNestedDeclaration_ReverseOrder_Class() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { Value: var value, IsOk: true }: return value; case { Value: var value }: return value; // 1 default: return Value; // not thought as reachable by nullable analysis because `this` is not-null } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithNestedDeclaration_ReverseOrder_Class_OnMaybeNullVariable() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M(Test? t) { switch (t) { case { Value: var value, IsOk: true }: return value; case { Value: var value }: return value; // 1 default: return t.Value; // 2 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "value").WithLocation(18, 24), // (20,24): warning CS8602: Dereference of a possibly null reference. // return t.Value; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(20, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithTopLevelDeclaration() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case { IsOk: true } c: return c.Value; default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_RecursivePattern_WithTopLevelDeclaration_WithType() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (this) { case C { IsOk: true } c: // note: has type return c.Value; case C c: return c.Value; // 1 default: throw null!; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return c.Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "c.Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_BinaryPatternTest() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public bool IsRandom { get; } public string? Value { get; } public string M() { if (this is { IsOk: true } and { IsRandom: true }) { return Value; } if (this is { IsOk: true } or { IsRandom: true }) { return Value; // 1 } return Value; // 2 } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (21,20): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(21, 20), // (24,16): warning CS8603: Possible null reference return. // return Value; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(24, 16) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_BinaryPatternTest_Struct() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct S { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { if (this is { IsOk: true }) { return Value; } throw null!; } } ", MemberNotNullWhenAttributeDefinition }); // Analysis of patterns assumes that they are pure, so testing a copy of a struct is // as good as testing the original instance c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_IsTrueTest() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { if (IsOk is true) { return Value; } else { return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (19,20): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(19, 20) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_IsNotTrueTest() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { if (IsOk is not true) { return Value; // 1 } else { return Value; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (15,20): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(15, 20) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_IsNotFalseTest() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { if (IsOk is not false) { return Value; } else { return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (19,20): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(19, 20) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_IsTrueTest_OnLocal() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public static string M(Test t) { if (t.IsOk is true) { return t.Value; } else { return t.Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (19,20): warning CS8603: Possible null reference return. // return t.Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t.Value").WithLocation(19, 20) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_IsFalseTest() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { if (IsOk is false) { return Value; // 1 } else { return Value; } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (15,20): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(15, 20) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_SwitchStatementOnProperty() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { switch (IsOk) { case true: return Value; default: return Value; // 1 } } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (18,24): warning CS8603: Possible null reference return. // return Value; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Value").WithLocation(18, 24) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_SwitchExpressionOnProperty() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { return IsOk switch { true => Value, _ => throw null!, }; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_SwitchExpressionOnMethod() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk() { throw null!; } public string? Value { get; } public string M() { return IsOk() switch { true => Value, _ => throw null!, }; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_SwitchExpressionOnProperty_WhenFalseBranch() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { return IsOk switch { true => throw null!, _ => Value }; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (13,16): warning CS8603: Possible null reference return. // return IsOk switch { true => throw null!, _ => Value }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "IsOk switch { true => throw null!, _ => Value }").WithLocation(13, 16) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_Ternary() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { return IsOk ? Value : throw null!; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNullWhenTrue_Ternary_WhenFalseBranch() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [MemberNotNullWhen(true, nameof(Value))] public bool IsOk { get; } public string? Value { get; } public string M() { return IsOk ? throw null! : Value; } } ", MemberNotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (13,16): warning CS8603: Possible null reference return. // return IsOk ? throw null! : Value; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "IsOk ? throw null! : Value").WithLocation(13, 16) ); } [Fact, WorkItem(49750, "https://github.com/dotnet/roslyn/issues/49750")] public void MemberNotNull_RecursivePattern() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; #nullable enable public struct Test { [MemberNotNull(nameof(Value))] public int InitCount { get; } public string? Value { get; } public string M() { switch (this) { case { InitCount: var n }: return Value; default: return Value; // 1 } } } ", MemberNotNullAttributeDefinition }); // We honored the unconditional MemberNotNull attributes in the arms where // we know it was evaluated. We recommend that users don't do this. c.VerifyDiagnostics( // (18,17): warning CS0162: Unreachable code detected // return Value; // 1 Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(18, 17) ); } [Fact] public void ConstructorUsesStateFromInitializers() { var source = @" public class Program { public string Prop { get; set; } = ""a""; public Program() { Prop.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source }); comp.VerifyDiagnostics(); } [Fact] public void ConstMembersUseDeclaredNullability_01() { var source = @" public class Program { const string s1 = ""hello""; public static readonly string s2 = s1.ToString(); public Program() { } } "; var comp = CreateNullableCompilation(new[] { source }); comp.VerifyDiagnostics(); } [Fact] public void ConstMembersUseDeclaredNullability_02() { var source = @" public class Program { const string? s1 = ""hello""; public Program() { var x = s1.ToString(); // 1 } } "; // Arguably we could just see through to the constant value and know it's non-null, // but it feels like the user should just fix the type of their 'const' in this scenario. var comp = CreateNullableCompilation(new[] { source }); comp.VerifyDiagnostics( // (8,17): warning CS8602: Dereference of a possibly null reference. // var x = s1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(8, 17)); } [Fact] public void ComputedPropertiesUseDeclaredNullability() { var source = @" public class Program { string Prop1 => ""hello""; string? Prop2 => ""world""; public Program() { Prop1.ToString(); Prop2.ToString(); // 1 } } "; var comp = CreateNullableCompilation(new[] { source }); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // Prop2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Prop2").WithLocation(10, 9)); } [Fact] public void MaybeNullWhenTrue_Simple() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (IsNull(s)) { s.ToString(); // warn } else { s.ToString(); // ok } s.ToString(); // ok } public static bool IsNull([MaybeNullWhen(true)] string s) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void MaybeNullWhenTrue_Indexer() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { _ = this[s] ? s.ToString() // 1 : s.ToString(); } public bool this[[MaybeNullWhen(true)] string s] => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 15) ); } [Fact] public void MaybeNullWhenTrue_OutParameter_MiscTypes() { // Warn on redundant nullability attributes (F3, F4 and F5)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool F1<T>(T t, [MaybeNullWhen(true)]out T t2) => throw null!; static bool F2<T>(T t, [MaybeNullWhen(true)]out T t2) where T : class => throw null!; static bool F3<T>(T t, [MaybeNullWhen(true)]out T? t2) where T : class => throw null!; static bool F4<T>(T t, [MaybeNullWhen(true)]out T t2) where T : struct => throw null!; static bool F5<T>(T? t, [MaybeNullWhen(true)]out T? t2) where T : struct => throw null!; static void M1<T>(T t1) { _ = F1(t1, out var s2) // 0 ? s2.ToString() // 1 : s2.ToString(); // 2 } static void M2<T>(T t2) where T : class { _ = F1(t2, out var s3) ? s3.ToString() // 3 : s3.ToString(); _ = F2(t2, out var s4) ? s4.ToString() // 4 : s4.ToString(); _ = F3(t2, out var s5) ? s5.ToString() // 5 : s5.ToString(); // 6 t2 = null; // 7 _ = F1(t2, out var s6) ? s6.ToString() // 8 : s6.ToString(); // 9 _ = F2(t2, out var s7) // 10 ? s7.ToString() // 11 : s7.ToString(); // 12 _ = F3(t2, out var s8) // 13 ? s8.ToString() // 14 : s8.ToString(); // 15 } static void M3<T>(T? t3) where T : class { _ = F1(t3, out var s9) ? s9.ToString() // 16 : s9.ToString(); // 17 _ = F2(t3, out var s10) // 18 ? s10.ToString() // 19 : s10.ToString(); // 20 _ = F3(t3, out var s11) // 21 ? s11.ToString() // 22 : s11.ToString(); // 23 if (t3 == null) return; _ = F1(t3, out var s12) ? s12.ToString() // 24 : s12.ToString(); _ = F2(t3, out var s13) ? s13.ToString() // 25 : s13.ToString(); _ = F3(t3, out var s14) ? s14.ToString() // 26 : s14.ToString(); // 27 } static void M4<T>(T t4) where T : struct { _ = F1(t4, out var s15) ? s15.ToString() : s15.ToString(); _ = F4(t4, out var s16) ? s16.ToString() : s16.ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1(t5, out var s17) ? s17.Value // 28 : s17.Value; // 29 _ = F5(t5, out var s18) ? s18.Value // 30 : s18.Value; // 31 if (t5 == null) return; _ = F1(t5, out var s19) ? s19.Value // 32 : s19.Value; // 33 _ = F5(t5, out var s20) ? s20.Value // 34 : s20.Value; // 35 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // ? s2.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 15), // (13,15): warning CS8602: Dereference of a possibly null reference. // : s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(13, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? s3.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(18, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // ? s4.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(22, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // ? s5.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(26, 15), // (27,15): warning CS8602: Dereference of a possibly null reference. // : s5.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(27, 15), // (29,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 7 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(29, 14), // (31,15): warning CS8602: Dereference of a possibly null reference. // ? s6.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(31, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // : s6.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(32, 15), // (34,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F2(t2, out var s7) // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(34, 13), // (35,15): warning CS8602: Dereference of a possibly null reference. // ? s7.ToString() // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s7").WithLocation(35, 15), // (36,15): warning CS8602: Dereference of a possibly null reference. // : s7.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s7").WithLocation(36, 15), // (38,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F3(t2, out var s8) // 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(38, 13), // (39,15): warning CS8602: Dereference of a possibly null reference. // ? s8.ToString() // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s8").WithLocation(39, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : s8.ToString(); // 15 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s8").WithLocation(40, 15), // (45,15): warning CS8602: Dereference of a possibly null reference. // ? s9.ToString() // 16 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s9").WithLocation(45, 15), // (46,15): warning CS8602: Dereference of a possibly null reference. // : s9.ToString(); // 17 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s9").WithLocation(46, 15), // (48,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F2(t3, out var s10) // 18 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(48, 13), // (49,15): warning CS8602: Dereference of a possibly null reference. // ? s10.ToString() // 19 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s10").WithLocation(49, 15), // (50,15): warning CS8602: Dereference of a possibly null reference. // : s10.ToString(); // 20 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s10").WithLocation(50, 15), // (52,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F3(t3, out var s11) // 21 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(52, 13), // (53,15): warning CS8602: Dereference of a possibly null reference. // ? s11.ToString() // 22 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s11").WithLocation(53, 15), // (54,15): warning CS8602: Dereference of a possibly null reference. // : s11.ToString(); // 23 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s11").WithLocation(54, 15), // (58,15): warning CS8602: Dereference of a possibly null reference. // ? s12.ToString() // 24 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s12").WithLocation(58, 15), // (62,15): warning CS8602: Dereference of a possibly null reference. // ? s13.ToString() // 25 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s13").WithLocation(62, 15), // (66,15): warning CS8602: Dereference of a possibly null reference. // ? s14.ToString() // 26 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s14").WithLocation(66, 15), // (67,15): warning CS8602: Dereference of a possibly null reference. // : s14.ToString(); // 27 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s14").WithLocation(67, 15), // (82,15): warning CS8629: Nullable value type may be null. // ? s17.Value // 28 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s17").WithLocation(82, 15), // (83,15): warning CS8629: Nullable value type may be null. // : s17.Value; // 29 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s17").WithLocation(83, 15), // (86,15): warning CS8629: Nullable value type may be null. // ? s18.Value // 30 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s18").WithLocation(86, 15), // (87,15): warning CS8629: Nullable value type may be null. // : s18.Value; // 31 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s18").WithLocation(87, 15), // (91,15): warning CS8629: Nullable value type may be null. // ? s19.Value // 32 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s19").WithLocation(91, 15), // (92,15): warning CS8629: Nullable value type may be null. // : s19.Value; // 33 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s19").WithLocation(92, 15), // (95,15): warning CS8629: Nullable value type may be null. // ? s20.Value // 34 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s20").WithLocation(95, 15), // (96,15): warning CS8629: Nullable value type may be null. // : s20.Value; // 35 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s20").WithLocation(96, 15) ); } [Fact] public void MaybeNullWhenTrue_FromMetadata() { var lib = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static bool MaybeNullWhenTrue([MaybeNullWhen(true)] string s) => throw null!; } ", MaybeNullWhenAttributeDefinition }); var c = CreateNullableCompilation(@" public class D { public void Main(string s) { _ = C.MaybeNullWhenTrue(s) ? s.ToString() // 1 : s.ToString(); s.ToString(); } } ", references: new[] { lib.EmitToImageReference() }); c.VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 15) ); } [Fact] public void MaybeNullWhenFalse_FromMetadata() { var lib = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static bool MaybeNullWhenFalse([MaybeNullWhen(false)] string s) => throw null!; } ", MaybeNullWhenAttributeDefinition }); var c = CreateNullableCompilation(@" public class D { public void Main(string s) { _ = C.MaybeNullWhenFalse(s) ? s.ToString() : s.ToString(); // 1 } } ", references: new[] { lib.EmitToImageReference() }); c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 15) ); } [Fact] public void MaybeNullWhenFalse_TryGetValue() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Optional<T> { public void Main(Optional<string> holder) { _ = holder.TryGetValue(out var item) ? item.ToString() : item.ToString(); // 1 item = null; } bool TryGetValue([MaybeNullWhen(false)] out T item) => throw null!; } ", MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // : item.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(9, 15) ); } [Fact] public void MaybeNull_TryGetValue() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class Optional<T> { public void Main(Optional<string> holder) { _ = holder.TryGetValue(out var item) ? item.ToString() // 1 : item.ToString(); // 2 item = null; } bool TryGetValue([MaybeNull] out T item) => throw null!; } ", MaybeNullAttributeDefinition }); c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // ? item.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(8, 15), // (9,15): warning CS8602: Dereference of a possibly null reference. // : item.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "item").WithLocation(9, 15) ); } [Fact, WorkItem(42722, "https://github.com/dotnet/roslyn/issues/42722")] public void MaybeNull_NullableRefParameterAssigningToMaybeNullStringParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void M([MaybeNull] ref string s) { Test(ref s); } void Test(ref string? s) => s = null; } ", MaybeNullAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(42743, "https://github.com/dotnet/roslyn/issues/42743")] public void NotNull_NullableRefParameterAssigningToNotNullParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { static void M([NotNull] out string? s) { s = """"; Ref(ref s); void Ref(ref string? s) => s = null; } } ", NotNullAttributeDefinition }); c.VerifyDiagnostics( // (12,5): warning CS8777: Parameter 's' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("s").WithLocation(12, 5) ); } [Fact, WorkItem(42743, "https://github.com/dotnet/roslyn/issues/42743")] public void MaybeNull_NullableRefParameterAssigningToMaybeNullParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void M([MaybeNull] out string s) { s = null; Out(out s); Ref(ref s); void Out(out string? s) => s = null; void Ref(ref string? s) => s = null; } } ", MaybeNullAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(37014, "https://github.com/dotnet/roslyn/pull/37014")] public void NotNull_CompareExchangeIntoRefNotNullParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; using System.Threading; class C { internal static T InterlockedStore<T>([NotNull] ref T? target, T value) where T : class { return Interlocked.CompareExchange(ref target, value, null) ?? value; } } ", NotNullAttributeDefinition }); c.VerifyDiagnostics(); } [Fact] public void NotNullWhenTrue_FromMetadata() { var lib = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static bool NotNullWhenTrue([NotNullWhen(true)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }); var c = CreateNullableCompilation(@" public class D { public void Main(string? s) { _ = C.NotNullWhenTrue(s) ? s.ToString() : s.ToString(); // 1 } } ", references: new[] { lib.EmitToImageReference() }); c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 15) ); } [Fact] public void NotNullWhenFalse_FromMetadata() { var lib = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static bool NotNullWhenFalse([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }); var c = CreateNullableCompilation(@" public class D { public void Main(string? s) { _ = C.NotNullWhenFalse(s) ? s.ToString() // 1 : s.ToString(); } } ", references: new[] { lib.EmitToImageReference() }); c.VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 15) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(true)] out string? s) { bool b = true; if (b) { s = null; return false; } else { s = """"; return true; } } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNullWhenTrue_EnforceInMethodBody_ConditionalWithThrow() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { static bool M([NotNullWhen(true)] object? o) { return o == null ? true : throw null!; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNullWhenTrue_EnforceInMethodBody_WithMaybeNull_CallingObliviousAPI() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue<T>([MaybeNull] [NotNullWhen(true)] out T t) { return TryGetValue2<T>(out t); } #nullable disable public static bool TryGetValue2<T>(out T t) => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody_Warn() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(true)] out string? s) { bool b = true; if (b) { s = null; return true; // 1 } else { s = """"; return false; } } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,13): error CS8762: Parameter 's' must have a non-null value when exiting with 'true'. // return true; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return true;").WithArguments("s", "true").WithLocation(11, 13) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody_DoNotWarnInLocalFunction() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Reflection; public class C { private static bool TryGetTaskOfTOrValueTaskOfTType(TypeInfo taskTypeInfo, [NotNullWhen(true)] out TypeInfo? taskOfTTypeInfo) { TypeInfo? taskTypeInfoLocal = taskTypeInfo; while (taskTypeInfoLocal != null) { if (IsTaskOfTOrValueTaskOfT(taskTypeInfoLocal)) { taskOfTTypeInfo = taskTypeInfoLocal; return true; } taskTypeInfoLocal = taskTypeInfoLocal.BaseType?.GetTypeInfo(); } taskOfTTypeInfo = null; return false; bool IsTaskOfTOrValueTaskOfT(TypeInfo typeInfo) => typeInfo.IsGenericType && (typeInfo.GetGenericTypeDefinition() == typeof(int)); } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody_InTryFinally() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(true)] out string? s) { try { bool b = true; if (b) { s = """"; return true; } throw null!; } finally { s = null; } } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (13,17): warning CS8762: Parameter 's' must have a non-null value when exiting with 'true'. // return true; Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return true;").WithArguments("s", "true").WithLocation(13, 17) ); } [Fact, WorkItem(42981, "https://github.com/dotnet/roslyn/issues/42981")] public void MaybeNullWhenTrue_EnforceInMethodBody_InTryFinally() { var source = @" using System.Diagnostics.CodeAnalysis; class C { static bool M(bool b, [MaybeNullWhen(true)] out string s) { s = string.Empty; try { if (b) return false; // 1 } finally { s = null; } return true; } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8762: Parameter 's' must have a non-null value when exiting with 'false'. // return false; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return false;").WithArguments("s", "false").WithLocation(11, 15) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody_InTryFinally_Reversed() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(true)] out string? s) { try { bool b = true; if (b) { s = null; return true; } throw null!; } finally { s = """"; } } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenFalse_EnforceInMethodBody_InTryFinally() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(false)] out string? s) { try { bool b = true; if (b) { s = """"; return false; } throw null!; } finally { s = null; } } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (13,17): warning CS8762: Parameter 's' must have a non-null value when exiting with 'false'. // return false; Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return false;").WithArguments("s", "false").WithLocation(13, 17) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody_Warn_NonConstantReturn() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(true)] out string? s) { s = null; return NonConstantBool(); } static bool NonConstantBool() => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922"), WorkItem(44080, "https://github.com/dotnet/roslyn/issues/44080")] public void NotNullWhenFalse_EnforceInMethodBody_Warn_NonConstantReturn() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNullWhen(false)] out string? s) { s = null; return NonConstantBool(); } static bool NonConstantBool() => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922"), WorkItem(42386, "https://github.com/dotnet/roslyn/issues/42386")] public void NotNull_EnforceInMethodBody_Warn() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNull] out string? s) { s = null; return NonConstantBool(); // 1 } public static bool M([NotNull] string? s) { s = null; return NonConstantBool(); // 2 } public static bool M([NotNull] ref string? s) { s = null; return NonConstantBool(); // 3 } static bool NonConstantBool() => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (8,9): warning CS8777: Parameter 's' must have a non-null value when exiting. // return NonConstantBool(); // 1 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return NonConstantBool();").WithArguments("s").WithLocation(8, 9), // (13,9): warning CS8777: Parameter 's' must have a non-null value when exiting. // return NonConstantBool(); // 2 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return NonConstantBool();").WithArguments("s").WithLocation(13, 9), // (18,9): warning CS8777: Parameter 's' must have a non-null value when exiting. // return NonConstantBool(); // 3 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return NonConstantBool();").WithArguments("s").WithLocation(18, 9) ); } [Fact, WorkItem(42386, "https://github.com/dotnet/roslyn/issues/42386")] public void NotNull_EnforceInMethodBody_Warn_TransientAssignmentOkay() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNull] out string? s) { s = null; s = string.Empty; return NonConstantBool(); } static bool NonConstantBool() => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(42386, "https://github.com/dotnet/roslyn/issues/42386")] public void NotNull_EnforceInMethodBody_Warn_TryCatch() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([NotNull] out string? s) { bool b = true; try { if (b) return true; // 1 else return false; // 2 } finally { s = null; } } // 3 } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (12,17): warning CS8777: Parameter 's' must have a non-null value when exiting. // return true; // 1 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return true;").WithArguments("s").WithLocation(12, 17), // (14,17): warning CS8777: Parameter 's' must have a non-null value when exiting. // return false; // 2 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return false;").WithArguments("s").WithLocation(14, 17), // (20,5): warning CS8777: Parameter 's' must have a non-null value when exiting. // } // 3 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("s").WithLocation(20, 5) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void MaybeNullWhenTrue_EnforceInMethodBody() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static bool TryGetValue([MaybeNullWhen(true)] out string s) { bool b = true; if (b) { s = null; return false; // 1 } else { s = """"; return true; } } public static bool TryGetValue2([MaybeNullWhen(true)] out string s) { bool b = true; if (b) { s = """"; return false; } else { s = null; return true; } } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,13): warning CS8762: Parameter 's' must have a non-null value when exiting with 'false'. // return false; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return false;").WithArguments("s", "false").WithLocation(11, 13) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void NotNullWhenTrue_EnforceInMethodBody_OnConversionToBool() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public static implicit operator bool(C? c) => throw null!; public static bool TryGetValue(C? c, [NotNullWhen(true)] out string? s) { s = null; return c; } public static bool TryGetValue2(C c, [NotNullWhen(false)] out string? s) { s = null; return c; } static bool TryGetValue3([MaybeNullWhen(false)]out string s) { s = null; return (bool)true; // 1 } static bool TryGetValue4([MaybeNullWhen(false)]out string s) { s = null; return (bool)false; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (22,9): warning CS8762: Parameter 's' must have a non-null value when exiting with 'true'. // return (bool)true; Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return (bool)true;").WithArguments("s", "true").WithLocation(22, 9) ); } [Fact] public void MaybeNullWhenTrue_OutParameter() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { string s; _ = M(out s) // 1 ? s.ToString() // 2 : s.ToString(); } public static bool M([MaybeNullWhen(true)] out string s) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // _ = M(out s) // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(8, 19), // (9,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 15) ); } [Fact, WorkItem(42735, "https://github.com/dotnet/roslyn/issues/42735")] public void MaybeNullWhenTrue_OutParameter_UnconstrainedT() { var c = CreateNullableCompilation(new[] { @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { public static T M<T>() { GetT<T>(out var t); return t; // 1 } public static T M2<T>() { GetT<T>(out T t); return t; // 2 } public static bool GetT<T>([MaybeNullWhen(true)] out T t) => throw null!; } ", MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (9,16): warning CS8603: Possible null reference return. // return t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(9, 16), // (14,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // GetT<T>(out T t); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T t").WithLocation(14, 21), // (15,16): warning CS8603: Possible null reference return. // return t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(15, 16) ); } [Fact, WorkItem(42735, "https://github.com/dotnet/roslyn/issues/42735")] public void MaybeNullWhenFalse_OutParameter_UnconstrainedT() { var c = CreateNullableCompilation(new[] { @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { public static T M<T>() { GetT<T>(out var t); return t; // 1 } public static T M2<T>() { GetT<T>(out T t); return t; // 2 } public static bool GetT<T>([MaybeNullWhen(false)] out T t) => throw null!; } ", MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (9,16): warning CS8603: Possible null reference return. // return t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(9, 16), // (14,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // GetT<T>(out T t); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T t").WithLocation(14, 21), // (15,16): warning CS8603: Possible null reference return. // return t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(15, 16) ); } [Fact, WorkItem(42735, "https://github.com/dotnet/roslyn/issues/42735")] public void MaybeNull_OutParameter_UnconstrainedT() { var c = CreateNullableCompilation(new[] { @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { public static T M<T>() { GetT<T>(out var t); return t; // 1 } public static T M2<T>() { GetT<T>(out T t); return t; // 2 } public static bool GetT<T>([MaybeNull] out T t) => throw null!; } ", MaybeNullAttributeDefinition }, parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (9,16): warning CS8603: Possible null reference return. // return t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(9, 16), // (15,16): warning CS8603: Possible null reference return. // return t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(15, 16) ); c = CreateNullableCompilation(new[] { @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { public static T? M<T>() { GetT<T>(out var t); return t; } public static T? M2<T>() { GetT<T>(out T? t); return t; } public static bool GetT<T>([MaybeNull] out T t) => throw null!; } ", MaybeNullAttributeDefinition }); c.VerifyDiagnostics(); } [Fact] public void MaybeNull_OutParameter_InConditional() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { string s; _ = M(out s) // 1 ? s.ToString() // 2 : s.ToString(); // 3 } public static bool M([MaybeNull] out string s) => throw null!; } ", MaybeNullAttributeDefinition }, options: WithNullableEnable()); // Warn on misused nullability attributes (M)? https://github.com/dotnet/roslyn/issues/36073 c.VerifyDiagnostics( // (8,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // _ = M(out s) // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(8, 19), // (9,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 15), // (10,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 15) ); } [Fact] public void AllowNull_Parameter_OnPartial() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; partial class C { partial void M1([AllowNull] string s); partial void M1([AllowNull] string s) => throw null!; partial void M2([AllowNull] string s); partial void M2(string s) => throw null!; partial void M3(string s); partial void M3([AllowNull] string s) => throw null!; } ", AllowNullAttributeDefinition }); c.VerifyDiagnostics( // (5,22): error CS0579: Duplicate 'AllowNull' attribute // partial void M1([AllowNull] string s); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "AllowNull").WithArguments("AllowNull").WithLocation(5, 22) ); } [Fact] public void AllowNull_OnInterface() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; interface I { void M1([AllowNull] string s); [return: NotNull] string? M2(); } public class Implicit : I { public void M1(string s) => throw null!; // 1 public string? M2() => throw null!; // 2 } public class Explicit : I { void I.M1(string s) => throw null!; // 3 string? I.M2() => throw null!; // 4 } ", AllowNullAttributeDefinition, NotNullAttributeDefinition }); c.VerifyDiagnostics( // (10,17): warning CS8767: Nullability of reference types in type of parameter 's' of 'void Implicit.M1(string s)' doesn't match implicitly implemented member 'void I.M1(string s)' because of nullability attributes. // public void M1(string s) => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "M1").WithArguments("s", "void Implicit.M1(string s)", "void I.M1(string s)").WithLocation(10, 17), // (11,20): warning CS8766: Nullability of reference types in return type of 'string? Implicit.M2()' doesn't match implicitly implemented member 'string? I.M2()' because of nullability attributes. // public string? M2() => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M2").WithArguments("string? Implicit.M2()", "string? I.M2()").WithLocation(11, 20), // (15,12): warning CS8769: Nullability of reference types in type of parameter 's' doesn't match implemented member 'void I.M1(string s)' because of nullability attributes. // void I.M1(string s) => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "M1").WithArguments("s", "void I.M1(string s)").WithLocation(15, 12), // (16,15): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'string? I.M2()' because of nullability attributes. // string? I.M2() => throw null!; // 4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "M2").WithArguments("string? I.M2()").WithLocation(16, 15) ); } [Fact] public void MaybeNull_RefParameter_InConditional() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { string s = """"; _ = M(ref s) // 1 ? s.ToString() // 2 : s.ToString(); // 3 } public static bool M([MaybeNull] ref string s) => throw null!; } ", MaybeNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // _ = M(ref s) // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(8, 19), // (9,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 15), // (10,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 15) ); } [Fact] public void MaybeNullWhenTrue_RefParameter() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { string s = """"; _ = M(ref s) // 1 ? s.ToString() // 2 : s.ToString(); } public static bool M([MaybeNullWhen(true)] ref string s) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // _ = M(ref s) // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(8, 19), // (9,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 15) ); } [Fact] public void MaybeNullWhenTrue_OnImplicitConversion() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class A { public static implicit operator C(A a) => throw null!; } public class C { public void Main() { A a = new A(); _ = IsNull(a) ? a.ToString() // 1 : a.ToString(); } public static bool IsNull([MaybeNullWhen(true)] C c) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); // This warning is correct because we should be able to infer that `a` may be null when `(C)a` may be null c.VerifyDiagnostics( // (13,15): warning CS8602: Dereference of a possibly null reference. // ? a.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(13, 15) ); } [Fact] public void MaybeNullWhenTrue_OnImplicitConversion_ToNullable() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class A { public static implicit operator C?(A a) => throw null!; } public class C { public void Main() { A a = new A(); _ = IsNull(a) // 1 ? a.ToString() : a.ToString(); } public static bool IsNull([MaybeNullWhen(true)] C c) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); // Unexpected second warning // We should not blindly strip conversions when learning that a value is null. // In this case, we shouldn't infer that `a` may be null from the fact that `(C)a` may be null in the when-true branch. // Tracked by https://github.com/dotnet/roslyn/issues/36164 c.VerifyDiagnostics( // (12,20): warning CS8604: Possible null reference argument for parameter 'c' in 'bool C.IsNull(C c)'. // _ = IsNull(a) // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("c", "bool C.IsNull(C c)").WithLocation(12, 20), // (13,15): warning CS8602: Dereference of a possibly null reference. // ? a.ToString() Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(13, 15) ); } [Fact] public void MaybeNullWhenTrue_OnExplicitConversion() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class A { public static explicit operator C(A a) => throw null!; } public class C { public void Main() { A a = new A(); _ = IsNull((C)a) ? a.ToString() // 1 : a.ToString(); } public static bool IsNull([MaybeNullWhen(true)] C c) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,15): warning CS8602: Dereference of a possibly null reference. // ? a.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(13, 15) ); } [Fact] public void MaybeNull_OnExplicitConversion() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class A { public static explicit operator C(A? a) => throw null!; } public class C { public void Main() { A a = new A(); _ = IsNull((C)a) ? a.ToString() : a.ToString(); } public static bool IsNull([MaybeNull] C c) => throw null!; } ", MaybeNullAttributeDefinition }, options: WithNullableEnable()); // Both diagnostics are unexpected // We should not blindly strip conversions when learning that a value is null. // In this case, we shouldn't infer that `a` may be null from the fact that `(C)a` may be null. // Tracked by https://github.com/dotnet/roslyn/issues/36164 c.VerifyDiagnostics( // (13,15): warning CS8602: Dereference of a possibly null reference. // ? a.ToString() Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(13, 15), // (14,15): warning CS8602: Dereference of a possibly null reference. // : a.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(14, 15) ); } [Fact] public void MaybeNull_Property() { // Warn on redundant nullability attributes (P3, P5)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [MaybeNull]public TOpen P1 { get; set; } = default!; } public class CClass<TClass> where TClass : class { [MaybeNull]public TClass P2 { get; set; } = null!; [MaybeNull]public TClass? P3 { get; set; } = null; } public class CStruct<TStruct> where TStruct : struct { [MaybeNull]public TStruct P4 { get; set; } [MaybeNull]public TStruct? P5 { get; set; } }"; var lib = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, lib_cs }); lib.VerifyDiagnostics(); var source = @" class C { static void M1<T>(T t1) { new COpen<T>().P1 = t1; new COpen<T>().P1.ToString(); // 0, 1 var xOpen = new COpen<T>(); xOpen.P1 = t1; xOpen.P1.ToString(); // 2, 3 var xOpen2 = new COpen<T>(); if (xOpen2.P1 is object) // 4 { xOpen2.P1.ToString(); } } static void M2<T>(T t2) where T : class { new COpen<T>().P1.ToString(); // 5 new CClass<T>().P2.ToString(); // 6 new CClass<T>().P3.ToString(); // 7 } static void M4<T>(T t4) where T : struct { new COpen<T>().P1.ToString(); new CStruct<T>().P4.ToString(); new COpen<T?>().P1.Value.ToString(); // 8 new CStruct<T>().P5.Value.ToString(); // 9 } }"; var expected = new[] { // (7,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>().P1.ToString(); // 0, 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>().P1").WithLocation(7, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // xOpen.P1.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xOpen.P1").WithLocation(11, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>().P1.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>().P1").WithLocation(21, 9), // (22,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>().P2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>().P2").WithLocation(22, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>().P3.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>().P3").WithLocation(23, 9), // (29,9): warning CS8629: Nullable value type may be null. // new COpen<T?>().P1.Value.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new COpen<T?>().P1").WithLocation(29, 9), // (30,9): warning CS8629: Nullable value type may be null. // new CStruct<T>().P5.Value.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new CStruct<T>().P5").WithLocation(30, 9) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, MaybeNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var copenAttributes = copen.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(copenAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableContextAttribute(1)", "System.Runtime.CompilerServices.NullableAttribute(0)" }, copenAttributes); } var property = copen.GetMembers().OfType<PropertySymbol>().Single(); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" }, propertyAttributes); } else { AssertEx.Empty(propertyAttributes); } var getter = property.GetMethod; var getterAttributes = getter.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(getterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, getterAttributes); } var getterReturnAttributes = getter.GetReturnTypeAttributes().Select(a => a.ToString()); Assert.Equal(FlowAnalysisAnnotations.MaybeNull, getter.ReturnTypeFlowAnalysisAnnotations); if (isSource) { AssertEx.Empty(getterReturnAttributes); } else { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" }, getterReturnAttributes); } var setter = property.SetMethod; var setterAttributes = setter.GetAttributes(); if (isSource) { AssertEx.Empty(setterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, setterAttributes.Select(a => a.ToString())); } Assert.Equal(FlowAnalysisAnnotations.None, setter.ReturnTypeFlowAnalysisAnnotations); var setterReturnAttributes = setter.GetReturnTypeAttributes(); AssertEx.Empty(setterReturnAttributes); } } [Fact] public void MaybeNull_Property_InCompoundAssignment() { var source = @" using System.Diagnostics.CodeAnalysis; class C { [MaybeNull] C Property { get; set; } = null!; public static C operator+(C one, C other) => throw null!; void M(C c) { Property += c; // 1 } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,9): warning CS8604: Possible null reference argument for parameter 'one' in 'C C.operator +(C one, C other)'. // Property += c; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "Property").WithArguments("one", "C C.operator +(C one, C other)").WithLocation(10, 9) ); } [Fact, WorkItem(36073, "https://github.com/dotnet/roslyn/issues/36073")] public void MaybeNull_Property_WithNotNull() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [MaybeNull, NotNull]public TOpen P1 { get; set; } = default!; }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, NotNullAttributeDefinition, source }); comp.VerifyDiagnostics(); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var copenAttributes = copen.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(copenAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableContextAttribute(1)", "System.Runtime.CompilerServices.NullableAttribute(0)" }, copenAttributes); } var property = copen.GetMembers().OfType<PropertySymbol>().Single(); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.MaybeNullAttribute", "System.Diagnostics.CodeAnalysis.NotNullAttribute" }, propertyAttributes); } else { AssertEx.Empty(propertyAttributes); } var getter = property.GetMethod; var getterAttributes = getter.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(getterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, getterAttributes); } var getterReturnAttributes = getter.GetReturnTypeAttributes().Select(a => a.ToString()); Assert.Equal(FlowAnalysisAnnotations.MaybeNull | FlowAnalysisAnnotations.NotNull, getter.ReturnTypeFlowAnalysisAnnotations); if (isSource) { AssertEx.Empty(getterReturnAttributes); } else { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.MaybeNullAttribute", "System.Diagnostics.CodeAnalysis.NotNullAttribute" }, getterReturnAttributes); } } } [Fact] public void MaybeNull_Property_WithExpressionBody() { // Warn on misused nullability attributes (P3, P5)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [MaybeNull]public TOpen P1 => throw null!; } public class CClass<TClass> where TClass : class { [MaybeNull]public TClass P2 => throw null!; [MaybeNull]public TClass? P3 => throw null!; } public class CStruct<TStruct> where TStruct : struct { [MaybeNull]public TStruct P4 => throw null!; [MaybeNull]public TStruct? P5 => throw null!; }"; var lib = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, lib_cs }); lib.VerifyDiagnostics(); var source = @" class C { static void M1<T>(T t1) { new COpen<T>().P1.ToString(); // 0, 1 } static void M2<T>(T t2) where T : class { new COpen<T>().P1.ToString(); // 2 new CClass<T>().P2.ToString(); // 3 new CClass<T>().P3.ToString(); // 4 } static void M4<T>(T t4) where T : struct { new COpen<T>().P1.ToString(); new CStruct<T>().P4.ToString(); new COpen<T?>().P1.Value.ToString(); // 5 new CStruct<T>().P5.Value.ToString(); // 6 } }"; var expected = new[] { // (6,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>().P1.ToString(); // 0, 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>().P1").WithLocation(6, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>().P1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>().P1").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>().P2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>().P2").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>().P3.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>().P3").WithLocation(12, 9), // (18,9): warning CS8629: Nullable value type may be null. // new COpen<T?>().P1.Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new COpen<T?>().P1").WithLocation(18, 9), // (19,9): warning CS8629: Nullable value type may be null. // new CStruct<T>().P5.Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new CStruct<T>().P5").WithLocation(19, 9) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, MaybeNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void MaybeNull_Property_OnVirtualProperty() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [MaybeNull] public virtual string P => throw null!; public virtual string P2 => throw null!; } public class C : Base { public override string P => throw null!; [MaybeNull] public override string P2 => throw null!; // 0 static void M(C c, Base b) { b.P.ToString(); // 1 c.P.ToString(); b.P2.ToString(); c.P2.ToString(); // 2 } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,46): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [MaybeNull] public override string P2 => throw null!; // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "throw null!").WithLocation(11, 46), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.P").WithLocation(15, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // c.P2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P2").WithLocation(19, 9) ); } [Fact] public void MaybeNull_Property_OnVirtualProperty_OnlyOverridingSetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [MaybeNull] public virtual string P { get { throw null!; } set { throw null!; } } public virtual string P2 { get { throw null!; } set { throw null!; } } } public class C : Base { public override string P { set { throw null!; } } [MaybeNull] public override string P2 { set { throw null!; } } static void M(C c, Base b) { b.P.ToString(); // 1 c.P.ToString(); // 2 b.P2.ToString(); c.P2.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // b.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.P").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(16, 9) ); } [Fact] public void MaybeNull_Property_OnVirtualProperty_OnlyOverridingGetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [MaybeNull] public virtual string P { get { throw null!; } set { throw null!; } } public virtual string P2 { get { throw null!; } set { throw null!; } } } public class C : Base { public override string P { get { throw null!; } } [MaybeNull] public override string P2 { get { throw null!; } } // 0 static void M(C c, Base b) { b.P.ToString(); // 1 c.P.ToString(); b.P2.ToString(); c.P2.ToString(); // 2 } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,45): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [MaybeNull] public override string P2 { get { throw null!; } } // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(11, 45), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.P").WithLocation(15, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // c.P2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P2").WithLocation(19, 9) ); } [Fact] public void MaybeNull_Property_InDeconstructionAssignment_UnconstrainedGeneric() { var source = @"using System.Diagnostics.CodeAnalysis; public class C<T> { [MaybeNull] public T P { get; set; } = default!; void M(C<T> c, T t) { (c.P, _) = (t, 1); c.P.ToString(); // 1, 2 (c.P, _) = c; c.P.ToString(); // 3, 4 } void Deconstruct(out T x, out T y) => throw null!; }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(9, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(12, 9) ); } [Fact] public void MaybeNull_Indexer() { // Warn on redundant nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [MaybeNull]public TOpen this[int i] { get => throw null!; } } public class CClass<TClass> where TClass : class { [MaybeNull]public TClass this[int i] { get => throw null!; } } public class CClass2<TClass> where TClass : class { [MaybeNull]public TClass? this[int i] { get => throw null!; } } public class CStruct<TStruct> where TStruct : struct { [MaybeNull]public TStruct this[int i] { get => throw null!; } } public class CStruct2<TStruct> where TStruct : struct { [MaybeNull]public TStruct? this[int i] { get => throw null!; } }"; var lib = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, lib_cs }); var source = @" class C { static void M1<T>(T t1) { new COpen<T>()[0].ToString(); // 1 } static void M2<T>(T t2) where T : class { new COpen<T>()[0].ToString(); // 2 new CClass<T>()[0].ToString(); // 3 new CClass2<T>()[0].ToString(); // 4 } static void M4<T>(T t4) where T : struct { new COpen<T>()[0].ToString(); new CStruct<T>()[0].ToString(); new COpen<T?>()[0].Value.ToString(); // 5 new CStruct2<T>()[0].Value.ToString(); // 6 } }"; var expected = new[] { // (6,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>()[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>()[0]").WithLocation(6, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>()[0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>()[0]").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>()[0].ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>()[0]").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // new CClass2<T>()[0].ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass2<T>()[0]").WithLocation(12, 9), // (18,9): warning CS8629: Nullable value type may be null. // new COpen<T?>()[0].Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new COpen<T?>()[0]").WithLocation(18, 9), // (19,9): warning CS8629: Nullable value type may be null. // new CStruct2<T>()[0].Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new CStruct2<T>()[0]").WithLocation(19, 9) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, MaybeNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void MaybeNull_Indexer_OnVirtualIndexer_OnlyOverridingSetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [MaybeNull] public virtual string this[int i] { get { throw null!; } set { throw null!; } } public virtual string this[byte i] { get { throw null!; } set { throw null!; } } } public class C : Base { public override string this[int i] { set { throw null!; } } [MaybeNull] public override string this[byte i] { set { throw null!; } } static void M(C c, Base b) { b[(int)0].ToString(); // 1 c[(int)0].ToString(); // 2 b[(byte)0].ToString(); c[(byte)0].ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // b[(int)0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[(int)0]").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // c[(int)0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[(int)0]").WithLocation(16, 9) ); } [Fact] public void MaybeNull_Indexer_OnVirtualIndexer_OnlyOverridingGetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [MaybeNull] public virtual string this[int i] { get { throw null!; } set { throw null!; } } public virtual string this[byte i] { get { throw null!; } set { throw null!; } } } public class C : Base { public override string this[int i] { get { throw null!; } } [MaybeNull] public override string this[byte i] { get { throw null!; } } // 0 static void M(C c, Base b) { b[(int)0].ToString(); // 1 c[(int)0].ToString(); b[(byte)0].ToString(); c[(byte)0].ToString(); // 2 } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,55): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [MaybeNull] public override string this[byte i] { get { throw null!; } } // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(11, 55), // (15,9): warning CS8602: Dereference of a possibly null reference. // b[(int)0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[(int)0]").WithLocation(15, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // c[(byte)0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[(byte)0]").WithLocation(19, 9) ); } [Fact] public void MaybeNull_Indexer_Implementation() { var source = @"using System.Diagnostics.CodeAnalysis; public class CClass<TClass> where TClass : class { [MaybeNull]public TClass this[int i] { get => null; } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNull_Field() { // Warn on misused nullability attributes (f2, f3, f4, f5)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [MaybeNull]public TOpen f1 = default!; } public class CClass<TClass> where TClass : class { [MaybeNull]public TClass f2 = null!; [MaybeNull]public TClass? f3 = null; } public class CStruct<TStruct> where TStruct : struct { [MaybeNull]public TStruct f4; [MaybeNull]public TStruct? f5; } "; var lib = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, lib_cs }); var source = @" using System.Diagnostics.CodeAnalysis; class C { static void M1<T>([MaybeNull]T t1) { new COpen<T>().f1 = t1; new COpen<T>().f1.ToString(); // 0, 1 var xOpen = new COpen<T>(); xOpen.f1 = t1; xOpen.f1.ToString(); // 2, 3 var xOpen2 = new COpen<T>(); xOpen2.f1.ToString(); // 4, 5 xOpen2.f1.ToString(); var xOpen3 = new COpen<T>(); if (xOpen3.f1 is object) // 6 { xOpen3.f1.ToString(); } } static void M2<T>() where T : class { new COpen<T>().f1.ToString(); // 7 new CClass<T>().f2.ToString(); // 8 new CClass<T>().f3.ToString(); // 9 } static void M4<T>(T t4) where T : struct { new COpen<T>().f1.ToString(); new CStruct<T>().f4.ToString(); new CStruct<T>().f5.Value.ToString(); // 10 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>().f1.ToString(); // 0, 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>().f1").WithLocation(8, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // xOpen.f1.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xOpen.f1").WithLocation(12, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // xOpen2.f1.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xOpen2.f1").WithLocation(15, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // new COpen<T>().f1.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new COpen<T>().f1").WithLocation(26, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>().f2.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>().f2").WithLocation(27, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // new CClass<T>().f3.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new CClass<T>().f3").WithLocation(28, 9), // (34,9): warning CS8629: Nullable value type may be null. // new CStruct<T>().f5.Value.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new CStruct<T>().f5").WithLocation(34, 9) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, MaybeNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var field = copen.GetMembers().OfType<FieldSymbol>().Single(); var fieldAttributes = field.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" }, fieldAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableAttribute(1)", "System.Diagnostics.CodeAnalysis.MaybeNullAttribute" }, fieldAttributes); } } } [Fact] public void MaybeNull_Field_WithAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [MaybeNull] string f1 = """"; void M() { f1.ToString(); // 1 f1 = """"; f1.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // f1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "f1").WithLocation(7, 9) ); } [Fact] public void MaybeNull_Field_WithAssignment_NullableInt() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [MaybeNull] int? f1 = 1; void M() { f1.Value.ToString(); // 1 f1 = 2; f1.Value.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (7,9): warning CS8629: Nullable value type may be null. // f1.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "f1").WithLocation(7, 9) ); } [Fact] public void MaybeNull_Field_WithContainerAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [MaybeNull] public string f1 = """"; void M(C c) { c.f1.ToString(); // 1 c.f1 = """"; c = new C(); c.f1.ToString(); // 2 } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // c.f1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.f1").WithLocation(7, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // c.f1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.f1").WithLocation(11, 9) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/37217"), WorkItem(36830, "https://github.com/dotnet/roslyn/issues/36830")] public void MaybeNull_Field_InDebugAssert() { var source = @"using System.Diagnostics.CodeAnalysis; class C { [MaybeNull] string? f1 = """"; void M() { System.Diagnostics.Debug.Assert(f1 != null); f1.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNull_Field_WithContainerAssignment_NullableInt() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [MaybeNull] public int? f1 = 1; void M(C c) { c.f1.Value.ToString(); // 1 c.f1 = 2; c = new C(); c.f1.Value.ToString(); // 2 } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (7,9): warning CS8629: Nullable value type may be null. // c.f1.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.f1").WithLocation(7, 9), // (11,9): warning CS8629: Nullable value type may be null. // c.f1.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.f1").WithLocation(11, 9) ); } [Fact] public void MaybeNullWhenTrue_OnImplicitReferenceConversion() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class A : Base { } public class Base { public void Main() { A a = new A(); _ = IsNull(a) ? a.ToString() // 1 : a.ToString(); } public static bool IsNull([MaybeNullWhen(true)] Base b) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // ? a.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(12, 15) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void MaybeNullWhenTrue_EqualsTrue() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (IsNull(s) == true) { s.ToString(); // warn } else { s.ToString(); // ok } s.ToString(); // ok } public static bool IsNull([MaybeNullWhen(true)] string s) => throw null!; } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void IsNullEqualsTrue() { var c = CreateNullableCompilation(@" class C { void M(string s) { if ((s is null) == true) s.ToString(); // 1 else s.ToString(); } void M2(string s) { if (true == (s is null)) s.ToString(); // 2 else s.ToString(); } } "); c.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 13) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void IsNullEqualsTrueEqualsFalse() { var c = CreateNullableCompilation(@" class C { void M(string s) { if (((s is null) == true) == false) s.ToString(); else s.ToString(); // 1 } void M2(string s) { if (false == (true == (s is null))) s.ToString(); else s.ToString(); // 2 } } "); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 13) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void IsNullEqualsFalse() { var c = CreateNullableCompilation(@" class C { void M(string s) { if ((s is null) == false) s.ToString(); else s.ToString(); // 1 } void M2(string s) { if (false == (s is null)) s.ToString(); else s.ToString(); // 2 } } "); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 13) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void IsNullNotEqualsTrue() { var c = CreateNullableCompilation(@" class C { void M(string s) { if ((s is null) != true) s.ToString(); else s.ToString(); // 1 } void M2(string s) { if (true != (s is null)) s.ToString(); else s.ToString(); // 2 } } "); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 13) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void IsNullNotEqualsFalse() { var c = CreateNullableCompilation(@" class C { void M(string s) { if ((s is null) != false) s.ToString(); // 1 else s.ToString(); } void M2(string s) { if (false != (s is null)) s.ToString(); // 2 else s.ToString(); } } "); c.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 13) ); } [Fact, WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void OnlySwapConditionalStatesWhenInConditionalState() { var c = CreateNullableCompilation(@" class C { void M(bool b) { if (b == (true != b)) { } } } "); c.VerifyDiagnostics(); } [Fact, WorkItem(41107, "https://github.com/dotnet/roslyn/issues/41107")] public void NullConditionalEqualsTrue() { var c = CreateNullableCompilation(new[] { @" public class C { public C? field; public bool value; static public void M(C c) { if (c.field?.value == true) { c.field.ToString(); } else { c.field.ToString(); // 1 } } static public void M2(C c) { if (false == c.field?.value) { c.field.ToString(); } else { c.field.ToString(); // 2 } } } ", NotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (15,13): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(15, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(27, 13) ); } [Fact, WorkItem(41107, "https://github.com/dotnet/roslyn/issues/41107")] public void EqualsComplicatedTrue() { var c = CreateNullableCompilation(new[] { @" public class C { public C? field; public bool value; static C? MaybeNull() => throw null!; static public void M(C c) { if ((c.field is null) == (true || MaybeNull()?.value == true)) { c.field.ToString(); // 1 } else { c.field.ToString(); // 2 } } static public void M2(C c) { if ((false && MaybeNull()?.value == true) == (c.field is null)) { c.field.ToString(); // 3 } else { c.field.ToString(); // 4 } } } ", NotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(13, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(17, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(25, 13), // (29,13): warning CS8602: Dereference of a possibly null reference. // c.field.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.field").WithLocation(29, 13) ); } [Fact, WorkItem(41107, "https://github.com/dotnet/roslyn/issues/41107")] public void NullConditionalWithExtensionMethodEqualsTrue() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public C? field; static public void M(C c) { if (c.field?.field.IsKind() == true) { c.field.field.ToString(); } } static public void M2(C c) { if (true == c.field?.field.IsKind()) { c.field.field.ToString(); } } static public void M3(C c) { if (Extension.IsKind(c.field?.field) == true) { c.field.field.ToString(); } } } public static class Extension { public static bool IsKind([NotNullWhen(true)] this C? c) { throw null!; } } ", NotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact] public void MaybeNullWhenTrue_MaybeNullInitialState() { // Warn on redundant nullability attributes (warn on IsNull)? https://github.com/dotnet/roslyn/issues/36073 var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (IsNull(s)) { s.ToString(); // 1 } else { s.ToString(); // 2 } } public static bool IsNull([MaybeNullWhen(true)] string? s) => throw null!; } ", MaybeNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); } [Fact] public void MaybeNullWhenTrue_MaybeNullWhenFalseOnSameParameter() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (IsNull(s)) { s.ToString(); // 1 } else { s.ToString(); // MaybeNullWhen(false) was ignored } } public static bool IsNull([MaybeNullWhen(true), MaybeNullWhen(false)] string s) => throw null!; // 2 } ", MaybeNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (16,53): error CS0579: Duplicate 'MaybeNullWhen' attribute // public static bool IsNull([MaybeNullWhen(true), MaybeNullWhen(false)] string s) => throw null!; // 2 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "MaybeNullWhen").WithArguments("MaybeNullWhen").WithLocation(16, 53) ); } [Fact] public void MaybeNullWhenTrue_MaybeNullOnSameParameter() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (IsNull(s)) { s.ToString(); // 1 } else { s.ToString(); // 2 } } public static bool IsNull([MaybeNullWhen(true), MaybeNull] string s) => throw null!; } ", MaybeNullWhenAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); } [Fact] public void MaybeNullWhenTrue_NotNullWhenTrueOnSecondParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (M(s, s)) { s.ToString(); } else { s.ToString(); } s.ToString(); } public static bool M([MaybeNullWhen(true)] string s, [NotNullWhen(true)] string s2) => throw null!; } ", MaybeNullWhenAttributeDefinition, NotNullWhenAttributeDefinition }); // post-condition attributes are applied on arguments left-to-right c.VerifyDiagnostics(); } [Fact] public void NotNullWhenTrue_MaybeNullWhenTrueOnSecondParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (M(s, s)) { s.ToString(); // 1 } else { s.ToString(); } } public static bool M([NotNullWhen(true)] string s, [MaybeNullWhen(true)] string s2) => throw null!; } ", MaybeNullWhenAttributeDefinition, NotNullWhenAttributeDefinition }); // Warn on redundant nullability attributes (warn on first parameter of M)? https://github.com/dotnet/roslyn/issues/36073 // post-condition attributes are applied on arguments left-to-right c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullWhenFalse_MaybeNullWhenFalseOnSecondParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s) { if (M(s, s)) { s.ToString(); } else { s.ToString(); // 1 } } public static bool M([NotNullWhen(false)] string s, [MaybeNullWhen(false)] string s2) => throw null!; } ", MaybeNullWhenAttributeDefinition, NotNullWhenAttributeDefinition }); // Warn on redundant nullability attributes (warn on first parameter of M)? https://github.com/dotnet/roslyn/issues/36073 // post-condition attributes are applied on arguments left-to-right c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); } [Fact] public void MaybeNullWhenFalse_NotNullWhenFalseOnSecondParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (M(s, s)) { s.ToString(); // 1 } else { s.ToString(); } } public static bool M([MaybeNullWhen(false)] string? s, [NotNullWhen(false)] string? s2) => throw null!; } ", MaybeNullWhenAttributeDefinition, NotNullWhenAttributeDefinition }); // Warn on redundant nullability attributes (warn on first parameter of M)? https://github.com/dotnet/roslyn/issues/36073 // post-condition attributes are applied on arguments left-to-right c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullWhenTrue_RefParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { string? s = null; _ = M(ref s) ? s.ToString() : s.ToString(); // 1 } public static bool M([NotNullWhen(true)] ref string? s) => throw null!; } ", NotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 15) ); } [Fact] public void NotNullWhenFalse_OutParameter_MiscTypes() { // Warn on redundant nullability attributes (F2, F4)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool F1<T>(T t, [NotNullWhen(false)]out T t2) => throw null!; static bool F2<T>(T t, [NotNullWhen(false)]out T t2) where T : class => throw null!; static bool F3<T>(T t, [NotNullWhen(false)]out T? t2) where T : class => throw null!; static bool F4<T>(T t, [NotNullWhen(false)]out T t2) where T : struct => throw null!; static bool F5<T>(T? t, [NotNullWhen(false)]out T? t2) where T : struct => throw null!; static void M1<T>(T t1) { _ = F1(t1, out var s2) ? s2.ToString() // 1 : s2.ToString(); } static void M2<T>(T t2) where T : class { _ = F1(t2, out var s3) ? s3.ToString() : s3.ToString(); _ = F2(t2, out var s4) ? s4.ToString() : s4.ToString(); _ = F3(t2, out var s5) ? s5.ToString() // 2 : s5.ToString(); t2 = null; // 3 _ = F1(t2, out var s6) ? s6.ToString() // 4 : s6.ToString(); _ = F2(t2, out var s7) // 5 ? s7.ToString() // 6 : s7.ToString(); _ = F3(t2, out var s8) // 7 ? s8.ToString() // 8 : s8.ToString(); } static void M3<T>(T? t3) where T : class { _ = F1(t3, out var s9) ? s9.ToString() // 9 : s9.ToString(); _ = F2(t3, out var s10) // 10 ? s10.ToString() // 11 : s10.ToString(); _ = F3(t3, out var s11) // 12 ? s11.ToString() // 13 : s11.ToString(); if (t3 == null) return; _ = F1(t3, out var s12) ? s12.ToString() : s12.ToString(); _ = F2(t3, out var s13) ? s13.ToString() : s13.ToString(); _ = F3(t3, out var s14) ? s14.ToString() // 14 : s14.ToString(); } static void M4<T>(T t4) where T : struct { _ = F1(t4, out var s15) ? s15.ToString() : s15.ToString(); _ = F4(t4, out var s16) ? s16.ToString() : s16.ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1(t5, out var s17) ? s17.Value // 15 : s17.Value; _ = F5(t5, out var s18) ? s18.Value // 16 : s18.Value; if (t5 == null) return; _ = F1(t5, out var s19) ? s19.Value // 17 : s19.Value; _ = F5(t5, out var s20) ? s20.Value // 18 : s20.Value; } }"; var comp = CreateNullableCompilation(new[] { NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // ? s2.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // ? s5.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(26, 15), // (29,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(29, 14), // (31,15): warning CS8602: Dereference of a possibly null reference. // ? s6.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(31, 15), // (34,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F2(t2, out var s7) // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(34, 13), // (35,15): warning CS8602: Dereference of a possibly null reference. // ? s7.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s7").WithLocation(35, 15), // (38,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F3(t2, out var s8) // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(38, 13), // (39,15): warning CS8602: Dereference of a possibly null reference. // ? s8.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s8").WithLocation(39, 15), // (45,15): warning CS8602: Dereference of a possibly null reference. // ? s9.ToString() // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s9").WithLocation(45, 15), // (48,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F2(t3, out var s10) // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(48, 13), // (49,15): warning CS8602: Dereference of a possibly null reference. // ? s10.ToString() // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s10").WithLocation(49, 15), // (52,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = F3(t3, out var s11) // 12 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(52, 13), // (53,15): warning CS8602: Dereference of a possibly null reference. // ? s11.ToString() // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s11").WithLocation(53, 15), // (66,15): warning CS8602: Dereference of a possibly null reference. // ? s14.ToString() // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s14").WithLocation(66, 15), // (82,15): warning CS8629: Nullable value type may be null. // ? s17.Value // 15 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s17").WithLocation(82, 15), // (86,15): warning CS8629: Nullable value type may be null. // ? s18.Value // 16 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s18").WithLocation(86, 15), // (91,15): warning CS8629: Nullable value type may be null. // ? s19.Value // 17 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s19").WithLocation(91, 15), // (95,15): warning CS8629: Nullable value type may be null. // ? s20.Value // 18 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s20").WithLocation(95, 15) ); } [Fact] public void NotNullWhenFalse_OutParameter() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { string? s; _ = M(out s) ? s.ToString() // 1 : s.ToString(); } public static bool M([NotNullWhen(false)] out string? s) => throw null!; } ", NotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 15) ); } [Fact] [WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void NotNullWhenFalse_EqualsTrue() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (MyIsNullOrEmpty(s) == true) { s.ToString(); // warn } else { s.ToString(); // ok } s.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullWhenFalse_Nested() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (MyIsNullOrEmpty(s?.ToString())) { s.ToString(); // warn } else { s.ToString(); } } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact, WorkItem(32335, "https://github.com/dotnet/roslyn/issues/32335")] public void NotNullWhenTrue_LearnFromNonNullTest() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void M(C? c1) { if (MyIsNullOrEmpty(c1?.Method())) c1.ToString(); // 1 else c1.ToString(); } C? Method() => throw null!; static bool MyIsNullOrEmpty([NotNullWhen(false)] C? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(8, 13) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void NotNullWhenFalse_EqualsTrue_InErrorInvocation() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (Missing(MyIsNullOrEmpty(s))) { s.ToString(); // 1 } else { s.ToString(); // 2 } s.ToString(); } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,13): error CS0103: The name 'Missing' does not exist in the current context // if (Missing(MyIsNullOrEmpty(s))) Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(7, 13), // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); } [Fact] [WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void NotNullWhenFalse_EqualsFalse() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (false == MyIsNullOrEmpty(s)) { s.ToString(); // ok } else { s.ToString(); // warn } s.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); } [Fact] [WorkItem(29855, "https://github.com/dotnet/roslyn/issues/29855")] public void NotNullWhenFalse_NotEqualsFalse() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (false != MyIsNullOrEmpty(s)) { s.ToString(); // warn } else { s.ToString(); // ok } s.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullWhenFalse_RequiresBoolReturn() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static object MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); VerifyAnnotations(c, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_RequiresBoolReturn_OnGenericMethod() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s) { if (MyIsNullOrEmpty(s, true)) { s.ToString(); // warn } else { s.ToString(); // ok } } public static T MyIsNullOrEmpty<T>([NotNullWhen(false)] string? s, T t) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullIfNotNull_Return() { // NotNullIfNotNull isn't enforced in scenarios like the following var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M(string? p) => null; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1).ToString(); c.M(p2).ToString(); // 1 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2)").WithLocation(8, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact, WorkItem(49077, "https://github.com/dotnet/roslyn/issues/49077")] public void NotNullIfNotNull_Return_Async() { var source = @" using System.Threading.Tasks; using System.Diagnostics.CodeAnalysis; string notNull = """"; var res = await C.M(notNull); res.ToString(); // 1 res = await C.M(null); // 2 res.ToString(); // 3 res = await C.M2(notNull); res.ToString(); // 4 public class C { [return: NotNullIfNotNull(""s1"")] public static async Task<string?>? M(string? s1) { await Task.Yield(); if (s1 is null) return null; else return null; } [return: NotNullIfNotNull(""s1"")] public static Task<string?>? M2(string? s1) { if (s1 is null) return null; else return null; // 5 } } "; var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }, options: TestOptions.DebugExe.WithNullableContextOptions(NullableContextOptions.Enable)); comp.VerifyDiagnostics( // (7,1): warning CS8602: Dereference of a possibly null reference. // res.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "res").WithLocation(7, 1), // (9,13): warning CS8602: Dereference of a possibly null reference. // res = await C.M(null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C.M(null)").WithLocation(9, 13), // (10,1): warning CS8602: Dereference of a possibly null reference. // res.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "res").WithLocation(10, 1), // (13,1): warning CS8602: Dereference of a possibly null reference. // res.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "res").WithLocation(13, 1), // (33,13): warning CS8825: Return value must be non-null because parameter 's1' is non-null. // return null; // 5 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;").WithArguments("s1").WithLocation(33, 13) ); } [Fact, WorkItem(49077, "https://github.com/dotnet/roslyn/issues/49077")] public void NotNullIfNotNull_Parameter_Async() { var source = @" using System.Threading.Tasks; using System.Diagnostics.CodeAnalysis; public class C { public async Task M([NotNullIfNotNull(""s2"")] string? s1, string? s2) { await Task.Yield(); if (s2 is object) { return; // 1 } } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (12,13): warning CS8824: Parameter 's1' must have a non-null value when exiting because parameter 's2' is non-null. // return; // 1 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return;").WithArguments("s1", "s2").WithLocation(12, 13) ); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Return_Checked_01() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M0(string? p) { if (p is null) { return null; } if (p is object) { return null; // 1 } if (p is object) { return M1(); // 2 } if (p is object) { return p; } p = ""a""; return M1(); // 3 } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return null; // 1 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;", isSuppressed: false).WithArguments("p").WithLocation(15, 13), // (20,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return M1(); // 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return M1();", isSuppressed: false).WithArguments("p").WithLocation(20, 13), // (29,9): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return M1(); // 3 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return M1();", isSuppressed: false).WithArguments("p").WithLocation(29, 9)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Return_Checked_02() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] [return: NotNullIfNotNull(""q"")] public string? M0(string? p, string? q, string? s) { if (p is object || q is object) { return null; } if (p is null || q is null) { return null; } if (p is object && q is object) { return null; // 1 } if (p is object && q is object) { return M1(); // 2 } if (p is object && s is object) { return M1(); // 3 } if (s is object) { return null; } if (p is null && q is null) { return null; } return M1(); } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (21,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return null; // 1 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;", isSuppressed: false).WithArguments("p").WithLocation(21, 13), // (26,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return M1(); // 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return M1();", isSuppressed: false).WithArguments("p").WithLocation(26, 13), // (31,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return M1(); // 3 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return M1();", isSuppressed: false).WithArguments("p").WithLocation(31, 13)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Return_Checked_03() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] [return: NotNullIfNotNull(""q"")] public string? M0(string? p, string? q) { if (q is null) { return null; } else if (p is null) { return null; // 1 } return M1(); // 2 } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,13): warning CS8825: Return value must be non-null because parameter 'q' is non-null. // return null; // 1 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;", isSuppressed: false).WithArguments("q").WithLocation(15, 13), // (18,9): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return M1(); // 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return M1();", isSuppressed: false).WithArguments("p").WithLocation(18, 9)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Return_Checked_04() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""t"")] public T? M0<T>(T? t) { if (t is object) { return default; // 1 } if (t is object) { return t; } if (t is null) { return default; } return t; } [return: NotNullIfNotNull(""t"")] public T M1<T>(T t) { if (t is object) { return default; // 2, 3 } if (t is object) { return t; } if (t is null) { return default; // 4 } if (t is null) { return t; // should give WRN_NullReferenceReturn: https://github.com/dotnet/roslyn/issues/47646 } return t; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,13): warning CS8825: Return value must be non-null because parameter 't' is non-null. // return default; // 1 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return default;", isSuppressed: false).WithArguments("t").WithLocation(10, 13), // (31,13): warning CS8825: Return value must be non-null because parameter 't' is non-null. // return default; // 2, 3 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return default;", isSuppressed: false).WithArguments("t").WithLocation(31, 13), // (31,20): warning CS8603: Possible null reference return. // return default; // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default", isSuppressed: false).WithLocation(31, 20), // (41,20): warning CS8603: Possible null reference return. // return default; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default", isSuppressed: false).WithLocation(41, 20)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Param_Checked_01() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public void M0(string? p, [NotNullIfNotNull(""p"")] out string? pOut) { if (p is object) { pOut = p; return; } if (p is object) { pOut = null; return; // 1 } if (p is null) { pOut = null; return; } pOut = M1(); } // 2 string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (16,13): warning CS8824: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return; // 1 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return;", isSuppressed: false).WithArguments("pOut", "p").WithLocation(16, 13), // (26,5): warning CS8824: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // } // 2 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "}", isSuppressed: false).WithArguments("pOut", "p").WithLocation(26, 5)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_ParamAndReturn_Checked_01() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M0(string? p, [NotNullIfNotNull(""p"")] out string? pOut) { if (p is object) { pOut = null; return p; // 1 } if (p is object) { pOut = p; return null; // 2 } if (p is object) { pOut = null; return null; // 3, 4 } if (p is null) { pOut = null; return null; } pOut = M1(); return pOut; // 5, 6 } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,13): warning CS8824: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return p; // 1 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return p;", isSuppressed: false).WithArguments("pOut", "p").WithLocation(11, 13), // (17,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return null; // 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;", isSuppressed: false).WithArguments("p").WithLocation(17, 13), // (23,13): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return null; // 3, 4 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;", isSuppressed: false).WithArguments("p").WithLocation(23, 13), // (23,13): warning CS8824: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return null; // 3, 4 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return null;", isSuppressed: false).WithArguments("pOut", "p").WithLocation(23, 13), // (33,9): warning CS8825: Return value must be non-null because parameter 'p' is non-null. // return pOut; // 5, 6 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return pOut;", isSuppressed: false).WithArguments("p").WithLocation(33, 9), // (33,9): warning CS8824: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return pOut; // 5, 6 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return pOut;", isSuppressed: false).WithArguments("pOut", "p").WithLocation(33, 9)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_NestedLambda_01() { var source = @" using System; using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M0(string? p, [NotNullIfNotNull(""p"")] string? pOut) { Func<string?> a = () => { if (p is object) { pOut = null; return p; } if (p is object) { pOut = p; return null; } if (p is object) { pOut = null; return null; } if (p is null) { pOut = null; return null; } pOut = M1(); return pOut; }; if (p is object) { return null; // 1, 2 } return p; } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (41,13): warning CS8826: Return value must be non-null because parameter 'p' is non-null. // return null; // 1, 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;").WithArguments("p").WithLocation(41, 13), // (41,13): warning CS8825: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return null; // 1, 2 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return null;").WithArguments("pOut", "p").WithLocation(41, 13)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_NestedLocalFunction_01() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M0(string? p, [NotNullIfNotNull(""p"")] string? pOut) { string? local1() { if (p is object) { pOut = null; return p; } if (p is object) { pOut = p; return null; } if (p is object) { pOut = null; return null; } if (p is null) { pOut = null; return null; } pOut = M1(); return pOut; } if (p is object) { return local1(); // 1, 2 } return p; } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (40,13): warning CS8826: Return value must be non-null because parameter 'p' is non-null. // return local1(); // 1, 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return local1();").WithArguments("p").WithLocation(40, 13), // (40,13): warning CS8825: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return local1(); // 1, 2 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return local1();").WithArguments("pOut", "p").WithLocation(40, 13)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_NestedLocalFunction_02() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public string M0() { [return: NotNullIfNotNull(""p"")] string? local1(string? p, [NotNullIfNotNull(""p"")] string? pOut) { if (p is object) { pOut = null; return p; // 1 } if (p is object) { pOut = p; return null; // 2 } if (p is object) { pOut = null; return null; // 3, 4 } if (p is null) { pOut = null; return null; } pOut = M1(); return pOut; // 5, 6 } return local1(""a"", null); } string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); // NotNullIfNotNull enforcement doesn't work on parameters of local functions // https://github.com/dotnet/roslyn/issues/47896 comp.VerifyDiagnostics( // (19,17): warning CS8826: Return value must be non-null because parameter 'p' is non-null. // return null; // 2 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;").WithArguments("p").WithLocation(19, 17), // (25,17): warning CS8826: Return value must be non-null because parameter 'p' is non-null. // return null; // 3, 4 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return null;").WithArguments("p").WithLocation(25, 17), // (35,13): warning CS8826: Return value must be non-null because parameter 'p' is non-null. // return pOut; // 5, 6 Diagnostic(ErrorCode.WRN_ReturnNotNullIfNotNull, "return pOut;").WithArguments("p").WithLocation(35, 13)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Constructor_01() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public C(string? p, [NotNullIfNotNull(""p"")] out string? pOut) { if (p is object) { pOut = null; return; // 1 } if (p is object) { pOut = p; return; } if (p is null) { pOut = null; return; } pOut = M1(); } // 2 string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,13): warning CS8825: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return; // 1 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return;").WithArguments("pOut", "p").WithLocation(10, 13), // (26,5): warning CS8825: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // } // 2 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "}").WithArguments("pOut", "p").WithLocation(26, 5)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Constructor_02() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public C() { } public C(string? p, [NotNullIfNotNull(""p"")] out string? pOut) : this() { if (p is object) { pOut = null; return; // 1 } if (p is object) { pOut = p; return; } if (p is null) { pOut = null; return; } pOut = M1(); } // 2 string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (12,13): warning CS8825: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // return; // 1 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "return;").WithArguments("pOut", "p").WithLocation(12, 13), // (28,5): warning CS8825: Parameter 'pOut' must have a non-null value when exiting because parameter 'p' is non-null. // } // 2 Diagnostic(ErrorCode.WRN_ParameterNotNullIfNotNull, "}").WithArguments("pOut", "p").WithLocation(28, 5)); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNullIfNotNull_Constructor_03() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public C(string x, string? y) : this(x, out y) { y.ToString(); } public C(string? p, [NotNullIfNotNull(""p"")] out string? pOut) { pOut = p; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(44539, "https://github.com/dotnet/roslyn/issues/44539")] public void NotNull_Constructor() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public C([NotNull] out string? pOut) { pOut = M1(); } // 1 string? M1() => null; } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (8,5): warning CS8777: Parameter 'pOut' must have a non-null value when exiting. // } // 1 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("pOut").WithLocation(8, 5)); } [Theory, WorkItem(48996, "https://github.com/dotnet/roslyn/issues/48996")] [InlineData("")] [InlineData("where T : class?")] public void NotNullProperty_Constructor(string constraints) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<T> " + constraints + @" { [NotNull] public T Prop { get; set; } public C() { } // 1 public C(T t) { Prop = t; } // 2 public C(T t, int x) { Prop = t; Prop.ToString(); } // 3 public C([DisallowNull] T t, int x, int y) { Prop = t; } [MemberNotNull(nameof(Prop))] public void Init(T t) { Prop = t; } // 4 } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition, MemberNotNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,12): warning CS8618: Non-nullable property 'Prop' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C() { } // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("property", "Prop").WithLocation(9, 12), // (10,12): warning CS8618: Non-nullable property 'Prop' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C(T t) { Prop = t; } // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("property", "Prop").WithLocation(10, 12), // (11,38): warning CS8602: Dereference of a possibly null reference. // public C(T t, int x) { Prop = t; Prop.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Prop").WithLocation(11, 38), // (18,5): warning CS8774: Member 'Prop' must have a non-null value when exiting. // } // 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("Prop").WithLocation(18, 5)); } [Theory, WorkItem(48996, "https://github.com/dotnet/roslyn/issues/48996")] [InlineData("")] [InlineData("where T : class?")] public void NotNullField_Constructor(string constraints) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<T> " + constraints + @" { [NotNull] public T field; public C() { } // 1 public C(T t) { field = t; } // 2 public C(T t, int x) { field = t; field.ToString(); } // 3 public C([DisallowNull] T t, int x, int y) { field = t; } [MemberNotNull(nameof(field))] public void Init(T t) { field = t; } // 4 } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition, MemberNotNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,12): warning CS8618: Non-nullable field 'field' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C() { } // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field").WithLocation(9, 12), // (10,12): warning CS8618: Non-nullable field 'field' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C(T t) { field = t; } // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "field").WithLocation(10, 12), // (11,39): warning CS8602: Dereference of a possibly null reference. // public C(T t, int x) { field = t; field.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field").WithLocation(11, 39), // (18,5): warning CS8774: Member 'field' must have a non-null value when exiting. // } // 4 Diagnostic(ErrorCode.WRN_MemberNotNull, "}").WithArguments("field").WithLocation(18, 5)); } [Fact, WorkItem(48996, "https://github.com/dotnet/roslyn/issues/48996")] public void DisallowNullProperty_Constructor() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; public class C1 { [DisallowNull, NotNull] public string? F1 { get; set; } public C1() { } // 1 public C1(string? F1) // 2 { this.F1 = F1; // 3 } public C1(int i) { this.F1 = ""a""; } } public class C2 { [NotNull] public string? F2 { get; set; } public C2() { } public C2(string? F2) { this.F2 = F2; } public C2(int i) { this.F2 = ""a""; } } public class C3 { [DisallowNull] public string? F3 { get; set; } public C3() { } public C3(string? F3) { this.F3 = F3; // 4 } public C3(int i) { this.F3 = ""a""; } } "; // We expect no warnings on `C2(string?)` because `C2.F`'s getter and setter are not linked. var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,12): warning CS8618: Non-nullable property 'F1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C1() { } // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C1").WithArguments("property", "F1").WithLocation(9, 12), // (10,12): warning CS8618: Non-nullable property 'F1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C1(string? F1) // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C1").WithArguments("property", "F1").WithLocation(10, 12), // (12,19): warning CS8601: Possible null reference assignment. // this.F1 = F1; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "F1").WithLocation(12, 19), // (44,19): warning CS8601: Possible null reference assignment. // this.F3 = F3; // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "F3").WithLocation(44, 19)); } [Fact, WorkItem(48996, "https://github.com/dotnet/roslyn/issues/48996")] public void DisallowNullField_Constructor() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; public class C1 { [DisallowNull, NotNull] public string? F; public C1() { } // 1 public C1(string? F) // 2 { this.F = F; // 3 } public C1(int i) { this.F = ""a""; } } public class C2 { [NotNull] public string? F; public C2() { } // 4 public C2(string? F) // 5 { this.F = F; } public C2(int i) { this.F = ""a""; } } public class C3 { [DisallowNull] public string? F; public C3() { } public C3(string? F) { this.F = F; // 6 } public C3(int i) { this.F = ""a""; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,12): warning CS8618: Non-nullable field 'F' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C1() { } // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C1").WithArguments("field", "F").WithLocation(9, 12), // (10,12): warning CS8618: Non-nullable field 'F' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C1(string? F) // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C1").WithArguments("field", "F").WithLocation(10, 12), // (12,18): warning CS8601: Possible null reference assignment. // this.F = F; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "F").WithLocation(12, 18), // (25,12): warning CS8618: Non-nullable field 'F' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C2() { } // 4 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C2").WithArguments("field", "F").WithLocation(25, 12), // (26,12): warning CS8618: Non-nullable field 'F' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C2(string? F) // 5 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C2").WithArguments("field", "F").WithLocation(26, 12), // (44,18): warning CS8601: Possible null reference assignment. // this.F = F; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "F").WithLocation(44, 18)); } [Fact, WorkItem(49964, "https://github.com/dotnet/roslyn/issues/49964")] public void AdjustPropertyState_MaybeDefaultInput_MaybeNullOutput() { var source = @" using System.Diagnostics.CodeAnalysis; public class C<T> { [AllowNull] T Prop { get; set; } public C() { } public C(int unused) { M1(Prop); // 1 } public void M() { Prop = default; M1(Prop); // 2 Prop.ToString(); } public void M1(T t) { } } "; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); // It's not clear whether diagnostic 1 and 2 are appropriate. // Going by the principle of "if you put a good value in, you will get a good value out", // it seems like property state should be MaybeNull after assigning a MaybeDefault to the property. // https://github.com/dotnet/roslyn/issues/49964 // Note that the lack of constructor exit warning in 'C()' is expected due to presence of 'AllowNull' on the property declaration. comp.VerifyDiagnostics( // (12,12): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.M1(T t)'. // M1(Prop); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "Prop").WithArguments("t", "void C<T>.M1(T t)").WithLocation(12, 12), // (18,12): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.M1(T t)'. // M1(Prop); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "Prop").WithArguments("t", "void C<T>.M1(T t)").WithLocation(18, 12)); } [Fact, WorkItem(49964, "https://github.com/dotnet/roslyn/issues/49964")] public void AdjustPropertyState_Generic_MaybeNullInput_NotNullOutput() { var source = @" using System.Diagnostics.CodeAnalysis; public class C<T> { [NotNull] T Prop { get; set; } public C() // 1 { } public C(T t) // 2 { Prop = t; } public void M(T t) { Prop = t; Prop.ToString(); // 3 } public void M1(T t) { } } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); // It's not clear whether diagnostic 2 or 3 are appropriate. // Going by the principle of "if you put a good value in, you will get a good value out", // it seems like property state should be NotNull after assigning a MaybeNull to the property. // https://github.com/dotnet/roslyn/issues/49964 comp.VerifyDiagnostics( // (8,12): warning CS8618: Non-nullable property 'Prop' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("property", "Prop").WithLocation(8, 12), // (12,12): warning CS8618: Non-nullable property 'Prop' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C(T t) // 2 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("property", "Prop").WithLocation(12, 12), // (19,9): warning CS8602: Dereference of a possibly null reference. // Prop.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Prop").WithLocation(19, 9)); } [Fact, WorkItem(49964, "https://github.com/dotnet/roslyn/issues/49964")] public void NotNull_MaybeNull_Property_Constructor() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [NotNull, MaybeNull] string Prop1 { get; set; } [NotNull, MaybeNull] string? Prop2 { get; set; } public C() { } public C(string prop1, string prop2) { Prop1 = prop1; Prop2 = prop2; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNullIfNotNull_Return_NullableInt() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public int? M(int? p) => throw null!; }"; var source = @" class D { static void M(C c, int? p1, int? p2) { _ = p1 ?? throw null!; c.M(p1).Value.ToString(); c.M(p2).Value.ToString(); // 1 } }"; var expected = new[] { // (8,9): warning CS8629: Nullable value type may be null. // c.M(p2).Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.M(p2)").WithLocation(8, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Return_UnconstrainedGeneric() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public T M<T>(T p) => throw null!; }"; var source = @" class D { static void M<T>(C c, T p1, T p2) { _ = p1 ?? throw null!; c.M(p1).ToString(); c.M(p2).ToString(); // 1 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2)").WithLocation(8, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Return_UnconstrainedGeneric2() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public U M<T, U>(T p, U p2) => throw null!; }"; var source = @" class D<U> { static void M<T>(C c, T p1, T p2, U u) { _ = p1 ?? throw null!; c.M(p1, u).ToString(); c.M(p2, u).ToString(); // 1 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2, u).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2, u)").WithLocation(8, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Return_MultipleParameters() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p""), NotNullIfNotNull(""p2"")] public string? M(string? p, string? p2) => throw null!; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1, p1).ToString(); c.M(p1, p2).ToString(); c.M(p2, p1).ToString(); c.M(p2, p2).ToString(); // 1 } }"; var expected = new[] { // (10,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2, p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2, p2)").WithLocation(10, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Return_DuplicateParameters() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p2""), NotNullIfNotNull(""p2"")] public string? M(string? p, string? p2) => throw null!; }"; // Warn on redundant attribute (duplicate parameter referenced)? https://github.com/dotnet/roslyn/issues/36073 var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1, p1).ToString(); c.M(p1, p2).ToString(); // 1 c.M(p2, p1).ToString(); c.M(p2, p2).ToString(); // 2 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // c.M(p1, p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p1, p2)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2, p2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2, p2)").WithLocation(10, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Return_MultipleParameters_SameName() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M(string? p, string? p) => throw null!; static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1, p1).ToString(); c.M(p1, p2).ToString(); c.M(p2, p1).ToString(); c.M(p2, p2).ToString(); // 1 } }"; var comp2 = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics( // (4,73): error CS0100: The parameter name 'p' is a duplicate // [return: NotNullIfNotNull("p")] public string? M(string? p, string? p) => throw null!; Diagnostic(ErrorCode.ERR_DuplicateParamName, "p").WithArguments("p").WithLocation(4, 73), // (12,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2, p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2, p2)").WithLocation(12, 9) ); } [Fact] public void NotNullIfNotNull_Return_NonExistentName() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""missing"")] public string? M(string? p) => throw null!; static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1).ToString(); // 1 c.M(p2).ToString(); // 2 } }"; // Warn on misused attribute? https://github.com/dotnet/roslyn/issues/36073 var comp2 = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c.M(p1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p1)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2)").WithLocation(10, 9) ); } [Fact] public void NotNullIfNotNull_Return_NullName() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(null)] public string? M(string? p) => throw null!; // 1 static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1).ToString(); // 2 c.M(p2).ToString(); // 3 } }"; var comp2 = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics( // (4,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // [return: NotNullIfNotNull(null)] public string? M(string? p) => throw null!; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 31), // (9,9): warning CS8602: Dereference of a possibly null reference. // c.M(p1).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p1)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2)").WithLocation(10, 9) ); } [Fact] public void NotNullIfNotNull_Return_ParamsParameter() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] public string? M(params string?[]? p) => throw null!; }"; var source = @" class D { static void M(C c, string?[]? p1, string?[]? p2, string? p3, string? p4) { _ = p1 ?? throw null!; c.M(p1).ToString(); c.M(p2).ToString(); // 1 c.M(null).ToString(); // 2 _ = p3 ?? throw null!; c.M(p3).ToString(); c.M(p4).ToString(); } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // c.M(null).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(null)").WithLocation(9, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Return_ExtensionThis() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public static class Extension { [return: NotNullIfNotNull(""p"")] public static string? M(this string? p) => throw null!; }"; var source = @" class D { static void M(string? p1, string? p2) { _ = p1 ?? throw null!; p1.M().ToString(); p2.M().ToString(); // 1 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // p2.M().ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p2.M()").WithLocation(8, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact, WorkItem(37238, "https://github.com/dotnet/roslyn/issues/37238")] public void NotNullIfNotNull_Return_Indexer() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [NotNullIfNotNull(""p"")] public string? this[string? p] { get { throw null!; } } }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c[p1].ToString(); c[p2].ToString(); // 1 } }"; var expected = new[] { // (7,9): warning CS8602: Dereference of a possibly null reference. // c[p1].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[p1]").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // c[p2].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[p2]").WithLocation(8, 9) }; // NotNullIfNotNull not yet supported on indexers. https://github.com/dotnet/roslyn/issues/37238 var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_Indexer_OutParameter() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { public int this[string? p, [NotNullIfNotNull(""p"")] out string? p2] { get { throw null!; } } }"; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,56): error CS0631: ref and out are not valid in this context // public int this[string? p, [NotNullIfNotNull("p")] out string? p2] { get { throw null!; } } Diagnostic(ErrorCode.ERR_IllegalRefParam, "out").WithLocation(4, 56) ); } [Fact] public void NotNullIfNotNull_OutParameter() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public void M(string? p, [NotNullIfNotNull(""p"")] out string? p2) => throw null!; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1, out var x1); x1.ToString(); c.M(p2, out var x2); x2.ToString(); // 1 } }"; var expected = new[] { // (11,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(11, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_OutParameter_WithMaybeNullWhen() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public bool M(string? p, [NotNullIfNotNull(""p""), MaybeNullWhen(true)] out string p2) => throw null!; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; _ = c.M(p1, out var x1) ? x1.ToString() : x1.ToString(); _ = c.M(p2, out var x2) ? x2.ToString() // 1 : x2.ToString(); } }"; var expected = new[] { // (12,11): warning CS8602: Dereference of a possibly null reference. // ? x2.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(12, 11) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, MaybeNullWhenAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_RefParameter() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public void M(string? p, [NotNullIfNotNull(""p"")] ref string? p2) => throw null!; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; string? x1 = null; c.M(p1, ref x1); x1.ToString(); string? x2 = null; c.M(p2, ref x2); x2.ToString(); // 1 string? x3 = """"; c.M(p2, ref x3); x3.ToString(); // 2 } }"; var expected = new[] { // (13,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(13, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(17, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void NotNullIfNotNull_ByValueParameter() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public void M(string? p, [NotNullIfNotNull(""p"")] string? p2) => throw null!; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; string? x1 = null; c.M(p1, x1); x1.ToString(); // 1 string? x2 = null; c.M(p2, x2); x2.ToString(); // 2 string? x3 = """"; c.M(p2, x3); x3.ToString(); // 3 } }"; var expected = new[] { // (9,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(9, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(13, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact, WorkItem(48489, "https://github.com/dotnet/roslyn/issues/48489")] public void NotNullIfNotNull_Return_BinaryOperator() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""x""), NotNullIfNotNull(""y"")] public static C? operator +(C? x, C? y) => null; public static C? operator *(C? x, C? y) => null; [return: NotNullIfNotNull(""x"")] public static C? operator -(C? x, C? y) => null; [return: NotNullIfNotNull(""y"")] public static C? operator /(C? x, C? y) => null; }"; var source = @" class D { static void M(C c1, C c2, C? cn1, C? cn2) { (c1 + c2).ToString(); // no warn (c1 + cn2).ToString(); // no warn (cn1 + c2).ToString(); // no warn (cn1 + cn2).ToString(); // warn (c1 * c2).ToString(); // warn (c1 * cn2).ToString(); // warn (cn1 * c2).ToString(); // warn (cn1 * cn2).ToString(); // warn (c1 - c2).ToString(); // no warn (c1 - cn2).ToString(); // no warn (cn1 - c2).ToString(); // warn (cn1 - cn2).ToString(); // warn (c1 / c2).ToString(); // no warn (c1 / cn2).ToString(); // warn (cn1 / c2).ToString(); // no warn (cn1 / cn2).ToString(); // warn } }"; var expected = new[] { // (9,10): warning CS8602: Dereference of a possibly null reference. // (cn1 + cn2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn1 + cn2").WithLocation(9, 10), // (11,10): warning CS8602: Dereference of a possibly null reference. // (c1 * c2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1 * c2").WithLocation(11, 10), // (12,10): warning CS8602: Dereference of a possibly null reference. // (c1 * cn2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1 * cn2").WithLocation(12, 10), // (13,10): warning CS8602: Dereference of a possibly null reference. // (cn1 * c2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn1 * c2").WithLocation(13, 10), // (14,10): warning CS8602: Dereference of a possibly null reference. // (cn1 * cn2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn1 * cn2").WithLocation(14, 10), // (18,10): warning CS8602: Dereference of a possibly null reference. // (cn1 - c2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn1 - c2").WithLocation(18, 10), // (19,10): warning CS8602: Dereference of a possibly null reference. // (cn1 - cn2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn1 - cn2").WithLocation(19, 10), // (22,10): warning CS8602: Dereference of a possibly null reference. // (c1 / cn2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1 / cn2").WithLocation(22, 10), // (24,10): warning CS8602: Dereference of a possibly null reference. // (cn1 / cn2).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn1 / cn2").WithLocation(24, 10) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact, WorkItem(48489, "https://github.com/dotnet/roslyn/issues/48489")] public void NotNullIfNotNull_Return_BinaryOperatorWithStruct() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public struct S { public int Value; } public class C { [return: NotNullIfNotNull(""y"")] public static C? operator +(C? x, S? y) => null; #pragma warning disable CS8825 [return: NotNullIfNotNull(""y"")] public static C? operator -(C? x, S y) => null; #pragma warning restore CS8825 }"; var source = @" class D { static void M(C c, C? cn, S s, S? sn) { (c + s).ToString(); // no warn (cn + s).ToString(); // no warn (c + sn).ToString(); // warn (cn + sn).ToString(); // warn (c - s).ToString(); // no warn (cn - s).ToString(); // no warn } }"; var expected = new[] { // (8,10): warning CS8602: Dereference of a possibly null reference. // (c + sn).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c + sn").WithLocation(8, 10), // (9,10): warning CS8602: Dereference of a possibly null reference. // (cn + sn).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "cn + sn").WithLocation(9, 10) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact, WorkItem(48489, "https://github.com/dotnet/roslyn/issues/48489")] public void NotNullIfNotNull_Return_BinaryOperatorInCompoundAssignment() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""x""), NotNullIfNotNull(""y"")] public static C? operator +(C? x, C? y) => null; public static C? operator *(C? x, C? y) => null; [return: NotNullIfNotNull(""x"")] public static C? operator -(C? x, C? y) => null; [return: NotNullIfNotNull(""y"")] public static C? operator /(C? x, C? y) => null; }"; var source = @" class E { static void A(C ac, C? acn, C ar1, C ar2, C? arn1, C? arn2) { ar1 += ac; ar1.ToString(); ar2 += acn; ar2.ToString(); arn1 += ac; arn1.ToString(); arn2 += acn; arn2.ToString(); // warn reference } static void M(C mc, C? mcn, C mr1, C mr2, C? mrn1, C? mrn2) { mr1 *= mc; // warn assignment mr1.ToString(); // warn reference mr2 *= mcn; // warn assignment mr2.ToString(); // warn reference mrn1 *= mc; mrn1.ToString(); // warn reference mrn2 *= mcn; mrn2.ToString(); // warn reference } static void S(C sc, C? scn, C sr1, C sr2, C? srn1, C? srn2) { sr1 -= sc; sr1.ToString(); sr2 -= scn; sr2.ToString(); srn1 -= sc; srn1.ToString(); // warn reference srn2 -= scn; srn2.ToString(); // warn reference } static void D(C dc, C? dcn, C dr1, C dr2, C? drn1, C? drn2) { dr1 /= dc; dr1.ToString(); dr2 /= dcn; // warn assignment dr2.ToString(); // warn reference drn1 /= dc; drn1.ToString(); drn2 /= dcn; drn2.ToString(); // warn reference } }"; var expected = new[] { // (13,9): warning CS8602: Dereference of a possibly null reference. // arn2.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "arn2").WithLocation(13, 9), // (18,9): warning CS8601: Possible null reference assignment. // mr1 *= mc; // warn assignment Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "mr1 *= mc").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // mr1.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "mr1").WithLocation(19, 9), // (20,9): warning CS8601: Possible null reference assignment. // mr2 *= mcn; // warn assignment Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "mr2 *= mcn").WithLocation(20, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // mr2.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "mr2").WithLocation(21, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // mrn1.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "mrn1").WithLocation(23, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // mrn2.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "mrn2").WithLocation(25, 9), // (35,9): warning CS8602: Dereference of a possibly null reference. // srn1.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "srn1").WithLocation(35, 9), // (37,9): warning CS8602: Dereference of a possibly null reference. // srn2.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "srn2").WithLocation(37, 9), // (44,9): warning CS8601: Possible null reference assignment. // dr2 *= dcn; // warn assignment Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "dr2 /= dcn").WithLocation(44, 9), // (45,9): warning CS8602: Dereference of a possibly null reference. // dr2.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "dr2").WithLocation(45, 9), // (49,9): warning CS8602: Dereference of a possibly null reference. // drn2.ToString(); // warn reference Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "drn2").WithLocation(49, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] public void MethodWithOutNullableParameter_AfterNotNullWhenTrue() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (M(s, out string? s2)) { s.ToString(); // ok s2.ToString(); // warn } else { s.ToString(); // warn 2 s2.ToString(); // warn 3 } s.ToString(); // ok s2.ToString(); // ok } public static bool M([NotNullWhen(true)] string? s, out string? s2) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(15, 13) ); } [Fact] public void NotNullIfNotNull_Return_WithMaybeNull() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p""), MaybeNull] public string M(string? p) => throw null!; }"; var source = @" class D { static void M(C c, string? p1, string? p2) { _ = p1 ?? throw null!; c.M(p1).ToString(); c.M(p2).ToString(); // 1 } }"; var expected = new[] { // (8,9): warning CS8602: Dereference of a possibly null reference. // c.M(p2).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.M(p2)").WithLocation(8, 9) }; var lib = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, MaybeNullAttributeDefinition, lib_cs }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullIfNotNullAttributeDefinition, MaybeNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2); } [Fact] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_OptionalParameter_NonNullDefault() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] string? M1(string? p = ""hello"") => p; void M2() { _ = M1().ToString(); _ = M1(null).ToString(); // 1 _ = M1(""world"").ToString(); } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(null).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(null)").WithLocation(11, 13)); } [Fact] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_OptionalParameter_NullDefault() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p"")] string? M1(string? p = null) => p; void M2() { _ = M1().ToString(); // 1 _ = M1(null).ToString(); // 2 _ = M1(""world"").ToString(); } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // _ = M1().ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1()").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(null).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(null)").WithLocation(11, 13)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/38801")] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_OptionalParameter_LocalFunction() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { void M1() { [return: NotNullIfNotNull(""p"")] string? local1(string? p = ""hello"") => p; _ = local1().ToString(); _ = local1(null).ToString(); // 1 _ = local1(""world"").ToString(); } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = local1(null).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "local1(null)").WithLocation(11, 13)); } [Fact] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_LabeledArguments() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""p1"")] string? M1(string? p1, string? p2) => p1; void M2() { _ = M1(""hello"", null).ToString(); _ = M1(p1: ""hello"", p2: null).ToString(); _ = M1(p2: null, p1: ""hello"").ToString(); _ = M1(p2: ""world"", p1: null).ToString(); // 1 } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p2: "world", p1: null).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"M1(p2: ""world"", p1: null)").WithLocation(13, 13)); } [Theory] [InlineData(@"""b""")] [InlineData("null")] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_LabeledArguments_OptionalParameters_NonNullDefault(string p2Default) { var source = $@" using System.Diagnostics.CodeAnalysis; public class C {{ [return: NotNullIfNotNull(""p1"")] string? M1(string? p1 = ""a"", string? p2 = {p2Default}) => p1; void M2() {{ _ = M1(p2: null).ToString(); _ = M1(p1: null).ToString(); // 1 _ = M1(p1: ""hello"", p2: null).ToString(); _ = M1(p2: ""hello"", p1: null).ToString(); // 2 _ = M1(p1: null, p2: ""hello"").ToString(); // 3 _ = M1(p2: null, p1: ""hello"").ToString(); }} }} "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p1: null).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(p1: null)").WithLocation(11, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p2: "hello", p1: null).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"M1(p2: ""hello"", p1: null)").WithLocation(13, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p1: null, p2: "hello").ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"M1(p1: null, p2: ""hello"")").WithLocation(14, 13)); } [Theory] [InlineData(@"""b""")] [InlineData("null")] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_LabeledArguments_OptionalParameters_NullDefault(string p2Default) { var source = $@" using System.Diagnostics.CodeAnalysis; public class C {{ [return: NotNullIfNotNull(""p1"")] string? M1(string? p1 = null, string? p2 = {p2Default}) => p1; void M2() {{ _ = M1(p2: null).ToString(); // 1 _ = M1(p1: null).ToString(); // 2 _ = M1(p1: ""hello"", p2: null).ToString(); _ = M1(p2: ""hello"", p1: null).ToString(); // 3 _ = M1(p1: null, p2: ""hello"").ToString(); // 4 _ = M1(p2: null, p1: ""hello"").ToString(); }} }} "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p2: null).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(p2: null)").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p1: null).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(p1: null)").WithLocation(11, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p2: "hello", p1: null).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"M1(p2: ""hello"", p1: null)").WithLocation(13, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(p1: null, p2: "hello").ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"M1(p1: null, p2: ""hello"")").WithLocation(14, 13)); } [Fact] [WorkItem(39868, "https://github.com/dotnet/roslyn/issues/39868")] public void NotNullIfNotNull_BadDefaultParameterValue() { var source = @" using System.Diagnostics.CodeAnalysis; class C { [return: NotNullIfNotNull(""s"")] string? M1(string? s = default(object)) => s; // 1 void M2() { _ = M1().ToString(); // 2 _ = M1(null).ToString(); // 3 _ = M1(""hello"").ToString(); } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (7,24): error CS1750: A value of type 'object' cannot be used as a default parameter because there are no standard conversions to type 'string' // string? M1(string? s = default(object)) => s; // 1 Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("object", "string").WithLocation(7, 24), // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = M1().ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1()").WithLocation(11, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // _ = M1(null).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(null)").WithLocation(12, 13)); } [Fact] [WorkItem(39868, "https://github.com/dotnet/roslyn/issues/39868")] public void NotNullIfNotNull_ParameterDefaultValue_Suppression() { var source1 = @" using System.Diagnostics.CodeAnalysis; public static class C1 { [return: NotNullIfNotNull(""s"")] public static string? M1(string? s = null!) => s; } "; var source2 = @" class C2 { static void M2() { _ = C1.M1().ToString(); _ = C1.M1(null).ToString(); _ = C1.M1(""hello"").ToString(); } } "; var comp1 = CreateNullableCompilation(new[] { source1, source2, NotNullIfNotNullAttributeDefinition }); // technically since the argument has not-null state, the return value should have not-null state here, // but it is such a corner case that it is unlikely to be of interest to modify the current behavior comp1.VerifyDiagnostics( // (6,13): warning CS8602: Dereference of a possibly null reference. // _ = C1.M1().ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C1.M1()").WithLocation(6, 13), // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = C1.M1(null).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C1.M1(null)").WithLocation(7, 13)); var reference = CreateNullableCompilation(new[] { source1, NotNullIfNotNullAttributeDefinition }).EmitToImageReference(); var comp2 = CreateNullableCompilation(source2, references: new[] { reference }); comp2.VerifyDiagnostics( // (6,13): warning CS8602: Dereference of a possibly null reference. // _ = C1.M1().ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C1.M1()").WithLocation(6, 13), // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = C1.M1(null).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C1.M1(null)").WithLocation(7, 13)); } [Fact] [WorkItem(37903, "https://github.com/dotnet/roslyn/issues/37903")] public void NotNullIfNotNull_Indexer_OptionalParameters() { // NOTE: NotNullIfNotNullAttribute is not supported on indexers. // But we want to make sure we don't trip asserts related to analysis of NotNullIfNotNullAttribute. var source = @" using System.Diagnostics.CodeAnalysis; public class C { [NotNullIfNotNull(""p"")] string? this[int i, string? p = ""hello""] => p; void M2() { _ = this[0].ToString(); // 1 _ = this[0, null].ToString(); // 2 _ = this[0, ""world""].ToString(); // 3 } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // _ = this[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this[0]").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = this[0, null].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this[0, null]").WithLocation(11, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // _ = this[0, "world"].ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"this[0, ""world""]").WithLocation(12, 13)); } [Fact] [WorkItem(39802, "https://github.com/dotnet/roslyn/issues/39802")] public void NotNullIfNotNull_ImplicitUserDefinedOperator() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""c"")] public static implicit operator string?(C? c) => c?.ToString(); void M1(string s) { } void M2() { M1(new C()); M1((C?)null); // 1 } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,12): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M1(string s)'. // M1((C?)null); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(C?)null").WithArguments("s", "void C.M1(string s)").WithLocation(13, 12)); } [Fact] [WorkItem(39802, "https://github.com/dotnet/roslyn/issues/39802")] public void NotNullIfNotNull_ImplicitUserDefinedOperator_MultipleAttributes() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""b"")] [return: NotNullIfNotNull(""c"")] public static implicit operator string?(C? c) => c?.ToString(); void M1(string s) { } void M2() { M1(new C()); M1((C?)null); // 1 } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (14,12): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M1(string s)'. // M1((C?)null); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(C?)null").WithArguments("s", "void C.M1(string s)").WithLocation(14, 12)); } [Fact] [WorkItem(39802, "https://github.com/dotnet/roslyn/issues/39802")] public void NotNullIfNotNull_ExplicitUserDefinedOperator() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [return: NotNullIfNotNull(""c"")] public static explicit operator string?(C? c) => c?.ToString(); void M1(string s) { } void M2() { M1((string)new C()); M1((string?)new C()); // 1 M1((string?)(C?)null); // 2 } } "; var comp = CreateNullableCompilation(new[] { NotNullIfNotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,12): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M1(string s)'. // M1((string?)new C()); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(string?)new C()").WithArguments("s", "void C.M1(string s)").WithLocation(13, 12), // (14,12): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M1(string s)'. // M1((string?)(C?)null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(string?)(C?)null").WithArguments("s", "void C.M1(string s)").WithLocation(14, 12)); } [Fact] [WorkItem(39802, "https://github.com/dotnet/roslyn/issues/39802")] public void UserDefinedConversion_UnconditionalParamAttributes() { var source = @" using System.Diagnostics.CodeAnalysis; public struct A { } public struct B { public static implicit operator A([DisallowNull] B? b) { b.Value.ToString(); return new A(); } void M1(A a) { } void M2() { M1(new B()); M1((B?)null); // 1 } } public class C { public static implicit operator string?([AllowNull] C c) => c?.ToString(); void M1(string? s) { } void M2() { M1(new C()); M1((C?)null); } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (18,12): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // M1((B?)null); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(B?)null").WithLocation(18, 12)); } [Theory] [InlineData("struct")] [InlineData("class")] [WorkItem(39802, "https://github.com/dotnet/roslyn/issues/39802")] public void UserDefinedConversion_ReturnAttributes_Lifted(string typeKind) { var source = @" using System.Diagnostics.CodeAnalysis; public " + typeKind + @" A { public static void AllowNull(A? a) { } public static void DisallowNull([DisallowNull] A? a) { } } public struct B { public static implicit operator A(B b) { return new A(); } void M() { A.AllowNull((B?)new B()); A.AllowNull((B?)null); A.DisallowNull((B?)new B()); A.DisallowNull((B?)null); // 1 } } public struct C { public static implicit operator A(C? c) { return new A(); } void M() { A.AllowNull((C?)new C()); A.AllowNull((C?)null); A.DisallowNull((C?)new C()); A.DisallowNull((C?)null); } } public struct D { [return: NotNull] public static implicit operator A?(D? d) { return new A(); } void M() { A.AllowNull((D?)new D()); A.AllowNull((D?)null); A.DisallowNull((D?)new D()); A.DisallowNull((D?)null); } } public struct E { [return: NotNull] public static implicit operator A?(E e) { return new A(); } void M() { A.AllowNull((E?)new E()); A.AllowNull((E?)null); A.DisallowNull((E?)new E()); A.DisallowNull((E?)null); // 2 } } public struct F { [return: NotNullIfNotNull(""f"")] public static implicit operator A?(F f) { return new A(); } void M() { A.AllowNull((F?)new F()); A.AllowNull((F?)null); A.DisallowNull((F?)new F()); A.DisallowNull((F?)null); // 3 } } public struct G { [return: NotNull] public static implicit operator A(G g) { return new A(); } void M() { A.AllowNull((G?)new G()); A.AllowNull((G?)null); A.DisallowNull((G?)new G()); A.DisallowNull((G?)null); // 4 } } public struct H { // This scenario verifies that DisallowNull has no effect, even when the conversion is lifted. public static implicit operator A([DisallowNull] H h) { return new A(); } void M() { A.AllowNull((H?)new H()); A.AllowNull((H?)null); A.DisallowNull((H?)new H()); A.DisallowNull((H?)null); // 5 } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, DisallowNullAttributeDefinition, NotNullAttributeDefinition, NotNullIfNotNullAttributeDefinition, source }); if (typeKind == "struct") { comp.VerifyDiagnostics( // (23,24): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // A.DisallowNull((B?)null); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(B?)null").WithLocation(23, 24), // (76,24): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // A.DisallowNull((E?)null); // 2 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(E?)null").WithLocation(76, 24), // (94,24): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // A.DisallowNull((F?)null); // 3 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(F?)null").WithLocation(94, 24), // (112,24): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // A.DisallowNull((G?)null); // 4 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(G?)null").WithLocation(112, 24), // (130,24): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // A.DisallowNull((H?)null); // 5 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(H?)null").WithLocation(130, 24) ); } else { comp.VerifyDiagnostics( // (23,24): warning CS8604: Possible null reference argument for parameter 'a' in 'void A.DisallowNull(A? a)'. // A.DisallowNull((B?)null); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(B?)null").WithArguments("a", "void A.DisallowNull(A? a)").WithLocation(23, 24), // (76,24): warning CS8604: Possible null reference argument for parameter 'a' in 'void A.DisallowNull(A? a)'. // A.DisallowNull((E?)null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(E?)null").WithArguments("a", "void A.DisallowNull(A? a)").WithLocation(76, 24), // (94,24): warning CS8604: Possible null reference argument for parameter 'a' in 'void A.DisallowNull(A? a)'. // A.DisallowNull((F?)null); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(F?)null").WithArguments("a", "void A.DisallowNull(A? a)").WithLocation(94, 24), // (112,24): warning CS8604: Possible null reference argument for parameter 'a' in 'void A.DisallowNull(A? a)'. // A.DisallowNull((G?)null); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(G?)null").WithArguments("a", "void A.DisallowNull(A? a)").WithLocation(112, 24), // (130,24): warning CS8604: Possible null reference argument for parameter 'a' in 'void A.DisallowNull(A? a)'. // A.DisallowNull((H?)null); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(H?)null").WithArguments("a", "void A.DisallowNull(A? a)").WithLocation(130, 24) ); } } [Fact] [WorkItem(39802, "https://github.com/dotnet/roslyn/issues/39802")] public void UserDefinedConversion_UnconditionalReturnAttributes() { var source = @" using System.Diagnostics.CodeAnalysis; public struct A { } public struct B { [return: NotNull] public static implicit operator A?(B? b) { return new A(); } void M1([DisallowNull] A? a) { } void M2() { M1(new B()); M1((B?)null); } } public class C { [return: MaybeNull] public static implicit operator string(C? c) => null; void M1(string s) { } void M2() { M1(new C()); // 1 M1((C?)null); // 2 } } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullAttributeDefinition, DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (29,12): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M1(string s)'. // M1(new C()); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "new C()").WithArguments("s", "void C.M1(string s)").WithLocation(29, 12), // (30,12): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M1(string s)'. // M1((C?)null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(C?)null").WithArguments("s", "void C.M1(string s)").WithLocation(30, 12)); } [Fact] public void MethodWithOutNullableParameter_AfterNotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (M(s, out string? s2)) { s.ToString(); // ok s2.ToString(); // warn } else { s.ToString(); // ok s2.ToString(); // warn 2 } s.ToString(); // ok s2.ToString(); // ok } public static bool M([NotNull] string? s, out string? s2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(15, 13) ); } [Fact] public void MethodWithOutNullableParameter_AfterNotNull_InErrorInvocation() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (Missing(M(s, out string? s2))) { s.ToString(); s2.ToString(); // 1 } else { s.ToString(); s2.ToString(); // 2 } s.ToString(); s2.ToString(); } public static bool M([NotNull] string? s, out string? s2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,13): error CS0103: The name 'Missing' does not exist in the current context // if (Missing(M(s, out string? s2))) Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(7, 13), // (10,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(15, 13) ); } [Fact] public void MethodWithOutNonNullableParameter() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main() { M(out string s); s.ToString(); // ok } public static void M(out string value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void MethodWithOutNonNullableParameter_WithNullableOutArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main() { M(out string? s); s.ToString(); // ok } public static void M(out string value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void MethodWithRefNonNullableParameter() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main() { string s = ""hello""; M(ref s); s.ToString(); // ok } public static void M(ref string value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void MethodWithRefNonNullableParameter_WithNullableRefArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? s) { M(ref s); // warn s.ToString(); } public static void M(ref string value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,15): warning CS8601: Possible null reference assignment. // M(ref s); // warn Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(6, 15) ); } [Fact, WorkItem(34874, "https://github.com/dotnet/roslyn/issues/34874")] public void MethodWithRefNonNullableParameter_WithNonNullRefArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main() { string? s = ""hello""; M(ref s); s.ToString(); } public static void M(ref string value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void MethodWithRefNullableParameter_WithNonNullableRefArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string s) { M(ref s); // warn 1 s.ToString(); // warn 2 } public static void M(ref string? value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // M(ref s); // warn 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(6, 15), // (7,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithRefNullableParameter_WithNonNullableLocal() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main() { string s = ""hello""; M(ref s); // warn 1 s.ToString(); // warn 2 } public static void M(ref string? value) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // M(ref s); // warn 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(7, 15), // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); } [Fact] public void MethodWithOutParameter_WithNullableOut() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { if (TryGetValue(key, out var s)) { s/*T:string?*/.ToString(); // warn } else { s/*T:string?*/.ToString(); // warn 2 } s.ToString(); // ok } public static bool TryGetValue(string key, out string? value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 13) ); } /// <summary> /// Check the inferred type of var from the semantic model, which currently means from initial binding. /// </summary> private static void VerifyOutVar(CSharpCompilation compilation, string expectedType) { if (SkipVerify(expectedType)) { return; } var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var outVar = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(outVar).Symbol.GetSymbol<LocalSymbol>(); Assert.Equal(expectedType, symbol.TypeWithAnnotations.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); Assert.Null(model.GetDeclaredSymbol(outVar)); } /// <summary> /// Check the inferred type of var from the semantic model, which currently means from initial binding. /// </summary> private static void VerifyVarLocal(CSharpCompilation compilation, string expectedType) { if (SkipVerify(expectedType)) { return; } var tree = compilation.SyntaxTrees.First(); var model = compilation.GetSemanticModel(tree); var varDecl = tree.GetRoot().DescendantNodes().OfType<LocalDeclarationStatementSyntax>().Where(d => d.Declaration.Type.IsVar).Single(); var variable = varDecl.Declaration.Variables.Single(); var symbol = model.GetDeclaredSymbol(variable).GetSymbol<LocalSymbol>(); Assert.Equal(expectedType, symbol.TypeWithAnnotations.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); Assert.Null(model.GetSymbolInfo(variable).Symbol); } // https://github.com/dotnet/roslyn/issues/30150: VerifyOutVar and VerifyVarLocal are currently // checking the type and nullability from initial binding, but there are many cases where initial binding // sets nullability to unknown - in particular, for method type inference which is used in many // of the existing callers of these methods. Re-enable these methods when we're checking the // nullability from NullableWalker instead of initial binding. private static bool SkipVerify(string expectedType) { return expectedType.Contains('?') || expectedType.Contains('!'); } [Fact] public void MethodWithGenericOutParameter() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { Copy(key, out var s); s/*T:string?*/.ToString(); // warn } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string!"); // https://github.com/dotnet/roslyn/issues/29856: expecting string? c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericOutParameter_WithUnnecessarySuppression() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { Copy(key!, out var s); s/*T:string!*/.ToString(); } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void VarLocal_FromGenericMethod_WithUnnecessarySuppression() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { var s = Copy(key!); s/*T:string!*/.ToString(); s = null; } public static T Copy<T>(T key) => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact, WorkItem(40755, "https://github.com/dotnet/roslyn/pull/40755")] public void VarLocal_ValueTypeUsedAsRefArgument() { var source = @"#nullable enable public class C { delegate void Delegate<T>(ref T x); void M2<T>(ref T x, Delegate<T> f) { } void M() { var x = 1; M2(ref x, (ref int i) => { }); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void VarLocal_FromGenericMethod() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { var s = Copy(key); s/*T:string?*/.ToString(); // warn s = null; } public static T Copy<T>(T key) => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string!"); // https://github.com/dotnet/roslyn/issues/29856: expecting string? c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericOutParameter_WithNonNullArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { key = ""hello""; CopyOrDefault(key, out var s); s/*T:string!*/.ToString(); // ok s = null; } public static void CopyOrDefault<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void MethodWithGenericNullableOutParameter() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { CopyOrDefault(key, out var s); s/*T:string?*/.ToString(); // warn } public static void CopyOrDefault<T>(T key, out T? value) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericNullableOutParameter_WithNullableArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { CopyOrDefault(key, out var s); s/*T:string?*/.ToString(); // warn } public static void CopyOrDefault<T>(T key, out T? value) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (6,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.CopyOrDefault<T>(T, out T?)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // CopyOrDefault(key, out var s); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "CopyOrDefault").WithArguments("C.CopyOrDefault<T>(T, out T?)", "T", "string?").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericNullableOutParameter_WithNonNullArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { key = ""hello""; CopyOrDefault(key, out var s); s/*T:string?*/.ToString(); // warn } public static void CopyOrDefault<T>(T key, out T? value) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); } [Fact] public void MethodWithGenericNullableArrayOutParameter() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { CopyOrDefault(key, out var s); s/*T:string?[]!*/[0].ToString(); // warn } public static void CopyOrDefault<T>(T key, out T?[] value) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?[]!"); c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?[]!*/[0].ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s/*T:string?[]!*/[0]").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericNullableArrayOutParameter_WithNullableArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { CopyOrDefault(key, out var s); s/*T:string?[]!*/[0].ToString(); // warn } public static void CopyOrDefault<T>(T key, out T?[] value) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?[]!"); c.VerifyTypes(); c.VerifyDiagnostics( // (6,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.CopyOrDefault<T>(T, out T?[])'. Nullability of type argument 'string?' doesn't match 'class' constraint. // CopyOrDefault(key, out var s); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "CopyOrDefault").WithArguments("C.CopyOrDefault<T>(T, out T?[])", "T", "string?").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?[]!*/[0].ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s/*T:string?[]!*/[0]").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericArrayOutParameter_WithNonNullableArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { CopyOrDefault(key, out var s); s/*T:string![]!*/[0].ToString(); // ok } public static void CopyOrDefault<T>(T key, out T[] value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string![]!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] [WorkItem(29295, "https://github.com/dotnet/roslyn/issues/29295")] public void CatchException() { var c = CreateCompilation(@" class C { void M() { try { System.Console.WriteLine(); } catch (System.Exception e) { e.ToString(); } } } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(29295, "https://github.com/dotnet/roslyn/issues/29295")] public void CatchException_WithWhenIsOperator() { var c = CreateCompilation(@" class C { void M() { try { System.Console.WriteLine(); } catch (System.Exception e) when (!(e is System.ArgumentException)) { e.ToString(); } } } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(29295, "https://github.com/dotnet/roslyn/issues/29295")] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void CatchException_NullableType() { var c = CreateCompilation(@" class C { void M() { try { System.Console.WriteLine(); } catch (System.Exception? e) { var e2 = Copy(e); e2.ToString(); e2 = null; e.ToString(); } } static U Copy<U>(U u) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(29295, "https://github.com/dotnet/roslyn/issues/33540")] public void CatchException_ConstrainedGenericTypeParameter() { var c = CreateCompilation(@" class C { static void M<T>() where T : System.Exception? { try { } catch (T e) { var e2 = Copy(e); e2.ToString(); // 1 e.ToString(); } } static U Copy<U>(U u) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // e2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e2").WithLocation(12, 13)); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_TopLevelNullability() { var c = CreateCompilation(@" class C { public void M() { string? s = """"; M(ref s); s.ToString(); // 1 string s2 = """"; M(ref s2); // 2 s2.ToString(); // 3 string s3 = null; // 4 M2(ref s3); // 5 s3.ToString(); } void M(ref string? s) => throw null!; void M2(ref string s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (11,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // M(ref s2); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s2").WithLocation(11, 15), // (12,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 9), // (14,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string s3 = null; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 21), // (15,16): warning CS8601: Possible null reference assignment. // M2(ref s3); // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s3").WithLocation(15, 16) ); } [Fact] public void RefParameter_WarningKind() { var c = CreateCompilation(@" class C { string field = """"; public void M() { string local = """"; M(ref local); // 1, W-warning M(ref field); // 2 M(ref RefString()); // 3 } ref string RefString() => throw null!; void M(ref string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // M(ref local); // 1, W-warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "local").WithLocation(8, 15), // (10,15): warning CS8601: Possible null reference assignment. // M(ref field); // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "field").WithLocation(10, 15), // (12,15): warning CS8601: Possible null reference assignment. // M(ref RefString()); // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "RefString()").WithLocation(12, 15) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_TopLevelNullability_AlwaysSet() { var c = CreateCompilation(@" class C { public void M() { string? s = null; M(ref s); s.ToString(); } void M(ref string s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (7,15): warning CS8601: Possible null reference assignment. // M(ref s); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(7, 15) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_TopLevelNullability_Suppressed() { var c = CreateCompilation(@" class C { public void M() { string? s = """"; M(ref s!); s.ToString(); // no warning string s2 = """"; M(ref s2!); // no warning s2.ToString(); // no warning } void M(ref string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_VariousLValues() { var c = CreateCompilation(@" class C { string field = """"; string Property { get; set; } = """"; public void M() { M(ref null); // 1 M(ref """"); // 2 M(ref field); // 3 field.ToString(); // 4 M(ref Property); // 5 Property = null; // 6 } void M(ref string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,15): error CS1510: A ref or out value must be an assignable variable // M(ref null); // 1 Diagnostic(ErrorCode.ERR_RefLvalueExpected, "null").WithLocation(8, 15), // (9,15): error CS1510: A ref or out value must be an assignable variable // M(ref ""); // 2 Diagnostic(ErrorCode.ERR_RefLvalueExpected, @"""""").WithLocation(9, 15), // (11,15): warning CS8601: Possible null reference assignment. // M(ref field); // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "field").WithLocation(11, 15), // (12,9): warning CS8602: Dereference of a possibly null reference. // field.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field").WithLocation(12, 9), // (14,15): error CS0206: A property or indexer may not be passed as an out or ref parameter // M(ref Property); // 5 Diagnostic(ErrorCode.ERR_RefProperty, "Property").WithArguments("C.Property").WithLocation(14, 15), // (15,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // Property = null; // 6 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 20) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_TopLevelNullability_Extension() { var c = CreateCompilation(@" public class C { public void M() { string? s = """"; this.M(ref s); s.ToString(); // 1 string s2 = """"; this.M(ref s2); // 2 s2.ToString(); // 3 } } public static class Extension { public static void M(this C c, ref string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (11,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // this.M(ref s2); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s2").WithLocation(11, 20), // (12,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 9) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_TopLevelNullability_Generic() { var c = CreateCompilation(@" class C { public void M<T>() where T : new() { T t = new T(); M(ref t); t.ToString(); // 1 } void M<T>(ref T t) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(8, 9) ); } [Fact] [WorkItem(37909, "https://github.com/dotnet/roslyn/issues/37909")] public void RefParameter_TypeInferenceUsesRValueType() { var c = CreateNullableCompilation(@" class C { public void M(string? s) { if (s is null) return; var t = M2(ref s); s.ToString(); t.ToString(); } T M2<T>(ref T t) => throw null!; } "); c.VerifyDiagnostics(); } [Fact] [WorkItem(37909, "https://github.com/dotnet/roslyn/issues/37909")] public void OutParameter_TypeInferenceUsesLValueType() { var c = CreateNullableCompilation(@" class C { void M() { string? s1; var t1 = M2(out s1); s1.ToString(); // 1 t1.ToString(); // 2 string? s2 = string.Empty; var t2 = M2(out s2); s2.ToString(); // 3 t2.ToString(); // 4 string? s3 = null; var t3 = M2(out s3); s3.ToString(); // 5 t3.ToString(); // 6 } T M2<T>(out T t) => throw null!; } "); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(9, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(14, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // s3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // t3.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3").WithLocation(19, 9) ); } [Fact] [WorkItem(47663, "https://github.com/dotnet/roslyn/issues/47663")] public void RefParameter_Issue_47663() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { static void X1<T>([NotNullIfNotNull(""value"")] ref T location, T value) where T : class? { } static void X2<T>(ref T location, T value) where T : class? { } private readonly double[] f1; private readonly double[] f2; C() { double[] bar = new double[3]; X1(ref f1, bar); X2(ref f2, bar); // 1, warn on outbound assignment } } "; var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyEmitDiagnostics( // (14,5): warning CS8618: Non-nullable field 'f2' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C", isSuppressed: false).WithArguments("field", "f2").WithLocation(14, 5), // (18,16): warning CS8601: Possible null reference assignment. // X2(ref f2, bar); // 1, warn on outbound assignment Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "f2", isSuppressed: false).WithLocation(18, 16) ); } [Fact] public void RefParameter_InterlockedExchange_ObliviousContext() { var source = @" #nullable enable warnings class C { object o; void M() { InterlockedExchange(ref o, null); } #nullable enable void InterlockedExchange<T>(ref T location, T value) { } } "; // This situation was encountered in VS codebases // Here we convert `ref object~` (oblivious) to `ref object?` and expect no warnings. var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( ); } [Fact] public void RefParameter_InterlockedExchange_NullableEnabledContext() { var source = @" #nullable enable class C { object? o; void M() { InterlockedExchange(ref o, null); } void InterlockedExchange<T>(ref T location, T value) { } } "; // With proper annotation on the field, we have no warning var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] public void RefParameter_MiscPermutations() { var source = @" #nullable enable class C { static T X<T>(ref T x, ref T y) => throw null!; void M1(string? maybeNull) { X(ref maybeNull, ref maybeNull).ToString(); // 1 } void M2(string? maybeNull, string notNull) { X(ref maybeNull, ref notNull).ToString(); // 2 } void M3(string notNull) { X(ref notNull, ref notNull).ToString(); } void M4(string? maybeNull, string notNull) { X(ref notNull, ref maybeNull).ToString(); // 3 } } "; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // X(ref maybeNull, ref maybeNull).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "X(ref maybeNull, ref maybeNull)").WithLocation(10, 9), // (15,15): warning CS8601: Possible null reference assignment. // X(ref maybeNull, ref notNull).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "maybeNull").WithLocation(15, 15), // (25,28): warning CS8601: Possible null reference assignment. // X(ref notNull, ref maybeNull).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "maybeNull").WithLocation(25, 28) ); } [Fact] [WorkItem(35534, "https://github.com/dotnet/roslyn/issues/35534")] public void RefParameter_Issue_35534() { var source = @" #nullable enable public class C { void M2() { string? x = ""hello""; var y = M(ref x); y.ToString(); } T M<T>(ref T t) { throw null!; } }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(37909, "https://github.com/dotnet/roslyn/issues/37909")] [WorkItem(43536, "https://github.com/dotnet/roslyn/issues/43536")] public void RefParameter_TypeInferenceUsesRValueType_WithNullArgument() { var c = CreateNullableCompilation(@" class C { public void M(string? s) { if (s is null) return; var t = Copy(ref s, null); s.ToString(); // 1 t.ToString(); // 2 } public void M2(string? s) { if (s is null) return; var t = Copy2(s, null); s.ToString(); t.ToString(); // 3 } T Copy<T>(ref T t, T t2) => throw null!; T Copy2<T>(T t, T t2) => throw null!; } "); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(9, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(16, 9) ); } [Fact] [WorkItem(37909, "https://github.com/dotnet/roslyn/issues/37909")] public void OutParameter_TypeInferenceUsesLValueType_WithNullArgument() { var c = CreateNullableCompilation(@" class C { public void M(string? s) { if (s is null) return; var t = Copy(out s, null); s.ToString(); // 1 t.ToString(); // 2 } T Copy<T>(out T t, T t2) => throw null!; } "); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(9, 9) ); } [Fact] [WorkItem(37909, "https://github.com/dotnet/roslyn/issues/37909")] public void ByValParameter_TypeInferenceUsesRValueType() { var c = CreateNullableCompilation(@" class C { public void M(string? s) { if (s is null) return; var t = M2(s); t.ToString(); } T M2<T>(T t) => throw null!; } "); c.VerifyDiagnostics(); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_TopLevelNullability_Generic_Suppressed() { var c = CreateCompilation(@" class C { public void M<T>() where T : new() { T t = new T(); M(ref t!); t.ToString(); // no warning } void M<T>(ref T t) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_NestedNullability() { var c = CreateCompilation(@" class C<T> { public void M(C<string?> s, C<string> s2) { M(ref s); s.ToString(); M(ref s2); // 1, 2 s2.ToString(); } void M(ref C<string?> s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (9,15): warning CS8620: Argument of type 'C<string>' cannot be used as an input of type 'C<string?>' for parameter 's' in 'void C<T>.M(ref C<string?> s)' due to differences in the nullability of reference types. // M(ref s2); // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2").WithArguments("C<string>", "C<string?>", "s", "void C<T>.M(ref C<string?> s)").WithLocation(9, 15)); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_EvaluationOrder() { var c = CreateCompilation(@" class C<T> { public void M(bool b) { string? s = """"; var v1 = M(ref s, b ? s : """"); s.ToString(); // 1 v1.ToString(); s = null; var v2 = M(ref s, s); s.ToString(); // 2 v2.ToString(); // 3 s = null; var v3 = M2(ref s, s); // 4 s.ToString(); v3.ToString(); // 5 } U M<U>(ref string? s, U u) => throw null!; U M2<U>(ref string s, U u) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // v2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v2").WithLocation(14, 9), // (17,25): warning CS8601: Possible null reference assignment. // var v3 = M2(ref s, s); // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(17, 25), // (19,9): warning CS8602: Dereference of a possibly null reference. // v3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v3").WithLocation(19, 9) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_EvaluationOrder_VisitLValuesOnce() { var c = CreateCompilation(@" class C { ref string? F(string? x) => throw null!; void G(ref string? s) => throw null!; public void M() { string s = """"; G(ref F(s = null)); } } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,16): warning CS0219: The variable 's' is assigned but its value is never used // string s = ""; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "s").WithArguments("s").WithLocation(8, 16), // (9,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // G(ref F(s = null)); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(9, 21) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void RefParameter_EvaluationOrder_VisitMultipleLValues() { var c = CreateCompilation(@" class C { void F(ref string? s) => throw null!; public void M(bool b) { string? s = """"; string? s2 = """"; F(ref (b ? ref s : ref s2)); s.ToString(); // 1 s2.ToString(); // 2 } } ", options: WithNullableEnable()); // Missing warnings // Need to track that an expression as an L-value corresponds to multiple slots // Relates to https://github.com/dotnet/roslyn/issues/33365 c.VerifyDiagnostics(); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_TopLevelNullability() { var c = CreateCompilation(@" class C { public void M() { string? s = """"; M(out s); s.ToString(); // 1 string s2 = """"; M(out s2); // 2 s2.ToString(); // 3 } void M(out string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (11,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // M(out s2); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s2").WithLocation(11, 15), // (12,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 9) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_TopLevelNullability_DeclarationExpression() { var c = CreateCompilation(@" class C { public void M() { M(out string? s); s.ToString(); // 1 M(out string s2); // 2 s2.ToString(); // 3 } void M(out string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9), // (9,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // M(out string s2); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "string s2").WithLocation(9, 15), // (10,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 9) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_TopLevelNullability_Suppressed() { var c = CreateCompilation(@" class C { public void M() { string? s = """"; M(out s!); s.ToString(); // no warning string s2 = """"; M(out s2!); // no warning s2.ToString(); // no warning } void M(out string? s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_TopLevelNullability_Generic() { var c = CreateCompilation(@" class C { public void M<T>() where T : new() { T t = new T(); M(out t); t.ToString(); // 1 } void M<T>(out T t) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(8, 9) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_TopLevelNullability_Generic_Suppressed() { var c = CreateCompilation(@" class C { public void M<T>() where T : new() { T t = new T(); M(out t!); t.ToString(); // no warning } void M<T>(out T t) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_NestedNullability() { var c = CreateCompilation(@" class C<T> { public void M(C<string?> s, C<string> s2) { M(out s); s.ToString(); M(out s2); // 1 s2.ToString(); } void M(out C<string?> s) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (9,15): warning CS8624: Argument of type 'C<string>' cannot be used as an output of type 'C<string?>' for parameter 's' in 'void C<T>.M(out C<string?> s)' due to differences in the nullability of reference types. // M(out s2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "s2").WithArguments("C<string>", "C<string?>", "s", "void C<T>.M(out C<string?> s)").WithLocation(9, 15) ); } [Fact] [WorkItem(26739, "https://github.com/dotnet/roslyn/issues/26739")] public void OutParameter_EvaluationOrder() { var c = CreateCompilation(@" class C<T> { public void M(bool b) { string? s = """"; var v1 = M(out s, b ? s : """"); s.ToString(); // 1 v1.ToString(); s = null; var v2 = M(out s, s); s.ToString(); // 2 v2.ToString(); // 3 s = null; var v3 = M2(out s, s); s.ToString(); v3.ToString(); // 4 } U M<U>(out string? s, U u) => throw null!; U M2<U>(out string s, U u) => throw null!; } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // v2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v2").WithLocation(14, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // v3.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v3").WithLocation(19, 9) ); } [Fact] public void MethodWithGenericArrayOutParameter_WithNonNullArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { key = ""hello""; CopyOrDefault(key, out var s); s/*T:string![]!*/[0].ToString(); // ok } public static void CopyOrDefault<T>(T key, out T[] value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string![]!"); // https://github.com/dotnet/roslyn/issues/29856: expecting string?[]! c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void MethodWithGenericOutParameter_WithNotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? key) { Copy(key, out var s); // ok s/*T:string!*/.ToString(); // ok } public static void Copy<T>(T key, [NotNull] out T value) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); VerifyOutVar(c, "string!"); // https://github.com/dotnet/roslyn/issues/29856: T is inferred to string! instead of string?, so the `var` gets `string!` c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void MethodWithGenericNullableOutParameter_WithNotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? key) { Copy(key, out var s); // ok s/*T:string!*/.ToString(); // ok } public static void Copy<T>(T key, [NotNull] out T? value) where T : class => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.Copy<T>(T, out T?)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // Copy(key, out var s); // ok Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Copy").WithArguments("C.Copy<T>(T, out T?)", "T", "string?").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericOutParameter_WithNullLiteralArgument_WithNonNullableString() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main() { Copy(null, out string s); // warn s/*T:string?*/.ToString(); // warn } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics( // (6,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // Copy(null, out string s); // warn Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "string s").WithLocation(6, 24), // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericOutParameter_WithNonNullableArgument_WithNonNullableString() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { Copy(key, out string s); s/*T:string!*/.ToString(); } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] [WorkItem(29857, "https://github.com/dotnet/roslyn/issues/29857")] public void MethodWithGenericOutParameter_WithNullableArgument_WithNonNullableString() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { Copy(key, out string s); s/*T:string?*/.ToString(); } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Copy(key, out string s); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "string s").WithLocation(6, 23), // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericOutParameter_WithNonNullableArgument_WithNullableString() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { Copy(key, out string? s); s/*T:string?*/.ToString(); } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void MethodWithGenericOutParameter_WithNullableArgument_WithNullableString() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { Copy(key, out string? s); s/*T:string?*/.ToString(); // warn } public static void Copy<T>(T key, out T value) => throw null!; } " }, options: WithNullableEnable()); VerifyOutVar(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void VarLocalFromGenericMethod() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string key) { var s = Copy(key); s/*T:string!*/.ToString(); // ok } public T Copy<T>(T key) => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void VarLocalFromGenericMethod_WithNullableArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { var s = Copy(key); s/*T:string?*/.ToString(); // warn } public T Copy<T>(T key) => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string!"); // https://github.com/dotnet/roslyn/issues/29856: expecting string? c.VerifyTypes(); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void VarLocalFromGenericMethod_WithNonNullArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { key = ""hello""; var s = Copy(key); s/*T:string!*/.ToString(); // ok } public T Copy<T>(T key) => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void VarLocalFromGenericMethod_WithNullableReturn() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { var s = Copy(key); s/*T:string?*/.ToString(); // warn } public T? Copy<T>(T key) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (6,17): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.Copy<T>(T)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var s = Copy(key); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Copy").WithArguments("C.Copy<T>(T)", "T", "string?").WithLocation(6, 17), // (7,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void VarLocalFromGenericMethod_WithNullableReturn_WithNonNullArgument() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string? key) { key = ""hello""; var s = Copy(key); s/*T:string?*/.ToString(); // warn } public T? Copy<T>(T key) where T : class => throw null!; } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string?"); c.VerifyTypes(); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s/*T:string?*/.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); } [Fact] [WorkItem(29858, "https://github.com/dotnet/roslyn/issues/29858")] public void GenericMethod_WithNotNullOnMethod() { CSharpCompilation c = CreateCompilation(@" using System.Diagnostics.CodeAnalysis; public class C { [NotNull] public static T Copy<T>(T key) => throw null!; } " + NotNullAttributeDefinition); c.VerifyDiagnostics( // (5,6): error CS0592: Attribute 'NotNull' is not valid on this declaration type. It is only valid on 'property, indexer, field, parameter, return' declarations. // [NotNull] Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "NotNull").WithArguments("NotNull", "property, indexer, field, parameter, return").WithLocation(5, 6) ); } [Fact] [WorkItem(29862, "https://github.com/dotnet/roslyn/issues/29862")] public void SuppressedNullGivesNonNullResult() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string s) { s = null!; var s2 = s; s2 /*T:string!*/ .ToString(); // ok s2 = null; } } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] [WorkItem(29862, "https://github.com/dotnet/roslyn/issues/29862")] public void SuppressedDefaultGivesNonNullResult() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string s) { s = default!; // default! returns a non-null result var s2 = s; s2/*T:string!*/.ToString(); // ok } } " }, options: WithNullableEnable()); VerifyVarLocal(c, "string!"); c.VerifyTypes(); c.VerifyDiagnostics(); } [Fact] public void SuppressedObliviousValueGivesNonNullResult() { var libComp = CreateCompilation(@" public static class Static { public static string Oblivious = null; } ", parseOptions: TestOptions.Regular7); var comp = CreateCompilation(new[] { @" public class C { public void Main(string s, string? ns) { s = Static.Oblivious!; var s2 = s; s2/*T:string!*/.ToString(); // ok ns = Static.Oblivious!; ns.ToString(); // ok } } " }, options: WithNullableEnable(), references: new[] { libComp.EmitToImageReference() }); VerifyVarLocal(comp, "string!"); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void SuppressedValueGivesNonNullResult() { var comp = CreateCompilation(new[] { @" public class C { public void Main(string? ns, bool b) { var x1 = F(ns!); x1 /*T:string!*/ .ToString(); var listNS = List.Create(ns); listNS /*T:List<string?>!*/ .ToString(); var x2 = F2(listNS); x2 /*T:string!*/ .ToString(); } public T F<T>(T? x) where T : class => throw null!; public T F2<T>(List<T?> x) where T : class => throw null!; } public class List { public static List<T> Create<T>(T t) => throw null!; } public class List<T> { } " }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void NestedNullabilityMismatchIgnoresSuppression() { var obliviousComp = CreateCompilation(@" public static class Static { public static string Oblivious = null; } ", parseOptions: TestOptions.Regular7); var comp = CreateCompilation(new[] { @" public class C { public void Main(string s, string? ns) { var o = Static.Oblivious; { var listS = List.Create(s); var listNS = List.Create(ns); listS /*T:List<string!>!*/ .ToString(); listNS /*T:List<string?>!*/ .ToString(); listS = listNS!; // 1 } { var listS = List.Create(s); var listO = List.Create(o); listO /*T:List<string!>!*/ .ToString(); listS = listO; // ok } { var listNS = List.Create(ns); var listS = List.Create(s); listNS = listS!; // 2 } { var listNS = List.Create(ns); var listO = List.Create(o); listNS = listO!; // 3 } { var listO = List.Create(o); var listNS = List.Create(ns); listO = listNS!; // 4 } { var listO = List.Create(o); var listS = List.Create(s); listO = listS; // ok } } } public class List { public static List<T> Create<T>(T t) => throw null!; } public class List<T> { } " }, options: WithNullableEnable(), references: new[] { obliviousComp.EmitToImageReference() }); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void AssignNull() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string s) { s = null; // warn s.ToString(); // warn 2 } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // warn Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void AssignDefault() { CSharpCompilation c = CreateCompilation(new[] { @" public class C { public void Main(string s) { s = default; // warn s.ToString(); // warn 2 } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = default; // warn Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9) ); } [Fact] public void NotNullWhenTrue_Simple() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string key) { if (TryGetValue(key, out string? s)) { s.ToString(); // ok } else { s.ToString(); // warn } s.ToString(); // ok } public static bool TryGetValue(string key, [NotNullWhen(true)] out string? value) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); VerifyAnnotationsAndMetadata(c, "C.Main", None); VerifyAnnotationsAndMetadata(c, "C.TryGetValue", None, NotNullWhenTrue); } [Fact] public void NotNullWhenTrue_Ref() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string key) { string? s = null; if (TryGetValue(key, ref s)) { s.ToString(); // ok } else { s.ToString(); // warn } } public static bool TryGetValue(string key, [NotNullWhen(true)] ref string? value) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 13) ); } [Fact] public void NotNullWhenTrue_Nested() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (IsNotNull(s?.ToString())) { s.ToString(); } else { s.ToString(); // warn } } public static bool IsNotNull([NotNullWhen(true)] string? value) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); } [Fact] public void NotNullWhenTrue_WithNotNullWhenFalse_WithVoidReturn() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main() { M(out string? s); s.ToString(); // 1 } public static void M([NotNullWhen(true), NotNullWhen(false)] out string? value) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (10,46): error CS0579: Duplicate 'NotNullWhen' attribute // public static void M([NotNullWhen(true), NotNullWhen(false)] out string? value) => throw null!; Diagnostic(ErrorCode.ERR_DuplicateAttribute, "NotNullWhen").WithArguments("NotNullWhen").WithLocation(10, 46) ); VerifyAnnotations(c, "C.M", NotNullWhenTrue); } [Fact, WorkItem(37081, "https://github.com/dotnet/roslyn/issues/37081")] public void DoesNotReturn_Simple() { string lib_cs = @" using System.Diagnostics.CodeAnalysis; public class C { [DoesNotReturn] public static void Throw() => throw null!; } "; string source = @" class D { void Main(object? o) { string unassigned; C.Throw(); o.ToString(); // unreachable for purpose of nullability analysis so no warning unassigned.ToString(); // 1, reachable for purpose of definite assignment } } "; // Should [DoesNotReturn] affect all flow analyses? https://github.com/dotnet/roslyn/issues/37081 var expected = new[] { // (9,9): error CS0165: Use of unassigned local variable 'unassigned' // unassigned.ToString(); // 1, reachable for purpose of definite assignment Diagnostic(ErrorCode.ERR_UseDefViolation, "unassigned").WithArguments("unassigned").WithLocation(9, 9) }; var lib = CreateNullableCompilation(new[] { lib_cs, DoesNotReturnAttributeDefinition }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DoesNotReturnAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact, WorkItem(45795, "https://github.com/dotnet/roslyn/issues/45795")] public void DoesNotReturn_ReturnStatementInLocalFunction() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable public class C { [DoesNotReturn] public void M() { _ = local1(); local2(); throw null!; int local1() { return 1; } void local2() { return; } } } "; var comp = CreateCompilation(new[] { source, DoesNotReturnAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(37081, "https://github.com/dotnet/roslyn/issues/37081")] public void LocalFunctionAlwaysThrows() { string source = @" class D { void Main(object? o) { string unassigned; boom(); o.ToString(); // 1 - reachable in nullable analysis unassigned.ToString(); // unreachable due to definite assignment analysis of local functions void boom() { throw null!; } } } "; // Should local functions which do not return affect nullability analysis? https://github.com/dotnet/roslyn/issues/45814 var comp = CreateNullableCompilation(new[] { source, DoesNotReturnAttributeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 1 - reachable in nullable analysis Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(8, 9)); } [Fact] [WorkItem(37081, "https://github.com/dotnet/roslyn/issues/37081")] public void DoesNotReturn_LocalFunction_CheckImpl() { string source = @" using System.Diagnostics.CodeAnalysis; class D { void Main(object? o) { boom(); [DoesNotReturn] void boom() { } } } "; // Should local functions support `[DoesNotReturn]`? https://github.com/dotnet/roslyn/issues/45814 var comp = CreateNullableCompilation(new[] { source, DoesNotReturnAttributeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact, WorkItem(45791, "https://github.com/dotnet/roslyn/issues/45791")] public void DoesNotReturn_VoidReturningMethod() { string source = @" using System.Diagnostics.CodeAnalysis; public class C { [DoesNotReturn] public void M() { return; } } "; var comp = CreateNullableCompilation(new[] { source, DoesNotReturnAttributeDefinition }); comp.VerifyDiagnostics( // (9,9): warning CS8763: A method marked [DoesNotReturn] should not return. // return; Diagnostic(ErrorCode.WRN_ShouldNotReturn, "return;").WithLocation(9, 9) ); } [Fact] public void DoesNotReturn_Operator() { // Annotations not honored on user-defined operators yet https://github.com/dotnet/roslyn/issues/32671 string lib_cs = @" using System.Diagnostics.CodeAnalysis; public class C { [DoesNotReturn] public static C operator +(C a, C b) => throw null!; } "; string source = @" class D { void Main(object? o, C c) { _ = c + c; o.ToString(); // unreachable so no warning } } "; var lib = CreateNullableCompilation(new[] { lib_cs, DoesNotReturnAttributeDefinition }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // unreachable so no warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(7, 9) ); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DoesNotReturnAttributeDefinition }); comp2.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // unreachable so no warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(7, 9) ); } [Fact] public void DoesNotReturn_WithDoesNotReturnIf() { string lib_cs = @" using System.Diagnostics.CodeAnalysis; public class C { [DoesNotReturn] public static bool Throw([DoesNotReturnIf(true)] bool x) => throw null!; } "; string source = @" class D { void Main(object? o, bool b) { _ = C.Throw(b) ? o.ToString() : o.ToString(); } } "; var lib = CreateNullableCompilation(new[] { lib_cs, DoesNotReturnAttributeDefinition, DoesNotReturnIfAttributeDefinition }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DoesNotReturnAttributeDefinition, DoesNotReturnIfAttributeDefinition }); comp2.VerifyDiagnostics(); } [Fact] public void DoesNotReturn_OnOverriddenMethod() { string lib_cs = @" using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool MayThrow() => throw null!; } public class C : Base { [DoesNotReturn] public override bool MayThrow() => throw null!; } "; string source = @" class D { void Main(object? o, object? o2, bool b) { _ = new Base().MayThrow() ? o.ToString() // 1 : o.ToString(); // 2 _ = new C().MayThrow() ? o2.ToString() : o2.ToString(); } } "; var expected = new[] { // (7,15): warning CS8602: Dereference of a possibly null reference. // ? o.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(7, 15), // (8,15): warning CS8602: Dereference of a possibly null reference. // : o.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(8, 15) }; var lib = CreateNullableCompilation(new[] { lib_cs, DoesNotReturnAttributeDefinition, DoesNotReturnIfAttributeDefinition }); var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DoesNotReturnAttributeDefinition, DoesNotReturnIfAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void DoesNotReturn_OnImplementation() { string source = @" using System.Diagnostics.CodeAnalysis; public interface I { bool MayThrow(); } public class C1 : I { [DoesNotReturn] public bool MayThrow() => throw null!; } public class C2 : I { [DoesNotReturn] bool I.MayThrow() => throw null!; } public interface I2 { [DoesNotReturn] bool MayThrow(); } public class C3 : I2 { public bool MayThrow() => throw null!; // 1 } public class C4 : I2 { bool I2.MayThrow() => throw null!; // 2 } "; var comp = CreateNullableCompilation(new[] { source, DoesNotReturnAttributeDefinition }); comp.VerifyDiagnostics( // (22,17): warning CS8770: Method 'bool C3.MayThrow()' lacks `[DoesNotReturn]` annotation to match implemented or overridden member. // public bool MayThrow() => throw null!; // 1 Diagnostic(ErrorCode.WRN_DoesNotReturnMismatch, "MayThrow").WithArguments("bool C3.MayThrow()").WithLocation(22, 17), // (26,13): warning CS8770: Method 'bool C4.MayThrow()' lacks `[DoesNotReturn]` annotation to match implemented or overridden member. // bool I2.MayThrow() => throw null!; // 2 Diagnostic(ErrorCode.WRN_DoesNotReturnMismatch, "MayThrow").WithArguments("bool C4.MayThrow()").WithLocation(26, 13) ); } [Fact] public void DoesNotReturnIfFalse_NotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { MyAssert(c != null); c.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(38124, "https://github.com/dotnet/roslyn/issues/38124")] public void DoesNotReturnIfFalse_AssertBooleanConstant() { var source = @" using System.Diagnostics.CodeAnalysis; class C { static void M(string? s, string? s2) { MyAssert(true); _ = s.Length; // 1 MyAssert(false); _ = s2.Length; } static void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, DoesNotReturnIfAttributeDefinition }); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13) ); } [Fact] public void DoesNotReturnIfFalse_NotNull_Nested() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { MyAssert(c?.ToString() != null); c.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void DoesNotReturnIfFalse_NotNull_InErrorInvocation() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { Missing(MyAssert(c != null)); c.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): error CS0103: The name 'Missing' does not exist in the current context // Missing(MyAssert(c != null)); Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(7, 9) ); } [Fact] public void DoesNotReturnIfFalse_NotNull_NullConditionalAccess() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { object? _o = null; void Main(C? c) { MyAssert(c?._o != null); c.ToString(); c._o.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DoesNotReturnIfFalse_Null() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { MyAssert(c == null); c.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void DoesNotReturnIfFalse_Null_InErrorInvocation() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { Missing(MyAssert(c == null)); c.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): error CS0103: The name 'Missing' does not exist in the current context // Missing(MyAssert(c == null)); Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9) ); } [Fact] public void DoesNotReturnIfFalse_RefOutInParameters() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(bool b) { MyAssert(ref b, out bool b2, in b); } void MyAssert([DoesNotReturnIf(false)] ref bool condition, [DoesNotReturnIf(true)] out bool condition2, [DoesNotReturnIf(false)] in bool condition3) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DoesNotReturnIfFalse_WithDoesNotReturnIfTrue() { CSharpCompilation c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void MyAssert([DoesNotReturnIf(false), DoesNotReturnIf(true)] bool condition) => throw null!; // 1 void MyAssert2([DoesNotReturnIf(true), DoesNotReturnIf(false)] bool condition) => throw null!; // 2 } ", DoesNotReturnIfAttributeDefinition }); c.VerifyDiagnostics( // (5,44): error CS0579: Duplicate 'DoesNotReturnIf' attribute // void MyAssert([DoesNotReturnIf(false), DoesNotReturnIf(true)] bool condition) => throw null!; // 1 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "DoesNotReturnIf").WithArguments("DoesNotReturnIf").WithLocation(5, 44), // (6,44): error CS0579: Duplicate 'DoesNotReturnIf' attribute // void MyAssert2([DoesNotReturnIf(true), DoesNotReturnIf(false)] bool condition) => throw null!; // 2 Diagnostic(ErrorCode.ERR_DuplicateAttribute, "DoesNotReturnIf").WithArguments("DoesNotReturnIf").WithLocation(6, 44) ); } [Fact] public void DoesNotReturnIfFalse_MethodWithReturnType() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { if (MyAssert(c != null)) { c.ToString(); } else { c.ToString(); } } bool MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void AssertsTrue_NotNullAndNotEmpty() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? c) { Assert(c != null && c != """"); c.ToString(); } static void Assert([DoesNotReturnIf(false)] bool b) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void AssertsTrue_NotNullOrUnknown() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? c, bool b) { Assert(c != null || b); c.ToString(); } static void Assert([DoesNotReturnIf(false)] bool b) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9) ); } [Fact] public void AssertsTrue_IsNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C c) { Assert(c == null, ""hello""); c.ToString(); } static void Assert([DoesNotReturnIf(false)] bool b, string message) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9) ); } [Fact] public void DoesNotReturnIfFalse_NoDuplicateDiagnostics() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { Assert(Method(null), ""hello""); c.ToString(); } bool Method(string x) => throw null!; static void Assert([DoesNotReturnIf(false)] bool b, string message) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,23): warning CS8625: Cannot convert null literal to non-nullable reference type. // Assert(Method(null), "hello"); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 23), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9) ); } [Fact] public void DoesNotReturnIfFalse_InTry() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { try { Assert(c != null, ""hello""); } catch { } c.ToString(); } static void Assert([DoesNotReturnIf(false)] bool b, string message) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(13, 9) ); } [Fact] public void DoesNotReturnIfTrue_Null() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { MyAssert(c == null); c.ToString(); } void MyAssert([DoesNotReturnIf(true)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DoesNotReturnIfTrue_NotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(C? c) { MyAssert(c != null); c.ToString(); } void MyAssert([DoesNotReturnIf(true)] bool condition) => throw null!; } ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9) ); } [Theory] [InlineData("true", "false")] [InlineData("false", "true")] public void DoesNotReturnIfTrue_DefaultArgument(string attributeArgument, string negatedArgument) { CSharpCompilation c = CreateCompilation(new[] { $@" using System.Diagnostics.CodeAnalysis; class C {{ void M1(C? c) {{ MyAssert1(); c.ToString(); }} void M2(C? c) {{ MyAssert1({attributeArgument}); c.ToString(); }} void M3(C? c) {{ MyAssert1({negatedArgument}); c.ToString(); // 1 }} void MyAssert1([DoesNotReturnIf({attributeArgument})] bool condition = {attributeArgument}) => throw null!; void M4(C? c) {{ MyAssert2(); c.ToString(); // 2 }} void M5(C? c) {{ MyAssert2({attributeArgument}); c.ToString(); }} void M6(C? c) {{ MyAssert2({negatedArgument}); c.ToString(); // 3 }} void MyAssert2([DoesNotReturnIf({attributeArgument})] bool condition = {negatedArgument}) => throw null!; }} ", DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (20,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(20, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(28, 9), // (40,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(40, 9)); } [Fact] [WorkItem(39868, "https://github.com/dotnet/roslyn/issues/39868")] public void BadNullableDefaultArgument() { string source = @" public struct MyStruct { static void M1(MyStruct? s = default(MyStruct)) { } // 1 static void M2() { M1(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (4,30): error CS1770: A value of type 'MyStruct' cannot be used as default parameter for nullable parameter 's' because 'MyStruct' is not a simple type // static void M1(MyStruct? s = default(MyStruct)) { } // 1 Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "s").WithArguments("MyStruct", "s").WithLocation(4, 30)); } [Fact] [WorkItem(51622, "https://github.com/dotnet/roslyn/issues/51622")] public void NullableEnumDefaultArgument_NonZeroValue() { string source = @" #nullable enable public enum E { E1 = 1 } class C { void M0(E? e = E.E1) { } void M1() { M0(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(39868, "https://github.com/dotnet/roslyn/issues/39868")] public void BadNonNullableReferenceDefaultArgument() { string source = @" public struct MyStruct { static void M1(string s = default(MyStruct)) { } // 1 static void M2() { M1(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (4,27): error CS1750: A value of type 'MyStruct' cannot be used as a default parameter because there are no standard conversions to type 'string' // static void M1(string s = default(MyStruct)) { } // 1 Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "s").WithArguments("MyStruct", "string").WithLocation(4, 27)); } [Fact] public void NotNullWhenFalse_Simple() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string? s) { if (MyIsNullOrEmpty(s)) { s.ToString(); // warn } else { s.ToString(); // ok } s.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); VerifyAnnotationsAndMetadata(c, "C.Main", None); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_BoolReturn() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public static object MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); VerifyAnnotations(c, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_OnTwoParameters() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s, string? s2) { if (MyIsNullOrEmpty(s, s2)) { s.ToString(); // warn 1 s2.ToString(); // warn 2 } else { s.ToString(); // ok s2.ToString(); // ok } s.ToString(); // ok s2.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s, [NotNullWhen(false)] string? s2) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (10,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 13) ); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNullWhenFalse, NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_WithNotNullWhenTrueOnSecondParameter() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s, string? s2) { if (MyIsNullOrEmpty(s, s2)) { s.ToString(); // warn 1 s2.ToString(); // ok } else { s.ToString(); // ok s2.ToString(); // warn 2 } s.ToString(); // ok s2.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s, [NotNullWhen(true)] string? s2) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(15, 13) ); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNullWhenFalse, NotNullWhenTrue); } [Fact] public void NotNullWhenFalse_OnIndexer() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s, int x) { if (this[s, x]) { s.ToString(); // warn } else { s.ToString(); // ok } s.ToString(); // ok } public bool this[[NotNullWhen(false)] string? s, int x] => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullWhenFalse_SecondArgumentDereferences() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { if (Method(s, s.ToString())) // warn 1 { s.ToString(); // ok } else { s.ToString(); // ok } } static bool Method([NotNullWhen(false)] string? s, string s2) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,23): warning CS8602: Dereference of a possibly null reference. // if (Method(s, s.ToString())) // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 23) ); } [Fact] public void NotNullWhenFalse_SecondArgumentAssigns() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { if (Method(s, s = null)) { s.ToString(); // 1 } else { s.ToString(); } } static bool Method([NotNullWhen(false)] string? s, string? s2) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullWhenFalse_MissingAttribute() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void Main(string? s) { if (MyIsNullOrEmpty(s)) { s.ToString(); // warn } else { s.ToString(); // warn 2 } s.ToString(); // ok } static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (17,34): error CS0246: The type or namespace name 'NotNullWhenAttribute' could not be found (are you missing a using directive or an assembly reference?) // static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotNullWhen").WithArguments("NotNullWhenAttribute").WithLocation(17, 34), // (17,34): error CS0246: The type or namespace name 'NotNullWhen' could not be found (are you missing a using directive or an assembly reference?) // static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotNullWhen").WithArguments("NotNullWhen").WithLocation(17, 34), // (8,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 13) ); VerifyAnnotations(c, "C.MyIsNullOrEmpty", None); } private static void VerifyAnnotations(CSharpCompilation compilation, string memberName, params FlowAnalysisAnnotations[] expected) { var method = compilation.GetMember<MethodSymbol>(memberName); Assert.True((object)method != null, $"Could not find method '{memberName}'"); var actual = method.Parameters.Select(p => p.FlowAnalysisAnnotations); Assert.Equal(expected, actual); } private void VerifyAnnotationsAndMetadata(CSharpCompilation compilation, string memberName, params FlowAnalysisAnnotations[] expected) { VerifyAnnotations(compilation, memberName, expected); // Also verify from metadata var compilation2 = CreateCompilation("", references: new[] { compilation.EmitToImageReference() }); VerifyAnnotations(compilation2, memberName, expected); } [Fact] public void NotNullWhenFalse_BadAttribute() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (MyIsNullOrEmpty(s)) { s.ToString(); // warn 1 } else { s.ToString(); // warn 2 } } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] public class NotNullWhenAttribute : Attribute { public NotNullWhenAttribute(bool when, bool other = false) { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", None); } [Fact] public void NotNullWhenFalse_InvertIf() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (!MyIsNullOrEmpty(s)) { s.ToString(); // ok } else { s.ToString(); // warn } } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13) ); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_WithNullLiteral() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { _ = MyIsNullOrEmpty(null); } static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNullWhenFalse_InstanceMethod() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (this.MyIsNullOrEmpty(s)) { s.ToString(); // warn } else { s.ToString(); // ok } } public bool MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_ExtensionMethod() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (this.MyIsNullOrEmpty(s)) { s.ToString(); // warn } else { s.ToString(); // ok } } } public static class Extension { public static bool MyIsNullOrEmpty(this C c, [NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); VerifyAnnotationsAndMetadata(c, "Extension.MyIsNullOrEmpty", None, NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_String_NotIsNullOrEmpty_NoDuplicateWarnings() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void M() { if (!string.IsNullOrEmpty(M2(null))) { } } string? M2(string s) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // if (!string.IsNullOrEmpty(M2(null))) Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 38) ); } [Fact] public void NotNullWhenFalse_String_NotIsNullOrEmpty_NotAString() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void M() { if (!string.IsNullOrEmpty(M2(null))) { } } void M2(string s) => throw null!; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,35): error CS1503: Argument 1: cannot convert from 'void' to 'string' // if (!string.IsNullOrEmpty(M2(null))) Diagnostic(ErrorCode.ERR_BadArgType, "M2(null)").WithArguments("1", "void", "string").WithLocation(6, 35), // (6,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // if (!string.IsNullOrEmpty(M2(null))) Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 38) ); } [Fact] public void NotNullWhenFalse_PartialMethod() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public partial class C { partial void M1(string? s); partial void M1([NotNullWhen(false)] string? s) => throw null!; partial void M2([NotNullWhen(false)] string? s); partial void M2(string? s) => throw null!; partial void M3([NotNullWhen(false)] string? s); partial void M3([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,22): error CS0579: Duplicate 'NotNullWhen' attribute // partial void M3([NotNullWhen(false)] string? s); Diagnostic(ErrorCode.ERR_DuplicateAttribute, "NotNullWhen").WithArguments("NotNullWhen").WithLocation(11, 22) ); VerifyAnnotations(c, "C.M1", NotNullWhenFalse); VerifyAnnotations(c, "C.M2", NotNullWhenFalse); VerifyAnnotations(c, "C.M3", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_ReturningDynamic() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (MyIsNullOrEmpty(s)) { s.ToString(); // warn } else { s.ToString(); } } public dynamic MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); VerifyAnnotations(c, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_ReturningObject_FromMetadata() { string il = @" .class private auto ansi sealed beforefieldinit System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig instance object MyIsNullOrEmpty (string s) cil managed { .param [1] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void System.Diagnostics.CodeAnalysis.NotNullWhenAttribute::.ctor(bool) = ( 01 00 00 00 00 ) IL_0000: ldnull IL_0001: throw } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldnull IL_0001: throw } } .class public auto ansi beforefieldinit System.Diagnostics.CodeAnalysis.NotNullWhenAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 00 08 00 00 01 00 54 02 0d 41 6c 6c 6f 77 4d 75 6c 74 69 70 6c 65 00 ) .method public hidebysig specialname rtspecialname instance void .ctor (bool when) cil managed { IL_0000: ldnull IL_0001: throw } } "; string source = @" public class D { void Main(C c, string? s) { if ((bool)c.MyIsNullOrEmpty(s)) { s.ToString(); // warn 1 } else { s.ToString(); // warn 2 } } } "; var compilation = CreateCompilationWithIL(new[] { source }, il, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 13) ); VerifyAnnotations(compilation, "C.MyIsNullOrEmpty", NotNullWhenFalse); } [Fact] public void NotNullWhenFalse_ReturningObject() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { MyIsNullOrEmpty(s); s.ToString(); // warn } object MyIsNullOrEmpty([NotNullWhen(false)] string? s) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); } [Fact] public void NotNullWhenFalse_FollowedByNotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (MyIsNullOrEmpty(s, s)) { s.ToString(); // ok } else { s.ToString(); // ok } s.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false)] string? s, [NotNull] string? s2) => throw null!; } ", NotNullWhenAttributeDefinition, NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNullWhenFalse, NotNull); } [Fact] public void NotNullWhenFalse_AndNotNull() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { if (MyIsNullOrEmpty(s)) { s.ToString(); // ok } else { s.ToString(); // ok } s.ToString(); // ok } public static bool MyIsNullOrEmpty([NotNullWhen(false), NotNull] string? s) => throw null!; } ", NotNullWhenAttributeDefinition, NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); VerifyAnnotationsAndMetadata(c, "C.MyIsNullOrEmpty", NotNull); } [Fact] public void NotNull_Simple() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { ThrowIfNull(42, s); s.ToString(); // ok } public static void ThrowIfNull(int x, [NotNull] string? s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); VerifyAnnotationsAndMetadata(c, "C.ThrowIfNull", None, NotNull); } [Fact] public void NotNull_Nested() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { ThrowIfNull(s?.ToString()); s.ToString(); // ok } public static void ThrowIfNull([NotNull] string? s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact, WorkItem(32335, "https://github.com/dotnet/roslyn/issues/32335")] public void NotNull_LearningFromNotNullTest() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void M(C? c1) { ThrowIfNull(c1?.Method()); c1.ToString(); // ok } C? Method() => throw null!; static void ThrowIfNull([NotNull] C? c) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact, WorkItem(38522, "https://github.com/dotnet/roslyn/issues/38522")] public void AsType_LearningFromNotNullTest() { var c = CreateNullableCompilation(@" public class C { public void M(object? o) { if (o as string != null) { o.ToString(); } } public void M2(object? o) { if (o is string) { o.ToString(); } } } "); c.VerifyDiagnostics(); } [Fact, WorkItem(38522, "https://github.com/dotnet/roslyn/issues/38522")] public void AsType_LearningFromNullResult() { var c = CreateNullableCompilation(@" public class C { public void M(object o) { if ((o as object) == null) { o.ToString(); // note: we're not inferring that o was null here, but we could consider it } } public void M2(object o) { if ((o as string) == null) { o.ToString(); } } } "); c.VerifyDiagnostics(); } [Fact] public void NotNull_ResettingStateMatters() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s, string? s2) { ThrowIfNull(s = s2, s2 = ""hello""); s.ToString(); // warn s2.ToString(); // ok } public static void ThrowIfNull(string? s1, [NotNull] string? s2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); } [Fact] public void NotNull_ResettingStateMatters_InIndexer() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s, string? s2) { _ = this[s = s2, s2 = ""hello""]; s.ToString(); // warn s2.ToString(); // ok } public int this[string? s1, [NotNull] string? s2] { get { throw null!; } } } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); } [Fact] public void NotNull_NoDuplicateDiagnosticsWhenResettingState() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public interface I<T> { } public class C { void Main(string? s, I<object> i) { ThrowIfNull(i, s); // single warning on conversion failure } public static void ThrowIfNull(I<object?> x, [NotNull] string? s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,21): warning CS8620: Nullability of reference types in argument of type 'I<object>' doesn't match target type 'I<object?>' for parameter 'x' in 'void C.ThrowIfNull(I<object?> x, string? s)'. // ThrowIfNull(i, s); // single warning on conversion failure Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "i").WithArguments("I<object>", "I<object?>", "x", "void C.ThrowIfNull(I<object?> x, string? s)").WithLocation(8, 21) ); } [Fact] public void NotNull_Generic_WithRefType() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { ThrowIfNull(s); s.ToString(); // ok } public static void ThrowIfNull<T>([NotNull] T s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNull_Generic_WithValueType() { CSharpCompilation c = CreateCompilation(@" using System.Diagnostics.CodeAnalysis; public class C { void Main(int s) { ThrowIfNull(s); s.ToString(); } public static void ThrowIfNull<T>([NotNull] T s) => throw null!; } " + NotNullAttributeDefinition); c.VerifyDiagnostics(); } [Fact] public void NotNull_Generic_WithUnconstrainedGenericType() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M<U>(U u) { ThrowIfNull(u); u.ToString(); } public static void ThrowIfNull<T>([NotNull] T s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNull_OnInterface() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s, Interface i) { i.ThrowIfNull(42, s); s.ToString(); // ok } } public interface Interface { void ThrowIfNull(int x, [NotNull] string? s); } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); VerifyAnnotationsAndMetadata(c, "Interface.ThrowIfNull", None, NotNull); } [Fact] public void NotNull_OnInterface_ImplementedWithoutAttribute() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C : Interface { void Main(string? s) { this.ThrowIfNull(42, s); s.ToString(); // warn ((Interface)this).ThrowIfNull(42, s); s.ToString(); // ok } public void ThrowIfNull(int x, string? s) => throw null!; // warn } public interface Interface { void ThrowIfNull(int x, [NotNull] string? s); } public class C2 : Interface { public void ThrowIfNull(int x, [NotNull] string? s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9), // (12,17): warning CS8767: Nullability of reference types in type of parameter 's' of 'void C.ThrowIfNull(int x, string? s)' doesn't match implicitly implemented member 'void Interface.ThrowIfNull(int x, string? s)' because of nullability attributes. // public void ThrowIfNull(int x, string? s) => throw null!; // warn Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "ThrowIfNull").WithArguments("s", "void C.ThrowIfNull(int x, string? s)", "void Interface.ThrowIfNull(int x, string? s)").WithLocation(12, 17) ); VerifyAnnotationsAndMetadata(c, "Interface.ThrowIfNull", None, NotNull); VerifyAnnotationsAndMetadata(c, "C.ThrowIfNull", None, None); } [Fact] public void NotNull_OnInterface_ImplementedWithAttribute() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C : Interface { void Main(string? s) { ((Interface)this).ThrowIfNull(42, s); s.ToString(); // warn this.ThrowIfNull(42, s); s.ToString(); // ok } public void ThrowIfNull(int x, [NotNull] string? s) => throw null!; } public interface Interface { void ThrowIfNull(int x, string? s); } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9) ); VerifyAnnotationsAndMetadata(c, "Interface.ThrowIfNull", None, None); VerifyAnnotationsAndMetadata(c, "C.ThrowIfNull", None, NotNull); } [Fact] public void NotNull_OnDelegate() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; delegate void D([NotNull] object? o); public class C { void Main(string? s, D d) { d(s); s.ToString(); // ok } } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNull_WithParams() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { static void NotNull([NotNull] params object?[]? args) { } // 0 static void F(object? x, object? y, object[]? a) { NotNull(); a.ToString(); // warn 1 NotNull(x, y); x.ToString(); // warn 2 y.ToString(); // warn 3 NotNull(a); a.ToString(); // ok } } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (5,61): warning CS8777: Parameter 'args' must have a non-null value when exiting. // static void NotNull([NotNull] params object?[]? args) { } // 0 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("args").WithLocation(5, 61), // (9,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(9, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // warn 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(13, 9) ); } [Fact] public void NotNullWhenTrue_WithParams() { CSharpCompilation c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { static bool NotNull([NotNullWhen(true)] params object?[]? args) => throw null!; static void F(object? x, object? y, object[]? a) { if (NotNull()) a.ToString(); // warn 1 if (NotNull(x, y)) { x.ToString(); // warn 2 y.ToString(); // warn 3 } if (NotNull(a)) a.ToString(); } } ", NotNullWhenAttributeDefinition }); c.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // warn 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(14, 13) ); } [Fact] public void NotNull_WithParamsOnFirstParameter() { CSharpCompilation c = CreateCompilationWithIL(new[] { @" public class D { static void F(object[]? a, object? b, object? c) { C.NotNull(a, b, c); a.ToString(); // ok b.ToString(); // warn 1 c.ToString(); // warn 2 } } " }, @" .class private auto ansi sealed beforefieldinit System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } .method public hidebysig specialname rtspecialname instance void .ctor ( bool[] '' ) cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } } .class public auto ansi beforefieldinit C extends [mscorlib]System.Object { .method public hidebysig static void NotNull ( object[] args, object[] args2 ) cil managed { .param [1] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 01 01 00 00 ) .custom instance void System.Diagnostics.CodeAnalysis.NotNullAttribute::.ctor() = ( 01 00 00 00 ) .param [2] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 01 01 00 00 ) .custom instance void System.Diagnostics.CodeAnalysis.NotNullAttribute::.ctor() = ( 01 00 00 00 ) IL_0000: nop IL_0001: ret } .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } } .class public auto ansi beforefieldinit System.Diagnostics.CodeAnalysis.NotNullAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.AttributeUsageAttribute::.ctor(valuetype [mscorlib]System.AttributeTargets) = ( 01 00 00 08 00 00 01 00 54 02 0d 41 6c 6c 6f 77 4d 75 6c 74 69 70 6c 65 00 ) .method public hidebysig specialname rtspecialname instance void .ctor () cil managed { IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(9, 9) ); } [Fact] public void NotNull_WithNamedArguments() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { static void NotNull1([NotNull] object? x = null, object? y = null) => throw null!; static void NotNull2(object? x = null, [NotNull] object? y = null) => throw null!; static void F(object? x) { NotNull1(); NotNull1(y: x); x.ToString(); // warn NotNull2(y: x); x.ToString(); // ok } } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 9) ); } [Fact] public void NotNull_OnDifferentTypes() { CSharpCompilation c = CreateCompilation(@" using System.Diagnostics.CodeAnalysis; public class C { public static void Bad<T>([NotNull] int i) => throw null!; public static void ThrowIfNull<T>([NotNull] T t) => throw null!; } " + NotNullAttributeDefinition); c.VerifyDiagnostics(); VerifyAnnotations(c, "C.Bad", NotNull); VerifyAnnotations(c, "C.ThrowIfNull", NotNull); } [Fact] public void NotNull_GenericMethod() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M<T>(T t) { t.ToString(); // warn ThrowIfNull(t); t.ToString(); // ok } public static void ThrowIfNull<T>([NotNull] T s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(7, 9) ); VerifyAnnotationsAndMetadata(c, "C.ThrowIfNull", NotNull); } [Fact] [WorkItem(30079, "https://github.com/dotnet/roslyn/issues/30079")] public void NotNull_BeginInvoke() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public delegate void Delegate([NotNull] string? s); public class C { void M(Delegate d, string? s) { if (s != string.Empty) s.ToString(); // warn d.BeginInvoke(s, null, null); s.ToString(); } } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,32): warning CS8602: Dereference of a possibly null reference. // if (s != string.Empty) s.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 32) ); } [Fact] public void NotNull_BackEffect() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1, string? s2) { ThrowIfNull(s2 = s1, s1); s2.ToString(); // warn } public static void ThrowIfNull(string? x1, [NotNull] string? x2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29865: Should we be able to trace that s2 was assigned a non-null value? c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(8, 9) ); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void NotNull_InErrorInvocation() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1, string? s2) { Missing(ThrowIfNull(s1, s2 = s1)); s2.ToString(); } public static void ThrowIfNull([NotNull] string? x1, string? x2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,9): error CS0103: The name 'Missing' does not exist in the current context // Missing(ThrowIfNull(s1, s2 = s1)); Diagnostic(ErrorCode.ERR_NameNotInContext, "Missing").WithArguments("Missing").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(8, 9) ); } [Fact] public void NotNull_NoForwardEffect() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1, string? s2) { ThrowIfNull(s1, s2 = s1); s1.ToString(); s2.ToString(); // 1 } public static void ThrowIfNull([NotNull] string? x1, string? x2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); // NotNull is a post-condition so it comes after all the arguments have been evaluated c.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(9, 9) ); } [Fact] public void NotNull_NoForwardEffect2() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1) { ThrowIfNull(s1, s1 = null); s1.ToString(); } public static void ThrowIfNull([NotNull] string? x1, string? x2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNull_NoForwardEffect3() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1, string? s2) { ThrowIfNull(s1 = null, s2 = s1, s1 = """", s1); s2.ToString(); // warn } public static void ThrowIfNull(string? x1, string? x2, string? x3, [NotNull] string? x4) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(8, 9) ); } [Fact] public void NotNullWhenTrue_NoForwardEffect() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1, string? s2) { if (ThrowIfNull(s1, s2 = s1)) { s1.ToString(); s2.ToString(); // 1 } else { s1.ToString(); // 2 s2.ToString(); // 3 } } public static bool ThrowIfNull([NotNullWhen(true)] string? x1, string? x2) => throw null!; } ", NotNullWhenAttributeDefinition }, options: WithNullableEnable()); // NotNullWhen is a post-condition so it comes after all the arguments have been evaluated c.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // s1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(14, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(15, 13) ); } [Fact] [WorkItem(29867, "https://github.com/dotnet/roslyn/issues/29867")] public void NotNull_TypeInference() { // Nullability flow analysis attributes do not affect type inference CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void M(string? s1) { ThrowIfNull(s1, out var s2); s2/*T:string?*/.ToString(); } public static void ThrowIfNull<T>([NotNull] T x1, out T x2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyTypes(); c.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s2/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(8, 9) ); } [Fact] public void NotNull_ConditionalMethodInReleaseMode() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { ThrowIfNull(42, s); s.ToString(); // ok } [System.Diagnostics.Conditional(""DEBUG"")] static void ThrowIfNull(int x, [NotNull] string? s) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNull_SecondArgumentDereferences() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { void Main(string? s) { ThrowIfNull(s, s.ToString()); // warn s.ToString(); // ok } public static void ThrowIfNull([NotNull] string? s, string s2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics( // (7,24): warning CS8602: Dereference of a possibly null reference. // ThrowIfNull(s, s.ToString()); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 24) ); VerifyAnnotationsAndMetadata(c, "C.ThrowIfNull", NotNull, None); } [Fact] public void NotNull_SecondArgumentAssigns() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { ThrowIfNull(s, s = null); s.ToString(); } static void ThrowIfNull([NotNull] string? s, string? s2) => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void NotNull_Indexer() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class C { void Main(string? s) { _ = this[42, s]; s.ToString(); // ok } public int this[int x, [NotNull] string? s] => throw null!; } ", NotNullAttributeDefinition }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectMethodBodies_ReferenceType() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { void M1([AllowNull]string x) { x.ToString(); // 1 } void M2([DisallowNull]string? x) { x.ToString(); x = null; } void M3([MaybeNull]out string x) { x = null; (x, _) = (null, 1); } void M4([NotNull]out string? x) { x = null; (x, _) = (null, 1); } // 2 [return: MaybeNull] string M5() { return null; } [return: NotNull] string? M6() { return null; // 3 } void M7([NotNull]string x) { x = null; // 4 (x, _) = (null, 1); // 5 } // 6 } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9), // (26,5): warning CS8777: Parameter 'x' must have a non-null value when exiting. // } // 2 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("x").WithLocation(26, 5), // (35,16): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(35, 16), // (40,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(40, 13), // (41,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // (x, _) = (null, 1); // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(41, 19), // (42,5): warning CS8777: Parameter 'x' must have a non-null value when exiting. // } // 6 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("x").WithLocation(42, 5) ); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectMethodBodies_NullableValueType() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { void M1([AllowNull]int? x) { x.Value.ToString(); // 1 } void M2([DisallowNull]int? x) { x.Value.ToString(); x = null; } void M3([MaybeNull]out int? x) { x = null; } void M4([NotNull]out int? x) { x = null; } // 2 [return: MaybeNull] int? M5() { return null; } [return: NotNull] int? M6() { return null; // 3 } void M7([NotNull]out int? x) { x = null; return; // 4 } } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8629: Nullable value type may be null. // x.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x", isSuppressed: false).WithLocation(7, 9), // (24,5): warning CS8777: Parameter 'x' must have a non-null value when exiting. // } // 2 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}", isSuppressed: false).WithArguments("x").WithLocation(24, 5), // (33,9): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // return null; // 3 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "return null;", isSuppressed: false).WithLocation(33, 9), // (39,9): warning CS8777: Parameter 'x' must have a non-null value when exiting. // return; // 4 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return;", isSuppressed: false).WithArguments("x").WithLocation(39, 9) ); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectMethodBodies_UnconstrainedGeneric() { var source = @" using System.Diagnostics.CodeAnalysis; public class C<T> { void M1([AllowNull]T x) { x.ToString(); // 1 } void M2([DisallowNull]T x) { x.ToString(); } void M3([MaybeNull]out T x) { x = default; } void M4([NotNull]out T x) { x = default; // 2 } // 3 [return: MaybeNull] T M5() { return default; } [return: NotNull] T M6() { return default; // 4 } } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9), // (22,13): warning CS8601: Possible null reference assignment. // x = default; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(22, 13), // (23,5): warning CS8777: Parameter 'x' must have a non-null value when exiting. // } // 3 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("x").WithLocation(23, 5), // (32,16): warning CS8603: Possible null reference return. // return default; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(32, 16) ); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectPropertyBodies_ReferenceType() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull] string? P1 { get { return null; } set { value.ToString(); } } [AllowNull] string P2 { get { return null; } // 1 set { value.ToString(); } // 2 } [MaybeNull] string P3 { get { return null; } set { value.ToString(); } } [NotNull] string? P4 { get { return null; } // 3 set { value.ToString(); } // 4 } } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,22): warning CS8603: Possible null reference return. // get { return null; } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(13, 22), // (14,15): warning CS8602: Dereference of a possibly null reference. // set { value.ToString(); } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(14, 15), // (25,22): warning CS8603: Possible null reference return. // get { return null; } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(25, 22), // (26,15): warning CS8602: Dereference of a possibly null reference. // set { value.ToString(); } // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(26, 15) ); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectPropertyBodies_ReferenceType_AutoProp() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull] string? P1 { get; set; } = """"; [AllowNull] string P2 { get; set; } = """"; [MaybeNull] string P3 { get; set; } = """"; [NotNull] string? P4 { get; set; } = """"; [DisallowNull] string? P5 { get; set; } = null; // 1 [AllowNull] string P6 { get; set; } = null; [MaybeNull] string P7 { get; set; } = null; // 2 [NotNull] string? P8 { get; set; } = null; } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,47): warning CS8625: Cannot convert null literal to non-nullable reference type. // [DisallowNull] string? P5 { get; set; } = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 47), // (12,43): warning CS8625: Cannot convert null literal to non-nullable reference type. // [MaybeNull] string P7 { get; set; } = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 43) ); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectPropertyBodies_NullableValueType() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull] int? P1 { get { return null; } set { value.Value.ToString(); } } [AllowNull] int? P2 { get { return null; } set { value.Value.ToString(); } // 1 } [MaybeNull] int? P3 { get { return null; } set { value.Value.ToString(); } // 2 } [NotNull] int? P4 { get { return null; } // 3 set { value.Value.ToString(); } // 4 } } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,15): warning CS8629: Nullable value type may be null. // set { value.Value.ToString(); } // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "value").WithLocation(14, 15), // (20,15): warning CS8629: Nullable value type may be null. // set { value.Value.ToString(); } // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "value").WithLocation(20, 15), // (25,15): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // get { return null; } // 3 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "return null;").WithLocation(25, 15), // (26,15): warning CS8629: Nullable value type may be null. // set { value.Value.ToString(); } // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "value").WithLocation(26, 15) ); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void UnconditionalAttributesAffectPropertyBodies_UnconstrainedGeneric() { var source = @" using System.Diagnostics.CodeAnalysis; public class C<T> { [DisallowNull] T P1 { get { return default; } // 1 set { value.ToString(); } } [AllowNull] T P2 { get { return default; } // 2 set { value.ToString(); } // 3 } [MaybeNull] T P3 { get { return default; } set { value.ToString(); } // 4 } [NotNull] T P4 { get { return default; } // 5 set { value.ToString(); } // 6 } } "; var comp = CreateCompilation( new[] { source, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,22): warning CS8603: Possible null reference return. // get { return default; } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(7, 22), // (13,22): warning CS8603: Possible null reference return. // get { return default; } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(13, 22), // (14,15): warning CS8602: Dereference of a possibly null reference. // set { value.ToString(); } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(14, 15), // (20,15): warning CS8602: Dereference of a possibly null reference. // set { value.ToString(); } // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(20, 15), // (25,22): warning CS8603: Possible null reference return. // get { return default; } // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(25, 22), // (26,15): warning CS8602: Dereference of a possibly null reference. // set { value.ToString(); } // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(26, 15) ); } [Fact] public void AllowNull_01() { // Warn on redundant nullability attributes (all except F1)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>([AllowNull]T t) { } static void F2<T>([AllowNull]T t) where T : class { } static void F3<T>([AllowNull]T t) where T : struct { } static void F4<T>([AllowNull]T? t) where T : class { } static void F5<T>([AllowNull]T? t) where T : struct { } static void M1<T>(T t1) { F1(t1); } static void M2<T>(T t2) where T : class { F1(t2); F2(t2); F4(t2); t2 = null; // 1 F1(t2); F2(t2); // 2 F4(t2); } static void M3<T>(T? t3) where T : class { F1(t3); F2(t3); // 3 F4(t3); if (t3 == null) return; F1(t3); F2(t3); F4(t3); } static void M4<T>(T t4) where T : struct { F1(t4); F3(t4); } static void M5<T>(T? t5) where T : struct { F1(t5); F5(t5); if (t5 == null) return; F1(t5); F5(t5); } }"; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }, options: WithNullableEnable()); // The constraint warnings on F2(t2) and F2(t3) are not ideal but expected. comp.VerifyDiagnostics( // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 14), // (20,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(20, 9), // (26,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t3); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(26, 9)); } [Fact] public void AllowNull_WithMaybeNull() { // Warn on misused nullability attributes (AllowNull on type that could be marked with `?`, MaybeNull on an `in` or by-val parameter)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F0<T>([AllowNull, MaybeNull]T t) { } static void F1<T>([AllowNull, MaybeNull]ref T t) { } static void F2<T>([AllowNull, MaybeNull]T t) where T : class { } static void F3<T>([AllowNull, MaybeNull]T t) where T : struct { } static void F4<T>([AllowNull, MaybeNull]T? t) where T : class { } static void F5<T>([AllowNull, MaybeNull]T? t) where T : struct { } static void F6<T>([AllowNull, MaybeNull]in T t) { } static void M<T>(string? s1, string s2) { F0<string>(s1); s1.ToString(); // 1 F0<string>(s2); s2.ToString(); // 2 } static void M_WithRef<T>(string? s1, string s2) { F1<string>(ref s1); s1.ToString(); // 3 F1<string>(ref s2); // 4 s2.ToString(); // 5 } }"; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(15, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(18, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // s1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(23, 9), // (25,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // F1<string>(ref s2); // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s2").WithLocation(25, 24), // (26,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(26, 9) ); } [Fact] public void AllowNull_02() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>([AllowNull]T t) { } static void F2<T>([AllowNull]T t) where T : class { } static void F3<T>([AllowNull]T t) where T : struct { } static void F4<T>([AllowNull]T? t) where T : class { } static void F5<T>([AllowNull]T? t) where T : struct { } static void M1<T>(T t1) { F1<T>(t1); } static void M2<T>(T t2) where T : class { F1<T>(t2); F2<T>(t2); F4<T>(t2); t2 = null; // 1 F1<T>(t2); F2<T>(t2); F4<T>(t2); } static void M3<T>(T? t3) where T : class { F1<T>(t3); F2<T>(t3); F4<T>(t3); if (t3 == null) return; F1<T>(t3); F2<T>(t3); F4<T>(t3); } static void M4<T>(T t4) where T : struct { F1<T>(t4); F3<T>(t4); } static void M5<T>(T? t5) where T : struct { F1<T?>(t5); F5<T>(t5); if (t5 == null) return; F1<T?>(t5); F5<T>(t5); } }"; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 14)); } [Fact] public void AllowNull_03() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([AllowNull]string s) { } static void F2([AllowNull]string? s) { } static void M1(string s1) { F1(s1); F2(s1); s1 = null; // 1 F1(s1); F2(s1); } static void M2(string? s2) { F1(s2); F2(s2); if (s2 == null) return; F1(s2); F2(s2); } }"; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // s1 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(10, 14)); } [Fact] public void AllowNull_RefParameter_03() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([AllowNull]ref string s) { } static void F2([AllowNull]ref string? s) { } static void M1() { string s1 = """"; F1(ref s1); s1.ToString(); string? s2 = """"; F2(ref s2); s2.ToString(); // 1 string s3 = null; // 2 F1(ref s3); s3.ToString(); string? s4 = null; F2(ref s4); s4.ToString(); // 3 } }"; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(14, 9), // (16,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string s3 = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 21), // (22,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(22, 9) ); } [Fact] public void AllowNull_04() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([AllowNull]int i) { } static void F2([AllowNull]int? i) { } static void M1(int i1) { F1(i1); F2(i1); } static void M2(int? i2) { F2(i2); if (i2 == null) return; F2(i2); } }"; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void AllowNull_05() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static void F1<T>(T t) where T : class { } public static void F2<T>([AllowNull]T t) where T : class { } }"; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x); // 2 F1(y); F2(x); // 3 F2(x!); F2(y); } }"; comp = CreateCompilation(source, references: new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(x); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T)", "T", "object?").WithLocation(7, 9), // (9,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T)", "T", "object?").WithLocation(9, 9)); } [Fact] public void AllowNull_01_Property() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [AllowNull]public TOpen P1 { get; set; } = default!; } public class CClass<TClass> where TClass : class { [AllowNull]public TClass P2 { get; set; } = null!; [AllowNull]public TClass? P3 { get; set; } = null; } public class CStruct<TStruct> where TStruct : struct { [AllowNull]public TStruct P4 { get; set; } [AllowNull]public TStruct? P5 { get; set; } }"; var lib = CreateNullableCompilation(new[] { lib_cs, AllowNullAttributeDefinition }); var source = @" class Program { static void M1<T>(T t1) { new COpen<T>().P1 = t1; } static void M2<T>(T t2) where T : class { new COpen<T>().P1 = t2; new CClass<T>().P2 = t2; new CClass<T>().P3 = t2; t2 = null; // 1 new COpen<T>().P1 = t2; new CClass<T>().P2 = t2; new CClass<T>().P3 = t2; var xOpen = new COpen<T>(); xOpen.P1 = null; xOpen.P1.ToString(); var xClass = new CClass<T>(); xClass.P2 = null; xClass.P2.ToString(); xClass.P3 = null; xClass.P3.ToString(); // 2 } static void M3<T>(T? t3) where T : class { new COpen<T>().P1 = t3; new CClass<T>().P2 = t3; new CClass<T>().P3 = t3; if (t3 == null) return; new COpen<T>().P1 = t3; new CClass<T>().P2 = t3; new CClass<T>().P3 = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>().P1 = t4; new CStruct<T>().P4 = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>().P1 = t5; new CStruct<T>().P5 = t5; if (t5 == null) return; new COpen<T?>().P1 = t5; new CStruct<T>().P5 = t5; } }"; var expected = new[] { // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 14), // (26,9): warning CS8602: Dereference of a possibly null reference. // xClass.P3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xClass.P3").WithLocation(26, 9) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, AllowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void AllowNull_Property_WithNotNull() { var source = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [AllowNull, NotNull]public TOpen P1 { get; set; } = default!; } public class CClass<TClass> where TClass : class { [AllowNull, NotNull]public TClass P2 { get; set; } = null!; [AllowNull, NotNull]public TClass? P3 { get; set; } = null; } public class CStruct<TStruct> where TStruct : struct { [AllowNull, NotNull]public TStruct? P5 { get; set; } } class Program { static void M1<T>([MaybeNull]T t1) { var xOpen = new COpen<T>(); xOpen.P1 = t1; xOpen.P1.ToString(); } static void M2<T>(T t2) where T : class { var xOpen = new COpen<T>(); xOpen.P1 = null; xOpen.P1.ToString(); var xClass = new CClass<T>(); xClass.P2 = null; xClass.P2.ToString(); xClass.P3 = null; xClass.P3.ToString(); } static void M5<T>(T? t5) where T : struct { var xOpen = new COpen<T?>(); xOpen.P1 = null; xOpen.P1.ToString(); var xStruct = new CStruct<T>(); xStruct.P5 = null; xStruct.P5.Value.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void AllowNull_Property_WithNotNull_NoSuppression() { var source = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [AllowNull, NotNull]public TOpen P1 { get; set; } = default; } public class CNotNull<TNotNull> where TNotNull : notnull { [AllowNull, NotNull]public TNotNull P1 { get; set; } = default; } public class CClass<TClass> where TClass : class { [AllowNull, NotNull]public TClass P2 { get; set; } = null; }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition, NotNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void AllowNull_Property_InCompoundAssignment() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [AllowNull] public C P { get; set; } public static C? operator +(C? x, C? y) => throw null!; }"; var lib = CreateNullableCompilation(new[] { lib_cs, AllowNullAttributeDefinition }); lib.VerifyDiagnostics( ); var source = @" class Program { static void M(C c) { c.P += null; c.P.ToString(); } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39966, "https://github.com/dotnet/roslyn/issues/39966")] public void AllowNull_Property_InObjectInitializer() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [AllowNull] public C P { get; set; } } class Program { static void M(C c1) { c1.P = null; new C { P = null }; } }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39966, "https://github.com/dotnet/roslyn/issues/39966")] public void AllowNull_Field_InObjectInitializer() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [AllowNull] public C F; } class Program { static void M(C c1) { c1.F = null; new C { F = null }; } }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39966, "https://github.com/dotnet/roslyn/issues/39966")] public void DisallowNull_Property_InObjectInitializer() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull] public C? P { get; set; } } class Program { static void M(C c1) { c1.P = null; // 1 new C { P = null // 2 }; } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (12,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // c1.P = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 16), // (16,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // P = null // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 17)); } [Fact, WorkItem(39966, "https://github.com/dotnet/roslyn/issues/39966")] public void DisallowNull_Field_InObjectInitializer() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull] public C? F; } class Program { static void M(C c1) { c1.F = null; // 1 new C { F = null // 2 }; } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (12,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // c1.F = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 16), // (16,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 17)); } [Fact] public void AllowNull_Property_InDeconstructionAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [AllowNull] public C P { get; set; } = null; } class Program { void M(C c) { (c.P, _) = (null, 1); c.P.ToString(); ((c.P, _), _) = ((null, 1), 2); c.P.ToString(); (c.P, _) = this; c.P.ToString(); ((_, c.P), _) = (this, 1); c.P.ToString(); } void Deconstruct(out C? x, out C? y) => throw null!; }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void AllowNull_Field() { // Warn on misused nullability attributes (f3, f4, f5)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [AllowNull]public TOpen f1 = default!; } public class CClass<TClass> where TClass : class { [AllowNull]public TClass f2 = null; [AllowNull]public TClass? f3 = null; } public class CStruct<TStruct> where TStruct : struct { [AllowNull]public TStruct f4; [AllowNull]public TStruct? f5; } "; var lib = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, lib_cs }); var source = @" using System.Diagnostics.CodeAnalysis; class C { static void M1<T>([MaybeNull] T t1) { new COpen<T>().f1 = t1; } static void M2<T>(T t2) where T : class { new COpen<T>().f1 = t2; new CClass<T>().f2 = t2; new CClass<T>().f3 = t2; t2 = null; // 1 new COpen<T>().f1 = t2; new CClass<T>().f2 = t2; new CClass<T>().f3 = t2; var xOpen = new COpen<T>(); xOpen.f1 = null; xOpen.f1.ToString(); // 2 var xClass = new CClass<T>(); xClass.f2 = null; xClass.f2.ToString(); // 3 xClass.f3 = null; xClass.f3.ToString(); // 4 } static void M3<T>(T? t3) where T : class { new COpen<T>().f1 = t3; new CClass<T>().f2 = t3; new CClass<T>().f3 = t3; if (t3 == null) return; new COpen<T>().f1 = t3; new CClass<T>().f2 = t3; new CClass<T>().f3 = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>().f1 = t4; new CStruct<T>().f4 = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>().f1 = t5; new CStruct<T>().f5 = t5; if (t5 == null) return; new COpen<T?>().f1 = t5; new CStruct<T>().f5 = t5; } }"; var expected = new[] { // (14,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 14), // (21,9): warning CS8602: Dereference of a possibly null reference. // xOpen.f1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xOpen.f1").WithLocation(21, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // xClass.f2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xClass.f2").WithLocation(25, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // xClass.f3.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xClass.f3").WithLocation(27, 9) }; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var field = copen.GetMembers().OfType<FieldSymbol>().Single(); var fieldAttributes = field.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.AllowNullAttribute" }, fieldAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableAttribute(1)", "System.Diagnostics.CodeAnalysis.AllowNullAttribute" }, fieldAttributes); } } } [Fact] public void AllowNull_Field_NullInitializer() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [AllowNull]public string field = null; string M() => field.ToString(); } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void AllowNull_Operator_CompoundAssignment() { var source = @" using System.Diagnostics.CodeAnalysis; class CLeft { CLeft? Property { get; set; } public static CLeft? operator+([AllowNull] CLeft one, CLeft other) => throw null!; void M(CLeft c, CLeft? c2) { Property += c; Property += c2; // 1 } } class CRight { CRight Property { get { throw null!; } set { throw null!; } } // note not annotated public static CRight operator+(CRight one, [AllowNull] CRight other) => throw null!; void M(CRight c, CRight? c2) { Property += c; Property += c2; } } class CNone { CNone? Property { get; set; } public static CNone? operator+(CNone one, CNone other) => throw null!; void M(CNone c, CNone? c2) { Property += c; // 2 Property += c2; // 3, 4 } }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,21): warning CS8604: Possible null reference argument for parameter 'other' in 'CLeft? CLeft.operator +(CLeft one, CLeft other)'. // Property += c2; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c2").WithArguments("other", "CLeft? CLeft.operator +(CLeft one, CLeft other)").WithLocation(11, 21), // (32,9): warning CS8604: Possible null reference argument for parameter 'one' in 'CNone? CNone.operator +(CNone one, CNone other)'. // Property += c; // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "Property").WithArguments("one", "CNone? CNone.operator +(CNone one, CNone other)").WithLocation(32, 9), // (33,9): warning CS8604: Possible null reference argument for parameter 'one' in 'CNone? CNone.operator +(CNone one, CNone other)'. // Property += c2; // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "Property").WithArguments("one", "CNone? CNone.operator +(CNone one, CNone other)").WithLocation(33, 9), // (33,21): warning CS8604: Possible null reference argument for parameter 'other' in 'CNone? CNone.operator +(CNone one, CNone other)'. // Property += c2; // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c2").WithArguments("other", "CNone? CNone.operator +(CNone one, CNone other)").WithLocation(33, 21) ); } [Fact] public void AllowNull_01_Indexer() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [AllowNull]public TOpen this[int i] { set => throw null!; } } public class CClass<TClass> where TClass : class { [AllowNull]public TClass this[int i] { set => throw null!; } } public class CClass2<TClass> where TClass : class { [AllowNull]public TClass? this[int i] { set => throw null!; } } public class CStruct<TStruct> where TStruct : struct { [AllowNull]public TStruct this[int i] { set => throw null!; } } public class CStruct2<TStruct> where TStruct : struct { [AllowNull]public TStruct? this[int i] { set => throw null!; } }"; var lib = CreateNullableCompilation(new[] { lib_cs, AllowNullAttributeDefinition }); var source = @" class Program { static void M1<T>(T t1) { new COpen<T>()[0] = t1; } static void M2<T>(T t2) where T : class { new COpen<T>()[0] = t2; new CClass<T>()[0] = t2; new CClass2<T>()[0] = t2; t2 = null; // 1 new COpen<T>()[0] = t2; new CClass<T>()[0] = t2; new CClass2<T>()[0] = t2; } static void M3<T>(T? t3) where T : class { new COpen<T>()[0] = t3; new CClass<T>()[0] = t3; new CClass2<T>()[0] = t3; if (t3 == null) return; new COpen<T>()[0] = t3; new CClass<T>()[0] = t3; new CClass2<T>()[0] = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>()[0] = t4; new CStruct<T>()[0] = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>()[0] = t5; new CStruct2<T>()[0] = t5; if (t5 == null) return; new COpen<T?>()[0] = t5; new CStruct2<T>()[0] = t5; } }"; var expected = new[] { // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 14) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, AllowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var copenAttributes = copen.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(copenAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableContextAttribute(1)", "System.Runtime.CompilerServices.NullableAttribute(0)", "System.Reflection.DefaultMemberAttribute(\"Item\")" }, copenAttributes); } var property = copen.GetMembers().OfType<PropertySymbol>().Single(); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.AllowNullAttribute" }, propertyAttributes); } else { AssertEx.Empty(propertyAttributes); } var setter = property.SetMethod; var setterAttributes = setter.GetAttributes(); AssertEx.Empty(setterAttributes); var setterValueAttributes = setter.Parameters.Last().GetAttributes().Select(a => a.ToString()); Assert.Equal(FlowAnalysisAnnotations.AllowNull, setter.Parameters.Last().FlowAnalysisAnnotations); if (isSource) { AssertEx.Empty(setterValueAttributes); } else { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.AllowNullAttribute" }, setterValueAttributes); } Assert.Equal(FlowAnalysisAnnotations.None, setter.ReturnTypeFlowAnalysisAnnotations); var setterReturnAttributes = setter.GetReturnTypeAttributes(); AssertEx.Empty(setterReturnAttributes); } } [Fact] public void AllowNull_01_Indexer_WithDisallowNull() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [AllowNull, DisallowNull]public TOpen this[int i] { set => throw null!; } }"; var comp = CreateNullableCompilation(new[] { lib_cs, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics(); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var copenAttributes = copen.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(copenAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableContextAttribute(1)", "System.Runtime.CompilerServices.NullableAttribute(0)", "System.Reflection.DefaultMemberAttribute(\"Item\")" }, copenAttributes); } var property = copen.GetMembers().OfType<PropertySymbol>().Single(); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.AllowNullAttribute", "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" }, propertyAttributes); } else { AssertEx.Empty(propertyAttributes); } var setter = property.SetMethod; var setterAttributes = setter.GetAttributes(); AssertEx.Empty(setterAttributes); var setterValueAttributes = setter.Parameters.Last().GetAttributes().Select(a => a.ToString()); Assert.Equal(FlowAnalysisAnnotations.AllowNull | FlowAnalysisAnnotations.DisallowNull, setter.Parameters.Last().FlowAnalysisAnnotations); if (isSource) { AssertEx.Empty(setterValueAttributes); } else { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.DisallowNullAttribute", "System.Diagnostics.CodeAnalysis.AllowNullAttribute" }, setterValueAttributes); } } } [Fact] public void AllowNull_Indexer_OtherParameters() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public string this[[AllowNull] string s] { set => throw null!; } } "; var lib = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new C()[s] = s2; new C()[s2] = s2; } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, AllowNullAttributeDefinition }); comp2.VerifyDiagnostics(); } [Fact] public void AllowNull_Indexer_OtherParameters_OverridingSetter() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual string this[[AllowNull] string s] { set => throw null!; } } public class C : Base { public override string this[string s] { set => throw null!; } } "; var lib = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new C()[s] = s2; // 1 new C()[s2] = s2; } }"; var expected = new[] { // (6,17): warning CS8604: Possible null reference argument for parameter 's' in 'string C.this[string s]'. // new C()[s] = s2; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s").WithArguments("s", "string C.this[string s]").WithLocation(6, 17) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, AllowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void AllowNull_DoesNotAffectTypeInference() { var source = @"using System.Diagnostics.CodeAnalysis; public class A { public static void F1<T>(T t, T t2) where T : class { } public static void F2<T>([AllowNull]T t, T t2) where T : class { } static void Main() { object x = null; // 1 object? y = new object(); F1(x, x); // 2 F1(x, y); // 3 F1(y, y); F1(y, x); // 4 F2(x, x); // 5 F2(x, y); // 6 F2(y, y); F2(y, x); // 7 F2(x, x!); // 8 F2(x!, x); // 9 F2(x!, y); F2(y, x!); } }"; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (8,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 20), // (10,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(x, x); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T, T)", "T", "object?").WithLocation(10, 9), // (11,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(x, y); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T, T)", "T", "object?").WithLocation(11, 9), // (13,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(y, x); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T, T)", "T", "object?").WithLocation(13, 9), // (15,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x, x); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T, T)", "T", "object?").WithLocation(15, 9), // (16,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x, y); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T, T)", "T", "object?").WithLocation(16, 9), // (18,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(y, x); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T, T)", "T", "object?").WithLocation(18, 9), // (20,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x, x!); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T, T)", "T", "object?").WithLocation(20, 9), // (21,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x!, x); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T, T)", "T", "object?").WithLocation(21, 9) ); } [Fact] public void AllowNull_Parameter_Generic() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) => throw null!; public virtual void F2<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : class => throw null!; public virtual void F3<T>([AllowNull]T? t1, [AllowNull] out T? t2, [AllowNull] ref T? t3, [AllowNull] in T? t4) where T : class => throw null!; public virtual void F4<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : struct => throw null!; public virtual void F5<T>([AllowNull]T? t1, [AllowNull] out T? t2, [AllowNull] ref T? t3, [AllowNull] in T? t4) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(12, 26), // (12,26): error CS8762: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (12,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(12, 26), // (13,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(13, 26), // (13,26): error CS8762: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t3").WithLocation(13, 26), // (13,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(13, 26) ); } [Fact] public void AllowNull_Parameter_Generic_ObliviousBase() { var source = @"using System.Diagnostics.CodeAnalysis; #nullable disable public class Base { public virtual void F1<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) => throw null!; public virtual void F2<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : class => throw null!; public virtual void F4<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : struct => throw null!; } #nullable enable public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; } "; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(12, 26), // (12,26): warning CS8765: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (12,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(12, 26), // (13,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(13, 26), // (13,26): warning CS8765: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t3").WithLocation(13, 26), // (13,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(13, 26) ); } [Fact] public void AllowNull_Parameter_Generic_ObliviousDerived() { var source = @"using System.Diagnostics.CodeAnalysis; #nullable enable public class Base { public virtual void F1<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) => throw null!; public virtual void F2<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : class => throw null!; public virtual void F4<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : struct => throw null!; public virtual void F5<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : notnull => throw null!; } #nullable disable public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public override void F5<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; } "; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void AllowNull_Parameter_Generic_OnOverrides() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public virtual void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public virtual void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public virtual void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public virtual void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; public virtual void F6<T>(T t1, out T t2, ref T t3, in T t4) where T : notnull=> throw null!; } public class Derived : Base { public override void F1<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) => throw null!; public override void F2<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : class => throw null!; public override void F3<T>([AllowNull]T? t1, [AllowNull] out T? t2, [AllowNull] ref T? t3, [AllowNull] in T? t4) where T : class => throw null!; public override void F4<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) where T : struct => throw null!; public override void F5<T>([AllowNull]T? t1, [AllowNull] out T? t2, [AllowNull] ref T? t3, [AllowNull] in T? t4) where T : struct => throw null!; public override void F6<T>([AllowNull]T t1, [AllowNull] out T t2, [AllowNull] ref T t3, [AllowNull] in T t4) => throw null!; } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void UnannotatedParam_UpdatesArgumentState() { var source = @" public class Program { void M0(string s0) { } void M1(string? s1) { M0(s1); // 1 _ = s1.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,12): warning CS8604: Possible null reference argument for parameter 's0' in 'void Program.M0(string s0)'. // M0(s1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s1").WithArguments("s0", "void Program.M0(string s0)").WithLocation(8, 12) ); } [Fact] public void UnannotatedTypeArgument_UpdatesArgumentState() { var source = @" public class Program { void M0<T>(T t) { } void M1<T>(T? t) where T : class { M0<T>(t); // 1 _ = t.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.M0<T>(T t)'. // M0<T>(t); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("t", "void Program.M0<T>(T t)").WithLocation(8, 15) ); } [Fact] public void UnannotatedTypeArgument_NullableClassConstrained_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0<T>(T t) { } void M1<T>(T t) where T : class? { M0(t); _ = t.ToString(); // 1 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(9, 13) ); } [Fact] public void UnannotatedParam_SuppressedArgument_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0(string s0) { } void M1(string? s1) { M0(s1!); _ = s1.ToString(); // 1 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 13) ); } [Fact] public void AnnotatedParam_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0(string? s0) { } void M1(string? s1) { M0(s1); _ = s1.ToString(); // 1 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 13) ); } [Fact] public void Params_AnnotatedElement_UnannotatedArray_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0(params string?[] s0) { } void M1(string? s1) { M0(s1); _ = s1.ToString(); // 1 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 13) ); } [Fact] public void Params_UnannotatedElement_AnnotatedArray_UpdatesArgumentState() { var source = @" public class Program { void M0(params string[]? s0) { } void M1(string? s1) { M0(s1); // 1 _ = s1.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,12): warning CS8604: Possible null reference argument for parameter 's0' in 'void Program.M0(params string[]? s0)'. // M0(s1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s1").WithArguments("s0", "void Program.M0(params string[]? s0)").WithLocation(8, 12) ); } [Fact] public void ObliviousParam_DoesNotUpdateArgumentState() { var source = @" public class Program { #nullable disable void M0(string s0) { } #nullable enable void M1(string? s1) { M0(s1); _ = s1.ToString(); // 1 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(10, 13) ); } [Fact] public void UnannotatedParam_MaybeNull_UpdatesArgumentState() { var source = @" using System.Diagnostics.CodeAnalysis; public class Program { void M0([MaybeNull] string s0) { } void M1(string s1) { M0(s1); _ = s1.ToString(); // 1 } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(11, 13) ); } [Fact] public void UnannotatedParam_MaybeNullWhen_UpdatesArgumentState() { var source = @" using System.Diagnostics.CodeAnalysis; public class Program { bool M0([MaybeNullWhen(true)] string s0) => false; void M1(string s1) { M0(s1); _ = s1.ToString(); // 1 } void M2(string s1) { _ = M0(s1) ? s1.ToString() // 2 : s1.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(11, 13), // (17,15): warning CS8602: Dereference of a possibly null reference. // ? s1.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(17, 15) ); } [Fact] public void AnnotatedParam_DisallowNull_UpdatesArgumentState() { var source = @" using System.Diagnostics.CodeAnalysis; public class Program { void M0([DisallowNull] int? i) { } void M1(int? i1) { M0(i1); // 1 _ = i1.Value.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,12): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // M0(i1); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "i1").WithLocation(10, 12) ); } [Fact] public void AnnotatedTypeParam_DisallowNull_UpdatesArgumentState() { var source = @" using System.Diagnostics.CodeAnalysis; public class Program<T> { void M0([DisallowNull] T? t) { } void M1(T t) { M0(t); // 1 _ = t.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,12): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // M0(t); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(10, 12) ); } [Fact] public void UnconstrainedTypeParam_ArgumentStateUpdatedToNotNull_01() { var source = @" public class Program<T> { void M0(T t) { } void M1() { T t = default; M0(t); // 1 M0(t); _ = t.ToString(); } } "; var comp = CreateNullableCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,12): warning CS8604: Possible null reference argument for parameter 't' in 'void Program<T>.M0(T t)'. // M0(t); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("t", "void Program<T>.M0(T t)").WithLocation(9, 12)); } [Fact] public void UnconstrainedTypeParam_ArgumentStateUpdatedToNotNull_02() { var source = @" public interface IHolder<T> { T Value { get; } } public class Program<T> where T : class?, IHolder<T?>? { void M0(T t) { } void M1() { T? t = default; M0(t?.Value); // 1 M0(t); _ = t.ToString(); M0(t.Value); _ = t.Value.ToString(); } void M2() { T? t = default; M0(t); // 2 M0(t); _ = t.ToString(); M0(t.Value); // 3 M0(t.Value); _ = t.Value.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (14,12): warning CS8604: Possible null reference argument for parameter 't' in 'void Program<T>.M0(T t)'. // M0(t?.Value); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t?.Value").WithArguments("t", "void Program<T>.M0(T t)").WithLocation(14, 12), // (24,12): warning CS8604: Possible null reference argument for parameter 't' in 'void Program<T>.M0(T t)'. // M0(t); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("t", "void Program<T>.M0(T t)").WithLocation(24, 12), // (27,12): warning CS8604: Possible null reference argument for parameter 't' in 'void Program<T>.M0(T t)'. // M0(t.Value); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t.Value").WithArguments("t", "void Program<T>.M0(T t)").WithLocation(27, 12) ); } [Fact, WorkItem(50602, "https://github.com/dotnet/roslyn/issues/50602")] public void UnconstrainedTypeParam_ArgumentStateUpdatedToNotNull_DisallowNull() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C1<T> { void M1(T t) { Test(t); // 1 Test(t); } void M2([AllowNull] T t) { Test(t); // 2 Test(t); } public void Test([DisallowNull] T s) { } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,14): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // Test(t); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(9, 14), // (15,14): warning CS8604: Possible null reference argument for parameter 's' in 'void C1<T>.Test(T s)'. // Test(t); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("s", "void C1<T>.Test(T s)").WithLocation(15, 14) ); } [Fact] [WorkItem(48605, "https://github.com/dotnet/roslyn/issues/48605")] [WorkItem(48134, "https://github.com/dotnet/roslyn/issues/48134")] [WorkItem(49136, "https://github.com/dotnet/roslyn/issues/49136")] public void AllowNullInputParam_DoesNotUpdateArgumentState() { var source = @" using System.Diagnostics.CodeAnalysis; public static class Program { public static void M1(string? s) { MExt(s); s.ToString(); // 1 } public static void M2(string? s) { s.MExt(); s.ToString(); // 2 } public static void M3(string? s) { C c = s; s.ToString(); // 3 } public static void MExt([AllowNull] this string s) { } public class C { public static implicit operator C([AllowNull] string s) => new C(); } } "; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(21, 9)); } [Fact] [WorkItem(48605, "https://github.com/dotnet/roslyn/issues/48605")] [WorkItem(48134, "https://github.com/dotnet/roslyn/issues/48134")] [WorkItem(49136, "https://github.com/dotnet/roslyn/issues/49136")] public void AllowNullNotNullInputParam_UpdatesArgumentState() { var source = @" using System.Diagnostics.CodeAnalysis; public static class Program { public static void M1(string? s) { MExt(s); s.ToString(); } public static void M2(string? s) { s.MExt(); s.ToString(); } public static void M3(string? s) { C c = s; s.ToString(); // 1 } public static void MExt([AllowNull, NotNull] this string s) { throw null!; } public class C { public static implicit operator C([AllowNull, NotNull] string s) { throw null!; } } } "; // we should respect postconditions on a conversion parameter // https://github.com/dotnet/roslyn/issues/49575 var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (21,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(21, 9)); } [Fact] [WorkItem(49136, "https://github.com/dotnet/roslyn/issues/49136")] public void DisallowNullInputParam_UpdatesArgumentState() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { void M1(int? x) { C c = x; // 1 Method(x); } void M2(int? x) { Method(x); // 2 C c = x; } void Method([DisallowNull] int? t) { } public static implicit operator C([DisallowNull] int? s) => new C(); } "; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,15): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // C c = x; // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "x").WithLocation(9, 15), // (15,16): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // Method(x); // 2 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "x").WithLocation(15, 16)); } [Fact] public void NotNullTypeParam_UpdatesArgumentState() { var source = @" public class Program<T> where T : notnull { void M0(T t) { } void M1() { T t = default; M0(t); // 2 _ = t.ToString(); } } "; var comp = CreateNullableCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,12): warning CS8604: Possible null reference argument for parameter 't' in 'void Program<T>.M0(T t)'. // M0(t); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("t", "void Program<T>.M0(T t)").WithLocation(9, 12) ); } [Fact] public void NotNullConstrainedParam_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0<T>(T t) where T : notnull { } void M1(string? s) { M0(s); // 1 _ = s.ToString(); // 2 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'Program.M0<T>(T)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M0(s); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M0").WithArguments("Program.M0<T>(T)", "T", "string?").WithLocation(8, 9), // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NotNullConstrainedParam_SuppressedArgument_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0<T>(T t) where T : notnull { } void M1(string? s) { M0(s!); _ = s.ToString(); // 1 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void Params_NotNullConstrainedElement_AnnotatedArray_DoesNotUpdateArgumentState() { var source = @" public class Program { void M0<T>(params T[]? s0) where T : notnull { } void M1(string? s1) { M0(s1); // 1 _ = s1.ToString(); // 2 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'Program.M0<T>(params T[]?)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M0(s1); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M0").WithArguments("Program.M0<T>(params T[]?)", "T", "string?").WithLocation(8, 9), // (9,13): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 13) ); } [Fact] public void Params_NotNullTypeArgument_AnnotatedArray_UpdatesArgumentState() { var source = @" public class Program { void M0<T>(params T[]? s0) where T : notnull { } void M1(string? s1) { M0<string>(s1); // 1 _ = s1.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,20): warning CS8604: Possible null reference argument for parameter 's0' in 'void Program.M0<string>(params string[]? s0)'. // M0<string>(s1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s1").WithArguments("s0", "void Program.M0<string>(params string[]? s0)").WithLocation(8, 20) ); } [Fact] public void NotNull_Parameter_Generic() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) => throw null!; public virtual void F2<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : class => throw null!; public virtual void F3<T>([NotNull]T? t1, [NotNull] out T? t2, [NotNull] ref T? t3, [NotNull] in T? t4) where T : class => throw null!; public virtual void F4<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : struct => throw null!; public virtual void F5<T>([NotNull]T? t1, [NotNull] out T? t2, [NotNull] ref T? t3, [NotNull] in T? t4) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t2, t3, t4 public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t2, t3, t4 public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t2, t3, t4 } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(12, 26), // (12,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(12, 26), // (12,26): error CS8762: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (12,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(12, 26), // (13,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(13, 26), // (13,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(13, 26), // (14,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t1").WithLocation(14, 26), // (14,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t2").WithLocation(14, 26), // (14,26): error CS8762: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t3").WithLocation(14, 26), // (14,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t4").WithLocation(14, 26), // (15,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t1").WithLocation(15, 26), // (15,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t4").WithLocation(15, 26), // (16,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t1").WithLocation(16, 26), // (16,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t2").WithLocation(16, 26), // (16,26): error CS8762: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t3").WithLocation(16, 26), // (16,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t2, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t4").WithLocation(16, 26) ); } [Fact] public void NotNullWhenTrue_Parameter_Generic() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>([NotNullWhen(true)]T t1, [NotNullWhen(true)] out T t2, [NotNullWhen(true)] ref T t3, [NotNullWhen(true)] in T t4) => throw null!; public virtual bool F2<T>([NotNullWhen(true)]T t1, [NotNullWhen(true)] out T t2, [NotNullWhen(true)] ref T t3, [NotNullWhen(true)] in T t4) where T : class => throw null!; public virtual bool F3<T>([NotNullWhen(true)]T? t1, [NotNullWhen(true)] out T? t2, [NotNullWhen(true)] ref T? t3, [NotNullWhen(true)] in T? t4) where T : class => throw null!; public virtual bool F4<T>([NotNullWhen(true)]T t1, [NotNullWhen(true)] out T t2, [NotNullWhen(true)] ref T t3, [NotNullWhen(true)] in T t4) where T : struct => throw null!; public virtual bool F5<T>([NotNullWhen(true)]T? t1, [NotNullWhen(true)] out T? t2, [NotNullWhen(true)] ref T? t3, [NotNullWhen(true)] in T? t4) where T : struct => throw null!; } public class Derived : Base { public override bool F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t2, t3 public override bool F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public override bool F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t2, t3 public override bool F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public override bool F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t2, t3 } "; var comp = CreateNullableCompilation(new[] { NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): warning CS8765: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override bool F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(12, 26), // (12,26): warning CS8765: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override bool F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (14,26): warning CS8765: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override bool F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t2").WithLocation(14, 26), // (14,26): warning CS8765: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override bool F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t3").WithLocation(14, 26), // (16,26): warning CS8765: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override bool F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t2").WithLocation(16, 26), // (16,26): warning CS8765: Type of parameter 't3' doesn't match overridden member because of nullability attributes. // public override bool F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t3").WithLocation(16, 26) ); } [Fact, WorkItem(42470, "https://github.com/dotnet/roslyn/issues/42470")] public void NotNullWhenTrue_Variance() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; interface I<T> { bool TryRead([MaybeNullWhen(false)] out T item); } class C : I<int[]> { public bool TryRead([NotNullWhen(true)] out int[]? item) => throw null!; } ", MaybeNullWhenAttributeDefinition, NotNullWhenAttributeDefinition }); c.VerifyDiagnostics(); } [Fact, WorkItem(42470, "https://github.com/dotnet/roslyn/issues/42470")] public void MaybeNull_Variance() { var c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; interface I<T> { [return: MaybeNull] T Get(); } class C : I<object> { public object? Get() => null!; } ", MaybeNullAttributeDefinition }); c.VerifyDiagnostics(); } [Fact] public void NotNull_Parameter_Generic_ObliviousBase() { var source = @"using System.Diagnostics.CodeAnalysis; #nullable disable public class Base { public virtual void F1<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) => throw null!; public virtual void F2<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : class => throw null!; public virtual void F4<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : struct => throw null!; } #nullable enable public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 } "; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(13, 26), // (13,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(13, 26), // (14,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(14, 26), // (14,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(14, 26), // (15,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t1").WithLocation(15, 26), // (15,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t4").WithLocation(15, 26) ); } [Fact] public void NotNull_Parameter_Generic_ObliviousDerived() { var source = @"using System.Diagnostics.CodeAnalysis; #nullable enable public class Base { public virtual void F1<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) => throw null!; public virtual void F2<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : class => throw null!; public virtual void F4<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : struct => throw null!; } #nullable disable annotations public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 } #nullable disable public class Derived2 : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; } "; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(13, 26), // (13,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(13, 26), // (14,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(14, 26), // (14,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(14, 26), // (15,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t1").WithLocation(15, 26), // (15,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t4").WithLocation(15, 26) ); } [Fact, WorkItem(40139, "https://github.com/dotnet/roslyn/issues/40139")] public void DisallowNull_EnforcedInMethodBody() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C<T> { object _f; C([DisallowNull]T t) { _f = t; } } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_MaybeNullWhen() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<T> { static void GetValue(T x, [MaybeNull] out T y) { y = x; } static bool TryGetValue(T x, [MaybeNullWhen(true)] out T y) { y = x; return y == null; } static bool TryGetValue2(T x, [MaybeNullWhen(true)] out T y) { y = x; return y != null; } static bool TryGetValue3(T x, [MaybeNullWhen(false)] out T y) { y = x; return y == null; } static bool TryGetValue4(T x, [MaybeNullWhen(false)] out T y) { y = x; return y != null; } } "; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Theory] [InlineData("TClass")] [InlineData("TNotNull")] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_MaybeNullWhen_NotNullableTypes(string type) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<TClass, TNotNull> where TClass : class where TNotNull : notnull { static bool TryGetValue(TYPE x, [MaybeNullWhen(true)] out TYPE y) { y = x; return y == null; } static bool TryGetValue2(TYPE x, [MaybeNullWhen(true)] out TYPE y) { y = x; return y != null; // 1 } static bool TryGetValue3(TYPE x, [MaybeNullWhen(false)] out TYPE y) { y = x; return y == null; // 2 } static bool TryGetValue4(TYPE x, [MaybeNullWhen(false)] out TYPE y) { y = x; return y != null; } } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, source.Replace("TYPE", type) }); comp.VerifyDiagnostics( // (18,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'false'. // return y != null; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return y != null;").WithArguments("y", "false").WithLocation(18, 9), // (24,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'true'. // return y == null; // 2 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return y == null;").WithArguments("y", "true").WithLocation(24, 9) ); } [Theory] [InlineData("T")] [InlineData("TClass")] [InlineData("TNotNull")] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_MaybeNullWhen_MaybeDefaultValue(string type) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<T, TClass, TNotNull> where TClass : class where TNotNull : notnull { static void GetValue([AllowNull] TYPE x, [MaybeNull] out TYPE y) { y = x; } static bool TryGetValue([AllowNull] TYPE x, [MaybeNullWhen(true)] out TYPE y) { y = x; return y == null; } static bool TryGetValue2([AllowNull] TYPE x, [MaybeNullWhen(true)] out TYPE y) { y = x; return y != null; // 1 } static bool TryGetValue3([AllowNull] TYPE x, [MaybeNullWhen(false)] out TYPE y) { y = x; return y == null; // 2 } static bool TryGetValue4([AllowNull] TYPE x, [MaybeNullWhen(false)] out TYPE y) { y = x; return y != null; } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, MaybeNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source.Replace("TYPE", type) }); comp.VerifyDiagnostics( // (24,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'false'. // return y != null; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return y != null;").WithArguments("y", "false").WithLocation(24, 9), // (30,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'true'. // return y == null; // 2 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return y == null;").WithArguments("y", "true").WithLocation(30, 9) ); } [Theory] [InlineData("T")] [InlineData("TClass")] [InlineData("TNotNull")] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_MaybeNullWhen_Composition(string type) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<T, TClass, TNotNull> where TClass : class where TNotNull : notnull { static void GetValue([AllowNull] TYPE x, [MaybeNull] out TYPE y) { GetValue(x, out y); } static bool TryGetValue([AllowNull] TYPE x, [MaybeNullWhen(true)] out TYPE y) { return TryGetValue(x, out y); } static bool TryGetValue3([AllowNull] TYPE x, [MaybeNullWhen(false)] out TYPE y) { return TryGetValue3(x, out y); } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, MaybeNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source.Replace("TYPE", type) }); comp.VerifyDiagnostics(); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_MaybeNullWhen_Composition_ImplementWithNotNullWhen() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { bool TryGetValue([MaybeNullWhen(true)] out string y) { return TryGetValueCore(out y); } bool TryGetValue2([MaybeNullWhen(true)] out string y) { return !TryGetValueCore(out y); // 1 } bool TryGetValueCore([NotNullWhen(false)] out string? y) { throw null!; } } "; var comp = CreateNullableCompilation(new[] { NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (15,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'false'. // return !TryGetValueCore(out y); // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return !TryGetValueCore(out y);").WithArguments("y", "false").WithLocation(15, 9) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_MaybeNullWhen_TwoParameter() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class Program { static bool TryGetValue<T>([AllowNull]T x, [MaybeNullWhen(true)]out T y, [MaybeNullWhen(true)]out T z) { y = x; z = x; return y != null || z != null; } static bool TryGetValue2<T>([AllowNull]T x, [MaybeNullWhen(false)]out T y, [MaybeNullWhen(false)]out T z) { y = x; z = x; return y != null && z != null; } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Theory] [InlineData("TStruct?")] [InlineData("TClass?")] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_NotNullWhen(string type) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<TStruct, TClass> where TStruct : struct where TClass : class { static bool TryGetValue([NotNullWhen(true)] out TYPE y) { y = null; if (y == null) { return true; // 1 } return false; } static bool TryGetValue2([NotNullWhen(true)] out TYPE y) { y = null; return y != null; } static bool TryGetValue2B([NotNullWhen(true)] out TYPE y) { y = null; return y == null; // 2 } static bool TryGetValue3([NotNullWhen(false)] out TYPE y) { y = null; return y == null; } static bool TryGetValue3B([NotNullWhen(false)] out TYPE y) { y = null; return y != null; // 3 } static bool TryGetValue4([NotNull] TYPE x, [NotNullWhen(false)] out TYPE y) { y = null; if (y != null) { return true; // 4 } return false; // 5, 6 } } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, NotNullWhenAttributeDefinition, source.Replace("TYPE", type) }); comp.VerifyDiagnostics( // (15,13): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'true'. // return true; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return true;").WithArguments("y", "true").WithLocation(15, 13), // (29,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'true'. // return y == null; // 2 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return y == null;").WithArguments("y", "true").WithLocation(29, 9), // (41,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'false'. // return y != null; // 3 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return y != null;").WithArguments("y", "false").WithLocation(41, 9), // (49,13): warning CS8777: Parameter 'x' must have a non-null value when exiting. // return true; // 4 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return true;").WithArguments("x").WithLocation(49, 13), // (51,9): warning CS8777: Parameter 'x' must have a non-null value when exiting. // return false; // 5, 6 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "return false;").WithArguments("x").WithLocation(51, 9), // (51,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'false'. // return false; // 5, 6 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return false;").WithArguments("y", "false").WithLocation(51, 9) ); } [Fact] public void EnforcedInMethodBody_NotNull_MiscTypes() { var source = @" using System.Diagnostics.CodeAnalysis; class C<TStruct, TNotNull> where TStruct : struct where TNotNull : notnull { void M([NotNull] int? i, [NotNull] int i2, [NotNull] TStruct? s, [NotNull] TStruct s2, [NotNull] TNotNull n) { } } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (10,5): warning CS8777: Parameter 'i' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("i").WithLocation(10, 5), // (10,5): warning CS8777: Parameter 's' must have a non-null value when exiting. // } Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("s").WithLocation(10, 5) ); } [Fact] public void EnforcedInMethodBody_NotNullImplementedWithDoesNotReturnIf() { var source = @" using System.Diagnostics.CodeAnalysis; class C { void M([NotNull] object? value) { Assert(value is object); } void Assert([DoesNotReturnIf(false)] bool b) => throw null!; } "; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition, DoesNotReturnIfAttributeDefinition }); comp.VerifyDiagnostics(); } [Theory] [InlineData("TStruct?")] [InlineData("TClass?")] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_NotNullWhen_Composition(string type) { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C<TStruct, TClass> where TStruct : struct where TClass : class { static bool TryGetValue([NotNullWhen(true)] out TYPE y) { return TryGetValue(out y); } static bool TryGetValue2([NotNullWhen(true)] out TYPE y) { return TryGetValue3(out y); // 1 } static bool TryGetValue3([NotNullWhen(false)] out TYPE y) { return TryGetValue3(out y); } static bool TryGetValue3B([NotNullWhen(false)] out TYPE y) { return TryGetValue2(out y); // 2 } static bool TryGetValue4([NotNull] TYPE x, [NotNullWhen(false)] out TYPE y) { return TryGetValue4(x, out y); } static bool TryGetValueString1(string key, [MaybeNullWhen(false)] out string value) => TryGetValueString2(key, out value); static bool TryGetValueString2(string key, [NotNullWhen(true)] out string? value) => TryGetValueString1(key, out value); } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, NotNullAttributeDefinition, NotNullWhenAttributeDefinition, source.Replace("TYPE", type) }); comp.VerifyDiagnostics( // (17,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'true'. // return TryGetValue3(out y); // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return TryGetValue3(out y);").WithArguments("y", "true").WithLocation(17, 9), // (27,9): warning CS8762: Parameter 'y' must have a non-null value when exiting with 'false'. // return TryGetValue2(out y); // 2 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return TryGetValue2(out y);").WithArguments("y", "false").WithLocation(27, 9) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_NotNullWhen_Unreachable() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { static bool TryGetValue([NotNullWhen(true)] out string? y) { if (false) { y = null; return true; } y = """"; return false; } } "; var comp = CreateNullableCompilation(new[] { NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,13): warning CS0162: Unreachable code detected // y = null; Diagnostic(ErrorCode.WRN_UnreachableCode, "y").WithLocation(11, 13) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_Misc_ProducingWarnings() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class Program { static void GetValue<T>([AllowNull]T x, out T y) { y = x; // 1 } static void GetValue2<T>(T x, out T y) { y = x; } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, MaybeNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (10,13): warning CS8601: Possible null reference assignment. // y = x; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(10, 13) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void EnforcedInMethodBody_DoesNotReturn() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; class C { [DoesNotReturn] static void ActuallyReturns() { } // 1 [DoesNotReturn] static bool ActuallyReturns2() { return true; // 2 } [DoesNotReturn] static bool ActuallyReturns3(bool b) { if (b) throw null!; else return true; // 3 } [DoesNotReturn] static bool ActuallyReturns4() => true; // 4 [DoesNotReturn] static void NeverReturns() { throw null!; } [DoesNotReturn] static bool NeverReturns2() { throw null!; } [DoesNotReturn] static bool NeverReturns3() => throw null!; [DoesNotReturn] static bool NeverReturns4() { return NeverReturns2(); } [DoesNotReturn] static void NeverReturns5() { NeverReturns(); } [DoesNotReturn] static void NeverReturns6() { while (true) { } } } "; var comp = CreateNullableCompilation(new[] { DoesNotReturnAttributeDefinition, source }); comp.VerifyDiagnostics( // (9,5): error CS8763: A method marked [DoesNotReturn] should not return. // } // 1 Diagnostic(ErrorCode.WRN_ShouldNotReturn, "}").WithLocation(9, 5), // (14,9): error CS8763: A method marked [DoesNotReturn] should not return. // return true; // 2 Diagnostic(ErrorCode.WRN_ShouldNotReturn, "return true;").WithLocation(14, 9), // (23,13): error CS8763: A method marked [DoesNotReturn] should not return. // return true; // 3 Diagnostic(ErrorCode.WRN_ShouldNotReturn, "return true;").WithLocation(23, 13), // (28,12): error CS8763: A method marked [DoesNotReturn] should not return. // => true; // 4 Diagnostic(ErrorCode.WRN_ShouldNotReturn, "true").WithLocation(28, 12) ); } [Fact, WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void DoesNotReturn_OHI() { var source = @" #nullable enable using System.Diagnostics.CodeAnalysis; public class Base { [DoesNotReturn] public virtual void M() => throw null!; } public class Derived : Base { public override void M() => throw null!; // 1 } public class Derived2 : Base { [DoesNotReturn] public override void M() => throw null!; } public class Derived3 : Base { [DoesNotReturn] public new void M() => throw null!; } public class Derived4 : Base { public new void M() => throw null!; } interface I { [DoesNotReturn] bool M(); } class C1 : I { bool I.M() => throw null!; // 2 } class C2 : I { [DoesNotReturn] bool I.M() => throw null!; } "; var comp = CreateNullableCompilation(new[] { DoesNotReturnAttributeDefinition, DoesNotReturnIfAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,26): warning CS8770: Method 'void Derived.M()' lacks `[DoesNotReturn]` annotation to match implemented or overridden member. // public override void M() => throw null!; // 1 Diagnostic(ErrorCode.WRN_DoesNotReturnMismatch, "M").WithArguments("void Derived.M()").WithLocation(11, 26), // (35,12): warning CS8770: Method 'bool C1.M()' lacks `[DoesNotReturn]` annotation to match implemented or overridden member. // bool I.M() => throw null!; // 2 Diagnostic(ErrorCode.WRN_DoesNotReturnMismatch, "M").WithArguments("bool C1.M()").WithLocation(35, 12) ); } [Fact] public void NotNull_Parameter_Generic_OnOverrides() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public virtual void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public virtual void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public virtual void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public virtual void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) => throw null!; public override void F2<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : class => throw null!; public override void F3<T>([NotNull]T? t1, [NotNull] out T? t2, [NotNull] ref T? t3, [NotNull] in T? t4) where T : class => throw null!; public override void F4<T>([NotNull]T t1, [NotNull] out T t2, [NotNull] ref T t3, [NotNull] in T t4) where T : struct => throw null!; public override void F5<T>([NotNull]T? t1, [NotNull] out T? t2, [NotNull] ref T? t3, [NotNull] in T? t4) where T : struct => throw null!; } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void NotNullWhenFalse_Parameter_Generic_OnOverrides() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public virtual bool F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public virtual bool F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public virtual bool F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public virtual bool F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } public class Derived : Base { public override bool F1<T>([NotNullWhen(false)]T t1, [NotNullWhen(false)] out T t2, [NotNullWhen(false)] ref T t3, [NotNullWhen(false)] in T t4) => throw null!; public override bool F2<T>([NotNullWhen(false)]T t1, [NotNullWhen(false)] out T t2, [NotNullWhen(false)] ref T t3, [NotNullWhen(false)] in T t4) where T : class => throw null!; public override bool F3<T>([NotNullWhen(false)]T? t1, [NotNullWhen(false)] out T? t2, [NotNullWhen(false)] ref T? t3, [NotNullWhen(false)] in T? t4) where T : class => throw null!; public override bool F4<T>([NotNullWhen(false)]T t1, [NotNullWhen(false)] out T t2, [NotNullWhen(false)] ref T t3, [NotNullWhen(false)] in T t4) where T : struct => throw null!; public override bool F5<T>([NotNullWhen(false)]T? t1, [NotNullWhen(false)] out T? t2, [NotNullWhen(false)] ref T? t3, [NotNullWhen(false)] in T? t4) where T : struct => throw null!; } "; var comp = CreateNullableCompilation(new[] { NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact, WorkItem(42169, "https://github.com/dotnet/roslyn/issues/42169")] public void NotNullWhenTrue_WithMaybeNull_Overriding() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { internal virtual bool TryGetValueCore<TKey, TValue>(TKey key, [MaybeNull] [NotNullWhen(true)] out TValue value) where TKey : class { throw null!; } } public class Derived : C { internal override bool TryGetValueCore<TKey, TValue>(TKey key, [MaybeNull] [NotNullWhen(true)] out TValue value) { throw null!; } } "; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact, WorkItem(42169, "https://github.com/dotnet/roslyn/issues/42169")] public void NotNullWhenFalse_WithMaybeNull_Overriding() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { internal virtual bool TryGetValueCore<TKey, TValue>(TKey key, [MaybeNull] [NotNullWhen(false)] out TValue value) where TKey : class { throw null!; } } public class Derived : C { internal override bool TryGetValueCore<TKey, TValue>(TKey key, [MaybeNull] [NotNullWhen(false)] out TValue value) { throw null!; } } "; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact, WorkItem(42169, "https://github.com/dotnet/roslyn/issues/42169")] public void MaybeNullWhenTrue_WithNotNull_Overriding() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { internal virtual bool TryGetValueCore<TKey, TValue>(TKey key, [NotNull] [MaybeNullWhen(true)] out TValue value) where TKey : class { throw null!; } } public class Derived : C { internal override bool TryGetValueCore<TKey, TValue>(TKey key, [NotNull] [MaybeNullWhen(true)] out TValue value) { throw null!; } } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNull_Parameter_Generic() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; public virtual void F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; public virtual void F3<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : class => throw null!; public virtual void F4<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : struct => throw null!; public virtual void F5<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : struct => throw null!; public virtual void F6<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : notnull => throw null!; } public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t4 public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t4 public override void F6<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 } "; // [MaybeNull] on a by-value or `in` parameter means a null-test (only returns if null) var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(13, 26), // (13,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(13, 26), // (14,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(14, 26), // (14,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(14, 26), // (15,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t1").WithLocation(15, 26), // (15,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t4").WithLocation(15, 26), // (16,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t1").WithLocation(16, 26), // (16,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t4").WithLocation(16, 26), // (17,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t1").WithLocation(17, 26), // (17,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t4").WithLocation(17, 26), // (18,26): error CS8762: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override void F6<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t1").WithLocation(18, 26), // (18,26): error CS8762: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override void F6<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t4").WithLocation(18, 26) ); } [Fact] public void MaybeNullWhenTrue_Parameter_Generic() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) => throw null!; public virtual bool F2<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : class => throw null!; public virtual bool F3<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : class => throw null!; public virtual bool F4<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : struct => throw null!; public virtual bool F5<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : struct => throw null!; public virtual bool F6<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : notnull => throw null!; } public class Derived : Base { public override bool F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public override bool F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public override bool F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public override bool F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public override bool F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; public override bool F6<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; // t1, t4 } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNullWhenTrue_ImplementingAnnotatedInterface() { var source = @"using System.Diagnostics.CodeAnalysis; #nullable disable public interface I<T> { bool TryGetValue(out T t); } #nullable enable public class C<T> : I<T> { public bool TryGetValue([MaybeNullWhen(false)] out T t) => throw null!; } "; // Note: because we're implementing `I<T!>!`, we complain about returning a possible null value // through `bool TryGetValue(out T! t)` var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,17): warning CS8767: Nullability of reference types in type of parameter 't' of 'bool C<T>.TryGetValue(out T t)' doesn't match implicitly implemented member 'bool I<T>.TryGetValue(out T t)' because of nullability attributes. // public bool TryGetValue([MaybeNullWhen(false)] out T t) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "TryGetValue").WithArguments("t", "bool C<T>.TryGetValue(out T t)", "bool I<T>.TryGetValue(out T t)").WithLocation(11, 17) ); } [Fact] public void MaybeNullWhenTrue_ImplementingObliviousInterface() { var source = @"using System.Diagnostics.CodeAnalysis; #nullable disable public interface I<T> { bool TryGetValue(out T t); } #nullable enable public class C<T> : I< #nullable disable T #nullable enable > { public bool TryGetValue([MaybeNullWhen(false)] out T t) => throw null!; } "; var comp = CreateCompilation(new[] { MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNull_Parameter_Generic_OnOverrides() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public virtual void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public virtual void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public virtual void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public virtual void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; // t2, t3 public override void F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; // t2, t3 public override void F3<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : class => throw null!; public override void F4<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : struct => throw null!; public override void F5<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : struct => throw null!; } "; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(12, 26), // (12,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (13,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t2").WithLocation(13, 26), // (13,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t3").WithLocation(13, 26) ); } [Fact] public void MaybeNullWhenTrue_Parameter_Generic_OnOverrides() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public virtual bool F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public virtual bool F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public virtual bool F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public virtual bool F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } public class Derived : Base { public override bool F1<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) => throw null!; // t2, t3 public override bool F2<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : class => throw null!; // t2, t3 public override bool F3<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : class => throw null!; public override bool F4<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : struct => throw null!; public override bool F5<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : struct => throw null!; } public class Derived2 : Derived { } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F1<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(12, 26), // (12,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F1<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (13,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F2<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t2").WithLocation(13, 26), // (13,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F2<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t3").WithLocation(13, 26) ); } [Fact, WorkItem(41437, "https://github.com/dotnet/roslyn/issues/41437")] public void MaybeNullWhenTrue_Parameter_Generic_OnOverrides_WithMaybeNullWhenFalse() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) => throw null!; public virtual bool F2<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : class => throw null!; public virtual bool F3<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : class => throw null!; public virtual bool F4<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : struct => throw null!; public virtual bool F5<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : struct => throw null!; public virtual bool F6<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : notnull => throw null!; } public class Derived : Base { public override bool F1<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t2, t3 public override bool F2<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : class => throw null!; // t2, t3 public override bool F3<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : class => throw null!; public override bool F4<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : struct => throw null!; public override bool F5<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : struct => throw null!; public override bool F6<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F1<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(13, 26), // (13,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F1<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(13, 26), // (14,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F2<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t2").WithLocation(14, 26), // (14,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F2<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t3").WithLocation(14, 26), // (18,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F6<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t2").WithLocation(18, 26), // (18,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F6<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t3").WithLocation(18, 26) ); } [Fact, WorkItem(41437, "https://github.com/dotnet/roslyn/issues/41437")] public void AssigningMaybeNullTNotNullToTNotNullInOverride() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F6<T>([AllowNull] in T t4) where T : notnull => throw null!; } public class Derived : Base { public override bool F6<T>(in T t4) => throw null!; } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (8,26): warning CS8765: Nullability of type of parameter 't4' doesn't match overridden member (possibly because of nullability attributes). // public override bool F6<T>(in T t4) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t4").WithLocation(8, 26) ); } [Fact, WorkItem(41437, "https://github.com/dotnet/roslyn/issues/41437")] public void MaybeNullWhenTrue_Parameter_Generic_OnOverrides_WithMaybeNull() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) => throw null!; public virtual bool F2<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : class => throw null!; public virtual bool F3<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : class => throw null!; public virtual bool F4<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : struct => throw null!; public virtual bool F5<T>([MaybeNullWhen(true)]T? t1, [MaybeNullWhen(true)] out T? t2, [MaybeNullWhen(true)] ref T? t3, [MaybeNullWhen(true)] in T? t4) where T : struct => throw null!; public virtual bool F6<T>([MaybeNullWhen(true)]T t1, [MaybeNullWhen(true)] out T t2, [MaybeNullWhen(true)] ref T t3, [MaybeNullWhen(true)] in T t4) where T : notnull => throw null!; } public class Derived : Base { public override bool F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; // t2, t3 public override bool F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; // t2, t3 public override bool F3<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : class => throw null!; public override bool F4<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : struct => throw null!; public override bool F5<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : struct => throw null!; public override bool F6<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(13, 26), // (13,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(13, 26), // (14,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t2").WithLocation(14, 26), // (14,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; // t2, t3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t3").WithLocation(14, 26), // (18,26): warning CS8765: Nullability of type of parameter 't2' doesn't match overridden member (possibly because of nullability attributes). // public override bool F6<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t2").WithLocation(18, 26), // (18,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override bool F6<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t3").WithLocation(18, 26) ); } [Fact] public void MaybeNull_Parameter_Generic_OnOverrides_WithMaybeNullWhenFalse() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual bool F1<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) => throw null!; public virtual bool F2<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : class => throw null!; public virtual bool F3<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : class => throw null!; public virtual bool F4<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : struct => throw null!; public virtual bool F5<T>([MaybeNull]T? t1, [MaybeNull] out T? t2, [MaybeNull] ref T? t3, [MaybeNull] in T? t4) where T : struct => throw null!; public virtual bool F6<T>([MaybeNull]T t1, [MaybeNull] out T t2, [MaybeNull] ref T t3, [MaybeNull] in T t4) where T : notnull => throw null!; } public class Derived : Base { public override bool F1<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t1, t4 public override bool F2<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : class => throw null!; // t1, t4 public override bool F3<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : class => throw null!; // t1, t4 public override bool F4<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : struct => throw null!; // t1, t4 public override bool F5<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : struct => throw null!; // t1, t4 public override bool F6<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t1, t4 } "; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override bool F1<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(13, 26), // (13,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override bool F1<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(13, 26), // (14,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override bool F2<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t1").WithLocation(14, 26), // (14,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override bool F2<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t4").WithLocation(14, 26), // (15,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override bool F3<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t1").WithLocation(15, 26), // (15,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override bool F3<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : class => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t4").WithLocation(15, 26), // (16,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override bool F4<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t1").WithLocation(16, 26), // (16,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override bool F4<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t4").WithLocation(16, 26), // (17,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override bool F5<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t1").WithLocation(17, 26), // (17,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override bool F5<T>([MaybeNullWhen(false)]T? t1, [MaybeNullWhen(false)] out T? t2, [MaybeNullWhen(false)] ref T? t3, [MaybeNullWhen(false)] in T? t4) where T : struct => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t4").WithLocation(17, 26), // (18,26): warning CS8765: Type of parameter 't1' doesn't match overridden member because of nullability attributes. // public override bool F6<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t1").WithLocation(18, 26), // (18,26): warning CS8765: Type of parameter 't4' doesn't match overridden member because of nullability attributes. // public override bool F6<T>([MaybeNullWhen(false)]T t1, [MaybeNullWhen(false)] out T t2, [MaybeNullWhen(false)] ref T t3, [MaybeNullWhen(false)] in T t4) => throw null!; // t1, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t4").WithLocation(18, 26) ); } [Fact] public void DisallowNull_Parameter_Generic() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) => throw null!; public virtual void F2<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) where T : class => throw null!; public virtual void F3<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : class => throw null!; public virtual void F4<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) where T : struct => throw null!; public virtual void F5<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public override void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public override void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public override void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public override void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void DisallowNull_Parameter_Generic_OnOverrides() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>(T t1, out T t2, ref T t3, in T t4) => throw null!; public virtual void F2<T>(T t1, out T t2, ref T t3, in T t4) where T : class => throw null!; public virtual void F3<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : class => throw null!; public virtual void F4<T>(T t1, out T t2, ref T t3, in T t4) where T : struct => throw null!; public virtual void F5<T>(T? t1, out T? t2, ref T? t3, in T? t4) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) => throw null!; // t1, t3, t4 public override void F2<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) where T : class => throw null!; public override void F3<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : class => throw null!; // t1, t3, t4 public override void F4<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) where T : struct => throw null!; public override void F5<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : struct => throw null!; // t1, t3, t4 } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): warning CS8765: Nullability of type of parameter 't1' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t1").WithLocation(12, 26), // (12,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t3").WithLocation(12, 26), // (12,26): warning CS8765: Nullability of type of parameter 't4' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([DisallowNull]T t1, [DisallowNull] out T t2, [DisallowNull] ref T t3, [DisallowNull] in T t4) => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t4").WithLocation(12, 26), // (14,26): warning CS8765: Nullability of type of parameter 't1' doesn't match overridden member (possibly because of nullability attributes). // public override void F3<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t1").WithLocation(14, 26), // (14,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override void F3<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t3").WithLocation(14, 26), // (14,26): warning CS8765: Nullability of type of parameter 't4' doesn't match overridden member (possibly because of nullability attributes). // public override void F3<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : class => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t4").WithLocation(14, 26), // (16,26): warning CS8765: Nullability of type of parameter 't1' doesn't match overridden member (possibly because of nullability attributes). // public override void F5<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : struct => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t1").WithLocation(16, 26), // (16,26): warning CS8765: Nullability of type of parameter 't3' doesn't match overridden member (possibly because of nullability attributes). // public override void F5<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : struct => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t3").WithLocation(16, 26), // (16,26): warning CS8765: Nullability of type of parameter 't4' doesn't match overridden member (possibly because of nullability attributes). // public override void F5<T>([DisallowNull]T? t1, [DisallowNull] out T? t2, [DisallowNull] ref T? t3, [DisallowNull] in T? t4) where T : struct => throw null!; // t1, t3, t4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t4").WithLocation(16, 26) ); } [Fact] public void DisallowNull_Parameter_01() { // Warn on misused nullability attributes (F2, F3, F4)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool b = false; static void F1<T>([DisallowNull]T t) { } static void F2<T>([DisallowNull]T t) where T : class { } static void F3<T>([DisallowNull]T? t) where T : class { } static void F4<T>([DisallowNull]T t) where T : struct { } static void F5<T>([DisallowNull]T? t) where T : struct { } static void M1<T>(T t1) { F1(t1); // 0 } static void M2<T>(T t2) where T : class { F1(t2); F2(t2); F3(t2); t2 = null; // 1 if (b) F1(t2); // 2 if (b) F2(t2); // 3, 4 if (b) F3(t2); // 5 } static void M3<T>(T? t3) where T : class { if (b) F1(t3); // 6 if (b) F2(t3); // 7, 8 if (b) F3(t3); // 9 if (t3 == null) return; F1(t3); F2(t3); F3(t3); } static void M4<T>(T t4) where T : struct { F1(t4); F4(t4); } static void M5<T>(T? t5) where T : struct { if (b) F1(t5); // 10 if (b) F5(t5); // 11 if (t5 == null) return; F1(t5); F5(t5); } }"; var comp = CreateCompilation(new[] { DisallowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,12): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // F1(t1); // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(12, 12), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 14), // (20,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T?>(T? t)'. // if (b) F1(t2); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F1<T?>(T? t)").WithLocation(20, 19), // (21,16): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // if (b) F2(t2); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(21, 16), // (21,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T?>(T? t)'. // if (b) F2(t2); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F2<T?>(T? t)").WithLocation(21, 19), // (22,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T? t)'. // if (b) F3(t2); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F3<T>(T? t)").WithLocation(22, 19), // (26,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T?>(T? t)'. // if (b) F1(t3); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F1<T?>(T? t)").WithLocation(26, 19), // (27,16): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // if (b) F2(t3); // 7, 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(27, 16), // (27,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T?>(T? t)'. // if (b) F2(t3); // 7, 8 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F2<T?>(T? t)").WithLocation(27, 19), // (28,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T? t)'. // if (b) F3(t3); // 9 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F3<T>(T? t)").WithLocation(28, 19), // (41,19): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // if (b) F1(t5); // 10 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(41, 19), // (42,19): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // if (b) F5(t5); // 11 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(42, 19) ); } [Fact, WorkItem(36009, "https://github.com/dotnet/roslyn/issues/36009")] public void DisallowNull_Parameter_NullableValueType() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F5<T>([DisallowNull]T? t) where T : struct { } static void M5<T>(T? t5) where T : struct { F5(t5); // 1 if (t5 == null) return; F5(t5); } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (7,12): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // F5(t5); Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(7, 12) ); } [Fact, WorkItem(36009, "https://github.com/dotnet/roslyn/issues/36009")] public void DisallowNull_RefParameter_NullableValueType() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F5<T>([DisallowNull]ref T? t) where T : struct { } static void M5<T>(T? t5) where T : struct { F5(ref t5); // 1 if (t5 == null) return; F5(ref t5); } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (7,16): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // F5(ref t5); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(7, 16) ); } [Fact, WorkItem(36009, "https://github.com/dotnet/roslyn/issues/36009")] public void DisallowNull_InParameter_NullableValueType() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F5<T>([DisallowNull]in T? t) where T : struct { } static void M5<T>(T? t5) where T : struct { F5(in t5); // 1 if (t5 == null) return; F5(in t5); } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (7,15): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // F5(in t5); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(7, 15) ); } [Fact, WorkItem(36009, "https://github.com/dotnet/roslyn/issues/36009")] public void DisallowNull_ByValParameter_NullableValueTypeViaConstraint() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base<T> { public virtual void M<U>(U u) where U : T { } } public class C<T2> : Base<System.Nullable<T2>> where T2 : struct { public override void M<U>(U u) // U is constrained to be a Nullable<T2> type { M2(u); // 1 if (u is null) return; M2(u); } void M2<T3>([DisallowNull] T3 t) { } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,12): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // M2(u); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "u").WithLocation(11, 12) ); } [Fact] public void DisallowNull_Parameter_01_WithAllowNull() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool b = false; static void F1<T>([DisallowNull, AllowNull]T t) { } static void F2<T>([DisallowNull, AllowNull]T t) where T : class { } static void F3<T>([DisallowNull, AllowNull]T? t) where T : class { } static void F4<T>([DisallowNull, AllowNull]T t) where T : struct { } static void F5<T>([DisallowNull, AllowNull]T? t) where T : struct { } static void M1<T>(T t1) { F1(t1); // 0 } static void M2<T>(T t2) where T : class { F1(t2); F2(t2); F3(t2); t2 = null; // 1 if (b) F1(t2); // 2 if (b) F2(t2); // 3, 4 if (b) F3(t2); // 5 } static void M3<T>(T? t3) where T : class { if (b) F1(t3); // 6 if (b) F2(t3); // 7, 8 if (b) F3(t3); // 9 if (t3 == null) return; F1(t3); F2(t3); F3(t3); } static void M4<T>(T t4) where T : struct { F1(t4); F4(t4); } static void M5<T>(T? t5) where T : struct { if (b) F1(t5); // 10 if (b) F5(t5); // 11 if (t5 == null) return; F1(t5); F5(t5); } }"; var comp = CreateCompilation(new[] { DisallowNullAttributeDefinition, AllowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,12): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // F1(t1); // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(12, 12), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 14), // (20,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T?>(T? t)'. // if (b) F1(t2); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F1<T?>(T? t)").WithLocation(20, 19), // (21,16): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // if (b) F2(t2); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(21, 16), // (21,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T?>(T? t)'. // if (b) F2(t2); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F2<T?>(T? t)").WithLocation(21, 19), // (22,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T? t)'. // if (b) F3(t2); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F3<T>(T? t)").WithLocation(22, 19), // (26,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T?>(T? t)'. // if (b) F1(t3); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F1<T?>(T? t)").WithLocation(26, 19), // (27,16): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // if (b) F2(t3); // 7, 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(27, 16), // (27,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T?>(T? t)'. // if (b) F2(t3); // 7, 8 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F2<T?>(T? t)").WithLocation(27, 19), // (28,19): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T? t)'. // if (b) F3(t3); // 9 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F3<T>(T? t)").WithLocation(28, 19), // (41,19): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // if (b) F1(t5); // 10 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(41, 19), // (42,19): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // if (b) F5(t5); // 11 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(42, 19) ); } [Fact, WorkItem(36009, "https://github.com/dotnet/roslyn/issues/36009")] public void DisallowNull_Parameter_02() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool b = false; static void F1<T>([DisallowNull]T t) { } static void F2<T>([DisallowNull]T t) where T : class { } static void F3<T>([DisallowNull]T? t) where T : class { } static void F4<T>([DisallowNull]T t) where T : struct { } static void F5<T>([DisallowNull]T? t) where T : struct { } static void M1<T>(T t1) { F1<T>(t1); // 0 } static void M2<T>(T t2) where T : class { F1<T>(t2); F2<T>(t2); F3<T>(t2); t2 = null; // 1 if (b) F1<T>(t2); // 2 if (b) F2<T>(t2); // 3 if (b) F3<T>(t2); // 4 } static void M3<T>(T? t3) where T : class { if (b) F1<T>(t3); // 5 if (b) F2<T>(t3); // 6 if (b) F3<T>(t3); // 7 if (t3 == null) return; F1<T>(t3); F2<T>(t3); F3<T>(t3); } static void M4<T>(T t4) where T : struct { F1<T>(t4); F4<T>(t4); } static void M5<T>(T? t5) where T : struct { F1<T?>(t5); // 8 F5<T>(t5); // 9 if (t5 == null) return; F1<T?>(t5); F5<T>(t5); } }"; var comp = CreateCompilation(new[] { DisallowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,15): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // F1<T>(t1); // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(12, 15), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 14), // (20,22): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T>(T t)'. // if (b) F1<T>(t2); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F1<T>(T t)").WithLocation(20, 22), // (21,22): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T>(T t)'. // if (b) F2<T>(t2); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F2<T>(T t)").WithLocation(21, 22), // (22,22): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T? t)'. // if (b) F3<T>(t2); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void Program.F3<T>(T? t)").WithLocation(22, 22), // (26,22): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T>(T t)'. // if (b) F1<T>(t3); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F1<T>(T t)").WithLocation(26, 22), // (27,22): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T>(T t)'. // if (b) F2<T>(t3); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F2<T>(T t)").WithLocation(27, 22), // (28,22): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T? t)'. // if (b) F3<T>(t3); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void Program.F3<T>(T? t)").WithLocation(28, 22), // (41,16): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // F1<T?>(t5); // 8 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(41, 16) ); } [Fact] public void DisallowNull_Parameter_03() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool b = false; static void F1([DisallowNull]string s) { } static void F2([DisallowNull]string? s) { } static void M1(string s1) { F1(s1); F2(s1); s1 = null; // 1 if (b) F1(s1); // 2 if (b) F2(s1); // 3 } static void M2(string? s2) { if (b) F1(s2); // 4 if (b) F2(s2); // 5 if (s2 == null) return; F1(s2); F2(s2); } }"; var comp = CreateCompilation(new[] { DisallowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // s1 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 14), // (12,19): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.F1(string s)'. // if (b) F1(s1); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s1").WithArguments("s", "void Program.F1(string s)").WithLocation(12, 19), // (13,19): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.F2(string? s)'. // if (b) F2(s1); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s1").WithArguments("s", "void Program.F2(string? s)").WithLocation(13, 19), // (17,19): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.F1(string s)'. // if (b) F1(s2); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s2").WithArguments("s", "void Program.F1(string s)").WithLocation(17, 19), // (18,19): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.F2(string? s)'. // if (b) F2(s2); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s2").WithArguments("s", "void Program.F2(string? s)").WithLocation(18, 19)); } [Fact, WorkItem(36009, "https://github.com/dotnet/roslyn/issues/36009")] public void DisallowNull_Parameter_04() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([DisallowNull]int i) { } static void F2([DisallowNull]int? i) { } static void M1(int i1) { F1(i1); F2(i1); } static void M2(int? i2) { F2(i2); // 1 if (i2 == null) return; F2(i2); } }"; var comp = CreateCompilation(new[] { DisallowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,12): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // F2(i2); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "i2").WithLocation(13, 12) ); } [Fact] public void DisallowNull_Parameter_05() { // Warn on misused nullability attributes (F2)? https://github.com/dotnet/roslyn/issues/36073 var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static void F1<T>(T? t) where T : class { } public static void F2<T>([DisallowNull]T? t) where T : class { } }"; var comp = CreateCompilation(new[] { DisallowNullAttributeDefinition, source0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x); F1(y); F2(x); // 2 F2(y); } }"; comp = CreateNullableCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (9,12): warning CS8604: Possible null reference argument for parameter 't' in 'void A.F2<object>(object? t)'. // F2(x); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void A.F2<object>(object? t)").WithLocation(9, 12) ); } [Fact] public void DisallowNull_Parameter_OnOverride() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void M([DisallowNull] string? s) { } } public class C : Base { public override void M(string? s) { } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new Base().M(s); // 1 new Base().M(s2); new C().M(s); new C().M(s2); } }"; var expected = new[] { // (6,22): warning CS8604: Possible null reference argument for parameter 's' in 'void Base.M(string? s)'. // new Base().M(s); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s").WithArguments("s", "void Base.M(string? s)").WithLocation(6, 22) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact, WorkItem(36703, "https://github.com/dotnet/roslyn/issues/36703")] public void DisallowNull_RefReturnValue_05() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static T? F1<T>(T t) where T : class => throw null!; [return: DisallowNull] public static ref T? F2<T>(T t) where T : class => throw null!; }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source0 }); comp.VerifyDiagnostics( // (5,14): error CS0592: Attribute 'DisallowNull' is not valid on this declaration type. It is only valid on 'property, indexer, field, parameter' declarations. // [return: DisallowNull] public static ref T? F2<T>(T t) where T : class => throw null!; Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "DisallowNull").WithArguments("DisallowNull", "property, indexer, field, parameter").WithLocation(5, 14) ); var source1 = @"using System.Diagnostics.CodeAnalysis; namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.All)] public sealed class DisallowNullAttribute : Attribute { } } public class A { public static ref T? F1<T>(T t) where T : class => throw null!; [return: DisallowNull] public static ref T? F2<T>(T t) where T : class => throw null!; static void Main() { object? y = new object(); F1(y) = y; F2(y) = y; // DisallowNull is ignored } }"; var comp2 = CreateNullableCompilation(source1); comp2.VerifyDiagnostics(); } [Fact] public void DisallowNull_OutParameter_03() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([DisallowNull]out string t) => throw null!; static void F2([DisallowNull]out string? t) => throw null!; static void M() { F1(out string? t1); t1.ToString(); F2(out string? t2); t2.ToString(); // 1 } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(12, 9) ); } [Fact] public void AllowNull_OutParameter_03() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([AllowNull]out string t) => throw null!; static void F2([AllowNull]out string? t) => throw null!; static void M() { F1(out string? t1); t1.ToString(); F2(out string? t2); t2.ToString(); // 1 } }"; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(12, 9) ); } [Fact] public void DisallowNull_RefParameter_03() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([DisallowNull]ref string s) { } static void F2([DisallowNull]ref string? s) { } static void M1() { string s1 = """"; F1(ref s1); s1.ToString(); string? s2 = """"; F2(ref s2); s2.ToString(); // 1 string s3 = null; // 2 F1(ref s3); // 3 s3.ToString(); string? s4 = null; // 4 F2(ref s4); // 5 s4.ToString(); // 6 } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(14, 9), // (16,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string s3 = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 21), // (17,16): warning CS8601: Possible null reference assignment. // F1(ref s3); // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s3").WithLocation(17, 16), // (21,16): warning CS8601: Possible null reference assignment. // F2(ref s4); // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s4").WithLocation(21, 16), // (22,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(22, 9) ); } [Fact] public void DisallowNull_Property() { // Warn on misused nullability attributes (P2, P3, P4)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [DisallowNull]public TOpen P1 { get; set; } = default!; } public class CClass<TClass> where TClass : class { [DisallowNull]public TClass P2 { get; set; } = null!; [DisallowNull]public TClass? P3 { get; set; } = null; } public class CStruct<TStruct> where TStruct : struct { [DisallowNull]public TStruct P4 { get; set; } [DisallowNull]public TStruct? P5 { get; set; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class C { static void M1<T>(T t1) { new COpen<T>().P1 = t1; // 0 } static void M2<T>(T t2) where T : class { new COpen<T>().P1 = t2; new CClass<T>().P2 = t2; new CClass<T>().P3 = t2; t2 = null; // 1 new COpen<T>().P1 = t2; // 2 new CClass<T>().P2 = t2; // 3 new CClass<T>().P3 = t2; // 4, [DisallowNull] honored on TClass? } static void M3<T>(T? t3) where T : class { new COpen<T>().P1 = t3; // 5 new CClass<T>().P2 = t3; // 6 new CClass<T>().P3 = t3; // 7, [DisallowNull] honored on TClass? if (t3 == null) return; new COpen<T>().P1 = t3; new CClass<T>().P2 = t3; new CClass<T>().P3 = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>().P1 = t4; new CStruct<T>().P4 = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>().P1 = t5; // 8 new CStruct<T>().P5 = t5; // 9 if (t5 == null) return; new COpen<T?>().P1 = t5; new CStruct<T>().P5 = t5; } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics( // (6,29): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T>().P1 = t1; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(6, 29), // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 14), // (14,29): warning CS8601: Possible null reference assignment. // new COpen<T>().P1 = t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(14, 29), // (15,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P2 = t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(15, 30), // (16,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P3 = t2; // 4, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(16, 30), // (20,29): warning CS8601: Possible null reference assignment. // new COpen<T>().P1 = t3; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(20, 29), // (21,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P2 = t3; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(21, 30), // (22,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P3 = t3; // 7, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(22, 30), // (35,30): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T?>().P1 = t5; // 8 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(35, 30), // (36,31): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new CStruct<T>().P5 = t5; // 9 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(36, 31)); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics( // (6,29): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T>().P1 = t1; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(6, 29), // (9,53): warning CS8625: Cannot convert null literal to non-nullable reference type. // [DisallowNull]public TClass? P3 { get; set; } = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 53), // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 14), // (14,29): warning CS8601: Possible null reference assignment. // new COpen<T>().P1 = t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(14, 29), // (15,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P2 = t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(15, 30), // (16,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P3 = t2; // 4, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(16, 30), // (20,29): warning CS8601: Possible null reference assignment. // new COpen<T>().P1 = t3; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(20, 29), // (21,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P2 = t3; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(21, 30), // (22,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P3 = t3; // 7, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(22, 30), // (35,30): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T?>().P1 = t5; // 8 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(35, 30), // (36,31): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new CStruct<T>().P5 = t5; // 9 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(36, 31)); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var copenAttributes = copen.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(copenAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableContextAttribute(1)", "System.Runtime.CompilerServices.NullableAttribute(0)" }, copenAttributes); } var property = copen.GetMembers().OfType<PropertySymbol>().Single(); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" }, propertyAttributes); } else { AssertEx.Empty(propertyAttributes); } var setter = property.SetMethod; var setterAttributes = setter.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(setterAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.CompilerGeneratedAttribute" }, setterAttributes); } var setterValueAttributes = setter.Parameters.Last().GetAttributes().Select(a => a.ToString()); Assert.Equal(FlowAnalysisAnnotations.DisallowNull, setter.Parameters.Last().FlowAnalysisAnnotations); if (isSource) { AssertEx.Empty(setterValueAttributes); } else { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" }, setterValueAttributes); } } } [Fact] [WorkItem(39926, "https://github.com/dotnet/roslyn/issues/39926")] public void DisallowNull_Property_NullInitializer() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull]public string? P1 { get; set; } = null; } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,53): warning CS8625: Cannot convert null literal to non-nullable reference type. // [DisallowNull]public string? P1 { get; set; } = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 53)); } [Fact] public void DisallowNull_Property_InDeconstructionAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull]public int? P1 { get; set; } = null; // 0 void M() { (P1, _) = (null, 1); // 1 P1.Value.ToString(); // 2 (_, (P1, _)) = (1, (null, 2)); // 3 (_, P1) = this; // 4 P1.Value.ToString(); // 5 ((_, P1), _) = (this, 2); // 6 } void Deconstruct(out int? x, out int? y) => throw null!; } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,50): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // [DisallowNull]public int? P1 { get; set; } = null; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "null").WithLocation(4, 50), // (7,19): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // (P1, _) = (null, 1); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(null, 1)").WithLocation(7, 19), // (8,9): warning CS8629: Nullable value type may be null. // P1.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "P1").WithLocation(8, 9), // (10,28): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // (_, (P1, _)) = (1, (null, 2)); // 3 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "(null, 2)").WithLocation(10, 28), // (12,13): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // (_, P1) = this; // 4 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "P1").WithLocation(12, 13), // (13,9): warning CS8629: Nullable value type may be null. // P1.Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "P1").WithLocation(13, 9), // (15,14): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // ((_, P1), _) = (this, 2); // 6 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "P1").WithLocation(15, 14) ); } [Fact] public void DisallowNull_Field() { // Warn on misused nullability attributes (f2, f3, f4)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [DisallowNull]public TOpen f1 = default!; } public class CClass<TClass> where TClass : class { [DisallowNull]public TClass f2 = null!; [DisallowNull]public TClass? f3 = null!; } public class CStruct<TStruct> where TStruct : struct { [DisallowNull]public TStruct f4; [DisallowNull]public TStruct? f5; } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class C { static void M1<T>(T t1) { new COpen<T>().f1 = t1; // 0 } static void M2<T>(T t2) where T : class { new COpen<T>().f1 = t2; new CClass<T>().f2 = t2; new CClass<T>().f3 = t2; t2 = null; // 1 new COpen<T>().f1 = t2; // 2 new CClass<T>().f2 = t2; // 3 new CClass<T>().f3 = t2; // 4 } static void M3<T>(T? t3) where T : class { new COpen<T>().f1 = t3; // 5 new CClass<T>().f2 = t3; // 6 new CClass<T>().f3 = t3; // 7 if (t3 == null) return; new COpen<T>().f1 = t3; new CClass<T>().f2 = t3; new CClass<T>().f3 = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>().f1 = t4; new CStruct<T>().f4 = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>().f1 = t5; // 8 new CStruct<T>().f5 = t5; // 9 if (t5 == null) return; new COpen<T?>().f1 = t5; new CStruct<T>().f5 = t5; } static void M6<T>([System.Diagnostics.CodeAnalysis.MaybeNull]T t6) where T : class { new CClass<T>().f2 = t6; } static void M7<T>([System.Diagnostics.CodeAnalysis.NotNull]T? t7) where T : class { new CClass<T>().f2 = t7; // 10 } // 11 static void M8<T>([System.Diagnostics.CodeAnalysis.AllowNull]T t8) where T : class { new CClass<T>().f2 = t8; // 12 } }"; var expected = new[] { // (6,29): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T>().f1 = t1; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(6, 29), // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 14), // (14,29): warning CS8601: Possible null reference assignment. // new COpen<T>().f1 = t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(14, 29), // (15,30): warning CS8601: Possible null reference assignment. // new CClass<T>().f2 = t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(15, 30), // (16,30): warning CS8601: Possible null reference assignment. // new CClass<T>().f3 = t2; // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(16, 30), // (20,29): warning CS8601: Possible null reference assignment. // new COpen<T>().f1 = t3; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(20, 29), // (21,30): warning CS8601: Possible null reference assignment. // new CClass<T>().f2 = t3; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(21, 30), // (22,30): warning CS8601: Possible null reference assignment. // new CClass<T>().f3 = t3; // 7 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(22, 30), // (35,30): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T?>().f1 = t5; // 8 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(35, 30), // (36,31): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new CStruct<T>().f5 = t5; // 9 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(36, 31), // (47,30): warning CS8601: Possible null reference assignment. // new CClass<T>().f2 = t7; // 10 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t7").WithLocation(47, 30), // (48,5): warning CS8777: Parameter 't7' must have a non-null value when exiting. // } // 11 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("t7").WithLocation(48, 5), // (51,30): warning CS8601: Possible null reference assignment. // new CClass<T>().f2 = t8; // 12 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t8").WithLocation(51, 30) }; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var field = copen.GetMembers().OfType<FieldSymbol>().Single(); var fieldAttributes = field.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" }, fieldAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableAttribute(1)", "System.Diagnostics.CodeAnalysis.DisallowNullAttribute" }, fieldAttributes); } } } [Fact] public void DisallowNull_AndOtherAnnotations_StaticField() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull]public static string? disallowNull = null!; [AllowNull]public static string allowNull = null; [MaybeNull]public static string maybeNull = null!; [NotNull]public static string? notNull = null; } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, AllowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition, lib_cs }); var source = @" class D { static void M() { C.disallowNull = null; // 1 C.allowNull = null; C.maybeNull.ToString(); // 2 C.notNull.ToString(); } }"; var expected = new[] { // (6,26): warning CS8625: Cannot convert null literal to non-nullable reference type. // C.disallowNull = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 26), // (8,9): warning CS8602: Dereference of a possibly null reference. // C.maybeNull.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C.maybeNull").WithLocation(8, 9) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition, AllowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void DisallowNull_Field_NullInitializer() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [DisallowNull]public string? field = null; // 1 void M() { field.ToString(); // 2 } } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,42): warning CS8625: Cannot convert null literal to non-nullable reference type. // [DisallowNull]public string? field = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 42), // (8,9): warning CS8602: Dereference of a possibly null reference. // field.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field").WithLocation(8, 9) ); } [Fact, WorkItem(40975, "https://github.com/dotnet/roslyn/issues/40975")] public void AllowNull_Parameter_NullDefaultValue() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { void M([AllowNull] string p = null) { } } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void Disallow_Property_OnVirtualProperty_OnlyOverridingGetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [DisallowNull] public virtual string? P { get { throw null!; } set { throw null!; } } public virtual string? P2 { get { throw null!; } set { throw null!; } } } public class C : Base { public override string? P { get { throw null!; } } [DisallowNull] public override string? P2 { get { throw null!; } } static void M(C c, Base b) { b.P = null; // 1 c.P = null; // 2 b.P2 = null; c.P2 = null; } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // b.P = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 15), // (16,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.P = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 15) ); } [Fact] public void Disallow_Indexer_OnVirtualIndexer_OnlyOverridingSetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [DisallowNull] public virtual string? this[int i] { get { throw null!; } set { throw null!; } } public virtual string? this[byte i] { get { throw null!; } set { throw null!; } } } public class C : Base { public override string? this[int it] { set { throw null!; } } [DisallowNull] public override string? this[byte i] { set { throw null!; } } // 0 static void M(C c, Base b) { b[(int)0] = null; // 1 c[(int)0] = null; b[(byte)0] = null; c[(byte)0] = null; // 2 } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,59): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // [DisallowNull] public override string? this[byte i] { set { throw null!; } } // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(11, 59), // (15,21): warning CS8625: Cannot convert null literal to non-nullable reference type. // b[(int)0] = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 21), // (19,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // c[(byte)0] = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 22) ); } [Fact] public void DisallowNull_Property_CompoundAssignment() { var source = @" using System.Diagnostics.CodeAnalysis; class C { [DisallowNull] C? Property { get; set; } = null!; public static C? operator+(C? one, C other) => throw null!; void M(C c) { Property += c; // 1 } } struct S { [DisallowNull] S? Property { get { throw null!; } set { throw null!; } } public static S? operator+(S? one, S other) => throw null!; void M(S s) { Property += s; // 2 } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,9): warning CS8601: Possible null reference assignment. // Property += c; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "Property += c").WithLocation(10, 9), // (20,9): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // Property += s; // 2 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "Property += s").WithLocation(20, 9) ); } [Fact] public void DisallowNull_Operator_CompoundAssignment() { var source = @" using System.Diagnostics.CodeAnalysis; class C { C? Property { get; set; } = null!; public static C? operator+([DisallowNull] C? one, C other) => throw null!; void M(C c) { Property += c; // 1 } } struct S { S? Property { get { throw null!; } set { throw null!; } } public static S? operator+([DisallowNull] S? one, S other) => throw null!; void M(S s) { Property += s; // 2 } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,9): warning CS8604: Possible null reference argument for parameter 'one' in 'C? C.operator +(C? one, C other)'. // Property += c; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "Property").WithArguments("one", "C? C.operator +(C? one, C other)").WithLocation(10, 9), // (20,9): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // Property += s; // 2 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "Property").WithLocation(20, 9) ); } [Fact] public void DisallowNull_Property_OnVirtualProperty() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [DisallowNull] public virtual string? P { get; set; } = null!; public virtual string? P2 { get; set; } = null!; } public class C : Base { public override string? P { get; set; } = null!; [DisallowNull] public override string? P2 { get; set; } = null!; // 0 static void M(C c, Base b) { b.P = null; // 1 c.P = null; b.P2 = null; c.P2 = null; // 2 } }"; var comp = CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,54): warning CS8765: Type of parameter 'value' doesn't match overridden member because of nullability attributes. // [DisallowNull] public override string? P2 { get; set; } = null!; // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "set").WithArguments("value").WithLocation(11, 54), // (15,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // b.P = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 15), // (19,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.P2 = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 16) ); } [Fact] public void DisallowNull_Property_Cycle() { var source = @" namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.Property, AllowMultiple = true)] public sealed class DisallowNullAttribute : Attribute { [DisallowNull, DisallowNull(1)] int Property { get; set; } public DisallowNullAttribute() { } public DisallowNullAttribute([DisallowNull] int i) { } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void DisallowNull_Property_ExplicitSetter() { // Warn on misused nullability attributes (P2, P3, P4)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [DisallowNull]public TOpen P1 { get { throw null!; } set { throw null!; } } } public class CClass<TClass> where TClass : class { [DisallowNull]public TClass P2 { get { throw null!; } set { throw null!; } } [DisallowNull]public TClass? P3 { get { throw null!; } set { throw null!; } } } public class CStruct<TStruct> where TStruct : struct { [DisallowNull]public TStruct P4 { get { throw null!; } set { throw null!; } } [DisallowNull]public TStruct? P5 { get { throw null!; } set { throw null!; } } } class C { static void M1<T>(T t1) { new COpen<T>().P1 = t1; // 0 } static void M2<T>(T t2) where T : class { new COpen<T>().P1 = t2; new CClass<T>().P2 = t2; new CClass<T>().P3 = t2; t2 = null; // 1 new COpen<T>().P1 = t2; // 2 new CClass<T>().P2 = t2; // 3 new CClass<T>().P3 = t2; // 4, [DisallowNull] honored on TClass? } static void M3<T>(T? t3) where T : class { new COpen<T>().P1 = t3; // 5 new CClass<T>().P2 = t3; // 6 new CClass<T>().P3 = t3; // 7, [DisallowNull] honored on TClass? if (t3 == null) return; new COpen<T>().P1 = t3; new CClass<T>().P2 = t3; new CClass<T>().P3 = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>().P1 = t4; new CStruct<T>().P4 = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>().P1 = t5; // 8 new CStruct<T>().P5 = t5; // 9 if (t5 == null) return; new COpen<T?>().P1 = t5; new CStruct<T>().P5 = t5; } }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (20,29): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T>().P1 = t1; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(20, 29), // (27,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(27, 14), // (28,29): warning CS8601: Possible null reference assignment. // new COpen<T>().P1 = t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(28, 29), // (29,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P2 = t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(29, 30), // (30,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P3 = t2; // 4, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(30, 30), // (34,29): warning CS8601: Possible null reference assignment. // new COpen<T>().P1 = t3; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(34, 29), // (35,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P2 = t3; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(35, 30), // (36,30): warning CS8601: Possible null reference assignment. // new CClass<T>().P3 = t3; // 7, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(36, 30), // (49,30): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // new COpen<T?>().P1 = t5; // 8 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(49, 30), // (50,31): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // new CStruct<T>().P5 = t5; // 9 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(50, 31) ); } [Fact] public void DisallowNull_Property_OnSetter() { var source = @"using System.Diagnostics.CodeAnalysis; public class CClass<TClass> where TClass : class { public TClass P2 { get; [DisallowNull] set; } = null!; public TClass? P3 { get; [DisallowNull] set; } = null; }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,30): error CS0592: Attribute 'DisallowNull' is not valid on this declaration type. It is only valid on 'property, indexer, field, parameter' declarations. // public TClass P2 { get; [DisallowNull] set; } = null!; Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "DisallowNull").WithArguments("DisallowNull", "property, indexer, field, parameter").WithLocation(4, 30), // (5,31): error CS0592: Attribute 'DisallowNull' is not valid on this declaration type. It is only valid on 'property, indexer, field, parameter' declarations. // public TClass? P3 { get; [DisallowNull] set; } = null; Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "DisallowNull").WithArguments("DisallowNull", "property, indexer, field, parameter").WithLocation(5, 31) ); } [Fact] public void DisallowNull_Property_OnGetter() { var source = @"using System.Diagnostics.CodeAnalysis; public class CClass<TClass> where TClass : class { public TClass P2 { [DisallowNull] get; set; } = null!; public TClass? P3 { [DisallowNull] get; set; } = null; }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,25): error CS0592: Attribute 'DisallowNull' is not valid on this declaration type. It is only valid on 'property, indexer, field, parameter' declarations. // public TClass P2 { [DisallowNull] get; set; } = null!; Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "DisallowNull").WithArguments("DisallowNull", "property, indexer, field, parameter").WithLocation(4, 25), // (5,26): error CS0592: Attribute 'DisallowNull' is not valid on this declaration type. It is only valid on 'property, indexer, field, parameter' declarations. // public TClass? P3 { [DisallowNull] get; set; } = null; Diagnostic(ErrorCode.ERR_AttributeOnBadSymbolType, "DisallowNull").WithArguments("DisallowNull", "property, indexer, field, parameter").WithLocation(5, 26) ); } [Fact] public void DisallowNull_Property_NoGetter() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [DisallowNull]public TOpen P1 { set { throw null!; } } [DisallowNull]public TOpen P2 => default!; }"; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void DisallowNull_Indexer() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [DisallowNull]public TOpen this[int i] { set => throw null!; } } public class CClass<TClass> where TClass : class? { [DisallowNull]public TClass this[int i] { set => throw null!; } } public class CClass2<TClass> where TClass : class { [DisallowNull]public TClass? this[int i] { set => throw null!; } } public class CStruct<TStruct> where TStruct : struct { [DisallowNull]public TStruct this[int i] { set => throw null!; } } public class CStruct2<TStruct> where TStruct : struct { [DisallowNull]public TStruct? this[int i] { set => throw null!; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class C { static void M1<T>(T t1) { new COpen<T>()[0] = t1; // 0 } static void M2<T>(T t2) where T : class { new COpen<T>()[0] = t2; new CClass<T>()[0] = t2; new CClass2<T>()[0] = t2; t2 = null; // 1 new COpen<T>()[0] = t2; // 2 new CClass<T>()[0] = t2; // 3 new CClass2<T>()[0] = t2; // 4, [DisallowNull] honored on TClass? } static void M3<T>(T? t3) where T : class { new COpen<T>()[0] = t3; // 5 new CClass<T>()[0] = t3; // 6 new CClass2<T>()[0] = t3; // 7, [DisallowNull] honored on TClass? if (t3 == null) return; new COpen<T>()[0] = t3; new CClass<T>()[0] = t3; new CClass2<T>()[0] = t3; } static void M4<T>(T t4) where T : struct { new COpen<T>()[0] = t4; new CStruct<T>()[0] = t4; } static void M5<T>(T? t5) where T : struct { new COpen<T?>()[0] = t5; // 8 new CStruct2<T>()[0] = t5; // 9 if (t5 == null) return; new COpen<T?>()[0] = t5; new CStruct2<T>()[0] = t5; } }"; var expected = new[] { // (6,29): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T>()[0] = t1; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t1").WithLocation(6, 29), // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 14), // (14,29): warning CS8601: Possible null reference assignment. // new COpen<T>()[0] = t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(14, 29), // (15,30): warning CS8601: Possible null reference assignment. // new CClass<T>()[0] = t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(15, 30), // (16,31): warning CS8601: Possible null reference assignment. // new CClass2<T>()[0] = t2; // 4, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(16, 31), // (20,29): warning CS8601: Possible null reference assignment. // new COpen<T>()[0] = t3; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(20, 29), // (21,30): warning CS8601: Possible null reference assignment. // new CClass<T>()[0] = t3; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(21, 30), // (22,31): warning CS8601: Possible null reference assignment. // new CClass2<T>()[0] = t3; // 7, [DisallowNull] honored on TClass? Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t3").WithLocation(22, 31), // (35,30): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new COpen<T?>()[0] = t5; // 8 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(35, 30), // (36,32): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // new CStruct2<T>()[0] = t5; // 9 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t5").WithLocation(36, 32) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void DisallowNull_Indexer_OtherParameters_String() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public string? this[[DisallowNull] string? s] { set => throw null!; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new C()[s] = s; // 1 new C()[s2] = s; } }"; var expected = new[] { // (6,17): warning CS8604: Possible null reference argument for parameter 's' in 'string? C.this[string? s]'. // new C()[s] = s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s").WithArguments("s", "string? C.this[string? s]").WithLocation(6, 17) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void DisallowNull_Indexer_OtherParameters_NullableInt() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class C { public int? this[[DisallowNull] int? s] { set => throw null!; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(int? i, int i2) { new C()[i] = i; // 1 new C()[i2] = i; } }"; var expected = new[] { // (6,17): warning CS8607: A possible null value may not be assigned to a target marked with the [DisallowNull] attribute // new C()[i] = i; // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "i").WithLocation(6, 17) }; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(expected); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(expected); } [Fact] public void DisallowNull_Indexer_OtherParameters_OverridingGetter() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual string this[[DisallowNull] string? s] { get => throw null!; } } public class C : Base { public override string this[string? s] { get => throw null!; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new C()[s].ToString(); new C()[s2].ToString(); } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(); } [Fact, WorkItem(36630, "https://github.com/dotnet/roslyn/issues/36630")] public void DisallowNull_Indexer_OtherParameters_OverridingGetterOnly() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual string this[[DisallowNull] string? s] { get => throw null!; set => throw null!; } } public class C : Base { public override string this[string? s] { set => throw null!; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new C()[s].ToString(); // 1 new C()[s2].ToString(); } }"; // Should report a warning for explicit parameter on getter https://github.com/dotnet/roslyn/issues/36630 var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(); } [Fact] public void DisallowNull_Indexer_OtherParameters_OverridingSetterOnly() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual string this[[DisallowNull] string? s] { get => throw null!; set => throw null!; } } public class C : Base { public override string this[string? s] { get => throw null!; } } "; var lib = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, lib_cs }); var source = @" class D { static void M1(string? s, string s2) { new C()[s].ToString(); new C()[s2].ToString(); } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, DisallowNullAttributeDefinition }); comp2.VerifyDiagnostics(); } [Fact] public void MaybeNullWhenFalse_WithNotNullWhenTrue() { var source = @"using System.Diagnostics.CodeAnalysis; internal class C<T> where T : class? { public bool TryGetTarget([MaybeNullWhen(false), NotNullWhen(true)] out T target) => throw null!; public string Method(C<string> wr) { if (!wr.TryGetTarget(out string? s)) { s = """"; } return s; } }"; var comp = CreateNullableCompilation(new[] { MaybeNullWhenAttributeDefinition, NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNull_WithNotNull() { var source = @"using System.Diagnostics.CodeAnalysis; internal class C<T> where T : class? { public bool F([MaybeNull, NotNull] out T target) => throw null!; [return: MaybeNull, NotNull] public T F2() => throw null!; public string Method(C<string> wr) { if (!wr.F(out string? s)) { s = """"; } return s; // 1 } public string Method2(C<string> wr, bool b) { var s = wr.F2(); if (b) return s; // 2 s = null; throw null!; } }"; // MaybeNull wins over NotNull var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,16): warning CS8603: Possible null reference return. // return s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(13, 16), // (19,20): warning CS8603: Possible null reference return. // return s; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(19, 20) ); } [Fact, WorkItem(36410, "https://github.com/dotnet/roslyn/issues/36410")] public void MaybeNull_WithNotNullWhenTrue() { var source = @"using System.Diagnostics.CodeAnalysis; internal class C<T> where T : class? { public bool TryGetTarget([MaybeNull, NotNullWhen(true)] out T target) => throw null!; public string Method(C<string> wr) { if (wr.TryGetTarget(out string? s)) { return s; } return s; // 1 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,16): warning CS8603: Possible null reference return. // return s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(11, 16) ); } [Fact, WorkItem(36410, "https://github.com/dotnet/roslyn/issues/36410")] public void MaybeNull_WithNotNullWhenFalse() { var source = @"using System.Diagnostics.CodeAnalysis; internal class C<T> where T : class? { public bool TryGetTarget([MaybeNull, NotNullWhen(false)] out T target) => throw null!; public string Method(C<string> wr) { if (wr.TryGetTarget(out string? s)) { return s; // 1 } return s; } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, NotNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (9,20): warning CS8603: Possible null reference return. // return s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(9, 20) ); } [Fact] public void MaybeNull_ReturnValue_01() { // Warn on misused nullability attributes (F2, F3, F4)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull] static T F1<T>(T t) => t; [return: MaybeNull] static T F2<T>(T t) where T : class => t; [return: MaybeNull] static T? F3<T>(T t) where T : class => t; [return: MaybeNull] static T F4<T>(T t) where T : struct => t; [return: MaybeNull] static T? F5<T>(T? t) where T : struct => t; static void M1<T>(T t1) { F1(t1).ToString(); // 0, 1 _ = F1(t1)!; } static void M2<T>(T t2) where T : class { F1(t2).ToString(); // 2 F2(t2).ToString(); // 3 F3(t2).ToString(); // 4 t2 = null; // 5 F1(t2).ToString(); // 6 F2(t2).ToString(); // 7 F3(t2).ToString(); // 8 } static void M3<T>(T? t3) where T : class { F1(t3).ToString(); // 9 F2(t3).ToString(); // 10 F3(t3).ToString(); // 11 if (t3 == null) return; F1(t3).ToString(); // 12 F2(t3).ToString(); // 13 F3(t3).ToString(); // 14 } static void M4<T>(T t4) where T : struct { F1(t4).ToString(); F4(t4).ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1(t5).Value; // 15 _ = F5(t5).Value; // 16 if (t5 == null) return; _ = F1(t5).Value; // 17 _ = F5(t5).Value; // 18 } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(t1).ToString(); // 0, 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(t1)").WithLocation(11, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F1(t2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(t2)").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F2(t2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(t2)").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F3(t2).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(t2)").WithLocation(18, 9), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 14), // (20,9): warning CS8602: Dereference of a possibly null reference. // F1(t2).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(t2)").WithLocation(20, 9), // (21,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t2).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(21, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // F2(t2).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(t2)").WithLocation(21, 9), // (22,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t2).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T)", "T", "T?").WithLocation(22, 9), // (22,9): warning CS8602: Dereference of a possibly null reference. // F3(t2).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(t2)").WithLocation(22, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // F1(t3).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(t3)").WithLocation(26, 9), // (27,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t3).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(27, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // F2(t3).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(t3)").WithLocation(27, 9), // (28,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t3).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T)", "T", "T?").WithLocation(28, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // F3(t3).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(t3)").WithLocation(28, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // F1(t3).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(t3)").WithLocation(30, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // F2(t3).ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(t3)").WithLocation(31, 9), // (32,9): warning CS8602: Dereference of a possibly null reference. // F3(t3).ToString(); // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(t3)").WithLocation(32, 9), // (41,13): warning CS8629: Nullable value type may be null. // _ = F1(t5).Value; // 15 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(t5)").WithLocation(41, 13), // (42,13): warning CS8629: Nullable value type may be null. // _ = F5(t5).Value; // 16 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F5(t5)").WithLocation(42, 13), // (44,13): warning CS8629: Nullable value type may be null. // _ = F1(t5).Value; // 17 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(t5)").WithLocation(44, 13), // (45,13): warning CS8629: Nullable value type may be null. // _ = F5(t5).Value; // 18 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F5(t5)").WithLocation(45, 13)); } [Fact] public void MaybeNull_ReturnValue_02() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull] static T F1<T>(T t) => t; [return: MaybeNull] static T F2<T>(T t) where T : class => t; [return: MaybeNull] static T? F3<T>(T t) where T : class => t; [return: MaybeNull] static T F4<T>(T t) where T : struct => t; [return: MaybeNull] static T? F5<T>(T? t) where T : struct => t; static void M1<T>(T t1) { F1<T>(t1).ToString(); // 1 } static void M2<T>(bool b, T t2) where T : class { F1<T>(t2).ToString(); // 2 F2<T>(t2).ToString(); // 3 F3<T>(t2).ToString(); // 4 t2 = null; // 5 F1<T>(b ? t2 : default).ToString(); // 6 F2<T>(b ? t2 : default).ToString(); // 7 F3<T>(b ? t2 : default).ToString(); // 8 } static void M3<T>(bool b, T? t3) where T : class { F1<T>(b ? t3 : default).ToString(); // 9 F2<T>(b ? t3 : default).ToString(); // 10 F3<T>(b ? t3 : default).ToString(); // 11 if (t3 == null) return; F1<T>(t3).ToString(); // 12 F2<T>(t3).ToString(); // 13 F3<T>(t3).ToString(); // 14 } static void M4<T>(T t4) where T : struct { F1<T>(t4).ToString(); F4<T>(t4).ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1<T?>(t5).Value; // 15 _ = F5<T>(t5).Value; // 16 if (t5 == null) return; _ = F1<T?>(t5).Value; // 17 _ = F5<T>(t5).Value; // 18 } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(t1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(t1)").WithLocation(11, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(t2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(t2)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(t2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(t2)").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(t2).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(t2)").WithLocation(17, 9), // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 14), // (19,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(b ? t2 : default).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(b ? t2 : default)").WithLocation(19, 9), // (19,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F1<T>(T t)'. // F1<T>(b ? t2 : default).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "T Program.F1<T>(T t)").WithLocation(19, 15), // (20,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(b ? t2 : default).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(b ? t2 : default)").WithLocation(20, 9), // (20,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F2<T>(T t)'. // F2<T>(b ? t2 : default).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "T Program.F2<T>(T t)").WithLocation(20, 15), // (21,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(b ? t2 : default).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(b ? t2 : default)").WithLocation(21, 9), // (21,15): warning CS8604: Possible null reference argument for parameter 't' in 'T? Program.F3<T>(T t)'. // F3<T>(b ? t2 : default).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "T? Program.F3<T>(T t)").WithLocation(21, 15), // (25,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(b ? t3 : default).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(b ? t3 : default)").WithLocation(25, 9), // (25,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F1<T>(T t)'. // F1<T>(b ? t3 : default).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "T Program.F1<T>(T t)").WithLocation(25, 15), // (26,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(b ? t3 : default).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(b ? t3 : default)").WithLocation(26, 9), // (26,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F2<T>(T t)'. // F2<T>(b ? t3 : default).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "T Program.F2<T>(T t)").WithLocation(26, 15), // (27,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(b ? t3 : default).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(b ? t3 : default)").WithLocation(27, 9), // (27,15): warning CS8604: Possible null reference argument for parameter 't' in 'T? Program.F3<T>(T t)'. // F3<T>(b ? t3 : default).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "T? Program.F3<T>(T t)").WithLocation(27, 15), // (29,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(t3).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(t3)").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(t3).ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(t3)").WithLocation(30, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(t3).ToString(); // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(t3)").WithLocation(31, 9), // (40,13): warning CS8629: Nullable value type may be null. // _ = F1<T?>(t5).Value; // 15 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1<T?>(t5)").WithLocation(40, 13), // (41,13): warning CS8629: Nullable value type may be null. // _ = F5<T>(t5).Value; // 16 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F5<T>(t5)").WithLocation(41, 13), // (43,13): warning CS8629: Nullable value type may be null. // _ = F1<T?>(t5).Value; // 17 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1<T?>(t5)").WithLocation(43, 13), // (44,13): warning CS8629: Nullable value type may be null. // _ = F5<T>(t5).Value; // 18 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F5<T>(t5)").WithLocation(44, 13)); } [Fact] public void MaybeNull_ReturnValue_02_WithNotNull() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull, NotNull] static T F1<T>(T t) => t; // [return: MaybeNull, NotNull] static T F2<T>(T t) where T : class => t; [return: MaybeNull, NotNull] static T? F3<T>(T t) where T : class => t; [return: MaybeNull, NotNull] static T F4<T>(T t) where T : struct => t; [return: MaybeNull, NotNull] static T? F5<T>(T? t) where T : struct => t; // static void M1<T>(T t1) { F1<T>(t1).ToString(); // 0, 1 } static void M2<T>(bool b, T t2) where T : class { F1<T>(t2).ToString(); // 2 F2<T>(t2).ToString(); // 3 F3<T>(t2).ToString(); // 4 t2 = null; // 5 F1<T>(b ? t2 : default).ToString(); // 6 F2<T>(b ? t2 : default).ToString(); // 7 F3<T>(b ? t2 : default).ToString(); // 8 } static void M3<T>(bool b, T? t3) where T : class { F1<T>(b ? t3 : default).ToString(); // 9 F2<T>(b ? t3 : default).ToString(); // 10 F3<T>(b ? t3 : default).ToString(); // 11 if (t3 == null) return; F1<T>(t3).ToString(); // 12 F2<T>(t3).ToString(); // 13 F3<T>(t3).ToString(); // 14 } static void M4<T>(T t4) where T : struct { F1<T>(t4).ToString(); F4<T>(t4).ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1<T?>(t5).Value; // 15 _ = F5<T>(t5).Value; // 16 if (t5 == null) return; _ = F1<T?>(t5).Value; // 17 _ = F5<T>(t5).Value; // 18 } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,57): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: MaybeNull, NotNull] static T F1<T>(T t) => t; // Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(4, 57), // (8,76): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: MaybeNull, NotNull] static T? F5<T>(T? t) where T : struct => t; // Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(8, 76), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(t1).ToString(); // 0, 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(t1)").WithLocation(11, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(t2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(t2)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(t2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(t2)").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(t2).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(t2)").WithLocation(17, 9), // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 14), // (19,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(b ? t2 : default).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(b ? t2 : default)").WithLocation(19, 9), // (19,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F1<T>(T t)'. // F1<T>(b ? t2 : default).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "T Program.F1<T>(T t)").WithLocation(19, 15), // (20,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(b ? t2 : default).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(b ? t2 : default)").WithLocation(20, 9), // (20,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F2<T>(T t)'. // F2<T>(b ? t2 : default).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "T Program.F2<T>(T t)").WithLocation(20, 15), // (21,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(b ? t2 : default).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(b ? t2 : default)").WithLocation(21, 9), // (21,15): warning CS8604: Possible null reference argument for parameter 't' in 'T? Program.F3<T>(T t)'. // F3<T>(b ? t2 : default).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "T? Program.F3<T>(T t)").WithLocation(21, 15), // (25,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(b ? t3 : default).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(b ? t3 : default)").WithLocation(25, 9), // (25,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F1<T>(T t)'. // F1<T>(b ? t3 : default).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "T Program.F1<T>(T t)").WithLocation(25, 15), // (26,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(b ? t3 : default).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(b ? t3 : default)").WithLocation(26, 9), // (26,15): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F2<T>(T t)'. // F2<T>(b ? t3 : default).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "T Program.F2<T>(T t)").WithLocation(26, 15), // (27,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(b ? t3 : default).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(b ? t3 : default)").WithLocation(27, 9), // (27,15): warning CS8604: Possible null reference argument for parameter 't' in 'T? Program.F3<T>(T t)'. // F3<T>(b ? t3 : default).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "T? Program.F3<T>(T t)").WithLocation(27, 15), // (29,9): warning CS8602: Dereference of a possibly null reference. // F1<T>(t3).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1<T>(t3)").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // F2<T>(t3).ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2<T>(t3)").WithLocation(30, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // F3<T>(t3).ToString(); // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3<T>(t3)").WithLocation(31, 9), // (40,13): warning CS8629: Nullable value type may be null. // _ = F1<T?>(t5).Value; // 15 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1<T?>(t5)").WithLocation(40, 13), // (41,13): warning CS8629: Nullable value type may be null. // _ = F5<T>(t5).Value; // 16 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F5<T>(t5)").WithLocation(41, 13), // (43,13): warning CS8629: Nullable value type may be null. // _ = F1<T?>(t5).Value; // 17 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1<T?>(t5)").WithLocation(43, 13), // (44,13): warning CS8629: Nullable value type may be null. // _ = F5<T>(t5).Value; // 18 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F5<T>(t5)").WithLocation(44, 13)); } [Fact] public void MaybeNull_ReturnValue_03() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull] static string F1() => string.Empty; [return: MaybeNull] static string? F2() => string.Empty; static void M() { F1().ToString(); // 1 F2().ToString(); // 2 } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F1().ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1()").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F2().ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2()").WithLocation(9, 9)); } [Fact] public void MaybeNull_ReturnValue_04() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull] static int F1() => 1; [return: MaybeNull] static int? F2() => 2; static void M() { F1().ToString(); _ = F2().Value; // 1 } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8629: Nullable value type may be null. // _ = F2().Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2()").WithLocation(9, 13)); } [Fact] public void MaybeNull_ReturnValue_05() { // Warn on misused nullability attributes (F2)? https://github.com/dotnet/roslyn/issues/36073 var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static T F1<T>(T t) where T : class => t; [return: MaybeNull] public static T F2<T>(T t) where T : class => t; }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x).ToString(); // 2, 3 F1(y).ToString(); F2(x).ToString(); // 4, 5 F2(y).ToString(); // 6 } }"; comp = CreateCompilation(source, references: new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(x).ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T)", "T", "object?").WithLocation(7, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (9,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x).ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T)", "T", "object?").WithLocation(9, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(10, 9) ); } [Fact] public void MaybeNull_ReturnValue_05_Unconstrained() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static T F1<T>(T t) => t; [return: MaybeNull] public static T F2<T>(T t) => t; }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x).ToString(); // 2 F1(y).ToString(); F2(x).ToString(); // 3 F2(y).ToString(); // 4 } }"; comp = CreateCompilation(source, references: new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(10, 9) ); } [Fact] public void MaybeNull_ReturnValue_06() { var source = @"using System.Diagnostics.CodeAnalysis; class C<T> { [return: MaybeNull] internal static T F() => throw null!; } class Program { static void M<T, U, V>() where U : class where V : struct { C<T>.F().ToString(); // 0, 1 C<U>.F().ToString(); // 2 C<U?>.F().ToString(); // 3 C<V>.F().ToString(); _ = C<V?>.F().Value; // 4 C<string>.F().ToString(); // 5 C<string?>.F().ToString(); // 6 C<int>.F().ToString(); _ = C<int?>.F().Value; // 7 } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // C<T>.F().ToString(); // 0, 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T>.F()").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // C<U>.F().ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<U>.F()").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // C<U?>.F().ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<U?>.F()").WithLocation(14, 9), // (16,13): warning CS8629: Nullable value type may be null. // _ = C<V?>.F().Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "C<V?>.F()").WithLocation(16, 13), // (17,9): warning CS8602: Dereference of a possibly null reference. // C<string>.F().ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<string>.F()").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // C<string?>.F().ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<string?>.F()").WithLocation(18, 9), // (20,13): warning CS8629: Nullable value type may be null. // _ = C<int?>.F().Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "C<int?>.F()").WithLocation(20, 13)); } [Fact] public void MaybeNull_InOrByValParameter() { var c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; public class C { public void Main(string s1, string s2) { _ = M(s1) ? s1.ToString() // 1 : s1.ToString(); // 2 _ = M(s2) ? s2.ToString() // 3 : s2.ToString(); // 4 } public static bool M([MaybeNull] in string s) => throw null!; public static bool M2([MaybeNull] string s) => throw null!; } ", MaybeNullAttributeDefinition }, options: WithNullableEnable()); // Warn on misused nullability attributes (warn on parameters of M and M2)? https://github.com/dotnet/roslyn/issues/36073 c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // ? s1.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(8, 15), // (9,15): warning CS8602: Dereference of a possibly null reference. // : s1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // ? s2.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 15), // (13,15): warning CS8602: Dereference of a possibly null reference. // : s2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(13, 15) ); } [Fact] public void MaybeNull_OutParameter_01() { // Warn on misused nullability attributes (F2, F3, F4 and probably F5)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>(T t, [MaybeNull]out T t2) { t2 = t; } static void F2<T>(T t, [MaybeNull]out T t2) where T : class { t2 = t; } static void F3<T>(T t, [MaybeNull]out T? t2) where T : class { t2 = t; } static void F4<T>(T t, [MaybeNull]out T t2) where T : struct { t2 = t; } static void F5<T>(T? t, [MaybeNull]out T? t2) where T : struct { t2 = t; } static void M1<T>(T t1) { F1(t1, out var s2); // 0 s2.ToString(); // 1 } static void M2<T>(T t2) where T : class { F1(t2, out var s3); s3.ToString(); // 2 F2(t2, out var s4); s4.ToString(); // 3 F3(t2, out var s5); s5.ToString(); // 4 t2 = null; // 5 F1(t2, out var s6); s6.ToString(); // 6 F2(t2, out var s7); // 7 s7.ToString(); // 8 F3(t2, out var s8); // 9 s8.ToString(); // 10 } static void M3<T>(T? t3) where T : class { F1(t3, out var s9); s9.ToString(); // 11 F2(t3, out var s10); // 12 s10.ToString(); // 13 F3(t3, out var s11); // 14 s11.ToString(); // 15 if (t3 == null) return; F1(t3, out var s12); s12.ToString(); // 16 F2(t3, out var s13); s13.ToString(); // 17 F3(t3, out var s14); s14.ToString(); // 18 } static void M4<T>(T t4) where T : struct { F1(t4, out var s15); s15.ToString(); F4(t4, out var s16); s16.ToString(); } static void M5<T>(T? t5) where T : struct { F1(t5, out var s17); _ = s17.Value; // 19 F5(t5, out var s18); _ = s18.Value; // 20 if (t5 == null) return; F1(t5, out var s19); _ = s19.Value; // 21 F5(t5, out var s20); _ = s20.Value; // 22 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // s3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(17, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(20, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // s5.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(23, 9), // (25,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(25, 14), // (27,9): warning CS8602: Dereference of a possibly null reference. // s6.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(27, 9), // (29,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t2, out var s7); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // s7.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s7").WithLocation(30, 9), // (32,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t2, out var s8); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(32, 9), // (33,9): warning CS8602: Dereference of a possibly null reference. // s8.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s8").WithLocation(33, 9), // (38,9): warning CS8602: Dereference of a possibly null reference. // s9.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s9").WithLocation(38, 9), // (40,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t3, out var s10); // 12 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(40, 9), // (41,9): warning CS8602: Dereference of a possibly null reference. // s10.ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s10").WithLocation(41, 9), // (43,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t3, out var s11); // 14 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(43, 9), // (44,9): warning CS8602: Dereference of a possibly null reference. // s11.ToString(); // 15 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s11").WithLocation(44, 9), // (48,9): warning CS8602: Dereference of a possibly null reference. // s12.ToString(); // 16 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s12").WithLocation(48, 9), // (51,9): warning CS8602: Dereference of a possibly null reference. // s13.ToString(); // 17 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s13").WithLocation(51, 9), // (54,9): warning CS8602: Dereference of a possibly null reference. // s14.ToString(); // 18 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s14").WithLocation(54, 9), // (67,13): warning CS8629: Nullable value type may be null. // _ = s17.Value; // 19 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s17").WithLocation(67, 13), // (70,13): warning CS8629: Nullable value type may be null. // _ = s18.Value; // 20 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s18").WithLocation(70, 13), // (74,13): warning CS8629: Nullable value type may be null. // _ = s19.Value; // 21 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s19").WithLocation(74, 13), // (77,13): warning CS8629: Nullable value type may be null. // _ = s20.Value; // 22 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s20").WithLocation(77, 13) ); } [Fact] public void MaybeNull_OutParameter_02() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>(T t, [MaybeNull]out T t2) => throw null!; static void F2<T>(T t, [MaybeNull]out T t2) where T : class => throw null!; static void F3<T>(T t, [MaybeNull]out T? t2) where T : class => throw null!; static void F4<T>(T t, [MaybeNull]out T t2) where T : struct => throw null!; static void F5<T>(T? t, [MaybeNull]out T? t2) where T : struct => throw null!; static void M1<T>(T t1) { F1<T>(t1, out var s1); // 0 s1.ToString(); // 1 } static void M2<T>(bool b, T t2) where T : class { F1<T>(t2, out var s2); s2.ToString(); // 2 F2<T>(t2, out var s3); s3.ToString(); // 3 F3<T>(t2, out var s4); s4.ToString(); // 4 t2 = null; // 5 F1<T>(b ? t2 : default, out var s5); // 6 s5.ToString(); // 6B F2<T>(b ? t2 : default, out var s6); // 7 s6.ToString(); // 7B F3<T>(b ? t2 : default, out var s7); // 8 s7.ToString(); // 8B } static void M3<T>(bool b, T? t3) where T : class { F1<T>(b ? t3 : default, out var s8); // 9 s8.ToString(); // 9B F2<T>(b ? t3 : default, out var s9); // 10 s9.ToString(); // 10B F3<T>(b ? t3 : default, out var s10); // 11 s10.ToString(); // 11B if (t3 == null) return; F1<T>(t3, out var s11); s11.ToString(); // 12 F2<T>(t3, out var s12); s12.ToString(); // 13 F3<T>(t3, out var s13); s13.ToString(); // 14 } static void M4<T>(T t4) where T : struct { F1<T>(t4, out var s14); s14.ToString(); F4<T>(t4, out var s15); s15.ToString(); } static void M5<T>(T? t5) where T : struct { F1<T?>(t5, out var s16); _ = s16.Value; // 15 F5<T>(t5, out var s17); _ = s17.Value; // 16 if (t5 == null) return; F1<T?>(t5, out var s18); _ = s18.Value; // 17 F5<T>(t5, out var s19); _ = s19.Value; // 18 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(12, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(17, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // s3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(20, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(23, 9), // (25,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(25, 14), // (26,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T>(T t, out T t2)'. // F1<T>(b ? t2 : default, out var s5); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "void Program.F1<T>(T t, out T t2)").WithLocation(26, 15), // (27,9): warning CS8602: Dereference of a possibly null reference. // s5.ToString(); // 6B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(27, 9), // (29,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T>(T t, out T t2)'. // F2<T>(b ? t2 : default, out var s6); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "void Program.F2<T>(T t, out T t2)").WithLocation(29, 15), // (30,9): warning CS8602: Dereference of a possibly null reference. // s6.ToString(); // 7B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(30, 9), // (32,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T t, out T? t2)'. // F3<T>(b ? t2 : default, out var s7); // 8 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t2 : default").WithArguments("t", "void Program.F3<T>(T t, out T? t2)").WithLocation(32, 15), // (33,9): warning CS8602: Dereference of a possibly null reference. // s7.ToString(); // 8B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s7").WithLocation(33, 9), // (37,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F1<T>(T t, out T t2)'. // F1<T>(b ? t3 : default, out var s8); // 9 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "void Program.F1<T>(T t, out T t2)").WithLocation(37, 15), // (38,9): warning CS8602: Dereference of a possibly null reference. // s8.ToString(); // 9B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s8").WithLocation(38, 9), // (40,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F2<T>(T t, out T t2)'. // F2<T>(b ? t3 : default, out var s9); // 10 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "void Program.F2<T>(T t, out T t2)").WithLocation(40, 15), // (41,9): warning CS8602: Dereference of a possibly null reference. // s9.ToString(); // 10B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s9").WithLocation(41, 9), // (43,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F3<T>(T t, out T? t2)'. // F3<T>(b ? t3 : default, out var s10); // 11 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? t3 : default").WithArguments("t", "void Program.F3<T>(T t, out T? t2)").WithLocation(43, 15), // (44,9): warning CS8602: Dereference of a possibly null reference. // s10.ToString(); // 11B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s10").WithLocation(44, 9), // (48,9): warning CS8602: Dereference of a possibly null reference. // s11.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s11").WithLocation(48, 9), // (51,9): warning CS8602: Dereference of a possibly null reference. // s12.ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s12").WithLocation(51, 9), // (54,9): warning CS8602: Dereference of a possibly null reference. // s13.ToString(); // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s13").WithLocation(54, 9), // (67,13): warning CS8629: Nullable value type may be null. // _ = s16.Value; // 15 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s16").WithLocation(67, 13), // (70,13): warning CS8629: Nullable value type may be null. // _ = s17.Value; // 16 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s17").WithLocation(70, 13), // (74,13): warning CS8629: Nullable value type may be null. // _ = s18.Value; // 17 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s18").WithLocation(74, 13), // (77,13): warning CS8629: Nullable value type may be null. // _ = s19.Value; // 18 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s19").WithLocation(77, 13) ); } [Fact] public void MaybeNull_OutParameter_03() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([MaybeNull]out string t) => throw null!; static void F2([MaybeNull]out string? t) => throw null!; static void M() { F1(out var t1); t1.ToString(); // 1 F2(out var t2); t2.ToString(); // 2 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(9, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(12, 9) ); } [Fact] public void MaybeNull_OutParameter_04() { // Warn on misused nullability attributes (F1, F2)? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([MaybeNull]out int i) => throw null!; static void F2([MaybeNull]out int? i) => throw null!; static void M() { F1(out var i1); i1.ToString(); F2(out var i2); _ = i2.Value; // 1 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,13): warning CS8629: Nullable value type may be null. // _ = i2.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i2").WithLocation(12, 13) ); } [Fact] public void MaybeNull_OutParameter_05() { // Warn on misused nullability attributes (F2)? https://github.com/dotnet/roslyn/issues/36073 var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static void F1<T>(T t, out T t2) where T : class => throw null!; public static void F2<T>(T t, [MaybeNull]out T t2) where T : class => throw null!; }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source0 }); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x, out var o1); // 2 o1.ToString(); // 2B F1(y, out var o2); o2.ToString(); F2(x, out var o3); // 3 o3.ToString(); // 3B F2(y, out var o4); o4.ToString(); // 4 } }"; comp = CreateNullableCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T, out T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(x, out var o1); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T, out T)", "T", "object?").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // o1.ToString(); // 2B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o1").WithLocation(8, 9), // (13,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T, out T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x, out var o3); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T, out T)", "T", "object?").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // o3.ToString(); // 3B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o3").WithLocation(14, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // o4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o4").WithLocation(17, 9) ); } [Fact] public void MaybeNull_OutParameter_05_Unconstrained() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static void F2<T>(T t, [MaybeNull]out T t2) => throw null!; }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source0 }); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F2(x, out var o3); o3.ToString(); // 2 F2(y, out var o4); o4.ToString(); // 3 } }"; comp = CreateNullableCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (9,9): warning CS8602: Dereference of a possibly null reference. // o3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o3").WithLocation(9, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // o4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o4").WithLocation(12, 9) ); } [Fact] public void MaybeNull_OutParameter_06() { var source = @"using System.Diagnostics.CodeAnalysis; class C<T> { internal static void F([MaybeNull]out T t) => throw null!; } class Program { static void M<T, U, V>() where U : class where V : struct { C<T>.F(out var o1); // 0 o1.ToString(); // 1 C<U>.F(out var o2); o2.ToString(); // 2 C<U?>.F(out var o3); o3.ToString(); // 3 C<V>.F(out var o4); o4.ToString(); C<V?>.F(out var o5); _ = o5.Value; // 4 C<string>.F(out var o6); o6.ToString(); // 5 C<string?>.F(out var o7); o7.ToString(); // 6 C<int>.F(out var o8); o8.ToString(); C<int?>.F(out var o9); _ = o9.Value; // 7 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // o1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o1").WithLocation(13, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // o2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o2").WithLocation(16, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // o3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o3").WithLocation(19, 9), // (25,13): warning CS8629: Nullable value type may be null. // _ = o5.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "o5").WithLocation(25, 13), // (28,9): warning CS8602: Dereference of a possibly null reference. // o6.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o6").WithLocation(28, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // o7.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o7").WithLocation(31, 9), // (37,13): warning CS8629: Nullable value type may be null. // _ = o9.Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "o9").WithLocation(37, 13) ); } [Fact] public void MaybeNull_RefParameter_01() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>(T t, [MaybeNull]ref T t2) { t2 = t; } static void F2<T>(T t, [MaybeNull]ref T t2) where T : class { t2 = t; } static void F3<T>(T t, [MaybeNull]ref T? t2) where T : class { t2 = t; } static void F4<T>(T t, [MaybeNull]ref T t2) where T : struct { t2 = t; } static void F5<T>(T? t, [MaybeNull]ref T? t2) where T : struct { t2 = t; } static void M1<T>(T t1) { T s2 = default!; F1(t1, ref s2); // 0 s2.ToString(); // 1 } static void M2<T>(T t2) where T : class { T? s3 = default!; F1(t2, ref s3); s3.ToString(); // 2 T s4 = default!; F2(t2, ref s4); // 3 s4.ToString(); // 4 T s4b = default!; F2(t2, ref s4b!); // suppression applies after MaybeNull s4b.ToString(); T? s5 = default!; F3(t2, ref s5); s5.ToString(); // 5 t2 = null; // 6 T? s6 = default!; F1(t2, ref s6); s6.ToString(); // 7 T? s7 = default!; F2(t2, ref s7); // 8 s7.ToString(); // 9 T? s8 = default!; F3(t2, ref s8); // 10 s8.ToString(); // 11 } static void M3<T>(T? t3) where T : class { T? s9 = default!; F1(t3, ref s9); s9.ToString(); // 12 T s10 = default!; F2(t3, ref s10); // 13, 14 s10.ToString(); // 15 T? s11 = default!; F3(t3, ref s11); // 16 s11.ToString(); // 17 if (t3 == null) return; T s12 = default!; F1(t3, ref s12); // 18 s12.ToString(); // 19 T s13 = default!; F2(t3, ref s13); // 20 s13.ToString(); // 21 T? s14 = default!; F3(t3, ref s14); s14.ToString(); // 22 } static void M4<T>(T t4) where T : struct { T s15 = default; F1(t4, ref s15); s15.ToString(); T s16 = default; F4(t4, ref s16); s16.ToString(); } static void M5<T>(T? t5) where T : struct { T s17 = default!; F1(t5, ref s17); // 23 _ = s17.Value; // 24 T s18 = default!; F5(t5, ref s18); // 25 _ = s18.Value; // 26 if (t5 == null) return; T s19 = default!; F1(t5, ref s19); // 27 _ = s19.Value; // 28 T s20 = default!; F5(t5, ref s20); // 29 _ = s20.Value; // 30 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(13, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // s3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(19, 9), // (22,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // F2(t2, ref s4); // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s4").WithLocation(22, 20), // (23,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(23, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // s5.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s5").WithLocation(31, 9), // (33,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(33, 14), // (36,9): warning CS8602: Dereference of a possibly null reference. // s6.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(36, 9), // (39,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, ref T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t2, ref s7); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, ref T)", "T", "T?").WithLocation(39, 9), // (40,9): warning CS8602: Dereference of a possibly null reference. // s7.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s7").WithLocation(40, 9), // (43,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, ref T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t2, ref s8); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, ref T?)", "T", "T?").WithLocation(43, 9), // (44,9): warning CS8602: Dereference of a possibly null reference. // s8.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s8").WithLocation(44, 9), // (50,9): warning CS8602: Dereference of a possibly null reference. // s9.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s9").WithLocation(50, 9), // (53,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, ref T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t3, ref s10); // 12, 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, ref T)", "T", "T?").WithLocation(53, 9), // (53,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // F2(t3, ref s10); // 12, 13 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s10").WithLocation(53, 20), // (54,9): warning CS8602: Dereference of a possibly null reference. // s10.ToString(); // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s10").WithLocation(54, 9), // (57,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, ref T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t3, ref s11); // 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, ref T?)", "T", "T?").WithLocation(57, 9), // (58,9): warning CS8602: Dereference of a possibly null reference. // s11.ToString(); // 16 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s11").WithLocation(58, 9), // (62,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // F1(t3, ref s12); // 17 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s12").WithLocation(62, 20), // (63,9): warning CS8602: Dereference of a possibly null reference. // s12.ToString(); // 18 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s12").WithLocation(63, 9), // (66,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // F2(t3, ref s13); // 19 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s13").WithLocation(66, 20), // (67,9): warning CS8602: Dereference of a possibly null reference. // s13.ToString(); // 20 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s13").WithLocation(67, 9), // (71,9): warning CS8602: Dereference of a possibly null reference. // s14.ToString(); // 21 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s14").WithLocation(71, 9), // (86,9): error CS0411: The type arguments for method 'Program.F1<T>(T, ref T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(t5, ref s17); // 22 Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T, ref T)").WithLocation(86, 9), // (87,17): error CS1061: 'T' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // _ = s17.Value; // 23 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Value").WithArguments("T", "Value").WithLocation(87, 17), // (90,20): error CS1503: Argument 2: cannot convert from 'ref T' to 'ref T?' // F5(t5, ref s18); // 24 Diagnostic(ErrorCode.ERR_BadArgType, "s18").WithArguments("2", "ref T", "ref T?").WithLocation(90, 20), // (91,17): error CS1061: 'T' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // _ = s18.Value; // 25 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Value").WithArguments("T", "Value").WithLocation(91, 17), // (95,9): error CS0411: The type arguments for method 'Program.F1<T>(T, ref T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F1(t5, ref s19); // 26 Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F1").WithArguments("Program.F1<T>(T, ref T)").WithLocation(95, 9), // (96,17): error CS1061: 'T' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // _ = s19.Value; // 27 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Value").WithArguments("T", "Value").WithLocation(96, 17), // (99,20): error CS1503: Argument 2: cannot convert from 'ref T' to 'ref T?' // F5(t5, ref s20); // 28 Diagnostic(ErrorCode.ERR_BadArgType, "s20").WithArguments("2", "ref T", "ref T?").WithLocation(99, 20), // (100,17): error CS1061: 'T' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // _ = s20.Value; // 29 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Value").WithArguments("T", "Value").WithLocation(100, 17) ); } [Fact] public void MaybeNull_RefParameter_03() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([MaybeNull]ref string t) { t = null; } static void F2([MaybeNull]ref string? t) { t = null; } static void M() { string t1 = null!; F1(ref t1); // 1 t1.ToString(); // 2 string? t2 = null; F1(ref t2); // 3 t2.ToString(); // 4 string? t3 = null!; F2(ref t3); t3.ToString(); // 5 } }"; var comp = CreateNullableCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (9,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // F1(ref t1); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t1").WithLocation(9, 16), // (10,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(10, 9), // (13,16): warning CS8601: Possible null reference assignment. // F1(ref t2); // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(13, 16), // (14,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(14, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // t3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3").WithLocation(18, 9) ); } [Fact] public void MaybeNull_MemberReference() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class C<T> { [MaybeNull] T F = default!; [MaybeNull] T P => default!; void M1() { _ = F; } static void M2(C<T> c) { _ = c.P; } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void MaybeNull_MethodCall() { var source = @"#nullable enable using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; static class E { [return: MaybeNull] internal static T FirstOrDefault<T>(this IEnumerable<T> e) => throw null!; internal static bool TryGet<K, V>(this Dictionary<K, V> d, K key, [MaybeNullWhen(false)] out V value) => throw null!; } class Program { [return: MaybeNull] static T M1<T>(IEnumerable<T> e) { e.FirstOrDefault(); _ = e.FirstOrDefault(); return e.FirstOrDefault(); } static void M2<K, V>(Dictionary<K, V> d, K key) { d.TryGet(key, out var value); } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void NotNull_ReturnValue_01() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: NotNull] static T F1<T>(T t) => t; // 00 [return: NotNull] static T F2<T>(T t) where T : class => t; [return: NotNull] static T? F3<T>(T t) where T : class => t; [return: NotNull] static T F4<T>(T t) where T : struct => t; [return: NotNull] static T? F5<T>(T? t) where T : struct => t; // 0 static void M1<T>(T t1) { F1(t1).ToString(); } static void M2<T>(T t2) where T : class { F1(t2).ToString(); F2(t2).ToString(); F3(t2).ToString(); t2 = null; // 1 F1(t2).ToString(); F2(t2).ToString(); // 2 F3(t2).ToString(); // 3 } static void M3<T>(T? t3) where T : class { F1(t3).ToString(); F2(t3).ToString(); // 4 F3(t3).ToString(); // 5 if (t3 == null) return; F1(t3).ToString(); F2(t3).ToString(); F3(t3).ToString(); } static void M4<T>(T t4) where T : struct { F1(t4).ToString(); F4(t4).ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1(t5).Value; _ = F5(t5).Value; if (t5 == null) return; _ = F1(t5).Value; _ = F5(t5).Value; } }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,46): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull] static T F1<T>(T t) => t; // 00 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(4, 46), // (8,65): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull] static T? F5<T>(T? t) where T : struct => t; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(8, 65), // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 14), // (20,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(20, 9), // (21,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T)", "T", "T?").WithLocation(21, 9), // (26,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t3).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T)", "T", "T?").WithLocation(26, 9), // (27,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t3).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T)", "T", "T?").WithLocation(27, 9) ); } [Fact] public void NotNull_ReturnValue_02() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: NotNull] static T F1<T>(T t) => t; // 00 [return: NotNull] static T F2<T>(T t) where T : class => t; [return: NotNull] static T? F3<T>(T t) where T : class => t; [return: NotNull] static T F4<T>(T t) where T : struct => t; [return: NotNull] static T? F5<T>(T? t) where T : struct => t; // 0 static void M1<T>(T t1) { F1<T>(t1).ToString(); } static void M2<T>(bool b, T t2) where T : class { F1<T>(t2).ToString(); F2<T>(t2).ToString(); F3<T>(t2).ToString(); t2 = null; // 1 if (b) F1<T>(t2).ToString(); // 2 if (b) F2<T>(t2).ToString(); // 3 if (b) F3<T>(t2).ToString(); // 4 } static void M3<T>(bool b, T? t3) where T : class { if (b) F1<T>(t3).ToString(); // 5 if (b) F2<T>(t3).ToString(); // 6 if (b) F3<T>(t3).ToString(); // 7 if (t3 == null) return; F1<T>(t3).ToString(); F2<T>(t3).ToString(); F3<T>(t3).ToString(); } static void M4<T>(T t4) where T : struct { F1<T>(t4).ToString(); F4<T>(t4).ToString(); } static void M5<T>(T? t5) where T : struct { _ = F1<T?>(t5).Value; _ = F5<T>(t5).Value; if (t5 == null) return; _ = F1<T?>(t5).Value; _ = F5<T>(t5).Value; } }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,46): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull] static T F1<T>(T t) => t; // 00 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(4, 46), // (8,65): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull] static T? F5<T>(T? t) where T : struct => t; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(8, 65), // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 14), // (19,22): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F1<T>(T t)'. // if (b) F1<T>(t2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "T Program.F1<T>(T t)").WithLocation(19, 22), // (20,22): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F2<T>(T t)'. // if (b) F2<T>(t2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "T Program.F2<T>(T t)").WithLocation(20, 22), // (21,22): warning CS8604: Possible null reference argument for parameter 't' in 'T? Program.F3<T>(T t)'. // if (b) F3<T>(t2).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "T? Program.F3<T>(T t)").WithLocation(21, 22), // (25,22): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F1<T>(T t)'. // if (b) F1<T>(t3).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "T Program.F1<T>(T t)").WithLocation(25, 22), // (26,22): warning CS8604: Possible null reference argument for parameter 't' in 'T Program.F2<T>(T t)'. // if (b) F2<T>(t3).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "T Program.F2<T>(T t)").WithLocation(26, 22), // (27,22): warning CS8604: Possible null reference argument for parameter 't' in 'T? Program.F3<T>(T t)'. // if (b) F3<T>(t3).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "T? Program.F3<T>(T t)").WithLocation(27, 22)); } [Fact] public void NotNull_ReturnValue_03() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: NotNull] static string F1() => string.Empty; [return: NotNull] static string? F2() => string.Empty; static void M() { F1().ToString(); F2().ToString(); } }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NotNull_ReturnValue_04() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { [return: NotNull] static int F1() => 1; [return: NotNull] static int? F2() => 2; static void M() { F1().ToString(); _ = F2().Value; } }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NotNull_ReturnValue_05() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static T F1<T>(T t) where T : class => t; [return: NotNull] public static T F2<T>(T t) where T : class => t; }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x).ToString(); // 2, 3 F1(y).ToString(); F2(x).ToString(); // 4 F2(y).ToString(); } }"; comp = CreateCompilation(source, references: new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F1<T>(T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F1(x).ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F1").WithArguments("A.F1<T>(T)", "T", "object?").WithLocation(7, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (9,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'A.F2<T>(T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // F2(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("A.F2<T>(T)", "T", "object?").WithLocation(9, 9) ); } [Fact] public void NotNull_ReturnValue_05_Unconstrained() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { public static T F1<T>(T t) => t; [return: NotNull] public static T F2<T>(T t) => t; }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source0 }); comp.VerifyDiagnostics( // (5,53): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull] public static T F2<T>(T t) => t; Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(5, 53) ); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F1(x).ToString(); // 2 F1(y).ToString(); F2(x).ToString(); F2(y).ToString(); } }"; comp = CreateNullableCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9) ); } [Fact] public void NotNull_ReturnValue_05_Unconstrained_WithMaybeNull() { var source0 = @"using System.Diagnostics.CodeAnalysis; public class A { [return: NotNull, MaybeNull] public static T F2<T>(T t) => t; }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullAttributeDefinition, source0 }); comp.VerifyDiagnostics( // (4,64): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull, MaybeNull] public static T F2<T>(T t) => t; Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(4, 64) ); var ref0 = comp.EmitToImageReference(); var source = @"class B : A { static void Main() { object x = null; // 1 object? y = new object(); F2(x).ToString(); // 2 F2(y).ToString(); // 3 } }"; comp = CreateNullableCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 20), // (7,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(8, 9) ); } [Fact] public void NotNull_ReturnValue_05_Unconstrained_WithMaybeNull_InSource() { var source = @"using System.Diagnostics.CodeAnalysis; public class A { [return: NotNull, MaybeNull] public static T F2<T>(T t) => t; // 0 } class B : A { static void Main() { object x = null; // 1 object? y = new object(); F2(x).ToString(); // 2 F2(y).ToString(); // 3 } }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,64): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull, MaybeNull] public static T F2<T>(T t) => t; // 0 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(4, 64), // (10,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(10, 20), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(13, 9) ); } [Fact] public void NotNull_ReturnValue_06() { var source = @"using System.Diagnostics.CodeAnalysis; class C<T> { [return: NotNull] internal static T F() => throw null!; } class Program { static void M<T, U, V>() where U : class where V : struct { C<T>.F().ToString(); C<U>.F().ToString(); C<U?>.F().ToString(); C<V>.F().ToString(); _ = C<V?>.F().Value; C<string>.F().ToString(); C<string?>.F().ToString(); C<int>.F().ToString(); _ = C<int?>.F().Value; } }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NotNull_Property() { // Warn on misused nullability attributes (P3, P5)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [NotNull]public TOpen P1 { get; set; } = default!; } public class CClass<TClass> where TClass : class { [NotNull]public TClass P2 { get; set; } = null!; [NotNull]public TClass? P3 { get; set; } = null; } public class CStruct<TStruct> where TStruct : struct { [NotNull]public TStruct P4 { get; set; } [NotNull]public TStruct? P5 { get; set; } }"; var lib = CreateNullableCompilation(new[] { lib_cs, NotNullAttributeDefinition }); var source = @" class C { static void M1<T>(T t1) { new COpen<T>().P1.ToString(); } static void M2<T>(T t2) where T : class { new COpen<T>().P1.ToString(); new CClass<T>().P2.ToString(); new CClass<T>().P3.ToString(); } static void M4<T>(T t4) where T : struct { new COpen<T>().P1.ToString(); new CStruct<T>().P4.ToString(); } static void M5<T>(T? t5) where T : struct { new COpen<T?>().P1.Value.ToString(); new CStruct<T>().P5.Value.ToString(); } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullAttributeDefinition }); comp2.VerifyDiagnostics(); } [Fact, WorkItem(36073, "https://github.com/dotnet/roslyn/issues/36073")] public void NotNull_Property_InitializedInConstructor() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [NotNull]public TOpen P1 { get; set; } COpen() // 1 { P1 = default; // 2 } } public class CClass<TClass> where TClass : class { [NotNull]public TClass P2 { get; set; } [NotNull]public TClass? P3 { get; set; } CClass() // 3 { P2 = null; // 4 P3 = null; } } public class CStruct<TStruct> where TStruct : struct { [NotNull]public TStruct P4 { get; set; } [NotNull]public TStruct? P5 { get; set; } CStruct() { P4 = default; P5 = null; } }"; var comp = CreateNullableCompilation(new[] { lib_cs, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,5): warning CS8618: Non-nullable property 'P1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // COpen() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "COpen").WithArguments("property", "P1").WithLocation(5, 5), // (7,14): warning CS8601: Possible null reference assignment. // P1 = default; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(7, 14), // (14,5): warning CS8618: Non-nullable property 'P2' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // CClass() // 3 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "CClass").WithArguments("property", "P2").WithLocation(14, 5), // (16,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // P2 = null; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 14) ); } [Fact, WorkItem(36073, "https://github.com/dotnet/roslyn/issues/36073")] public void NotNull_Property_InitializedInConstructor_WithValues() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> where TOpen : new() { [NotNull]public TOpen P1 { get; set; } COpen() { P1 = new TOpen(); } } public class CClass<TClass> where TClass : class, new() { [NotNull]public TClass P2 { get; set; } [NotNull]public TClass? P3 { get; set; } CClass() { P2 = new TClass(); P3 = new TClass(); } } public class CStruct<TStruct> where TStruct : struct { [NotNull]public TStruct P4 { get; set; } [NotNull]public TStruct? P5 { get; set; } CStruct() { P4 = new TStruct(); P5 = new TStruct(); } }"; var comp = CreateNullableCompilation(new[] { lib_cs, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact, WorkItem(36073, "https://github.com/dotnet/roslyn/issues/36073")] public void NotNull_Property_InitializedWithValues() { var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> where TOpen : new() { [NotNull]public TOpen P1 { get; set; } = new TOpen(); } public class CClass<TClass> where TClass : class, new() { [NotNull]public TClass P2 { get; set; } = new TClass(); [NotNull]public TClass? P3 { get; set; } = new TClass(); } public class CStruct<TStruct> where TStruct : struct { [NotNull]public TStruct P4 { get; set; } = new TStruct(); [NotNull]public TStruct? P5 { get; set; } = new TStruct(); }"; var comp = CreateNullableCompilation(new[] { lib_cs, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNull_Property_WithAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [NotNull] string? P { get; set; } void M() { P.ToString(); P = null; P.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNull_Property_OnVirtualProperty() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [NotNull] public virtual string? P => throw null!; public virtual string? P2 => throw null!; } public class C : Base { public override string? P => throw null!; // 0 [NotNull] public override string? P2 => throw null!; static void M(C c, Base b) { b.P.ToString(); c.P.ToString(); // 1 b.P2.ToString(); // 2 c.P2.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,34): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // public override string? P => throw null!; // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "throw null!").WithLocation(10, 34), // (16,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // b.P2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.P2").WithLocation(18, 9) ); } [Fact] public void NotNull_Property_OnVirtualProperty_OnlyOverridingGetter() { var source = @" using System.Diagnostics.CodeAnalysis; public class Base { [NotNull] public virtual string? P { get { throw null!; } set { throw null!; } } public virtual string? P2 { get { throw null!; } set { throw null!; } } } public class C : Base { public override string? P { get { throw null!; } } // 0 [NotNull] public override string? P2 { get { throw null!; } } static void M(C c, Base b) { b.P.ToString(); c.P.ToString(); // 1 b.P2.ToString(); // 2 c.P2.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (10,33): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override string? P { get { throw null!; } } // 0 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "get").WithLocation(10, 33), // (16,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // b.P2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.P2").WithLocation(18, 9) ); } [Fact] public void NotNull_Indexer_WithAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [NotNull] string? this[int i] { get => throw null!; set => throw null!; } void M() { this[0].ToString(); this[0] = null; this[0].ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNull_01_Indexer() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [NotNull]public TOpen this[int i] { get => throw null!; } } public class CClass<TClass> where TClass : class? { [NotNull]public TClass this[int i] { get => throw null!; } } public class CClass2<TClass> where TClass : class { [NotNull]public TClass? this[int i] { get => throw null!; } } public class CStruct<TStruct> where TStruct : struct { [NotNull]public TStruct this[int i] { get => throw null!; } } public class CStruct2<TStruct> where TStruct : struct { [NotNull]public TStruct? this[int i] { get => throw null!; } }"; var lib = CreateNullableCompilation(new[] { lib_cs, NotNullAttributeDefinition }); lib.VerifyDiagnostics(); var source = @" class C { static void M1<T>(T t1) { new COpen<T>()[0].ToString(); } static void M2<T>(T t2) where T : class { new COpen<T>()[0].ToString(); new CClass<T>()[0].ToString(); new CClass2<T>()[0].ToString(); } static void M4<T>(T t4) where T : struct { new COpen<T>()[0].ToString(); new CStruct<T>()[0].ToString(); new COpen<T?>()[0].Value.ToString(); new CStruct2<T>()[0].Value.ToString(); } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullAttributeDefinition }); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var copenAttributes = copen.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Empty(copenAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableContextAttribute(1)", "System.Runtime.CompilerServices.NullableAttribute(0)", "System.Reflection.DefaultMemberAttribute(\"Item\")" }, copenAttributes); } var property = copen.GetMembers().OfType<PropertySymbol>().Single(); var propertyAttributes = property.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.NotNullAttribute" }, propertyAttributes); } else { AssertEx.Empty(propertyAttributes); } var getter = property.GetMethod; Assert.Empty(getter.GetAttributes()); var getterReturnAttributes = getter.GetReturnTypeAttributes().Select(a => a.ToString()); Assert.Equal(FlowAnalysisAnnotations.NotNull, getter.ReturnTypeFlowAnalysisAnnotations); if (isSource) { AssertEx.Empty(getterReturnAttributes); } else { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.NotNullAttribute" }, getterReturnAttributes); } } } [Fact] public void NotNull_01_Indexer_Implementation() { var source = @"using System.Diagnostics.CodeAnalysis; public class CClass2<TClass> where TClass : class { [NotNull]public TClass? this[int i] { get => null; } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (4,50): warning CS8603: Possible null reference return. // [NotNull]public TClass? this[int i] { get => null; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(4, 50) ); } [Fact] public void NotNull_Field() { // Warn on misused nullability attributes (f2, f3, f4, f5)? https://github.com/dotnet/roslyn/issues/36073 var lib_cs = @"using System.Diagnostics.CodeAnalysis; public class COpen<TOpen> { [NotNull]public TOpen f1 = default!; } public class CClass<TClass> where TClass : class { [NotNull]public TClass f2 = null!; [NotNull]public TClass? f3 = null; } public class CStruct<TStruct> where TStruct : struct { [NotNull]public TStruct f4; [NotNull]public TStruct? f5; } "; var lib = CreateNullableCompilation(new[] { NotNullAttributeDefinition, lib_cs }); var source = @" class C { static void M1<T>(T t1) { new COpen<T>().f1.ToString(); } static void M2<T>() where T : class { new COpen<T>().f1.ToString(); new CClass<T>().f2.ToString(); new CClass<T>().f3.ToString(); } static void M4<T>(T t4) where T : struct { new COpen<T>().f1.ToString(); new CStruct<T>().f4.ToString(); new CStruct<T>().f5.Value.ToString(); } }"; var comp = CreateNullableCompilation(source, references: new[] { lib.EmitToImageReference() }); comp.VerifyDiagnostics(); var comp2 = CreateNullableCompilation(new[] { source, lib_cs, NotNullAttributeDefinition }); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var copen = (NamedTypeSymbol)m.GlobalNamespace.GetMember("COpen"); var field = copen.GetMembers().OfType<FieldSymbol>().Single(); var fieldAttributes = field.GetAttributes().Select(a => a.ToString()); if (isSource) { AssertEx.Equal(new[] { "System.Diagnostics.CodeAnalysis.NotNullAttribute" }, fieldAttributes); } else { AssertEx.Equal(new[] { "System.Runtime.CompilerServices.NullableAttribute(1)", "System.Diagnostics.CodeAnalysis.NotNullAttribute" }, fieldAttributes); } } } [Fact] public void NotNull_Field_WithAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [NotNull] string? f1 = default!; void M() { f1.ToString(); f1 = null; f1.ToString(); // 1 } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // f1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "f1").WithLocation(9, 9) ); } [Fact] public void NotNull_Field_WithContainerAssignment() { var source = @"using System.Diagnostics.CodeAnalysis; public class C { [NotNull] public string? f1 = default!; void M(C c) { c.f1.ToString(); c.f1 = null; c = new C(); c.f1.ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] public void NotNull_OutParameter_GenericType() { // Warn on misused nullability attributes? https://github.com/dotnet/roslyn/issues/36073 var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>(T t, [NotNull]out T t2) { t2 = t; } // 00 static void F2<T>(T t, [NotNull]out T t2) where T : class { t2 = t; } static void F3<T>(T t, [NotNull]out T? t2) where T : class { t2 = t; } static void F4<T>(T t, [NotNull]out T t2) where T : struct { t2 = t; } static void F5<T>(T? t, [NotNull]out T? t2) where T : struct { t2 = t; } // 0 static void M1<T>(T t1) { F1(t1, out var s1); s1.ToString(); } static void M2<T>(T t2) where T : class { F1(t2, out var s2); s2.ToString(); F2(t2, out var s3); s3.ToString(); F3(t2, out var s4); s4.ToString(); t2 = null; // 1 F1(t2, out var s5); s5.ToString(); F2(t2, out var s6); // 2 s6.ToString(); F3(t2, out var s7); // 3 s7.ToString(); } static void M3<T>(T? t3) where T : class { F1(t3, out var s8); s8.ToString(); F2(t3, out var s9); // 4 s9.ToString(); F3(t3, out var s10); // 5 s10.ToString(); if (t3 == null) return; F1(t3, out var s11); s11.ToString(); F2(t3, out var s12); s12.ToString(); F3(t3, out var s13); s13.ToString(); } static void M4<T>(T t4) where T : struct { F1(t4, out var s14); s14.ToString(); F4(t4, out var s15); s15.ToString(); } static void M5<T>(T? t5) where T : struct { F1(t5, out var s16); _ = s16.Value; F5(t5, out var s17); _ = s17.Value; if (t5 == null) return; F1(t5, out var s18); _ = s18.Value; F5(t5, out var s19); _ = s19.Value; } }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,57): warning CS8777: Parameter 't2' must have a non-null value when exiting. // static void F1<T>(T t, [NotNull]out T t2) { t2 = t; } // 00 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("t2").WithLocation(4, 57), // (8,76): warning CS8777: Parameter 't2' must have a non-null value when exiting. // static void F5<T>(T? t, [NotNull]out T? t2) where T : struct { t2 = t; } // 0 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("t2").WithLocation(8, 76), // (25,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t2 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(25, 14), // (29,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t2, out var s6); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(29, 9), // (32,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t2, out var s7); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(32, 9), // (40,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F2<T>(T, out T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F2(t3, out var s9); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F2").WithArguments("Program.F2<T>(T, out T)", "T", "T?").WithLocation(40, 9), // (43,9): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.F3<T>(T, out T?)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // F3(t3, out var s10); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F3").WithArguments("Program.F3<T>(T, out T?)", "T", "T?").WithLocation(43, 9)); } [Fact] public void NotNull_RefParameter_03() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F1([NotNull]ref string t) { t = null; } // 0 static void F2([NotNull]ref string? t) { t = null; } // 1 static void M() { string t1 = null; // 2 F1(ref t1); // 3 t1.ToString(); string? t2 = null; F1(ref t2); // 4 t2.ToString(); string? t3 = null; F2(ref t3); t3.ToString(); } static void F3([NotNull]ref string? t) { t = null!; } }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (4,49): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F1([NotNull]ref string t) { t = null; } // 0 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 49), // (4,55): warning CS8777: Parameter 't' must have a non-null value when exiting. // static void F1([NotNull]ref string t) { t = null; } // 0 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("t").WithLocation(4, 55), // (5,56): warning CS8777: Parameter 't' must have a non-null value when exiting. // static void F2([NotNull]ref string? t) { t = null; } // 1 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("t").WithLocation(5, 56), // (8,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string t1 = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 21), // (9,16): warning CS8601: Possible null reference assignment. // F1(ref t1); // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t1").WithLocation(9, 16), // (13,16): warning CS8601: Possible null reference assignment. // F1(ref t2); // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t2").WithLocation(13, 16) ); } [Fact] public void NotNull_ReturnValue_GenericType_Loosening() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { [return: NotNull] public virtual T F1<T>(T t) => throw null!; [return: NotNull] public virtual T F2<T>(T t) where T : class => t; [return: NotNull] public virtual T? F3<T>(T t) where T : class => t; [return: NotNull] public virtual T F4<T>(T t) where T : struct => t; [return: NotNull] public virtual T? F5<T>(T t) where T : struct => t; } public class Derived : Base { public override T F1<T>(T t) => t; // 1 public override T F2<T>(T t) where T : class => t; public override T? F3<T>(T t) where T : class => t; // 2 public override T F4<T>(T t) where T : struct => t; public override T? F5<T>(T t) where T : struct => t; // 3 } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,23): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T F1<T>(T t) => t; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F1").WithLocation(12, 23), // (14,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F3<T>(T t) where T : class => t; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F3").WithLocation(14, 24), // (16,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F5<T>(T t) where T : struct => t; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F5").WithLocation(16, 24) ); } [Fact] public void NotNull_ReturnValue_GenericType_Loosening_MaybeNull() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { [return: NotNull] public virtual T F1<T>() => throw null!; [return: NotNull] public virtual T F2<T>() where T : class => throw null!; [return: NotNull] public virtual T? F3<T>() where T : class => throw null!; [return: NotNull] public virtual T F4<T>() where T : struct => throw null!; [return: NotNull, MaybeNull] public virtual T F4B<T>() where T : struct => throw null!; [return: NotNull] public virtual T? F5<T>() where T : struct => throw null!; public virtual T F6<T>() where T : notnull => throw null!; } public class Derived : Base { [return: MaybeNull] public override T F1<T>() => throw null!; // 1 [return: MaybeNull] public override T F2<T>() where T : class => throw null!; // 2 [return: MaybeNull] public override T? F3<T>() where T : class => throw null!; // 3 [return: MaybeNull] public override T F4<T>() where T : struct => throw null!; [return: MaybeNull] public override T F4B<T>() where T : struct => throw null!; [return: MaybeNull] public override T? F5<T>() where T : struct => throw null!; // 4 [return: MaybeNull] public override T F6<T>() => throw null!; // 5 } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (14,43): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T F1<T>() => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F1").WithLocation(14, 43), // (15,43): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T F2<T>() where T : class => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F2").WithLocation(15, 43), // (16,44): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T? F3<T>() where T : class => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F3").WithLocation(16, 44), // (19,44): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T? F5<T>() where T : struct => throw null!; // 4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F5").WithLocation(19, 44), // (20,43): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T F6<T>() => throw null!; // 5 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F6").WithLocation(20, 43) ); } [Fact] public void NotNull_ReturnValue_GenericType_Loosening_MaybeNull_FromMetadata() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { [return: NotNull] public virtual T F1<T>() => throw null!; [return: NotNull] public virtual T F2<T>() where T : class => throw null!; [return: NotNull] public virtual T? F3<T>() where T : class => throw null!; [return: NotNull] public virtual T F4<T>() where T : struct => throw null!; [return: NotNull, MaybeNull] public virtual T F4B<T>() where T : struct => throw null!; [return: NotNull] public virtual T? F5<T>() where T : struct => throw null!; public virtual T F6<T>() where T : notnull => throw null!; } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullAttributeDefinition, source }); var source2 = @"using System.Diagnostics.CodeAnalysis; public class Derived : Base { [return: MaybeNull] public override T F1<T>() => throw null!; // 1 [return: MaybeNull] public override T F2<T>() where T : class => throw null!; // 2 [return: MaybeNull] public override T? F3<T>() where T : class => throw null!; // 3 [return: MaybeNull] public override T F4<T>() where T : struct => throw null!; [return: MaybeNull] public override T F4B<T>() where T : struct => throw null!; [return: MaybeNull] public override T? F5<T>() where T : struct => throw null!; // 4 [return: MaybeNull] public override T F6<T>() => throw null!; // 5 } "; var comp2 = CreateNullableCompilation(source2, references: new[] { comp.EmitToImageReference() }); comp2.VerifyDiagnostics( // (4,43): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T F1<T>() => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F1").WithLocation(4, 43), // (5,43): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T F2<T>() where T : class => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F2").WithLocation(5, 43), // (6,44): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T? F3<T>() where T : class => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F3").WithLocation(6, 44), // (9,44): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T? F5<T>() where T : struct => throw null!; // 4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F5").WithLocation(9, 44), // (10,43): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // [return: MaybeNull] public override T F6<T>() => throw null!; // 5 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F6").WithLocation(10, 43) ); } [Fact] public void NotNull_ReturnValue_GenericType_Loosening_MaybeNull_SpecificType() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base<TOpen, TClass, TStruct, TNotNull> where TClass : class where TStruct : struct where TNotNull : notnull { [return: NotNull] public virtual TOpen F1() => throw null!; [return: NotNull] public virtual TClass F2() => throw null!; [return: NotNull] public virtual TClass? F3() => throw null!; [return: NotNull] public virtual TStruct F4() => throw null!; [return: NotNull, MaybeNull] public virtual TStruct F4B() => throw null!; [return: NotNull] public virtual TStruct? F5() => throw null!; public virtual TNotNull F6() => throw null!; } public class Derived<TNotNull> : Base<string?, string, int, TNotNull> where TNotNull : notnull { [return: MaybeNull] public override string? F1() => throw null!; // 1 [return: MaybeNull] public override string F2() => throw null!; // 2 [return: MaybeNull] public override string? F3() => throw null!; // 3 [return: MaybeNull] public override int F4() => throw null!; [return: MaybeNull] public override int F4B() => throw null!; [return: MaybeNull] public override int? F5() => throw null!; // 4 [return: MaybeNull] public override TNotNull F6() => throw null!; // 5 } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (18,49): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [return: MaybeNull] public override string? F1() => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F1").WithLocation(18, 49), // (19,48): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [return: MaybeNull] public override string F2() => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F2").WithLocation(19, 48), // (20,49): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [return: MaybeNull] public override string? F3() => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F3").WithLocation(20, 49), // (23,46): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [return: MaybeNull] public override int? F5() => throw null!; // 4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F5").WithLocation(23, 46), // (24,50): warning CS8764: Return type doesn't match overridden member because of nullability attributes. // [return: MaybeNull] public override TNotNull F6() => throw null!; // 5 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F6").WithLocation(24, 50) ); } [Fact] public void DisallowNull_Parameter_Loosening_SpecificType() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base<TOpen, TClass, TStruct, TNotNull> where TClass : class where TStruct : struct where TNotNull : notnull { public virtual void F1([DisallowNull] TOpen p) => throw null!; public virtual void F2([DisallowNull] TClass p) => throw null!; public virtual void F3([DisallowNull] TClass? p) => throw null!; public virtual void F4([DisallowNull] TStruct p) => throw null!; public virtual void F4B([DisallowNull] TStruct p) => throw null!; public virtual void F5([DisallowNull] TStruct? p) => throw null!; public virtual void F6([DisallowNull] TNotNull p) => throw null!; } public class Derived<TNotNull> : Base<string?, string, int, TNotNull> where TNotNull : notnull { public override void F1(string? p) => throw null!; public override void F2(string p) => throw null!; public override void F3(string? p) => throw null!; public override void F4(int p) => throw null!; public override void F4B(int p) => throw null!; public override void F5(int? p) => throw null!; public override void F6(TNotNull p) => throw null!; } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics(); } [Fact] public void DisallowNull_Parameter_Tightening_SpecificType() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base<TOpen, TClass, TStruct, TNotNull> where TClass : class where TStruct : struct where TNotNull : notnull { public virtual void F1(TOpen p) => throw null!; public virtual void F2(TClass p) => throw null!; public virtual void F3(TClass? p) => throw null!; public virtual void F4(TStruct p) => throw null!; public virtual void F5(TStruct? p) => throw null!; public virtual void F6(TNotNull p) => throw null!; } public class Derived<TNotNull> : Base<string?, string, int, TNotNull> where TNotNull : notnull { public override void F1([DisallowNull] string? p) => throw null!; // 1 public override void F2([DisallowNull] string p) => throw null!; public override void F3([DisallowNull] string? p) => throw null!; // 2 public override void F4([DisallowNull] int p) => throw null!; public override void F5([DisallowNull] int? p) => throw null!; // 3 public override void F6([DisallowNull] TNotNull p) => throw null!; } "; var comp = CreateNullableCompilation(new[] { DisallowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (17,26): error CS8765: Type of parameter 'p' doesn't match overridden member because of nullability attributes. // public override void F1([DisallowNull] string? p) => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("p").WithLocation(17, 26), // (19,26): error CS8765: Type of parameter 'p' doesn't match overridden member because of nullability attributes. // public override void F3([DisallowNull] string? p) => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("p").WithLocation(19, 26), // (21,26): error CS8765: Type of parameter 'p' doesn't match overridden member because of nullability attributes. // public override void F5([DisallowNull] int? p) => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("p").WithLocation(21, 26) ); } [Fact] public void AllowNull_Parameter_Tightening_SpecificType() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base<TOpen, TClass, TStruct, TNotNull> where TClass : class where TStruct : struct where TNotNull : notnull { public virtual void F1([AllowNull] TOpen p) => throw null!; public virtual void F2([AllowNull] TClass p) => throw null!; public virtual void F3([AllowNull] TClass? p) => throw null!; public virtual void F4([AllowNull] TStruct p) => throw null!; public virtual void F5([AllowNull] TStruct? p) => throw null!; public virtual void F6([AllowNull] TNotNull p) => throw null!; } public class Derived<TNotNull> : Base<string?, string, int, TNotNull> where TNotNull : notnull { public override void F1(string? p) => throw null!; public override void F2(string p) => throw null!; // 1 public override void F3(string? p) => throw null!; public override void F4(int p) => throw null!; public override void F5(int? p) => throw null!; public override void F6(TNotNull p) => throw null!; // 2 } "; var comp = CreateNullableCompilation(new[] { AllowNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (18,26): error CS8765: Type of parameter 'p' doesn't match overridden member because of nullability attributes. // public override void F2(string p) => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("p").WithLocation(18, 26), // (22,26): error CS8765: Type of parameter 'p' doesn't match overridden member because of nullability attributes. // public override void F6(TNotNull p) => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("p").WithLocation(22, 26) ); } [Fact, WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void NotNull_OutParameter_GenericType_Loosening() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual void F1<T>([NotNull]out T t2) => throw null!; public virtual void F2<T>([NotNull]out T t2) where T : class => throw null!; public virtual void F3<T>([NotNull]out T? t2) where T : class => throw null!; public virtual void F4<T>([NotNull]out T t2) where T : struct => throw null!; public virtual void F5<T>([NotNull]out T? t2) where T : struct => throw null!; } public class Derived : Base { public override void F1<T>(out T t2) => throw null!; // 1 public override void F2<T>(out T t2) where T : class => throw null!; public override void F3<T>(out T? t2) where T : class => throw null!; // 2 public override void F4<T>(out T t2) where T : struct => throw null!; public override void F5<T>(out T? t2) where T : struct => throw null!; // 3 } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (12,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F1<T>(out T t2) => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(12, 26), // (14,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F3<T>(out T? t2) where T : class => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t2").WithLocation(14, 26), // (16,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F5<T>(out T? t2) where T : struct => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t2").WithLocation(16, 26) ); } [Fact, WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void NotNull_OutParameter_GenericType_Loosening_SpecificType() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base<TOpen, TClass, TStruct> where TClass : class where TStruct : struct { public virtual void F1([NotNull]out TOpen t2) => throw null!; public virtual void F2([NotNull]out TClass t2) => throw null!; public virtual void F3([NotNull]out TClass? t2) => throw null!; public virtual void F4([NotNull]out TStruct t2) => throw null!; public virtual void F5([NotNull]out TStruct? t2) => throw null!; } public class Derived : Base<string?, string, int> { public override void F1(out string? t2) => throw null!; // 1 public override void F2(out string t2) => throw null!; public override void F3(out string? t2) => throw null!; // 2 public override void F4(out int t2) => throw null!; public override void F5(out int? t2) => throw null!; // 3 } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (14,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F1(out string? t2) => throw null!; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t2").WithLocation(14, 26), // (16,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F3(out string? t2) => throw null!; // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t2").WithLocation(16, 26), // (18,26): error CS8762: Type of parameter 't2' doesn't match overridden member because of nullability attributes. // public override void F5(out int? t2) => throw null!; // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t2").WithLocation(18, 26) ); } [Fact] public void NotNull_ReturnValue_GenericType_Tightening() { var source = @"using System.Diagnostics.CodeAnalysis; public class Base { public virtual T F1<T>(T t) => t; public virtual T F2<T>(T t) where T : class => t; public virtual T? F3<T>(T t) where T : class => t; public virtual T F4<T>(T t) where T : struct => t; public virtual T? F5<T>(T t) where T : struct => t; public virtual T F6<T>(T t) where T : notnull => t; } public class Derived : Base { [return: NotNull] public override T F1<T>(T t) => t; // 1 [return: NotNull] public override T F2<T>(T t) where T : class => t; [return: NotNull] public override T? F3<T>(T t) where T : class => t; [return: NotNull] public override T F4<T>(T t) where T : struct => t; [return: NotNull] public override T? F5<T>(T t) where T : struct => t; [return: NotNull] public override T F6<T>(T t) => t; } "; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, source }); comp.VerifyDiagnostics( // (13,55): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // [return: NotNull] public override T F1<T>(T t) => t; // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "t").WithLocation(13, 55) ); } [Fact, WorkItem(36410, "https://github.com/dotnet/roslyn/issues/36410")] public void NotNull_WithMaybeNullWhenTrue() { var source = @"using System.Diagnostics.CodeAnalysis; internal class C<T> where T : class? { public bool TryGetTarget([NotNull, MaybeNullWhen(true)] out T target) => throw null!; public string Method(C<string?> wr) { if (wr.TryGetTarget(out string? s)) { return s; // 1 } return s; } }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (9,20): warning CS8603: Possible null reference return. // return s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(9, 20) ); } [Fact, WorkItem(36410, "https://github.com/dotnet/roslyn/issues/36410")] public void NotNull_WithMaybeNullWhenFalse() { var source = @"using System.Diagnostics.CodeAnalysis; internal class C<T> where T : class? { public bool TryGetTarget([NotNull, MaybeNullWhen(false)] out T target) => throw null!; public string Method(C<string?> wr) { if (wr.TryGetTarget(out string? s)) { return s; } return s; // 1 } }"; var comp = CreateNullableCompilation(new[] { NotNullAttributeDefinition, MaybeNullWhenAttributeDefinition, source }); comp.VerifyDiagnostics( // (11,16): warning CS8603: Possible null reference return. // return s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(11, 16) ); } [Fact] public void NullableAnnotationAttributes_Deconstruction() { var source = @"using System.Diagnostics.CodeAnalysis; class Pair<T, U> { internal void Deconstruct([MaybeNull] out T t, [NotNull] out U u) => throw null!; } class Program { static void F1<T>(Pair<T, T> p) { var (x1, y1) = p; x1.ToString(); // 1 y1.ToString(); } static void F2<T>(Pair<T, T> p) where T : class { var (x2, y2) = p; x2.ToString(); // 2 y2.ToString(); x2 = null; y2 = null; } static void F3<T>(Pair<T, T> p) where T : class? { var (x3, y3) = p; x3.ToString(); // 3 y3.ToString(); x3 = null; y3 = null; } static void F4<T>(Pair<T?, T?> p) where T : struct { var (x4, y4) = p; _ = x4.Value; // 4 _ = y4.Value; } }"; var comp = CreateCompilation(new[] { MaybeNullAttributeDefinition, NotNullAttributeDefinition, source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(17, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(25, 9), // (33,13): warning CS8629: Nullable value type may be null. // _ = x4.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x4").WithLocation(33, 13) ); } [Fact] public void NullableAnnotationAttributes_ExtensionMethodThis() { var source = @"using System.Diagnostics.CodeAnalysis; delegate void D(); static class Program { static void E1<T>([AllowNull] this T t) where T : class { } static void E2<T>([DisallowNull] this T t) where T : class? { } static void F1<T>(T t1) where T : class { D d; d = t1.E1; d = t1.E2; t1 = null; // 1 d = t1.E1; // 2 d = t1.E2; // 3 } static void F2<T>(T t2) where T : class? { D d; d = t2.E1; // 4 d = t2.E2; // 5 } }"; var comp = CreateCompilation(new[] { AllowNullAttributeDefinition, DisallowNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t1 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 14), // (13,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'Program.E1<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // d = t1.E1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "t1.E1").WithArguments("Program.E1<T>(T)", "T", "T?").WithLocation(13, 13), // (14,13): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.E2<T?>(T? t)'. // d = t1.E2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t1").WithArguments("t", "void Program.E2<T?>(T? t)").WithLocation(14, 13), // (19,13): warning CS8634: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Program.E1<T>(T)'. Nullability of type argument 'T' doesn't match 'class' constraint. // d = t2.E1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "t2.E1").WithArguments("Program.E1<T>(T)", "T", "T").WithLocation(19, 13)); } [Fact] public void ConditionalBranching_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 x1, CL1? y1, CL1 z1) { if (y1 != null) { x1 = y1; } else { z1 = y1; } } void Test2(CL1 x2, CL1? y2, CL1 z2) { if (y2 == null) { x2 = y2; } else { z2 = y2; } } void Test3(CL2 x3, CL2? y3, CL2 z3) { if (y3 != null) { x3 = y3; } else { z3 = y3; } } void Test4(CL2 x4, CL2? y4, CL2 z4) { if (y4 == null) { x4 = y4; } else { z4 = y4; } } void Test5(CL1 x5, CL1 y5, CL1 z5) { if (y5 != null) { x5 = y5; } else { z5 = y5; } } } class CL1 { } class CL2 { public static bool operator == (CL2? x, CL2? y) { return false; } public static bool operator != (CL2? x, CL2? y) { return false; } public override bool Equals(object obj) { return false; } public override int GetHashCode() { return 0; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(16, 18), // (24,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2").WithLocation(24, 18), // (40,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z3 = y3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y3").WithLocation(40, 18), // (48,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = y4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y4").WithLocation(48, 18), // (64,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z5 = y5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y5").WithLocation(64, 18) ); } [Fact] public void ConditionalBranching_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 x1, CL1? y1, CL1 z1) { if (null != y1) { x1 = y1; } else { z1 = y1; } } void Test2(CL1 x2, CL1? y2, CL1 z2) { if (null == y2) { x2 = y2; } else { z2 = y2; } } void Test3(CL2 x3, CL2? y3, CL2 z3) { if (null != y3) { x3 = y3; } else { z3 = y3; } } void Test4(CL2 x4, CL2? y4, CL2 z4) { if (null == y4) { x4 = y4; } else { z4 = y4; } } void Test5(CL1 x5, CL1 y5, CL1 z5) { if (null == y5) { x5 = y5; } else { z5 = y5; } } } class CL1 { } class CL2 { public static bool operator == (CL2? x, CL2? y) { return false; } public static bool operator != (CL2? x, CL2? y) { return false; } public override bool Equals(object obj) { return false; } public override int GetHashCode() { return 0; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(16, 18), // (24,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2").WithLocation(24, 18), // (40,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z3 = y3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y3").WithLocation(40, 18), // (48,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = y4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y4").WithLocation(48, 18), // (60,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x5 = y5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y5").WithLocation(60, 18) ); } [Fact] public void ConditionalBranching_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 x1, CL1? y1, CL1 z1, bool u1) { if (null != y1 || u1) { x1 = y1; } else { z1 = y1; } } void Test2(CL1 x2, CL1? y2, CL1 z2, bool u2) { if (y2 != null && u2) { x2 = y2; } else { z2 = y2; } } bool Test3(CL1? x3) { return x3.M1(); } bool Test4(CL1? x4) { return x4 != null && x4.M1(); } bool Test5(CL1? x5) { return x5 == null && x5.M1(); } } class CL1 { public bool M1() { return true; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(12, 18), // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(16, 18), // (28,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z2 = y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2").WithLocation(28, 18), // (34,16): warning CS8602: Dereference of a possibly null reference. // return x3.M1(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(34, 16), // (44,30): warning CS8602: Dereference of a possibly null reference. // return x5 == null && x5.M1(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x5").WithLocation(44, 30) ); } [Fact] public void ConditionalBranching_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 x1, CL1? y1) { CL1 z1 = y1 ?? x1; } void Test2(CL1? x2, CL1? y2) { CL1 z2 = y2 ?? x2; } void Test3(CL1 x3, CL1? y3) { CL1 z3 = x3 ?? y3; } void Test4(CL1? x4, CL1 y4) { x4 = y4; CL1 z4 = x4 ?? x4.M1(); } void Test5(CL1 x5) { const CL1? y5 = null; CL1 z5 = y5 ?? x5; } void Test6(CL1 x6) { const string? y6 = """"; string z6 = y6 ?? x6.M2(); } } class CL1 { public CL1 M1() { return new CL1(); } public string? M2() { return null; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = y2 ?? x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2 ?? x2").WithLocation(15, 18), // (20,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z3 = x3 ?? y3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3 ?? y3").WithLocation(20, 18), // (26,24): warning CS8602: Dereference of a possibly null reference. // CL1 z4 = x4 ?? x4.M1(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(26, 24)); } [Fact] public void ConditionalBranching_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1? x1) { CL1 z1 = x1?.M1(); } void Test2(CL1? x2, CL1 y2) { x2 = y2; CL1 z2 = x2?.M1(); } void Test3(CL1? x3, CL1 y3) { x3 = y3; CL1 z3 = x3?.M2(); } void Test4(CL1? x4) { x4?.M3(x4); } } class CL1 { public CL1 M1() { return new CL1(); } public CL1? M2() { return null; } public void M3(CL1 x) { } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z1 = x1?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1?.M1()").WithLocation(10, 18), // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = x2?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2?.M1()").WithLocation(16, 18), // (22,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z3 = x3?.M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3?.M2()").WithLocation(22, 18) ); } [Fact] public void ConditionalBranching_06() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 x1, CL1? y1) { CL1 z1 = y1 != null ? y1 : x1; } void Test2(CL1? x2, CL1? y2) { CL1 z2 = y2 != null ? y2 : x2; } void Test3(CL1 x3, CL1? y3) { CL1 z3 = x3 != null ? x3 : y3; } void Test4(CL1? x4, CL1 y4) { x4 = y4; CL1 z4 = x4 != null ? x4 : x4.M1(); } void Test5(CL1 x5) { const CL1? y5 = null; CL1 z5 = y5 != null ? y5 : x5; } void Test6(CL1 x6) { const string? y6 = """"; string z6 = y6 != null ? y6 : x6.M2(); } void Test7(CL1 x7) { const string? y7 = null; string z7 = y7 != null ? y7 : x7.M2(); } } class CL1 { public CL1 M1() { return new CL1(); } public string? M2() { return null; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = y2 != null ? y2 : x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2 != null ? y2 : x2").WithLocation(15, 18), // (20,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z3 = x3 != null ? x3 : y3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3 != null ? x3 : y3").WithLocation(20, 18), // (26,36): warning CS8602: Dereference of a possibly null reference. // CL1 z4 = x4 != null ? x4 : x4.M1(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(26, 36), // (44,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string z7 = y7 != null ? y7 : x7.M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y7 != null ? y7 : x7.M2()").WithLocation(44, 21) ); } [Fact] public void ConditionalBranching_07() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 x1, CL1? y1) { CL1 z1 = y1 == null ? x1 : y1; } void Test2(CL1? x2, CL1? y2) { CL1 z2 = y2 == null ? x2 : y2; } void Test3(CL1 x3, CL1? y3) { CL1 z3 = x3 == null ? y3 : x3; } void Test4(CL1? x4, CL1 y4) { x4 = y4; CL1 z4 = x4 == null ? x4.M1() : x4; } void Test5(CL1 x5) { const CL1? y5 = null; CL1 z5 = y5 == null ? x5 : y5; } void Test6(CL1 x6) { const string? y6 = """"; string z6 = y6 == null ? x6.M2() : y6; } void Test7(CL1 x7) { const string? y7 = null; string z7 = y7 == null ? x7.M2() : y7; } } class CL1 { public CL1 M1() { return new CL1(); } public string? M2() { return null; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = y2 == null ? x2 : y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2 == null ? x2 : y2").WithLocation(15, 18), // (20,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z3 = x3 == null ? y3 : x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3 == null ? y3 : x3").WithLocation(20, 18), // (26,31): warning CS8602: Dereference of a possibly null reference. // CL1 z4 = x4 == null ? x4.M1() : x4; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(26, 31), // (44,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string z7 = y7 == null ? x7.M2() : y7; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y7 == null ? x7.M2() : y7").WithLocation(44, 21) ); } [Fact] [WorkItem(26624, "https://github.com/dotnet/roslyn/issues/26624")] public void ConditionalBranching_08() { CSharpCompilation c = CreateCompilation(@" class C { bool Test1(CL1? x1) { if (x1?.P1 == true) { return x1.P2; } return x1.P2; // 1 } } class CL1 { public bool P1 { get { return true;} } public bool P2 { get { return true;} } } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (11,16): warning CS8602: Dereference of a possibly null reference. // return x1.P2; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 16) ); } [Fact] public void ConditionalBranching_09() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(object x1, object? y1) { y1 = x1; y1.ToString(); object z1 = y1 ?? x1; y1.ToString(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(13, 9)); } [Fact] public void ConditionalBranching_10() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(object x1, object? y1) { y1 = x1; y1.ToString(); object z1 = y1 != null ? y1 : x1; y1.ToString(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(13, 9) ); } [Fact] public void ConditionalBranching_11() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void Test1(object x1, object? y1) { y1 = x1; y1.ToString(); y1?.GetHashCode(); y1.ToString(); // 1 } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(9, 9) ); } [Fact] public void ConditionalBranching_12() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(object x1, object? y1) { y1 = x1; y1.ToString(); if (y1 == null) { System.Console.WriteLine(1); } else { System.Console.WriteLine(2); } y1.ToString(); // 1 } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (22,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(22, 9) ); } [Fact] public void ConditionalBranching_13() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(object x1, object? y1) { y1 = x1; y1.ToString(); if (y1 != null) { System.Console.WriteLine(1); } else { System.Console.WriteLine(2); } y1.ToString(); // 1 } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (22,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(22, 9) ); } [Fact] public void ConditionalBranching_14() { var compilation = CreateCompilation(new[] { @" class C { C? _cField = null; C _nonNullCField = new C(); C? GetC() => null; C? CProperty { get => null; } void Test1(C? c1) { if (c1?._cField != null) { c1._cField.ToString(); } else { c1._cField.ToString(); // warn 1 2 } } void Test2() { C? c2 = GetC(); if (c2?._cField != null) { c2._cField.ToString(); } else { c2._cField.ToString(); // warn 3 4 } } void Test3(C? c3) { if (c3?._cField?._cField != null) { c3._cField._cField.ToString(); } else if (c3?._cField != null) { c3._cField.ToString(); c3._cField._cField.ToString(); // warn 5 } else { c3.ToString(); // warn 6 } } void Test4(C? c4) { if (c4?._nonNullCField._cField?._nonNullCField._cField != null) { c4._nonNullCField._cField._nonNullCField._cField.ToString(); } else { c4._nonNullCField._cField._nonNullCField._cField.ToString(); // warn 7 8 9 } } void Test5(C? c5) { if (c5?._cField == null) { c5._cField.ToString(); // warn 10 11 } else { c5._cField.ToString(); } } void Test6(C? c6) { if (c6?._cField?.GetC() != null) { c6._cField.GetC().ToString(); // warn 12 } } void Test7(C? c7) { if (c7?._cField?.CProperty != null) { c7._cField.CProperty.ToString(); } } } " }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (17,13): warning CS8602: Dereference of a possibly null reference. // c1._cField.ToString(); // warn 1 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(17, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // c1._cField.ToString(); // warn 1 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1._cField").WithLocation(17, 13), // (30,13): warning CS8602: Dereference of a possibly null reference. // c2._cField.ToString(); // warn 3 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(30, 13), // (30,13): warning CS8602: Dereference of a possibly null reference. // c2._cField.ToString(); // warn 3 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2._cField").WithLocation(30, 13), // (43,13): warning CS8602: Dereference of a possibly null reference. // c3._cField._cField.ToString(); // warn 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c3._cField._cField").WithLocation(43, 13), // (47,13): warning CS8602: Dereference of a possibly null reference. // c3.ToString(); // warn 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c3").WithLocation(47, 13), // (59,13): warning CS8602: Dereference of a possibly null reference. // c4._nonNullCField._cField._nonNullCField._cField.ToString(); // warn 7 8 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c4").WithLocation(59, 13), // (59,13): warning CS8602: Dereference of a possibly null reference. // c4._nonNullCField._cField._nonNullCField._cField.ToString(); // warn 7 8 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c4._nonNullCField._cField").WithLocation(59, 13), // (59,13): warning CS8602: Dereference of a possibly null reference. // c4._nonNullCField._cField._nonNullCField._cField.ToString(); // warn 7 8 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c4._nonNullCField._cField._nonNullCField._cField").WithLocation(59, 13), // (67,13): warning CS8602: Dereference of a possibly null reference. // c5._cField.ToString(); // warn 10 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c5").WithLocation(67, 13), // (67,13): warning CS8602: Dereference of a possibly null reference. // c5._cField.ToString(); // warn 10 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c5._cField").WithLocation(67, 13), // (79,13): warning CS8602: Dereference of a possibly null reference. // c6._cField.GetC().ToString(); // warn 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c6._cField.GetC()").WithLocation(79, 13) ); } [Fact] public void ConditionalBranching_15() { var compilation = CreateCompilation(new[] { @" class C { void Test(C? c1) { if (c1?[0] != null) { c1.ToString(); c1[0].ToString(); // warn 1 } else { c1.ToString(); // warn 2 } } object? this[int i] { get => null; } } " }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // c1[0].ToString(); // warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1[0]").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // c1.ToString(); // warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(13, 13) ); } [Fact] public void ConditionalBranching_16() { var compilation = CreateCompilation(new[] { @" class C { void Test<T>(T t) { if (t?.ToString() != null) { t.ToString(); } else { t.ToString(); // warn } } }" }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(12, 13) ); } [Fact] public void ConditionalBranching_17() { var compilation = CreateCompilation(new[] { @" class C { object? Prop { get; } object? GetObj(bool val) => null; void Test(C? c1, C? c2) { if (c1?.GetObj(c2?.Prop != null) != null) { c2.Prop.ToString(); // warn 1 2 } } }" }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // c2.Prop.ToString(); // warn 1 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(10, 13), // (10,13): warning CS8602: Dereference of a possibly null reference. // c2.Prop.ToString(); // warn 1 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2.Prop").WithLocation(10, 13) ); } [Fact] public void ConditionalBranching_18() { var compilation = CreateCompilation(new[] { @" class C { void Test(C? x, C? y) { if ((x = y)?.GetHashCode() != null) { x.ToString(); y.ToString(); // warn } } }" }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 13) ); } [Fact] [WorkItem(26624, "https://github.com/dotnet/roslyn/issues/26624")] [WorkItem(39424, "https://github.com/dotnet/roslyn/issues/39424")] public void ConditionalBranching_19() { CSharpCompilation c = CreateCompilation(@" class C { void Test1(CL1? x1) { _ = x1?.P1 ?? false ? x1.P1 : x1.P1; // 1 _ = x1?.P1 ?? true ? x1.P1 // 2 : x1.P1; } } class CL1 { public bool P1 { get { return true; } } } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x1.P1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(8, 15), // (11,15): warning CS8602: Dereference of a possibly null reference. // ? x1.P1 // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 15)); } [Fact] [WorkItem(26624, "https://github.com/dotnet/roslyn/issues/26624")] public void ConditionalBranching_20() { CSharpCompilation c = CreateCompilation(@" class C { void Test1(CL1? x1) { _ = x1?.Next?.Next?.P1 ?? false ? x1.ToString() + x1.Next.Next.ToString() : x1.ToString(); // 1 _ = x1?.Next?.Next?.P1 ?? true ? x1.ToString() // 2 : x1.ToString() + x1.Next.Next.ToString(); } } class CL1 { public bool P1 { get { return true; } } public CL1? Next { get { return null; } } } ", options: WithNullableEnable()); c.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(8, 15), // (11,15): warning CS8602: Dereference of a possibly null reference. // ? x1.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 15)); } /// <remarks>Ported from <see cref="FlowTests.IfConditionalConstant" />.</remarks> [Theory] [InlineData("true", "false")] [InlineData("FIELD_TRUE", "FIELD_FALSE")] [InlineData("LOCAL_TRUE", "LOCAL_FALSE")] [InlineData("true || false", "true && false")] [InlineData("!false", "!true")] public void ConditionalConstant_01(string @true, string @false) { var source = @" #pragma warning disable 219 // The variable is assigned but its value is never used class C { const bool FIELD_TRUE = true; const bool FIELD_FALSE = false; static void M(bool b, object? x) { const bool LOCAL_TRUE = true; const bool LOCAL_FALSE = false; x = null; _ = (b ? x != null : " + @false + @") // `b && x != null` ? x.ToString() : x.ToString(); // 1 x = new object(); _ = (b ? x != null : " + @false + @") // `b && x != null` ? x.ToString() : x.ToString(); // 2 x = null; _ = (b ? x != null : " + @true + @") // `!b || x != null` ? x.ToString() // 3 : x.ToString(); // 4 x = new object(); _ = (b ? x != null : " + @true + @") // `!b || x != null` ? x.ToString() : x.ToString(); // 5 x = null; _ = (b ? " + @false + @" : x != null) // `!b && x != null` ? x.ToString() : x.ToString(); // 6 x = new object(); _ = (b ? " + @false + @" : x != null) // `!b && x != null` ? x.ToString() : x.ToString(); // 7 x = null; _ = (b ? " + @true + @" : x != null) // `b || x != null` ? x.ToString() // 8 : x.ToString(); // 9 x = new object(); _ = (b ? " + @true + @" : x != null) // `b || x != null` ? x.ToString() : x.ToString(); // 10 x = null; _ = !(b ? " + @true + @" : x != null) // `!(b || x != null)` -> `!b && x == null` ? x.ToString() // 11 : x.ToString(); // 12 x = new object(); _ = !(b ? " + @true + @" : x != null) // `!(b || x != null)` -> `!b && x == null` ? x.ToString() // 13 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 15), // (27,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(27, 15), // (28,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(28, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(33, 15), // (39,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(39, 15), // (44,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(44, 15), // (49,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(49, 15), // (50,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(50, 15), // (55,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(55, 15), // (60,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(60, 15), // (61,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(61, 15), // (65,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(65, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IfConditionalConstant" />.</remarks> [Theory] [InlineData("true", "false")] [InlineData("FIELD_TRUE", "FIELD_FALSE")] [InlineData("LOCAL_TRUE", "LOCAL_FALSE")] [InlineData("true || false", "true && false")] [InlineData("!false", "!true")] public void ConditionalConstant_02(string @true, string @false) { var source = @" #pragma warning disable 219 // The variable is assigned but its value is never used class C { const bool FIELD_TRUE = true; const bool FIELD_FALSE = false; static void M(bool b, object? x) { const bool LOCAL_TRUE = true; const bool LOCAL_FALSE = false; x = null; _ = (b ? x == null : " + @false + @") // `b && x == null` ? x.ToString() // 1 : x.ToString(); // 2 x = new object(); _ = (b ? x == null : " + @false + @") // `b && x == null` ? x.ToString() // 3 : x.ToString(); x = null; _ = (b ? x == null : " + @true + @") // `!b || x == null` ? x.ToString() // 4 : x.ToString(); x = new object(); _ = (b ? x == null : " + @true + @") // `!b || x == null` ? x.ToString() // 5 : x.ToString(); x = null; _ = (b ? " + @false + @" : x == null) // `!b && x == null` ? x.ToString() // 6 : x.ToString(); // 7 x = new object(); _ = (b ? " + @false + @" : x == null) // `!b && x == null` ? x.ToString() // 8 : x.ToString(); x = null; _ = !(b ? " + @false + @" : x == null) // `!(!b && x == null)` -> `b || x != null` ? x.ToString() // 9 : x.ToString(); // 10 x = new object(); _ = !(b ? " + @false + @" : x == null) // `!(!b && x == null)` -> `b || x != null` ? x.ToString() : x.ToString(); // 11 x = null; _ = (b ? " + @true + @" : x == null) // `b || x == null` ? x.ToString() // 12 : x.ToString(); x = new object(); _ = (b ? " + @true + @" : x == null) // `b || x == null` ? x.ToString() // 13 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (17,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (27,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(27, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(32, 15), // (38,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(38, 15), // (39,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(39, 15), // (43,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(43, 15), // (49,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(49, 15), // (50,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(50, 15), // (55,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(55, 15), // (60,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(60, 15), // (65,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(65, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IfConditional_ComplexCondition_ConstantConsequence" /></remarks> [Fact] public void IfConditional_ComplexCondition_ConstantConsequence() { var source = @" class C { bool M0(int x) => true; void M1(object? x) { _ = (x != null ? true : false) ? x.ToString() : x.ToString(); // 1 } void M2(object? x) { _ = (x != null ? false : true) ? x.ToString() // 2 : x.ToString(); } void M3(object? x) { _ = (x == null ? true : false) ? x.ToString() // 3 : x.ToString(); } void M4(object? x) { _ = (x == null ? false : true) ? x.ToString() : x.ToString(); // 4 } void M5(object? x) { _ = (!(x == null ? false : true)) ? x.ToString() // 5 : x.ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (23,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(23, 15), // (31,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(31, 15), // (37,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(37, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void EqualsCondAccess_NotNullWhenTrue_RightBoolConstant(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c) { _ = c?.M0(out var obj) == true ? obj.ToString() : obj.ToString(); // 1, 2 } static void M2(C? c) { _ = c?.M0(out var obj) == false ? obj.ToString() // 3 : obj.ToString(); // 4, 5 } static void M3(C? c) { _ = c?.M0(out var obj) != true ? obj.ToString() // 6, 7 : obj.ToString(); // 8 } static void M4(C? c) { _ = c?.M0(out var obj) != false ? obj.ToString() // 9, 10 : obj.ToString(); // 11 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (12,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 1, 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (19,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 4, 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 6, 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(25, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(26, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(32, 15), // (32,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 9, 10 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(32, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(33, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void EqualsCondAccess_NotNullWhenTrue_LeftBoolConstant(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c) { _ = true == c?.M0(out var obj) ? obj.ToString() : obj.ToString(); // 1, 2 } static void M2(C? c) { _ = false == c?.M0(out var obj) ? obj.ToString() // 3 : obj.ToString(); // 4, 5 } static void M3(C? c) { _ = true != c?.M0(out var obj) ? obj.ToString() // 6, 7 : obj.ToString(); // 8 } static void M4(C? c) { _ = false != c?.M0(out var obj) ? obj.ToString() // 9, 10 : obj.ToString(); // 11 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (12,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 1, 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (19,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 4, 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 6, 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(25, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(26, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(32, 15), // (32,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 9, 10 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(32, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(33, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void EqualsCondAccess_NotNullWhenTrue_RightBool(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, bool b) { _ = c?.M0(out var obj1) == b ? obj1.ToString() // 1 : """"; } static void M2(C? c, bool b) { _ = c?.M0(out var obj2) == b ? """" : obj2.ToString(); // 2, 3 } static void M3(C? c, bool b) { _ = c?.M0(out var obj3) != b ? obj3.ToString() // 4, 5 : """"; } static void M4(C? c, bool b) { _ = c?.M0(out var obj4) != b ? """" : obj4.ToString(); // 6 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(11, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(19, 15), // (19,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 2, 3 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj3.ToString() // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj3").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj3' // ? obj3.ToString() // 4, 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj3").WithArguments("obj3").WithLocation(25, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj4").WithLocation(33, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void EqualsCondAccess_NotNullWhenTrue_LeftBool(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, bool b) { _ = b == c?.M0(out var obj1) ? obj1.ToString() // 1 : """"; } static void M2(C? c, bool b) { _ = b == c?.M0(out var obj2) ? """" : obj2.ToString(); // 2, 3 } static void M3(C? c, bool b) { _ = b != c?.M0(out var obj3) ? obj3.ToString() // 4, 5 : """"; } static void M4(C? c, bool b) { _ = b != c?.M0(out var obj4) ? """" : obj4.ToString(); // 6 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(11, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(19, 15), // (19,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 2, 3 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj3.ToString() // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj3").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj3' // ? obj3.ToString() // 4, 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj3").WithArguments("obj3").WithLocation(25, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj4").WithLocation(33, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void EqualsCondAccess_NotNullWhenTrue_RightNullableBool(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c) { _ = c?.M0(out var obj) == null ? obj.ToString() // 1, 2 : obj.ToString(); // 3 } static void M2(C? c) { _ = c?.M0(out var obj) != null ? obj.ToString() // 4 : obj.ToString(); // 5, 6 } static void M3(C? c, bool? b) { _ = c?.M0(out var obj1) == b ? obj1.ToString() // 7, 8 : """"; // 9, 10 _ = c?.M0(out var obj2) == b ? """" // 7, 8 : obj2.ToString(); // 9, 10 } static void M4(C? c, bool? b) { _ = c?.M0(out var obj1) != b ? obj1.ToString() // 11, 12 : """"; // 9, 10 _ = c?.M0(out var obj2) != b ? """" // 7, 8 : obj2.ToString(); // 13, 14 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (11,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 1, 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 5, 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (19,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 5, 6 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 7, 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj1' // ? obj1.ToString() // 7, 8 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(25, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(30, 15), // (30,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 9, 10 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(30, 15), // (36,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 11, 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(36, 15), // (36,15): error CS0165: Use of unassigned local variable 'obj1' // ? obj1.ToString() // 11, 12 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(36, 15), // (41,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 13, 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(41, 15), // (41,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 13, 14 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(41, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void EqualsCondAccess_NotNullWhenTrue_LeftNullableBool(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c) { _ = null == c?.M0(out var obj) ? obj.ToString() // 1, 2 : obj.ToString(); // 3 } static void M2(C? c) { _ = null != c?.M0(out var obj) ? obj.ToString() // 4 : obj.ToString(); // 5, 6 } static void M3(C? c, bool? b) { _ = b == c?.M0(out var obj1) ? obj1.ToString() // 7, 8 : """"; // 9, 10 _ = b == c?.M0(out var obj2) ? """" // 7, 8 : obj2.ToString(); // 9, 10 } static void M4(C? c, bool? b) { _ = b != c?.M0(out var obj1) ? obj1.ToString() // 11, 12 : """"; // 9, 10 _ = b != c?.M0(out var obj2) ? """" // 7, 8 : obj2.ToString(); // 13, 14 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (11,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 1, 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 5, 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (19,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 5, 6 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 7, 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj1' // ? obj1.ToString() // 7, 8 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(25, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(30, 15), // (30,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 9, 10 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(30, 15), // (36,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 11, 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(36, 15), // (36,15): error CS0165: Use of unassigned local variable 'obj1' // ? obj1.ToString() // 11, 12 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(36, 15), // (41,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 13, 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(41, 15), // (41,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 13, 14 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(41, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_01"/>.</remarks> [Theory] [InlineData("b")] [InlineData("true")] [InlineData("false")] public void EqualsCondAccess_01(string operand) { var source = @" class C { public bool M0(out object x) { x = 42; return true; } public void M1(C? c, object? x, bool b) { _ = c?.M0(out x) == " + operand + @" ? x.ToString() : x.ToString(); // 1 } public void M2(C? c, object? x, bool b) { _ = c?.M0(out x) != " + operand + @" ? x.ToString() // 2 : x.ToString(); } public void M3(C? c, object? x, bool b) { _ = " + operand + @" == c?.M0(out x) ? x.ToString() : x.ToString(); // 3 } public void M4(C? c, object? x, bool b) { _ = " + operand + @" != c?.M0(out x) ? x.ToString() // 4 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(30, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_02"/>.</remarks> [Theory] [InlineData("i")] [InlineData("42")] public void EqualsCondAccess_02(string operand) { var source = @" class C { public int M0(out object x) { x = 1; return 0; } public void M1(C? c, object? x, int i) { _ = c?.M0(out x) == " + operand + @" ? x.ToString() : x.ToString(); // 1 } public void M2(C? c, object? x, int i) { _ = c?.M0(out x) != " + operand + @" ? x.ToString() // 2 : x.ToString(); } public void M3(C? c, object? x, int i) { _ = " + operand + @" == c?.M0(out x) ? x.ToString() : x.ToString(); // 3 } public void M4(C? c, object? x, int i) { _ = " + operand + @" != c?.M0(out x) ? x.ToString() // 4 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(30, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_03"/>.</remarks> [Theory] [InlineData("object?")] [InlineData("int?")] [InlineData("bool?")] public void EqualsCondAccess_03(string returnType) { var source = @" class C { public " + returnType + @" M0(out object x) { x = 42; return null; } public void M1(C? c, object? x) { _ = c?.M0(out x) != null ? x.ToString() : x.ToString(); // 1 } public void M2(C? c, object? x) { _ = c?.M0(out x) == null ? x.ToString() // 2 : x.ToString(); } public void M3(C? c, object? x) { _ = null != c?.M0(out x) ? x.ToString() : x.ToString(); // 3 } public void M4(C? c, object? x) { _ = null == c?.M0(out x) ? x.ToString() // 4 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(30, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_04"/>.</remarks> [Theory] [InlineData("bool", "false")] [InlineData("int", "1")] [InlineData("object", "1")] public void EqualsCondAccess_04_01(string returnType, string returnValue) { var source = @" class C { public " + returnType + @" M0(out object x) { x = 42; return " + returnValue + @"; } public void M1(C? c, object? x, object? y) { _ = c?.M0(out x) == c!.M0(out y) ? x.ToString() + y.ToString() : x.ToString() + y.ToString(); // 1 } public void M2(C? c, object? x, object? y) { _ = c?.M0(out x) != c!.M0(out y) ? x.ToString() + y.ToString() // 2 : x.ToString() + y.ToString(); } public void M3(C? c, object? x, object? y) { _ = c!.M0(out x) == c?.M0(out y) ? x.ToString() + y.ToString() : x.ToString() + y.ToString(); // 3 } public void M4(C? c, object? x, object? y) { _ = c!.M0(out x) != c?.M0(out y) ? x.ToString() + y.ToString() // 4 : x.ToString() + y.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (24,30): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(24, 30), // (30,30): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(30, 30) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_04"/>.</remarks> [Fact] public void EqualsCondAccess_04_02() { var source = @" class C { public object? M0(out object x) { x = 42; return null; } public void M1(C? c, object? x, object? y) { _ = c?.M0(out x) == c!.M0(out y) ? x.ToString() + y.ToString() // 1 : x.ToString() + y.ToString(); // 2 } public void M2(C? c, object? x, object? y) { _ = c?.M0(out x) != c!.M0(out y) ? x.ToString() + y.ToString() // 3 : x.ToString() + y.ToString(); // 4 } public void M3(C? c, object? x, object? y) { _ = c!.M0(out x) == c?.M0(out y) ? x.ToString() + y.ToString() // 5 : x.ToString() + y.ToString(); // 6 } public void M4(C? c, object? x, object? y) { _ = c!.M0(out x) != c?.M0(out y) ? x.ToString() + y.ToString() // 7 : x.ToString() + y.ToString(); // 8 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15), // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (17,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 15), // (23,30): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(23, 30), // (24,30): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(24, 30), // (30,30): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(30, 30), // (31,30): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(31, 30) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_04"/>.</remarks> [Fact] public void EqualsCondAccess_04_03() { var source = @" class C { public object M0(object? x) => new object(); public void M1(C? c, object? x) { _ = c?.M0(x = null) == c!.M0(x = new object()) ? x.ToString() : x.ToString(); } public void M2(C? c, object? x) { _ = c?.M0(x = new object()) != c!.M0(x = null) ? x.ToString() // 1 : x.ToString(); // 2 } public void M3(C? c, object? x) { _ = c!.M0(x = new object()) != c?.M0(x = null) ? x.ToString() // 3 : x.ToString(); // 4 } public void M4(C? c, object? x) { _ = c!.M0(x = null) != c?.M0(x = new object()) ? x.ToString() // 5 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (17,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 15), // (23,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(23, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(30, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_04"/>.</remarks> [Fact] public void EqualsCondAccess_04_04() { var source = @" class C { public object M0(object? x) => new object(); public void M1(C? c, object? x, object? y) { _ = c?.M0(x = new object()) == c!.M0(y = x) ? y.ToString() : y.ToString(); // 1 } public void M2(C? c, object? x, object? y) { _ = c?.M0(x = new object()) != c!.M0(y = x) ? y.ToString() // 2 : y.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? y.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(16, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_05"/>.</remarks> [Fact] public void EqualsCondAccess_05() { var source = @" class C { public static bool operator ==(C? left, C? right) => false; public static bool operator !=(C? left, C? right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public C? M0(out object x) { x = 42; return this; } public void M1(C? c, object? x) { _ = c?.M0(out x) != null ? x.ToString() : x.ToString(); // 1 } public void M2(C? c, object? x) { _ = c?.M0(out x) == null ? x.ToString() // 2 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_06"/>.</remarks> [Fact] public void EqualsCondAccess_06() { var source = @" class C { public C? M0(out object x) { x = 42; return this; } public void M1(C c, object? x, object? y) { _ = c.M0(out x)?.M0(out y) != null ? x.ToString() + y.ToString() : x.ToString() + y.ToString(); // 1 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,30): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(10, 30) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_07"/>.</remarks> [Fact] public void EqualsCondAccess_07() { var source = @" struct S { public static bool operator ==(S left, S right) => false; public static bool operator !=(S left, S right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public S M0(out object x) { x = 42; return this; } public void M1(S? s, object? x) { _ = s?.M0(out x) != null ? x.ToString() : x.ToString(); // 1 } public void M2(S? s, object? x) { _ = s?.M0(out x) == null ? x.ToString() // 2 : x.ToString(); } public void M3(S? s, object? x) { _ = null != s?.M0(out x) ? x.ToString() : x.ToString(); // 3 } public void M4(S? s, object? x) { _ = null == s?.M0(out x) ? x.ToString() // 4 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (29,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(29, 15), // (35,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(35, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_08"/>.</remarks> [Fact] public void EqualsCondAccess_08() { var source = @" #nullable enable struct S { public static bool operator ==(S left, S right) => false; public static bool operator !=(S left, S right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public S M0(out object x) { x = 42; return this; } public void M1(S? s, object? x) { _ = s?.M0(out x) != new S() ? x.ToString() // 1 : x.ToString(); } public void M2(S? s, object? x) { _ = s?.M0(out x) == new S() ? x.ToString() : x.ToString(); // 2 } public void M3(S? s, object? x) { _ = new S() != s?.M0(out x) ? x.ToString() // 3 : x.ToString(); } public void M4(S? s, object? x) { _ = new S() == s?.M0(out x) ? x.ToString() : x.ToString(); // 4 } } "; CreateCompilation(source).VerifyDiagnostics( // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(30, 15), // (38,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(38, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_09"/>.</remarks> [Fact] public void EqualsCondAccess_09() { var source = @" struct S { public static bool operator ==(S left, S right) => false; public static bool operator !=(S left, S right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public S M0(out object x) { x = 42; return this; } public void M1(S? s, object? x) { _ = s?.M0(out x) != s ? x.ToString() // 1 : x.ToString(); // 2 } public void M2(S? s, object? x) { _ = s?.M0(out x) == s ? x.ToString() // 3 : x.ToString(); // 4 } public void M3(S? s, object? x) { _ = s != s?.M0(out x) ? x.ToString() // 5 : x.ToString(); // 6 } public void M4(S? s, object? x) { _ = s == s?.M0(out x) ? x.ToString() // 7 : x.ToString(); // 8 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (14,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 15), // (28,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(28, 15), // (29,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(29, 15), // (35,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(35, 15), // (36,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(36, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_10"/>.</remarks> [Theory] [InlineData("S? left, S? right")] [InlineData("S? left, S right")] public void EqualsCondAccess_10(string operatorParameters) { var source = @" struct S { public static bool operator ==(" + operatorParameters + @") => false; public static bool operator !=(" + operatorParameters + @") => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public S M0(out object x) { x = 42; return this; } public void M1(S? s, object? x) { _ = s?.M0(out x) != new S() ? x.ToString() // 1 : x.ToString(); } public void M2(S? s, object? x) { _ = s?.M0(out x) == new S() ? x.ToString() : x.ToString(); // 2 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (14,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_11"/>.</remarks> [Fact] public void EqualsCondAccess_11() { var source = @" struct T { public static implicit operator S(T t) => new S(); public T M0(out object x) { x = 42; return this; } } struct S { public static bool operator ==(S left, S right) => false; public static bool operator !=(S left, S right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public void M1(T? t, object? x) { _ = t?.M0(out x) != new S() ? x.ToString() // 1 : x.ToString(); } public void M2(T? t, object? x) { _ = t?.M0(out x) == new S() ? x.ToString() : x.ToString(); // 2 } public void M3(T? t, object? x) { _ = new S() != t?.M0(out x) ? x.ToString() // 3 : x.ToString(); } public void M4(T? t, object? x) { _ = new S() == t?.M0(out x) ? x.ToString() : x.ToString(); // 4 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (18,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(18, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(26, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(32, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(40, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_12"/>.</remarks> [Fact] public void EqualsCondAccess_12() { var source = @" class C { int? M0(object obj) => null; void M1(C? c, object? x, object? obj) { _ = (c?.M0(x = 0) == (int?)obj) ? x.ToString() // 1 : x.ToString(); // 2 } void M2(C? c, object? x, object? obj) { _ = (c?.M0(x = 0) == (int?)null) ? x.ToString() // 3 : x.ToString(); } void M3(C? c, object? x, object? obj) { _ = (c?.M0(x = 0) == null) ? x.ToString() // 4 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15), // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (23,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(23, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_13"/>.</remarks> [Fact] public void EqualsCondAccess_13() { var source = @" class C { long? M0(object obj) => null; void M(C? c, object? x, int i) { _ = (c?.M0(x = 0) == i) ? x.ToString() : x.ToString(); // 1 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_14"/>.</remarks> [Fact] public void EqualsCondAccess_14() { var source = @" using System.Diagnostics.CodeAnalysis; class C { long? M0(object obj) => null; void M1(C? c, object? x, int? i) { _ = (c?.M0(x = 0) == i) ? x.ToString() // 1 : x.ToString(); // 2 } void M2(C? c, object? x, int? i) { if (i is null) throw null!; _ = (c?.M0(x = 0) == i) ? x.ToString() : x.ToString(); // 3 } void M3(C? c, object? x, [DisallowNull] int? i) { _ = (c?.M0(x = 0) == i) ? x.ToString() : x.ToString(); // 4 } } "; CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }).VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (28,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(28, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_15"/>.</remarks> [Fact] public void EqualsCondAccess_15() { var source = @" class C { C M0(object obj) => this; void M(C? c, object? x) { _ = ((object?)c?.M0(x = 0) != null) ? x.ToString() : x.ToString(); // 1 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_16"/>.</remarks> [Fact] public void EqualsCondAccess_16() { var source = @" class C { void M(object? x) { _ = ""a""?.Equals(x = 0) == true ? x.ToString() : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_17"/>.</remarks> [Fact] public void EqualsCondAccess_17() { var source = @" class C { void M(C? c, object? x, object? y) { _ = (c?.Equals(x = 0), c?.Equals(y = 0)) == (true, true) ? x.ToString() // 1 : y.ToString(); // 2 } } "; // https://github.com/dotnet/roslyn/issues/50980 CreateNullableCompilation(source).VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 15), // (8,15): warning CS8602: Dereference of a possibly null reference. // : y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(8, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_18"/>.</remarks> [Fact] public void EqualsCondAccess_18() { var source = @" class C { public static bool operator ==(C? left, C? right) => false; public static bool operator !=(C? left, C? right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public C M0(out object x) { x = 42; return this; } public void M1(C? c, object? x) { _ = c?.M0(out x) != null ? x.ToString() : x.ToString(); // 1 } public void M2(C? c, object? x) { _ = c?.M0(out x) == null ? x.ToString() // 2 : x.ToString(); } public void M3(C? c, object? x) { _ = null != c?.M0(out x) ? x.ToString() : x.ToString(); // 3 } public void M4(C? c, object? x) { _ = null == c?.M0(out x) ? x.ToString() // 4 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (29,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(29, 15), // (35,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(35, 15) ); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_19"/>.</remarks> [Fact] public void EqualsCondAccess_19() { var source = @" class C { public string M0(object obj) => obj.ToString(); public void M1(C? c, object? x, object? y) { _ = c?.M0(x = y = 1) != x.ToString() // 1 ? y.ToString() // 2 : y.ToString(); } public void M2(C? c, object? x, object? y) { _ = x.ToString() != c?.M0(x = y = 1) // 3 ? y.ToString() // 4 : y.ToString(); } public void M3(C? c, string? x) { _ = c?.M0(x = ""a"") != x ? x.ToString() // 5 : x.ToString(); // 6 } public void M4(C? c, string? x) { _ = x != c?.M0(x = ""a"") ? x.ToString() // 7 : x.ToString(); // 8 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (8,33): warning CS8602: Dereference of a possibly null reference. // _ = c?.M0(x = y = 1) != x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 33), // (9,15): warning CS8602: Dereference of a possibly null reference. // ? y.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 15), // (15,13): warning CS8602: Dereference of a possibly null reference. // _ = x.ToString() != c?.M0(x = y = 1) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 13), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? y.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(16, 15), // (23,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(23, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(30, 15), // (31,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(31, 15) ); } [Fact] public void EqualsBoolConstant_UserDefinedOperator_BoolRight() { var source = @" class C { public static bool operator ==(C? left, bool right) => false; public static bool operator !=(C? left, bool right) => false; public override bool Equals(object obj) => false; public override int GetHashCode() => 0; public void M1(C? c, object? x) { _ = c == (x != null) ? x.ToString() // 1 : x.ToString(); // 2 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 15), // (13,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_01"/>.</remarks> [Fact] public void IsCondAccess_01() { var source = @" class C { C M0(object obj) => this; void M1(C? c, object? x) { _ = c?.M0(x = 0) is C ? x.ToString() : x.ToString(); // 1 } void M2(C? c, object? x) { _ = c?.Equals(x = 0) is bool ? x.ToString() : x.ToString(); // 2 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (17,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_02"/>.</remarks> [Fact] public void IsCondAccess_02() { var source = @" class C { C M0(object obj) => this; void M1(C? c, object? x) { _ = c?.M0(x = 0) is (_) ? x.ToString() // 1 : x.ToString(); // unreachable } void M2(C? c, object? x) { _ = c?.M0(x = 0) is var y ? x.ToString() // 2 : x.ToString(); // unreachable } void M3(C? c, object? x) { _ = c?.M0(x = 0) is { } ? x.ToString() : x.ToString(); // 3 } void M4(C? c, object? x) { _ = c?.M0(x = 0) is { } c1 ? x.ToString() : x.ToString(); // 4 } void M5(C? c, object? x) { _ = c?.M0(x = 0) is C c1 ? x.ToString() : x.ToString(); // 5 } void M6(C? c, object? x) { _ = c?.M0(x = 0) is not null ? x.ToString() : x.ToString(); // 6 } void M7(C? c, object? x) { _ = c?.M0(x = 0) is not C ? x.ToString() // 7 : x.ToString(); } void M8(C? c, object? x) { _ = c?.M0(x = 0) is null ? x.ToString() // 8 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (31,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(31, 15), // (38,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(38, 15), // (45,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(45, 15), // (51,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(51, 15), // (58,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(58, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_03"/>.</remarks> [Fact] public void IsCondAccess_03() { var source = @" #nullable enable class C { (C, C) M0(object obj) => (this, this); void M1(C? c, object? x) { _ = c?.M0(x = 0) is (_, _) ? x.ToString() : x.ToString(); // 1 } void M2(C? c, object? x) { _ = c?.M0(x = 0) is not null ? x.ToString() : x.ToString(); // 2 } void M3(C? c, object? x) { _ = c?.M0(x = 0) is (not null, null) ? x.ToString() : x.ToString(); // 3 } void M4(C? c, object? x) { _ = c?.M0(x = 0) is null ? x.ToString() // 4 : x.ToString(); } void M5(C? c, object? x, object? y) { _ = (c?.M0(x = 0), c?.M0(y = 0)) is (not null, not null) ? x.ToString() // 5 : y.ToString(); // 6 } } "; // note: "state when not null" is not tracked when pattern matching against tuples containing conditional accesses. CreateCompilation(source).VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(19, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(26, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(32, 15), // (39,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(39, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : y.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(40, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_04"/>.</remarks> [Fact] public void IsCondAccess_04() { var source = @" #pragma warning disable 8794 // An expression always matches the provided pattern class C { C M0(object obj) => this; void M1(C? c, object? x) { _ = c?.M0(x = 0) is null or not null ? x.ToString() // 1 : x.ToString(); // unreachable } void M2(C? c, object? x) { _ = c?.M0(x = 0) is C or null ? x.ToString() // 2 : x.ToString(); // unreachable } void M3(C? c, object? x) { _ = c?.M0(x = 0) is not null and C ? x.ToString() : x.ToString(); // 3 } void M4(C? c, object? x) { _ = c?.M0(x = 0) is null ? x.ToString() // 4 : x.ToString(); } void M5(C? c, object? x) { _ = c?.M0(x = 0) is not (C or { }) ? x.ToString() // 5 : x.ToString(); } void M6(C? c, object? x) { _ = c?.M0(x = 0) is _ and C ? x.ToString() : x.ToString(); // 6 } void M7(C? c, object? x) { _ = c?.M0(x = 0) is C and _ ? x.ToString() : x.ToString(); // 7 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(18, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(26, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(32, 15), // (39,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(39, 15), // (47,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(47, 15), // (54,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(54, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_05"/>.</remarks> [Theory] [InlineData("int")] [InlineData("int?")] public void IsCondAccess_05(string returnType) { var source = @" class C { " + returnType + @" M0(object obj) => 1; void M1(C? c, object? x) { _ = c?.M0(x = 0) is 1 ? x.ToString() : x.ToString(); // 1 } void M2(C? c, object? x) { _ = c?.M0(x = 0) is > 10 ? x.ToString() : x.ToString(); // 2 } void M3(C? c, object? x) { _ = c?.M0(x = 0) is > 10 or < 0 ? x.ToString() : x.ToString(); // 3 } void M4(C? c, object? x) { _ = c?.M0(x = 0) is 1 or 2 ? x.ToString() : x.ToString(); // 4 } void M5(C? c, object? x) { _ = c?.M0(x = 0) is null ? x.ToString() // 5 : x.ToString(); } void M6(C? c, object? x) { _ = c?.M0(x = 0) is not null ? x.ToString() : x.ToString(); // 6 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (17,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 15), // (24,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 15), // (31,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(31, 15), // (37,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(37, 15), // (45,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(45, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_06"/>.</remarks> [Fact] public void IsCondAccess_06() { var source = @" class C { int M0(object obj) => 1; void M1(C? c, object? x) { _ = c?.M0(x = 0) is not null is true ? x.ToString() : x.ToString(); // 1 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_07"/>.</remarks> [Fact] public void IsCondAccess_07() { var source = @" class C { bool M0(object obj) => false; void M1(C? c, object? x) { _ = c?.M0(x = 0) is true or false ? x.ToString() : x.ToString(); // 1 } void M2(C? c, object? x) { _ = c?.M0(x = 0) is not (true or false) ? x.ToString() // 2 : x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_08"/>.</remarks> [Fact] public void IsCondAccess_08() { var source = @" #nullable enable class C { bool M0(object obj) => false; void M1(C? c, object? x) { _ = c?.M0(x = 0) is null or false ? x.ToString() // 1 : x.ToString(); } void M2(C? c, object? x) { _ = c?.M0(x = 0) is not (true or null) ? x.ToString() : x.ToString(); // 2 } } "; CreateCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(18, 15) ); } /// <remarks>Ported from <see cref="FlowTests.IsCondAccess_09"/>.</remarks> [Fact] public void IsCondAccess_09() { var source = @" #nullable enable class C { bool M0(object obj) => false; void M1(C? c, object? x) { _ = c?.M0(x = 0) is var z ? x.ToString() // 1 : x.ToString(); // unreachable } } "; CreateCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 15) ); } [Fact] public void IsCondAccess_10() { var source = @" #nullable enable class C { object M0() => """"; void M1(C? c) { _ = c?.M0() is { } z ? z.ToString() : z.ToString(); // 1 } void M2(C? c) { _ = c?.M0() is """" and { } z ? z.ToString() : z.ToString(); // 2 } void M3(C? c) { _ = (string?)c?.M0() is 42 and { } z // 3 ? z.ToString() : z.ToString(); // 4 } void M4(C? c) { _ = c?.M0() is string z ? z.ToString() : z.ToString(); // 5 } } "; CreateCompilation(source).VerifyDiagnostics( // (11,15): error CS0165: Use of unassigned local variable 'z' // : z.ToString(); // 1 Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(11, 15), // (18,15): error CS0165: Use of unassigned local variable 'z' // : z.ToString(); // 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(18, 15), // (23,33): error CS0029: Cannot implicitly convert type 'int' to 'string' // _ = (string?)c?.M0() is 42 and { } z // 3 Diagnostic(ErrorCode.ERR_NoImplicitConv, "42").WithArguments("int", "string").WithLocation(23, 33), // (25,15): error CS0165: Use of unassigned local variable 'z' // : z.ToString(); // 4 Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(25, 15), // (32,15): error CS0165: Use of unassigned local variable 'z' // : z.ToString(); // 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "z").WithArguments("z").WithLocation(32, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void IsCondAccess_NotNullWhenTrue_01(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) is true ? obj.ToString() : obj.ToString(); // 1 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) is false ? obj.ToString() // 2 : obj.ToString(); // 3 } static void M3(C? c, object? obj) { _ = c?.M0(out obj) is not true // `is null or false` ? obj.ToString() // 4 : obj.ToString(); // 5 } static void M4(C? c, object? obj) { _ = c?.M0(out obj) is not false // `is null or true` ? obj.ToString() // 6 : obj.ToString(); // 7 } static void M5(C? c, object? obj) { _ = c?.M0(out obj) is not (true or null) // `is false` ? obj.ToString() // 8 : obj.ToString(); // 9 } static void M6(C? c, object? obj) { _ = c?.M0(out obj) is not (false or null) // `is true` ? obj.ToString() : obj.ToString(); // 10 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(25, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(32, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(33, 15), // (39,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(39, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(40, 15), // (47,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(47, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void IsCondAccess_NotNullWhenTrue_02(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) is true and 1 // 1 ? obj.ToString() // 2 : obj.ToString(); // 3 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) is true and var x ? obj.ToString() : obj.ToString(); // 4 } static void M3(C? c, object? obj) { _ = c?.M0(out obj) is _ and true ? obj.ToString() : obj.ToString(); // 5 } static void M4(C? c, object? obj) { _ = c?.M0(out obj) is true and bool b ? obj.ToString() : obj.ToString(); // 6 } static void M5(C? c, object? obj) { _ = c?.M0(out obj) is bool and true ? obj.ToString() : obj.ToString(); // 7 } static void M6(C? c, object? obj) { _ = c?.M0(out obj) is { } and true ? obj.ToString() : obj.ToString(); // 8 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (10,40): error CS0029: Cannot implicitly convert type 'int' to 'bool' // _ = c?.M0(out obj) is true and 1 // 1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool").WithLocation(10, 40), // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(26, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(33, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(40, 15), // (47,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(47, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void IsCondAccess_NotNullWhenTrue_03(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) is true or 1 // 1 ? obj.ToString() // 2 : obj.ToString(); // 3 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) is true or var x // 4, 5 ? obj.ToString() // 6 : obj.ToString(); // unreachable } static void M3(C? c, object? obj) { _ = c?.M0(out obj) is _ or true // 7 ? obj.ToString() // 8 : obj.ToString(); // unreachable } static void M4(C? c, object? obj) { _ = c?.M0(out obj) is true or bool b // 9 ? obj.ToString() // 10 : obj.ToString(); // 11 } static void M5(C? c, object? obj) { _ = c?.M0(out obj) is bool or true ? obj.ToString() // 12 : obj.ToString(); // 13 } static void M6(C? c, object? obj) { _ = c?.M0(out obj) is { } or true ? obj.ToString() // 14 : obj.ToString(); // 15 } static void M7(C? c, object? obj) { _ = c?.M0(out obj) is true or false ? obj.ToString() // 16 : obj.ToString(); // 17 } static void M8(C? c, object? obj) { _ = c?.M0(out obj) is null ? obj.ToString() // 18 : obj.ToString(); // 19 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (10,39): error CS0029: Cannot implicitly convert type 'int' to 'bool?' // _ = c?.M0(out obj) is true or 1 // 1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "1").WithArguments("int", "bool?").WithLocation(10, 39), // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (17,13): warning CS8794: An expression of type 'bool?' always matches the provided pattern. // _ = c?.M0(out obj) is true or var x // 4, 5 Diagnostic(ErrorCode.WRN_IsPatternAlways, "c?.M0(out obj) is true or var x").WithArguments("bool?").WithLocation(17, 13), // (17,43): error CS8780: A variable may not be declared within a 'not' or 'or' pattern. // _ = c?.M0(out obj) is true or var x // 4, 5 Diagnostic(ErrorCode.ERR_DesignatorBeneathPatternCombinator, "x").WithLocation(17, 43), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (24,13): warning CS8794: An expression of type 'bool?' always matches the provided pattern. // _ = c?.M0(out obj) is _ or true // 7 Diagnostic(ErrorCode.WRN_IsPatternAlways, "c?.M0(out obj) is _ or true").WithArguments("bool?").WithLocation(24, 13), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(25, 15), // (31,44): error CS8780: A variable may not be declared within a 'not' or 'or' pattern. // _ = c?.M0(out obj) is true or bool b // 9 Diagnostic(ErrorCode.ERR_DesignatorBeneathPatternCombinator, "b").WithLocation(31, 44), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(32, 15), // (33,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(33, 15), // (39,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(39, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(40, 15), // (46,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(46, 15), // (47,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 15 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(47, 15), // (53,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 16 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(53, 15), // (54,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 17 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(54, 15), // (60,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 18 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(60, 15), // (61,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 19 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(61, 15) ); } [Theory] [InlineData("[NotNullWhen(false)] out object? obj")] [InlineData("[MaybeNullWhen(true)] out object obj")] public void IsCondAccess_NotNullWhenFalse(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) is true ? obj.ToString() // 1 : obj.ToString(); // 2 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) is false ? obj.ToString() : obj.ToString(); // 3 } static void M3(C? c, object? obj) { _ = c?.M0(out obj) is not true // `is null or false` ? obj.ToString() // 4 : obj.ToString(); // 5 } static void M4(C? c, object? obj) { _ = c?.M0(out obj) is not false // `is null or true` ? obj.ToString() // 6 : obj.ToString(); } static void M5(C? c, object? obj) { _ = c?.M0(out obj) is not (true or null) // `is false` ? obj.ToString() : obj.ToString(); // 7 } static void M6(C? c, object? obj) { _ = c?.M0(out obj) is not (false or null) // `is true` ? obj.ToString() // 8 : obj.ToString(); // 9 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(25, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(26, 15), // (32,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(32, 15), // (40,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(40, 15), // (46,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(46, 15), // (47,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(47, 15) ); } [Fact] public void IsPattern_LeftConditionalState() { var source = @" class C { void M(object? obj) { _ = (obj != null) is true ? obj.ToString() : obj.ToString(); // 1 } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(8, 15)); } [Fact, WorkItem(53308, "https://github.com/dotnet/roslyn/issues/53308")] public void IsPattern_LeftCondAccess_PropertyPattern_01() { var source = @" class Program { void M1(B? b) { if (b is { C: { Prop: { } } }) { b.C.Prop.ToString(); } } void M2(B? b) { if (b?.C is { Prop: { } }) { b.C.Prop.ToString(); // 1 } } } class B { public C? C { get; set; } } class C { public string? Prop { get; set; } }"; // Ideally we would not issue diagnostic (1). // However, additional work is needed in nullable pattern analysis to make this work. var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (16,13): warning CS8602: Dereference of a possibly null reference. // b.C.Prop.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.C.Prop").WithLocation(16, 13)); } /// <remarks>Ported from <see cref="FlowTests.EqualsCondAccess_LeftCondAccess"/>.</remarks> [Fact] public void EqualsCondAccess_LeftCondAccess() { var source = @" class C { public C M0(object x) => this; public void M1(C? c, object? x, object? y) { _ = (c?.M0(x = 1))?.M0(y = 1) != null ? c.ToString() + x.ToString() + y.ToString() : c.ToString() + x.ToString() + y.ToString(); // 1, 2, 3 } public void M2(C? c, object? x, object? y, object? z) { _ = (c?.M0(x = 1)?.M0(y = 1))?.M0(z = 1) != null ? c.ToString() + x.ToString() + y.ToString() + z.ToString() : c.ToString() + x.ToString() + y.ToString() + z.ToString(); // 4, 5, 6, 7 } public void M3(C? c, object? x, object? y) { _ = ((object?)c?.M0(x = 1))?.Equals(y = 1) != null ? c.ToString() + x.ToString() + y.ToString() : c.ToString() + x.ToString() + y.ToString(); // 8, 9, 10 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString(); // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(10, 15), // (10,30): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString(); // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 30), // (10,45): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString(); // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(10, 45), // (17,15): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString() + z.ToString(); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(17, 15), // (17,30): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString() + z.ToString(); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 30), // (17,45): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString() + z.ToString(); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(17, 45), // (17,60): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString() + z.ToString(); // 4, 5, 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(17, 60), // (24,15): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString(); // 8, 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(24, 15), // (24,30): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString(); // 8, 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(24, 30), // (24,45): warning CS8602: Dereference of a possibly null reference. // : c.ToString() + x.ToString() + y.ToString(); // 8, 9, 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(24, 45) ); } [Fact] public void ConditionalOperator_OperandConditionalState() { var source = @" class C { void M1(object? x, bool b) { _ = (b ? x != null : x != null) ? x.ToString() : x.ToString(); // 1 } void M2(object? x, bool b) { _ = (b ? x != null : x == null) ? x.ToString() // 2 : x.ToString(); // 3 } void M3(object? x, bool b) { _ = (b ? x == null : x != null) ? x.ToString() // 4 : x.ToString(); // 5 } void M4(object? x, bool b) { _ = (b ? x == null : x == null) ? x.ToString() // 6 : x.ToString(); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (14,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 15), // (28,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(28, 15)); } [Fact] public void ConditionalOperator_OperandUnreachable() { var source = @" class C { void M1(object? x, bool b) { _ = (b ? x != null : throw null!) ? x.ToString() : x.ToString(); // 1 } void M2(object? x, bool b) { _ = (b ? throw null! : x == null) ? x.ToString() // 2 : x.ToString(); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (14,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 15) ); } [Fact] public void NullCoalescing_RightSideBoolConstant() { var source = @" class C { bool M0(out object obj) { obj = new object(); return false; } static void M3(C? c, object? obj) { _ = c?.M0(out obj) ?? false ? obj.ToString() : obj.ToString(); // 1 } static void M4(C? c, object? obj) { _ = c?.M0(out obj) ?? true ? obj.ToString() // 2 : obj.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(16, 15) ); } [Fact] public void NullCoalescing_RightSideNullTest() { var source = @" class C { bool M0(out object obj) { obj = new object(); return false; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) ?? obj != null ? obj.ToString() : obj.ToString(); // 1 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) ?? obj == null ? obj.ToString() // 2 : obj.ToString(); } static void M5(C? c) { _ = c?.M0(out var obj) ?? obj != null // 3 ? obj.ToString() : obj.ToString(); // 4 } static void M6(C? c) { _ = c?.M0(out var obj) ?? obj == null // 5 ? obj.ToString() // 6 : obj.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(10, 15), // (16,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(16, 15), // (22,35): error CS0165: Use of unassigned local variable 'obj' // _ = c?.M0(out var obj) ?? obj != null // 3 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(22, 35), // (24,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(24, 15), // (29,35): error CS0165: Use of unassigned local variable 'obj' // _ = c?.M0(out var obj) ?? obj == null // 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(29, 35), // (30,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(30, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void NotNullWhenTrue_NullCoalescing_RightSideBool(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c) { _ = c?.M0(out var obj) ?? false ? obj.ToString() : obj.ToString(); // 1, 2 } static void M2(C? c) { _ = c?.M0(out var obj) ?? true ? obj.ToString() // 3, 4 : obj.ToString(); // 5 } static void M3(C? c, bool b) { _ = c?.M0(out var obj1) ?? b ? obj1.ToString() // 6, 7 : """"; _ = c?.M0(out var obj2) ?? b ? """" : obj2.ToString(); // 8, 9 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (12,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 1, 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (18,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 3, 4 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj1' // ? obj1.ToString() // 6, 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(25, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 8, 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(30, 15), // (30,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 8, 9 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(30, 15) ); } [Theory] [InlineData("[NotNullWhen(true)] out object? obj")] [InlineData("[MaybeNullWhen(false)] out object obj")] public void NotNullWhenTrue_NullCoalescing_RightSideNullTest(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) ?? obj != null ? obj.ToString() : obj.ToString(); // 1 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) ?? obj == null ? obj.ToString() // 2 : obj.ToString(); // 3 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(19, 15) ); } [Theory] [InlineData("[NotNullWhen(false)] out object? obj")] [InlineData("[MaybeNullWhen(true)] out object obj")] public void NotNullWhenFalse_NullCoalescing_RightSideNullTest(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return true; } static void M1(C? c, object? obj) { _ = c?.M0(out obj) ?? obj != null ? obj.ToString() // 1 : obj.ToString(); // 2 } static void M2(C? c, object? obj) { _ = c?.M0(out obj) ?? obj == null ? obj.ToString() // 3 : obj.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15) ); } [Theory] [InlineData("[NotNullWhen(false)] out object? obj")] [InlineData("[MaybeNullWhen(true)] out object obj")] public void NotNullWhenFalse_NullCoalescing(string param) { var source = @" using System.Diagnostics.CodeAnalysis; class C { bool M0(" + param + @") { obj = new object(); return false; } static void M1(C? c) { _ = c?.M0(out var obj) ?? false ? obj.ToString() // 1 : obj.ToString(); // 2, 3 } static void M2(C? c) { _ = c?.M0(out var obj) ?? true ? obj.ToString() // 4, 5 : obj.ToString(); } static void M3(C? c, bool b) { _ = c?.M0(out var obj1) ?? b ? obj1.ToString() // 6, 7 : """"; _ = c?.M0(out var obj2) ?? b ? """" : obj2.ToString(); // 8, 9 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(12, 15), // (12,15): error CS0165: Use of unassigned local variable 'obj' // : obj.ToString(); // 2, 3 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(12, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (18,15): error CS0165: Use of unassigned local variable 'obj' // ? obj.ToString() // 4, 5 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj").WithArguments("obj").WithLocation(18, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj1.ToString() // 6, 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj1").WithLocation(25, 15), // (25,15): error CS0165: Use of unassigned local variable 'obj1' // ? obj1.ToString() // 6, 7 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj1").WithArguments("obj1").WithLocation(25, 15), // (30,15): warning CS8602: Dereference of a possibly null reference. // : obj2.ToString(); // 8, 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj2").WithLocation(30, 15), // (30,15): error CS0165: Use of unassigned local variable 'obj2' // : obj2.ToString(); // 8, 9 Diagnostic(ErrorCode.ERR_UseDefViolation, "obj2").WithArguments("obj2").WithLocation(30, 15) ); } [Fact] [WorkItem(26624, "https://github.com/dotnet/roslyn/issues/26624")] public void CondAccess_Multiple_Arguments() { var source = @" static class C { static bool? M0(this bool b, object? obj) { return b; } static void M1(bool? b, object? obj) { _ = b?.M0(obj = new object()) ?? false ? obj.ToString() : obj.ToString(); // 1 } static void M2(bool? b) { var obj = new object(); _ = b?.M0(obj = null)?.M0(obj = new object()) ?? false ? obj.ToString() : obj.ToString(); // 2 } static void M3(bool? b) { var obj = new object(); _ = b?.M0(obj = new object())?.M0(obj = null) ?? false ? obj.ToString() // 3 : obj.ToString(); // 4 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(10, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(18, 15), // (25,15): warning CS8602: Dereference of a possibly null reference. // ? obj.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(25, 15), // (26,15): warning CS8602: Dereference of a possibly null reference. // : obj.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(26, 15) ); } [Fact] [WorkItem(26624, "https://github.com/dotnet/roslyn/issues/26624")] public void NullCoalescing_LeftStateAfterExpression() { var source = @" class C { static void M1(bool? flag) { _ = flag ?? false ? flag.Value : flag.Value; // 1 } } "; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (8,15): warning CS8629: Nullable value type may be null. // : flag.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "flag").WithLocation(8, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_01"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_01() { var source = @" class C { void M1(C c, object? x) { _ = c?.M(x = new object()) ?? true ? x.ToString() // 1 : x.ToString(); } void M2(C c, object? x) { _ = c?.M(x = new object()) ?? false ? x.ToString() : x.ToString(); // 2; } bool M(object x) => true; } "; CreateNullableCompilation(source).VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_02"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_02() { var source = @" class C { void M1(C c1, C c2, object? x) { _ = c1?.M(x = new object()) ?? c2?.M(x = new object()) ?? true ? x.ToString() // 1 : x.ToString(); } void M2(C c1, C c2, object? x) { _ = c1?.M(x = new object()) ?? c2?.M(x = new object()) ?? false ? x.ToString() : x.ToString(); // 2; } bool M(object x) => true; } "; CreateNullableCompilation(source).VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_03"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_03() { var source = @" class C { void M1(C c1, object? x) { _ = c1?.MA().MB(x = new object()) ?? false ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = c1?.MA()?.MB(x = new object()) ?? false ? x.ToString() : x.ToString(); // 2; } C MA() => this; bool MB(object x) => true; } "; CreateNullableCompilation(source).VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_04"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_04() { var source = @" class C { void M1(C c1, object? x) { _ = c1?.MA(x = new object()).MB() ?? false ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = c1?.MA(x = new object())?.MB() ?? false ? x.ToString() : x.ToString(); // 2; } C MA(object x) => this; bool MB() => true; } "; CreateNullableCompilation(source).VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_05"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_05() { var source = @" class C { void M1(C c1, object? x) { _ = c1?.MA(c1.MB(x = new object())) ?? false ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = c1?.MA(c1?.MB(x = new object())) ?? false ? x.ToString() // 2 : x.ToString(); // 3 } bool MA(object? obj) => true; C MB(object x) => this; } "; CreateNullableCompilation(source).VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (14,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_06"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_06() { var source = @" class C { void M1(C c1, object? x) { _ = c1?.M(out x) ?? false ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = c1?.M(out x) ?? false ? x.ToString() : x.ToString(); // 2 } bool M(out object obj) { obj = new object(); return true; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_07"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_07() { var source = @" class C { void M1(bool b, C c1, object? x) { _ = c1?.M(x = new object()) ?? b ? x.ToString() // 1 : x.ToString(); // 2 } bool M(object obj) { return true; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 15), // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_08"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_08() { var source = @" class C { void M1(C c1, object? x) { _ = (c1?.M(x = 0)) ?? false ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = c1?.M(x = 0)! ?? false ? x.ToString() : x.ToString(); // 2 } void M3(C c1, object? x) { _ = (c1?.M(x = 0))! ?? false ? x.ToString() : x.ToString(); // 3 } bool M(object obj) { return true; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_09"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_09() { var source = @" class C { void M1(C c1, object? x) { _ = (c1?[x = 0]) ?? false ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = (c1?[x = 0]) ?? true ? x.ToString() // 2 : x.ToString(); } public bool this[object x] => false; } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15) ); } ///<remarks>Ported from <see cref="FlowTests.CondAccess_NullCoalescing_10"/>.</remarks> [Fact] public void CondAccess_NullCoalescing_10() { var source = @" class C { void M1(C c1, object? x) { _ = (bool?)null ?? (c1?.M(x = 0) ?? false) ? x.ToString() : x.ToString(); // 1 } void M2(C c1, object? x) { _ = (bool?)null ?? (c1?.M(x = 0) ?? true) ? x.ToString() // 2 : x.ToString(); } bool M(object obj) { return true; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 15), // (15,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 15)); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_ConditionalLeft"/>.</remarks> [Fact] public void NullCoalescing_ConditionalLeft() { var source = @" class C { void M1(C c1, bool b, object? x) { _ = (bool?)(b && c1.M(x = 0)) ?? false ? x.ToString() // 1 : x.ToString(); // 2 } void M2(C c1, bool b, object? x) { _ = (bool?)c1.M(x = 0) ?? false ? x.ToString() : x.ToString(); } void M3(C c1, bool b, object? x, object? y) { _ = (bool?)((y = 0) is 0 && c1.M(x = 0)) ?? false ? x.ToString() + y.ToString() // 3 : x.ToString() + y.ToString(); // 4 } bool M(object obj) { return true; } } "; // Note that we unsplit any conditional state after visiting the left side of `??`. CreateNullableCompilation(source).VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 15), // (8,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 15), // (21,15): warning CS8602: Dereference of a possibly null reference. // ? x.ToString() + y.ToString() // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(21, 15), // (22,15): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 15) ); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_Throw"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_Throw() { var source = @" class C { void M1(C c1, bool b, object? x) { _ = c1?.M(x = 0) ?? throw new System.Exception(); x.ToString(); } bool M(object obj) { return true; } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_Cast"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_Cast() { var source = @" class C { void M1(C c1, bool b, object? x) { _ = (object)c1?.M(x = 0) ?? throw new System.Exception(); // 1 x.ToString(); } C M(object obj) { return this; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // _ = (object)c1?.M(x = 0) ?? throw new System.Exception(); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)c1?.M(x = 0)").WithLocation(6, 13)); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_01"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_UserDefinedConv_01() { var source = @" struct S { } struct C { public static implicit operator S(C? c) { return default(S); } void M1(C? c1, object? x) { S s = c1?.M2(x = 0) ?? c1!.Value.M3(x = 0); x.ToString(); } C M2(object obj) { return this; } S M3(object obj) { return this; } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_02"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_UserDefinedConv_02() { var source = @" class B { } class C { public static implicit operator B(C c) => new B(); void M1(C c1, object? x) { B b = c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_03"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_UserDefinedConv_03() { var source = @" struct B { } struct C { public static implicit operator B(C c) => new B(); void M1(C? c1, object? x) { B b = c1?.M1(x = 0) ?? c1!.Value.M2(x = 0); x.ToString(); } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_04"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_UserDefinedConv_04() { var source = @" struct B { } struct C { public static implicit operator B?(C c) => null; void M1(C? c1, object? x) { B? b = c1?.M1(x = 0) ?? c1!.Value.M2(x = 0); x.ToString(); } C M1(object obj) { return this; } B? M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_05"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_UserDefinedConv_05() { var source = @" struct B { public static implicit operator B(C c) => default; } class C { static void M1(C c1, object? x) { B b = c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); } C M1(object obj) { return this; } B M2(object obj) { return this; } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_01"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_01_01(string conversionKind) { var source = @" struct S { } struct C { public static " + conversionKind + @" operator S(C? c) { return default(S); } void M1(C? c1, object? x) { S s = (S?)c1?.M2(x = 0) ?? c1!.Value.M3(x = 0); x.ToString(); // 1 } C M2(object obj) { return this; } S M3(object obj) { return (S)this; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 9) ); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_01"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_01_02(string conversionKind) { var source = @" using System.Diagnostics.CodeAnalysis; struct S { } struct C { public static " + conversionKind + @" operator S([DisallowNull] C? c) { return default(S); } void M1(C? c1, object? x) { S s = (S?)c1?.M2(x = 0) ?? c1!.Value.M3(x = 0); // 1 x.ToString(); // 2 } C M2(object obj) { return this; } S M3(object obj) { return (S)this; } } "; CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }).VerifyDiagnostics( // (15,19): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // S s = (S?)c1?.M2(x = 0) ?? c1!.Value.M3(x = 0); // 1 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "c1?.M2(x = 0)").WithLocation(15, 19), // (16,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 9) ); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_02"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_02_01(string conversionKind) { var source = @" class B { } class C { public static " + conversionKind + @" operator B(C? c) => new B(); void M1(C c1, object? x) { B b = (B)c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); // 1 } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9)); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_02"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_02_02(string conversionKind) { var source = @" class B { } class C { public static " + conversionKind + @" operator B?(C? c) => new B(); void M1(C c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); // 1 } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9)); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_02"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_02_03(string conversionKind) { var source = @" using System.Diagnostics.CodeAnalysis; class B { } class C { [return: NotNullIfNotNull(""c"")] public static " + conversionKind + @" operator B?(C? c) => new B(); void M1(C c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); // 1 } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }).VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 9)); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_02"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_02_04(string conversionKind) { var source = @" using System.Diagnostics.CodeAnalysis; class B { } class C { [return: NotNull] public static " + conversionKind + @" operator B?(C? c) => new B(); void M1(C c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); // 1 } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(new[] { source, NotNullAttributeDefinition }).VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 9)); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_02"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_02_05(string conversionKind) { var source = @" class B { } class C { public static " + conversionKind + @" operator B(C c) => new B(); void M1(C c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); // 1 x.ToString(); // 2 } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (9,19): warning CS8604: Possible null reference argument for parameter 'c' in 'C.implicit operator B(C c)'. // B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c1?.M1(x = 0)").WithArguments("c", "C." + conversionKind + " operator B(C c)").WithLocation(9, 19), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9) ); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_03"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_03(string conversionKind) { var source = @" struct B { } struct C { public static " + conversionKind + @" operator B(C c) => new B(); void M1(C? c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.Value.M2(x = 0); x.ToString(); } C M1(object obj) { return this; } B M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_04"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_04(string conversionKind) { var source = @" struct B { } struct C { public static " + conversionKind + @" operator B?(C c) => null; void M1(C? c1, object? x) { B? b = (B?)c1?.M1(x = 0) ?? c1!.Value.M2(x = 0); x.ToString(); } C M1(object obj) { return this; } B? M2(object obj) { return new B(); } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_05"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_05_01(string conversionKind) { var source = @" struct B { public static " + conversionKind + @" operator B(C? c) => default; } class C { static void M1(C c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); x.ToString(); // 1 } C M1(object obj) { return this; } B M2(object obj) { return default; } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 9) ); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_UserDefinedConv_05"/>.</remarks> [Theory] [InlineData("explicit")] [InlineData("implicit")] public void NullCoalescing_CondAccess_ExplicitUserDefinedConv_05_02(string conversionKind) { var source = @" using System.Diagnostics.CodeAnalysis; struct B { public static " + conversionKind + @" operator B([DisallowNull] C? c) => default; } class C { static void M1(C c1, object? x) { B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); // 1 x.ToString(); // 2 } C M1(object obj) { return this; } B M2(object obj) { return default; } } "; CreateNullableCompilation(new[] { source, DisallowNullAttributeDefinition }).VerifyDiagnostics( // (13,19): warning CS8604: Possible null reference argument for parameter 'c' in 'B.implicit operator B(C? c)'. // B b = (B?)c1?.M1(x = 0) ?? c1!.M2(x = 0); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c1?.M1(x = 0)").WithArguments("c", "B." + conversionKind + " operator B(C? c)").WithLocation(13, 19), // (14,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 9) ); } ///<remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_NullableEnum"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_NullableEnum() { var source = @" public enum E { E1 = 1 } public static class Extensions { public static E M1(this E e, object obj) => e; static void M2(E? e, object? x) { E e2 = e?.M1(x = 0) ?? e!.Value.M1(x = 0); x.ToString(); } } "; CreateNullableCompilation(source).VerifyDiagnostics(); } /// <remarks>Ported from <see cref="FlowTests.NullCoalescing_CondAccess_NonNullConstantLeft"/>.</remarks> [Fact] public void NullCoalescing_CondAccess_NonNullConstantLeft() { var source = @" static class C { static string M0(this string s, object? x) => s; static void M1(object? x) { _ = """"?.Equals(x = new object()) ?? false ? x.ToString() : x.ToString(); } static void M2(object? x, object? y) { _ = """"?.M0(x = new object())?.Equals(y = new object()) ?? false ? x.ToString() + y.ToString() : x.ToString() + y.ToString(); // 1 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (17,30): warning CS8602: Dereference of a possibly null reference. // : x.ToString() + y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(17, 30)); } /// <remarks>Ported from <see cref="FlowTests.NullCoalescing_NonNullConstantLeft"/>.</remarks> [Fact] public void NullCoalescing_NonNullConstantLeft() { var source = @" static class C { static void M1(object? x) { _ = """" ?? $""{x.ToString()}""; // unreachable _ = """".ToString() ?? $""{x.ToString()}""; // 1 } } "; CreateNullableCompilation(source).VerifyDiagnostics( // (7,33): warning CS8602: Dereference of a possibly null reference. // _ = "".ToString() ?? $"{x.ToString()}"; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 33) ); } [Fact] public void NullCoalescing_CondAccess_NullableClassConstraint() { var source = @" interface I { bool M0(object obj); } static class C<T> where T : class?, I { static void M1(T t, object? x) { _ = t?.M0(x = 1) ?? false ? t.ToString() + x.ToString() : t.ToString() + x.ToString(); // 1, 2 } static void M2(T t, object? x) { _ = t?.M0(x = 1) ?? false ? M2(t) + x.ToString() : M2(t) + x.ToString(); // 3, 4 } // 'T' is allowed as an argument with a maybe-null state, but not with a maybe-default state. static string M2(T t) => t!.ToString(); } "; CreateNullableCompilation(source).VerifyDiagnostics( // (13,15): warning CS8602: Dereference of a possibly null reference. // : t.ToString() + x.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(13, 15), // (13,30): warning CS8602: Dereference of a possibly null reference. // : t.ToString() + x.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 30), // (20,18): warning CS8604: Possible null reference argument for parameter 't' in 'string C<T>.M2(T t)'. // : M2(t) + x.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("t", "string C<T>.M2(T t)").WithLocation(20, 18), // (20,23): warning CS8602: Dereference of a possibly null reference. // : M2(t) + x.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(20, 23) ); } [Fact] public void ConditionalBranching_Is_ReferenceType() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void Test(object? x) { if (x is C) { x.ToString(); } else { x.ToString(); // warn } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 13) ); } [Fact] public void ConditionalBranching_Is_GenericType() { CSharpCompilation c = CreateCompilation(new[] { @" class Base { } class C : Base { void Test<T>(C? x) where T : Base { if (x is T) { x.ToString(); } else { x.ToString(); // warn } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 13) ); } [Fact] public void ConditionalBranching_Is_UnconstrainedGenericType() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void F<T>(object? o) { if (o is T) { o.ToString(); } else { o.ToString(); // warn } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(12, 13) ); } [Fact] public void ConditionalBranching_Is_StructConstrainedGenericType() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void F<T>(object? o) where T : struct { if (o is T) { o.ToString(); } else { o.ToString(); // warn } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(12, 13) ); } [Fact] public void ConditionalBranching_Is_ClassConstrainedGenericType() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void F<T>(object? o) where T : class { if (o is T) { o.ToString(); } else { o.ToString(); // warn } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(12, 13) ); } [Fact] public void ConditionalBranching_Is_UnconstrainedGenericOperand() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void F<T>(T t, object? o) { if (t is string) t.ToString(); if (t is string s) { t.ToString(); s.ToString(); } if (t != null) t.ToString(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void ConditionalBranching_Is_NullOperand() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void F(object? o) { if (null is string) return; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (6,13): warning CS0184: The given expression is never of the provided ('string') type // if (null is string) return; Diagnostic(ErrorCode.WRN_IsAlwaysFalse, "null is string").WithArguments("string").WithLocation(6, 13) ); } [Fact] public void ConditionalOperator_01() { var source = @"class C { static void F(bool b, object x, object? y) { var z = b ? x : y; z.ToString(); var w = b ? y : x; w.ToString(); var v = true ? y : x; v.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // w.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // v.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v").WithLocation(10, 9)); } [Fact] public void ConditionalOperator_02() { var source = @"class C { static void F(bool b, object x, object? y) { (b ? x : y).ToString(); (b ? y : x).ToString(); if (y != null) (b ? x : y).ToString(); if (y != null) (b ? y : x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,10): warning CS8602: Dereference of a possibly null reference. // (b ? x : y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x : y").WithLocation(5, 10), // (6,10): warning CS8602: Dereference of a possibly null reference. // (b ? y : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? y : x").WithLocation(6, 10)); } [Fact] public void ConditionalOperator_03() { var source = @"class C { static void F(object x, object? y) { (false ? x : y).ToString(); (false ? y : x).ToString(); (true ? x : y).ToString(); (true ? y : x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,10): warning CS8602: Dereference of a possibly null reference. // (false ? x : y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "false ? x : y").WithLocation(5, 10), // (8,10): warning CS8602: Dereference of a possibly null reference. // (true ? y : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "true ? y : x").WithLocation(8, 10)); } [Fact] public void ConditionalOperator_04() { var source = @"class C { static void F(bool b, object x, string? y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } static void G(bool b, object? x, string y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,10): warning CS8602: Dereference of a possibly null reference. // (b ? x : y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x : y").WithLocation(5, 10), // (6,10): warning CS8602: Dereference of a possibly null reference. // (b ? y : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? y : x").WithLocation(6, 10), // (10,10): warning CS8602: Dereference of a possibly null reference. // (b ? x : y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x : y").WithLocation(10, 10), // (11,10): warning CS8602: Dereference of a possibly null reference. // (b ? y : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? y : x").WithLocation(11, 10)); } [Fact] public void ConditionalOperator_05() { var source = @"#pragma warning disable 0649 class A<T> { } class B1 : A<object?> { } class B2 : A<object> { } class C { static void F(bool b, A<object> x, A<object?> y, B1 z, B2 w) { object o; o = (b ? x : z)/*T:A<object!>!*/; o = (b ? x : w)/*T:A<object!>!*/; o = (b ? z : x)/*T:A<object!>!*/; o = (b ? w : x)/*T:A<object!>!*/; o = (b ? y : z)/*T:A<object?>!*/; o = (b ? y : w)/*T:A<object?>!*/; o = (b ? z : y)/*T:A<object?>!*/; o = (b ? w : y)/*T:A<object?>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (10,22): warning CS8619: Nullability of reference types in value of type 'B1' doesn't match target type 'A<object>'. // o = (b ? x : z)/*T:A<object!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "z").WithArguments("B1", "A<object>").WithLocation(10, 22), // (12,18): warning CS8619: Nullability of reference types in value of type 'B1' doesn't match target type 'A<object>'. // o = (b ? z : x)/*T:A<object!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "z").WithArguments("B1", "A<object>").WithLocation(12, 18), // (15,22): warning CS8619: Nullability of reference types in value of type 'B2' doesn't match target type 'A<object?>'. // o = (b ? y : w)/*T:A<object?>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("B2", "A<object?>").WithLocation(15, 22), // (17,18): warning CS8619: Nullability of reference types in value of type 'B2' doesn't match target type 'A<object?>'. // o = (b ? w : y)/*T:A<object?>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("B2", "A<object?>").WithLocation(17, 18)); } [Fact] public void ConditionalOperator_06() { var source = @"class C { static void F(bool b, object x, string? y) { (b ? null : x).ToString(); (b ? null : y).ToString(); (b ? x: null).ToString(); (b ? y: null).ToString(); (b ? null: null).ToString(); (b ? default : x).ToString(); (b ? default : y).ToString(); (b ? x: default).ToString(); (b ? y: default).ToString(); (b ? default: default).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and '<null>' // (b ? null: null).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? null: null").WithArguments("<null>", "<null>").WithLocation(9, 10), // (14,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'default' and 'default' // (b ? default: default).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? default: default").WithArguments("default", "default").WithLocation(14, 10), // (5,10): warning CS8602: Dereference of a possibly null reference. // (b ? null : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? null : x").WithLocation(5, 10), // (6,10): warning CS8602: Dereference of a possibly null reference. // (b ? null : y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? null : y").WithLocation(6, 10), // (7,10): warning CS8602: Dereference of a possibly null reference. // (b ? x: null).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x: null").WithLocation(7, 10), // (8,10): warning CS8602: Dereference of a possibly null reference. // (b ? y: null).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? y: null").WithLocation(8, 10), // (10,10): warning CS8602: Dereference of a possibly null reference. // (b ? default : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? default : x").WithLocation(10, 10), // (11,10): warning CS8602: Dereference of a possibly null reference. // (b ? default : y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? default : y").WithLocation(11, 10), // (12,10): warning CS8602: Dereference of a possibly null reference. // (b ? x: default).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x: default").WithLocation(12, 10), // (13,10): warning CS8602: Dereference of a possibly null reference. // (b ? y: default).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? y: default").WithLocation(13, 10) ); } [Fact] public void ConditionalOperator_07() { var source = @"class C { static void F(bool b, Unknown x, Unknown? y) { (b ? null : x).ToString(); (b ? null : y).ToString(); (b ? x: null).ToString(); (b ? y: null).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,27): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // static void F(bool b, Unknown x, Unknown? y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(3, 27), // (3,38): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // static void F(bool b, Unknown x, Unknown? y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(3, 38) ); } [Fact] public void ConditionalOperator_08() { var source = @"class C { static void F1(bool b, UnknownA x, UnknownB y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } static void F2(bool b, UnknownA? x, UnknownB y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } static void F3(bool b, UnknownA? x, UnknownB? y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,28): error CS0246: The type or namespace name 'UnknownA' could not be found (are you missing a using directive or an assembly reference?) // static void F2(bool b, UnknownA? x, UnknownB y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnknownA").WithArguments("UnknownA").WithLocation(8, 28), // (8,41): error CS0246: The type or namespace name 'UnknownB' could not be found (are you missing a using directive or an assembly reference?) // static void F2(bool b, UnknownA? x, UnknownB y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnknownB").WithArguments("UnknownB").WithLocation(8, 41), // (13,28): error CS0246: The type or namespace name 'UnknownA' could not be found (are you missing a using directive or an assembly reference?) // static void F3(bool b, UnknownA? x, UnknownB? y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnknownA").WithArguments("UnknownA").WithLocation(13, 28), // (13,41): error CS0246: The type or namespace name 'UnknownB' could not be found (are you missing a using directive or an assembly reference?) // static void F3(bool b, UnknownA? x, UnknownB? y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnknownB").WithArguments("UnknownB").WithLocation(13, 41), // (3,28): error CS0246: The type or namespace name 'UnknownA' could not be found (are you missing a using directive or an assembly reference?) // static void F1(bool b, UnknownA x, UnknownB y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnknownA").WithArguments("UnknownA").WithLocation(3, 28), // (3,40): error CS0246: The type or namespace name 'UnknownB' could not be found (are you missing a using directive or an assembly reference?) // static void F1(bool b, UnknownA x, UnknownB y) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "UnknownB").WithArguments("UnknownB").WithLocation(3, 40), // (15,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'UnknownA?' and 'UnknownB?' // (b ? x : y).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? x : y").WithArguments("UnknownA?", "UnknownB?").WithLocation(15, 10), // (16,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'UnknownB?' and 'UnknownA?' // (b ? y : x).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? y : x").WithArguments("UnknownB?", "UnknownA?").WithLocation(16, 10) ); } [Fact] public void ConditionalOperator_09() { var source = @"struct A { } struct B { } class C { static void F1(bool b, A x, B y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } static void F2(bool b, A x, C y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } static void F3(bool b, B x, C? y) { (b ? x : y).ToString(); (b ? y : x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'B' // (b ? x : y).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? x : y").WithArguments("A", "B").WithLocation(7, 10), // (8,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'B' and 'A' // (b ? y : x).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? y : x").WithArguments("B", "A").WithLocation(8, 10), // (12,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'A' and 'C' // (b ? x : y).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? x : y").WithArguments("A", "C").WithLocation(12, 10), // (13,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'C' and 'A' // (b ? y : x).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? y : x").WithArguments("C", "A").WithLocation(13, 10), // (17,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'B' and 'C' // (b ? x : y).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? x : y").WithArguments("B", "C").WithLocation(17, 10), // (18,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'C' and 'B' // (b ? y : x).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? y : x").WithArguments("C", "B").WithLocation(18, 10) ); } [Fact] public void ConditionalOperator_10() { var source = @"using System; class C { static void F(bool b, object? x, object y) { (b ? x : throw new Exception()).ToString(); (b ? y : throw new Exception()).ToString(); (b ? throw new Exception() : x).ToString(); (b ? throw new Exception() : y).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (b ? x : throw new Exception()).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x : throw new Exception()").WithLocation(6, 10), // (8,10): warning CS8602: Dereference of a possibly null reference. // (b ? throw new Exception() : x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? throw new Exception() : x").WithLocation(8, 10)); } [Fact] public void ConditionalOperator_11() { var source = @"class C { static void F(bool b, object x) { (b ? x : throw null!).ToString(); (b ? throw null! : x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ConditionalOperator_12() { var source = @"using System; class C { static void F(bool b) { (b ? throw new Exception() : throw new Exception()).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between '<throw expression>' and '<throw expression>' // (b ? throw new Exception() : throw new Exception()).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? throw new Exception() : throw new Exception()").WithArguments("<throw expression>", "<throw expression>").WithLocation(6, 10)); } [Fact] public void ConditionalOperator_13() { var source = @"class C { static bool F(object? x) { return true; } static void F1(bool c, bool b1, bool b2, object v1) { object x1; object y1; object? z1 = null; object? w1 = null; if (c ? b1 && F(x1 = v1) && F(z1 = v1) : b2 && F(y1 = v1) && F(w1 = v1)) { x1.ToString(); // unassigned (if) y1.ToString(); // unassigned (if) z1.ToString(); // may be null (if) w1.ToString(); // may be null (if) } else { x1.ToString(); // unassigned (no error) (else) y1.ToString(); // unassigned (no error) (else) z1.ToString(); // may be null (else) w1.ToString(); // may be null (else) } } static void F2(bool b1, bool b2, object v2) { object x2; object y2; object? z2 = null; object? w2 = null; if (true ? b1 && F(x2 = v2) && F(z2 = v2) : b2 && F(y2 = v2) && F(w2 = v2)) { x2.ToString(); // ok (if) y2.ToString(); // unassigned (if) z2.ToString(); // ok (if) w2.ToString(); // may be null (if) } else { x2.ToString(); // unassigned (else) y2.ToString(); // unassigned (no error) (else) z2.ToString(); // may be null (else) w2.ToString(); // may be null (else) } } static void F3(bool b1, bool b2, object v3) { object x3; object y3; object? z3 = null; object? w3 = null; if (false ? b1 && F(x3 = v3) && F(z3 = v3) : b2 && F(y3 = v3) && F(w3 = v3)) { x3.ToString(); // unassigned (if) y3.ToString(); // ok (if) z3.ToString(); // may be null (if) w3.ToString(); // ok (if) } else { x3.ToString(); // unassigned (no error) (else) y3.ToString(); // unassigned (else) z3.ToString(); // may be null (else) w3.ToString(); // may be null (else) } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): error CS0165: Use of unassigned local variable 'x1' // x1.ToString(); // unassigned (if) Diagnostic(ErrorCode.ERR_UseDefViolation, "x1").WithArguments("x1").WithLocation(15, 13), // (16,13): error CS0165: Use of unassigned local variable 'y1' // y1.ToString(); // unassigned (if) Diagnostic(ErrorCode.ERR_UseDefViolation, "y1").WithArguments("y1").WithLocation(16, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // z1.ToString(); // may be null (if) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1").WithLocation(17, 13), // (18,13): warning CS8602: Dereference of a possibly null reference. // w1.ToString(); // may be null (if) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w1").WithLocation(18, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // z1.ToString(); // may be null (else) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1").WithLocation(24, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // w1.ToString(); // may be null (else) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w1").WithLocation(25, 13), // (37,13): error CS0165: Use of unassigned local variable 'y2' // y2.ToString(); // unassigned (if) Diagnostic(ErrorCode.ERR_UseDefViolation, "y2").WithArguments("y2").WithLocation(37, 13), // (43,13): error CS0165: Use of unassigned local variable 'x2' // x2.ToString(); // unassigned (else) Diagnostic(ErrorCode.ERR_UseDefViolation, "x2").WithArguments("x2").WithLocation(43, 13), // (39,13): warning CS8602: Dereference of a possibly null reference. // w2.ToString(); // may be null (if) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w2").WithLocation(39, 13), // (45,13): warning CS8602: Dereference of a possibly null reference. // z2.ToString(); // may be null (else) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2").WithLocation(45, 13), // (46,13): warning CS8602: Dereference of a possibly null reference. // w2.ToString(); // may be null (else) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w2").WithLocation(46, 13), // (57,13): error CS0165: Use of unassigned local variable 'x3' // x3.ToString(); // unassigned (if) Diagnostic(ErrorCode.ERR_UseDefViolation, "x3").WithArguments("x3").WithLocation(57, 13), // (65,13): error CS0165: Use of unassigned local variable 'y3' // y3.ToString(); // unassigned (else) Diagnostic(ErrorCode.ERR_UseDefViolation, "y3").WithArguments("y3").WithLocation(65, 13), // (59,13): warning CS8602: Dereference of a possibly null reference. // z3.ToString(); // may be null (if) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z3").WithLocation(59, 13), // (66,13): warning CS8602: Dereference of a possibly null reference. // z3.ToString(); // may be null (else) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z3").WithLocation(66, 13), // (67,13): warning CS8602: Dereference of a possibly null reference. // w3.ToString(); // may be null (else) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w3").WithLocation(67, 13)); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_14() { var source = @"interface I<T> { T P { get; } } interface IIn<in T> { } interface IOut<out T> { T P { get; } } class C { static void F1(bool b, ref string? x1, ref string y1) { (b ? ref x1 : ref x1)/*T:string?*/.ToString(); // 1 (b ? ref x1 : ref y1)/*T:string?*/.ToString(); // 2, 3 (b ? ref y1 : ref x1)/*T:string?*/.ToString(); // 4, 5 (b ? ref y1 : ref y1)/*T:string!*/.ToString(); } static void F2(bool b, ref I<string?> x2, ref I<string> y2) { (b ? ref x2 : ref x2)/*T:I<string?>!*/.P.ToString(); // 6 (b ? ref y2 : ref x2)/*T:I<string>!*/.P.ToString(); // 7 (b ? ref x2 : ref y2)/*T:I<string>!*/.P.ToString(); // 8, 9 (b ? ref y2 : ref y2)/*T:I<string!>!*/.P.ToString(); } static void F3(bool b, ref IIn<string?> x3, ref IIn<string> y3) { (b ? ref x3 : ref x3)/*T:IIn<string?>!*/.ToString(); (b ? ref y3 : ref x3)/*T:IIn<string>!*/.ToString(); // 10 (b ? ref x3 : ref y3)/*T:IIn<string>!*/.ToString(); // 11 (b ? ref y3 : ref y3)/*T:IIn<string!>!*/.ToString(); } static void F4(bool b, ref IOut<string?> x4, ref IOut<string> y4) { (b ? ref x4 : ref x4)/*T:IOut<string?>!*/.P.ToString(); // 12 (b ? ref y4 : ref x4)/*T:IOut<string>!*/.P.ToString(); // 13 (b ? ref x4 : ref y4)/*T:IOut<string>!*/.P.ToString(); // 14 (b ? ref y4 : ref y4)/*T:IOut<string!>!*/.P.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (8,10): warning CS8602: Possible dereference of a null reference. // (b ? ref x1 : ref x1)/*T:string?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref x1 : ref x1").WithLocation(8, 10), // (9,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // (b ? ref x1 : ref y1)/*T:string?*/.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x1 : ref y1").WithArguments("string?", "string").WithLocation(9, 10), // (9,10): warning CS8602: Possible dereference of a null reference. // (b ? ref x1 : ref y1)/*T:string?*/.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref x1 : ref y1").WithLocation(9, 10), // (10,10): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // (b ? ref y1 : ref x1)/*T:string?*/.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y1 : ref x1").WithArguments("string", "string?").WithLocation(10, 10), // (10,10): warning CS8602: Possible dereference of a null reference. // (b ? ref y1 : ref x1)/*T:string?*/.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref y1 : ref x1").WithLocation(10, 10), // (15,9): warning CS8602: Possible dereference of a null reference. // (b ? ref x2 : ref x2)/*T:I<string?>!*/.P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b ? ref x2 : ref x2)/*T:I<string?>!*/.P").WithLocation(15, 9), // (16,10): warning CS8619: Nullability of reference types in value of type 'I<string>' doesn't match target type 'I<string?>'. // (b ? ref y2 : ref x2)/*T:I<string>!*/.P.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y2 : ref x2").WithArguments("I<string>", "I<string?>").WithLocation(16, 10), // (17,10): warning CS8619: Nullability of reference types in value of type 'I<string?>' doesn't match target type 'I<string>'. // (b ? ref x2 : ref y2)/*T:I<string>!*/.P.ToString(); // 8, 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x2 : ref y2").WithArguments("I<string?>", "I<string>").WithLocation(17, 10), // (23,10): warning CS8619: Nullability of reference types in value of type 'IIn<string>' doesn't match target type 'IIn<string?>'. // (b ? ref y3 : ref x3)/*T:IIn<string>!*/.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y3 : ref x3").WithArguments("IIn<string>", "IIn<string?>").WithLocation(23, 10), // (24,10): warning CS8619: Nullability of reference types in value of type 'IIn<string?>' doesn't match target type 'IIn<string>'. // (b ? ref x3 : ref y3)/*T:IIn<string>!*/.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x3 : ref y3").WithArguments("IIn<string?>", "IIn<string>").WithLocation(24, 10), // (29,9): warning CS8602: Possible dereference of a null reference. // (b ? ref x4 : ref x4)/*T:IOut<string?>!*/.P.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b ? ref x4 : ref x4)/*T:IOut<string?>!*/.P").WithLocation(29, 9), // (30,10): warning CS8619: Nullability of reference types in value of type 'IOut<string>' doesn't match target type 'IOut<string?>'. // (b ? ref y4 : ref x4)/*T:IOut<string>!*/.P.ToString(); // 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y4 : ref x4").WithArguments("IOut<string>", "IOut<string?>").WithLocation(30, 10), // (31,10): warning CS8619: Nullability of reference types in value of type 'IOut<string?>' doesn't match target type 'IOut<string>'. // (b ? ref x4 : ref y4)/*T:IOut<string>!*/.P.ToString(); // 14, 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x4 : ref y4").WithArguments("IOut<string?>", "IOut<string>").WithLocation(31, 10)); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_WithLambdaConversions() { var source = @" using System; class C { Func<bool, T> D1<T>(T t) => k => t; void M1(bool b, string? s) { _ = (b ? D1(s) : k => s) /*T:System.Func<bool, string?>!*/; _ = (b ? k => s : D1(s)) /*T:System.Func<bool, string?>!*/; _ = (true ? D1(s) : k => s) /*T:System.Func<bool, string?>!*/; _ = (true ? k => s : D1(s)) /*T:System.Func<bool, string>!*/; // unexpected type _ = (false ? D1(s) : k => s) /*T:System.Func<bool, string>!*/; // unexpected type _ = (false ? k => s : D1(s)) /*T:System.Func<bool, string?>!*/; _ = (b ? D1(s!) : k => s) /*T:System.Func<bool, string>!*/; // 1, unexpected type _ = (b ? k => s : D1(s!)) /*T:System.Func<bool, string>!*/; // 2, unexpected type _ = (true ? D1(s!) : k => s) /*T:System.Func<bool, string>!*/; // unexpected type _ = (true ? k => s : D1(s!)) /*T:System.Func<bool, string>!*/; // 3, unexpected type _ = (false ? D1(s!) : k => s) /*T:System.Func<bool, string>!*/; // 4, unexpected type _ = (false ? k => s : D1(s!)) /*T:System.Func<bool, string>!*/; // unexpected type _ = (b ? D1(true ? throw null! : s) : k => s) /*T:System.Func<bool, string>!*/; // 5, unexpected type _ = (b ? k => s : D1(true ? throw null! : s)) /*T:System.Func<bool, string>!*/; // 6, unexpected type _ = (true ? D1(true ? throw null! : s) : k => s) /*T:System.Func<bool, string>!*/; // unexpected type _ = (true ? k => s : D1(true ? throw null! : s)) /*T:System.Func<bool, string>!*/; // 7, unexpected type _ = (false ? D1(true ? throw null! : s) : k => s) /*T:System.Func<bool, string>!*/; // 8, unexpected type _ = (false ? k => s : D1(true ? throw null! : s)) /*T:System.Func<bool, string>!*/; // unexpected type } delegate T MyDelegate<T>(bool b); ref MyDelegate<T> D2<T>(T t) => throw null!; void M(bool b, string? s) { _ = (b ? ref D2(s) : ref D2(s!)) /*T:C.MyDelegate<string>!*/; // 9 _ = (b ? ref D2(s!) : ref D2(s)) /*T:C.MyDelegate<string>!*/; // 10 _ = (true ? ref D2(s) : ref D2(s!)) /*T:C.MyDelegate<string>!*/; // 11 _ = (true ? ref D2(s!) : ref D2(s)) /*T:C.MyDelegate<string!>!*/; _ = (false ? ref D2(s) : ref D2(s!)) /*T:C.MyDelegate<string!>!*/; _ = (false ? ref D2(s!) : ref D2(s)) /*T:C.MyDelegate<string>!*/; // 12 } }"; // See https://github.com/dotnet/roslyn/issues/34392 // Best type inference involving lambda conversion should agree with method type inference // Missing diagnostics var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (36,14): warning CS8619: Nullability of reference types in value of type 'C.MyDelegate<string?>' doesn't match target type 'C.MyDelegate<string>'. // _ = (b ? ref D2(s) : ref D2(s!)) /*T:C.MyDelegate<string>!*/; // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref D2(s) : ref D2(s!)").WithArguments("C.MyDelegate<string?>", "C.MyDelegate<string>").WithLocation(36, 14), // (37,14): warning CS8619: Nullability of reference types in value of type 'C.MyDelegate<string>' doesn't match target type 'C.MyDelegate<string?>'. // _ = (b ? ref D2(s!) : ref D2(s)) /*T:C.MyDelegate<string>!*/; // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref D2(s!) : ref D2(s)").WithArguments("C.MyDelegate<string>", "C.MyDelegate<string?>").WithLocation(37, 14), // (38,14): warning CS8619: Nullability of reference types in value of type 'C.MyDelegate<string?>' doesn't match target type 'C.MyDelegate<string>'. // _ = (true ? ref D2(s) : ref D2(s!)) /*T:C.MyDelegate<string>!*/; // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "true ? ref D2(s) : ref D2(s!)").WithArguments("C.MyDelegate<string?>", "C.MyDelegate<string>").WithLocation(38, 14), // (41,14): warning CS8619: Nullability of reference types in value of type 'C.MyDelegate<string>' doesn't match target type 'C.MyDelegate<string?>'. // _ = (false ? ref D2(s!) : ref D2(s)) /*T:C.MyDelegate<string>!*/; // unexpected type Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "false ? ref D2(s!) : ref D2(s)").WithArguments("C.MyDelegate<string>", "C.MyDelegate<string?>").WithLocation(41, 14) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_WithUserDefinedConversion() { var source = @" class D { } class C { public static implicit operator D?(C c) => throw null!; static void M1(bool b, C c, D d) { _ = (b ? c : d) /*T:D?*/; _ = (b ? d : c) /*T:D?*/; _ = (true ? c : d) /*T:D?*/; _ = (true ? d : c) /*T:D!*/; _ = (false ? c : d) /*T:D!*/; _ = (false ? d : c) /*T:D?*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_NestedNullabilityMismatch() { var source = @" class C<T1, T2> { static void M1(bool b, string s, string? s2) { (b ? ref Create(s, s2) : ref Create(s2, s)) /*T:C<string, string>!*/ = null; (b ? ref Create(s2, s) : ref Create(s, s2)) /*T:C<string, string>!*/ = null; } static ref C<U1, U2> Create<U1, U2>(U1 x, U2 y) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,10): warning CS8619: Nullability of reference types in value of type 'C<string, string?>' doesn't match target type 'C<string?, string>'. // (b ? ref Create(s, s2) : ref Create(s2, s)) /*T:C<string, string>!*/ = null; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref Create(s, s2) : ref Create(s2, s)").WithArguments("C<string, string?>", "C<string?, string>").WithLocation(6, 10), // (6,80): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref Create(s, s2) : ref Create(s2, s)) /*T:C<string, string>!*/ = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 80), // (7,10): warning CS8619: Nullability of reference types in value of type 'C<string?, string>' doesn't match target type 'C<string, string?>'. // (b ? ref Create(s2, s) : ref Create(s, s2)) /*T:C<string, string>!*/ = null; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref Create(s2, s) : ref Create(s, s2)").WithArguments("C<string?, string>", "C<string, string?>").WithLocation(7, 10), // (7,80): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref Create(s2, s) : ref Create(s, s2)) /*T:C<string, string>!*/ = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 80) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_WithAlteredStates() { var source = @" class C { static void F1(bool b, ref string? x1, ref string y1) { y1 = null; // 1 (b ? ref x1 : ref x1)/*T:string?*/.ToString(); // 2 (b ? ref x1 : ref y1)/*T:string?*/.ToString(); // 3, 4 (b ? ref y1 : ref x1)/*T:string?*/.ToString(); // 5, 6 (b ? ref y1 : ref y1)/*T:string?*/.ToString(); // 7 x1 = """"; y1 = """"; (b ? ref x1 : ref x1)/*T:string!*/.ToString(); (b ? ref x1 : ref y1)/*T:string!*/.ToString(); // 8 (b ? ref y1 : ref x1)/*T:string!*/.ToString(); // 9 (b ? ref y1 : ref y1)/*T:string!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // y1 = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 14), // (7,10): warning CS8602: Possible dereference of a null reference. // (b ? ref x1 : ref x1)/*T:string?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref x1 : ref x1").WithLocation(7, 10), // (8,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // (b ? ref x1 : ref y1)/*T:string?*/.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x1 : ref y1").WithArguments("string?", "string").WithLocation(8, 10), // (8,10): warning CS8602: Possible dereference of a null reference. // (b ? ref x1 : ref y1)/*T:string?*/.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref x1 : ref y1").WithLocation(8, 10), // (9,10): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // (b ? ref y1 : ref x1)/*T:string?*/.ToString(); // 5, 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y1 : ref x1").WithArguments("string", "string?").WithLocation(9, 10), // (9,10): warning CS8602: Possible dereference of a null reference. // (b ? ref y1 : ref x1)/*T:string?*/.ToString(); // 5, 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref y1 : ref x1").WithLocation(9, 10), // (10,10): warning CS8602: Possible dereference of a null reference. // (b ? ref y1 : ref y1)/*T:string?*/.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? ref y1 : ref y1").WithLocation(10, 10), // (15,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // (b ? ref x1 : ref y1)/*T:string!*/.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x1 : ref y1").WithArguments("string?", "string").WithLocation(15, 10), // (16,10): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // (b ? ref y1 : ref x1)/*T:string!*/.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y1 : ref x1").WithArguments("string", "string?").WithLocation(16, 10) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_WithUnreachable() { var source = @" class C { static void F1(bool b, string? x1, string y1) { ((b && false) ? x1 : x1)/*T:string?*/.ToString(); // 1 ((b && false) ? x1 : y1)/*T:string!*/.ToString(); ((b && false) ? y1 : x1)/*T:string?*/.ToString(); // 2 ((b && false) ? y1 : y1)/*T:string!*/.ToString(); ((b || true) ? x1 : x1)/*T:string?*/.ToString(); // 3 ((b || true) ? x1 : y1)/*T:string?*/.ToString(); // 4 ((b || true) ? y1 : x1)/*T:string!*/.ToString(); ((b || true) ? y1 : y1)/*T:string!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,10): warning CS8602: Possible dereference of a null reference. // ((b && false) ? x1 : x1)/*T:string?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b && false) ? x1 : x1").WithLocation(6, 10), // (8,10): warning CS8602: Possible dereference of a null reference. // ((b && false) ? y1 : x1)/*T:string?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b && false) ? y1 : x1").WithLocation(8, 10), // (11,10): warning CS8602: Possible dereference of a null reference. // ((b || true) ? x1 : x1)/*T:string?*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b || true) ? x1 : x1").WithLocation(11, 10), // (12,10): warning CS8602: Possible dereference of a null reference. // ((b || true) ? x1 : y1)/*T:string?*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b || true) ? x1 : y1").WithLocation(12, 10) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_SideEffectsInUnreachableBranch() { var source = @" class C { void M1(string? s, string? s2) { s = """"; (false ? ref M3(s = null) : ref s2) = null; s.ToString(); (true ? ref M3(s = null) : ref s2) = null; s.ToString(); // 1 } void M2(string? s, string? s2) { s = """"; (true ? ref s2 : ref M3(s = null)) = null; s.ToString(); (false ? ref s2 : ref M3(s = null)) = null; s.ToString(); // 2 } ref string? M3(string? x) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Possible dereference of a null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 9), // (18,9): warning CS8602: Possible dereference of a null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 9)); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_WithReachableBranchThatThrows() { var source = @" class C { static void F1(bool b) { (b ? M1(false ? 1 : throw new System.Exception()) : M2(2))/*T:string!*/.ToString(); (b ? M1(1) : M2(false ? 2 : throw new System.Exception()))/*T:string?*/.ToString(); // 1 } static string? M1(int i) => throw null!; static string M2(int i) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (7,10): warning CS8602: Possible dereference of a null reference. // (b ? M1(1) : M2(false ? 2 : throw new System.Exception()))/*T:string?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? M1(1) : M2(false ? 2 : throw new System.Exception())").WithLocation(7, 10) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_EndNotReachable() { var source = @" class C { static void F1(bool b) { (true ? M1(false ? 1 : throw new System.Exception()) : M2(2)) /*T:string!*/.ToString(); (false ? M1(1) : M2(false ? 2 : throw new System.Exception())) /*T:string!*/.ToString(); } static string? M1(int i) => throw null!; static string M2(int i) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_WithReachableBranchThatThrows() { var source = @" class C { static void F1(bool b) { (b ? ref M1(false ? 1 : throw new System.Exception()) : ref M2(2)) /*T:string!*/ = null; // 1, 2 (b ? ref M1(1) : ref M2(false ? 2 : throw new System.Exception())) /*T:string?*/ = null; // 3, 4 } static ref string? M1(int i) => throw null!; static ref string M2(int i) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // (b ? ref M1(false ? 1 : throw new System.Exception()) : ref M2(2)) /*T:string!*/ = null; // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref M1(false ? 1 : throw new System.Exception()) : ref M2(2)").WithArguments("string?", "string").WithLocation(6, 10), // (6,92): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref M1(false ? 1 : throw new System.Exception()) : ref M2(2)) /*T:string!*/ = null; // 1, 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 92), // (7,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // (b ? ref M1(1) : ref M2(false ? 2 : throw new System.Exception())) /*T:string?*/ = null; // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref M1(1) : ref M2(false ? 2 : throw new System.Exception())").WithArguments("string?", "string").WithLocation(7, 10), // (7,92): warning CS8625: Cannot convert null literal to non-nullable reference type. // (b ? ref M1(1) : ref M2(false ? 2 : throw new System.Exception())) /*T:string?*/ = null; // 3, 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 92) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_EndNotReachable() { var source = @" class C { static void F1(bool b) { (true ? ref M1(false ? 1 : throw new System.Exception()) : ref M2(2)) /*T:string!*/ = null; (false ? ref M1(1) : ref M2(false ? 2 : throw new System.Exception())) /*T:string!*/ = null; } static ref string? M1(int i) => throw null!; static ref string M2(int i) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_WithUnreachable() { var source = @" class C { static void F1(bool b, ref string? x1, ref string y1) { ((b && false) ? ref x1 : ref x1)/*T:string?*/ = null; ((b && false) ? ref x1 : ref y1)/*T:string!*/ = null; // 1, 2 ((b && false) ? ref y1 : ref x1)/*T:string?*/ = null; // 3, 4 ((b && false) ? ref y1 : ref y1)/*T:string!*/ = null; // 5 ((b || true) ? ref x1 : ref x1)/*T:string?*/ = null; ((b || true) ? ref x1 : ref y1)/*T:string?*/ = null; // 6, 7 ((b || true) ? ref y1 : ref x1)/*T:string!*/ = null; // 8, 9 ((b || true) ? ref y1 : ref y1)/*T:string!*/ = null; // 10 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (7,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // ((b && false) ? ref x1 : ref y1)/*T:string!*/ = null; // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(b && false) ? ref x1 : ref y1").WithArguments("string?", "string").WithLocation(7, 10), // (7,57): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((b && false) ? ref x1 : ref y1)/*T:string!*/ = null; // 1, 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(7, 57), // (8,10): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // ((b && false) ? ref y1 : ref x1)/*T:string?*/ = null; // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(b && false) ? ref y1 : ref x1").WithArguments("string", "string?").WithLocation(8, 10), // (8,57): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((b && false) ? ref y1 : ref x1)/*T:string?*/ = null; // 3, 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 57), // (9,57): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((b && false) ? ref y1 : ref y1)/*T:string!*/ = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 57), // (12,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // ((b || true) ? ref x1 : ref y1)/*T:string?*/ = null; // 6, 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(b || true) ? ref x1 : ref y1").WithArguments("string?", "string").WithLocation(12, 10), // (12,56): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((b || true) ? ref x1 : ref y1)/*T:string?*/ = null; // 6, 7 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 56), // (13,10): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // ((b || true) ? ref y1 : ref x1)/*T:string!*/ = null; // 8, 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(b || true) ? ref y1 : ref x1").WithArguments("string", "string?").WithLocation(13, 10), // (13,56): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((b || true) ? ref y1 : ref x1)/*T:string!*/ = null; // 8, 9 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 56), // (14,56): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((b || true) ? ref y1 : ref y1)/*T:string!*/ = null; // 10 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 56) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_WithError() { var source = @" class C { static void F1(bool b, ref string? x1) { (b ? ref x1 : ref error)/*T:!*/.ToString(); (b ? ref x1 : ref error)/*T:!*/.ToString(); (b ? ref error : ref x1)/*T:!*/.ToString(); (b ? ref error : ref error)/*T:!*/.ToString(); x1 = """"; (b ? ref x1 : ref error)/*T:!*/.ToString(); (b ? ref x1 : ref error)/*T:!*/.ToString(); (b ? ref error : ref x1)/*T:!*/.ToString(); (b ? ref error : ref error)/*T:!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref x1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(6, 27), // (7,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref x1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(7, 27), // (8,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref x1)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 18), // (9,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(9, 18), // (9,30): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(9, 30), // (12,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref x1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(12, 27), // (13,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref x1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(13, 27), // (14,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref x1)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(14, 18), // (15,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(15, 18), // (15,30): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(15, 30) ); } [Fact] [WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_Ref_WithError_Nested() { var source = @" class C<T> { static void F1(bool b, ref C<string?> x1, ref C<string> y1) { (b ? ref x1 : ref error)/*T:!*/.ToString(); (b ? ref x1 : ref error)/*T:!*/.ToString(); (b ? ref error : ref x1)/*T:!*/.ToString(); (b ? ref error : ref error)/*T:!*/.ToString(); (b ? ref y1 : ref error)/*T:!*/.ToString(); (b ? ref y1 : ref error)/*T:!*/.ToString(); (b ? ref error : ref y1)/*T:!*/.ToString(); (b ? ref error : ref error)/*T:!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref x1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(6, 27), // (7,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref x1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(7, 27), // (8,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref x1)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(8, 18), // (9,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(9, 18), // (9,30): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(9, 30), // (11,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref y1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(11, 27), // (12,27): error CS0103: The name 'error' does not exist in the current context // (b ? ref y1 : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(12, 27), // (13,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref y1)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(13, 18), // (14,18): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(14, 18), // (14,30): error CS0103: The name 'error' does not exist in the current context // (b ? ref error : ref error)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_NameNotInContext, "error").WithArguments("error").WithLocation(14, 30) ); } [Fact] public void ConditionalOperator_15() { // We likely shouldn't be warning on the x[0] access, as code is an error. However, we currently do // because of fallout from https://github.com/dotnet/roslyn/issues/34158: when we calculate the // type of new[] { x }, the type of the BoundLocal x is ErrorType var, but the type of the local // symbol is ErrorType var[]. VisitLocal prefers the type of the BoundLocal, and so the // new[] { x } expression is calculated to have a final type of ErrorType var[]. The default is // target typed to ErrorType var[] as well, and the logic in VisitConditionalOperator therefore // uses that type as the final type of the expression. This calculation succeeded, so that result // is stored as the current nullability of x, causing us to warn on the subsequent line. var source = @"class Program { static void F(bool b) { var x = b ? new[] { x } : default; x[0].ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,29): error CS0841: Cannot use local variable 'x' before it is declared // var x = b ? new[] { x } : default; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "x").WithArguments("x").WithLocation(5, 29), // (6,9): warning CS8602: Dereference of a possibly null reference. // x[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9)); } [Fact] public void ConditionalOperator_16() { var source = @"class Program { static bool F(object? x) { return true; } static void F1(bool b, bool c, object x1, object? y1) { if (b ? c && F(x1 = y1) : true) // 1 { x1.ToString(); // 2 } } static void F2(bool b, bool c, object x2, object? y2) { if (b ? true : c && F(x2 = y2)) // 3 { x2.ToString(); // 4 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,29): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (b ? c && F(x1 = y1) : true) // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(9, 29), // (11,13): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 13), // (16,36): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (b ? true : c && F(x2 = y2)) // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2").WithLocation(16, 36), // (18,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(18, 13)); } [Fact] public void ConditionalOperator_17() { var source = @"class Program { static void F(bool x, bool y, bool z, bool? w) { object o; o = x ? y && z : w; // 1 o = true ? y && z : w; o = false ? w : y && z; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = x ? y && z : w; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x ? y && z : w").WithLocation(6, 13)); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_18() { var comp = CreateCompilation(@" using System; class C { public void M(bool b, Action? action) { _ = b ? () => { action(); } : action = new Action(() => {}); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,25): warning CS8602: Dereference of a possibly null reference. // _ = b ? () => { action(); } Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "action").WithLocation(6, 25) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_01() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { string? s = null; Func<string> a = b ? () => s.ToString() : () => s?.ToString(); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,36): warning CS8602: Dereference of a possibly null reference. // Func<string> a = b ? () => s.ToString() : () => s?.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 36), // (8,57): warning CS8603: Possible null reference return. // Func<string> a = b ? () => s.ToString() : () => s?.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s?.ToString()").WithLocation(8, 57) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_02() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { string? s = null; object a = (Func<string>)(b ? () => s.ToString() : () => s?.ToString()); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,45): warning CS8602: Dereference of a possibly null reference. // object a = (Func<string>)(b ? () => s.ToString() : () => s?.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 45), // (8,66): warning CS8603: Possible null reference return. // object a = (Func<string>)(b ? () => s.ToString() : () => s?.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s?.ToString()").WithLocation(8, 66) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_03() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { Func<string>? s = () => """"; Func<object>? o = b ? () => s() : s = null; } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_04() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { Func<string>? s = () => """"; Func<object>? o = b ? s = null : () => s(); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_05() { var comp = CreateCompilation(@" class C { static void M(bool b) { string? s = null; object a = b ? () => s.ToString() : () => s?.ToString(); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,30): warning CS8602: Dereference of a possibly null reference. // object a = b ? () => s.ToString() : () => s?.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 30) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_06() { var comp = CreateCompilation(@" using System; class C { static void M(bool b) { string? s1 = null; string? s2 = """"; M1(s2, b ? () => s1.ToString() : () => s1?.ToString()).ToString(); } static T M1<T>(T t1, Func<T> t2) => t1; } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,26): warning CS8602: Dereference of a possibly null reference. // M1(s2, b ? () => s1.ToString() : () => s1?.ToString()).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 26), // (9,48): warning CS8603: Possible null reference return. // M1(s2, b ? () => s1.ToString() : () => s1?.ToString()).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s1?.ToString()").WithLocation(9, 48) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void ConditionalOperator_TargetTyped_07() { var comp = CreateCompilation(@" interface I {} class A : I {} class B : I {} class C { static void M(I i, A a, B? b, bool @bool) { M1(i, @bool ? a : b).ToString(); } static T M1<T>(T t1, T t2) => t1; } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,15): warning CS8604: Possible null reference argument for parameter 't2' in 'I C.M1<I>(I t1, I t2)'. // M1(i, @bool ? a : b).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "@bool ? a : b").WithArguments("t2", "I C.M1<I>(I t1, I t2)").WithLocation(9, 15) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461"), WorkItem(49735, "https://github.com/dotnet/roslyn/issues/49735")] public void ConditionalOperator_TargetTyped_08() { var comp = CreateCompilation(@" C? c = """".Length > 0 ? new A() : new B(); c.ToString(); class C { } class A { public static implicit operator C?(A a) => null; } class B { public static implicit operator C?(B b) => null; } ", options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (3,1): warning CS8602: Dereference of a possibly null reference. // c.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(3, 1) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461"), WorkItem(49735, "https://github.com/dotnet/roslyn/issues/49735")] public void ConditionalOperator_TargetTyped_09() { var comp = CreateCompilation(@" C? c = true ? new A() : new B(); c.ToString(); class C { } class A { public static implicit operator C(A a) => new C(); } class B { public static implicit operator C?(B b) => null; } ", options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461"), WorkItem(49735, "https://github.com/dotnet/roslyn/issues/49735")] public void ConditionalOperator_TargetTyped_10() { var comp = CreateCompilation(@" C? c = false ? new A() : new B(); c.ToString(); class C { } class A { public static implicit operator C?(A a) => null; } class B { public static implicit operator C(B b) => new C(); } ", options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_ConditionalOperator_WithoutType_WithNullLiterals() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { if (b) return b ? null : null; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nullNode = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("null", nullNode.ToString()); Assert.Null(model.GetTypeInfo(nullNode).Type); Assert.Equal("System.Object?", model.GetTypeInfo(nullNode).ConvertedType.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model.GetTypeInfo(nullNode).ConvertedNullability.FlowState); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( // (9,24): warning CS8603: Possible null reference return. // return b ? null : null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? null : null").WithLocation(9, 24) ); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ArrayTypeInference_ConditionalOperator_WithoutType_WithNullLiterals() { var source = @"class Program { static void F(bool b) { var x = new[] { b ? null : null, new object() }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nullNode = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("null", nullNode.ToString()); Assert.Null(model.GetTypeInfo(nullNode).Type); Assert.Equal("System.Object?", model.GetTypeInfo(nullNode).ConvertedType.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model.GetTypeInfo(nullNode).ConvertedNullability.FlowState); var invocationNode = tree.GetRoot().DescendantNodes().OfType<ImplicitArrayCreationExpressionSyntax>().Single(); Assert.Equal("System.Object?[]", model.GetTypeInfo(invocationNode).Type.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_ConditionalOperator_WithoutType_WithDefaultLiterals() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F<U>(bool b) where U : new() { M(() => { if (b) return b ? default : default; else return new U(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var defaultNode = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", defaultNode.ToString()); Assert.Equal("U?", model.GetTypeInfo(defaultNode).Type.ToTestDisplayString()); Assert.Equal("U?", model.GetTypeInfo(defaultNode).ConvertedType.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model.GetTypeInfo(defaultNode).ConvertedNullability.FlowState); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<U>(System.Func<U> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( // (9,24): warning CS8603: Possible null reference return. // return b ? default : default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? default : default").WithLocation(9, 24) ); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_ConditionalOperator_WithoutType_WithDefaultLiterals_StructType() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F<U>(bool b) where U : struct { M(() => { if (b) return b ? default : default; else return new U(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var defaultNode = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("default", defaultNode.ToString()); Assert.Equal("U", model.GetTypeInfo(defaultNode).Type.ToTestDisplayString()); Assert.Equal("U", model.GetTypeInfo(defaultNode).ConvertedType.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableFlowState.NotNull, model.GetTypeInfo(defaultNode).ConvertedNullability.FlowState); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<U>(System.Func<U> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_ConditionalOperator_WithoutType_WithMaybeNullVariables() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { Program? x = null; string? y = null; if (b) return b ? x : y; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( // (11,24): warning CS8603: Possible null reference return. // return b ? x : y; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? x : y").WithLocation(11, 24) ); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_ConditionalOperator_WithoutType_WithNotNullVariables() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { Program? x = new(); string? y = string.Empty; if (b) return b ? x : y; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954"), WorkItem(51403, "https://github.com/dotnet/roslyn/issues/51403")] public void ReturningValues_ConditionalOperator_WithoutType_WithMaybeNullVariables_UserDefinedConversion() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool @bool, A a, B? b, C? c) { M(() => { if (@bool) return @bool ? b : c; else return a; }); } } class A {} class B { public static implicit operator A(B? b) => new A(); } class C { public static implicit operator A(C? c) => new A(); }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<A>(System.Func<A> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_SwitchExpression_WithoutType_NullLiteral() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { if (b) return b switch { _ => null }; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nullNode = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("null", nullNode.ToString()); Assert.Null(model.GetTypeInfo(nullNode).Type); Assert.Equal("System.Object?", model.GetTypeInfo(nullNode).ConvertedType.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableFlowState.MaybeNull, model.GetTypeInfo(nullNode).ConvertedNullability.FlowState); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( // (9,24): warning CS8603: Possible null reference return. // return b switch { _ => null }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { _ => null }").WithLocation(9, 24) ); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_SwitchExpression_WithoutType_WithMaybeNullVariables() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { Program? x = null; string? y = null; if (b) return b switch { true => x, _ => y }; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( // (11,24): warning CS8603: Possible null reference return. // return b switch { true => x, _ => y }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { true => x, _ => y }").WithLocation(11, 24) ); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_SwitchExpression_WithoutType_WithNotNullVariables() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { Program? x = new(); string? y = string.Empty; if (b) return b switch { true => x, _ => y }; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954"), WorkItem(51403, "https://github.com/dotnet/roslyn/issues/51403")] public void ReturningValues_SwitchExpression_WithoutType_WithMaybeNullVariables_UserDefinedConversion() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool @bool, A a, B? b, C? c) { M(() => { if (@bool) return @bool switch { true => b, false => c }; else return a; }); } } class A {} class B { public static implicit operator A(B? b) => new A(); } class C { public static implicit operator A(C? c) => new A(); }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<A>(System.Func<A> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_WithoutType_New() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { if (b) return new(); else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var newNode = tree.GetRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().First(); Assert.Equal("new()", newNode.ToString()); Assert.Equal("System.Object", model.GetTypeInfo(newNode).Type.ToTestDisplayString()); Assert.Equal("System.Object", model.GetTypeInfo(newNode).ConvertedType.ToTestDisplayString()); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object>(System.Func<System.Object> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_WithoutType_NewWithArguments() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { if (b) return new(null); else return new Program(string.Empty); }); } Program(string s) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var newNode = tree.GetRoot().DescendantNodes().OfType<ImplicitObjectCreationExpressionSyntax>().First(); Assert.Equal("new(null)", newNode.ToString()); Assert.Equal("Program", model.GetTypeInfo(newNode).Type.ToTestDisplayString()); Assert.Equal("Program", model.GetTypeInfo(newNode).ConvertedType.ToTestDisplayString()); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<Program>(System.Func<Program> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( // (10,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // return new(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 28) ); } [Fact, WorkItem(46954, "https://github.com/dotnet/roslyn/issues/46954")] public void ReturningValues_WithoutType() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b) { M(() => { if (b) return null; else return new object(); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var nullNode = tree.GetRoot().DescendantNodes().OfType<LiteralExpressionSyntax>().First(); Assert.Equal("null", nullNode.ToString()); Assert.Null(model.GetTypeInfo(nullNode).Type); Assert.Equal("System.Object?", model.GetTypeInfo(nullNode).ConvertedType.ToTestDisplayString()); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Object?>(System.Func<System.Object?> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact, WorkItem(44339, "https://github.com/dotnet/roslyn/issues/44339")] public void TypeInference_LambdasWithNullsAndDefaults() { var source = @" #nullable enable public class C<T1, T2> { public void M1(bool b) { var map = new C<string, string>(); map.GetOrAdd("""", _ => default); // 1 map.GetOrAdd("""", _ => null); // 2 map.GetOrAdd("""", _ => { if (b) return default; return """"; }); // 3 map.GetOrAdd("""", _ => { if (b) return null; return """"; }); // 4 map.GetOrAdd("""", _ => { if (b) return """"; return null; }); // 5 } } public static class Extensions { public static V GetOrAdd<K, V>(this C<K, V> dictionary, K key, System.Func<K, V> function) => throw null!; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,31): warning CS8603: Possible null reference return. // map.GetOrAdd("", _ => default); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(10, 31), // (11,31): warning CS8603: Possible null reference return. // map.GetOrAdd("", _ => null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(11, 31), // (13,9): warning CS8620: Argument of type 'C<string, string>' cannot be used for parameter 'dictionary' of type 'C<string, string?>' in 'string? Extensions.GetOrAdd<string, string?>(C<string, string?> dictionary, string key, Func<string, string?> function)' due to differences in the nullability of reference types. // map.GetOrAdd("", _ => { if (b) return default; return ""; }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "map").WithArguments("C<string, string>", "C<string, string?>", "dictionary", "string? Extensions.GetOrAdd<string, string?>(C<string, string?> dictionary, string key, Func<string, string?> function)").WithLocation(13, 9), // (14,9): warning CS8620: Argument of type 'C<string, string>' cannot be used for parameter 'dictionary' of type 'C<string, string?>' in 'string? Extensions.GetOrAdd<string, string?>(C<string, string?> dictionary, string key, Func<string, string?> function)' due to differences in the nullability of reference types. // map.GetOrAdd("", _ => { if (b) return null; return ""; }); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "map").WithArguments("C<string, string>", "C<string, string?>", "dictionary", "string? Extensions.GetOrAdd<string, string?>(C<string, string?> dictionary, string key, Func<string, string?> function)").WithLocation(14, 9), // (15,9): warning CS8620: Argument of type 'C<string, string>' cannot be used for parameter 'dictionary' of type 'C<string, string?>' in 'string? Extensions.GetOrAdd<string, string?>(C<string, string?> dictionary, string key, Func<string, string?> function)' due to differences in the nullability of reference types. // map.GetOrAdd("", _ => { if (b) return ""; return null; }); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "map").WithArguments("C<string, string>", "C<string, string?>", "dictionary", "string? Extensions.GetOrAdd<string, string?>(C<string, string?> dictionary, string key, Func<string, string?> function)").WithLocation(15, 9) ); } [Fact, WorkItem(43536, "https://github.com/dotnet/roslyn/issues/43536")] public void TypeInference_StringAndNullOrDefault() { var source = @" #nullable enable class C { void M(string s) { Infer(s, default); Infer(s, null); } T Infer<T>(T t1, T t2) => t1 ?? t2; } "; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("System.String? C.Infer<System.String?>(System.String? t1, System.String? t2)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); var invocationNode2 = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Last(); Assert.Equal("System.String? C.Infer<System.String?>(System.String? t1, System.String? t2)", model.GetSymbolInfo(invocationNode2).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics( ); } [Fact] public void ConditionalOperator_WithoutType_Lambda() { var source = @"class Program { static void M<T>(System.Func<T> t) { } static void F(bool b, System.Action a) { M(() => { if (b) return () => { }; else return a; }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var lambdaNode = tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Last(); Assert.Equal("() => { }", lambdaNode.ToString()); Assert.Null(model.GetTypeInfo(lambdaNode).Type); Assert.Equal("System.Action", model.GetTypeInfo(lambdaNode).ConvertedType.ToTestDisplayString()); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void Program.M<System.Action>(System.Func<System.Action> t)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); comp.VerifyDiagnostics(); } [Fact] public void ConditionalOperator_TopLevelNullability() { var source = @"class C { static void F(bool b, object? x, object y) { object? o; o = (b ? x : x)/*T:object?*/; o = (b ? x : y)/*T:object?*/; o = (b ? y : x)/*T:object?*/; o = (b ? y : y)/*T:object!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] [Fact] public void ConditionalOperator_NestedNullability_Invariant() { var source0 = @"public class A { public static B<object> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F(bool b, B<object?> x, B<object> y) { var z = A.F/*T:B<object>!*/; object o; o = (b ? x : x)/*T:B<object?>!*/; o = (b ? x : y)/*T:B<object!>!*/; // 1 o = (b ? x : z)/*T:B<object?>!*/; o = (b ? y : x)/*T:B<object!>!*/; // 2 o = (b ? y : y)/*T:B<object!>!*/; o = (b ? y : z)/*T:B<object!>!*/; o = (b ? z : x)/*T:B<object?>!*/; o = (b ? z : y)/*T:B<object!>!*/; o = (b ? z : z)/*T:B<object>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,18): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // o = (b ? x : y)/*T:B<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(8, 18), // (10,22): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // o = (b ? y : x)/*T:B<object!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(10, 22) ); comp.VerifyTypes(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void ConditionalOperator_NestedNullability_Variant() { var source0 = @"public class A { public static I<object> F; public static IIn<object> FIn; public static IOut<object> FOut; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F1(bool b, I<object> x, I<object?> y) { var z = A.F/*T:I<object>!*/; object o; o = (b ? x : x)/*T:I<object!>!*/; o = (b ? x : y)/*T:I<object!>!*/; // 1 o = (b ? x : z)/*T:I<object!>!*/; o = (b ? y : x)/*T:I<object!>!*/; // 2 o = (b ? y : y)/*T:I<object?>!*/; o = (b ? y : z)/*T:I<object?>!*/; o = (b ? z : x)/*T:I<object!>!*/; o = (b ? z : y)/*T:I<object?>!*/; o = (b ? z : z)/*T:I<object>!*/; } static void F2(bool b, IIn<object> x, IIn<object?> y) { var z = A.FIn/*T:IIn<object>!*/; object o; o = (b ? x : x)/*T:IIn<object!>!*/; o = (b ? x : y)/*T:IIn<object!>!*/; o = (b ? x : z)/*T:IIn<object!>!*/; o = (b ? y : x)/*T:IIn<object!>!*/; o = (b ? y : y)/*T:IIn<object?>!*/; o = (b ? y : z)/*T:IIn<object>!*/; o = (b ? z : x)/*T:IIn<object!>!*/; o = (b ? z : y)/*T:IIn<object>!*/; o = (b ? z : z)/*T:IIn<object>!*/; } static void F3(bool b, IOut<object> x, IOut<object?> y) { var z = A.FOut/*T:IOut<object>!*/; object o; o = (b ? x : x)/*T:IOut<object!>!*/; o = (b ? x : y)/*T:IOut<object?>!*/; o = (b ? x : z)/*T:IOut<object>!*/; o = (b ? y : x)/*T:IOut<object?>!*/; o = (b ? y : y)/*T:IOut<object?>!*/; o = (b ? y : z)/*T:IOut<object?>!*/; o = (b ? z : x)/*T:IOut<object>!*/; o = (b ? z : y)/*T:IOut<object?>!*/; o = (b ? z : z)/*T:IOut<object>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,22): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // o = (b ? x : y)/*T:I<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(8, 22), // (10,18): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // o = (b ? y : x)/*T:I<object!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(10, 18) ); comp.VerifyTypes(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void ConditionalOperator_NestedNullability_VariantAndInvariant() { var source0 = @"public class A { public static IIn<object, string> F1; public static IOut<object, string> F2; } public interface IIn<in T, U> { } public interface IOut<T, out U> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F1(bool b, IIn<object, string> x1, IIn<object?, string?> y1) { var z1 = A.F1/*T:IIn<object, string>!*/; object o; o = (b ? x1 : x1)/*T:IIn<object!, string!>!*/; o = (b ? x1 : y1)/*T:IIn<object!, string!>!*/; // 1 o = (b ? x1 : z1)/*T:IIn<object!, string!>!*/; o = (b ? y1 : x1)/*T:IIn<object!, string!>!*/; // 2 o = (b ? y1 : y1)/*T:IIn<object?, string?>!*/; o = (b ? y1 : z1)/*T:IIn<object, string?>!*/; o = (b ? z1 : x1)/*T:IIn<object!, string!>!*/; o = (b ? z1 : y1)/*T:IIn<object, string?>!*/; o = (b ? z1 : z1)/*T:IIn<object, string>!*/; } static void F2(bool b, IOut<object, string> x2, IOut<object?, string?> y2) { var z2 = A.F2/*T:IOut<object, string>!*/; object o; o = (b ? x2 : x2)/*T:IOut<object!, string!>!*/; o = (b ? x2 : y2)/*T:IOut<object!, string?>!*/; // 3 o = (b ? x2 : z2)/*T:IOut<object!, string>!*/; o = (b ? y2 : x2)/*T:IOut<object!, string?>!*/; // 4 o = (b ? y2 : y2)/*T:IOut<object?, string?>!*/; o = (b ? y2 : z2)/*T:IOut<object?, string?>!*/; o = (b ? z2 : x2)/*T:IOut<object!, string>!*/; o = (b ? z2 : y2)/*T:IOut<object?, string?>!*/; o = (b ? z2 : z2)/*T:IOut<object, string>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,23): warning CS8619: Nullability of reference types in value of type 'IIn<object?, string?>' doesn't match target type 'IIn<object, string>'. // o = (b ? x1 : y1)/*T:IIn<object!, string!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("IIn<object?, string?>", "IIn<object, string>").WithLocation(8, 23), // (10,18): warning CS8619: Nullability of reference types in value of type 'IIn<object?, string?>' doesn't match target type 'IIn<object, string>'. // o = (b ? y1 : x1)/*T:IIn<object!, string!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("IIn<object?, string?>", "IIn<object, string>").WithLocation(10, 18), // (22,23): warning CS8619: Nullability of reference types in value of type 'IOut<object?, string?>' doesn't match target type 'IOut<object, string?>'. // o = (b ? x2 : y2)/*T:IOut<object!, string?>!*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y2").WithArguments("IOut<object?, string?>", "IOut<object, string?>").WithLocation(22, 23), // (24,18): warning CS8619: Nullability of reference types in value of type 'IOut<object?, string?>' doesn't match target type 'IOut<object, string?>'. // o = (b ? y2 : x2)/*T:IOut<object!, string?>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y2").WithArguments("IOut<object?, string?>", "IOut<object, string?>").WithLocation(24, 18) ); comp.VerifyTypes(); } [Fact] public void ConditionalOperator_NestedNullability_Tuples() { var source0 = @"public class A { public static I<object> F; } public interface I<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @" class C { static void F1(bool b, object x1, object? y1) { object o; o = (b ? (x1, x1) : (x1, y1))/*T:(object!, object?)*/; o = (b ? (x1, y1) : (y1, y1))/*T:(object?, object?)*/; } static void F2(bool b, I<object> x2, I<object?> y2) { var z2 = A.F/*T:I<object>!*/; object o; o = (b ? (x2, x2) : (x2, y2))/*T:(I<object!>!, I<object!>!)*/; o = (b ? (z2, x2) : (x2, x2))/*T:(I<object!>!, I<object!>!)*/; o = (b ? (y2, y2) : (y2, z2))/*T:(I<object?>!, I<object?>!)*/; o = (b ? (x2, y2) : (y2, y2))/*T:(I<object!>!, I<object?>!)*/; o = (b ? (z2, z2) : (z2, x2))/*T:(I<object>!, I<object!>!)*/; o = (b ? (y2, z2) : (z2, z2))/*T:(I<object?>!, I<object>!)*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (14,29): warning CS8619: Nullability of reference types in value of type '(I<object> x2, I<object?> y2)' doesn't match target type '(I<object>, I<object>)'. // o = (b ? (x2, x2) : (x2, y2))/*T:(I<object!>!, I<object!>!)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x2, y2)").WithArguments("(I<object> x2, I<object?> y2)", "(I<object>, I<object>)").WithLocation(14, 29), // (17,29): warning CS8619: Nullability of reference types in value of type '(I<object?>, I<object?>)' doesn't match target type '(I<object>, I<object?>)'. // o = (b ? (x2, y2) : (y2, y2))/*T:(I<object!>!, I<object?>!)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(y2, y2)").WithArguments("(I<object?>, I<object?>)", "(I<object>, I<object?>)").WithLocation(17, 29) ); comp.VerifyTypes(); } [WorkItem(30432, "https://github.com/dotnet/roslyn/issues/30432")] [Fact] public void ConditionalOperator_TopLevelNullability_Ref() { var source0 = @"public class A { public static object F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F(bool b, object? x, object y) { ref var xx = ref b ? ref x : ref x; ref var xy = ref b ? ref x : ref y; // 1 ref var xz = ref b ? ref x : ref A.F; ref var yx = ref b ? ref y : ref x; // 2 ref var yy = ref b ? ref y : ref y; ref var yz = ref b ? ref y : ref A.F; ref var zx = ref b ? ref A.F : ref x; ref var zy = ref b ? ref A.F : ref y; ref var zz = ref b ? ref A.F : ref A.F; } }"; var comp = CreateCompilation(source, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (6,26): warning CS8619: Nullability of reference types in value of type 'object?' doesn't match target type 'object'. // ref var xy = ref b ? ref x : ref y; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x : ref y").WithArguments("object?", "object").WithLocation(6, 26), // (8,26): warning CS8619: Nullability of reference types in value of type 'object' doesn't match target type 'object?'. // ref var yx = ref b ? ref y : ref x; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y : ref x").WithArguments("object", "object?").WithLocation(8, 26) ); } [WorkItem(30432, "https://github.com/dotnet/roslyn/issues/30432")] [Fact] public void ConditionalOperator_NestedNullability_Ref() { var source0 = @"public class A { public static I<object> IOblivious; public static IIn<object> IInOblivious; public static IOut<object> IOutOblivious; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F1(bool b, I<object> x1, I<object?> y1) { var z1 = A.IOblivious/*T:I<object>!*/; ref var xx = ref b ? ref x1 : ref x1; ref var xy = ref b ? ref x1 : ref y1; // 1 ref var xz = ref b ? ref x1 : ref z1; // 2 ref var yx = ref b ? ref y1 : ref x1; // 3 ref var yy = ref b ? ref y1 : ref y1; ref var yz = ref b ? ref y1 : ref z1; // 4 ref var zx = ref b ? ref z1 : ref x1; // 5 ref var zy = ref b ? ref z1 : ref y1; // 6 ref var zz = ref b ? ref z1 : ref z1; } static void F2(bool b, IIn<object> x2, IIn<object?> y2) { var z2 = A.IInOblivious/*T:IIn<object>!*/; ref var xx = ref b ? ref x2 : ref x2; ref var xy = ref b ? ref x2 : ref y2; // 7 ref var xz = ref b ? ref x2 : ref z2; // 8 ref var yx = ref b ? ref y2 : ref x2; // 9 ref var yy = ref b ? ref y2 : ref y2; ref var yz = ref b ? ref y2 : ref z2; // 10 ref var zx = ref b ? ref z2 : ref x2; // 11 ref var zy = ref b ? ref z2 : ref y2; // 12 ref var zz = ref b ? ref z2 : ref z2; } static void F3(bool b, IOut<object> x3, IOut<object?> y3) { var z3 = A.IOutOblivious/*T:IOut<object>!*/; ref var xx = ref b ? ref x3 : ref x3; ref var xy = ref b ? ref x3 : ref y3; // 13 ref var xz = ref b ? ref x3 : ref z3; // 14 ref var yx = ref b ? ref y3 : ref x3; // 15 ref var yy = ref b ? ref y3 : ref y3; // 16 ref var yz = ref b ? ref y3 : ref z3; // 17 ref var zx = ref b ? ref z3 : ref x3; // 18 ref var zy = ref b ? ref z3 : ref y3; // 19 ref var zz = ref b ? ref z3 : ref z3; } }"; var comp = CreateCompilation(source, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (7,26): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // ref var xy = ref b ? ref x1 : ref y1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x1 : ref y1").WithArguments("I<object>", "I<object?>").WithLocation(7, 26), // (8,26): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object>?'. // ref var xz = ref b ? ref x1 : ref z1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x1 : ref z1").WithArguments("I<object>", "I<object>?").WithLocation(8, 26), // (9,26): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // ref var yx = ref b ? ref y1 : ref x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y1 : ref x1").WithArguments("I<object?>", "I<object>").WithLocation(9, 26), // (11,26): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>?'. // ref var yz = ref b ? ref y1 : ref z1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y1 : ref z1").WithArguments("I<object?>", "I<object>?").WithLocation(11, 26), // (12,26): warning CS8619: Nullability of reference types in value of type 'I<object>?' doesn't match target type 'I<object>'. // ref var zx = ref b ? ref z1 : ref x1; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref z1 : ref x1").WithArguments("I<object>?", "I<object>").WithLocation(12, 26), // (13,26): warning CS8619: Nullability of reference types in value of type 'I<object>?' doesn't match target type 'I<object?>'. // ref var zy = ref b ? ref z1 : ref y1; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref z1 : ref y1").WithArguments("I<object>?", "I<object?>").WithLocation(13, 26), // (20,26): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // ref var xy = ref b ? ref x2 : ref y2; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x2 : ref y2").WithArguments("IIn<object>", "IIn<object?>").WithLocation(20, 26), // (21,26): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object>?'. // ref var xz = ref b ? ref x2 : ref z2; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x2 : ref z2").WithArguments("IIn<object>", "IIn<object>?").WithLocation(21, 26), // (22,26): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'IIn<object>'. // ref var yx = ref b ? ref y2 : ref x2; // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y2 : ref x2").WithArguments("IIn<object?>", "IIn<object>").WithLocation(22, 26), // (24,26): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'IIn<object>?'. // ref var yz = ref b ? ref y2 : ref z2; // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y2 : ref z2").WithArguments("IIn<object?>", "IIn<object>?").WithLocation(24, 26), // (25,26): warning CS8619: Nullability of reference types in value of type 'IIn<object>?' doesn't match target type 'IIn<object>'. // ref var zx = ref b ? ref z2 : ref x2; // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref z2 : ref x2").WithArguments("IIn<object>?", "IIn<object>").WithLocation(25, 26), // (26,26): warning CS8619: Nullability of reference types in value of type 'IIn<object>?' doesn't match target type 'IIn<object?>'. // ref var zy = ref b ? ref z2 : ref y2; // 12 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref z2 : ref y2").WithArguments("IIn<object>?", "IIn<object?>").WithLocation(26, 26), // (33,26): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'IOut<object?>'. // ref var xy = ref b ? ref x3 : ref y3; // 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x3 : ref y3").WithArguments("IOut<object>", "IOut<object?>").WithLocation(33, 26), // (34,26): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'IOut<object>?'. // ref var xz = ref b ? ref x3 : ref z3; // 14 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x3 : ref z3").WithArguments("IOut<object>", "IOut<object>?").WithLocation(34, 26), // (35,26): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // ref var yx = ref b ? ref y3 : ref x3; // 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y3 : ref x3").WithArguments("IOut<object?>", "IOut<object>").WithLocation(35, 26), // (37,26): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>?'. // ref var yz = ref b ? ref y3 : ref z3; // 17 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y3 : ref z3").WithArguments("IOut<object?>", "IOut<object>?").WithLocation(37, 26), // (38,26): warning CS8619: Nullability of reference types in value of type 'IOut<object>?' doesn't match target type 'IOut<object>'. // ref var zx = ref b ? ref z3 : ref x3; // 18 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref z3 : ref x3").WithArguments("IOut<object>?", "IOut<object>").WithLocation(38, 26), // (39,26): warning CS8619: Nullability of reference types in value of type 'IOut<object>?' doesn't match target type 'IOut<object?>'. // ref var zy = ref b ? ref z3 : ref y3; // 19 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref z3 : ref y3").WithArguments("IOut<object>?", "IOut<object?>").WithLocation(39, 26) ); comp.VerifyTypes(); } [Fact, WorkItem(33664, "https://github.com/dotnet/roslyn/issues/33664")] public void ConditionalOperator_AssigningToRefConditional() { var source0 = @"public class A { public static string F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var comp = CreateCompilation(@" class C { void M(bool c, ref string x, ref string? y) { (c ? ref x : ref y) = null; // 1, 2 } void M2(bool c, ref string x, ref string? y) { (c ? ref y : ref x) = null; // 3, 4 } void M3(bool c, ref string x, ref string? y) { (c ? ref x : ref A.F) = null; // 5 (c ? ref y : ref A.F) = null; } void M4(bool c, ref string x, ref string? y) { (c ? ref A.F : ref x) = null; // 6 (c ? ref A.F : ref y) = null; } }", options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (6,10): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // (c ? ref x : ref y) = null; // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? ref x : ref y").WithArguments("string", "string?").WithLocation(6, 10), // (6,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // (c ? ref x : ref y) = null; // 1, 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 31), // (10,10): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // (c ? ref y : ref x) = null; // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? ref y : ref x").WithArguments("string?", "string").WithLocation(10, 10), // (10,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // (c ? ref y : ref x) = null; // 3, 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 31), // (14,33): warning CS8625: Cannot convert null literal to non-nullable reference type. // (c ? ref x : ref A.F) = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 33), // (19,33): warning CS8625: Cannot convert null literal to non-nullable reference type. // (c ? ref A.F : ref x) = null; // 6 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 33) ); } [Fact] public void IdentityConversion_ConditionalOperator() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(bool c, I<object> x, I<object?> y) { I<object> a; a = c ? x : y; a = false ? x : y; a = true ? x : y; // ok I<object?> b; b = c ? x : y; b = false ? x : y; b = true ? x : y; } static void F(bool c, IIn<object> x, IIn<object?> y) { IIn<object> a; a = c ? x : y; a = false ? x : y; a = true ? x : y; IIn<object?> b; b = c ? x : y; b = false ? x : y; b = true ? x : y; } static void F(bool c, IOut<object> x, IOut<object?> y) { IOut<object> a; a = c ? x : y; a = false ? x : y; a = true ? x : y; IOut<object?> b; b = c ? x : y; b = false ? x : y; b = true ? x : y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,21): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // a = c ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(9, 21), // (10,25): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // a = false ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(10, 25), // (13,13): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // b = c ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x : y").WithArguments("I<object>", "I<object?>").WithLocation(13, 13), // (13,21): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // b = c ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(13, 21), // (14,13): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // b = false ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "false ? x : y").WithArguments("I<object>", "I<object?>").WithLocation(14, 13), // (14,25): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // b = false ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(14, 25), // (15,13): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // b = true ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "true ? x : y").WithArguments("I<object>", "I<object?>").WithLocation(15, 13), // (24,13): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // b = c ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x : y").WithArguments("IIn<object>", "IIn<object?>").WithLocation(24, 13), // (25,13): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // b = false ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "false ? x : y").WithArguments("IIn<object>", "IIn<object?>").WithLocation(25, 13), // (26,13): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // b = true ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "true ? x : y").WithArguments("IIn<object>", "IIn<object?>").WithLocation(26, 13), // (31,13): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // a = c ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x : y").WithArguments("IOut<object?>", "IOut<object>").WithLocation(31, 13), // (32,13): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // a = false ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "false ? x : y").WithArguments("IOut<object?>", "IOut<object>").WithLocation(32, 13), // (33,13): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // a = true ? x : y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "true ? x : y").WithArguments("IOut<object?>", "IOut<object>").WithLocation(33, 13)); } [Fact] public void NullCoalescingOperator_01() { var source = @"class C { static void F(object? x, object? y) { var z = x ?? y; z.ToString(); if (y == null) return; var w = x ?? y; w.ToString(); var v = null ?? x; v.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(6, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // v.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v").WithLocation(11, 9)); } [Fact] public void NullCoalescingOperator_02() { var source = @"class C { static void F(int i, object? x, object? y) { switch (i) { case 1: (x ?? y).ToString(); // 1 break; case 2: if (y != null) (x ?? y).ToString(); break; case 3: if (y != null) (y ?? x).ToString(); // 2 break; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,18): warning CS8602: Dereference of a possibly null reference. // (x ?? y).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x ?? y").WithLocation(8, 18), // (14,33): warning CS8602: Dereference of a possibly null reference. // if (y != null) (y ?? x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y ?? x").WithLocation(14, 33) ); } [Fact] public void NullCoalescingOperator_03() { var source = @"class C { static void F(object x, object? y) { (null ?? null).ToString(); (null ?? x).ToString(); (null ?? y).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,10): error CS0019: Operator '??' cannot be applied to operands of type '<null>' and '<null>' // (null ?? null).ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "null ?? null").WithArguments("??", "<null>", "<null>").WithLocation(5, 10), // (7,10): warning CS8602: Dereference of a possibly null reference. // (null ?? y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "null ?? y").WithLocation(7, 10)); } [Fact] public void NullCoalescingOperator_04() { var source = @"class C { static void F(string x, string? y) { ("""" ?? x).ToString(); ("""" ?? y).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); } [Fact] public void NullCoalescingOperator_05() { var source0 = @"public class A { } public class B { } public class UnknownNull { public A A; public B B; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source1 = @"public class MaybeNull { public A? A; public B? B; } public class NotNull { public A A = new A(); public B B = new B(); }"; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { ref0 }); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var source = @"class C { static void F1(UnknownNull x1, UnknownNull y1) { (x1.A ?? y1.B)/*T:!*/.ToString(); } static void F2(UnknownNull x2, MaybeNull y2) { (x2.A ?? y2.B)/*T:!*/.ToString(); } static void F3(MaybeNull x3, UnknownNull y3) { (x3.A ?? y3.B)/*T:!*/.ToString(); } static void F4(MaybeNull x4, MaybeNull y4) { (x4.A ?? y4.B)/*T:!*/.ToString(); } static void F5(UnknownNull x5, NotNull y5) { (x5.A ?? y5.B)/*T:!*/.ToString(); } static void F6(NotNull x6, UnknownNull y6) { (x6.A ?? y6.B)/*T:!*/.ToString(); } static void F7(MaybeNull x7, NotNull y7) { (x7.A ?? y7.B)/*T:!*/.ToString(); } static void F8(NotNull x8, MaybeNull y8) { (x8.A ?? y8.B)/*T:!*/.ToString(); } static void F9(NotNull x9, NotNull y9) { (x9.A ?? y9.B)/*T:!*/.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0, ref1 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (5,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x1.A ?? y1.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1.A ?? y1.B").WithArguments("??", "A", "B").WithLocation(5, 10), // (9,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x2.A ?? y2.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x2.A ?? y2.B").WithArguments("??", "A", "B").WithLocation(9, 10), // (13,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x3.A ?? y3.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x3.A ?? y3.B").WithArguments("??", "A", "B").WithLocation(13, 10), // (17,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x4.A ?? y4.B)/*T:?*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x4.A ?? y4.B").WithArguments("??", "A", "B").WithLocation(17, 10), // (21,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x5.A ?? y5.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x5.A ?? y5.B").WithArguments("??", "A", "B").WithLocation(21, 10), // (25,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x6.A ?? y6.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x6.A ?? y6.B").WithArguments("??", "A", "B").WithLocation(25, 10), // (29,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x7.A ?? y7.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x7.A ?? y7.B").WithArguments("??", "A", "B").WithLocation(29, 10), // (33,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x8.A ?? y8.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x8.A ?? y8.B").WithArguments("??", "A", "B").WithLocation(33, 10), // (37,10): error CS0019: Operator '??' cannot be applied to operands of type 'A' and 'B' // (x9.A ?? y9.B)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x9.A ?? y9.B").WithArguments("??", "A", "B").WithLocation(37, 10) ); } [Fact] public void NullCoalescingOperator_06() { var source = @"class C { static void F1(int i, C x1, Unknown? y1) { switch (i) { case 1: (x1 ?? y1)/*T:!*/.ToString(); break; case 2: (y1 ?? x1)/*T:!*/.ToString(); break; case 3: (null ?? y1)/*T:Unknown?*/.ToString(); break; case 4: (y1 ?? null)/*T:Unknown!*/.ToString(); break; } } static void F2(int i, C? x2, Unknown y2) { switch (i) { case 1: (x2 ?? y2)/*T:!*/.ToString(); break; case 2: (y2 ?? x2)/*T:!*/.ToString(); break; case 3: (null ?? y2)/*T:!*/.ToString(); break; case 4: (y2 ?? null)/*T:!*/.ToString(); break; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // Note: Unknown type is treated as a value type comp.VerifyTypes(); comp.VerifyDiagnostics( // (3,33): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // static void F1(int i, C x1, Unknown? y1) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(3, 33), // (21,34): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // static void F2(int i, C? x2, Unknown y2) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(21, 34), // (8,18): error CS0019: Operator '??' cannot be applied to operands of type 'C' and 'Unknown?' // (x1 ?? y1)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x1 ?? y1").WithArguments("??", "C", "Unknown?").WithLocation(8, 18), // (11,18): error CS0019: Operator '??' cannot be applied to operands of type 'Unknown?' and 'C' // (y1 ?? x1)/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_BadBinaryOps, "y1 ?? x1").WithArguments("??", "Unknown?", "C").WithLocation(11, 18)); } [Fact] public void NullCoalescingOperator_07() { var source = @"class C { static void F(object? o, object[]? a, object?[]? b) { if (o == null) { var c = new[] { o }; (a ?? c)[0].ToString(); (b ?? c)[0].ToString(); } else { var c = new[] { o }; (a ?? c)[0].ToString(); (b ?? c)[0].ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // (a ?? c)[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(a ?? c)[0]").WithLocation(8, 13), // (9,13): warning CS8602: Dereference of a possibly null reference. // (b ?? c)[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b ?? c)[0]").WithLocation(9, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // (b ?? c)[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b ?? c)[0]").WithLocation(15, 13)); } [Fact] public void NullCoalescingOperator_08() { var source = @"interface I<T> { } class C { static object? F((I<object>, I<object?>)? x, (I<object?>, I<object>)? y) { return x ?? y; } static object F((I<object>, I<object?>)? x, (I<object?>, I<object>) y) { return x ?? y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,21): warning CS8619: Nullability of reference types in value of type '(I<object?>, I<object>)?' doesn't match target type '(I<object>, I<object?>)?'. // return x ?? y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("(I<object?>, I<object>)?", "(I<object>, I<object?>)?").WithLocation(6, 21), // (10,21): warning CS8619: Nullability of reference types in value of type '(I<object?>, I<object>)' doesn't match target type '(I<object>, I<object?>)'. // return x ?? y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("(I<object?>, I<object>)", "(I<object>, I<object?>)").WithLocation(10, 21)); } [Fact, WorkItem(51975, "https://github.com/dotnet/roslyn/issues/51975")] public void NullCoalescingOperator_09() { var source = @"C? c = new C(); D d = c ?? new D(); d.ToString(); class C {} class D { public static implicit operator D?(C c) => default; } "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (2,7): warning CS8600: Converting null literal or possible null value to non-nullable type. // D d = c ?? new D(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ?? new D()").WithLocation(2, 7), // (4,1): warning CS8602: Dereference of a possibly null reference. // d.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d").WithLocation(4, 1) ); } [Fact, WorkItem(51975, "https://github.com/dotnet/roslyn/issues/51975")] public void NullCoalescingOperator_10() { var source = @"C? c = new C(); D d = c ?? new D(); d.ToString(); class C { public static implicit operator D?(C c) => default; } class D {} "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (2,7): warning CS8600: Converting null literal or possible null value to non-nullable type. // D d = c ?? new D(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ?? new D()").WithLocation(2, 7), // (4,1): warning CS8602: Dereference of a possibly null reference. // d.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d").WithLocation(4, 1) ); } [Fact, WorkItem(51975, "https://github.com/dotnet/roslyn/issues/51975")] public void NullCoalescingOperator_11() { var source = @"C? c = new C(); D d = c ?? new D(); d.ToString(); struct C { public static implicit operator D?(C c) => default; } class D {} "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (2,7): warning CS8600: Converting null literal or possible null value to non-nullable type. // D d = c ?? new D(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ?? new D()").WithLocation(2, 7), // (4,1): warning CS8602: Dereference of a possibly null reference. // d.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d").WithLocation(4, 1) ); } [Fact, WorkItem(51975, "https://github.com/dotnet/roslyn/issues/51975")] public void NullCoalescingOperator_12() { var source = @"C? c = new C(); C c2 = c ?? new D(); c2.ToString(); class C { public static implicit operator C?(D c) => default; } class D {} "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (2,8): warning CS8600: Converting null literal or possible null value to non-nullable type. // C c2 = c ?? new D(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ?? new D()").WithLocation(2, 8), // (4,1): warning CS8602: Dereference of a possibly null reference. // c2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(4, 1) ); } [Fact, WorkItem(29955, "https://github.com/dotnet/roslyn/issues/29955")] public void NullCoalescingOperator_13() { var source = @"C<string?> c = new C<string?>(); C<string?> c2 = c ?? new D<string>(); c2.ToString(); class C<T> { public static implicit operator C<T>(D<T> c) => default!; } class D<T> {} "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (2,22): warning CS8619: Nullability of reference types in value of type 'D<string>' doesn't match target type 'D<string?>'. // C<string?> c2 = c ?? new D<string>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new D<string>()").WithArguments("D<string>", "D<string?>").WithLocation(2, 22) ); } [Fact, WorkItem(29955, "https://github.com/dotnet/roslyn/issues/29955")] public void NullCoalescingOperator_14() { var source = @"using System; Action<string?> a1 = param => {}; Action<string?> a2 = a1 ?? ((string s) => {}); "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (3,29): warning CS8622: Nullability of reference types in type of parameter 's' of 'lambda expression' doesn't match the target delegate 'Action<string?>' (possibly because of nullability attributes). // Action<string?> a2 = a1 ?? ((string s) => {}); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(string s) => {}").WithArguments("s", "lambda expression", "System.Action<string?>").WithLocation(3, 29) ); } [Fact, WorkItem(29955, "https://github.com/dotnet/roslyn/issues/29955")] public void NullCoalescingOperator_15() { var source = @"using System; Action<string?> a1 = param => {}; Action<string?> a2 = a1 ?? (Action<string>)((string s) => {}); "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (3,22): warning CS8619: Nullability of reference types in value of type 'Action<string>' doesn't match target type 'Action<string?>'. // Action<string?> a2 = a1 ?? (Action<string>)((string s) => {}); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1 ?? (Action<string>)((string s) => {})").WithArguments("System.Action<string>", "System.Action<string?>").WithLocation(3, 22) ); } [Fact, WorkItem(29955, "https://github.com/dotnet/roslyn/issues/29955")] public void NullCoalescingOperator_16() { var source = @"using System; Func<string> a1 = () => string.Empty; Func<string> a2 = a1 ?? (() => null); "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (3,32): warning CS8603: Possible null reference return. // Func<string> a2 = a1 ?? (() => null); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(3, 32) ); } [Fact, WorkItem(29955, "https://github.com/dotnet/roslyn/issues/29955")] public void NullCoalescingOperator_17() { var source = @"using System; Func<string> a1 = () => string.Empty; Func<string> a2 = a1 ?? (Func<string?>)(() => null); "; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (3,19): warning CS8619: Nullability of reference types in value of type 'Func<string?>' doesn't match target type 'Func<string>'. // Func<string> a2 = a1 ?? (Func<string?>)(() => null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1 ?? (Func<string?>)(() => null)").WithArguments("System.Func<string?>", "System.Func<string>").WithLocation(3, 19) ); } [Fact, WorkItem(51975, "https://github.com/dotnet/roslyn/issues/51975")] public void NullCoalescingOperator_18() { var source = @"using System.Diagnostics.CodeAnalysis; C? c = new C(); D d1 = c ?? new D(); d1.ToString(); D d2 = ((C?)null) ?? new D(); d2.ToString(); c = null; D d3 = c ?? new D(); d3.ToString(); class C {} class D { [return: NotNullIfNotNull(""c"")] public static implicit operator D?(C c) => default!; } "; var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics(); } [Fact] public void IdentityConversion_NullCoalescingOperator_01() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F1(I<object>? x1, I<object?> y1) { I<object> z1 = x1 ?? y1; I<object?> w1 = y1 ?? x1; } static void F2(IIn<object>? x2, IIn<object?> y2) { IIn<object> z2 = x2 ?? y2; IIn<object?> w2 = y2 ?? x2; } static void F3(IOut<object>? x3, IOut<object?> y3) { IOut<object> z3 = x3 ?? y3; IOut<object?> w3 = y3 ?? x3; } static void F4(IIn<object>? x4, IIn<object> y4) { IIn<object> z4; z4 = ((IIn<object?>)x4) ?? y4; z4 = x4 ?? (IIn<object?>)y4; } static void F5(IIn<object?>? x5, IIn<object?> y5) { IIn<object> z5; z5 = ((IIn<object>)x5) ?? y5; z5 = x5 ?? (IIn<object>)y5; } static void F6(IOut<object?>? x6, IOut<object?> y6) { IOut<object?> z6; z6 = ((IOut<object>)x6) ?? y6; z6 = x6 ?? (IOut<object>)y6; } static void F7(IOut<object>? x7, IOut<object> y7) { IOut<object?> z7; z7 = ((IOut<object?>)x7) ?? y7; z7 = x7 ?? (IOut<object?>)y7; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,30): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // I<object> z1 = x1 ?? y1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("I<object?>", "I<object>").WithLocation(8, 30), // (9,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // I<object?> w1 = y1 ?? x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1 ?? x1").WithLocation(9, 25), // (9,31): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // I<object?> w1 = y1 ?? x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("I<object>", "I<object?>").WithLocation(9, 31), // (14,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // IIn<object?> w2 = y2 ?? x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2 ?? x2").WithLocation(14, 27), // (14,27): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // IIn<object?> w2 = y2 ?? x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y2 ?? x2").WithArguments("IIn<object>", "IIn<object?>").WithLocation(14, 27), // (18,27): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // IOut<object> z3 = x3 ?? y3; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3 ?? y3").WithArguments("IOut<object?>", "IOut<object>").WithLocation(18, 27), // (19,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // IOut<object?> w3 = y3 ?? x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y3 ?? x3").WithLocation(19, 28), // (24,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // z4 = ((IIn<object?>)x4) ?? y4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IIn<object?>)x4").WithLocation(24, 15), // (30,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // z5 = ((IIn<object>)x5) ?? y5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IIn<object>)x5").WithLocation(30, 15), // (36,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // z6 = ((IOut<object>)x6) ?? y6; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IOut<object>)x6").WithLocation(36, 15), // (42,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // z7 = ((IOut<object?>)x7) ?? y7; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IOut<object?>)x7").WithLocation(42, 15)); } [Fact] [WorkItem(35012, "https://github.com/dotnet/roslyn/issues/35012")] public void IdentityConversion_NullCoalescingOperator_02() { var source = @"interface IIn<in T> { } interface IOut<out T> { } class C { static IIn<T>? FIn<T>(T x) { return null; } static IOut<T>? FOut<T>(T x) { return null; } static void FIn(IIn<object?>? x) { } static T FOut<T>(IOut<T>? x) { throw new System.Exception(); } static void F1(IIn<object>? x1, IIn<object?>? y1) { FIn((x1 ?? y1)/*T:IIn<object!>?*/); FIn((y1 ?? x1)/*T:IIn<object!>?*/); } static void F2(IOut<object>? x2, IOut<object?>? y2) { FOut((x2 ?? y2)/*T:IOut<object?>?*/).ToString(); FOut((y2 ?? x2)/*T:IOut<object?>?*/).ToString(); } static void F3(object? x3, object? y3) { FIn((FIn(x3) ?? FIn(y3))/*T:IIn<object?>?*/); // A if (x3 == null) return; FIn((FIn(x3) ?? FIn(y3))/*T:IIn<object!>?*/); // B FIn((FIn(y3) ?? FIn(x3))/*T:IIn<object!>?*/); // C if (y3 == null) return; FIn((FIn(x3) ?? FIn(y3))/*T:IIn<object!>?*/); // D } static void F4(object? x4, object? y4) { FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object?>?*/).ToString(); // A if (x4 == null) return; FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object?>?*/).ToString(); // B FOut((FOut(y4) ?? FOut(x4))/*T:IOut<object?>?*/).ToString(); // C if (y4 == null) return; FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object!>?*/).ToString(); // D } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (22,14): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'x' in 'void C.FIn(IIn<object?>? x)'. // FIn((x1 ?? y1)/*T:IIn<object!>?*/); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1 ?? y1").WithArguments("IIn<object>", "IIn<object?>", "x", "void C.FIn(IIn<object?>? x)").WithLocation(22, 14), // (23,14): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'x' in 'void C.FIn(IIn<object?>? x)'. // FIn((y1 ?? x1)/*T:IIn<object!>?*/); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1 ?? x1").WithArguments("IIn<object>", "IIn<object?>", "x", "void C.FIn(IIn<object?>? x)").WithLocation(23, 14), // (27,9): warning CS8602: Dereference of a possibly null reference. // FOut((x2 ?? y2)/*T:IOut<object?>?*/).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "FOut((x2 ?? y2)/*T:IOut<object?>?*/)").WithLocation(27, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // FOut((y2 ?? x2)/*T:IOut<object?>?*/).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "FOut((y2 ?? x2)/*T:IOut<object?>?*/)").WithLocation(28, 9), // (34,14): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'x' in 'void C.FIn(IIn<object?>? x)'. // FIn((FIn(x3) ?? FIn(y3))/*T:IIn<object!>?*/); // B Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "FIn(x3) ?? FIn(y3)").WithArguments("IIn<object>", "IIn<object?>", "x", "void C.FIn(IIn<object?>? x)").WithLocation(34, 14), // (35,14): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'x' in 'void C.FIn(IIn<object?>? x)'. // FIn((FIn(y3) ?? FIn(x3))/*T:IIn<object!>?*/); // C Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "FIn(y3) ?? FIn(x3)").WithArguments("IIn<object>", "IIn<object?>", "x", "void C.FIn(IIn<object?>? x)").WithLocation(35, 14), // (37,14): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'x' in 'void C.FIn(IIn<object?>? x)'. // FIn((FIn(x3) ?? FIn(y3))/*T:IIn<object!>?*/); // D Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "FIn(x3) ?? FIn(y3)").WithArguments("IIn<object>", "IIn<object?>", "x", "void C.FIn(IIn<object?>? x)").WithLocation(37, 14), // (41,9): warning CS8602: Dereference of a possibly null reference. // FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object?>?*/).ToString(); // A Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object?>?*/)").WithLocation(41, 9), // (43,9): warning CS8602: Dereference of a possibly null reference. // FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object?>?*/).ToString(); // B Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "FOut((FOut(x4) ?? FOut(y4))/*T:IOut<object?>?*/)").WithLocation(43, 9), // (44,9): warning CS8602: Dereference of a possibly null reference. // FOut((FOut(y4) ?? FOut(x4))/*T:IOut<object?>?*/).ToString(); // C Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "FOut((FOut(y4) ?? FOut(x4))/*T:IOut<object?>?*/)").WithLocation(44, 9)); } [Fact] public void IdentityConversion_NullCoalescingOperator_03() { var source = @"class C { static void F((object?, object?)? x, (object, object) y) { (x ?? y).Item1.ToString(); } static void G((object, object)? x, (object?, object?) y) { (x ?? y).Item1.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // (x ?? y).Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x ?? y).Item1").WithLocation(5, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // (x ?? y).Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x ?? y).Item1").WithLocation(9, 9)); } [Fact] public void IdentityConversion_NullCoalescingOperator_04() { var source = @"#pragma warning disable 0649 struct A<T> { public static implicit operator B<T>(A<T> a) => default; } struct B<T> { internal T F; } class C { static void F1(A<object>? x1, B<object?> y1) { (x1 ?? y1)/*T:B<object?>*/.F.ToString(); } static void F2(A<object?>? x2, B<object> y2) { (x2 ?? y2)/*T:B<object!>*/.F.ToString(); } static void F3(A<object> x3, B<object?>? y3) { (y3 ?? x3)/*T:B<object?>*/.F.ToString(); } static void F4(A<object?> x4, B<object>? y4) { (y4 ?? x4)/*T:B<object!>*/.F.ToString(); } static void F5(A<object>? x5, B<object?>? y5) { (x5 ?? y5)/*T:B<object?>?*/.Value.F.ToString(); (y5 ?? x5)/*T:B<object?>?*/.Value.F.ToString(); } static void F6(A<object?>? x6, B<object>? y6) { (x6 ?? y6)/*T:B<object!>?*/.Value.F.ToString(); (y6 ?? x6)/*T:B<object!>?*/.Value.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (14,10): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'B<object?>'. // (x1 ?? y1)/*T:B<object?>*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("A<object>", "B<object?>").WithLocation(14, 10), // (14,9): warning CS8602: Dereference of a possibly null reference. // (x1 ?? y1)/*T:B<object?>*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x1 ?? y1)/*T:B<object?>*/.F").WithLocation(14, 9), // (18,10): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'B<object>'. // (x2 ?? y2)/*T:B<object!>*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("A<object?>", "B<object>").WithLocation(18, 10), // (22,16): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'B<object?>'. // (y3 ?? x3)/*T:B<object?>*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("B<object>", "B<object?>").WithLocation(22, 16), // (22,9): warning CS8602: Dereference of a possibly null reference. // (y3 ?? x3)/*T:B<object?>*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(y3 ?? x3)/*T:B<object?>*/.F").WithLocation(22, 9), // (26,16): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // (y4 ?? x4)/*T:B<object!>*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x4").WithArguments("B<object?>", "B<object>").WithLocation(26, 16), // (30,10): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'B<object?>?'. // (x5 ?? y5)/*T:B<object?>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x5").WithArguments("A<object>", "B<object?>?").WithLocation(30, 10), // (30,10): warning CS8629: Nullable value type may be null. // (x5 ?? y5)/*T:B<object?>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x5 ?? y5").WithLocation(30, 10), // (30,9): warning CS8602: Dereference of a possibly null reference. // (x5 ?? y5)/*T:B<object?>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x5 ?? y5)/*T:B<object?>?*/.Value.F").WithLocation(30, 9), // (31,16): warning CS8619: Nullability of reference types in value of type 'B<object>?' doesn't match target type 'B<object?>?'. // (y5 ?? x5)/*T:B<object?>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x5").WithArguments("B<object>?", "B<object?>?").WithLocation(31, 16), // (31,10): warning CS8629: Nullable value type may be null. // (y5 ?? x5)/*T:B<object?>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y5 ?? x5").WithLocation(31, 10), // (31,9): warning CS8602: Dereference of a possibly null reference. // (y5 ?? x5)/*T:B<object?>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(y5 ?? x5)/*T:B<object?>?*/.Value.F").WithLocation(31, 9), // (35,10): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'B<object>?'. // (x6 ?? y6)/*T:B<object!>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x6").WithArguments("A<object?>", "B<object>?").WithLocation(35, 10), // (35,10): warning CS8629: Nullable value type may be null. // (x6 ?? y6)/*T:B<object!>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x6 ?? y6").WithLocation(35, 10), // (36,16): warning CS8619: Nullability of reference types in value of type 'B<object?>?' doesn't match target type 'B<object>?'. // (y6 ?? x6)/*T:B<object!>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x6").WithArguments("B<object?>?", "B<object>?").WithLocation(36, 16), // (36,10): warning CS8629: Nullable value type may be null. // (y6 ?? x6)/*T:B<object!>?*/.Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y6 ?? x6").WithLocation(36, 10) ); } [Fact] [WorkItem(29871, "https://github.com/dotnet/roslyn/issues/29871")] public void IdentityConversion_NullCoalescingOperator_05() { var source = @"#pragma warning disable 0649 struct A<T> { public static implicit operator B<T>(A<T> a) => new B<T>(); } class B<T> { internal T F; } class C { static void F1(A<object>? x1, B<object?> y1) { (x1 ?? y1)/*T:B<object?>!*/.F.ToString(); } static void F2(A<object?>? x2, B<object> y2) { (x2 ?? y2)/*T:B<object!>!*/.F.ToString(); } static void F3(A<object> x3, B<object?>? y3) { (y3 ?? x3)/*T:B<object?>!*/.F.ToString(); } static void F4(A<object?> x4, B<object>? y4) { (y4 ?? x4)/*T:B<object!>!*/.F.ToString(); } static void F5(A<object>? x5, B<object?>? y5) { (x5 ?? y5)/*T:B<object?>?*/.F.ToString(); (y5 ?? x5)/*T:B<object?>?*/.F.ToString(); } static void F6(A<object?>? x6, B<object>? y6) { (x6 ?? y6)/*T:B<object!>?*/.F.ToString(); (y6 ?? x6)/*T:B<object!>?*/.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (8,16): warning CS8618: Non-nullable field 'F' is uninitialized. Consider declaring the field as nullable. // internal T F; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "F").WithArguments("field", "F").WithLocation(8, 16), // (14,10): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'B<object?>'. // (x1 ?? y1)/*T:B<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("A<object>", "B<object?>").WithLocation(14, 10), // (14,9): warning CS8602: Dereference of a possibly null reference. // (x1 ?? y1)/*T:B<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x1 ?? y1)/*T:B<object?>!*/.F").WithLocation(14, 9), // (18,10): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'B<object>'. // (x2 ?? y2)/*T:B<object!>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("A<object?>", "B<object>").WithLocation(18, 10), // (22,16): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'B<object?>'. // (y3 ?? x3)/*T:B<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("B<object>", "B<object?>").WithLocation(22, 16), // (22,9): warning CS8602: Dereference of a possibly null reference. // (y3 ?? x3)/*T:B<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(y3 ?? x3)/*T:B<object?>!*/.F").WithLocation(22, 9), // (26,16): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // (y4 ?? x4)/*T:B<object!>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x4").WithArguments("B<object?>", "B<object>").WithLocation(26, 16), // (30,10): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'B<object?>'. // (x5 ?? y5)/*T:B<object?>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x5").WithArguments("A<object>", "B<object?>").WithLocation(30, 10), // (30,10): warning CS8602: Dereference of a possibly null reference. // (x5 ?? y5)/*T:B<object?>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x5 ?? y5").WithLocation(30, 10), // (30,9): warning CS8602: Dereference of a possibly null reference. // (x5 ?? y5)/*T:B<object?>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(x5 ?? y5)/*T:B<object?>?*/.F").WithLocation(30, 9), // (31,16): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'B<object?>'. // (y5 ?? x5)/*T:B<object?>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x5").WithArguments("B<object>", "B<object?>").WithLocation(31, 16), // (31,10): warning CS8602: Dereference of a possibly null reference. // (y5 ?? x5)/*T:B<object?>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y5 ?? x5").WithLocation(31, 10), // (31,9): warning CS8602: Dereference of a possibly null reference. // (y5 ?? x5)/*T:B<object?>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(y5 ?? x5)/*T:B<object?>?*/.F").WithLocation(31, 9), // (35,10): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'B<object>'. // (x6 ?? y6)/*T:B<object!>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x6").WithArguments("A<object?>", "B<object>").WithLocation(35, 10), // (35,10): warning CS8602: Dereference of a possibly null reference. // (x6 ?? y6)/*T:B<object!>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x6 ?? y6").WithLocation(35, 10), // (36,16): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // (y6 ?? x6)/*T:B<object!>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x6").WithArguments("B<object?>", "B<object>").WithLocation(36, 16), // (36,10): warning CS8602: Dereference of a possibly null reference. // (y6 ?? x6)/*T:B<object!>?*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y6 ?? x6").WithLocation(36, 10)); } [Fact] public void IdentityConversion_NullCoalescingOperator_06() { var source = @"class C { static void F1(object? x, dynamic? y, dynamic z) { (x ?? y).ToString(); // 1 (x ?? z).ToString(); // ok (y ?? x).ToString(); // 2 (y ?? z).ToString(); // ok (z ?? x).ToString(); // 3 (z ?? y).ToString(); // 4 } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,10): warning CS8602: Dereference of a possibly null reference. // (x ?? y).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x ?? y").WithLocation(5, 10), // (7,10): warning CS8602: Dereference of a possibly null reference. // (y ?? x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y ?? x").WithLocation(7, 10), // (9,10): warning CS8602: Dereference of a possibly null reference. // (z ?? x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z ?? x").WithLocation(9, 10), // (10,10): warning CS8602: Dereference of a possibly null reference. // (z ?? y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z ?? y").WithLocation(10, 10)); } [Fact] public void ImplicitConversion_NullCoalescingOperator_01() { var source0 = @"public class UnknownNull { public object Object; public string String; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source1 = @"public class MaybeNull { public object? Object; public string? String; } public class NotNull { public object Object = new object(); public string String = string.Empty; }"; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var source = @"class C { static void F1(bool b, UnknownNull x1, UnknownNull y1) { if (b) { (x1.Object ?? y1.String)/*T:object!*/.ToString(); } else { (y1.String ?? x1.Object)/*T:object!*/.ToString(); } } static void F2(bool b, UnknownNull x2, MaybeNull y2) { if (b) { (x2.Object ?? y2.String)/*T:object?*/.ToString(); // 1 } else { (y2.String ?? x2.Object)/*T:object!*/.ToString(); } } static void F3(bool b, MaybeNull x3, UnknownNull y3) { if (b) { (x3.Object ?? y3.String)/*T:object!*/.ToString(); } else { (y3.String ?? x3.Object)/*T:object?*/.ToString(); // 2 } } static void F4(bool b, MaybeNull x4, MaybeNull y4) { if (b) { (x4.Object ?? y4.String)/*T:object?*/.ToString(); // 3 } else { (y4.String ?? x4.Object)/*T:object?*/.ToString(); // 4 } } static void F5(bool b, UnknownNull x5, NotNull y5) { if (b) { (x5.Object ?? y5.String)/*T:object!*/.ToString(); } else { (y5.String ?? x5.Object)/*T:object!*/.ToString(); } } static void F6(bool b, NotNull x6, UnknownNull y6) { if (b) { (x6.Object ?? y6.String)/*T:object!*/.ToString(); } else { (y6.String ?? x6.Object)/*T:object!*/.ToString(); } } static void F7(bool b, MaybeNull x7, NotNull y7) { if (b) { (x7.Object ?? y7.String)/*T:object!*/.ToString(); } else { (y7.String ?? x7.Object)/*T:object?*/.ToString(); // 5 } } static void F8(bool b, NotNull x8, MaybeNull y8) { if (b) { (x8.Object ?? y8.String)/*T:object?*/.ToString(); // 6 } else { (y8.String ?? x8.Object)/*T:object!*/.ToString(); } } static void F9(bool b, NotNull x9, NotNull y9) { if (b) { (x9.Object ?? y9.String)/*T:object!*/.ToString(); } else { (y9.String ?? x9.Object)/*T:object!*/.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0, ref1 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (14,14): warning CS8602: Dereference of a possibly null reference. // (x2.Object ?? y2.String)/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2.Object ?? y2.String").WithLocation(14, 14), // (24,14): warning CS8602: Dereference of a possibly null reference. // (y3.String ?? x3.Object)/*T:object?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y3.String ?? x3.Object").WithLocation(24, 14), // (30,14): warning CS8602: Dereference of a possibly null reference. // (x4.Object ?? y4.String)/*T:object?*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4.Object ?? y4.String").WithLocation(30, 14), // (32,14): warning CS8602: Dereference of a possibly null reference. // (y4.String ?? x4.Object)/*T:object?*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y4.String ?? x4.Object").WithLocation(32, 14), // (56,14): warning CS8602: Dereference of a possibly null reference. // (y7.String ?? x7.Object)/*T:object?*/.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y7.String ?? x7.Object").WithLocation(56, 14), // (62,14): warning CS8602: Dereference of a possibly null reference. // (x8.Object ?? y8.String)/*T:object?*/.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x8.Object ?? y8.String").WithLocation(62, 14)); } [Fact] public void ImplicitConversion_NullCoalescingOperator_02() { var source = @"#pragma warning disable 0649 class A<T> { internal T F; } class B<T> : A<T> { } class C { static void F(A<object>? x, B<object?> y) { (x ?? y).F.ToString(); // 1 (y ?? x).F.ToString(); // 2 } static void G(A<object?> z, B<object>? w) { (z ?? w).F.ToString(); // 3 (w ?? z).F.ToString(); // 4 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,16): warning CS8618: Non-nullable field 'F' is uninitialized. Consider declaring the field as nullable. // internal T F; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "F").WithArguments("field", "F").WithLocation(4, 16), // (11,15): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'A<object>'. // (x ?? y).F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("B<object?>", "A<object>").WithLocation(11, 15), // (12,10): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'A<object>'. // (y ?? x).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("B<object?>", "A<object>").WithLocation(12, 10), // (12,10): warning CS8602: Dereference of a possibly null reference. // (y ?? x).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y ?? x").WithLocation(12, 10), // (16,15): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // (z ?? w).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("B<object>", "A<object?>").WithLocation(16, 15), // (16,10): warning CS8602: Dereference of a possibly null reference. // (z ?? w).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z ?? w").WithLocation(16, 10), // (16,9): warning CS8602: Dereference of a possibly null reference. // (z ?? w).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(z ?? w).F").WithLocation(16, 9), // (17,10): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // (w ?? z).F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("B<object>", "A<object?>").WithLocation(17, 10), // (17,10): warning CS8602: Dereference of a possibly null reference. // (w ?? z).F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w ?? z").WithLocation(17, 10), // (17,9): warning CS8602: Dereference of a possibly null reference. // (w ?? z).F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(w ?? z).F").WithLocation(17, 9)); } [Fact] public void ImplicitConversion_NullCoalescingOperator_03() { var source = @"interface IIn<in T> { void F(T x, T y); } class C { static void F(bool b, IIn<object>? x, IIn<string?> y) { if (b) { (x ?? y)/*T:IIn<string?>!*/.F(string.Empty, null); // 1 } else { (y ?? x)/*T:IIn<string?>?*/.F(string.Empty, null); // 2 } } static void G(bool b, IIn<object?> z, IIn<string>? w) { if (b) { (z ?? w)/*T:IIn<string!>?*/.F(string.Empty, null); // 3 } else { (w ?? z)/*T:IIn<string!>!*/.F(string.Empty, null); // 4 } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (10,14): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<string?>'. // (x ?? y)/*T:IIn<string?>!*/.F(string.Empty, null); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object>", "IIn<string?>").WithLocation(10, 14), // (12,14): warning CS8602: Dereference of a possibly null reference. // (y ?? x)/*T:IIn<string?>?*/.F(string.Empty, null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y ?? x").WithLocation(12, 14), // (12,19): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<string?>'. // (y ?? x)/*T:IIn<string?>?*/.F(string.Empty, null); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object>", "IIn<string?>").WithLocation(12, 19), // (18,14): warning CS8602: Dereference of a possibly null reference. // (z ?? w)/*T:IIn<string!>?*/.F(string.Empty, null); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z ?? w").WithLocation(18, 14), // (18,57): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // (z ?? w)/*T:IIn<string!>?*/.F(string.Empty, null); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(18, 57), // (20,57): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // (w ?? z)/*T:IIn<string!>!*/.F(string.Empty, null); // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 57)); } [Fact] public void ImplicitConversion_NullCoalescingOperator_04() { var source = @"interface IOut<out T> { T P { get; } } class C { static void F(bool b, IOut<object>? x, IOut<string?> y) { if (b) { (x ?? y)/*T:IOut<object!>!*/.P.ToString(); // 1 } else { (y ?? x)/*T:IOut<object!>?*/.P.ToString(); // 2 } } static void G(bool b, IOut<object?> z, IOut<string>? w) { if (b) { (z ?? w)/*T:IOut<object?>?*/.P.ToString(); // 3 } else { (w ?? z)/*T:IOut<object?>!*/.P.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (10,19): warning CS8619: Nullability of reference types in value of type 'IOut<string?>' doesn't match target type 'IOut<object>'. // (x ?? y)/*T:IOut<object!>!*/.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("IOut<string?>", "IOut<object>").WithLocation(10, 19), // (12,14): warning CS8619: Nullability of reference types in value of type 'IOut<string?>' doesn't match target type 'IOut<object>'. // (y ?? x)/*T:IOut<object!>?*/.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("IOut<string?>", "IOut<object>").WithLocation(12, 14), // (12,14): warning CS8602: Dereference of a possibly null reference. // (y ?? x)/*T:IOut<object!>?*/.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y ?? x").WithLocation(12, 14), // (18,13): warning CS8602: Dereference of a possibly null reference. // (z ?? w)/*T:IOut<object?>?*/.P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(z ?? w)/*T:IOut<object?>?*/.P").WithLocation(18, 13), // (18,14): warning CS8602: Dereference of a possibly null reference. // (z ?? w)/*T:IOut<object?>?*/.P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z ?? w").WithLocation(18, 14), // (20,13): warning CS8602: Dereference of a possibly null reference. // (w ?? z)/*T:IOut<object?>!*/.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(w ?? z)/*T:IOut<object?>!*/.P").WithLocation(20, 13)); } [Fact] public void Loop_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1? x1, CL1 y1, CL1? z1) { x1 = y1; x1.M1(); // 1 for (int i = 0; i < 2; i++) { x1.M1(); // 2 x1 = z1; } } CL1 Test2(CL1? x2, CL1 y2, CL1? z2) { x2 = y2; x2.M1(); // 1 for (int i = 0; i < 2; i++) { x2 = z2; x2.M1(); // 2 y2 = z2; y2.M2(y2); if (i == 1) { return x2; } } return y2; } } class CL1 { public void M1() { } public void M2(CL1 x) { } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,13): warning CS8602: Dereference of a possibly null reference. // x1.M1(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(15, 13), // (28,13): warning CS8602: Dereference of a possibly null reference. // x2.M1(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(28, 13), // (29,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // y2 = z2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z2").WithLocation(29, 18), // (30,13): warning CS8602: Dereference of a possibly null reference. // y2.M2(y2); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(30, 13)); } [Fact] public void Loop_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1? x1, CL1 y1, CL1? z1) { x1 = y1; if (x1 == null) {} // 1 for (int i = 0; i < 2; i++) { if (x1 == null) {} // 2 x1 = z1; } } void Test2(CL1? x2, CL1 y2, CL1? z2) { x2 = y2; if (x2 == null) {} // 1 for (int i = 0; i < 2; i++) { x2 = z2; if (x2 == null) {} // 2 } } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Loop_03() { var source0 = @"public class A { public object F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var source1 = @"#pragma warning disable 8618 class B { object G; static object F1(B b1, object? o) { for (int i = 0; i < 2; i++) { b1.G = o; } return b1.G; } static object F2(B b2, A a) { for (int i = 0; i < 2; i++) { b2.G = a.F; } return b2.G; } static object F3(B b3, object? o, A a) { for (int i = 0; i < 2; i++) { if (i % 2 == 0) b3.G = o; else b3.G = a.F; } return b3.G; } }"; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { comp0.EmitToImageReference() }); comp1.VerifyDiagnostics( // (9,20): warning CS8601: Possible null reference assignment. // b1.G = o; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "o").WithLocation(9, 20), // (11,16): warning CS8603: Possible null reference return. // return b1.G; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b1.G").WithLocation(11, 16), // (26,24): warning CS8601: Possible null reference assignment. // b3.G = o; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "o").WithLocation(26, 24), // (30,16): warning CS8603: Possible null reference return. // return b3.G; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b3.G").WithLocation(30, 16)); } [Fact] public void Loop_04() { var source0 = @"public class A { public object F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var source1 = @"#pragma warning disable 8618 class C { static object F1(A a1, object? o) { for (int i = 0; i < 2; i++) { a1.F = o; } return a1.F; } static object F2(A a2, object o) { for (int i = 0; i < 2; i++) { a2.F = o; } return a2.F; } static object F3(A a3, object? o, A a) { for (int i = 0; i < 2; i++) { if (i % 2 == 0) a3.F = o; else a3.F = a.F; } return a3.F; } }"; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { comp0.EmitToImageReference() }); comp1.VerifyDiagnostics( // (10,16): warning CS8603: Possible null reference return. // return a1.F; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "a1.F").WithLocation(10, 16), // (29,16): warning CS8603: Possible null reference return. // return a3.F; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "a3.F").WithLocation(29, 16)); } [Fact, WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void Var_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? Test1() { var x1 = (CL1)null; return x1; } CL1? Test2(CL1 x2) { var y2 = x2; y2 = null; return y2; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // var x1 = (CL1)null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(CL1)null").WithLocation(10, 18)); } [Fact, WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void Var_NonNull() { var source = @"class C { static void F(string str) { var s = str; s.ToString(); s = null; s.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 9)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclarationSyntax>().First(); Assert.Equal("System.String?", model.GetTypeInfoAndVerifyIOperation(declaration.Type).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, model.GetTypeInfo(declaration.Type).Nullability.Annotation); Assert.Equal("System.String?", model.GetTypeInfo(declaration.Type).ConvertedType.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, model.GetTypeInfo(declaration.Type).ConvertedNullability.Annotation); } [Fact] public void Var_NonNull_CSharp7() { var source = @"class C { static void Main() { var s = string.Empty; s.ToString(); s = null; s.ToString(); } }"; var comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Oblivious, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_01() { var source = @"class C { static void F(string? s) { var t = s; t.ToString(); t = null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(6, 9)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_02() { var source = @"class C { static void F(string? s) { t = null/*T:<null>?*/; var t = s; t.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS0841: Cannot use local variable 't' before it is declared // t = null; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "t").WithArguments("t").WithLocation(5, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(7, 9)); comp.VerifyTypes(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_03() { var source = @"class C { static void F(string? s) { if (s == null) { return; } var t = s; t.ToString(); t = null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_04() { var source = @"class C { static void F(int n) { string? s = string.Empty; while (n-- > 0) { var t = s; t.ToString(); t = null; s = null; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(9, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_05() { var source = @"class C { static void F(int n, string? s) { while (n-- > 0) { var t = s; t.ToString(); t = null; s = string.Empty; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(8, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_06() { var source = @"class C { static void F(int n) { string? s = string.Empty; while (n-- > 0) { var t = s; t.ToString(); t = null; if (n % 2 == 0) s = null; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(9, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Skip(1).First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_07() { var source = @"class C { static void F(int n) { string? s = string.Empty; while (n-- > 0) { var t = s; t.ToString(); t = null; if (n % 2 == 0) s = string.Empty; else s = null; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(9, 13)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Skip(1).First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_FlowAnalysis_08() { var source = @"class C { static void F(string? s) { var t = s!; t/*T:string!*/.ToString(); t = null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_Cycle() { var source = @"class C { static void Main() { var s = s; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,17): error CS0841: Cannot use local variable 's' before it is declared // var s = s; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "s").WithArguments("s").WithLocation(5, 17)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); var type = symbol.TypeWithAnnotations; Assert.True(type.Type.IsErrorType()); Assert.Equal("var?", type.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, type.NullableAnnotation); } [Fact] public void Var_ConditionalOperator() { var source = @"class C { static void F(bool b, string s) { var s0 = b ? s : s; var s1 = b ? s : null; var s2 = b ? null : s; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[2]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString()); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Var_Array_01() { var source = @"class C { static void F(string str) { var s = new[] { str }; s[0].ToString(); var t = new[] { str, null }; t[0].ToString(); var u = new[] { 1, null }; u[0].ToString(); var v = new[] { null, (int?)2 }; v[0].ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,28): error CS0037: Cannot convert null to 'int' because it is a non-nullable value type // var u = new[] { 1, null }; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "null").WithArguments("int").WithLocation(9, 28), // (8,9): warning CS8602: Dereference of a possibly null reference. // t[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t[0]").WithLocation(8, 9)); } [Fact] public void Var_Array_02() { var source = @"delegate void D(); class C { static void Main() { var a = new[] { new D(Main), () => { } }; a[0].ToString(); var b = new[] { new D(Main), null }; b[0].ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // b[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0]").WithLocation(9, 9)); } [Fact] public void Array_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1? [] x1) { CL1? y1 = x1[0]; CL1 z1 = x1[0]; } void Test2(CL1 [] x2, CL1 y2, CL1? z2) { x2[0] = y2; x2[1] = z2; } void Test3(CL1 [] x3) { CL1? y3 = x3[0]; CL1 z3 = x3[0]; } void Test4(CL1? [] x4, CL1 y4, CL1? z4) { x4[0] = y4; x4[1] = z4; } void Test5(CL1 y5, CL1? z5) { var x5 = new CL1 [] { y5, z5 }; } void Test6(CL1 y6, CL1? z6) { var x6 = new CL1 [,] { {y6}, {z6} }; } void Test7(CL1 y7, CL1? z7) { var u7 = new CL1? [] { y7, z7 }; var v7 = new CL1? [,] { {y7}, {z7} }; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z1 = x1[0]; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1[0]").WithLocation(11, 18), // (17,17): warning CS8601: Possible null reference assignment. // x2[1] = z2; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "z2").WithLocation(17, 17), // (34,35): warning CS8601: Possible null reference assignment. // var x5 = new CL1 [] { y5, z5 }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "z5").WithLocation(34, 35), // (39,39): warning CS8601: Possible null reference assignment. // var x6 = new CL1 [,] { {y6}, {z6} }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "z6").WithLocation(39, 39) ); } [Fact] public void Array_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 y1, CL1? z1) { CL1? [] u1 = new [] { y1, z1 }; CL1? [,] v1 = new [,] { {y1}, {z1} }; } void Test2(CL1 y2, CL1? z2) { var u2 = new [] { y2, z2 }; var v2 = new [,] { {y2}, {z2} }; u2[0] = z2; v2[0,0] = z2; } void Test3(CL1 y3, CL1? z3) { CL1? [] u3; CL1? [,] v3; u3 = new [] { y3, z3 }; v3 = new [,] { {y3}, {z3} }; } void Test4(CL1 y4, CL1? z4) { var u4 = new [] { y4 }; var v4 = new [,] {{y4}}; u4[0] = z4; v4[0,0] = z4; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (37,17): warning CS8601: Possible null reference assignment. // u4[0] = z4; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "z4").WithLocation(37, 17), // (38,19): warning CS8601: Possible null reference assignment. // v4[0,0] = z4; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "z4").WithLocation(38, 19) ); } [Fact] public void Array_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1() { int[]? u1 = new [] { 1, 2 }; u1 = null; var z1 = u1[0]; } void Test2() { int[]? u1 = new [] { 1, 2 }; u1 = null; var z1 = u1?[u1[0]]; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,18): warning CS8602: Dereference of a possibly null reference. // var z1 = u1[0]; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u1").WithLocation(12, 18) ); } [Fact] public void Array_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL1 y1, CL1? z1) { CL1 [] u1; CL1 [,] v1; u1 = new [] { y1, z1 }; v1 = new [,] { {y1}, {z1} }; } void Test3(CL1 y2, CL1? z2) { CL1 [] u2; CL1 [,] v2; var a2 = new [] { y2, z2 }; var b2 = new [,] { {y2}, {z2} }; u2 = a2; v2 = b2; } void Test8(CL1 y8, CL1? z8) { CL1 [] x8 = new [] { y8, z8 }; } void Test9(CL1 y9, CL1? z9) { CL1 [,] x9 = new [,] { {y9}, {z9} }; } void Test11(CL1 y11, CL1? z11) { CL1? [] u11; CL1? [,] v11; u11 = new [] { y11, z11 }; v11 = new [,] { {y11}, {z11} }; } void Test13(CL1 y12, CL1? z12) { CL1? [] u12; CL1? [,] v12; var a12 = new [] { y12, z12 }; var b12 = new [,] { {y12}, {z12} }; u12 = a12; v12 = b12; } void Test18(CL1 y18, CL1? z18) { CL1? [] x18 = new [] { y18, z18 }; } void Test19(CL1 y19, CL1? z19) { CL1? [,] x19 = new [,] { {y19}, {z19} }; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,14): warning CS8619: Nullability of reference types in value of type 'CL1?[]' doesn't match target type 'CL1[]'. // u1 = new [] { y1, z1 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new [] { y1, z1 }").WithArguments("CL1?[]", "CL1[]").WithLocation(13, 14), // (14,14): warning CS8619: Nullability of reference types in value of type 'CL1?[*,*]' doesn't match target type 'CL1[*,*]'. // v1 = new [,] { {y1}, {z1} }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new [,] { {y1}, {z1} }").WithArguments("CL1?[*,*]", "CL1[*,*]").WithLocation(14, 14), // (25,14): warning CS8619: Nullability of reference types in value of type 'CL1?[]' doesn't match target type 'CL1[]'. // u2 = a2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("CL1?[]", "CL1[]").WithLocation(25, 14), // (26,14): warning CS8619: Nullability of reference types in value of type 'CL1?[*,*]' doesn't match target type 'CL1[*,*]'. // v2 = b2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b2").WithArguments("CL1?[*,*]", "CL1[*,*]").WithLocation(26, 14), // (31,21): warning CS8619: Nullability of reference types in value of type 'CL1?[]' doesn't match target type 'CL1[]'. // CL1 [] x8 = new [] { y8, z8 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new [] { y8, z8 }").WithArguments("CL1?[]", "CL1[]").WithLocation(31, 21), // (36,22): warning CS8619: Nullability of reference types in value of type 'CL1?[*,*]' doesn't match target type 'CL1[*,*]'. // CL1 [,] x9 = new [,] { {y9}, {z9} }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new [,] { {y9}, {z9} }").WithArguments("CL1?[*,*]", "CL1[*,*]").WithLocation(36, 22) ); } [Fact] public void Array_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1() { int[]? u1 = new [] { 1, 2 }; var z1 = u1.Length; } void Test2() { int[]? u2 = new [] { 1, 2 }; u2 = null; var z2 = u2.Length; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (18,18): warning CS8602: Dereference of a possibly null reference. // var z2 = u2.Length; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2").WithLocation(18, 18) ); } [Fact] public void Array_06() { const string source = @" class C { static void Main() { } object Test1() { object []? u1 = null; return u1; } object Test2() { object [][]? u2 = null; return u2; } object Test3() { object []?[]? u3 = null; return u3; } } "; var expected = new[] { // (10,18): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // object []? u1 = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(10, 18), // (15,20): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // object [][]? u2 = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(15, 20), // (20,18): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // object []?[]? u3 = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(20, 18), // (20,21): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // object []?[]? u3 = null; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(20, 21) }; var c = CreateCompilation(source, parseOptions: TestOptions.Regular7); c.VerifyDiagnostics(expected); } [Fact] public void Array_07() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1() { object? [] u1 = new [] { null, new object() }; u1 = null; } void Test2() { object [] u2 = new [] { null, new object() }; } void Test3() { var u3 = new object [] { null, new object() }; } object? Test4() { object []? u4 = null; return u4; } object Test5() { object? [] u5 = null; return u5; } void Test6() { object [][,]? u6 = null; u6[0] = null; u6[0][0,0] = null; u6[0][0,0].ToString(); } void Test7() { object [][,] u7 = null; u7[0] = null; u7[0][0,0] = null; } void Test8() { object []?[,] u8 = null; u8[0,0] = null; u8[0,0].ToString(); u8[0,0][0] = null; u8[0,0][0].ToString(); } void Test9() { object []?[,]? u9 = null; u9[0,0] = null; u9[0,0][0] = null; u9[0,0][0].ToString(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // u1 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 14), // (16,24): warning CS8619: Nullability of reference types in value of type 'object?[]' doesn't match target type 'object[]'. // object [] u2 = new [] { null, new object() }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new [] { null, new object() }").WithArguments("object?[]", "object[]").WithLocation(16, 24), // (21,34): warning CS8625: Cannot convert null literal to non-nullable reference type. // var u3 = new object [] { null, new object() }; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 34), // (32,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // object? [] u5 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(32, 25), // (33,16): warning CS8603: Possible null reference return. // return u5; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u5").WithLocation(33, 16), // (39,9): warning CS8602: Dereference of a possibly null reference. // u6[0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u6").WithLocation(39, 9), // (39,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // u6[0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(39, 17), // (40,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u6[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(40, 22), // (46,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // object [][,] u7 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(46, 27), // (47,9): warning CS8602: Dereference of a possibly null reference. // u7[0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u7").WithLocation(47, 9), // (47,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // u7[0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(47, 17), // (48,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u7[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(48, 22), // (53,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // object []?[,] u8 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(53, 28), // (54,9): warning CS8602: Dereference of a possibly null reference. // u8[0,0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u8").WithLocation(54, 9), // (55,9): warning CS8602: Dereference of a possibly null reference. // u8[0,0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u8[0,0]").WithLocation(55, 9), // (56,9): warning CS8602: Dereference of a possibly null reference. // u8[0,0][0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u8[0,0]").WithLocation(56, 9), // (56,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u8[0,0][0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(56, 22), // (57,9): warning CS8602: Dereference of a possibly null reference. // u8[0,0][0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u8[0,0]").WithLocation(57, 9), // (63,9): warning CS8602: Dereference of a possibly null reference. // u9[0,0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u9").WithLocation(63, 9), // (64,9): warning CS8602: Dereference of a possibly null reference. // u9[0,0][0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u9[0,0]").WithLocation(64, 9), // (64,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u9[0,0][0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(64, 22), // (65,9): warning CS8602: Dereference of a possibly null reference. // u9[0,0][0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u9[0,0]").WithLocation(65, 9) ); } [Fact] public void Array_08() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test3() { var u3 = new object? [] { null }; } void Test6() { var u6 = new object [,]?[] {null, new object[,] {{null}}}; u6[0] = null; u6[0][0,0] = null; u6[0][0,0].ToString(); } void Test7() { var u7 = new object [][,] {null, new object[,] {{null}}}; u7[0] = null; u7[0][0,0] = null; } void Test8() { object [][,]? u8 = new object [][,] {null, new object[,] {{null}}}; u8[0] = null; u8[0][0,0] = null; u8[0][0,0].ToString(); } void Test9() { object [,]?[]? u9 = new object [,]?[] {null, new object[,] {{null}}}; u9[0] = null; u9[0][0,0] = null; u9[0][0,0].ToString(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (16,53): warning CS8625: Cannot convert null literal to non-nullable reference type. // new object[,] {{null}}}; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 53), // (18,9): warning CS8602: Dereference of a possibly null reference. // u6[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u6[0]").WithLocation(18, 9), // (18,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u6[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(18, 22), // (19,9): warning CS8602: Dereference of a possibly null reference. // u6[0][0,0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u6[0]").WithLocation(19, 9), // (24,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // var u7 = new object [][,] {null, Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(24, 36), // (25,52): warning CS8625: Cannot convert null literal to non-nullable reference type. // new object[,] {{null}}}; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(25, 52), // (26,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // u7[0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(26, 17), // (27,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u7[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(27, 22), // (32,46): warning CS8625: Cannot convert null literal to non-nullable reference type. // object [][,]? u8 = new object [][,] {null, Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(32, 46), // (33,53): warning CS8625: Cannot convert null literal to non-nullable reference type. // new object[,] {{null}}}; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(33, 53), // (34,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // u8[0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(34, 17), // (35,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u8[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(35, 22), // (42,54): warning CS8625: Cannot convert null literal to non-nullable reference type. // new object[,] {{null}}}; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(42, 54), // (44,9): warning CS8602: Dereference of a possibly null reference. // u9[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u9[0]").WithLocation(44, 9), // (44,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // u9[0][0,0] = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(44, 22), // (45,9): warning CS8602: Dereference of a possibly null reference. // u9[0][0,0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u9[0]").WithLocation(45, 9) ); } [Fact] public void Array_09() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0<string?> x1, CL0<string> y1) { var u1 = new [] { x1, y1 }; var a1 = new [] { y1, x1 }; var v1 = new CL0<string?>[] { x1, y1 }; var w1 = new CL0<string>[] { x1, y1 }; } } class CL0<T> {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,27): warning CS8619: Nullability of reference types in value of type 'CL0<string?>' doesn't match target type 'CL0<string>'. // var u1 = new [] { x1, y1 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("CL0<string?>", "CL0<string>").WithLocation(10, 27), // (11,31): warning CS8619: Nullability of reference types in value of type 'CL0<string?>' doesn't match target type 'CL0<string>'. // var a1 = new [] { y1, x1 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("CL0<string?>", "CL0<string>").WithLocation(11, 31), // (12,43): warning CS8619: Nullability of reference types in value of type 'CL0<string>' doesn't match target type 'CL0<string?>'. // var v1 = new CL0<string?>[] { x1, y1 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("CL0<string>", "CL0<string?>").WithLocation(12, 43), // (13,38): warning CS8619: Nullability of reference types in value of type 'CL0<string?>' doesn't match target type 'CL0<string>'. // var w1 = new CL0<string>[] { x1, y1 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("CL0<string?>", "CL0<string>").WithLocation(13, 38) ); } [Fact] public void Array_10() { var source = @"class C { static void F1<T>() { T[] a1; a1 = new T[] { default }; // 1 a1 = new T[] { default(T) }; // 2 } static void F2<T>() where T : class { T[] a2; a2 = new T[] { null }; // 3 a2 = new T[] { default }; // 4 a2 = new T[] { default(T) }; // 5 } static void F3<T>() where T : struct { T[] a3; a3 = new T[] { default }; a3 = new T[] { default(T) }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,24): warning CS8601: Possible null reference assignment. // a1 = new T[] { default }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(6, 24), // (7,24): warning CS8601: Possible null reference assignment. // a1 = new T[] { default(T) }; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default(T)").WithLocation(7, 24), // (12,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // a2 = new T[] { null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 24), // (13,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // a2 = new T[] { default }; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(13, 24), // (14,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // a2 = new T[] { default(T) }; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default(T)").WithLocation(14, 24) ); } [Fact] public void ImplicitlyTypedArrayCreation_01() { var source = @"class C { static void F(object x, object? y) { var a = new[] { x, x }; a.ToString(); a[0].ToString(); var b = new[] { x, y }; b.ToString(); b[0].ToString(); var c = new[] { b }; c[0].ToString(); c[0][0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // b[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0]").WithLocation(10, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // c[0][0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[0][0]").WithLocation(13, 9)); } [Fact] [WorkItem(33346, "https://github.com/dotnet/roslyn/issues/33346")] [WorkItem(30376, "https://github.com/dotnet/roslyn/issues/30376")] public void ImplicitlyTypedArrayCreation_02() { var source = @"class C { static void F(object x, object? y) { var a = new[] { x }; a[0].ToString(); var b = new[] { y }; b[0].ToString(); // 1 } static void F(object[] a, object?[] b) { var c = new[] { a, b }; c[0][0].ToString(); // 2 var d = new[] { a, b! }; d[0][0].ToString(); // 3 var e = new[] { b!, a }; e[0][0].ToString(); // 4 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // b[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0]").WithLocation(8, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // c[0][0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[0][0]").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // d[0][0].ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d[0][0]").WithLocation(15, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // e[0][0].ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e[0][0]").WithLocation(17, 9) ); } [Fact, WorkItem(30376, "https://github.com/dotnet/roslyn/issues/30376")] public void ImplicitlyTypedArrayCreation_02_TopLevelNullability() { var source = @"class C { static void F(object? y) { var b = new[] { y! }; b[0].ToString(); } static void F(object[]? a, object?[]? b) { var c = new[] { a, b }; _ = c[0].Length; var d = new[] { a, b! }; _ = d[0].Length; var e = new[] { b!, a }; _ = e[0].Length; var f = new[] { b!, a! }; _ = f[0].Length; var g = new[] { a!, b! }; _ = g[0].Length; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = c[0].Length; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[0]").WithLocation(11, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = d[0].Length; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d[0]").WithLocation(13, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // _ = e[0].Length; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e[0]").WithLocation(15, 13)); } [Fact] public void ImplicitlyTypedArrayCreation_03() { var source = @"class C { static void F(object x, object? y) { (new[] { x, x })[1].ToString(); (new[] { y, x })[1].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, x })[1].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, x })[1]").WithLocation(6, 9)); } [Fact] public void ImplicitlyTypedArrayCreation_04() { var source = @"class C { static void F() { object? o = new object(); var a = new[] { o }; a[0].ToString(); var b = new[] { a }; b[0][0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ImplicitlyTypedArrayCreation_05() { var source = @"class C { static void F(int n) { object? o = new object(); while (n-- > 0) { var a = new[] { o }; a[0].ToString(); var b = new[] { a }; b[0][0].ToString(); o = null; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // a[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a[0]").WithLocation(9, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // b[0][0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0][0]").WithLocation(11, 13)); } [Fact] public void ImplicitlyTypedArrayCreation_06() { var source = @"class C { static void F(string s) { var a = new[] { new object(), (string)null }; a[0].ToString(); var b = new[] { (object)null, s }; b[0].ToString(); var c = new[] { s, (object)null }; c[0].ToString(); var d = new[] { (string)null, new object() }; d[0].ToString(); var e = new[] { new object(), (string)null! }; e[0].ToString(); var f = new[] { (object)null!, s }; f[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,39): warning CS8600: Converting null literal or possible null value to non-nullable type. // var a = new[] { new object(), (string)null }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(5, 39), // (6,9): warning CS8602: Dereference of a possibly null reference. // a[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a[0]").WithLocation(6, 9), // (7,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // var b = new[] { (object)null, s }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)null").WithLocation(7, 25), // (8,9): warning CS8602: Dereference of a possibly null reference. // b[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0]").WithLocation(8, 9), // (9,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // var c = new[] { s, (object)null }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)null").WithLocation(9, 28), // (10,9): warning CS8602: Dereference of a possibly null reference. // c[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[0]").WithLocation(10, 9), // (11,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // var d = new[] { (string)null, new object() }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(11, 25), // (12,9): warning CS8602: Dereference of a possibly null reference. // d[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d[0]").WithLocation(12, 9)); } [Fact] public void ImplicitlyTypedArrayCreation_NestedNullability_Derived() { var source0 = @"public class A { public static B<object> F; } public class B<T> { } public class C0 : B<object> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C1 : B<object?> { } class C2 : B<object> { } class Program { static void F(B<object?> x, B<object> y, C0 cz, C1 cx, C2 cy) { var z = A.F/*T:B<object>!*/; object o; o = (new[] { x, cx })[0]/*B<object?>*/; o = (new[] { x, cy })[0]/*B<object>*/; // 1 o = (new[] { x, cz })[0]/*B<object?>*/; o = (new[] { y, cx })[0]/*B<object>*/; // 2 o = (new[] { cy, y })[0]/*B<object!>*/; o = (new[] { cz, y })[0]/*B<object!>*/; o = (new[] { cx, z })[0]/*B<object?>*/; o = (new[] { cy, z })[0]/*B<object!>*/; o = (new[] { cz, z })[0]/*B<object>*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (10,25): warning CS8619: Nullability of reference types in value of type 'C2' doesn't match target type 'B<object?>'. // o = (new[] { x, cy })[0]/*B<object>*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "cy").WithArguments("C2", "B<object?>").WithLocation(10, 25), // (12,25): warning CS8619: Nullability of reference types in value of type 'C1' doesn't match target type 'B<object>'. // o = (new[] { y, cx })[0]/*B<object>*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "cx").WithArguments("C1", "B<object>").WithLocation(12, 25) ); comp.VerifyTypes(); } [Fact] [WorkItem(29888, "https://github.com/dotnet/roslyn/issues/29888")] public void ImplicitlyTypedArrayCreation_08() { var source = @"class C<T> { } class C { static void F(C<object>? a, C<object?> b) { if (a == null) { var c = new[] { a, b }; c[0].ToString(); var d = new[] { b, a }; d[0].ToString(); } else { var c = new[] { a, b }; c[0].ToString(); var d = new[] { b, a }; d[0].ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,32): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var c = new[] { a, b }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b").WithArguments("C<object?>", "C<object>").WithLocation(8, 32), // (9,13): warning CS8602: Dereference of a possibly null reference. // c[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c[0]").WithLocation(9, 13), // (10,29): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var d = new[] { b, a }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b").WithArguments("C<object?>", "C<object>").WithLocation(10, 29), // (11,13): warning CS8602: Dereference of a possibly null reference. // d[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d[0]").WithLocation(11, 13), // (15,32): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var c = new[] { a, b }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b").WithArguments("C<object?>", "C<object>").WithLocation(15, 32), // (17,29): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var d = new[] { b, a }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b").WithArguments("C<object?>", "C<object>").WithLocation(17, 29) ); } [Fact] public void ImplicitlyTypedArrayCreation_09() { var source = @"class C { static void F(C x1, Unknown? y1) { var a1 = new[] { x1, y1 }; a1[0].ToString(); var b1 = new[] { y1, x1 }; b1[0].ToString(); } static void G(C? x2, Unknown y2) { var a2 = new[] { x2, y2 }; a2[0].ToString(); var b2 = new[] { y2, x2 }; b2[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,26): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // static void G(C? x2, Unknown y2) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(10, 26), // (3,25): error CS0246: The type or namespace name 'Unknown' could not be found (are you missing a using directive or an assembly reference?) // static void F(C x1, Unknown? y1) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unknown").WithArguments("Unknown").WithLocation(3, 25), // (5,18): error CS0826: No best type found for implicitly-typed array // var a1 = new[] { x1, y1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { x1, y1 }").WithLocation(5, 18), // (7,18): error CS0826: No best type found for implicitly-typed array // var b1 = new[] { y1, x1 }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { y1, x1 }").WithLocation(7, 18)); } [Fact] public void ImplicitlyTypedArrayCreation_TopLevelNullability_01() { var source0 = @"public class A { public static object F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F(object? x, object y) { var z = A.F/*T:object!*/; object? o; o = (new[] { x, x })[0]/*T:object?*/; o = (new[] { x, y })[0]/*T:object?*/; o = (new[] { x, z })[0]/*T:object?*/; o = (new[] { y, x })[0]/*T:object?*/; o = (new[] { y, y })[0]/*T:object!*/; o = (new[] { y, z })[0]/*T:object!*/; o = (new[] { z, x })[0]/*T:object?*/; o = (new[] { z, y })[0]/*T:object!*/; o = (new[] { z, z })[0]/*T:object!*/; o = (new[] { x, y, z })[0]/*T:object?*/; o = (new[] { z, y, x })[0]/*T:object?*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void ImplicitlyTypedArrayCreation_TopLevelNullability_02() { var source = @"class C { static void F<T, U>(T t, U u) where T : class? where U : class, T { object? o; o = (new[] { t, t })[0]/*T:T*/; o = (new[] { t, u })[0]/*T:T*/; o = (new[] { u, t })[0]/*T:T*/; o = (new[] { u, u })[0]/*T:U!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] [Fact] public void ImplicitlyTypedArrayCreation_NestedNullability_Invariant() { var source0 = @"public class A { public static B<object> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class Program { static void F(bool b, B<object?> x, B<object> y) { var z = A.F/*T:B<object>!*/; object o; o = (new[] { x, y })[0]/*T:B<object!>!*/; // 1 o = (new[] { x, z })[0]/*T:B<object?>!*/; o = (new[] { y, x })[0]/*T:B<object!>!*/; // 2 o = (new[] { y, z })[0]/*T:B<object!>!*/; o = (new[] { z, x })[0]/*T:B<object?>!*/; o = (new[] { z, y })[0]/*T:B<object!>!*/; o = (new[] { x, y, z })[0]/*T:B<object!>!*/; // 3 o = (new[] { z, y, x })[0]/*T:B<object!>!*/; // 4 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (7,22): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // o = (new[] { x, y })[0]/*T:B<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(7, 22), // (9,25): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // o = (new[] { y, x })[0]/*T:B<object!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(9, 25), // (13,22): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // o = (new[] { x, y, z })[0]/*T:B<object!>!*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(13, 22), // (14,28): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // o = (new[] { z, y, x })[0]/*T:B<object!>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(14, 28) ); comp.VerifyTypes(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] public void ImplicitlyTypedArrayCreation_NestedNullability_Variant_01() { var source0 = @"public class A { public static I<object> F; public static IIn<object> FIn; public static IOut<object> FOut; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F(I<object> x, I<object?> y) { var z = A.F/*T:I<object>!*/; object o; o = (new[] { x, x })[0]/*T:I<object!>!*/; o = (new[] { x, y })[0]/*T:I<object!>!*/; // 1 o = (new[] { x, z })[0]/*T:I<object!>!*/; o = (new[] { y, x })[0]/*T:I<object!>!*/; // 2 o = (new[] { y, y })[0]/*T:I<object?>!*/; o = (new[] { y, z })[0]/*T:I<object?>!*/; o = (new[] { z, x })[0]/*T:I<object!>!*/; o = (new[] { z, y })[0]/*T:I<object?>!*/; o = (new[] { z, z })[0]/*T:I<object>!*/; } static void F(IIn<object> x, IIn<object?> y) { var z = A.FIn/*T:IIn<object>!*/; object o; o = (new[] { x, x })[0]/*T:IIn<object!>!*/; o = (new[] { x, y })[0]/*T:IIn<object!>!*/; o = (new[] { x, z })[0]/*T:IIn<object!>!*/; o = (new[] { y, x })[0]/*T:IIn<object!>!*/; o = (new[] { y, y })[0]/*T:IIn<object?>!*/; o = (new[] { y, z })[0]/*T:IIn<object>!*/; o = (new[] { z, x })[0]/*T:IIn<object!>!*/; o = (new[] { z, y })[0]/*T:IIn<object>!*/; o = (new[] { z, z })[0]/*T:IIn<object>!*/; } static void F(IOut<object> x, IOut<object?> y) { var z = A.FOut/*T:IOut<object>!*/; object o; o = (new[] { x, x })[0]/*T:IOut<object!>!*/; o = (new[] { x, y })[0]/*T:IOut<object?>!*/; o = (new[] { x, z })[0]/*T:IOut<object>!*/; o = (new[] { y, x })[0]/*T:IOut<object?>!*/; o = (new[] { y, y })[0]/*T:IOut<object?>!*/; o = (new[] { y, z })[0]/*T:IOut<object?>!*/; o = (new[] { z, x })[0]/*T:IOut<object>!*/; o = (new[] { z, y })[0]/*T:IOut<object?>!*/; o = (new[] { z, z })[0]/*T:IOut<object>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,25): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // o = (new[] { x, y })[0]/*T:I<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(8, 25), // (10,22): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // o = (new[] { y, x })[0]/*T:I<object!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(10, 22) ); comp.VerifyTypes(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] public void ImplicitlyTypedArrayCreation_NestedNullability_Variant_02() { var source0 = @"public class A { public static I<string> F; public static IIn<string> FIn; public static IOut<string> FOut; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static I<T> Create1<T>(T t) => throw null!; static void G1(I<IOut<string?>> x1, I<IOut<string>> y1) { var z1 = Create1(A.FOut)/*T:I<IOut<string>!>!*/; object o; o = (new [] { x1, x1 })[0]/*T:I<IOut<string?>!>!*/; o = (new [] { x1, y1 })[0]/*T:I<IOut<string!>!>!*/; // 1 o = (new [] { x1, z1 })[0]/*T:I<IOut<string?>!>!*/; o = (new [] { y1, x1 })[0]/*T:I<IOut<string!>!>!*/; // 2 o = (new [] { y1, y1 })[0]/*T:I<IOut<string!>!>!*/; o = (new [] { y1, z1 })[0]/*T:I<IOut<string!>!>!*/; o = (new [] { z1, x1 })[0]/*T:I<IOut<string?>!>!*/; o = (new [] { z1, y1 })[0]/*T:I<IOut<string!>!>!*/; o = (new [] { z1, z1 })[0]/*T:I<IOut<string>!>!*/; } static IOut<T> Create2<T>(T t) => throw null!; static void G2(IOut<IIn<string?>> x2, IOut<IIn<string>> y2) { var z2 = Create2(A.FIn)/*T:IOut<IIn<string>!>!*/; object o; o = (new [] { x2, x2 })[0]/*T:IOut<IIn<string?>!>!*/; o = (new [] { x2, y2 })[0]/*T:IOut<IIn<string!>!>!*/; o = (new [] { x2, z2 })[0]/*T:IOut<IIn<string>!>!*/; o = (new [] { y2, x2 })[0]/*T:IOut<IIn<string!>!>!*/; o = (new [] { y2, y2 })[0]/*T:IOut<IIn<string!>!>!*/; o = (new [] { y2, z2 })[0]/*T:IOut<IIn<string!>!>!*/; o = (new [] { z2, x2 })[0]/*T:IOut<IIn<string>!>!*/; o = (new [] { z2, y2 })[0]/*T:IOut<IIn<string!>!>!*/; o = (new [] { z2, z2 })[0]/*T:IOut<IIn<string>!>!*/; } static IIn<T> Create3<T>(T t) => throw null!; static void G3(IIn<IOut<string?>> x3, IIn<IOut<string>> y3) { var z3 = Create3(A.FOut)/*T:IIn<IOut<string>!>!*/; object o; o = (new [] { x3, x3 })[0]/*T:IIn<IOut<string?>!>!*/; o = (new [] { x3, y3 })[0]/*T:IIn<IOut<string!>!>!*/; o = (new [] { x3, z3 })[0]/*T:IIn<IOut<string>!>!*/; o = (new [] { y3, x3 })[0]/*T:IIn<IOut<string!>!>!*/; o = (new [] { y3, y3 })[0]/*T:IIn<IOut<string!>!>!*/; o = (new [] { y3, z3 })[0]/*T:IIn<IOut<string!>!>!*/; o = (new [] { z3, x3 })[0]/*T:IIn<IOut<string>!>!*/; o = (new [] { z3, y3 })[0]/*T:IIn<IOut<string!>!>!*/; o = (new [] { z3, z3 })[0]/*T:IIn<IOut<string>!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (10,23): warning CS8619: Nullability of reference types in value of type 'I<IOut<string?>>' doesn't match target type 'I<IOut<string>>'. // o = (new [] { x1, y1 })[0]/*T:I<IOut<string!>!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("I<IOut<string?>>", "I<IOut<string>>").WithLocation(10, 23), // (12,27): warning CS8619: Nullability of reference types in value of type 'I<IOut<string?>>' doesn't match target type 'I<IOut<string>>'. // o = (new [] { y1, x1 })[0]/*T:I<IOut<string!>!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("I<IOut<string?>>", "I<IOut<string>>").WithLocation(12, 27) ); comp.VerifyTypes(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] public void ImplicitlyTypedArrayCreation_NestedNullability_Variant_03() { var source0 = @"public class A { public static object F1; public static string F2; public static B<object>.INone BON; public static B<object>.I<string> BOI; public static B<object>.IIn<string> BOIIn; public static B<object>.IOut<string> BOIOut; } public class B<T> { public interface INone { } public interface I<U> { } public interface IIn<in U> { } public interface IOut<out U> { } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static void G0(B<object>.INone x0, B<object?>.INone y0) { var z0 = A.BON/*T:B<object>.INone!*/; object o; o = (new[] { x0, x0 })[0]/*T:B<object!>.INone!*/; o = (new[] { x0, y0 })[0]/*T:B<object!>.INone!*/; // 1 o = (new[] { x0, z0 })[0]/*T:B<object!>.INone!*/; o = (new[] { y0, x0 })[0]/*T:B<object!>.INone!*/; // 2 o = (new[] { y0, y0 })[0]/*T:B<object?>.INone!*/; o = (new[] { y0, z0 })[0]/*T:B<object?>.INone!*/; o = (new[] { z0, x0 })[0]/*T:B<object!>.INone!*/; o = (new[] { z0, y0 })[0]/*T:B<object?>.INone!*/; o = (new[] { z0, z0 })[0]/*T:B<object>.INone!*/; } static void G1(B<object>.I<string> x1, B<object?>.I<string?> y1) { var z1 = A.BOI/*T:B<object>.I<string>!*/; object o; o = (new[] { x1, x1 })[0]/*T:B<object!>.I<string!>!*/; o = (new[] { x1, y1 })[0]/*T:B<object!>.I<string!>!*/; // 3 o = (new[] { x1, z1 })[0]/*T:B<object!>.I<string!>!*/; o = (new[] { y1, x1 })[0]/*T:B<object!>.I<string!>!*/; // 4 o = (new[] { y1, y1 })[0]/*T:B<object?>.I<string?>!*/; o = (new[] { y1, z1 })[0]/*T:B<object?>.I<string?>!*/; o = (new[] { z1, x1 })[0]/*T:B<object!>.I<string!>!*/; o = (new[] { z1, y1 })[0]/*T:B<object?>.I<string?>!*/; o = (new[] { z1, z1 })[0]/*T:B<object>.I<string>!*/; } static void G2(B<object>.IIn<string> x2, B<object?>.IIn<string?> y2) { var z2 = A.BOIIn/*T:B<object>.IIn<string>!*/; object o; o = (new[] { x2, x2 })[0]/*T:B<object!>.IIn<string!>!*/; o = (new[] { x2, y2 })[0]/*T:B<object!>.IIn<string!>!*/; // 5 o = (new[] { x2, z2 })[0]/*T:B<object!>.IIn<string!>!*/; o = (new[] { y2, x2 })[0]/*T:B<object!>.IIn<string!>!*/; // 6 o = (new[] { y2, y2 })[0]/*T:B<object?>.IIn<string?>!*/; o = (new[] { y2, z2 })[0]/*T:B<object?>.IIn<string>!*/; o = (new[] { z2, x2 })[0]/*T:B<object!>.IIn<string!>!*/; o = (new[] { z2, y2 })[0]/*T:B<object?>.IIn<string>!*/; o = (new[] { z2, z2 })[0]/*T:B<object>.IIn<string>!*/; } static void G3(B<object>.IOut<string> x3, B<object?>.IOut<string?> y3) { var z3 = A.BOIOut/*T:B<object>.IOut<string>!*/; object o; o = (new[] { x3, x3 })[0]/*T:B<object!>.IOut<string!>!*/; o = (new[] { x3, y3 })[0]/*T:B<object!>.IOut<string?>!*/; // 7 o = (new[] { x3, z3 })[0]/*T:B<object!>.IOut<string>!*/; o = (new[] { y3, x3 })[0]/*T:B<object!>.IOut<string?>!*/; // 8 o = (new[] { y3, y3 })[0]/*T:B<object?>.IOut<string?>!*/; o = (new[] { y3, z3 })[0]/*T:B<object?>.IOut<string?>!*/; o = (new[] { z3, x3 })[0]/*T:B<object!>.IOut<string>!*/; o = (new[] { z3, y3 })[0]/*T:B<object?>.IOut<string?>!*/; o = (new[] { z3, z3 })[0]/*T:B<object>.IOut<string>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (9,26): warning CS8619: Nullability of reference types in value of type 'B<object?>.INone' doesn't match target type 'B<object>.INone'. // o = (new[] { x0, y0 })[0]/*T:B<object!>.INone!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y0").WithArguments("B<object?>.INone", "B<object>.INone").WithLocation(9, 26), // (11,22): warning CS8619: Nullability of reference types in value of type 'B<object?>.INone' doesn't match target type 'B<object>.INone'. // o = (new[] { y0, x0 })[0]/*T:B<object!>.INone!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y0").WithArguments("B<object?>.INone", "B<object>.INone").WithLocation(11, 22), // (23,26): warning CS8619: Nullability of reference types in value of type 'B<object?>.I<string?>' doesn't match target type 'B<object>.I<string>'. // o = (new[] { x1, y1 })[0]/*T:B<object!>.I<string!>!*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("B<object?>.I<string?>", "B<object>.I<string>").WithLocation(23, 26), // (25,22): warning CS8619: Nullability of reference types in value of type 'B<object?>.I<string?>' doesn't match target type 'B<object>.I<string>'. // o = (new[] { y1, x1 })[0]/*T:B<object!>.I<string!>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("B<object?>.I<string?>", "B<object>.I<string>").WithLocation(25, 22), // (37,26): warning CS8619: Nullability of reference types in value of type 'B<object?>.IIn<string?>' doesn't match target type 'B<object>.IIn<string>'. // o = (new[] { x2, y2 })[0]/*T:B<object!>.IIn<string!>!*/; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y2").WithArguments("B<object?>.IIn<string?>", "B<object>.IIn<string>").WithLocation(37, 26), // (39,22): warning CS8619: Nullability of reference types in value of type 'B<object?>.IIn<string?>' doesn't match target type 'B<object>.IIn<string>'. // o = (new[] { y2, x2 })[0]/*T:B<object!>.IIn<string!>!*/; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y2").WithArguments("B<object?>.IIn<string?>", "B<object>.IIn<string>").WithLocation(39, 22), // (51,26): warning CS8619: Nullability of reference types in value of type 'B<object?>.IOut<string?>' doesn't match target type 'B<object>.IOut<string?>'. // o = (new[] { x3, y3 })[0]/*T:B<object!>.IOut<string?>!*/; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y3").WithArguments("B<object?>.IOut<string?>", "B<object>.IOut<string?>").WithLocation(51, 26), // (53,22): warning CS8619: Nullability of reference types in value of type 'B<object?>.IOut<string?>' doesn't match target type 'B<object>.IOut<string?>'. // o = (new[] { y3, x3 })[0]/*T:B<object!>.IOut<string?>!*/; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y3").WithArguments("B<object?>.IOut<string?>", "B<object>.IOut<string?>").WithLocation(53, 22)); comp.VerifyTypes(); } [Fact] public void ImplicitlyTypedArrayCreation_NestedNullability_Tuples() { var source0 = @"public class A { public static object F; public static I<object> IF; } public interface I<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F1(bool b, object x1, object? y1) { var z1 = A.F/*T:object!*/; object o; o = (new[] { (x1, x1), (x1, y1) })[0]/*T:(object!, object?)*/; o = (new[] { (z1, x1), (x1, x1) })[0]/*T:(object!, object!)*/; o = (new[] { (y1, y1), (y1, z1) })[0]/*T:(object?, object?)*/; o = (new[] { (x1, y1), (y1, y1) })[0]/*T:(object?, object?)*/; o = (new[] { (z1, z1), (z1, x1) })[0]/*T:(object!, object!)*/; o = (new[] { (y1, z1), (z1, z1) })[0]/*T:(object?, object!)*/; } static void F2(bool b, I<object> x2, I<object?> y2) { var z2 = A.IF/*T:I<object>!*/; object o; o = (new[] { (x2, x2), (x2, y2) })[0]/*T:(I<object!>!, I<object!>!)*/; // 1 o = (new[] { (z2, x2), (x2, x2) })[0]/*T:(I<object!>!, I<object!>!)*/; o = (new[] { (y2, y2), (y2, z2) })[0]/*T:(I<object?>!, I<object?>!)*/; o = (new[] { (x2, y2), (y2, y2) })[0]/*T:(I<object!>!, I<object?>!)*/; // 2 o = (new[] { (z2, z2), (z2, x2) })[0]/*T:(I<object>!, I<object!>!)*/; o = (new[] { (y2, z2), (z2, z2) })[0]/*T:(I<object?>!, I<object>!)*/; o = (new[] { (x2, x2)!, (x2, y2) })[0]/*T:(I<object!>!, I<object!>!)*/; // 3 o = (new[] { (x2, y2), (y2, y2)! })[0]/*T:(I<object!>!, I<object?>!)*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (18,32): warning CS8619: Nullability of reference types in value of type '(I<object> x2, I<object?> y2)' doesn't match target type '(I<object>, I<object>)'. // o = (new[] { (x2, x2), (x2, y2) })[0]/*T:(I<object!>!, I<object!>!)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x2, y2)").WithArguments("(I<object> x2, I<object?> y2)", "(I<object>, I<object>)").WithLocation(18, 32), // (21,32): warning CS8619: Nullability of reference types in value of type '(I<object?>, I<object?>)' doesn't match target type '(I<object>, I<object?>)'. // o = (new[] { (x2, y2), (y2, y2) })[0]/*T:(I<object!>!, I<object?>!)*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(y2, y2)").WithArguments("(I<object?>, I<object?>)", "(I<object>, I<object?>)").WithLocation(21, 32), // (25,33): warning CS8619: Nullability of reference types in value of type '(I<object> x2, I<object?> y2)' doesn't match target type '(I<object>, I<object>)'. // o = (new[] { (x2, x2)!, (x2, y2) })[0]/*T:(I<object!>!, I<object!>!)*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x2, y2)").WithArguments("(I<object> x2, I<object?> y2)", "(I<object>, I<object>)").WithLocation(25, 33)); comp.VerifyTypes(); } [Fact] public void ImplicitlyTypedArrayCreation_Empty() { var source = @"class Program { static void Main() { var a = new[] { }; var b = new[] { null }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,17): error CS0826: No best type found for implicitly-typed array // var a = new[] { }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { }").WithLocation(5, 17), // (6,17): error CS0826: No best type found for implicitly-typed array // var b = new[] { null }; Diagnostic(ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, "new[] { null }").WithLocation(6, 17)); } [Fact, WorkItem(36132, "https://github.com/dotnet/roslyn/issues/36132")] public void ImplicitlyTypedArrayCreation_UsesNullabilitiesOfConvertedTypes() { var source = @" class A { } class B { public static implicit operator A(B? b) => new A(); } class C { public static implicit operator A?(C c) => new A(); } class D { void Test(A a, B? b, C c) { _ = (new A[] { a, b }) /*T:A![]!*/; _ = (new A?[] { a, b }) /*T:A?[]!*/; _ = (new[] { a, b }) /*T:A![]!*/; _ = (new[] { b, a }) /*T:A![]!*/; _ = (new A[] { a, c }) /*T:A![]!*/; // 1 _ = (new A?[] { a, c }) /*T:A?[]!*/; _ = (new[] { a, c }) /*T:A?[]!*/; _ = (new[] { c, a }) /*T:A?[]!*/; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (15,27): warning CS8601: Possible null reference assignment. // _ = (new A[] { a, c }) /*T:A![]!*/; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c").WithLocation(15, 27) ); comp.VerifyTypes(); } [Fact, WorkItem(36132, "https://github.com/dotnet/roslyn/issues/36132")] public void Ternary_UsesNullabilitiesOfConvertedTypes() { var source = @" class A { } class B { public static implicit operator A(B? b) => new A(); } class C { public static implicit operator A?(C c) => new A(); } class D { void Test(A a, B? b, C c, bool cond) { _ = (cond ? a : b) /*T:A!*/; _ = (cond ? b : a) /*T:A!*/; _ = (cond ? a : c) /*T:A?*/; _ = (cond ? c : a) /*T:A?*/; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact, WorkItem(36132, "https://github.com/dotnet/roslyn/issues/36132")] public void ReturnTypeInference_UsesNullabilitiesOfConvertedTypes() { var source = @" using System; class A { } class B { public static implicit operator A(B? b) => new A(); } class C { public static implicit operator A?(C c) => new A(); } class D { void Test(A a, B? b, C c, bool cond) { Func<A> x1 = () => { if (cond) return a; else return b; }; Func<A> x2 = () => { if (cond) return b; else return a; }; Func<A?> x3 = () => { if (cond) return a; else return c; }; Func<A?> x4 = () => { if (cond) return c; else return a; }; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void ExplicitlyTypedArrayCreation() { var source = @"class C { static void F(object x, object? y) { var a = new object[] { x, y }; a[0].ToString(); var b = new object?[] { x, y }; b[0].ToString(); var c = new object[] { x, y! }; c[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,35): warning CS8601: Possible null reference assignment. // var a = new object[] { x, y }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(5, 35), // (8,9): warning CS8602: Dereference of a possibly null reference. // b[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b[0]").WithLocation(8, 9)); } [Fact] public void IdentityConversion_ArrayInitializer_02() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(I<object> x, I<object?> y, I<object>? z, I<object?>? w) { (new[] { x, y })[0].ToString(); // A1 (new[] { x, z })[0].ToString(); // A2 (new[] { x, w })[0].ToString(); // A3 (new[] { y, z })[0].ToString(); // A4 (new[] { y, w })[0].ToString(); // A5 (new[] { w, z })[0].ToString(); // A6 } static void F(IIn<object> x, IIn<object?> y, IIn<object>? z, IIn<object?>? w) { (new[] { x, y })[0].ToString(); // B1 (new[] { x, z })[0].ToString(); // B2 (new[] { x, w })[0].ToString(); // B3 (new[] { y, z })[0].ToString(); // B4 (new[] { y, w })[0].ToString(); // B5 (new[] { w, z })[0].ToString(); // B6 } static void F(IOut<object> x, IOut<object?> y, IOut<object>? z, IOut<object?>? w) { (new[] { x, y })[0].ToString(); // C1 (new[] { x, z })[0].ToString(); // C2 (new[] { x, w })[0].ToString(); // C3 (new[] { y, z })[0].ToString(); // C4 (new[] { y, w })[0].ToString(); // C5 (new[] { w, z })[0].ToString(); // C6 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,21): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // (new[] { x, y })[0].ToString(); // A1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(8, 21), // (9,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, z })[0].ToString(); // A2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, z })[0]").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, w })[0].ToString(); // A3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, w })[0]").WithLocation(10, 9), // (10,21): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // (new[] { x, w })[0].ToString(); // A3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("I<object?>", "I<object>").WithLocation(10, 21), // (11,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, z })[0].ToString(); // A4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, z })[0]").WithLocation(11, 9), // (11,18): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // (new[] { y, z })[0].ToString(); // A4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(11, 18), // (12,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, w })[0].ToString(); // A5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, w })[0]").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // (new[] { w, z })[0].ToString(); // A6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { w, z })[0]").WithLocation(13, 9), // (13,18): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // (new[] { w, z })[0].ToString(); // A6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w").WithArguments("I<object?>", "I<object>").WithLocation(13, 18), // (18,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, z })[0].ToString(); // B2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, z })[0]").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, w })[0].ToString(); // B3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, w })[0]").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, z })[0].ToString(); // B4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, z })[0]").WithLocation(20, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, w })[0].ToString(); // B5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, w })[0]").WithLocation(21, 9), // (22,9): warning CS8602: Dereference of a possibly null reference. // (new[] { w, z })[0].ToString(); // B6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { w, z })[0]").WithLocation(22, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, z })[0].ToString(); // C2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, z })[0]").WithLocation(27, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, w })[0].ToString(); // C3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, w })[0]").WithLocation(28, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, z })[0].ToString(); // C4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, z })[0]").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, w })[0].ToString(); // C5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, w })[0]").WithLocation(30, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // (new[] { w, z })[0].ToString(); // C6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { w, z })[0]").WithLocation(31, 9) ); } [Fact] public void IdentityConversion_ArrayInitializer_IsNullableNull() { var source0 = @"#pragma warning disable 8618 public class A<T> { public T F; } public class B : A<object> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static void F(object? x, B b) { var y = b.F/*T:object!*/; (new[] { x, x! })[0].ToString(); // 1 (new[] { x!, x })[0].ToString(); // 2 (new[] { x!, x! })[0].ToString(); (new[] { y, y! })[0].ToString(); (new[] { y!, y })[0].ToString(); (new[] { x, y })[0].ToString(); // 3 (new[] { x, y! })[0].ToString(); // 4 (new[] { x!, y })[0].ToString(); (new[] { x!, y! })[0].ToString(); } static void F(A<object?> z, B w) { (new[] { z, z! })[0].F.ToString(); // 5 (new[] { z!, z })[0].F.ToString(); // 6 (new[] { z!, z! })[0].F.ToString(); // 7 (new[] { w, w! })[0].F.ToString(); (new[] { w!, w })[0].F.ToString(); (new[] { z, w })[0].F.ToString(); // 8 (new[] { z, w! })[0].F.ToString(); // 9 (new[] { z!, w })[0].F.ToString(); // 10 (new[] { z!, w! })[0].F.ToString(); // 11 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); // https://github.com/dotnet/roslyn/issues/30376: `!` should suppress conversion warnings. comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, x! })[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, x! })[0]").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x!, x })[0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x!, x })[0]").WithLocation(7, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, y })[0].ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, y })[0]").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, y! })[0].ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, y! })[0]").WithLocation(12, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z, z! })[0].F.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z, z! })[0].F").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z!, z })[0].F.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z!, z })[0].F").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z!, z! })[0].F.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z!, z! })[0].F").WithLocation(20, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z, w })[0].F.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z, w })[0].F").WithLocation(23, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z, w! })[0].F.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z, w! })[0].F").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z!, w })[0].F.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z!, w })[0].F").WithLocation(25, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // (new[] { z!, w! })[0].F.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { z!, w! })[0].F").WithLocation(26, 9)); } [Fact] public void IdentityConversion_ArrayInitializer_ExplicitType() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(I<object>? x, I<object?>? y) { I<object?>?[] a = new[] { x }; I<object?>[] b = new[] { y }; I<object>?[] c = new[] { y }; I<object>[] d = new[] { x }; } static void F(IIn<object>? x, IIn<object?>? y) { IIn<object?>?[] a = new[] { x }; IIn<object?>[] b = new[] { y }; IIn<object>?[] c = new[] { y }; IIn<object>[] d = new[] { x }; } static void F(IOut<object>? x, IOut<object?>? y) { IOut<object?>?[] a = new[] { x }; IOut<object?>[] b = new[] { y }; IOut<object>?[] c = new[] { y }; IOut<object>[] d = new[] { x }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,27): warning CS8619: Nullability of reference types in value of type 'I<object>?[]' doesn't match target type 'I<object?>?[]'. // I<object?>?[] a = new[] { x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { x }").WithArguments("I<object>?[]", "I<object?>?[]").WithLocation(8, 27), // (9,26): warning CS8619: Nullability of reference types in value of type 'I<object?>?[]' doesn't match target type 'I<object?>[]'. // I<object?>[] b = new[] { y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { y }").WithArguments("I<object?>?[]", "I<object?>[]").WithLocation(9, 26), // (10,26): warning CS8619: Nullability of reference types in value of type 'I<object?>?[]' doesn't match target type 'I<object>?[]'. // I<object>?[] c = new[] { y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { y }").WithArguments("I<object?>?[]", "I<object>?[]").WithLocation(10, 26), // (11,25): warning CS8619: Nullability of reference types in value of type 'I<object>?[]' doesn't match target type 'I<object>[]'. // I<object>[] d = new[] { x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { x }").WithArguments("I<object>?[]", "I<object>[]").WithLocation(11, 25), // (15,29): warning CS8619: Nullability of reference types in value of type 'IIn<object>?[]' doesn't match target type 'IIn<object?>?[]'. // IIn<object?>?[] a = new[] { x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { x }").WithArguments("IIn<object>?[]", "IIn<object?>?[]").WithLocation(15, 29), // (16,28): warning CS8619: Nullability of reference types in value of type 'IIn<object?>?[]' doesn't match target type 'IIn<object?>[]'. // IIn<object?>[] b = new[] { y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { y }").WithArguments("IIn<object?>?[]", "IIn<object?>[]").WithLocation(16, 28), // (18,27): warning CS8619: Nullability of reference types in value of type 'IIn<object>?[]' doesn't match target type 'IIn<object>[]'. // IIn<object>[] d = new[] { x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { x }").WithArguments("IIn<object>?[]", "IIn<object>[]").WithLocation(18, 27), // (23,29): warning CS8619: Nullability of reference types in value of type 'IOut<object?>?[]' doesn't match target type 'IOut<object?>[]'. // IOut<object?>[] b = new[] { y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { y }").WithArguments("IOut<object?>?[]", "IOut<object?>[]").WithLocation(23, 29), // (24,29): warning CS8619: Nullability of reference types in value of type 'IOut<object?>?[]' doesn't match target type 'IOut<object>?[]'. // IOut<object>?[] c = new[] { y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { y }").WithArguments("IOut<object?>?[]", "IOut<object>?[]").WithLocation(24, 29), // (25,28): warning CS8619: Nullability of reference types in value of type 'IOut<object>?[]' doesn't match target type 'IOut<object>[]'. // IOut<object>[] d = new[] { x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new[] { x }").WithArguments("IOut<object>?[]", "IOut<object>[]").WithLocation(25, 28)); } [Fact] public void ImplicitConversion_ArrayInitializer_ExplicitType_01() { var source = @"class A<T> { } class B<T> : A<T> { } class C { static void F(A<object> x, B<object?> y) { var z = new A<object>[] { x, y }; var w = new A<object?>[] { x, y }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,38): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'A<object>'. // var z = new A<object>[] { x, y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("B<object?>", "A<object>").WithLocation(7, 38), // (8,36): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'A<object?>'. // var w = new A<object?>[] { x, y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "A<object?>").WithLocation(8, 36)); } [Fact] public void ImplicitConversion_ArrayInitializer_ExplicitType_02() { var source = @"interface IIn<in T> { } interface IOut<out T> { } class C { static void F(IIn<object> x, IIn<object?> y) { var a = new IIn<string?>[] { x }; var b = new IIn<string>[] { y }; } static void F(IOut<string> x, IOut<string?> y) { var a = new IOut<object?>[] { x }; var b = new IOut<object>[] { y }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,38): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<string?>'. // var a = new IIn<string?>[] { x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object>", "IIn<string?>").WithLocation(7, 38), // (13,38): warning CS8619: Nullability of reference types in value of type 'IOut<string?>' doesn't match target type 'IOut<object>'. // var b = new IOut<object>[] { y }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("IOut<string?>", "IOut<object>").WithLocation(13, 38)); } [Fact] public void MultipleConversions_ArrayInitializer() { var source = @"class A { public static implicit operator C(A a) => new C(); } class B : A { } class C { static void F(B x, C? y) { (new[] { x, y })[0].ToString(); (new[] { y, x })[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, y })[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, y })[0]").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, x })[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, x })[0]").WithLocation(13, 9)); } [Fact] public void MultipleConversions_ArrayInitializer_ConversionWithNullableOutput() { var source = @"class A { public static implicit operator C?(A a) => new C(); } class B : A { } class C { static void F(B x, C y) { (new[] { x, y })[0].ToString(); (new[] { y, x })[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // (new[] { x, y })[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { x, y })[0]").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // (new[] { y, x })[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new[] { y, x })[0]").WithLocation(13, 9)); } [Fact] public void MultipleConversions_ArrayInitializer_ConversionWithNullableInput() { var source = @"class A { public static implicit operator C(A? a) => new C(); } class B : A { } class C { static void F(B? x, C y) { (new[] { x, y })[0].ToString(); (new[] { y, x })[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ObjectInitializer_01() { CSharpCompilation c = CreateCompilation( new[] { @"#pragma warning disable 8618 class C { static void Main() {} void Test1(CL1? x1, CL1? y1) { var z1 = new CL1() { F1 = x1, F2 = y1 }; } void Test2(CL1? x2, CL1? y2) { var z2 = new CL1() { P1 = x2, P2 = y2 }; } void Test3(CL1 x3, CL1 y3) { var z31 = new CL1() { F1 = x3, F2 = y3 }; var z32 = new CL1() { P1 = x3, P2 = y3 }; } } class CL1 { public CL1 F1; public CL1? F2; public CL1 P1 {get; set;} public CL1? P2 {get; set;} } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,35): warning CS8601: Possible null reference assignment. // var z1 = new CL1() { F1 = x1, F2 = y1 }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x1").WithLocation(9, 35), // (14,35): warning CS8601: Possible null reference assignment. // var z2 = new CL1() { P1 = x2, P2 = y2 }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x2").WithLocation(14, 35) ); } [Fact] public void ObjectInitializer_02() { var source = @"class C { C(object o) { } static void F(object? x) { var y = new C(x); if (x != null) y = new C(x); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,23): warning CS8604: Possible null reference argument for parameter 'o' in 'C.C(object o)'. // var y = new C(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("o", "C.C(object o)").WithLocation(6, 23)); } [Fact] public void ObjectInitializer_03() { var source = @"class A { internal B F = new B(); } class B { internal object? G; } class C { static void Main() { var o = new A() { F = { G = new object() } }; o.F.G.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ObjectInitializer_ParameterlessStructConstructor() { var src = @" #nullable enable var s1 = new S1() { }; s1.field.ToString(); var s2 = new S2() { }; s2.field.ToString(); // 1 var s3 = new S3() { }; s3.field.ToString(); public struct S1 { public string field; public S1() { field = string.Empty; } } public struct S2 { public string field; } public struct S3 { public string field = string.Empty; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,1): warning CS8602: Dereference of a possibly null reference. // s2.field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2.field").WithLocation(8, 1) ); } [Fact] public void IdentityConversion_ObjectElementInitializerArgumentsOrder() { var source = @"interface I<T> { } class C { static C F(I<string> x, I<object> y) { return new C() { [ y: y, // warn 1 x: x] = 1 }; } static object G(C c, I<string?> x, I<object?> y) { return new C() { [ y: y, x: x] // warn 2 = 2 }; } int this[I<string> x, I<object?> y] { get { return 0; } set { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,16): warning CS8620: Nullability of reference types in argument of type 'I<object>' doesn't match target type 'I<object?>' for parameter 'y' in 'int C.this[I<string> x, I<object?> y]'. // y: y, // warn 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object>", "I<object?>", "y", "int C.this[I<string> x, I<object?> y]").WithLocation(7, 16), // (15,16): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'x' in 'int C.this[I<string> x, I<object?> y]'. // x: x] // warn 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<string?>", "I<string>", "x", "int C.this[I<string> x, I<object?> y]").WithLocation(15, 16)); } [Fact] public void ImplicitConversion_CollectionInitializer() { var source = @"using System.Collections.Generic; class A<T> { } class B<T> : A<T> { } class C { static void M(B<object>? x, B<object?> y) { var c = new List<A<object>> { x, // 1 y, // 2 }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8604: Possible null reference argument for parameter 'item' in 'void List<A<object>>.Add(A<object> item)'. // x, // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("item", "void List<A<object>>.Add(A<object> item)").WithLocation(10, 13), // (11,13): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'A<object>' for parameter 'item' in 'void List<A<object>>.Add(A<object> item)'. // y, // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("B<object?>", "A<object>", "item", "void List<A<object>>.Add(A<object> item)").WithLocation(11, 13)); } [Fact] public void Structs_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL1 x1) { S1 y1 = new S1(); y1.F1 = x1; y1 = new S1(); x1 = y1.F1; } void M1(ref S1 x) {} void Test2(CL1 x2) { S1 y2 = new S1(); y2.F1 = x2; M1(ref y2); x2 = y2.F1; } void Test3(CL1 x3) { S1 y3 = new S1() { F1 = x3 }; x3 = y3.F1; } void Test4(CL1 x4, CL1? z4) { var y4 = new S2() { F2 = new S1() { F1 = x4, F3 = z4 } }; x4 = y4.F2.F1 ?? x4; x4 = y4.F2.F3; } void Test5(CL1 x5, CL1? z5) { var y5 = new S2() { F2 = new S1() { F1 = x5, F3 = z5 } }; var u5 = y5.F2; x5 = u5.F1 ?? x5; x5 = u5.F3; } } class CL1 { } struct S1 { public CL1? F1; public CL1? F3; } struct S2 { public S1 F2; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = y1.F1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1.F1").WithLocation(12, 14), // (22,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = y2.F1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2.F1").WithLocation(22, 14), // (35,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = y4.F2.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y4.F2.F3").WithLocation(35, 14), // (43,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x5 = u5.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u5.F3").WithLocation(43, 14) ); } [Fact] public void Structs_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL1 x1) { S1 y1; y1.F1 = x1; S1 z1 = y1; x1 = z1.F3; x1 = z1.F3 ?? x1; z1.F3 = null; } struct Test2 { S1 z2 {get;} public Test2(CL1 x2) { S1 y2; y2.F1 = x2; z2 = y2; x2 = z2.F3; x2 = z2.F3 ?? x2; } } void Test3(CL1 x3) { S1 y3; CL1? z3 = y3.F3; x3 = z3; x3 = z3 ?? x3; } void Test4(CL1 x4, CL1? z4) { S1 y4; z4 = y4.F3; x4 = z4; x4 = z4 ?? x4; } void Test5(CL1 x5) { S1 y5; var z5 = new { F3 = y5.F3 }; x5 = z5.F3; x5 = z5.F3 ?? x5; } void Test6(CL1 x6, S1 z6) { S1 y6; y6.F1 = x6; z6 = y6; x6 = z6.F3; x6 = z6.F3 ?? x6; } void Test7(CL1 x7) { S1 y7; y7.F1 = x7; var z7 = new { F3 = y7 }; x7 = z7.F3.F3; x7 = z7.F3.F3 ?? x7; } struct Test8 { CL1? z8 {get;} public Test8(CL1 x8) { S1 y8; y8.F1 = x8; z8 = y8.F3; x8 = z8; x8 = z8 ?? x8; } } } class CL1 { } struct S1 { public CL1? F1; public CL1? F3; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,17): error CS0165: Use of unassigned local variable 'y1' // S1 z1 = y1; Diagnostic(ErrorCode.ERR_UseDefViolation, "y1").WithArguments("y1").WithLocation(11, 17), // (12,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = z1.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z1.F3").WithLocation(12, 14), // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = z1.F3 ?? x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z1.F3 ?? x1").WithLocation(13, 14), // (25,18): error CS0165: Use of unassigned local variable 'y2' // z2 = y2; Diagnostic(ErrorCode.ERR_UseDefViolation, "y2").WithArguments("y2").WithLocation(25, 18), // (26,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = z2.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z2.F3").WithLocation(26, 18), // (27,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = z2.F3 ?? x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z2.F3 ?? x2").WithLocation(27, 18), // (34,19): error CS0170: Use of possibly unassigned field 'F3' // CL1? z3 = y3.F3; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y3.F3").WithArguments("F3").WithLocation(34, 19), // (35,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = z3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z3").WithLocation(35, 14), // (36,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = z3 ?? x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z3 ?? x3").WithLocation(36, 14), // (42,14): error CS0170: Use of possibly unassigned field 'F3' // z4 = y4.F3; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y4.F3").WithArguments("F3").WithLocation(42, 14), // (43,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = z4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z4").WithLocation(43, 14), // (44,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = z4 ?? x4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z4 ?? x4").WithLocation(44, 14), // (50,29): error CS0170: Use of possibly unassigned field 'F3' // var z5 = new { F3 = y5.F3 }; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y5.F3").WithArguments("F3").WithLocation(50, 29), // (51,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x5 = z5.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z5.F3").WithLocation(51, 14), // (52,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x5 = z5.F3 ?? x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z5.F3 ?? x5").WithLocation(52, 14), // (59,14): error CS0165: Use of unassigned local variable 'y6' // z6 = y6; Diagnostic(ErrorCode.ERR_UseDefViolation, "y6").WithArguments("y6").WithLocation(59, 14), // (60,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x6 = z6.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z6.F3").WithLocation(60, 14), // (61,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x6 = z6.F3 ?? x6; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z6.F3 ?? x6").WithLocation(61, 14), // (68,29): error CS0165: Use of unassigned local variable 'y7' // var z7 = new { F3 = y7 }; Diagnostic(ErrorCode.ERR_UseDefViolation, "y7").WithArguments("y7").WithLocation(68, 29), // (69,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x7 = z7.F3.F3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z7.F3.F3").WithLocation(69, 14), // (70,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x7 = z7.F3.F3 ?? x7; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z7.F3.F3 ?? x7").WithLocation(70, 14), // (81,18): error CS0170: Use of possibly unassigned field 'F3' // z8 = y8.F3; Diagnostic(ErrorCode.ERR_UseDefViolationField, "y8.F3").WithArguments("F3").WithLocation(81, 18), // (82,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x8 = z8; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z8").WithLocation(82, 18), // (83,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // x8 = z8 ?? x8; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z8 ?? x8").WithLocation(83, 18) ); } [Fact] public void Structs_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL1 x1) { x1 = new S1().F1; } void Test2(CL1 x2) { x2 = new S1() {F1 = x2}.F1; } void Test3(CL1 x3) { x3 = new S1() {F1 = x3}.F1 ?? x3; } void Test4(CL1 x4) { x4 = new S2().F2; } void Test5(CL1 x5) { x5 = new S2().F2 ?? x5; } } class CL1 { } struct S1 { public CL1? F1; } struct S2 { public CL1 F2; S2(CL1 x) { F2 = x; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = new S1().F1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "new S1().F1").WithLocation(9, 14), // (24,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = new S2().F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "new S2().F2").WithLocation(24, 14) ); } [Fact] public void Structs_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} } struct TS2 { System.Action? E2; TS2(System.Action x2) { this = new TS2(); System.Action z2 = E2; System.Action y2 = E2 ?? x2; } void Dummy() { E2 = null; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action z2 = E2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(15, 28) ); } [Fact] [WorkItem(29889, "https://github.com/dotnet/roslyn/issues/29889")] public void AnonymousTypes_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL1 x1, CL1? z1) { var y1 = new { p1 = x1, p2 = z1 }; x1 = y1.p1 ?? x1; x1 = y1.p2; // 1 } void Test2(CL1 x2, CL1? z2) { var u2 = new { p1 = x2, p2 = z2 }; var v2 = new { p1 = z2, p2 = x2 }; u2 = v2; // 2 x2 = u2.p2 ?? x2; x2 = u2.p1; // 3 x2 = v2.p2 ?? x2; // 4 x2 = v2.p1; // 5 } void Test3(CL1 x3, CL1? z3) { var u3 = new { p1 = x3, p2 = z3 }; var v3 = u3; x3 = v3.p1 ?? x3; x3 = v3.p2; // 6 } void Test4(CL1 x4, CL1? z4) { var u4 = new { p0 = new { p1 = x4, p2 = z4 } }; var v4 = new { p0 = new { p1 = z4, p2 = x4 } }; u4 = v4; // 7 x4 = u4.p0.p2 ?? x4; x4 = u4.p0.p1; // 8 x4 = v4.p0.p2 ?? x4; // 9 x4 = v4.p0.p1; // 10 } void Test5(CL1 x5, CL1? z5) { var u5 = new { p0 = new { p1 = x5, p2 = z5 } }; var v5 = u5; x5 = v5.p0.p1 ?? x5; x5 = v5.p0.p2; // 11 } void Test6(CL1 x6, CL1? z6) { var u6 = new { p0 = new { p1 = x6, p2 = z6 } }; var v6 = u6.p0; x6 = v6.p1 ?? x6; x6 = v6.p2; // 12 } void Test7(CL1 x7, CL1? z7) { var u7 = new { p0 = new S1() { p1 = x7, p2 = z7 } }; var v7 = new { p0 = new S1() { p1 = z7, p2 = x7 } }; u7 = v7; x7 = u7.p0.p2 ?? x7; x7 = u7.p0.p1; // 13 x7 = v7.p0.p2 ?? x7; // 14 x7 = v7.p0.p1; // 15 } void Test8(CL1 x8, CL1? z8) { var u8 = new { p0 = new S1() { p1 = x8, p2 = z8 } }; var v8 = u8; x8 = v8.p0.p1 ?? x8; x8 = v8.p0.p2; // 16 } void Test9(CL1 x9, CL1? z9) { var u9 = new { p0 = new S1() { p1 = x9, p2 = z9 } }; var v9 = u9.p0; x9 = v9.p1 ?? x9; x9 = v9.p2; // 17 } void M1<T>(ref T x) {} void Test10(CL1 x10) { var u10 = new { a0 = x10, a1 = new { p1 = x10 }, a2 = new S1() { p2 = x10 } }; x10 = u10.a0; x10 = u10.a1.p1; x10 = u10.a2.p2; M1(ref u10); x10 = u10.a0; x10 = u10.a1.p1; x10 = u10.a2.p2; // 18 } } class CL1 { } struct S1 { public CL1? p1; public CL1? p2; }" }, options: WithNullableEnable()); c.VerifyDiagnostics( // (11,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = y1.p2; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1.p2").WithLocation(11, 14), // (18,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: CL1? p1, CL1 p2>' doesn't match target type '<anonymous type: CL1 p1, CL1? p2>'. // u2 = v2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "v2").WithArguments("<anonymous type: CL1? p1, CL1 p2>", "<anonymous type: CL1 p1, CL1? p2>").WithLocation(18, 14), // (20,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = u2.p1; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u2.p1").WithLocation(20, 14), // (21,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = v2.p2 ?? x2; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v2.p2 ?? x2").WithLocation(21, 14), // (22,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = v2.p1; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v2.p1").WithLocation(22, 14), // (30,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = v3.p2; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v3.p2").WithLocation(30, 14), // (37,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: <anonymous type: CL1? p1, CL1 p2> p0>' doesn't match target type '<anonymous type: <anonymous type: CL1 p1, CL1? p2> p0>'. // u4 = v4; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "v4").WithArguments("<anonymous type: <anonymous type: CL1? p1, CL1 p2> p0>", "<anonymous type: <anonymous type: CL1 p1, CL1? p2> p0>").WithLocation(37, 14), // (39,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = u4.p0.p1; // 8 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u4.p0.p1").WithLocation(39, 14), // (40,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = v4.p0.p2 ?? x4; // 9 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v4.p0.p2 ?? x4").WithLocation(40, 14), // (41,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x4 = v4.p0.p1; // 10 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v4.p0.p1").WithLocation(41, 14), // (49,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x5 = v5.p0.p2; // 11 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v5.p0.p2").WithLocation(49, 14), // (57,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x6 = v6.p2; // 12 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v6.p2").WithLocation(57, 14), // (66,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x7 = u7.p0.p1; // 13 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u7.p0.p1").WithLocation(66, 14), // (67,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x7 = v7.p0.p2 ?? x7; // 14 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v7.p0.p2 ?? x7").WithLocation(67, 14), // (68,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x7 = v7.p0.p1; // 15 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v7.p0.p1").WithLocation(68, 14), // (76,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x8 = v8.p0.p2; // 16 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v8.p0.p2").WithLocation(76, 14), // (84,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x9 = v9.p2; // 17 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "v9.p2").WithLocation(84, 14), // (100,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // x10 = u10.a2.p2; // 18 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u10.a2.p2").WithLocation(100, 15)); } [Fact] public void AnonymousTypes_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL1? x1) { var y1 = new { p1 = x1 }; y1.p1?. M1(y1.p1); } void Test2(CL1? x2) { var y2 = new { p1 = x2 }; if (y2.p1 != null) { y2.p1.M1(y2.p1); } } void Test3(out CL1? x3, CL1 z3) { var y3 = new { p1 = x3 }; x3 = y3.p1 ?? z3.M1(y3.p1); CL1 v3 = y3.p1; } } class CL1 { public CL1? M1(CL1 x) { return null; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (25,29): error CS0269: Use of unassigned out parameter 'x3' // var y3 = new { p1 = x3 }; Diagnostic(ErrorCode.ERR_UseDefViolationOut, "x3").WithArguments("x3").WithLocation(25, 29), // (27,29): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1? CL1.M1(CL1 x)'. // z3.M1(y3.p1); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y3.p1").WithArguments("x", "CL1? CL1.M1(CL1 x)").WithLocation(27, 29)); } [Fact] public void AnonymousTypes_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test2(CL1 x2) { x2 = new {F1 = x2}.F1; } void Test3(CL1 x3) { x3 = new {F1 = x3}.F1 ?? x3; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void AnonymousTypes_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL1<string> x1, CL1<string?> y1) { var u1 = new { F1 = x1 }; var v1 = new { F1 = y1 }; u1 = v1; v1 = u1; } } class CL1<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: CL1<string?> F1>' doesn't match target type '<anonymous type: CL1<string> F1>'. // u1 = v1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "v1").WithArguments("<anonymous type: CL1<string?> F1>", "<anonymous type: CL1<string> F1>").WithLocation(12, 14), // (13,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: CL1<string> F1>' doesn't match target type '<anonymous type: CL1<string?> F1>'. // v1 = u1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "u1").WithArguments("<anonymous type: CL1<string> F1>", "<anonymous type: CL1<string?> F1>").WithLocation(13, 14) ); } [Fact] [WorkItem(29889, "https://github.com/dotnet/roslyn/issues/29889")] [WorkItem(33577, "https://github.com/dotnet/roslyn/issues/33577")] public void AnonymousTypes_05() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F0(string x0, string? y0) { var a0 = new { F = x0 }; var b0 = new { F = y0 }; a0 = b0; // 1 b0 = a0; // 2 } static void F1(I<string> x1, I<string?> y1) { var a1 = new { F = x1 }; var b1 = new { F = y1 }; a1 = b1; // 3 b1 = a1; // 4 } static void F2(IIn<string> x2, IIn<string?> y2) { var a2 = new { F = x2 }; var b2 = new { F = y2 }; a2 = b2; b2 = a2; // 5 } static void F3(IOut<string> x3, IOut<string?> y3) { var a3 = new { F = x3 }; var b3 = new { F = y3 }; a3 = b3; // 6 b3 = a3; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/33577: Should not report a warning for `a2 = b2` or `b3 = a3`. comp.VerifyDiagnostics( // (10,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: string? F>' doesn't match target type '<anonymous type: string F>'. // a0 = b0; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b0").WithArguments("<anonymous type: string? F>", "<anonymous type: string F>").WithLocation(10, 14), // (11,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: string F>' doesn't match target type '<anonymous type: string? F>'. // b0 = a0; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a0").WithArguments("<anonymous type: string F>", "<anonymous type: string? F>").WithLocation(11, 14), // (17,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: I<string?> F>' doesn't match target type '<anonymous type: I<string> F>'. // a1 = b1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b1").WithArguments("<anonymous type: I<string?> F>", "<anonymous type: I<string> F>").WithLocation(17, 14), // (18,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: I<string> F>' doesn't match target type '<anonymous type: I<string?> F>'. // b1 = a1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1").WithArguments("<anonymous type: I<string> F>", "<anonymous type: I<string?> F>").WithLocation(18, 14), // (24,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: IIn<string?> F>' doesn't match target type '<anonymous type: IIn<string> F>'. // a2 = b2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b2").WithArguments("<anonymous type: IIn<string?> F>", "<anonymous type: IIn<string> F>").WithLocation(24, 14), // (25,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: IIn<string> F>' doesn't match target type '<anonymous type: IIn<string?> F>'. // b2 = a2; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("<anonymous type: IIn<string> F>", "<anonymous type: IIn<string?> F>").WithLocation(25, 14), // (31,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: IOut<string?> F>' doesn't match target type '<anonymous type: IOut<string> F>'. // a3 = b3; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b3").WithArguments("<anonymous type: IOut<string?> F>", "<anonymous type: IOut<string> F>").WithLocation(31, 14), // (32,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: IOut<string> F>' doesn't match target type '<anonymous type: IOut<string?> F>'. // b3 = a3; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a3").WithArguments("<anonymous type: IOut<string> F>", "<anonymous type: IOut<string?> F>").WithLocation(32, 14)); } [Fact] [WorkItem(29890, "https://github.com/dotnet/roslyn/issues/29890")] public void AnonymousTypes_06() { var source = @"class C { static void F(string x, string y) { x = new { x, y }.x ?? x; y = new { x, y = y }.y ?? y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void AnonymousTypes_07() { var source = @"class Program { static T F<T>(T t) => t; static void G() { var a = new { }; a = new { }; a = F(a); a = F(new { }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] public void AnonymousTypes_08() { var source = @"class Program { static void F<T>(T x, T? y) where T : class { new { x, y }.x.ToString(); new { x, y }.y.ToString(); // 1 new { y, x }.x.ToString(); new { y, x }.y.ToString(); // 2 new { x = x, y = y }.x.ToString(); new { x = x, y = y }.y.ToString(); // 3 new { x = y, y = x }.x.ToString(); // 4 new { x = y, y = x }.y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // new { x, y }.y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new { x, y }.y").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // new { y, x }.y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new { y, x }.y").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // new { x = x, y = y }.y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new { x = x, y = y }.y").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // new { x = y, y = x }.x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new { x = y, y = x }.x").WithLocation(11, 9)); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] public void AnonymousTypes_09() { var source = @"class Program { static void F<T>(T? x, T? y) where T : struct { if (y == null) return; _ = new { x = x, y = y }.x.Value; // 1 _ = new { x = x, y = y }.y.Value; _ = new { x = y, y = x }.x.Value; _ = new { x = y, y = x }.y.Value; // 2 _ = new { x, y }.x.Value; // 3 _ = new { x, y }.y.Value; _ = new { y, x }.x.Value; // 4 _ = new { y, x }.y.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8629: Nullable value type may be null. // _ = new { x = x, y = y }.x.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new { x = x, y = y }.x").WithLocation(6, 13), // (9,13): warning CS8629: Nullable value type may be null. // _ = new { x = y, y = x }.y.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new { x = y, y = x }.y").WithLocation(9, 13), // (10,13): warning CS8629: Nullable value type may be null. // _ = new { x, y }.x.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new { x, y }.x").WithLocation(10, 13), // (12,13): warning CS8629: Nullable value type may be null. // _ = new { y, x }.x.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new { y, x }.x").WithLocation(12, 13)); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] public void AnonymousTypes_10() { var source = @"class Program { static void F<T>(T x, T? y) where T : class { var a = new { x, y }; a.x/*T:T!*/.ToString(); a.y/*T:T?*/.ToString(); // 1 a = new { x = y, y = x }; // 2 a.x/*T:T?*/.ToString(); // 3 a.y/*T:T!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // a.y/*T:T?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.y").WithLocation(7, 9), // (8,13): warning CS8619: Nullability of reference types in value of type '<anonymous type: T? x, T y>' doesn't match target type '<anonymous type: T x, T? y>'. // a = new { x = y, y = x }; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new { x = y, y = x }").WithArguments("<anonymous type: T? x, T y>", "<anonymous type: T x, T? y>").WithLocation(8, 13), // (9,9): warning CS8602: Dereference of a possibly null reference. // a.x/*T:T?*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.x").WithLocation(9, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] [WorkItem(33577, "https://github.com/dotnet/roslyn/issues/33577")] public void AnonymousTypes_11() { var source = @"class Program { static void F<T>() where T : struct { T? x = new T(); T? y = null; var a = new { x, y }; _ = a.x.Value; _ = a.y.Value; // 1 x = null; y = new T(); a = new { x, y }; _ = a.x.Value; // 2 _ = a.y.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8629: Nullable value type may be null. // _ = a.y.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "a.y").WithLocation(9, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = a.x.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "a.x").WithLocation(13, 13)); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] public void AnonymousTypes_12() { var source = @"class Program { static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var a = new { x, y }; a.x/*T:T?*/.ToString(); // 2 a.y/*T:T!*/.ToString(); x = new T(); y = null; a = new { x, y }; // 3 a.x/*T:T!*/.ToString(); a.y/*T:T?*/.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 15), // (8,9): warning CS8602: Dereference of a possibly null reference. // a.x/*T:T?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.x").WithLocation(8, 9), // (12,13): warning CS8619: Nullability of reference types in value of type '<anonymous type: T x, T? y>' doesn't match target type '<anonymous type: T? x, T y>'. // a = new { x, y }; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new { x, y }").WithArguments("<anonymous type: T x, T? y>", "<anonymous type: T? x, T y>").WithLocation(12, 13), // (14,9): warning CS8602: Dereference of a possibly null reference. // a.y/*T:T?*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.y").WithLocation(14, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] public void AnonymousTypes_13() { var source = @"class Program { static void F<T>(T x, T y) { } static void G<T>(T x, T? y) where T : class { F(new { x, y }, new { x = x, y = y }); F(new { x, y }, new { x = y, y = x }); // 1 F(new { x = x, y = y }, new { x = x, y = y }); F(new { x = x, y = y }, new { x = y, y = x }); // 2 F(new { x = x, y = y }, new { x, y }); F(new { x = y, y = x }, new { x, y }); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,25): warning CS8620: Argument of type '<anonymous type: T? x, T y>' cannot be used for parameter 'y' of type '<anonymous type: T x, T? y>' in 'void Program.F<<anonymous type: T x, T? y>>(<anonymous type: T x, T? y> x, <anonymous type: T x, T? y> y)' due to differences in the nullability of reference types. // F(new { x, y }, new { x = y, y = x }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new { x = y, y = x }").WithArguments("<anonymous type: T? x, T y>", "<anonymous type: T x, T? y>", "y", "void Program.F<<anonymous type: T x, T? y>>(<anonymous type: T x, T? y> x, <anonymous type: T x, T? y> y)").WithLocation(9, 25), // (11,33): warning CS8620: Argument of type '<anonymous type: T? x, T y>' cannot be used for parameter 'y' of type '<anonymous type: T x, T? y>' in 'void Program.F<<anonymous type: T x, T? y>>(<anonymous type: T x, T? y> x, <anonymous type: T x, T? y> y)' due to differences in the nullability of reference types. // F(new { x = x, y = y }, new { x = y, y = x }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new { x = y, y = x }").WithArguments("<anonymous type: T? x, T y>", "<anonymous type: T x, T? y>", "y", "void Program.F<<anonymous type: T x, T? y>>(<anonymous type: T x, T? y> x, <anonymous type: T x, T? y> y)").WithLocation(11, 33), // (13,33): warning CS8620: Argument of type '<anonymous type: T x, T? y>' cannot be used for parameter 'y' of type '<anonymous type: T? x, T y>' in 'void Program.F<<anonymous type: T? x, T y>>(<anonymous type: T? x, T y> x, <anonymous type: T? x, T y> y)' due to differences in the nullability of reference types. // F(new { x = y, y = x }, new { x, y }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "new { x, y }").WithArguments("<anonymous type: T x, T? y>", "<anonymous type: T? x, T y>", "y", "void Program.F<<anonymous type: T? x, T y>>(<anonymous type: T? x, T y> x, <anonymous type: T? x, T y> y)").WithLocation(13, 33)); } [Fact] [WorkItem(33007, "https://github.com/dotnet/roslyn/issues/33007")] public void AnonymousTypes_14() { var source = @"class Program { static T F<T>(T t) => t; static void F1<T>(T t1) where T : class { var a1 = F(new { t = t1 }); a1.t.ToString(); } static void F2<T>(T? t2) where T : class { var a2 = F(new { t = t2 }); a2.t.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // a2.t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2.t").WithLocation(12, 9)); } [Fact] [WorkItem(33007, "https://github.com/dotnet/roslyn/issues/33007")] public void AnonymousTypes_15() { var source = @"using System; class Program { static U F<T, U>(Func<T, U> f, T t) => f(t); static void F1<T>(T t1) where T : class { var a1 = F(t => new { t }, t1); a1.t.ToString(); } static void F2<T>(T? t2) where T : class { var a2 = F(t => new { t }, t2); a2.t.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // a2.t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2.t").WithLocation(13, 9)); } [Fact] [WorkItem(24018, "https://github.com/dotnet/roslyn/issues/24018")] public void AnonymousTypes_16() { var source = @"class Program { static void F<T>(T? t) where T : class { new { }.Missing(); if (t == null) return; new { t }.Missing(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,17): error CS1061: '<empty anonymous type>' does not contain a definition for 'Missing' and no accessible extension method 'Missing' accepting a first argument of type '<empty anonymous type>' could be found (are you missing a using directive or an assembly reference?) // new { }.Missing(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Missing").WithArguments("<empty anonymous type>", "Missing").WithLocation(5, 17), // (7,19): error CS1061: '<anonymous type: T t>' does not contain a definition for 'Missing' and no accessible extension method 'Missing' accepting a first argument of type '<anonymous type: T t>' could be found (are you missing a using directive or an assembly reference?) // new { t }.Missing(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Missing").WithArguments("<anonymous type: T t>", "Missing").WithLocation(7, 19)); } [Fact] [WorkItem(35044, "https://github.com/dotnet/roslyn/issues/35044")] public void AnonymousTypes_17() { var source = @" class Program { static void M(object o1, object? o2) { new { O1/*T:object!*/ = o1, O1/*T:object?*/ = o2 }.O1.ToString();; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,37): error CS0833: An anonymous type cannot have multiple properties with the same name // new { O1/*T:object!*/ = o1, O1/*T:object?*/ = o2 }.O1.ToString();; Diagnostic(ErrorCode.ERR_AnonymousTypeDuplicatePropertyName, "O1/*T:object?*/ = o2").WithLocation(6, 37)); comp.VerifyTypes(); } [Fact] public void AnonymousObjectCreation_01() { var source = @"class C { static void F(object? o) { (new { P = o }).P.ToString(); if (o == null) return; (new { Q = o }).Q.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // (new { P = o }).P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new { P = o }).P").WithLocation(5, 9)); } [Fact] [WorkItem(29891, "https://github.com/dotnet/roslyn/issues/29891")] public void AnonymousObjectCreation_02() { var source = @"class C { static void F(object? o) { (new { P = new[] { o }}).P[0].ToString(); if (o == null) return; (new { Q = new[] { o }}).Q[0].ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // (new { P = new[] { o }}).P[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(new { P = new[] { o }}).P[0]").WithLocation(5, 9)); } [Fact] public void This() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1() { this.Test2(); } void Test2() { this?.Test1(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void ReadonlyAutoProperties_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C1 { static void Main() { } C1 P1 {get;} public C1(C1? x1) // 1 { P1 = x1; // 2 } } class C2 { C2? P2 {get;} public C2(C2 x2) { x2 = P2; // 3 } } class C3 { C3? P3 {get;} public C3(C3 x3, C3? y3) { P3 = y3; x3 = P3; // 4 } } class C4 { C4? P4 {get;} public C4(C4 x4) { P4 = x4; x4 = P4; } } class C5 { S1 P5 {get;} public C5(C0 x5) { P5 = new S1() { F1 = x5 }; x5 = P5.F1; } } class C0 {} struct S1 { public C0? F1; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,14): warning CS8601: Possible null reference assignment. // P1 = x1; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x1").WithLocation(12, 14), // (10,12): warning CS8618: Non-nullable property 'P1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C1(C1? x1) // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C1").WithArguments("property", "P1").WithLocation(10, 12), // (22,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = P2; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P2").WithLocation(22, 14), // (33,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = P3; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P3").WithLocation(33, 14) ); } [Fact] public void ReadonlyAutoProperties_02() { CSharpCompilation c = CreateCompilation(new[] { @" struct C1 { static void Main() { } C0 P1 {get;} public C1(C0? x1) // 1 { P1 = x1; // 2 } } struct C2 { C0? P2 {get;} public C2(C0 x2) { x2 = P2; // 3, 4 P2 = null; } } struct C3 { C0? P3 {get;} public C3(C0 x3, C0? y3) { P3 = y3; x3 = P3; // 5 } } struct C4 { C0? P4 {get;} public C4(C0 x4) { P4 = x4; x4 = P4; } } struct C5 { S1 P5 {get;} public C5(C0 x5) { P5 = new S1() { F1 = x5 }; x5 = P5.F1 ?? x5; } } class C0 {} struct S1 { public C0? F1; } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,14): warning CS8601: Possible null reference assignment. // P1 = x1; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x1").WithLocation(12, 14), // (10,12): warning CS8618: Non-nullable property 'P1' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C1(C0? x1) // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C1").WithArguments("property", "P1").WithLocation(10, 12), // (34,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = P3; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P3").WithLocation(34, 14), // (22,14): error CS8079: Use of possibly unassigned auto-implemented property 'P2' // x2 = P2; // 3, 4 Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "P2").WithArguments("P2").WithLocation(22, 14), // (22,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = P2; // 3, 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P2").WithLocation(22, 14) ); } [Fact] public void NotAssigned() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(object? x1) { CL1? y1; if (x1 == null) { y1 = null; return; } CL1 z1 = y1; } void Test2(object? x2, out CL1? y2) { if (x2 == null) { y2 = null; return; } CL1 z2 = y2; y2 = null; } } class CL1 { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (17,18): error CS0165: Use of unassigned local variable 'y1' // CL1 z1 = y1; Diagnostic(ErrorCode.ERR_UseDefViolation, "y1").WithArguments("y1").WithLocation(17, 18), // (17,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(17, 18), // (28,18): error CS0269: Use of unassigned out parameter 'y2' // CL1 z2 = y2; Diagnostic(ErrorCode.ERR_UseDefViolationOut, "y2").WithArguments("y2").WithLocation(28, 18), // (28,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2").WithLocation(28, 18)); } [Fact] public void Lambda_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Func<CL1?> x1 = () => M1(); } void Test2() { System.Func<CL1?> x2 = delegate { return M1(); }; } delegate CL1? D1(); void Test3() { D1 x3 = () => M1(); } void Test4() { D1 x4 = delegate { return M1(); }; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Lambda_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Action<CL1?> x1 = (p1) => p1 = M1(); } delegate void D1(CL1? p); void Test3() { D1 x3 = (p3) => p3 = M1(); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Lambda_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Func<CL1> x1 = () => M1(); } void Test2() { System.Func<CL1> x2 = delegate { return M1(); }; } delegate CL1 D1(); void Test3() { D1 x3 = () => M1(); } void Test4() { D1 x4 = delegate { return M1(); }; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,37): warning CS8603: Possible null reference return. // System.Func<CL1> x1 = () => M1(); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(12, 37), // (17,49): warning CS8603: Possible null reference return. // System.Func<CL1> x2 = delegate { return M1(); }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(17, 49), // (24,23): warning CS8603: Possible null reference return. // D1 x3 = () => M1(); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(24, 23), // (29,35): warning CS8603: Possible null reference return. // D1 x4 = delegate { return M1(); }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(29, 35) ); } [Fact] public void Lambda_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Action<CL1> x1 = (p1) => p1 = M1(); } delegate void D1(CL1 p); void Test3() { D1 x3 = (p3) => p3 = M1(); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action<CL1> x1 = (p1) => p1 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(12, 46), // (19,30): warning CS8600: Converting null literal or possible null value to non-nullable type. // D1 x3 = (p3) => p3 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(19, 30) ); } [Fact] public void Lambda_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } delegate CL1 D1(); delegate CL1? D2(); void M2(int x, D1 y) {} void M2(long x, D2 y) {} void M3(long x, D2 y) {} void M3(int x, D1 y) {} void Test1(int x1) { M2(x1, () => M1()); } void Test2(int x2) { M3(x2, () => M1()); } void Test3(int x3) { M2(x3, delegate { return M1(); }); } void Test4(int x4) { M3(x4, delegate { return M1(); }); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (20,22): warning CS8603: Possible null reference return. // M2(x1, () => M1()); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(20, 22), // (25,22): warning CS8603: Possible null reference return. // M3(x2, () => M1()); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(25, 22), // (30,34): warning CS8603: Possible null reference return. // M2(x3, delegate { return M1(); }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(30, 34), // (35,34): warning CS8603: Possible null reference return. // M3(x4, delegate { return M1(); }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(35, 34) ); } [Fact] public void Lambda_06() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } delegate CL1 D1(); delegate CL1? D2(); void M2(int x, D2 y) {} void M2(long x, D1 y) {} void M3(long x, D1 y) {} void M3(int x, D2 y) {} void Test1(int x1) { M2(x1, () => M1()); } void Test2(int x2) { M3(x2, () => M1()); } void Test3(int x3) { M2(x3, delegate { return M1(); }); } void Test4(int x4) { M3(x4, delegate { return M1(); }); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Lambda_07() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } delegate T D<T>(); void M2(int x, D<CL1> y) {} void M2<T>(int x, D<T> y) {} void M3<T>(int x, D<T> y) {} void M3(int x, D<CL1> y) {} void Test1(int x1) { M2(x1, () => M1()); } void Test2(int x2) { M3(x2, () => M1()); } void Test3(int x3) { M2(x3, delegate { return M1(); }); } void Test4(int x4) { M3(x4, delegate { return M1(); }); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (19,22): warning CS8603: Possible null reference return. // M2(x1, () => M1()); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(19, 22), // (24,22): warning CS8603: Possible null reference return. // M3(x2, () => M1()); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(24, 22), // (29,34): warning CS8603: Possible null reference return. // M2(x3, delegate { return M1(); }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(29, 34), // (34,34): warning CS8603: Possible null reference return. // M3(x4, delegate { return M1(); }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "M1()").WithLocation(34, 34) ); } [Fact] public void Lambda_08() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } delegate T D<T>(); void M2(int x, D<CL1?> y) {} void M2<T>(int x, D<T> y) {} void M3<T>(int x, D<T> y) {} void M3(int x, D<CL1?> y) {} void Test1(int x1) { M2(x1, () => M1()); } void Test2(int x2) { M3(x2, () => M1()); } void Test3(int x3) { M2(x3, delegate { return M1(); }); } void Test4(int x4) { M3(x4, delegate { return M1(); }); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Lambda_09() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } delegate T1 D<T1, T2>(T2 y); void M2(int x, D<CL1, CL1> y) {} void M2<T>(int x, D<T, CL1> y) {} void M3<T>(int x, D<T, CL1> y) {} void M3(int x, D<CL1, CL1> y) {} void Test1(int x1) { M2(x1, (y1) => { y1 = M1(); return y1; }); } void Test2(int x2) { M3(x2, (y2) => { y2 = M1(); return y2; }); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (21,26): warning CS8600: Converting null literal or possible null value to non-nullable type. // y1 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(21, 26), // (22,28): warning CS8603: Possible null reference return. // return y1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y1").WithLocation(22, 28), // (30,26): warning CS8600: Converting null literal or possible null value to non-nullable type. // y2 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(30, 26), // (31,28): warning CS8603: Possible null reference return. // return y2; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y2").WithLocation(31, 28) ); } [Fact] public void Lambda_10() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } delegate T1 D<T1, T2>(T2 y); void M2(int x, D<CL1, CL1?> y) {} void M2<T>(int x, D<T, CL1> y) {} void M3<T>(int x, D<T, CL1> y) {} void M3(int x, D<CL1, CL1?> y) {} void Test1(int x1) { M2(x1, (y1) => { y1 = M1(); return y1; }); } void Test2(int x2) { M3(x2, (y2) => { y2 = M1(); return y2; }); } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (22,28): warning CS8603: Possible null reference return. // return y1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y1").WithLocation(22, 28), // (31,28): warning CS8603: Possible null reference return. // return y2; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y2").WithLocation(31, 28) ); } [Fact] public void Lambda_11() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Action<CL1> x1 = (CL1 p1) => p1 = M1(); } void Test2() { System.Action<CL1> x2 = delegate (CL1 p2) { p2 = M1(); }; } delegate void D1(CL1 p); void Test3() { D1 x3 = (CL1 p3) => p3 = M1(); } void Test4() { D1 x4 = delegate (CL1 p4) { p4 = M1(); }; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action<CL1> x1 = (CL1 p1) => p1 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(12, 50), // (17,58): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action<CL1> x2 = delegate (CL1 p2) { p2 = M1(); }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(17, 58), // (24,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // D1 x3 = (CL1 p3) => p3 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(24, 34), // (29,42): warning CS8600: Converting null literal or possible null value to non-nullable type. // D1 x4 = delegate (CL1 p4) { p4 = M1(); }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(29, 42) ); } [Fact] public void Lambda_12() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Action<CL1?> x1 = (CL1 p1) => p1 = M1(); } void Test2() { System.Action<CL1?> x2 = delegate (CL1 p2) { p2 = M1(); }; } delegate void D1(CL1? p); void Test3() { D1 x3 = (CL1 p3) => p3 = M1(); } void Test4() { D1 x4 = delegate (CL1 p4) { p4 = M1(); }; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action<CL1?> x1 = (CL1 p1) => p1 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(12, 51), // (12,34): warning CS8622: Nullability of reference types in type of parameter 'p1' of 'lambda expression' doesn't match the target delegate 'Action<CL1?>'. // System.Action<CL1?> x1 = (CL1 p1) => p1 = M1(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1 p1) => p1 = M1()").WithArguments("p1", "lambda expression", "System.Action<CL1?>").WithLocation(12, 34), // (17,59): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action<CL1?> x2 = delegate (CL1 p2) { p2 = M1(); }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(17, 59), // (17,34): warning CS8622: Nullability of reference types in type of parameter 'p2' of 'anonymous method' doesn't match the target delegate 'Action<CL1?>'. // System.Action<CL1?> x2 = delegate (CL1 p2) { p2 = M1(); }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "delegate (CL1 p2) { p2 = M1(); }").WithArguments("p2", "anonymous method", "System.Action<CL1?>").WithLocation(17, 34), // (24,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // D1 x3 = (CL1 p3) => p3 = M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(24, 34), // (24,17): warning CS8622: Nullability of reference types in type of parameter 'p3' of 'lambda expression' doesn't match the target delegate 'C.D1'. // D1 x3 = (CL1 p3) => p3 = M1(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1 p3) => p3 = M1()").WithArguments("p3", "lambda expression", "C.D1").WithLocation(24, 17), // (29,42): warning CS8600: Converting null literal or possible null value to non-nullable type. // D1 x4 = delegate (CL1 p4) { p4 = M1(); }; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M1()").WithLocation(29, 42), // (29,17): warning CS8622: Nullability of reference types in type of parameter 'p4' of 'anonymous method' doesn't match the target delegate 'C.D1'. // D1 x4 = delegate (CL1 p4) { p4 = M1(); }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "delegate (CL1 p4) { p4 = M1(); }").WithArguments("p4", "anonymous method", "C.D1").WithLocation(29, 17) ); } [Fact] public void Lambda_13() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Action<CL1> x1 = (CL1? p1) => p1 = M1(); } void Test2() { System.Action<CL1> x2 = delegate (CL1? p2) { p2 = M1(); }; } delegate void D1(CL1 p); void Test3() { D1 x3 = (CL1? p3) => p3 = M1(); } void Test4() { D1 x4 = delegate (CL1? p4) { p4 = M1(); }; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,33): warning CS8622: Nullability of reference types in type of parameter 'p1' of 'lambda expression' doesn't match the target delegate 'Action<CL1>'. // System.Action<CL1> x1 = (CL1? p1) => p1 = M1(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1? p1) => p1 = M1()").WithArguments("p1", "lambda expression", "System.Action<CL1>").WithLocation(12, 33), // (17,33): warning CS8622: Nullability of reference types in type of parameter 'p2' of 'anonymous method' doesn't match the target delegate 'Action<CL1>'. // System.Action<CL1> x2 = delegate (CL1? p2) { p2 = M1(); }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "delegate (CL1? p2) { p2 = M1(); }").WithArguments("p2", "anonymous method", "System.Action<CL1>").WithLocation(17, 33), // (24,17): warning CS8622: Nullability of reference types in type of parameter 'p3' of 'lambda expression' doesn't match the target delegate 'C.D1'. // D1 x3 = (CL1? p3) => p3 = M1(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1? p3) => p3 = M1()").WithArguments("p3", "lambda expression", "C.D1").WithLocation(24, 17), // (29,17): warning CS8622: Nullability of reference types in type of parameter 'p4' of 'anonymous method' doesn't match the target delegate 'C.D1'. // D1 x4 = delegate (CL1? p4) { p4 = M1(); }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "delegate (CL1? p4) { p4 = M1(); }").WithArguments("p4", "anonymous method", "C.D1").WithLocation(29, 17) ); } [Fact] public void Lambda_14() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL1? M1() { return null; } void Test1() { System.Action<CL1?> x1 = (CL1? p1) => p1 = M1(); } void Test2() { System.Action<CL1?> x2 = delegate (CL1? p2) { p2 = M1(); }; } delegate void D1(CL1? p); void Test3() { D1 x3 = (CL1? p3) => p3 = M1(); } void Test4() { D1 x4 = delegate (CL1? p4) { p4 = M1(); }; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Lambda_15() { CSharpCompilation notAnnotated = CreateCompilation(@" public class CL0 { public static void M1(System.Func<CL1<CL0>, CL0> x) {} } public class CL1<T> { public T F1; public CL1() { F1 = default(T); } } ", options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} static void Test1() { CL0.M1(p1 => { p1.F1 = null; p1 = null; return null; }); } static void Test2() { System.Func<CL1<CL0>, CL0> l2 = p2 => { p2.F1 = null; // 1 p2 = null; // 2 return null; // 3 }; } } " }, options: WithNullableEnable(), references: new[] { notAnnotated.EmitToImageReference() }); c.VerifyDiagnostics( // (20,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // p2.F1 = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 29), // (21,26): warning CS8600: Converting null literal or possible null value to non-nullable type. // p2 = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(21, 26), // (22,28): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(22, 28) ); } [Fact] public void Lambda_16() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1() { System.Action<CL1<string?>> x1 = (CL1<string> p1) => System.Console.WriteLine(); } void Test2() { System.Action<CL1<string>> x2 = (CL1<string?> p2) => System.Console.WriteLine(); } } class CL1<T> {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,42): warning CS8622: Nullability of reference types in type of parameter 'p1' of 'lambda expression' doesn't match the target delegate 'Action<CL1<string?>>'. // System.Action<CL1<string?>> x1 = (CL1<string> p1) => System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1<string> p1) => System.Console.WriteLine()").WithArguments("p1", "lambda expression", "System.Action<CL1<string?>>").WithLocation(10, 42), // (15,41): warning CS8622: Nullability of reference types in type of parameter 'p2' of 'lambda expression' doesn't match the target delegate 'Action<CL1<string>>'. // System.Action<CL1<string>> x2 = (CL1<string?> p2) => System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1<string?> p2) => System.Console.WriteLine()").WithArguments("p2", "lambda expression", "System.Action<CL1<string>>").WithLocation(15, 41) ); } [Fact] public void Lambda_17() { CSharpCompilation c = CreateCompilation(new[] { @" using System.Linq.Expressions; class C { static void Main() { } void Test1() { Expression<System.Action<CL1<string?>>> x1 = (CL1<string> p1) => System.Console.WriteLine(); } void Test2() { Expression<System.Action<CL1<string>>> x2 = (CL1<string?> p2) => System.Console.WriteLine(); } } class CL1<T> {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,54): warning CS8622: Nullability of reference types in type of parameter 'p1' of 'lambda expression' doesn't match the target delegate 'Action<CL1<string?>>'. // Expression<System.Action<CL1<string?>>> x1 = (CL1<string> p1) => System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1<string> p1) => System.Console.WriteLine()").WithArguments("p1", "lambda expression", "System.Action<CL1<string?>>").WithLocation(12, 54), // (17,53): warning CS8622: Nullability of reference types in type of parameter 'p2' of 'lambda expression' doesn't match the target delegate 'Action<CL1<string>>'. // Expression<System.Action<CL1<string>>> x2 = (CL1<string?> p2) => System.Console.WriteLine(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(CL1<string?> p2) => System.Console.WriteLine()").WithArguments("p2", "lambda expression", "System.Action<CL1<string>>").WithLocation(17, 53) ); } [Fact] public void Lambda_18() { var source = @"delegate T D<T>(T t) where T : class; class C { static void F() { var d1 = (D<string?>)((string s1) => { s1 = null; return s1; }); var d2 = (D<string>)((string? s2) => { s2.ToString(); return s2; }); // suppressed var d3 = (D<string?>)((string s1) => { s1 = null; return s1; }!); var d4 = (D<string>)((string? s2) => { s2.ToString(); return s2; }!); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): warning CS8622: Nullability of reference types in type of parameter 's1' of 'lambda expression' doesn't match the target delegate 'D<string?>'. // var d1 = (D<string?>)((string s1) => { s1 = null; return s1; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(D<string?>)((string s1) => { s1 = null; return s1; })").WithArguments("s1", "lambda expression", "D<string?>").WithLocation(6, 18), // (6,21): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'D<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var d1 = (D<string?>)((string s1) => { s1 = null; return s1; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("D<T>", "T", "string?").WithLocation(6, 21), // (6,53): warning CS8600: Converting null literal or possible null value to non-nullable type. // var d1 = (D<string?>)((string s1) => { s1 = null; return s1; }); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 53), // (7,18): warning CS8622: Nullability of reference types in type of parameter 's2' of 'lambda expression' doesn't match the target delegate 'D<string>'. // var d2 = (D<string>)((string? s2) => { s2.ToString(); return s2; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(D<string>)((string? s2) => { s2.ToString(); return s2; })").WithArguments("s2", "lambda expression", "D<string>").WithLocation(7, 18), // (7,48): warning CS8602: Dereference of a possibly null reference. // var d2 = (D<string>)((string? s2) => { s2.ToString(); return s2; }); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(7, 48), // (10,21): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'D<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // var d3 = (D<string?>)((string s1) => { s1 = null; return s1; }!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("D<T>", "T", "string?").WithLocation(10, 21), // (10,53): warning CS8600: Converting null literal or possible null value to non-nullable type. // var d3 = (D<string?>)((string s1) => { s1 = null; return s1; }!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(10, 53), // (11,48): warning CS8602: Dereference of a possibly null reference. // var d4 = (D<string>)((string? s2) => { s2.ToString(); return s2; }!); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(11, 48) ); } /// <summary> /// To track nullability of captured variables inside and outside a lambda, /// the lambda should be considered executed at the location the lambda /// is converted to a delegate. /// </summary> [Fact] [WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void Lambda_19() { var source = @"using System; class C { static void F1(object? x1, object y1) { object z1 = y1; Action f = () => { z1 = x1; // warning }; f(); z1.ToString(); } static void F2(object? x2, object y2) { object z2 = x2; // warning Action f = () => { z2 = y2; }; f(); z2.ToString(); // warning } static void F3(object? x3, object y3) { object z3 = y3; if (x3 == null) return; Action f = () => { z3 = x3; }; f(); z3.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z1 = x1; // warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(9, 18), // (16,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object z2 = x2; // warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(16, 21), // (22,9): warning CS8602: Dereference of a possibly null reference. // z2.ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2").WithLocation(22, 9)); } [Fact] public void Lambda_20() { var source = @"#nullable enable #pragma warning disable 649 using System; class Program { static Action? F; static Action M(Action a) { if (F == null) return a; return () => F(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [ConditionalFact(typeof(IsRelease))] [WorkItem(48174, "https://github.com/dotnet/roslyn/issues/48174")] public void Lambda_Nesting_Large_01() { const int depth = 30; var builder = new StringBuilder(); for (int i = 1; i < depth; i++) { builder.AppendLine($" M0(c{i} =>"); } builder.Append($" M0(c{depth} => {{ }}"); for (int i = 0; i < depth; i++) { builder.Append(")"); } builder.Append(";"); var source = @" using System; class C { void M0(Action<C> action) { } void M1() { " + builder.ToString() + @" } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void Lambda_21() { var comp = CreateCompilation(@" class C { static void M() { string? s = null; C c = new C(() => s.ToString()); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,19): error CS1729: 'C' does not contain a constructor that takes 1 arguments // C c = new C(() => s.ToString()); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "C").WithArguments("C", "1").WithLocation(7, 19), // (7,27): warning CS8602: Dereference of a possibly null reference. // C c = new C(() => s.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 27) ); } [Fact, WorkItem(51461, "https://github.com/dotnet/roslyn/issues/51461")] public void Lambda_22() { var comp = CreateCompilation(@" class C { static void M() { string? s = null; M(() => s.ToString()); } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): error CS1501: No overload for method 'M' takes 1 arguments // M(() => s.ToString()); Diagnostic(ErrorCode.ERR_BadArgCount, "M").WithArguments("M", "1").WithLocation(7, 9), // (7,17): warning CS8602: Dereference of a possibly null reference. // M(() => s.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 17) ); } [ConditionalFact(typeof(IsRelease))] [WorkItem(48174, "https://github.com/dotnet/roslyn/issues/48174")] public void Lambda_Nesting_Large_02() { const int depth = 30; var builder = new StringBuilder(); for (int i = 0; i < depth; i++) { builder.AppendLine($" Action<C> a{i} = c{i} => {{"); } for (int i = 0; i < depth; i++) { builder.AppendLine(" };"); } var source = @" using System; class C { void M1() { " + builder.ToString() + @" } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [ConditionalFact(typeof(IsRelease))] [WorkItem(48174, "https://github.com/dotnet/roslyn/issues/48174")] public void Lambda_Nesting_Large_03() { var source = #region large source @"using System; namespace nullable_repro { public class Recursive { public void Method(Action<Recursive> next) { } public void Initial(Recursive recurse) { recurse.Method(((recurse2) => { recurse2.Method(((recurse3) => { recurse3.Method(((recurse4) => { recurse4.Method(((recurse5) => { recurse5.Method(((recurse6) => { recurse6.Method(((recurse7) => { recurse7.Method(((recurse8) => { recurse8.Method(((recurse9) => { recurse9.Method(((recurse10) => { recurse10.Method(((recurse11) => { recurse11.Method(((recurse12) => { recurse12.Method(((recurse13) => { recurse13.Method(((recurse14) => { recurse14.Method(((recurse15) => { recurse15.Method(((recurse16) => { recurse16.Method(((recurse17) => { recurse17.Method(((recurse18) => { recurse18.Method(((recurse19) => { recurse19.Method(((recurse20) => { recurse20.Method(((recurse21) => { } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } )); } } }"; #endregion var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [ConditionalFact(typeof(IsRelease))] [WorkItem(48174, "https://github.com/dotnet/roslyn/issues/48174")] public void Lambda_Nesting_ErrorType() { var source = @" public class Program { public static void M(string? x) { ERROR error1 = () => // 1 { ERROR(() => { x.ToString(); // 2 }); x.ToString(); // 3 }; x.ToString(); // 4 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (6,9): error CS0246: The type or namespace name 'ERROR' could not be found (are you missing a using directive or an assembly reference?) // ERROR error1 = () => // 1 Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ERROR").WithArguments("ERROR").WithLocation(6, 9), // (10,17): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 17), // (12,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 13), // (14,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 9) ); } [Fact] public void LambdaReturnValue_01() { var source = @"using System; class C { static void F(Func<object> f) { } static void G(string x, object? y) { F(() => { if ((object)x == y) return x; return y; }); F(() => { if (y == null) return x; return y; }); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,56): warning CS8603: Possible null reference return. // F(() => { if ((object)x == y) return x; return y; }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y").WithLocation(9, 56)); } [Fact] public void LambdaReturnValue_02() { var source = @"using System; class C { static void F(Func<object> f) { } static void G(bool b, object x, string? y) { F(() => { if (b) return x; return y; }); F(() => { if (b) return y; return x; }); } static void H(bool b, object? x, string y) { F(() => { if (b) return x; return y; }); F(() => { if (b) return y; return x; }); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,43): warning CS8603: Possible null reference return. // F(() => { if (b) return x; return y; }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y").WithLocation(9, 43), // (10,33): warning CS8603: Possible null reference return. // F(() => { if (b) return y; return x; }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y").WithLocation(10, 33), // (14,33): warning CS8603: Possible null reference return. // F(() => { if (b) return x; return y; }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x").WithLocation(14, 33), // (15,43): warning CS8603: Possible null reference return. // F(() => { if (b) return y; return x; }); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x").WithLocation(15, 43)); } [Fact] public void LambdaReturnValue_03() { var source = @"using System; class C { static T F<T>(Func<T> f) { throw null!; } static void G(bool b, object x, string? y) { F(() => { if (b) return x; return y; }).ToString(); } static void H(bool b, object? x, string y) { F(() => { if (b) return x; return y; }).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(() => { if (b) return x; return y; }).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => { if (b) return x; return y; })").WithLocation(10, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F(() => { if (b) return x; return y; }).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => { if (b) return x; return y; })").WithLocation(14, 9)); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void LambdaReturnValue_04() { var source = @"using System; class C { static T F<T>(Func<T> f) { throw null!; } static void G(object? o) { F(() => o).ToString(); // 1 if (o != null) F(() => o).ToString(); F(() => { return o; }).ToString(); // 2 if (o != null) F(() => { return o; }).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(() => o).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => o)").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F(() => { return o; }).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => { return o; })").WithLocation(12, 9)); } [Fact] public void LambdaReturnValue_05() { var source = @"using System; class C { static T F<T>(Func<object?, T> f) { throw null!; } static void G() { F(o => o).ToString(); // 1 F(o => { if (o == null) throw new ArgumentException(); return o; }).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(o => o).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(o => o)").WithLocation(10, 9) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void LambdaReturnValue_05_WithSuppression() { var source = @"using System; class C { static T F<T>(Func<object?, T> f) { throw null!; } static void G() { F(o => { if (o == null) throw new ArgumentException(); return o; }!).ToString(); } }"; // covers suppression case in InferReturnType var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void LambdaReturnValue_06() { var source = @"using System; class C { static U F<T, U>(Func<T, U> f, T t) { return f(t); } static void M(object? x) { F(y => F(z => z, y), x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(y => F(z => z, y), x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y => F(z => z, y), x)").WithLocation(10, 9)); } [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] [WorkItem(30480, "https://github.com/dotnet/roslyn/issues/30480")] [Fact] public void LambdaReturnValue_NestedNullability_Invariant() { var source0 = @"public class A { public static B<object> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"using System; class C { static T F<T>(Func<int, T> f) => throw null!; static void F(B<object?> x, B<object> y) { var z = A.F/*T:B<object>!*/; F(i => { switch (i) { case 0: return x; default: return x; }})/*T:B<object?>!*/; F(i => { switch (i) { case 0: return x; default: return y; }})/*T:B<object!>!*/; // 1 F(i => { switch (i) { case 0: return x; default: return z; }})/*T:B<object?>!*/; F(i => { switch (i) { case 0: return y; default: return x; }})/*T:B<object!>!*/; // 2 F(i => { switch (i) { case 0: return y; default: return y; }})/*T:B<object!>!*/; F(i => { switch (i) { case 0: return y; default: return z; }})/*T:B<object!>!*/; F(i => { switch (i) { case 0: return z; default: return x; }})/*T:B<object?>!*/; F(i => { switch (i) { case 0: return z; default: return y; }})/*T:B<object!>!*/; F(i => { switch (i) { case 0: return z; default: return z; }})/*T:B<object>!*/; F(i => { switch (i) { case 0: return x; case 1: return y; default: return z; }})/*T:B<object!>!*/; // 3 F(i => { switch (i) { case 0: return z; case 1: return y; default: return x; }})/*T:B<object!>!*/; // 4 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (9,46): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // F(i => { switch (i) { case 0: return x; default: return y; }})/*T:B<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(9, 46), // (11,65): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // F(i => { switch (i) { case 0: return y; default: return x; }})/*T:B<object!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(11, 65), // (17,46): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // F(i => { switch (i) { case 0: return x; case 1: return y; default: return z; }})/*T:B<object!>*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(17, 46), // (18,83): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // F(i => { switch (i) { case 0: return z; case 1: return y; default: return x; }})/*T:B<object!>*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(18, 83) ); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void LambdaReturnValue_NestedNullability_Variant_01() { var source0 = @"public class A { public static I<object> F; public static IIn<object> FIn; public static IOut<object> FOut; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"using System; class C { static T F<T>(Func<bool, T> f) => throw null!; static void F1(I<object> x, I<object?> y) { var z = A.F/*T:I<object>!*/; F(b => { if (b) return x; else return x; })/*T:I<object!>!*/; F(b => { if (b) return x; else return y; })/*T:I<object!>!*/; // 1 F(b => { if (b) return x; else return z; })/*T:I<object!>!*/; F(b => { if (b) return y; else return x; })/*T:I<object!>!*/; // 2 F(b => { if (b) return y; else return y; })/*T:I<object?>!*/; F(b => { if (b) return y; else return z; })/*T:I<object?>!*/; F(b => { if (b) return z; else return x; })/*T:I<object!>!*/; F(b => { if (b) return z; else return y; })/*T:I<object?>!*/; F(b => { if (b) return z; else return z; })/*T:I<object>!*/; } static void F2(IIn<object> x, IIn<object?> y) { var z = A.FIn/*T:IIn<object>!*/; F(b => { if (b) return x; else return x; })/*T:IIn<object!>!*/; F(b => { if (b) return x; else return y; })/*T:IIn<object!>!*/; F(b => { if (b) return x; else return z; })/*T:IIn<object!>!*/; F(b => { if (b) return y; else return x; })/*T:IIn<object!>!*/; F(b => { if (b) return y; else return y; })/*T:IIn<object?>!*/; F(b => { if (b) return y; else return z; })/*T:IIn<object>!*/; F(b => { if (b) return z; else return x; })/*T:IIn<object!>!*/; F(b => { if (b) return z; else return y; })/*T:IIn<object>!*/; F(b => { if (b) return z; else return z; })/*T:IIn<object>!*/; } static void F3(IOut<object> x, IOut<object?> y) { var z = A.FOut/*T:IOut<object>!*/; F(b => { if (b) return x; else return x; })/*T:IOut<object!>!*/; F(b => { if (b) return x; else return y; })/*T:IOut<object?>!*/; F(b => { if (b) return x; else return z; })/*T:IOut<object>!*/; F(b => { if (b) return y; else return x; })/*T:IOut<object?>!*/; F(b => { if (b) return y; else return y; })/*T:IOut<object?>!*/; F(b => { if (b) return y; else return z; })/*T:IOut<object?>!*/; F(b => { if (b) return z; else return x; })/*T:IOut<object>!*/; F(b => { if (b) return z; else return y; })/*T:IOut<object?>!*/; F(b => { if (b) return z; else return z; })/*T:IOut<object>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (9,47): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // F(b => { if (b) return x; else return y; })/*T:I<object!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(9, 47), // (11,32): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // F(b => { if (b) return y; else return x; })/*T:I<object!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(11, 32) ); } [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] [Fact] public void LambdaReturnValue_NestedNullability_Variant_02() { var source0 = @"public class A { public static B<object> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"using System; class C { static Func<int, T> CreateFunc<T>(T t) => throw null!; static void F(B<object?> x, B<object> y) { var f = CreateFunc(y)/*Func<int, B<object!>!>!*/; var z = A.F/*T:B<object>!*/; f = i => { switch (i) { case 0: return x; default: return x; }}; // 1 2 f = i => { switch (i) { case 0: return x; default: return y; }}; // 3 f = i => { switch (i) { case 0: return x; default: return z; }}; // 4 f = i => { switch (i) { case 0: return y; default: return x; }}; // 5 f = i => { switch (i) { case 0: return y; default: return y; }}; f = i => { switch (i) { case 0: return y; default: return z; }}; f = i => { switch (i) { case 0: return z; default: return x; }}; // 6 f = i => { switch (i) { case 0: return z; default: return y; }}; f = i => { switch (i) { case 0: return z; default: return z; }}; f = i => { switch (i) { case 0: return x; case 1: return y; default: return z; }}; // 7 f = i => { switch (i) { case 0: return z; case 1: return y; default: return x; }}; // 8 var g = CreateFunc(z)/*Func<int, B<object>!>!*/; g = i => { switch (i) { case 0: return x; default: return x; }}; g = i => { switch (i) { case 0: return x; default: return y; }}; g = i => { switch (i) { case 0: return x; default: return z; }}; g = i => { switch (i) { case 0: return y; default: return x; }}; g = i => { switch (i) { case 0: return y; default: return y; }}; g = i => { switch (i) { case 0: return y; default: return z; }}; g = i => { switch (i) { case 0: return z; default: return x; }}; g = i => { switch (i) { case 0: return z; default: return y; }}; g = i => { switch (i) { case 0: return z; default: return z; }}; g = i => { switch (i) { case 0: return x; case 1: return y; default: return z; }}; g = i => { switch (i) { case 0: return z; case 1: return y; default: return x; }}; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (9,48): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return x; default: return x; }}; // 1 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(9, 48), // (9,67): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return x; default: return x; }}; // 1 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(9, 67), // (10,48): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return x; default: return y; }}; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(10, 48), // (11,48): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return x; default: return z; }}; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(11, 48), // (12,67): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return y; default: return x; }}; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(12, 67), // (15,67): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return z; default: return x; }}; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(15, 67), // (18,48): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return x; case 1: return y; default: return z; }}; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(18, 48), // (19,85): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'B<object>'. // f = i => { switch (i) { case 0: return z; case 1: return y; default: return x; }}; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object?>", "B<object>").WithLocation(19, 85) ); comp.VerifyTypes(); } [WorkItem(30432, "https://github.com/dotnet/roslyn/issues/30432")] [Fact] public void LambdaReturnValue_TopLevelNullability_Ref() { var source = @"delegate ref V D<T, U, V>(ref T t, ref U u); class C { static V F<T, U, V>(D<T, U, V> d) => throw null!; static void G(bool b) { F((ref object? x1, ref object? y1) => { if (b) return ref x1; return ref y1; }); F((ref object? x2, ref object y2) => { if (b) return ref x2; return ref y2; }); F((ref object x3, ref object? y3) => { if (b) return ref x3; return ref y3; }); F((ref object x4, ref object y4) => { if (b) return ref x4; return ref y4; }); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,81): warning CS8619: Nullability of reference types in value of type 'object' doesn't match target type 'object?'. // F((ref object? x2, ref object y2) => { if (b) return ref x2; return ref y2; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y2").WithArguments("object", "object?").WithLocation(8, 81), // (9,66): warning CS8619: Nullability of reference types in value of type 'object' doesn't match target type 'object?'. // F((ref object x3, ref object? y3) => { if (b) return ref x3; return ref y3; }); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("object", "object?").WithLocation(9, 66) ); } [WorkItem(30432, "https://github.com/dotnet/roslyn/issues/30432")] [WorkItem(30964, "https://github.com/dotnet/roslyn/issues/30964")] [Fact] public void LambdaReturnValue_NestedNullability_Ref() { var source = @"delegate ref V D<T, U, V>(ref T t, ref U u); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static V F<T, U, V>(D<T, U, V> d) => throw null!; static void G(bool b) { // I<object> F((ref I<object?> a1, ref I<object?> b1) => { if (b) return ref a1; return ref b1; }); F((ref I<object?> a2, ref I<object> b2) => { if (b) return ref a2; return ref b2; }); // 1 F((ref I<object> a3, ref I<object?> b3) => { if (b) return ref a3; return ref b3; }); // 2 F((ref I<object> a4, ref I<object> b4) => { if (b) return ref a4; return ref b4; }); // IIn<object> F((ref IIn<object?> c1, ref IIn<object?> d1) => { if (b) return ref c1; return ref d1; }); F((ref IIn<object?> c2, ref IIn<object> d2) => { if (b) return ref c2; return ref d2; }); // 3 F((ref IIn<object> c3, ref IIn<object?> d3) => { if (b) return ref c3; return ref d3; }); // 4 F((ref IIn<object> c4, ref IIn<object> d4) => { if (b) return ref c4; return ref d4; }); // IOut<object> F((ref IOut<object?> e1, ref IOut<object?> f1) => { if (b) return ref e1; return ref f1; }); F((ref IOut<object?> e2, ref IOut<object> f2) => { if (b) return ref e2; return ref f2; }); // 5 F((ref IOut<object> e3, ref IOut<object?> f3) => { if (b) return ref e3; return ref f3; }); // 6 F((ref IOut<object> e4, ref IOut<object> f4) => { if (b) return ref e4; return ref f4; }); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,72): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // F((ref I<object?> a2, ref I<object> b2) => { if (b) return ref a2; return ref b2; }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("I<object?>", "I<object>").WithLocation(12, 72), // (13,87): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // F((ref I<object> a3, ref I<object?> b3) => { if (b) return ref a3; return ref b3; }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b3").WithArguments("I<object?>", "I<object>").WithLocation(13, 87), // (17,76): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'IIn<object>'. // F((ref IIn<object?> c2, ref IIn<object> d2) => { if (b) return ref c2; return ref d2; }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c2").WithArguments("IIn<object?>", "IIn<object>").WithLocation(17, 76), // (18,91): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'IIn<object>'. // F((ref IIn<object> c3, ref IIn<object?> d3) => { if (b) return ref c3; return ref d3; }); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "d3").WithArguments("IIn<object?>", "IIn<object>").WithLocation(18, 91), // (22,93): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'IOut<object?>'. // F((ref IOut<object?> e2, ref IOut<object> f2) => { if (b) return ref e2; return ref f2; }); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "f2").WithArguments("IOut<object>", "IOut<object?>").WithLocation(22, 93), // (23,78): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'IOut<object?>'. // F((ref IOut<object> e3, ref IOut<object?> f3) => { if (b) return ref e3; return ref f3; }); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "e3").WithArguments("IOut<object>", "IOut<object?>").WithLocation(23, 78) ); } [Fact] public void LambdaParameterValue() { var source = @"using System; class C { static void F<T>(T t, Action<T> f) { } static void G(object? x) { F(x, y => F(y, z => { y.ToString(); z.ToString(); })); if (x != null) F(x, y => F(y, z => { y.ToString(); z.ToString(); })); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,31): warning CS8602: Dereference of a possibly null reference. // F(x, y => F(y, z => { y.ToString(); z.ToString(); })); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 31), // (9,45): warning CS8602: Dereference of a possibly null reference. // F(x, y => F(y, z => { y.ToString(); z.ToString(); })); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(9, 45)); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LocalFunction_OnlyCalledInLambda_01() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main(string[] args) { var x = M1(); Task.Run(() => Bar()); Task.Run(() => Baz()); void Bar() => M2(x); void Baz() => Console.WriteLine(x.ToString()); } private static object M1() => new object(); private static bool M2(object instance) => instance != null; } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LocalFunction_OnlyCalledInLambda_02() { var source = @" using System.Threading.Tasks; using System; class Program { static void Main(string[] args) { var x = M1(); void Bar() => M2(x); void Baz() => Console.WriteLine(x.ToString()); Task.Run(() => Bar()); Task.Run(() => Baz()); } private static object M1() => new object(); private static bool M2(object instance) => instance != null; } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LambdaWritesDoNotUpdateContainingMethodState() { var source = @" using System; class Program { static void M1() { string? x = ""hello""; M2(() => { x = null; }); x.ToString(); x = null; x.ToString(); // 1 } static void M2(Action a) { } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (16,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 9)); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LambdaWritesDoNotUpdateContainingMethodState_02() { var source = @" using System; class Program { static void M1() { M2(() => { string? y = ""world""; M2(() => { y = null; }); y.ToString(); y = null; y.ToString(); // 1 }); } static void M2(Action a) { } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (18,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(18, 13)); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void AnonymousMethodWritesDoNotUpdateContainingMethodState() { var source = @" using System; class Program { static void M1() { string? x = ""hello""; M2(delegate() { x = null; }); x.ToString(); x = null; x.ToString(); // 1 } static void M2(Action a) { } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (16,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 9)); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LocalFunctionWritesDoNotUpdateContainingMethodState_01() { var source = @" using System; class Program { static void M1() { string? x = ""hello""; x.ToString(); M2(local); x.ToString(); local(); x.ToString(); void local() { x = null; } } static void M2(Action a) { } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LocalFunctionWritesDoNotUpdateContainingMethodState_02() { var source = @" using System; class Program { static void M1() { string? x = ""hello""; void local() { x = null; } x.ToString(); M2(local); x.ToString(); local(); x.ToString(); } static void M2(Action a) { } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LocalFunctionStateConsidersAllUsages_01() { var source = @" class Program { static void M1() { string? x = ""hello""; local1(); local2(); x = null; local1(); void local1() { _ = x.ToString(); // 1 } void local2() { _ = x.ToString(); } } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 17)); } [Fact, WorkItem(44411, "https://github.com/dotnet/roslyn/issues/44411")] public void LocalFunctionStateConsidersAllUsages_02() { var source = @" using System; class Program { static void M1() { string? x = ""hello""; M2(local1); M2(local2); x = null; M2(local1); void local1() { _ = x.ToString(); // 1 } void local2() { _ = x.ToString(); } } static void M2(Action a) { } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (17,17): warning CS8602: Dereference of a possibly null reference. // _ = x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(17, 17)); } [Fact] [WorkItem(33645, "https://github.com/dotnet/roslyn/issues/33645")] public void ReinferLambdaReturnType() { var source = @"using System; class C { static T F<T>(Func<T> f) => f(); static void G(object? x) { F(() => x)/*T:object?*/; if (x == null) return; F(() => x)/*T:object!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void ReinferLambdaReturnType_IgnoreInnerLocalFunction() { var source = @" using System; class C { static T F<T>(Func<T> f) => f(); void M() { F(() => new object()).ToString(); F(() => { _ = local1(); return new object(); object? local1() { return null; } }).ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void ReinferLambdaReturnType_IgnoreInnerLambda() { var source = @" using System; class C { static T F<T>(Func<T> f) => f(); void M() { F(() => new object()).ToString(); F(() => { Func<object?> fn1 = () => { return null; }; _ = fn1(); return new object(); }).ToString(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void IdentityConversion_LambdaReturnType() { var source = @"delegate T D<T>(); interface I<T> { } class C { static void F(object x, object? y) { D<object?> a = () => x; D<object> b = () => y; // 1 if (y == null) return; a = () => y; b = () => y; a = (D<object?>)(() => y); b = (D<object>)(() => y); } static void F(I<object> x, I<object?> y) { D<I<object?>> a = () => x; // 2 D<I<object>> b = () => y; // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,29): warning CS8603: Possible null reference return. // D<object> b = () => y; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y").WithLocation(8, 29), // (17,33): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // D<I<object?>> a = () => x; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("I<object>", "I<object?>").WithLocation(17, 33), // (18,32): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // D<I<object>> b = () => y; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(18, 32)); } [Fact] public void IdentityConversion_LambdaParameter() { var source = @"delegate void D<T>(T t); interface I<T> { } class C { static void F() { D<object?> a = (object o) => { }; D<object> b = (object? o) => { }; D<I<object?>> c = (I<object> o) => { }; D<I<object>> d = (I<object?> o) => { }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,24): warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'D<object?>'. // D<object?> a = (object o) => { }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(object o) => { }").WithArguments("o", "lambda expression", "D<object?>").WithLocation(7, 24), // (8,23): warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'D<object>'. // D<object> b = (object? o) => { }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(object? o) => { }").WithArguments("o", "lambda expression", "D<object>").WithLocation(8, 23), // (9,27): warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'D<I<object?>>'. // D<I<object?>> c = (I<object> o) => { }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(I<object> o) => { }").WithArguments("o", "lambda expression", "D<I<object?>>").WithLocation(9, 27), // (10,26): warning CS8622: Nullability of reference types in type of parameter 'o' of 'lambda expression' doesn't match the target delegate 'D<I<object>>'. // D<I<object>> d = (I<object?> o) => { }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(I<object?> o) => { }").WithArguments("o", "lambda expression", "D<I<object>>").WithLocation(10, 26)); } [Fact, WorkItem(40561, "https://github.com/dotnet/roslyn/issues/40561")] public void ReturnLambda_InsideConditionalExpr() { var source = @" using System; class C { static void M0(string s) { } static Action? M1(string? s) => s != null ? () => M0(s) : (Action?)null; static Action? M2(string? s) => s != null ? (Action)(() => M0(s)) : null; static Action? M3(string? s) => s != null ? () => { M0(s); s = null; } : (Action?)null; static Action? M4(string? s) { return s != null ? local(() => M0(s), s = null) : (Action?)null; Action local(Action a1, string? s) { return a1; } } static Action? M5(string? s) { return s != null ? local(s = null, () => M0(s)) // 1 : (Action?)null; Action local(string? s, Action a1) { return a1; } } static Action? M6(string? s) { return s != null ? local(() => M0(s)) : (Action?)null; Action local(Action a1) { s = null; return a1; } } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (38,40): warning CS8604: Possible null reference argument for parameter 's' in 'void C.M0(string s)'. // ? local(s = null, () => M0(s)) // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s").WithArguments("s", "void C.M0(string s)").WithLocation(38, 40)); } [Fact] [WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void ReturnTypeInference_01() { var source = @"class C { static T F<T>(System.Func<T> f) { return f(); } static void G(string x, string? y) { F(() => x).ToString(); F(() => y).ToString(); // 1 if (y != null) F(() => y).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(() => y).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => y)").WithLocation(10, 9)); } [Fact] public void ReturnTypeInference_DelegateTypes() { var source = @" class C { System.Func<bool, T> D1<T>(T t) => k => t; void M1(bool b, string? s, string s2) { M2(k => s, D1(s)) /*T:System.Func<bool, string?>!*/; M2(D1(s), k => s) /*T:System.Func<bool, string?>!*/; M2(k => s2, D1(s2)) /*T:System.Func<bool, string!>!*/; M2(D1(s2), k => s2) /*T:System.Func<bool, string!>!*/; _ = (new[] { k => s, D1(s) }) /*T:System.Func<bool, string?>![]!*/; _ = (new[] { D1(s), k => s }) /*T:System.Func<bool, string?>![]!*/; _ = (new[] { k => s2, D1(s2) }) /*T:System.Func<bool, string>![]!*/; // wrong _ = (new[] { D1(s2), k => s2 }) /*T:System.Func<bool, string>![]!*/; // wrong } T M2<T>(T x, T y) => throw null!; }"; // See https://github.com/dotnet/roslyn/issues/34392 // Best type inference involving lambda conversion should agree with method type inference var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } // Multiple returns, one of which is null. [Fact] public void ReturnTypeInference_02() { var source = @"class C { static T F<T>(System.Func<T> f) { return f(); } static void G(string x) { F(() => { if (x.Length > 0) return x; return null; }).ToString(); F(() => { if (x.Length == 0) return null; return x; }).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F(() => { if (x.Length > 0) return x; return null; }).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => { if (x.Length > 0) return x; return null; })").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F(() => { if (x.Length == 0) return null; return x; }).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => { if (x.Length == 0) return null; return x; })").WithLocation(10, 9)); } [Fact] public void ReturnTypeInference_CSharp7() { var source = @"using System; class C { static void Main(string[] args) { args.F(arg => arg.Length); } } static class E { internal static U[] F<T, U>(this T[] a, Func<T, U> f) => throw new Exception(); }"; var comp = CreateCompilationWithMscorlib45( new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); } [Fact] public void UnboundLambda_01() { var source = @"class C { static void F() { var y = x => x; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,17): error CS8917: The delegate type could not be inferred. // var y = x => x; Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "x => x").WithLocation(5, 17)); } [Fact] public void UnboundLambda_02() { var source = @"class C { static void F(object? x) { var z = y => y ?? x.ToString(); System.Func<object?, object> z2 = y => y ?? x.ToString(); System.Func<object?, object> z3 = y => null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,17): error CS8917: The delegate type could not be inferred. // var z = y => y ?? x.ToString(); Diagnostic(ErrorCode.ERR_CannotInferDelegateType, "y => y ?? x.ToString()").WithLocation(5, 17), // (5,27): warning CS8602: Dereference of a possibly null reference. // var z = y => y ?? x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(5, 27), // (6,53): warning CS8602: Dereference of a possibly null reference. // System.Func<object?, object> z2 = y => y ?? x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 53), // (7,48): warning CS8603: Possible null reference return. // System.Func<object?, object> z3 = y => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(7, 48)); } /// <summary> /// Inferred nullability of captured variables should be tracked across /// local function invocations, as if the local function was inlined. /// </summary> [Fact] [WorkItem(29892, "https://github.com/dotnet/roslyn/issues/29892")] public void LocalFunction_01() { var source = @"class C { static void F1(object? x1, object y1) { object z1 = y1; f(); z1.ToString(); // warning void f() { z1 = x1; // warning } } static void F2(object? x2, object y2) { object z2 = x2; // warning f(); z2.ToString(); void f() { z2 = y2; } } static void F3(object? x3, object y3) { object z3 = y3; void f() { z3 = x3; } if (x3 == null) return; f(); z3.ToString(); } static void F4(object? x4) { f().ToString(); // warning if (x4 != null) f().ToString(); object? f() => x4; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29892: Should report warnings as indicated in source above. comp.VerifyDiagnostics( // (10,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // z1 = x1; // warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(10, 18), // (15,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object z2 = x2; // warning Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(15, 21), // (17,9): warning CS8602: Dereference of a possibly null reference. // z2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2").WithLocation(17, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // f().ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "f()").WithLocation(36, 9), // (37,25): warning CS8602: Dereference of a possibly null reference. // if (x4 != null) f().ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "f()").WithLocation(37, 25)); } [Fact] [WorkItem(29892, "https://github.com/dotnet/roslyn/issues/29892")] public void LocalFunction_02() { var source = @"class C { static void F1() { string? x = """"; f(); x = """"; g(); void f() { x.ToString(); // warn x = null; f(); } void g() { x.ToString(); x = null; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 13) ); } [Fact] [WorkItem(29892, "https://github.com/dotnet/roslyn/issues/29892")] public void LocalFunction_03() { var source = @"class C { static void F1() { string? x = """"; f(); h(); void f() { x.ToString(); } void g() { x.ToString(); // warn } void h() { x = null; g(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 13) ); } [Fact] [WorkItem(29892, "https://github.com/dotnet/roslyn/issues/29892")] public void LocalFunction_04() { var source = @"class C { static void F1() { string? x = """"; f(); void f() { x.ToString(); // warn if (string.Empty == """") // non-constant { x = null; f(); } } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 13) ); } [Fact] [WorkItem(42396, "https://github.com/dotnet/roslyn/issues/42396")] public void LocalFunction_05() { var source = @" using System; using System.Collections.Generic; class C { void M<T>() where T : class { Func<IEnumerable<List<T>>> f = () => { IEnumerable<T> Enumerate(IEnumerable<T> xs) { foreach (T x in xs) yield return x; } Enumerate(new List<T>()); return new List<T>[0]; }; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(42396, "https://github.com/dotnet/roslyn/issues/42396")] public void LocalFunction_06() { var source = @" using System; using System.Collections.Generic; class C { void M<T>() where T : class { Func<IEnumerable<List<T>>> f = () => { IEnumerable<T> Enumerate(IEnumerable<T> xs) { return xs; } Enumerate(new List<T>()); return new List<T>[0]; }; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } /// <summary> /// Should report warnings within unused local functions. /// </summary> [Fact] [WorkItem(29892, "https://github.com/dotnet/roslyn/issues/29892")] public void LocalFunction_NoCallers() { var source = @"#pragma warning disable 8321 class C { static void F1(object? x1) { void f1() { x1.ToString(); // 1 } } static void F2(object? x2) { if (x2 == null) return; void f2() { x2.ToString(); // 2 } } static void F3(object? x3) { object? y3 = x3; void f3() { y3.ToString(); // 3 } if (y3 == null) return; void g3() { y3.ToString(); // 4 } } static void F4() { void f4(object? x4) { x4.ToString(); // 5 } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(8, 13), // (16,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(16, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // y3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y3").WithLocation(24, 13), // (29,13): warning CS8602: Dereference of a possibly null reference. // y3.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y3").WithLocation(29, 13), // (36,13): warning CS8602: Dereference of a possibly null reference. // x4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(36, 13)); } [Fact] public void New_01() { var source = @"class C { static void F1() { object? x1; x1 = new object?(); // error 1 x1 = new object? { }; // error 2 x1 = (new object?[1])[0]; x1 = new object[]? {}; // error 3 } static void F2<T2>() { object? x2; x2 = new T2?(); // error 4 x2 = new T2? { }; // error 5 x2 = (new T2?[1])[0]; } static void F3<T3>() where T3 : class, new() { object? x3; x3 = new T3?(); // error 6 x3 = new T3? { }; // error 7 x3 = (new T3?[1])[0]; } static void F4<T4>() where T4 : new() { object? x4; x4 = new T4?(); // error 8 x4 = new T4? { }; // error 9 x4 = (new T4?[1])[0]; x4 = new System.Nullable<int>? { }; // error 11 } static void F5<T5>() where T5 : class { object? x5; x5 = new T5?(); // error 10 x5 = new T5? { }; // error 11 x5 = (new T5?[1])[0]; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,14): error CS8628: Cannot use a nullable reference type in object creation. // x1 = new object?(); // error 1 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new object?()").WithArguments("object").WithLocation(6, 14), // (7,14): error CS8628: Cannot use a nullable reference type in object creation. // x1 = new object? { }; // error 2 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new object? { }").WithArguments("object").WithLocation(7, 14), // (9,14): error CS8628: Cannot use a nullable reference type in object creation. // x1 = new object[]? {}; // error 3 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new object[]? {}").WithArguments("object[]").WithLocation(9, 14), // (9,18): error CS8386: Invalid object creation // x1 = new object[]? {}; // error 3 Diagnostic(ErrorCode.ERR_InvalidObjectCreation, "object[]?").WithArguments("object[]").WithLocation(9, 18), // (14,18): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // x2 = new T2?(); // error 4 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(14, 18), // (14,14): error CS8628: Cannot use a nullable reference type in object creation. // x2 = new T2?(); // error 4 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T2?()").WithArguments("T2").WithLocation(14, 14), // (14,14): error CS0304: Cannot create an instance of the variable type 'T2' because it does not have the new() constraint // x2 = new T2?(); // error 4 Diagnostic(ErrorCode.ERR_NoNewTyvar, "new T2?()").WithArguments("T2").WithLocation(14, 14), // (15,18): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // x2 = new T2? { }; // error 5 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(15, 18), // (15,14): error CS8628: Cannot use a nullable reference type in object creation. // x2 = new T2? { }; // error 5 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T2? { }").WithArguments("T2").WithLocation(15, 14), // (15,14): error CS0304: Cannot create an instance of the variable type 'T2' because it does not have the new() constraint // x2 = new T2? { }; // error 5 Diagnostic(ErrorCode.ERR_NoNewTyvar, "new T2? { }").WithArguments("T2").WithLocation(15, 14), // (16,19): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // x2 = (new T2?[1])[0]; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(16, 19), // (21,14): error CS8628: Cannot use a nullable reference type in object creation. // x3 = new T3?(); // error 6 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T3?()").WithArguments("T3").WithLocation(21, 14), // (22,14): error CS8628: Cannot use a nullable reference type in object creation. // x3 = new T3? { }; // error 7 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T3? { }").WithArguments("T3").WithLocation(22, 14), // (28,18): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // x4 = new T4?(); // error 8 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T4?").WithArguments("9.0").WithLocation(28, 18), // (28,14): error CS8628: Cannot use a nullable reference type in object creation. // x4 = new T4?(); // error 8 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T4?()").WithArguments("T4").WithLocation(28, 14), // (29,18): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // x4 = new T4? { }; // error 9 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T4?").WithArguments("9.0").WithLocation(29, 18), // (29,14): error CS8628: Cannot use a nullable reference type in object creation. // x4 = new T4? { }; // error 9 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T4? { }").WithArguments("T4").WithLocation(29, 14), // (30,19): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // x4 = (new T4?[1])[0]; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T4?").WithArguments("9.0").WithLocation(30, 19), // (31,18): error CS0453: The type 'int?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // x4 = new System.Nullable<int>? { }; // error 11 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "System.Nullable<int>?").WithArguments("System.Nullable<T>", "T", "int?").WithLocation(31, 18), // (36,14): error CS8628: Cannot use a nullable reference type in object creation. // x5 = new T5?(); // error 10 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T5?()").WithArguments("T5").WithLocation(36, 14), // (36,14): error CS0304: Cannot create an instance of the variable type 'T5' because it does not have the new() constraint // x5 = new T5?(); // error 10 Diagnostic(ErrorCode.ERR_NoNewTyvar, "new T5?()").WithArguments("T5").WithLocation(36, 14), // (37,14): error CS8628: Cannot use a nullable reference type in object creation. // x5 = new T5? { }; // error 11 Diagnostic(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, "new T5? { }").WithArguments("T5").WithLocation(37, 14), // (37,14): error CS0304: Cannot create an instance of the variable type 'T5' because it does not have the new() constraint // x5 = new T5? { }; // error 11 Diagnostic(ErrorCode.ERR_NoNewTyvar, "new T5? { }").WithArguments("T5").WithLocation(37, 14) ); } [Fact] public void New_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1<T1>(T1 x1) where T1 : class, new() { x1 = new T1(); } void Test2<T2>(T2 x2) where T2 : class, new() { x2 = new T2() ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } // `where T : new()` does not imply T is non-nullable. [Fact] public void New_03() { var source = @"class C { static void F1<T>() where T : new() { } static void F2<T>(T t) where T : new() { } static void G<U>() where U : class, new() { object? x = null; F1<object?>(); F2(x); U? y = null; F1<U?>(); F2(y); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void New_04() { var source = @"class C { internal object? F; internal object P { get; set; } = null!; } class Program { static void F<T>() where T : C, new() { T x = new T() { F = 1, P = null }; // 1 x.F.ToString(); x.P.ToString(); // 2 C y = new T() { F = 2, P = null }; // 3 y.F.ToString(); y.P.ToString(); // 4 C z = (C)new T() { F = 3, P = null }; // 5 z.F.ToString(); z.P.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // T x = new T() { F = 1, P = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 36), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.P").WithLocation(12, 9), // (13,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // C y = new T() { F = 2, P = null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 36), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.P").WithLocation(15, 9), // (16,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // C z = (C)new T() { F = 3, P = null }; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 39), // (18,9): warning CS8602: Dereference of a possibly null reference. // z.P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.P").WithLocation(18, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void New_05() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F<T>() where T : I, new() { T x = new T() { P = 1, Q = null }; // 1 x.P.ToString(); x.Q.ToString(); // 2 I y = new T() { P = 2, Q = null }; // 3 y.P.ToString(); y.Q.ToString(); // 4 I z = (I)new T() { P = 3, Q = null }; // 5 z.P.ToString(); z.Q.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // T x = new T() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 36), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Q").WithLocation(12, 9), // (13,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // I y = new T() { P = 2, Q = null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 36), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.Q.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Q").WithLocation(15, 9), // (16,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // I z = (I)new T() { P = 3, Q = null }; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 39), // (18,9): warning CS8602: Dereference of a possibly null reference. // z.Q.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.Q").WithLocation(18, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void New_06() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F<T>() where T : class, I, new() { T x = new T() { P = 1, Q = null }; // 1 x.P.ToString(); x.Q.ToString(); // 2 I y = new T() { P = 2, Q = null }; // 3 y.P.ToString(); y.Q.ToString(); // 4 I z = (I)new T() { P = 3, Q = null }; // 5 z.P.ToString(); z.Q.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // T x = new T() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 36), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Q").WithLocation(12, 9), // (13,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // I y = new T() { P = 2, Q = null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 36), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.Q.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Q").WithLocation(15, 9), // (16,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // I z = (I)new T() { P = 3, Q = null }; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 39), // (18,9): warning CS8602: Dereference of a possibly null reference. // z.Q.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.Q").WithLocation(18, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void New_07() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F<T>() where T : struct, I { T x = new T() { P = 1, Q = null }; // 1 x.P.ToString(); x.Q.ToString(); // 2 I y = new T() { P = 2, Q = null }; // 3 y.P.ToString(); y.Q.ToString(); // 4 I z = (I)new T() { P = 3, Q = null }; // 5 z.P.ToString(); z.Q.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // T x = new T() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 36), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Q").WithLocation(12, 9), // (13,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // I y = new T() { P = 2, Q = null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 36), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.Q.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Q").WithLocation(15, 9), // (16,39): warning CS8625: Cannot convert null literal to non-nullable reference type. // I z = (I)new T() { P = 3, Q = null }; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 39), // (18,9): warning CS8602: Dereference of a possibly null reference. // z.Q.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.Q").WithLocation(18, 9)); } [Fact] public void DynamicObjectCreation_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = new CL0((dynamic)0); } void Test2(CL0 x2) { x2 = new CL0((dynamic)0) ?? x2; } } class CL0 { public CL0(int x) {} public CL0(long x) {} } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicObjectCreation_02() { var source = @"class C { C(object x, object y) { } static void G(object? x, dynamic y) { var o = new C(x, y); if (x != null) o = new C(y, x); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29893: We should be able to report warnings // when all applicable methods agree on the nullability of particular parameters. // (For instance, x in F(x, y) above.) comp.VerifyDiagnostics(); } [Fact] public void DynamicObjectCreation_03() { var source = @"class C { C(object f) { F = f; } object? F; object? G; static void M(dynamic d) { var o = new C(d) { G = new object() }; o.G.ToString(); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void DynamicIndexerAccess_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = x1[(dynamic)0]; } void Test2(CL0 x2) { x2 = x2[(dynamic)0] ?? x2; } } class CL0 { public CL0 this[int x] { get { return new CL0(); } set { } } public CL0 this[long x] { get { return new CL0(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicIndexerAccess_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { dynamic y1 = x1[(dynamic)0]; } void Test2(CL0 x2) { dynamic y2 = x2[(dynamic)0] ?? x2; } } class CL0 { public CL0? this[int x] { get { return new CL0(); } set { } } public CL0 this[long x] { get { return new CL0(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicIndexerAccess_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { dynamic y1 = x1[(dynamic)0]; } void Test2(CL0 x2) { dynamic y2 = x2[(dynamic)0] ?? x2; } } class CL0 { public CL0 this[int x] { get { return new CL0(); } set { } } public CL0? this[long x] { get { return new CL0(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicIndexerAccess_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { dynamic y1 = x1[(dynamic)0]; } void Test2(CL0 x2) { dynamic y2 = x2[(dynamic)0] ?? x2; } } class CL0 { public CL0? this[int x] { get { return new CL0(); } set { } } public CL0? this[long x] { get { return new CL0(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicIndexerAccess_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = x1[(dynamic)0]; } void Test2(CL0 x2) { x2 = x2[(dynamic)0] ?? x2; } } class CL0 { public int this[int x] { get { return x; } set { } } public int this[long x] { get { return (int)x; } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicIndexerAccess_06() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = x1[(dynamic)0]; } void Test2(CL0 x2) { x2 = x2[(dynamic)0] ?? x2; } } class CL0 { public int this[int x] { get { return x; } set { } } public long this[long x] { get { return x; } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicIndexerAccess_07() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(dynamic x1) { x1 = x1[0]; } void Test2(dynamic x2) { x2 = x2[0] ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicIndexerAccess_08() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1<T>(CL0<T> x1) { x1 = x1[(dynamic)0]; } void Test2<T>(CL0<T> x2) { x2 = x2[(dynamic)0] ?? x2; } } class CL0<T> { public T this[int x] { get { return default(T); } set { } } public long this[long x] { get { return x; } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (22,22): warning CS8603: Possible null reference return. // get { return default(T); } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(22, 22)); } [Fact] public void DynamicIndexerAccess_09() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1, dynamic y1) { x1[(dynamic)0] = y1; } void Test2(CL0 x2, dynamic? y2, CL1 z2) { x2[(dynamic)0] = y2; z2[0] = y2; } } class CL0 { public CL0 this[int x] { get { return new CL0(); } set { } } public CL0 this[long x] { get { return new CL0(); } set { } } } class CL1 { public dynamic this[int x] { get { return new CL0(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,17): warning CS8601: Possible null reference assignment. // z2[0] = y2; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y2").WithLocation(15, 17) ); } [Fact] public void DynamicIndexerAccess_10() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0? x1) { x1 = x1[(dynamic)0]; } void Test2(CL0? x2) { x2 = x2[0]; } } class CL0 { public CL0 this[int x] { get { return new CL0(); } set { } } public CL0 this[long x] { get { return new CL0(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,14): warning CS8602: Dereference of a possibly null reference. // x1 = x1[(dynamic)0]; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(9, 14), // (14,14): warning CS8602: Dereference of a possibly null reference. // x2 = x2[0]; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(14, 14) ); } [Fact] public void DynamicInvocation_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = x1.M1((dynamic)0); } void Test2(CL0 x2) { x2 = x2.M1((dynamic)0) ?? x2; } } class CL0 { public CL0 M1(int x) { return new CL0(); } public CL0 M1(long x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicInvocation_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { dynamic y1 = x1.M1((dynamic)0); } void Test2(CL0 x2) { dynamic y2 = x2.M1((dynamic)0) ?? x2; } } class CL0 { public CL0? M1(int x) { return new CL0(); } public CL0 M1(long x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicInvocation_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { dynamic y1 = x1.M1((dynamic)0); } void Test2(CL0 x2) { dynamic y2 = x2.M1((dynamic)0) ?? x2; } } class CL0 { public CL0 M1(int x) { return new CL0(); } public CL0? M1(long x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicInvocation_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { dynamic y1 = x1.M1((dynamic)0); } void Test2(CL0 x2) { dynamic y2 = x2.M1((dynamic)0) ?? x2; } } class CL0 { public CL0? M1(int x) { return new CL0(); } public CL0? M1(long x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics(); } [Fact] public void DynamicInvocation_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = x1.M1((dynamic)0); } void Test2(CL0 x2) { x2 = x2.M1((dynamic)0) ?? x2; } } class CL0 { public int M1(int x) { return x; } public int M1(long x) { return (int)x; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicInvocation_06() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0 x1) { x1 = x1.M1((dynamic)0); } void Test2(CL0 x2) { x2 = x2.M1((dynamic)0) ?? x2; } } class CL0 { public int M1(int x) { return x; } public long M1(long x) { return x; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicInvocation_07() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(dynamic x1) { x1 = x1.M1(0); } void Test2(dynamic x2) { x2 = x2.M1(0) ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicInvocation_08() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1<T>(CL0<T> x1) { x1 = x1.M1((dynamic)0); } void Test2<T>(CL0<T> x2) { x2 = x2.M1((dynamic)0) ?? x2; } } class CL0<T> { public T M1(int x) { return default(T); } public long M1(long x) { return x; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (22,16): warning CS8603: Possible null reference return. // return default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(22, 16)); } [Fact] public void DynamicInvocation_09() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(CL0? x1) { x1 = x1.M1((dynamic)0); } void Test2(CL0? x2) { x2 = x2.M1(0); } } class CL0 { public CL0 M1(int x) { return new CL0(); } public CL0 M1(long x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,14): warning CS8602: Dereference of a possibly null reference. // x1 = x1.M1((dynamic)0); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(9, 14), // (14,14): warning CS8602: Dereference of a possibly null reference. // x2 = x2.M1(0); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(14, 14) ); } [Fact] public void DynamicMemberAccess_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1(dynamic x1) { x1 = x1.M1; } void Test2(dynamic x2) { x2 = x2.M1 ?? x2; } void Test3(dynamic? x3) { dynamic y3 = x3.M1; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (19,22): warning CS8602: Dereference of a possibly null reference. // dynamic y3 = x3.M1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(19, 22) ); } [Fact] public void DynamicMemberAccess_02() { var source = @"class C { static void M(dynamic x) { x.F/*T:dynamic!*/.ToString(); var y = x.F; y/*T:dynamic!*/.ToString(); y = null; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void DynamicObjectCreationExpression_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() {} void Test1() { dynamic? x1 = null; CL0 y1 = new CL0(x1); } void Test2(CL0 y2) { dynamic? x2 = null; CL0 z2 = new CL0(x2) ?? y2; } } class CL0 { public CL0(int x) { } public CL0(long x) { } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DynamicInvocation() { var source = @"class C { static void F(object x, object y) { } static void G(object? x, dynamic y) { F(x, y); if (x != null) F(y, x); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29893: We should be able to report warnings // when all applicable methods agree on the nullability of particular parameters. // (For instance, x in F(x, y) above.) comp.VerifyDiagnostics(); } [Fact] public void NameOf_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(string x1, string? y1) { x1 = nameof(y1); } void Test2(string x2, string? y2) { string? z2 = nameof(y2); x2 = z2 ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void StringInterpolation_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(string x1, string? y1) { x1 = $""{y1}""; } void Test2(string x2, string? y2) { x2 = $""{y2}"" ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Theory] [CombinatorialData] public void StringInterpolation_02(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{s = """"}{s.ToString()}""", @"$""{s = """"}"" + $""{s.ToString()}""")] string expression) { CSharpCompilation c = CreateCompilation(new[] { @" #nullable enable string? s = null; M(" + expression + @", s); void M(CustomHandler c, string s) {} ", GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns, includeTrailingOutConstructorParameter: validityParameter) }, parseOptions: TestOptions.RegularPreview); if (validityParameter) { c.VerifyDiagnostics( // (5,30): warning CS8604: Possible null reference argument for parameter 's' in 'void M(CustomHandler c, string s)'. // M($"{s = ""}{s.ToString()}", s); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s").WithArguments("s", "void M(CustomHandler c, string s)").WithLocation(5, 19 + expression.IndexOf("s.ToString")) ); } else { c.VerifyDiagnostics(); } } [Theory] [CombinatorialData] public void StringInterpolation_03(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; #nullable enable string? s = """"; M( #line 1000 ref s, #line 2000 " + expression + @", #line 3000 s.ToString()); void M<T>(ref T t1, [InterpolatedStringHandlerArgument(""t1"")] CustomHandler<T> c, T t2) {} public partial struct CustomHandler<T> { public CustomHandler(int literalLength, int formattedCount, [MaybeNull] ref T t " + (validityParameter ? ", out bool success" : "") + @") : this() { " + (validityParameter ? "success = true;" : "") + @" } } ", GetInterpolatedStringCustomHandlerType("CustomHandler<T>", "partial struct", useBoolReturns, includeTrailingOutConstructorParameter: validityParameter), InterpolatedStringHandlerArgumentAttribute, MaybeNullAttributeDefinition }, parseOptions: TestOptions.RegularPreview); // https://github.com/dotnet/roslyn/issues/54583 // Should be a warning on `s.ToString()` c.VerifyDiagnostics( // (1000,9): warning CS8601: Possible null reference assignment. // ref s, Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(1000, 9) ); } [Theory] [CombinatorialData] public void StringInterpolation_04(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""""", @"$"""" + $""""")] string expression) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s = null; M(s, " + expression + @"); void M(string? s1, [InterpolatedStringHandlerArgument(""s1"")] CustomHandler c) {} public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount, string s" + (validityParameter ? ", out bool success" : "") + @") : this() { " + (validityParameter ? "success = true;" : "") + @" } } ", GetInterpolatedStringCustomHandlerType("CustomHandler", "partial struct", useBoolReturns, includeTrailingOutConstructorParameter: validityParameter), InterpolatedStringHandlerArgumentAttribute }, parseOptions: TestOptions.RegularPreview); // https://github.com/dotnet/roslyn/issues/54583 // Should be a warning for the constructor parameter c.VerifyDiagnostics( ); } [Theory] [CombinatorialData] public void StringInterpolation_05(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{s}""", @"$""{s}"" + $""""")] string expression) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s = null; M(" + expression + @"); void M(CustomHandler c) {} [InterpolatedStringHandler] public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + (validityParameter ? ", out bool success" : "") + @") : this() { " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted(object o) { return " + (useBoolReturns ? "true" : "") + @"; } } ", InterpolatedStringHandlerAttribute }, parseOptions: TestOptions.RegularPreview); c.VerifyDiagnostics( // (6,6): warning CS8604: Possible null reference argument for parameter 'o' in 'void CustomHandler.AppendFormatted(object o)'. // M($"{s}"); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "s").WithArguments("o", (useBoolReturns ? "bool" : "void") + " CustomHandler.AppendFormatted(object o)").WithLocation(6, 6) ); } [Theory] [CombinatorialData] public void StringInterpolation_06(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{s = null}{s = """"}""", @"$""{s = null}"" + $""{s = """"}""")] string expression) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s = """"; M(" + expression + @"); _ = s.ToString(); void M(CustomHandler c) {} [InterpolatedStringHandler] public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + (validityParameter ? ", out bool success" : "") + @") : this() { " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted(object? o) { return " + (useBoolReturns ? "true" : "") + @"; } } ", InterpolatedStringHandlerAttribute }, parseOptions: TestOptions.RegularPreview); if (useBoolReturns) { c.VerifyDiagnostics( // (7,5): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 5) ); } else { c.VerifyDiagnostics( ); } } [Theory] [CombinatorialData] public void StringInterpolation_07(bool useBoolReturns, bool validityParameter, [CombinatorialValues(@"$""{s1 = null}{s2 = null}{s3 = null}{s1 = """"}{s2 = """"}{s3 = """"}""", @"$""{s1 = null}"" + $""{s2 = null}"" + $""{s3 = null}"" + $""{s1 = """"}"" + $""{s2 = """"}"" + $""{s3 = """"}""")] string expression) { CSharpCompilation c = CreateCompilation(new[] { @" using System.Runtime.CompilerServices; #nullable enable string? s1 = """"; string? s2 = """"; string? s3 = """"; M(" + expression + @"); _ = s1.ToString(); _ = s2.ToString(); _ = s3.ToString(); void M(CustomHandler c) {} [InterpolatedStringHandler] public partial struct CustomHandler { public CustomHandler(int literalLength, int formattedCount" + (validityParameter ? ", out bool success" : "") + @") : this() { " + (validityParameter ? "success = true;" : "") + @" } public " + (useBoolReturns ? "bool" : "void") + @" AppendFormatted(object? o) { return " + (useBoolReturns ? "true" : "") + @"; } } ", InterpolatedStringHandlerAttribute }, parseOptions: TestOptions.RegularPreview); if (useBoolReturns) { c.VerifyDiagnostics( // (9,5): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 5), // (10,5): warning CS8602: Dereference of a possibly null reference. // _ = s2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 5), // (11,5): warning CS8602: Dereference of a possibly null reference. // _ = s3.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(11, 5) ); } else { c.VerifyDiagnostics(); } } [Fact] public void DelegateCreation_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(System.Action x1) { x1 = new System.Action(Main); } void Test2(System.Action x2) { x2 = new System.Action(Main) ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void DelegateCreation_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } CL0<string?> M1(CL0<string> x) { throw new System.Exception(); } CL0<string> M2(CL0<string> x) { throw new System.Exception(); } delegate CL0<string> D1(CL0<string?> x); void Test1() { D1 x1 = new D1(M1); D1 x2 = new D1(M2); } CL0<string> M3(CL0<string?> x) { throw new System.Exception(); } CL0<string?> M4(CL0<string?> x) { throw new System.Exception(); } delegate CL0<string?> D2(CL0<string> x); void Test2() { D2 x1 = new D2(M3); D2 x2 = new D2(M4); } } class CL0<T>{} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (14,24): warning CS8621: Nullability of reference types in return type of 'CL0<string?> C.M1(CL0<string> x)' doesn't match the target delegate 'C.D1' (possibly because of nullability attributes). // D1 x1 = new D1(M1); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M1").WithArguments("CL0<string?> C.M1(CL0<string> x)", "C.D1").WithLocation(14, 24), // (15,24): warning CS8622: Nullability of reference types in type of parameter 'x' of 'CL0<string> C.M2(CL0<string> x)' doesn't match the target delegate 'C.D1' (possibly because of nullability attributes). // D1 x2 = new D1(M2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M2").WithArguments("x", "CL0<string> C.M2(CL0<string> x)", "C.D1").WithLocation(15, 24), // (24,24): warning CS8621: Nullability of reference types in return type of 'CL0<string> C.M3(CL0<string?> x)' doesn't match the target delegate 'C.D2' (possibly because of nullability attributes). // D2 x1 = new D2(M3); Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M3").WithArguments("CL0<string> C.M3(CL0<string?> x)", "C.D2").WithLocation(24, 24), // (25,24): warning CS8622: Nullability of reference types in type of parameter 'x' of 'CL0<string?> C.M4(CL0<string?> x)' doesn't match the target delegate 'C.D2' (possibly because of nullability attributes). // D2 x2 = new D2(M4); Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M4").WithArguments("x", "CL0<string?> C.M4(CL0<string?> x)", "C.D2").WithLocation(25, 24) ); } [Fact] public void DelegateCreation_03() { var source = @"delegate void D(object x, object? y); class Program { static void Main() { _ = new D((object x1, object? y1) => { x1 = null; // 1 y1.ToString(); // 2 }); _ = new D((x2, y2) => { x2 = null; // 3 y2.ToString(); // 4 }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 22), // (9,17): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(9, 17), // (13,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = null; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 22), // (14,17): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(14, 17)); } [Fact] public void DelegateCreation_04() { var source = @"delegate object D1(); delegate object? D2(); class Program { static void F(object x, object? y) { x = null; // 1 y = 2; _ = new D1(() => x); // 2 _ = new D2(() => x); _ = new D1(() => y); _ = new D2(() => y); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 13), // (9,26): warning CS8603: Possible null reference return. // _ = new D1(() => x); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "x").WithLocation(9, 26)); } [Fact] [WorkItem(35549, "https://github.com/dotnet/roslyn/issues/35549")] public void DelegateCreation_05() { var source = @"delegate T D<T>(); class Program { static T F<T>() => throw null!; static void G<T>() where T : class { _ = new D<T?>(F<T>)!; _ = new D<T?>(F<T>!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,25): error CS0119: 'T' is a type, which is not valid in the given context // _ = new D<T?>(F<T>!); Diagnostic(ErrorCode.ERR_BadSKunknown, "T").WithArguments("T", "type").WithLocation(8, 25), // (8,28): error CS1525: Invalid expression term ')' // _ = new D<T?>(F<T>!); Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(8, 28)); } [Fact] public void DelegateCreation_06() { var source = @"delegate T D<T>(); class Program { static T F<T>() => throw null!; static void G<T>() where T : class { _ = new D<T>(F<T?>)!; // 1 _ = new D<T>(F<T?>!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,22): warning CS8621: Nullability of reference types in return type of 'T? Program.F<T?>()' doesn't match the target delegate 'D<T>'. // _ = new D<T>(F<T?>)!; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<T?>").WithArguments("T? Program.F<T?>()", "D<T>").WithLocation(7, 22)); } [Fact] public void DelegateCreation_07() { var source = @"delegate T D<T>(); class Program { static T F<T>() => throw null!; static void G<T>() where T : class { _ = new D<T?>(() => F<T>())!; _ = new D<T?>(() => F<T>()!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void DelegateCreation_08() { var source = @"delegate T D<T>(); class Program { static T F<T>() => throw null!; static void G<T>() where T : class { _ = new D<T>(() => F<T?>())!; // 1 _ = new D<T>(() => F<T?>()!); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,28): warning CS8603: Possible null reference return. // _ = new D<T>(() => F<T?>())!; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "F<T?>()").WithLocation(7, 28)); } [Fact] public void DelegateCreation_09() { var source = @"delegate void D(); class C { void F() { } static void M() { D d = default(C).F; // 1 _ = new D(default(C).F); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // D d = default(C).F; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(C)").WithLocation(7, 15), // (8,19): warning CS8602: Dereference of a possibly null reference. // _ = new D(default(C).F); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(C)").WithLocation(8, 19)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_ReturnType_01() { var source = @"delegate T D<T>(); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>() => throw null!; static void Main() { _ = new D<object>(() => F<object?>()); // 1 _ = new D<object?>(() => F<object>()); _ = new D<I<object>>(() => F<I<object?>>()); // 2 _ = new D<I<object?>>(() => F<I<object>>()); // 3 _ = new D<IIn<object>>(() => F<IIn<object?>>()); _ = new D<IIn<object?>>(() => F<IIn<object>>()); // 4 _ = new D<IOut<object>>(() => F<IOut<object?>>()); // 5 _ = new D<IOut<object?>>(() => F<IOut<object>>()); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,33): warning CS8603: Possible null reference return. // _ = new D<object>(() => F<object?>()); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "F<object?>()").WithLocation(10, 33), // (12,36): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // _ = new D<I<object>>(() => F<I<object?>>()); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "F<I<object?>>()").WithArguments("I<object?>", "I<object>").WithLocation(12, 36), // (13,37): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // _ = new D<I<object?>>(() => F<I<object>>()); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "F<I<object>>()").WithArguments("I<object>", "I<object?>").WithLocation(13, 37), // (15,39): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // _ = new D<IIn<object?>>(() => F<IIn<object>>()); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "F<IIn<object>>()").WithArguments("IIn<object>", "IIn<object?>").WithLocation(15, 39), // (16,39): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // _ = new D<IOut<object>>(() => F<IOut<object?>>()); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "F<IOut<object?>>()").WithArguments("IOut<object?>", "IOut<object>").WithLocation(16, 39)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_ReturnType_02() { var source = @"delegate T D<T>(); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>() => throw null!; static void Main() { _ = new D<object>(F<object?>); // 1 _ = new D<object?>(F<object>); _ = new D<I<object>>(F<I<object?>>); // 2 _ = new D<I<object?>>(F<I<object>>); // 3 _ = new D<IIn<object>>(F<IIn<object?>>); _ = new D<IIn<object?>>(F<IIn<object>>); // 4 _ = new D<IOut<object>>(F<IOut<object?>>); // 5 _ = new D<IOut<object?>>(F<IOut<object>>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,27): warning CS8621: Nullability of reference types in return type of 'object? C.F<object?>()' doesn't match the target delegate 'D<object>'. // _ = new D<object>(F<object?>); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<object?>").WithArguments("object? C.F<object?>()", "D<object>").WithLocation(10, 27), // (12,30): warning CS8621: Nullability of reference types in return type of 'I<object?> C.F<I<object?>>()' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>(F<I<object?>>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<I<object?>>").WithArguments("I<object?> C.F<I<object?>>()", "D<I<object>>").WithLocation(12, 30), // (13,31): warning CS8621: Nullability of reference types in return type of 'I<object> C.F<I<object>>()' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>(F<I<object>>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<I<object>>").WithArguments("I<object> C.F<I<object>>()", "D<I<object?>>").WithLocation(13, 31), // (15,33): warning CS8621: Nullability of reference types in return type of 'IIn<object> C.F<IIn<object>>()' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>(F<IIn<object>>); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<IIn<object>>").WithArguments("IIn<object> C.F<IIn<object>>()", "D<IIn<object?>>").WithLocation(15, 33), // (16,33): warning CS8621: Nullability of reference types in return type of 'IOut<object?> C.F<IOut<object?>>()' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>(F<IOut<object?>>); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<IOut<object?>>").WithArguments("IOut<object?> C.F<IOut<object?>>()", "D<IOut<object>>").WithLocation(16, 33)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_Parameter_01() { var source = @"delegate void D<T>(T t1); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void Main() { // parameter name is different than delegate to ensure that diagnostics refer to the correct names _ = new D<object>((object? t2) => { }); // 1 _ = new D<object?>((object t2) => { }); // 2 _ = new D<I<object>>((I<object?> t2) => { }); // 3 _ = new D<I<object?>>((I<object> t2) => { }); // 4 _ = new D<IIn<object>>((IIn<object?> t2) => { }); // 5 _ = new D<IIn<object?>>((IIn<object> t2) => { }); // 6 _ = new D<IOut<object>>((IOut<object?> t2) => { }); // 7 _ = new D<IOut<object?>>((IOut<object> t2) => { }); // 8 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,40): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<object>'. // _ = new D<object>((object? t2) => { }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<object>").WithLocation(10, 40), // (11,40): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>((object t2) => { }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<object?>").WithLocation(11, 40), // (12,46): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>((I<object?> t2) => { }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<I<object>>").WithLocation(12, 46), // (13,46): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>((I<object> t2) => { }); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<I<object?>>").WithLocation(13, 46), // (14,50): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>((IIn<object?> t2) => { }); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IIn<object>>").WithLocation(14, 50), // (15,50): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>((IIn<object> t2) => { }); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IIn<object?>>").WithLocation(15, 50), // (16,52): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>((IOut<object?> t2) => { }); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IOut<object>>").WithLocation(16, 52), // (17,52): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>((IOut<object> t2) => { }); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IOut<object?>>").WithLocation(17, 52)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_Parameter_02() { var source = @"delegate void D<T>(T t1); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { // parameter name is different than delegate to ensure that diagnostics refer to the correct names static void F<T>(T t2) { } static void Main() { _ = new D<object>(F<object?>); _ = new D<object?>(F<object>); // 1 _ = new D<I<object>>(F<I<object?>>); // 2 _ = new D<I<object?>>(F<I<object>>); // 3 _ = new D<IIn<object>>(F<IIn<object?>>); // 4 _ = new D<IIn<object?>>(F<IIn<object>>); _ = new D<IOut<object>>(F<IOut<object?>>); _ = new D<IOut<object?>>(F<IOut<object>>); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,28): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<object>(object t2)' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>(F<object>); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object>").WithArguments("t2", "void C.F<object>(object t2)", "D<object?>").WithLocation(12, 28), // (13,30): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<I<object?>>(I<object?> t2)' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>(F<I<object?>>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t2", "void C.F<I<object?>>(I<object?> t2)", "D<I<object>>").WithLocation(13, 30), // (14,31): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<I<object>>(I<object> t2)' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>(F<I<object>>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t2", "void C.F<I<object>>(I<object> t2)", "D<I<object?>>").WithLocation(14, 31), // (15,32): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<IIn<object?>>(IIn<object?> t2)' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>(F<IIn<object?>>); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object?>>").WithArguments("t2", "void C.F<IIn<object?>>(IIn<object?> t2)", "D<IIn<object>>").WithLocation(15, 32), // (18,34): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<IOut<object>>(IOut<object> t2)' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>(F<IOut<object>>); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object>>").WithArguments("t2", "void C.F<IOut<object>>(IOut<object> t2)", "D<IOut<object?>>").WithLocation(18, 34)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_OutParameter_01() { var source = @"delegate void D<T>(out T t1); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void Main() { // parameter name is different than delegate to ensure that diagnostics refer to the correct names _ = new D<object>((out object? t2) => t2 = default!); // 1 _ = new D<object?>((out object t2) => t2 = default!); // 2 _ = new D<I<object>>((out I<object?> t2) => t2 = default!); // 3 _ = new D<I<object?>>((out I<object> t2) => t2 = default!); // 4 _ = new D<IIn<object>>((out IIn<object?> t2) => t2 = default!); // 5 _ = new D<IIn<object?>>((out IIn<object> t2) => t2 = default!); // 6 _ = new D<IOut<object>>((out IOut<object?> t2) => t2 = default!); // 7 _ = new D<IOut<object?>>((out IOut<object> t2) => t2 = default!); // 8 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,44): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<object>'. // _ = new D<object>((out object? t2) => t2 = default!); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<object>").WithLocation(10, 44), // (11,44): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>((out object t2) => t2 = default!); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<object?>").WithLocation(11, 44), // (12,50): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>((out I<object?> t2) => t2 = default!); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<I<object>>").WithLocation(12, 50), // (13,50): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>((out I<object> t2) => t2 = default!); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<I<object?>>").WithLocation(13, 50), // (14,54): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>((out IIn<object?> t2) => t2 = default!); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IIn<object>>").WithLocation(14, 54), // (15,54): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>((out IIn<object> t2) => t2 = default!); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IIn<object?>>").WithLocation(15, 54), // (16,56): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>((out IOut<object?> t2) => t2 = default!); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IOut<object>>").WithLocation(16, 56), // (17,56): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>((out IOut<object> t2) => t2 = default!); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IOut<object?>>").WithLocation(17, 56)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_OutParameter_02() { var source = @"delegate void D<T>(out T t1); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { // parameter name is different than delegate to ensure that diagnostics refer to the correct names static void F<T>(out T t2) { t2 = default!; } static void Main() { _ = new D<object>(F<object?>); // 1 _ = new D<object?>(F<object>); _ = new D<I<object>>(F<I<object?>>); // 2 _ = new D<I<object?>>(F<I<object>>); // 3 _ = new D<IIn<object>>(F<IIn<object?>>); _ = new D<IIn<object?>>(F<IIn<object>>); // 4 _ = new D<IOut<object>>(F<IOut<object?>>); // 5 _ = new D<IOut<object?>>(F<IOut<object>>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,27): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<object?>(out object? t2)' doesn't match the target delegate 'D<object>'. // _ = new D<object>(F<object?>); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object?>").WithArguments("t2", "void C.F<object?>(out object? t2)", "D<object>").WithLocation(11, 27), // (13,30): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<I<object?>>(out I<object?> t2)' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>(F<I<object?>>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t2", "void C.F<I<object?>>(out I<object?> t2)", "D<I<object>>").WithLocation(13, 30), // (14,31): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<I<object>>(out I<object> t2)' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>(F<I<object>>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t2", "void C.F<I<object>>(out I<object> t2)", "D<I<object?>>").WithLocation(14, 31), // (16,33): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<IIn<object>>(out IIn<object> t2)' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>(F<IIn<object>>); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object>>").WithArguments("t2", "void C.F<IIn<object>>(out IIn<object> t2)", "D<IIn<object?>>").WithLocation(16, 33), // (17,33): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<IOut<object?>>(out IOut<object?> t2)' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>(F<IOut<object?>>); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object?>>").WithArguments("t2", "void C.F<IOut<object?>>(out IOut<object?> t2)", "D<IOut<object>>").WithLocation(17, 33)); } [Fact] [WorkItem(32563, "https://github.com/dotnet/roslyn/issues/32563")] public void DelegateCreation_InParameter_01() { var source = @"delegate void D<T>(in T t1); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void Main() { // parameter name is different than delegate to ensure that diagnostics refer to the correct names _ = new D<object>((in object? t2) => { }); // 1 _ = new D<object?>((in object t2) => { }); // 2 _ = new D<I<object>>((in I<object?> t2) => { }); // 3 _ = new D<I<object?>>((in I<object> t2) => { }); // 4 _ = new D<IIn<object>>((in IIn<object?> t2) => { }); // 5 _ = new D<IIn<object?>>((in IIn<object> t2) => { }); // 6 _ = new D<IOut<object>>((in IOut<object?> t2) => { }); // 7 _ = new D<IOut<object?>>((in IOut<object> t2) => { }); // 8 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,43): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<object>'. // _ = new D<object>((in object? t2) => { }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<object>").WithLocation(10, 43), // (11,43): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>((in object t2) => { }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<object?>").WithLocation(11, 43), // (12,49): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>((in I<object?> t2) => { }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<I<object>>").WithLocation(12, 49), // (13,49): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>((in I<object> t2) => { }); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<I<object?>>").WithLocation(13, 49), // (14,53): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>((in IIn<object?> t2) => { }); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IIn<object>>").WithLocation(14, 53), // (15,53): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>((in IIn<object> t2) => { }); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IIn<object?>>").WithLocation(15, 53), // (16,55): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>((in IOut<object?> t2) => { }); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IOut<object>>").WithLocation(16, 55), // (17,55): warning CS8622: Nullability of reference types in type of parameter 't2' of 'lambda expression' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>((in IOut<object> t2) => { }); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t2", "lambda expression", "D<IOut<object?>>").WithLocation(17, 55)); } [Fact] [WorkItem(32563, "https://github.com/dotnet/roslyn/issues/32563")] public void DelegateCreation_InParameter_02() { var source = @"delegate void D<T>(in T t1); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { // parameter name is different than delegate to ensure that diagnostics refer to the correct names static void F<T>(in T t2) { } static void Main() { _ = new D<object>(F<object?>); _ = new D<object?>(F<object>); // 1 _ = new D<I<object>>(F<I<object?>>); // 2 _ = new D<I<object?>>(F<I<object>>); // 3 _ = new D<IIn<object>>(F<IIn<object?>>); // 4 _ = new D<IIn<object?>>(F<IIn<object>>); _ = new D<IOut<object>>(F<IOut<object?>>); _ = new D<IOut<object?>>(F<IOut<object>>); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,28): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<object>(in object t2)' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>(F<object>); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object>").WithArguments("t2", "void C.F<object>(in object t2)", "D<object?>").WithLocation(12, 28), // (13,30): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<I<object?>>(in I<object?> t2)' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>(F<I<object?>>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t2", "void C.F<I<object?>>(in I<object?> t2)", "D<I<object>>").WithLocation(13, 30), // (14,31): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<I<object>>(in I<object> t2)' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>(F<I<object>>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t2", "void C.F<I<object>>(in I<object> t2)", "D<I<object?>>").WithLocation(14, 31), // (15,32): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<IIn<object?>>(in IIn<object?> t2)' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>(F<IIn<object?>>); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object?>>").WithArguments("t2", "void C.F<IIn<object?>>(in IIn<object?> t2)", "D<IIn<object>>").WithLocation(15, 32), // (18,34): warning CS8622: Nullability of reference types in type of parameter 't2' of 'void C.F<IOut<object>>(in IOut<object> t2)' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>(F<IOut<object>>); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object>>").WithArguments("t2", "void C.F<IOut<object>>(in IOut<object> t2)", "D<IOut<object?>>").WithLocation(18, 34)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_RefParameter_01() { var source = @"delegate void D<T>(ref T t); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void Main() { _ = new D<object>((ref object? t) => { }); // 1 _ = new D<object?>((ref object t) => { }); // 2 _ = new D<I<object>>((ref I<object?> t) => { }); // 3 _ = new D<I<object?>>((ref I<object> t) => { }); // 4 _ = new D<IIn<object>>((ref IIn<object?> t) => { }); // 5 _ = new D<IIn<object?>>((ref IIn<object> t) => { }); // 6 _ = new D<IOut<object>>((ref IOut<object?> t) => { }); // 7 _ = new D<IOut<object?>>((ref IOut<object> t) => { }); // 8 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,43): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<object>'. // _ = new D<object>((ref object? t) => { }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<object>").WithLocation(9, 43), // (10,43): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>((ref object t) => { }); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<object?>").WithLocation(10, 43), // (11,49): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>((ref I<object?> t) => { }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<I<object>>").WithLocation(11, 49), // (12,49): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>((ref I<object> t) => { }); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<I<object?>>").WithLocation(12, 49), // (13,53): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>((ref IIn<object?> t) => { }); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<IIn<object>>").WithLocation(13, 53), // (14,53): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>((ref IIn<object> t) => { }); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<IIn<object?>>").WithLocation(14, 53), // (15,55): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>((ref IOut<object?> t) => { }); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<IOut<object>>").WithLocation(15, 55), // (16,55): warning CS8622: Nullability of reference types in type of parameter 't' of 'lambda expression' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>((ref IOut<object> t) => { }); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "=>").WithArguments("t", "lambda expression", "D<IOut<object?>>").WithLocation(16, 55)); } [Fact] [WorkItem(32499, "https://github.com/dotnet/roslyn/issues/32499")] public void DelegateCreation_RefParameter_02() { var source = @"delegate void D<T>(ref T t); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F<T>(ref T t) { } static void Main() { _ = new D<object>(F<object?>); // 1 _ = new D<object?>(F<object>); // 2 _ = new D<I<object>>(F<I<object?>>); // 3 _ = new D<I<object?>>(F<I<object>>); // 4 _ = new D<IIn<object>>(F<IIn<object?>>); // 5 _ = new D<IIn<object?>>(F<IIn<object>>); // 6 _ = new D<IOut<object>>(F<IOut<object?>>); // 7 _ = new D<IOut<object?>>(F<IOut<object>>); // 8 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,27): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object?>(ref object? t)' doesn't match the target delegate 'D<object>'. // _ = new D<object>(F<object?>); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object?>").WithArguments("t", "void C.F<object?>(ref object? t)", "D<object>").WithLocation(10, 27), // (11,28): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object>(ref object t)' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>(F<object>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object>").WithArguments("t", "void C.F<object>(ref object t)", "D<object?>").WithLocation(11, 28), // (12,30): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object?>>(ref I<object?> t)' doesn't match the target delegate 'D<I<object>>'. // _ = new D<I<object>>(F<I<object?>>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t", "void C.F<I<object?>>(ref I<object?> t)", "D<I<object>>").WithLocation(12, 30), // (13,31): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object>>(ref I<object> t)' doesn't match the target delegate 'D<I<object?>>'. // _ = new D<I<object?>>(F<I<object>>); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t", "void C.F<I<object>>(ref I<object> t)", "D<I<object?>>").WithLocation(13, 31), // (14,32): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object?>>(ref IIn<object?> t)' doesn't match the target delegate 'D<IIn<object>>'. // _ = new D<IIn<object>>(F<IIn<object?>>); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object?>>").WithArguments("t", "void C.F<IIn<object?>>(ref IIn<object?> t)", "D<IIn<object>>").WithLocation(14, 32), // (15,33): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object>>(ref IIn<object> t)' doesn't match the target delegate 'D<IIn<object?>>'. // _ = new D<IIn<object?>>(F<IIn<object>>); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object>>").WithArguments("t", "void C.F<IIn<object>>(ref IIn<object> t)", "D<IIn<object?>>").WithLocation(15, 33), // (16,33): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object?>>(ref IOut<object?> t)' doesn't match the target delegate 'D<IOut<object>>'. // _ = new D<IOut<object>>(F<IOut<object?>>); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object?>>").WithArguments("t", "void C.F<IOut<object?>>(ref IOut<object?> t)", "D<IOut<object>>").WithLocation(16, 33), // (17,34): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object>>(ref IOut<object> t)' doesn't match the target delegate 'D<IOut<object?>>'. // _ = new D<IOut<object?>>(F<IOut<object>>); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object>>").WithArguments("t", "void C.F<IOut<object>>(ref IOut<object> t)", "D<IOut<object?>>").WithLocation(17, 34)); } [Fact] [WorkItem(37984, "https://github.com/dotnet/roslyn/issues/37984")] public void DelegateCreation_FromCompatibleDelegate() { var source = @" using System; delegate void D(); class C { void M(Action a1, Action? a2, D d1, D? d2) { _ = new D(a1); _ = new D(a2); // 1 _ = new D(a2!); _ = new Action(d1); _ = new Action(d2); // 2 _ = new Action(d2!); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,19): warning CS8601: Possible null reference assignment. // _ = new D(a2); // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "a2").WithLocation(11, 19), // (14,24): warning CS8601: Possible null reference assignment. // _ = new Action(d2); // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "d2").WithLocation(14, 24)); } [Fact] [WorkItem(37984, "https://github.com/dotnet/roslyn/issues/37984")] public void DelegateCreation_FromNullableMismatchedDelegate() { var source = @" using System; delegate void D1(string s); delegate void D2(string? s); class C { void M(Action<string> a1, Action<string?> a2, D1 d1, D2 d2) { _ = new D1(a1); _ = new D1(a2); _ = new D2(a1); // 1 _ = new D2(a1!); _ = new D2(a2); _ = new D1(d1); _ = new D1(d2); _ = new D2(d1); // 2 _ = new D2(d1!); _ = new D2(d2); _ = new Action<string>(d1); _ = new Action<string>(d2); _ = new Action<string?>(d1); // 3 _ = new Action<string?>(d1!); _ = new Action<string?>(d2); _ = new Action<string>(a1); _ = new Action<string>(a2); _ = new Action<string?>(a1); // 4 _ = new Action<string?>(a1!); _ = new Action<string?>(a2); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (13,20): warning CS8622: Nullability of reference types in type of parameter 'obj' of 'void Action<string>.Invoke(string obj)' doesn't match the target delegate 'D2'. // _ = new D2(a1); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "a1").WithArguments("obj", "void Action<string>.Invoke(string obj)", "D2").WithLocation(13, 20), // (19,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'void D1.Invoke(string s)' doesn't match the target delegate 'D2'. // _ = new D2(d1); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "d1").WithArguments("s", "void D1.Invoke(string s)", "D2").WithLocation(19, 20), // (25,33): warning CS8622: Nullability of reference types in type of parameter 's' of 'void D1.Invoke(string s)' doesn't match the target delegate 'Action<string?>'. // _ = new Action<string?>(d1); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "d1").WithArguments("s", "void D1.Invoke(string s)", "System.Action<string?>").WithLocation(25, 33), // (31,33): warning CS8622: Nullability of reference types in type of parameter 'obj' of 'void Action<string>.Invoke(string obj)' doesn't match the target delegate 'Action<string?>'. // _ = new Action<string?>(a1); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "a1").WithArguments("obj", "void Action<string>.Invoke(string obj)", "System.Action<string?>").WithLocation(31, 33)); } [Fact] [WorkItem(37984, "https://github.com/dotnet/roslyn/issues/37984")] public void DelegateCreation_Oblivious() { var source = @" using System; class C { void M(Action<string>? a1) { // even though the delegate is declared in a disabled context, the delegate creation still requires a not-null delegate argument _ = new D1(a1); // 1 _ = new D1(a1!); } } #nullable disable delegate void D1(string s); "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,20): warning CS8601: Possible null reference assignment. // _ = new D1(a1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "a1").WithLocation(9, 20)); } [Fact] [WorkItem(37984, "https://github.com/dotnet/roslyn/issues/37984")] public void DelegateCreation_Errors() { var source = @" using System; delegate void D1(string s); delegate void D2(string? s); class C { void M() { _ = new D1(null); // 1 _ = new D1((Action<string>?)null); // 2 _ = new D1((Action<string>)null!); _ = new D1(default(D1)); // 3 _ = new D1(default(D1)!); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,20): error CS0149: Method name expected // _ = new D1(null); // 1 Diagnostic(ErrorCode.ERR_MethodNameExpected, "null").WithLocation(11, 20), // (12,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // _ = new D1((Action<string>?)null); // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(Action<string>?)null").WithLocation(12, 20), // (14,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // _ = new D1(default(D1)); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default(D1)").WithLocation(14, 20)); } [Fact] [WorkItem(37984, "https://github.com/dotnet/roslyn/issues/37984")] public void DelegateCreation_UpdateArgumentFlowState() { var source = @" using System; delegate void D1(); class C { void M(Action? a) { _ = new D1(a); // 1 a(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (10,20): warning CS8601: Possible null reference assignment. // _ = new D1(a); // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "a").WithLocation(10, 20)); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44129")] public void DelegateCreation_FromMethodGroup_NullabilityAttributes_01() { var source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [return: MaybeNull] public string M1() => null; public void M2([DisallowNull] string? s2) { } } static class Program { static void M3(this C c, [DisallowNull] string? s2) { } static void M() { var c = new C(); _ = new Func<string>(c.M1); // 1 _ = new Action<string?>(c.M2); // 2 _ = new Action<string?>(c.M3); // 3 } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (19,30): warning CS8621: Nullability of reference types in return type of 'string C.M1()' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes). // _ = new Func<string>(c.M1); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "c.M1").WithArguments("string C.M1()", "System.Func<string>").WithLocation(19, 30), // (20,33): warning CS8622: Nullability of reference types in type of parameter 's2' of 'void C.M2(string? s2)' doesn't match the target delegate 'Action<string?>' (possibly because of nullability attributes). // _ = new Action<string?>(c.M2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M2").WithArguments("s2", "void C.M2(string? s2)", "System.Action<string?>").WithLocation(20, 33), // (21,33): warning CS8622: Nullability of reference types in type of parameter 's2' of 'void Program.M3(C c, string? s2)' doesn't match the target delegate 'Action<string?>' (possibly because of nullability attributes). // _ = new Action<string?>(c.M3); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M3").WithArguments("s2", "void Program.M3(C c, string? s2)", "System.Action<string?>").WithLocation(21, 33) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44129")] public void DelegateCreation_FromMethodGroup_NullabilityAttributes_02() { var source = @" using System.Diagnostics.CodeAnalysis; delegate void D1(out string s); delegate bool D2(out string s); delegate void D3(ref string s); class C { public void M1(out string s) => throw null!; public void M2(out string? s) => throw null!; public void M3([MaybeNull] out string s) => throw null!; public bool M4([MaybeNullWhen(false)] out string s) => throw null!; public void M5(ref string s) => throw null!; public void M6([MaybeNull] ref string s) => throw null!; static void M() { var c = new C(); _ = new D1(c.M1); _ = new D1(c.M2); // 1 _ = new D1(c.M3); // 2 _ = new D2(c.M4); // 3 _ = new D3(c.M5); _ = new D3(c.M6); // 4 } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition, MaybeNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (22,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'void C.M2(out string? s)' doesn't match the target delegate 'D1' (possibly because of nullability attributes). // _ = new D1(c.M2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M2").WithArguments("s", "void C.M2(out string? s)", "D1").WithLocation(22, 20), // (23,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'void C.M3(out string s)' doesn't match the target delegate 'D1' (possibly because of nullability attributes). // _ = new D1(c.M3); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M3").WithArguments("s", "void C.M3(out string s)", "D1").WithLocation(23, 20), // (24,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'bool C.M4(out string s)' doesn't match the target delegate 'D2' (possibly because of nullability attributes). // _ = new D2(c.M4); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M4").WithArguments("s", "bool C.M4(out string s)", "D2").WithLocation(24, 20), // (26,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'void C.M6(ref string s)' doesn't match the target delegate 'D3' (possibly because of nullability attributes). // _ = new D3(c.M6); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M6").WithArguments("s", "void C.M6(ref string s)", "D3").WithLocation(26, 20) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44129")] public void DelegateCreation_FromMethodGroup_NullabilityAttributes_03() { var source = @" using System.Diagnostics.CodeAnalysis; delegate void D1([AllowNull] string s); [return: NotNull] delegate string? D2(); class C { public void M1(string s) => throw null!; public void M2(string? s) => throw null!; public string M3() => throw null!; public string? M4() => throw null!; static void M() { var c = new C(); _ = new D1(c.M1); // 1 _ = new D1(c.M2); _ = new D2(c.M3); _ = new D2(c.M4); // 2 } } "; var comp = CreateNullableCompilation(new[] { source, AllowNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (17,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'void C.M1(string s)' doesn't match the target delegate 'D1' (possibly because of nullability attributes). // _ = new D1(c.M1); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M1").WithArguments("s", "void C.M1(string s)", "D1").WithLocation(17, 20), // (20,20): warning CS8621: Nullability of reference types in return type of 'string? C.M4()' doesn't match the target delegate 'D2' (possibly because of nullability attributes). // _ = new D2(c.M4); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "c.M4").WithArguments("string? C.M4()", "D2").WithLocation(20, 20) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44129")] public void DelegateCreation_FromMethodGroup_NullabilityAttributes_04() { var source = @" using System; using System.Diagnostics.CodeAnalysis; class C { [return: MaybeNull] public string M1() => null; public string M2() => """"; public void M3([DisallowNull] object? s2) { } public void M4(object? s2) { } } static class Program { [return: MaybeNull] static string M5(this C c) => null; static string M6(this C c) => """"; static void M7(this C c, [DisallowNull] object? s2) { } static void M8(this C c, object? s2) { } static void M() { var c = new C(); _ = new Func<object>(c.M1); // 1 _ = new Func<object?>(c.M1); _ = new Func<object>(c.M2); _ = new Func<object?>(c.M2); _ = new Action<string>(c.M3); _ = new Action<string?>(c.M3); // 2 _ = new Action<string>(c.M4); _ = new Action<string?>(c.M4); _ = new Func<object>(c.M5); // 3 _ = new Func<object?>(c.M5); _ = new Func<object>(c.M6); _ = new Func<object?>(c.M6); _ = new Action<string>(c.M7); _ = new Action<string?>(c.M7); // 4 _ = new Action<string>(c.M8); _ = new Action<string?>(c.M8); } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (27,30): warning CS8621: Nullability of reference types in return type of 'string C.M1()' doesn't match the target delegate 'Func<object>' (possibly because of nullability attributes). // _ = new Func<object>(c.M1); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "c.M1").WithArguments("string C.M1()", "System.Func<object>").WithLocation(27, 30), // (33,33): warning CS8622: Nullability of reference types in type of parameter 's2' of 'void C.M3(object? s2)' doesn't match the target delegate 'Action<string?>' (possibly because of nullability attributes). // _ = new Action<string?>(c.M3); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M3").WithArguments("s2", "void C.M3(object? s2)", "System.Action<string?>").WithLocation(33, 33), // (37,30): warning CS8621: Nullability of reference types in return type of 'string Program.M5(C c)' doesn't match the target delegate 'Func<object>' (possibly because of nullability attributes). // _ = new Func<object>(c.M5); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "c.M5").WithArguments("string Program.M5(C c)", "System.Func<object>").WithLocation(37, 30), // (43,33): warning CS8622: Nullability of reference types in type of parameter 's2' of 'void Program.M7(C c, object? s2)' doesn't match the target delegate 'Action<string?>' (possibly because of nullability attributes). // _ = new Action<string?>(c.M7); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "c.M7").WithArguments("s2", "void Program.M7(C c, object? s2)", "System.Action<string?>").WithLocation(43, 33) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44129")] public void DelegateCreation_FromExtensionMethodGroup_BadParameterCount() { var source = @" using System; using System.Diagnostics.CodeAnalysis; class C { } static class Program { static void M3(this C c, [DisallowNull] string? s2) { } static void M() { var c = new C(); _ = new Action<string?, string>(c.M3); // 1 _ = new Action(c.M3); // 2 } } "; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,13): error CS0123: No overload for 'M3' matches delegate 'Action<string?, string>' // _ = new Action<string?, string>(c.M3); // 1 Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Action<string?, string>(c.M3)").WithArguments("M3", "System.Action<string?, string>").WithLocation(15, 13), // (16,13): error CS0123: No overload for 'M3' matches delegate 'Action' // _ = new Action(c.M3); // 2 Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "new Action(c.M3)").WithArguments("M3", "System.Action").WithLocation(16, 13) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44129")] public void DelegateCreation_FromMethodGroup_MaybeNullReturn() { var source = @" using System; using System.Diagnostics.CodeAnalysis; public static class D { [return: MaybeNull] public static string FirstOrDefault(this string[] e) => e.Length > 0 ? e[0] : null; public static void Main() { var e = new string[0]; Func<string> f = e.FirstOrDefault; // 1 f().ToString(); } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,26): warning CS8621: Nullability of reference types in return type of 'string D.FirstOrDefault(string[] e)' doesn't match the target delegate 'Func<string>' (possibly because of nullability attributes). // Func<string> f = e.FirstOrDefault; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "e.FirstOrDefault").WithArguments("string D.FirstOrDefault(string[] e)", "System.Func<string>").WithLocation(13, 26) ); } [Fact] [WorkItem(46977, "https://github.com/dotnet/roslyn/issues/46977")] public void DelegateCreation_FromMethodGroup_ReadonlyRefCovariance_01() { var source = @" delegate ref readonly T D<T>(); class C { void M() { D<string> d1 = M1; D<string?> d2 = M1; D<string> d3 = M2; // 1 D<string?> d4 = M2; _ = new D<string>(d1); _ = new D<string?>(d1); _ = new D<string>(d2); // 2 _ = new D<string?>(d2); D<string> d5 = d1; D<string?> d6 = d1; // 3 D<string> d7 = d2; // 4 D<string?> d8 = d2; } ref readonly string M1() => throw null!; ref readonly string? M2() => throw null!; }"; // Note: strictly speaking we don't need to warn on 3, but it would require a // change to nullable reference conversion analysis which special cases delegates. var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (10,24): warning CS8621: Nullability of reference types in return type of 'ref readonly string? C.M2()' doesn't match the target delegate 'D<string>' (possibly because of nullability attributes). // D<string> d3 = M2; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M2").WithArguments("ref readonly string? C.M2()", "D<string>").WithLocation(10, 24), // (15,27): warning CS8621: Nullability of reference types in return type of 'ref readonly string? D<string?>.Invoke()' doesn't match the target delegate 'D<string>' (possibly because of nullability attributes). // _ = new D<string>(d2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "d2").WithArguments("ref readonly string? D<string?>.Invoke()", "D<string>").WithLocation(15, 27), // (19,25): warning CS8619: Nullability of reference types in value of type 'D<string>' doesn't match target type 'D<string?>'. // D<string?> d6 = d1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "d1").WithArguments("D<string>", "D<string?>").WithLocation(19, 25), // (20,24): warning CS8619: Nullability of reference types in value of type 'D<string?>' doesn't match target type 'D<string>'. // D<string> d7 = d2; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "d2").WithArguments("D<string?>", "D<string>").WithLocation(20, 24) ); } [Fact] [WorkItem(46977, "https://github.com/dotnet/roslyn/issues/46977")] public void DelegateCreation_FromMethodGroup_ReadonlyRefCovariance_02() { var source = @" delegate ref readonly string D1(); delegate ref readonly string? D2(); class C { void M() { D1 d1 = M1; D2 d2 = M1; D1 d3 = M2; // 1 D2 d4 = M2; _ = new D1(d1); _ = new D2(d1); _ = new D1(d2); // 2 _ = new D2(d2); } ref readonly string M1() => throw null!; ref readonly string? M2() => throw null!; }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,17): warning CS8621: Nullability of reference types in return type of 'ref readonly string? C.M2()' doesn't match the target delegate 'D1' (possibly because of nullability attributes). // D1 d3 = M2; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M2").WithArguments("ref readonly string? C.M2()", "D1").WithLocation(11, 17), // (16,20): warning CS8621: Nullability of reference types in return type of 'ref readonly string? D2.Invoke()' doesn't match the target delegate 'D1' (possibly because of nullability attributes). // _ = new D1(d2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "d2").WithArguments("ref readonly string? D2.Invoke()", "D1").WithLocation(16, 20) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44174")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_01() { var source = @" using System; using System.Diagnostics.CodeAnalysis; public class C { public Func<string?, string?> M1() { return Helper.Method; } public Func<string, string> M2() { return Helper.Method; } public Func<string, string?> M3() { return Helper.Method; } public Func<string?, string> M4() { return Helper.Method; // 1 } public Func< #nullable disable string, #nullable enable string> M5() { return Helper.Method; } } static class Helper { [return: NotNullIfNotNull(""arg"")] public static string? Method(string? arg) => arg; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (24,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method(string? arg)' doesn't match the target delegate 'Func<string?, string>' (possibly because of nullability attributes). // return Helper.Method; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method").WithArguments("string? Helper.Method(string? arg)", "System.Func<string?, string>").WithLocation(24, 16) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44174")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_02() { var source = @" using System.Diagnostics.CodeAnalysis; public delegate void D1(string? x, out string? y); public delegate void D2(string x, out string y); public delegate void D3(string x, out string? y); public delegate void D4(string? x, out string y); public delegate void D5( #nullable disable string x, #nullable enable out string y); public delegate void D6(string? x, out string? y, out string? z); public delegate void D7(string x, out string? y, out string z); public delegate void D8(string x, out string y, out string z); public delegate void D9(string? x, out string y, out string z); public class C { public D1 M1() { return Helper.Method1; } public D2 M2() { return Helper.Method1; } public D3 M3() { return Helper.Method1; } public D4 M4() { return Helper.Method1; // 1 } public D5 M5() { return Helper.Method1; } public D6 M6() { return Helper.Method2; } public D7 M7() { return Helper.Method2; // 2 } public D8 M8() { return Helper.Method3; } public D9 M9() { return Helper.Method3; // 3, 4 } } static class Helper { public static void Method1(string? x, [NotNullIfNotNull(""x"")] out string? y) { y = x; } public static void Method2(string? x, [NotNullIfNotNull(""x"")] out string? y, [NotNullIfNotNull(""y"")] out string? z) { z = y = x; } public static void Method3(string? x, [NotNullIfNotNull(""x"")] out string? y, [NotNullIfNotNull(""x"")] out string? z) { z = y = x; } } "; // Diagnostic 2 is verifying something a bit esoteric: non-nullability of 'x' does not propagate to 'z'. var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (34,16): warning CS8622: Nullability of reference types in type of parameter 'y' of 'void Helper.Method1(string? x, out string? y)' doesn't match the target delegate 'D4' (possibly because of nullability attributes). // return Helper.Method1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Helper.Method1").WithArguments("y", "void Helper.Method1(string? x, out string? y)", "D4").WithLocation(34, 16), // (46,16): warning CS8622: Nullability of reference types in type of parameter 'z' of 'void Helper.Method2(string? x, out string? y, out string? z)' doesn't match the target delegate 'D7' (possibly because of nullability attributes). // return Helper.Method2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Helper.Method2").WithArguments("z", "void Helper.Method2(string? x, out string? y, out string? z)", "D7").WithLocation(46, 16), // (54,16): warning CS8622: Nullability of reference types in type of parameter 'y' of 'void Helper.Method3(string? x, out string? y, out string? z)' doesn't match the target delegate 'D9' (possibly because of nullability attributes). // return Helper.Method3; // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Helper.Method3").WithArguments("y", "void Helper.Method3(string? x, out string? y, out string? z)", "D9").WithLocation(54, 16), // (54,16): warning CS8622: Nullability of reference types in type of parameter 'z' of 'void Helper.Method3(string? x, out string? y, out string? z)' doesn't match the target delegate 'D9' (possibly because of nullability attributes). // return Helper.Method3; // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Helper.Method3").WithArguments("z", "void Helper.Method3(string? x, out string? y, out string? z)", "D9").WithLocation(54, 16) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44174")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_03() { var source = @" using System; using System.Diagnostics.CodeAnalysis; public class C { public Func<string, string> M1() { return Helper.Method1<string?>; } public Func<string, string?> M2() { return Helper.Method1<string?>; } public Func<string?, string> M3() { return Helper.Method1<string?>; // 1 } public Func<string?, string?> M4() { return Helper.Method1<string?>; } public Func<T, T> M5<T>() { return Helper.Method1<T?>; // 2 } public Func<T, T?> M6<T>() { return Helper.Method1<T?>; } public Func<T?, T> M7<T>() { return Helper.Method1<T?>; // 3 } public Func<T?, T?> M8<T>() { return Helper.Method1<T?>; } } static class Helper { [return: NotNullIfNotNull(""t"")] public static T Method1<T>(T t) => t; } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (15,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1<string?>(string? t)' doesn't match the target delegate 'Func<string?, string>' (possibly because of nullability attributes). // return Helper.Method1<string?>; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1<string?>").WithArguments("string? Helper.Method1<string?>(string? t)", "System.Func<string?, string>").WithLocation(15, 16), // (23,16): warning CS8621: Nullability of reference types in return type of 'T? Helper.Method1<T?>(T? t)' doesn't match the target delegate 'Func<T, T>' (possibly because of nullability attributes). // return Helper.Method1<T?>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1<T?>").WithArguments("T? Helper.Method1<T?>(T? t)", "System.Func<T, T>").WithLocation(23, 16), // (31,16): warning CS8621: Nullability of reference types in return type of 'T? Helper.Method1<T?>(T? t)' doesn't match the target delegate 'Func<T?, T>' (possibly because of nullability attributes). // return Helper.Method1<T?>; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1<T?>").WithArguments("T? Helper.Method1<T?>(T? t)", "System.Func<T?, T>").WithLocation(31, 16) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44174")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_04() { var source = @" using System.Diagnostics.CodeAnalysis; public delegate void Del<T1, T2, T3>(T1 x, T2 y, out T3 z); public class C { public Del<string, string, string> M1() { return Helper.Method1; } public Del<string, string, string?> M2() { return Helper.Method1; } public Del<string, string?, string> M3() { return Helper.Method1; } public Del<string?, string, string> M4() { return Helper.Method1; } public Del<string?, string?, string> M5() { return Helper.Method1; // 1 } public Del<string?, string?, string?> M6() { return Helper.Method1; } } static class Helper { public static void Method1(string? x, string? y, [NotNullIfNotNull(""x""), NotNullIfNotNull(""y"")] out string? z) { z = x ?? y; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (24,16): warning CS8622: Nullability of reference types in type of parameter 'z' of 'void Helper.Method1(string? x, string? y, out string? z)' doesn't match the target delegate 'Del<string?, string?, string>' (possibly because of nullability attributes). // return Helper.Method1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Helper.Method1").WithArguments("z", "void Helper.Method1(string? x, string? y, out string? z)", "Del<string?, string?, string>").WithLocation(24, 16) ); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44174")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_05() { var source = @" using System; using System.Diagnostics.CodeAnalysis; public class C { public Func<string, string, string> M1() { return Helper.Method1; } public Func<string, string, string?> M2() { return Helper.Method1; } public Func<string, string?, string> M3() { return Helper.Method1; } public Func<string?, string, string> M4() { return Helper.Method1; } public Func<string?, string?, string> M5() { return Helper.Method1; // 1 } public Func<string?, string?, string?> M6() { return Helper.Method1; } } static class Helper { [return: NotNullIfNotNull(""x""), NotNullIfNotNull(""y"")] public static string? Method1(string? x, string? y) { return x ?? y; } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (23,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1(string? x, string? y)' doesn't match the target delegate 'Func<string?, string?, string>' (possibly because of nullability attributes). // return Helper.Method1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1").WithArguments("string? Helper.Method1(string? x, string? y)", "System.Func<string?, string?, string>").WithLocation(23, 16) ); } [Fact] [WorkItem(49865, "https://github.com/dotnet/roslyn/issues/49865")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_06() { var source = @" using System; using System.Diagnostics.CodeAnalysis; public class C { public Func<T, string> M1<T>() { return Helper.Method1; // 1 } public Func<T, string> M2<T>() where T : notnull { return Helper.Method1; } public Func<T, string> M3<T>() where T : class { return Helper.Method1; } public Func<T, string> M4<T>() where T : class? { return Helper.Method1; // 2 } public Func<T, string> M5<T>() where T : struct { return Helper.Method1; } public Func<T?, string> M6<T>() { return Helper.Method1; // 3 } } static class Helper { [return: NotNullIfNotNull(""t"")] public static string? Method1<T>(T t) { return t?.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (7,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1<T>(T t)' doesn't match the target delegate 'Func<T, string>' (possibly because of nullability attributes). // return Helper.Method1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1").WithArguments("string? Helper.Method1<T>(T t)", "System.Func<T, string>").WithLocation(7, 16), // (19,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1<T>(T t)' doesn't match the target delegate 'Func<T, string>' (possibly because of nullability attributes). // return Helper.Method1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1").WithArguments("string? Helper.Method1<T>(T t)", "System.Func<T, string>").WithLocation(19, 16), // (28,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1<T?>(T? t)' doesn't match the target delegate 'Func<T?, string>' (possibly because of nullability attributes). // return Helper.Method1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1").WithArguments("string? Helper.Method1<T?>(T? t)", "System.Func<T?, string>").WithLocation(28, 16)); } [Fact] [WorkItem(49865, "https://github.com/dotnet/roslyn/issues/49865")] public void DelegateCreation_FromMethodGroup_NotNullIfNotNull_07() { var source = @" using System.Diagnostics.CodeAnalysis; public class C { public D1<T> M1<T>() { return Helper.Method1; // 1 } public D2<T> M2<T>() { return Helper.Method1; // 2 } public D3<T> M3<T>() { return Helper.Method1; } } public delegate string D1<T>(T t); public delegate string D2<T>(T? t); public delegate string D3<T>([DisallowNull] T t); static class Helper { [return: NotNullIfNotNull(""t"")] public static string? Method1<T>(T t) { return t?.ToString(); } } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }); comp.VerifyDiagnostics( // (6,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1<T>(T t)' doesn't match the target delegate 'D1<T>' (possibly because of nullability attributes). // return Helper.Method1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1").WithArguments("string? Helper.Method1<T>(T t)", "D1<T>").WithLocation(6, 16), // (10,16): warning CS8621: Nullability of reference types in return type of 'string? Helper.Method1<T?>(T? t)' doesn't match the target delegate 'D2<T>' (possibly because of nullability attributes). // return Helper.Method1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Helper.Method1").WithArguments("string? Helper.Method1<T?>(T? t)", "D2<T>").WithLocation(10, 16)); } [Fact] [WorkItem(44129, "https://github.com/dotnet/roslyn/issues/44174")] public void NotNullIfNotNull_Override() { var source = @" using System.Diagnostics.CodeAnalysis; abstract class Base1 { public abstract string? Method(string? arg); } class Derived1 : Base1 { [return: NotNullIfNotNull(""arg"")] public override string? Method(string? arg) => arg; } abstract class Base2 { public abstract string Method(string arg); } class Derived2 : Base2 { [return: NotNullIfNotNull(""arg"")] public override string? Method(string? arg) => arg; } abstract class Base3 { public abstract string? Method(string arg); } class Derived3 : Base3 { [return: NotNullIfNotNull(""arg"")] public override string? Method(string? arg) => arg; } abstract class Base4 { public abstract string Method(string? arg); } class Derived4 : Base4 { [return: NotNullIfNotNull(""arg"")] public override string? Method(string? arg) => arg; // 1 } "; var comp = CreateNullableCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }); comp.VerifyDiagnostics( // (37,29): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override string? Method(string? arg) => arg; // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "Method").WithLocation(37, 29) ); } [Fact] public void IdentityConversion_DelegateReturnType() { var source = @"delegate T D<T>(); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>() => throw new System.Exception(); static void G() { D<object> a = F<object?>; D<object?> b = F<object>; D<I<object>> c = F<I<object?>>; D<I<object?>> d = F<I<object>>; D<IIn<object>> e = F<IIn<object?>>; D<IIn<object?>> f = F<IIn<object>>; D<IOut<object>> g = F<IOut<object?>>; D<IOut<object?>> h = F<IOut<object>>; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,23): warning CS8621: Nullability of reference types in return type of 'object? C.F<object?>()' doesn't match the target delegate 'D<object>'. // D<object> a = F<object?>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<object?>").WithArguments("object? C.F<object?>()", "D<object>").WithLocation(10, 23), // (12,26): warning CS8621: Nullability of reference types in return type of 'I<object?> C.F<I<object?>>()' doesn't match the target delegate 'D<I<object>>'. // D<I<object>> c = F<I<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<I<object?>>").WithArguments("I<object?> C.F<I<object?>>()", "D<I<object>>").WithLocation(12, 26), // (13,27): warning CS8621: Nullability of reference types in return type of 'I<object> C.F<I<object>>()' doesn't match the target delegate 'D<I<object?>>'. // D<I<object?>> d = F<I<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<I<object>>").WithArguments("I<object> C.F<I<object>>()", "D<I<object?>>").WithLocation(13, 27), // (15,29): warning CS8621: Nullability of reference types in return type of 'IIn<object> C.F<IIn<object>>()' doesn't match the target delegate 'D<IIn<object?>>'. // D<IIn<object?>> f = F<IIn<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<IIn<object>>").WithArguments("IIn<object> C.F<IIn<object>>()", "D<IIn<object?>>").WithLocation(15, 29), // (16,29): warning CS8621: Nullability of reference types in return type of 'IOut<object?> C.F<IOut<object?>>()' doesn't match the target delegate 'D<IOut<object>>'. // D<IOut<object>> g = F<IOut<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F<IOut<object?>>").WithArguments("IOut<object?> C.F<IOut<object?>>()", "D<IOut<object>>").WithLocation(16, 29)); } [Fact] public void IdentityConversion_DelegateParameter_01() { var source = @"delegate void D<T>(T t); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F<T>(T t) { } static void G() { D<object> a = F<object?>; D<object?> b = F<object>; D<I<object>> c = F<I<object?>>; D<I<object?>> d = F<I<object>>; D<IIn<object>> e = F<IIn<object?>>; D<IIn<object?>> f = F<IIn<object>>; D<IOut<object>> g = F<IOut<object?>>; D<IOut<object?>> h = F<IOut<object>>; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,24): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object>(object t)' doesn't match the target delegate 'D<object?>'. // D<object?> b = F<object>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object>").WithArguments("t", "void C.F<object>(object t)", "D<object?>").WithLocation(11, 24), // (12,26): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object?>>(I<object?> t)' doesn't match the target delegate 'D<I<object>>'. // D<I<object>> c = F<I<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t", "void C.F<I<object?>>(I<object?> t)", "D<I<object>>").WithLocation(12, 26), // (13,27): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object>>(I<object> t)' doesn't match the target delegate 'D<I<object?>>'. // D<I<object?>> d = F<I<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t", "void C.F<I<object>>(I<object> t)", "D<I<object?>>").WithLocation(13, 27), // (14,28): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object?>>(IIn<object?> t)' doesn't match the target delegate 'D<IIn<object>>'. // D<IIn<object>> e = F<IIn<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object?>>").WithArguments("t", "void C.F<IIn<object?>>(IIn<object?> t)", "D<IIn<object>>").WithLocation(14, 28), // (17,30): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object>>(IOut<object> t)' doesn't match the target delegate 'D<IOut<object?>>'. // D<IOut<object?>> h = F<IOut<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object>>").WithArguments("t", "void C.F<IOut<object>>(IOut<object> t)", "D<IOut<object?>>").WithLocation(17, 30)); } [Fact] [WorkItem(29844, "https://github.com/dotnet/roslyn/issues/29844")] public void IdentityConversion_DelegateParameter_02() { var source = @"delegate T D<T>(); class A<T> { internal T M() => throw new System.NotImplementedException(); } class B { static A<T> F<T>(T t) => throw null!; static void G(object? o) { var x = F(o); D<object?> d = x.M; D<object> e = x.M; // 1 if (o == null) return; var y = F(o); d = y.M; e = y.M; d = (D<object?>)y.M; e = (D<object>)y.M; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,23): warning CS8621: Nullability of reference types in return type of 'object? A<object?>.M()' doesn't match the target delegate 'D<object>'. // D<object> e = x.M; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.M").WithArguments("object? A<object?>.M()", "D<object>").WithLocation(13, 23)); } [Fact] [WorkItem(29844, "https://github.com/dotnet/roslyn/issues/29844")] public void IdentityConversion_DelegateOutParameter() { var source = @"delegate void D<T>(out T t); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F<T>(out T t) { t = default!; } static void G() { D<object> a = F<object?>; D<object?> b = F<object>; D<I<object>> c = F<I<object?>>; D<I<object?>> d = F<I<object>>; D<IIn<object>> e = F<IIn<object?>>; D<IIn<object?>> f = F<IIn<object>>; D<IOut<object>> g = F<IOut<object?>>; D<IOut<object?>> h = F<IOut<object>>; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,23): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object?>(out object? t)' doesn't match the target delegate 'D<object>'. // D<object> a = F<object?>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object?>").WithArguments("t", "void C.F<object?>(out object? t)", "D<object>").WithLocation(10, 23), // (12,26): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object?>>(out I<object?> t)' doesn't match the target delegate 'D<I<object>>'. // D<I<object>> c = F<I<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t", "void C.F<I<object?>>(out I<object?> t)", "D<I<object>>").WithLocation(12, 26), // (13,27): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object>>(out I<object> t)' doesn't match the target delegate 'D<I<object?>>'. // D<I<object?>> d = F<I<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t", "void C.F<I<object>>(out I<object> t)", "D<I<object?>>").WithLocation(13, 27), // (15,29): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object>>(out IIn<object> t)' doesn't match the target delegate 'D<IIn<object?>>'. // D<IIn<object?>> f = F<IIn<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object>>").WithArguments("t", "void C.F<IIn<object>>(out IIn<object> t)", "D<IIn<object?>>").WithLocation(15, 29), // (16,29): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object?>>(out IOut<object?> t)' doesn't match the target delegate 'D<IOut<object>>'. // D<IOut<object>> g = F<IOut<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object?>>").WithArguments("t", "void C.F<IOut<object?>>(out IOut<object?> t)", "D<IOut<object>>").WithLocation(16, 29) ); } [Fact] [WorkItem(32563, "https://github.com/dotnet/roslyn/issues/32563")] public void IdentityConversion_DelegateInParameter() { var source = @"delegate void D<T>(in T t); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F<T>(in T t) { } static void G() { D<object> a = F<object?>; D<object?> b = F<object>; D<I<object>> c = F<I<object?>>; D<I<object?>> d = F<I<object>>; D<IIn<object>> e = F<IIn<object?>>; D<IIn<object?>> f = F<IIn<object>>; D<IOut<object>> g = F<IOut<object?>>; D<IOut<object?>> h = F<IOut<object>>; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,24): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object>(in object t)' doesn't match the target delegate 'D<object?>'. // D<object?> b = F<object>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object>").WithArguments("t", "void C.F<object>(in object t)", "D<object?>").WithLocation(11, 24), // (12,26): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object?>>(in I<object?> t)' doesn't match the target delegate 'D<I<object>>'. // D<I<object>> c = F<I<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t", "void C.F<I<object?>>(in I<object?> t)", "D<I<object>>").WithLocation(12, 26), // (13,27): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object>>(in I<object> t)' doesn't match the target delegate 'D<I<object?>>'. // D<I<object?>> d = F<I<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t", "void C.F<I<object>>(in I<object> t)", "D<I<object?>>").WithLocation(13, 27), // (14,28): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object?>>(in IIn<object?> t)' doesn't match the target delegate 'D<IIn<object>>'. // D<IIn<object>> e = F<IIn<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object?>>").WithArguments("t", "void C.F<IIn<object?>>(in IIn<object?> t)", "D<IIn<object>>").WithLocation(14, 28), // (17,30): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object>>(in IOut<object> t)' doesn't match the target delegate 'D<IOut<object?>>'. // D<IOut<object?>> h = F<IOut<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object>>").WithArguments("t", "void C.F<IOut<object>>(in IOut<object> t)", "D<IOut<object?>>").WithLocation(17, 30) ); } [Fact] public void IdentityConversion_DelegateRefParameter() { var source = @"delegate void D<T>(ref T t); interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F<T>(ref T t) { } static void G() { D<object> a = F<object?>; D<object?> b = F<object>; D<I<object>> c = F<I<object?>>; D<I<object?>> d = F<I<object>>; D<IIn<object>> e = F<IIn<object?>>; D<IIn<object?>> f = F<IIn<object>>; D<IOut<object>> g = F<IOut<object?>>; D<IOut<object?>> h = F<IOut<object>>; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,23): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object?>(ref object? t)' doesn't match the target delegate 'D<object>'. // D<object> a = F<object?>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object?>").WithArguments("t", "void C.F<object?>(ref object? t)", "D<object>").WithLocation(10, 23), // (11,24): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<object>(ref object t)' doesn't match the target delegate 'D<object?>'. // D<object?> b = F<object>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<object>").WithArguments("t", "void C.F<object>(ref object t)", "D<object?>").WithLocation(11, 24), // (12,26): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object?>>(ref I<object?> t)' doesn't match the target delegate 'D<I<object>>'. // D<I<object>> c = F<I<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object?>>").WithArguments("t", "void C.F<I<object?>>(ref I<object?> t)", "D<I<object>>").WithLocation(12, 26), // (13,27): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<I<object>>(ref I<object> t)' doesn't match the target delegate 'D<I<object?>>'. // D<I<object?>> d = F<I<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<I<object>>").WithArguments("t", "void C.F<I<object>>(ref I<object> t)", "D<I<object?>>").WithLocation(13, 27), // (14,28): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object?>>(ref IIn<object?> t)' doesn't match the target delegate 'D<IIn<object>>'. // D<IIn<object>> e = F<IIn<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object?>>").WithArguments("t", "void C.F<IIn<object?>>(ref IIn<object?> t)", "D<IIn<object>>").WithLocation(14, 28), // (15,29): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IIn<object>>(ref IIn<object> t)' doesn't match the target delegate 'D<IIn<object?>>'. // D<IIn<object?>> f = F<IIn<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IIn<object>>").WithArguments("t", "void C.F<IIn<object>>(ref IIn<object> t)", "D<IIn<object?>>").WithLocation(15, 29), // (16,29): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object?>>(ref IOut<object?> t)' doesn't match the target delegate 'D<IOut<object>>'. // D<IOut<object>> g = F<IOut<object?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object?>>").WithArguments("t", "void C.F<IOut<object?>>(ref IOut<object?> t)", "D<IOut<object>>").WithLocation(16, 29), // (17,30): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C.F<IOut<object>>(ref IOut<object> t)' doesn't match the target delegate 'D<IOut<object?>>'. // D<IOut<object?>> h = F<IOut<object>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F<IOut<object>>").WithArguments("t", "void C.F<IOut<object>>(ref IOut<object> t)", "D<IOut<object?>>").WithLocation(17, 30)); } [Fact] public void Base_01() { CSharpCompilation c = CreateCompilation(new[] { @" class Base { public virtual void Test() {} } class C : Base { static void Main() { } public override void Test() { base.Test(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void Base_02() { var source0 = @"public abstract class A<T> { } public class B<T> : A<T?> where T : B<T> { }"; var comp0 = CreateCompilation(source0, options: WithNullableEnable()); comp0.VerifyDiagnostics(); CompileAndVerify(comp0, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var b = m.GlobalNamespace.GetTypeMember("B"); Assert.Equal("A<T?>", b.BaseTypeNoUseSiteDiagnostics.ToTestDisplayString(true)); } } [Fact] public void Base_03() { var source0 = @"public abstract class A<T> { } public class B<T> : A<T> where T : B<T> { }"; var comp0 = CreateCompilation(source0, options: WithNullableEnable()); comp0.VerifyDiagnostics(); CompileAndVerify(comp0, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var b = m.GlobalNamespace.GetTypeMember("B"); Assert.Equal("A<T!>", b.BaseTypeNoUseSiteDiagnostics.ToTestDisplayString(true)); } } [Fact] public void TypeOf_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(System.Type x1) { x1 = typeof(C); } void Test2(System.Type x2) { x2 = typeof(C) ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] [WorkItem(29894, "https://github.com/dotnet/roslyn/issues/29894")] public void TypeOf_02() { CSharpCompilation c = CreateCompilation(new[] { @" class List<T> { } class C<T, TClass, TStruct> where TClass : class where TStruct : struct { void M() { _ = typeof(C<int, object, int>?); _ = typeof(T?); _ = typeof(TClass?); _ = typeof(TStruct?); _ = typeof(List<T?>); _ = typeof(List<TClass?>); _ = typeof(List<TStruct?>); } } " }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); c.VerifyDiagnostics( // (9,13): error CS8639: The typeof operator cannot be used on a nullable reference type // _ = typeof(C<int, object, int>?); Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(C<int, object, int>?)").WithLocation(9, 13), // (10,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // _ = typeof(T?); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(10, 20), // (11,13): error CS8639: The typeof operator cannot be used on a nullable reference type // _ = typeof(TClass?); Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(TClass?)").WithLocation(11, 13), // (13,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // _ = typeof(List<T?>); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(13, 25)); } [Fact] public void Default_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(C x1) { x1 = default(C); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = default(C); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(C)").WithLocation(10, 14) ); } [Fact] public void Default_NonNullable() { var source = @"class C { static void Main() { var s = default(string); s.ToString(); var i = default(int); i.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("System.Int32", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.NotAnnotated, symbol.TypeWithAnnotations.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, symbol.GetPublicSymbol().NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, symbol.GetPublicSymbol().Type.NullableAnnotation); } [Fact] public void Default_Nullable() { var source = @"class C { static void Main() { var s = default(string?); s.ToString(); var i = default(int?); i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("System.Int32?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Default_TUnconstrained() { var source = @"class C { static void F<T>() { var s = default(T); s.ToString(); var t = default(T?); t.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9), // (7,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // var t = default(T?); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 25), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(8, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("T?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("T?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void Default_TClass() { var source = @"class C { static void F<T>() where T : class { var s = default(T); s.ToString(); var t = default(T?); t.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(8, 9)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("T?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("T?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void DefaultInferred_NonNullable() { var source = @"class C { static void Main() { string s = default; s.ToString(); int i = default; i.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // string s = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(5, 20), // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String!", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.NotAnnotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("System.Int32", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.NotAnnotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void DefaultInferred_Nullable() { var source = @"class C { static void Main() { string? s = default; s.ToString(); int? i = default; i.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("System.String?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("System.Int32?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void DefaultInferred_TUnconstrained() { var source = @"class C { static void F<T>() { T s = default; s.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9) ); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("T", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.NotAnnotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] public void DefaultInferred_TClass() { var source = @"class C { static void F<T>() where T : class { T s = default; s.ToString(); T? t = default; t.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T s = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(5, 15), // (6,9): warning CS8602: Dereference of a possibly null reference. // s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(8, 9)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarators = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); var symbol = model.GetDeclaredSymbol(declarators[0]).GetSymbol<LocalSymbol>(); Assert.Equal("T!", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.NotAnnotated, symbol.TypeWithAnnotations.NullableAnnotation); symbol = model.GetDeclaredSymbol(declarators[1]).GetSymbol<LocalSymbol>(); Assert.Equal("T?", symbol.TypeWithAnnotations.ToTestDisplayString(true)); Assert.Equal(NullableAnnotation.Annotated, symbol.TypeWithAnnotations.NullableAnnotation); } [Fact] [WorkItem(29896, "https://github.com/dotnet/roslyn/issues/29618")] public void DeconstructionTypeInference() { var source = @"class C { static void F((object? a, object? b) t) { if (t.b == null) return; object? x; object? y; (x, y) = t; x.ToString(); y.ToString(); } static void F(object? a, object? b) { if (b == null) return; object? x; object? y; (x, y) = (a, b); x.ToString(); y.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(18, 9)); } [Fact] public void IdentityConversion_DeconstructionAssignment() { var source = @"interface IIn<in T> { } interface IOut<out T> { } class C<T> { void Deconstruct(out IIn<T> x, out IOut<T> y) { throw new System.NotImplementedException(); } static void F(C<object> c) { IIn<object?> x; IOut<object?> y; (x, y) = c; } static void G(C<object?> c) { IIn<object> x; IOut<object> y; (x, y) = c; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,10): warning CS8624: Argument of type 'IIn<object?>' cannot be used as an output of type 'IIn<object>' for parameter 'x' in 'void C<object>.Deconstruct(out IIn<object> x, out IOut<object> y)' due to differences in the nullability of reference types. // (x, y) = c; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "x").WithArguments("IIn<object?>", "IIn<object>", "x", "void C<object>.Deconstruct(out IIn<object> x, out IOut<object> y)").WithLocation(13, 10), // (19,13): warning CS8624: Argument of type 'IOut<object>' cannot be used as an output of type 'IOut<object?>' for parameter 'y' in 'void C<object?>.Deconstruct(out IIn<object?> x, out IOut<object?> y)' due to differences in the nullability of reference types. // (x, y) = c; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "y").WithArguments("IOut<object>", "IOut<object?>", "y", "void C<object?>.Deconstruct(out IIn<object?> x, out IOut<object?> y)").WithLocation(19, 13) ); } [Fact] [WorkItem(29618, "https://github.com/dotnet/roslyn/issues/29618")] public void DeconstructionTypeInference_01() { var source = @"class C { static void M() { (var x, var y) = ((string?)null, string.Empty); x.ToString(); // 1 y.ToString(); x = null; y = null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9) ); } [Fact] [WorkItem(29618, "https://github.com/dotnet/roslyn/issues/29618")] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void DeconstructionTypeInference_02() { var source = @"class C { static (string?, string) F() => (string.Empty, string.Empty); static void G() { (var x, var y) = F(); x.ToString(); // 1 y.ToString(); x = null; y = null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] [WorkItem(29618, "https://github.com/dotnet/roslyn/issues/29618")] public void DeconstructionTypeInference_03() { var source = @"class C { void Deconstruct(out string? x, out string y) { x = string.Empty; y = string.Empty; } static void M() { (var x, var y) = new C(); x.ToString(); y.ToString(); x = null; y = null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 9)); } [Fact] public void DeconstructionTypeInference_04() { var source = @"class C { static (string?, string) F() => (null, string.Empty); static void G() { string x; string? y; var t = ((x, y) = F()); _ = t/*T:(string x, string y)*/; t.x.ToString(); // 1 t.y.ToString(); t.x = null; t.y = null; // 2 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/33011: Deconstruction should infer string? for x, // string! for y, and (string?, string!) for t. comp.VerifyDiagnostics( // (8,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // var t = ((x, y) = F()); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F()").WithLocation(8, 27) ); comp.VerifyTypes(); } [Fact] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void DeconstructionTypeInference_05() { var source = @"using System; using System.Collections.Generic; class C { static IEnumerable<(string, string?)> F() => throw new Exception(); static void G() { foreach ((var x, var y) in F()) { x.ToString(); y.ToString(); // 1 x = null; // 2 y = null; // 3 } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 13), // (12,13): error CS1656: Cannot assign to 'x' because it is a 'foreach iteration variable' // x = null; // 2 Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "x").WithArguments("x", "foreach iteration variable").WithLocation(12, 13), // (13,13): error CS1656: Cannot assign to 'y' because it is a 'foreach iteration variable' // y = null; // 3 Diagnostic(ErrorCode.ERR_AssgReadonlyLocalCause, "y").WithArguments("y", "foreach iteration variable").WithLocation(13, 13) ); } [Fact] public void Discard_01() { var source = @"class C { static void F((object, object?) t) { object? x; ((_, x) = t).Item1.ToString(); ((x, _) = t).Item2.ToString(); } }"; // https://github.com/dotnet/roslyn/issues/33011: Should report WRN_NullReferenceReceiver. var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); //// (7,9): warning CS8602: Dereference of a possibly null reference. //// ((x, _) = t).Item2.ToString(); //Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((x, _) = t).Item2").WithLocation(7, 9)); } [Fact, WorkItem(29635, "https://github.com/dotnet/roslyn/issues/29635")] public void Discard_02() { var source = @"#nullable disable class C<T> { #nullable enable void F(object? o1, object? o2, C<object> o3, C<object?> o4) { if (o1 is null) throw null!; _ /*T:object!*/ = o1; _ /*T:object?*/ = o2; _ /*T:C<object!>!*/ = o3; _ /*T:C<object?>!*/ = o4; } #nullable disable void F(C<object> o) { _ /*T:C<object>!*/ = o; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular.WithFeature("run-nullable-analysis", "always"), options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); var tree = comp.SyntaxTrees.Single(); var discards = tree.GetRoot().DescendantNodes().OfType<AssignmentExpressionSyntax>().Select(a => a.Left).ToArray(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var discard1 = model.GetSymbolInfo(discards[0]).Symbol; Assert.Equal(SymbolKind.Discard, discard1.Kind); Assert.Equal("object _", discard1.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var discard2 = model.GetSymbolInfo(discards[1]).Symbol; Assert.Equal(SymbolKind.Discard, discard2.Kind); Assert.Equal("object? _", discard2.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var discard3 = model.GetSymbolInfo(discards[2]).Symbol; Assert.Equal(SymbolKind.Discard, discard3.Kind); Assert.Equal("C<object> _", discard3.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var discard4 = model.GetSymbolInfo(discards[3]).Symbol; Assert.Equal(SymbolKind.Discard, discard4.Kind); Assert.Equal("C<object?> _", discard4.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); var discard5 = model.GetSymbolInfo(discards[4]).Symbol; Assert.Equal(SymbolKind.Discard, discard5.Kind); Assert.Equal("C<object> _", discard5.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); } [Fact, WorkItem(36503, "https://github.com/dotnet/roslyn/issues/36503")] public void Discard_Reinferred() { var source = @" #nullable enable interface I<in T> {} class C { void M(I<string?> i1, I<string> i2) { var x = i2 ?? i1; _ = x /*T:I<string!>!*/; _ /*T:I<string!>!*/ = i2 ?? i1; var y = (_ = i2 ?? i1); _ = y /*T:I<string!>!*/; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact, WorkItem(36503, "https://github.com/dotnet/roslyn/issues/36503")] public void Discard_Reinferred_Nested() { var source = @" #nullable enable interface I<in T> {} class C { void M(I<I<string?>> i1, I<I<string>?> i2) { var x = i2 ?? i1; _ = x /*T:I<I<string?>!>!*/; _ /*T:I<I<string?>!>!*/ = i2 ?? i1; var y = (_ = i2 ?? i1); _ = y /*T:I<I<string?>!>!*/; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact, WorkItem(36503, "https://github.com/dotnet/roslyn/issues/36503")] public void Discard_OutDiscard() { var source = @" class C { void M<T>(out T t) => throw null!; void M2() { M<string?>(out var _); M<object?>(out _); M<string>(out var _); #nullable disable annotations M<object>(out _); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var arguments = tree.GetRoot().DescendantNodes().OfType<ArgumentSyntax>(); var discard1 = arguments.First().Expression; Assert.Equal("var _", discard1.ToString()); Assert.Equal("System.String?", model.GetTypeInfoAndVerifyIOperation(discard1).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, model.GetTypeInfo(discard1).Nullability.Annotation); var discard2 = arguments.Skip(1).First().Expression; Assert.Equal("_", discard2.ToString()); Assert.Equal("System.Object?", model.GetTypeInfoAndVerifyIOperation(discard2).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, model.GetTypeInfo(discard2).Nullability.Annotation); var discard3 = arguments.Skip(2).First().Expression; Assert.Equal("var _", discard3.ToString()); Assert.Equal("System.String", model.GetTypeInfoAndVerifyIOperation(discard3).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, model.GetTypeInfo(discard3).Nullability.Annotation); var discard4 = arguments.Skip(3).First().Expression; Assert.Equal("_", discard4.ToString()); Assert.Equal("System.Object", model.GetTypeInfoAndVerifyIOperation(discard4).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, model.GetTypeInfo(discard4).Nullability.Annotation); } [Fact, WorkItem(36503, "https://github.com/dotnet/roslyn/issues/35010")] public void Discard_Deconstruction() { var source = @" class C { void M(string x, object y) { x = null; // 1 y = null; // 2 (var _, _) = (x, y); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 13) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var arguments = tree.GetRoot().DescendantNodes().OfType<ArgumentSyntax>(); // https://github.com/dotnet/roslyn/issues/35010: handle GetTypeInfo for deconstruction variables, discards, foreach deconstructions and nested deconstructions var discard1 = (DeclarationExpressionSyntax)arguments.First().Expression; Assert.Equal("var _", discard1.ToString()); Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfoAndVerifyIOperation(discard1.Designation).Nullability.Annotation); Assert.Equal("System.String", model.GetTypeInfo(discard1).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfo(discard1).Nullability.Annotation); Assert.Null(model.GetSymbolInfo(discard1).Symbol); Assert.Null(model.GetSymbolInfo(discard1.Designation).Symbol); Assert.Null(model.GetDeclaredSymbol(discard1)); Assert.Null(model.GetDeclaredSymbol(discard1.Designation)); var discard2 = arguments.Skip(1).First().Expression; Assert.Equal("_", discard2.ToString()); Assert.Equal("System.Object", model.GetTypeInfoAndVerifyIOperation(discard2).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfo(discard2).Nullability.Annotation); Assert.Equal("object _", model.GetSymbolInfo(discard2).Symbol.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)); Assert.Null(model.GetDeclaredSymbol(discard2)); } [Fact, WorkItem(35032, "https://github.com/dotnet/roslyn/issues/35032")] public void Discard_Pattern() { var source = @" public class C { public object? Property { get; } public void Deconstruct(out object? x, out object y) => throw null!; void M(C c) { _ = c is C { Property: _ }; _ = c is C (_, _); } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var discardPatterns = tree.GetRoot().DescendantNodes().OfType<DiscardPatternSyntax>().ToArray(); var discardPattern1 = discardPatterns[0]; Assert.Equal("_", discardPattern1.ToString()); Assert.Equal("System.Object", model.GetTypeInfo(discardPattern1).Type.ToTestDisplayString()); // Nullability in patterns are not yet supported: https://github.com/dotnet/roslyn/issues/35032 Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfo(discardPattern1).Nullability.Annotation); Assert.Null(model.GetSymbolInfo(discardPattern1).Symbol); var discardPattern2 = discardPatterns[1]; Assert.Equal("_", discardPattern2.ToString()); Assert.Equal("System.Object", model.GetTypeInfo(discardPattern2).Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfo(discardPattern2).Nullability.Annotation); Assert.Null(model.GetSymbolInfo(discardPattern2).Symbol); } [Fact] public void Discard_03() { var source = @"#nullable disable class C<T> { #nullable enable void F(bool b, object o1, object? o2, C<object> o3, C<object?> o4) { _ /*T:object?*/ = (b ? o1 : o2); _ /*T:C<object!>!*/ = (b ? o3 : o4); // 1 var x = (b ? o3 : o4); // 2 _ /*T:C<object!>!*/ = (b ? o4 : o3); // 3 var y = (b ? o4 : o3); // 4 _ /*T:C<object!>!*/ = (b ? o3 : o5); _ /*T:C<object?>!*/ = (b ? o4 : o5); } #nullable disable static C<object> o5 = null; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,41): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // _ /*T:C<object!>!*/ = (b ? o3 : o4); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "o4").WithArguments("C<object?>", "C<object>").WithLocation(8, 41), // (9,27): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var x = (b ? o3 : o4); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "o4").WithArguments("C<object?>", "C<object>").WithLocation(9, 27), // (11,36): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // _ /*T:C<object!>!*/ = (b ? o4 : o3); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "o4").WithArguments("C<object?>", "C<object>").WithLocation(11, 36), // (12,22): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var y = (b ? o4 : o3); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "o4").WithArguments("C<object?>", "C<object>").WithLocation(12, 22) ); comp.VerifyTypes(); } [Fact, WorkItem(29635, "https://github.com/dotnet/roslyn/issues/29635")] public void Discard_04() { var source = @"#nullable disable class C<T> { #nullable enable void F(bool b, object o1) { (_ /*T:object!*/ = o1) /*T:object!*/.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void BinaryOperator_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(string? x1, string? y1) { string z1 = x1 + y1; } void Test2(string? x2, string? y2) { string z2 = x2 + y2 ?? """"; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void BinaryOperator_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(dynamic? x1, dynamic? y1) { dynamic z1 = x1 + y1; } void Test2(dynamic? x2, dynamic? y2) { dynamic z2 = x2 + y2 ?? """"; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void BinaryOperator_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(string? x1, CL0? y1) { CL0? z1 = x1 + y1; CL0 u1 = z1 ?? new CL0(); } void Test2(string? x2, CL1? y2) { CL1 z2 = x2 + y2; } void Test3(string x3, CL0? y3, CL2 z3) { CL2 u3 = x3 + y3 + z3; } void Test4(string x4, CL1 y4, CL2 z4) { CL2 u4 = x4 + y4 + z4; } } class CL0 { public static CL0 operator + (string? x, CL0 y) { return y; } } class CL1 { public static CL1? operator + (string x, CL1? y) { return y; } } class CL2 { public static CL2 operator + (CL0 x, CL2 y) { return y; } public static CL2 operator + (CL1 x, CL2 y) { return y; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,24): warning CS8604: Possible null reference argument for parameter 'y' in 'CL0 CL0.operator +(string? x, CL0 y)'. // CL0? z1 = x1 + y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y1").WithArguments("y", "CL0 CL0.operator +(string? x, CL0 y)").WithLocation(10, 24), // (16,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1? CL1.operator +(string x, CL1? y)'. // CL1 z2 = x2 + y2; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("x", "CL1? CL1.operator +(string x, CL1? y)").WithLocation(16, 18), // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = x2 + y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2 + y2").WithLocation(16, 18), // (21,23): warning CS8604: Possible null reference argument for parameter 'y' in 'CL0 CL0.operator +(string? x, CL0 y)'. // CL2 u3 = x3 + y3 + z3; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y3").WithArguments("y", "CL0 CL0.operator +(string? x, CL0 y)").WithLocation(21, 23), // (26,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL2 CL2.operator +(CL1 x, CL2 y)'. // CL2 u4 = x4 + y4 + z4; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x4 + y4").WithArguments("x", "CL2 CL2.operator +(CL1 x, CL2 y)").WithLocation(26, 18) ); } [Fact] public void BinaryOperator_03_WithDisallowAndAllowNull() { CSharpCompilation c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class CL0 { void Test1(string? x1, CL0? y1) { CL0? z1 = x1 + y1; CL0 u1 = z1 ?? new CL0(); } public static CL0 operator + (string? x, [AllowNull] CL0 y) => throw null!; } class CL1 { void Test2(string? x2, CL1? y2) { CL1 z2 = x2 + y2; // 1, 2 } public static CL1? operator + ([AllowNull] string x, [DisallowNull] CL1? y) => throw null!; } class CL2 { void Test3(string x3, CL0? y3, CL2 z3) { CL2 u3 = x3 + y3 + z3; } void Test4(string x4, CL1 y4, CL2 z4) { CL2 u4 = x4 + y4 + z4; } public static CL2 operator + ([AllowNull] CL0 x, CL2 y) => throw null!; public static CL2 operator + ([AllowNull] CL1 x, CL2 y) => throw null!; } ", AllowNullAttributeDefinition, DisallowNullAttributeDefinition }); // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 c.VerifyDiagnostics( // (8,24): warning CS8604: Possible null reference argument for parameter 'y' in 'CL0 CL0.operator +(string? x, CL0 y)'. // CL0? z1 = x1 + y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y1").WithArguments("y", "CL0 CL0.operator +(string? x, CL0 y)").WithLocation(8, 24), // (19,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1? CL1.operator +(string x, CL1? y)'. // CL1 z2 = x2 + y2; // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("x", "CL1? CL1.operator +(string x, CL1? y)").WithLocation(19, 18), // (19,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 z2 = x2 + y2; // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2 + y2").WithLocation(19, 18), // (29,23): warning CS8604: Possible null reference argument for parameter 'y' in 'CL0 CL0.operator +(string? x, CL0 y)'. // CL2 u3 = x3 + y3 + z3; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y3").WithArguments("y", "CL0 CL0.operator +(string? x, CL0 y)").WithLocation(29, 23), // (34,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL2 CL2.operator +(CL1 x, CL2 y)'. // CL2 u4 = x4 + y4 + z4; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x4 + y4").WithArguments("x", "CL2 CL2.operator +(CL1 x, CL2 y)").WithLocation(34, 18) ); } [Fact] public void BinaryOperator_03_WithMaybeAndNotNull() { CSharpCompilation c = CreateNullableCompilation(new[] { @" using System.Diagnostics.CodeAnalysis; class CL0 { void Test1(string x1, CL0 y1) { CL0 z1 = x1 + y1; // 1 } [return: MaybeNull] public static CL0 operator + (string x, CL0 y) => throw null!; } class CL1 { void Test2(string x2, CL1 y2) { CL1 z2 = x2 + y2; } [return: NotNull] public static CL1? operator + (string x, CL1 y) => throw null!; } class CL2 { void Test3(string x3, CL0 y3, CL2 z3) { CL2 u3 = x3 + y3 + z3; // 2, 3 } void Test4(string x4, CL1 y4, CL2 z4) { CL2 u4 = x4 + y4 + z4; } [return: MaybeNull] public static CL2 operator + (CL0 x, CL2 y) => throw null!; [return: NotNull] public static CL2? operator + (CL1 x, CL2 y) => throw null!; } ", MaybeNullAttributeDefinition, NotNullAttributeDefinition }); c.VerifyDiagnostics( // (8,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 z1 = x1 + y1; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1 + y1").WithLocation(8, 18), // (28,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL2 CL2.operator +(CL0 x, CL2 y)'. // CL2 u3 = x3 + y3 + z3; // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x3 + y3").WithArguments("x", "CL2 CL2.operator +(CL0 x, CL2 y)").WithLocation(28, 18), // (28,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL2 u3 = x3 + y3 + z3; // 2, 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3 + y3 + z3").WithLocation(28, 18) ); } [Fact] public void BinaryOperator_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1, CL0? y1) { CL0? z1 = x1 && y1; CL0 u1 = z1; } void Test2(CL0 x2, CL0? y2) { CL0? z2 = x2 && y2; CL0 u2 = z2 ?? new CL0(); } } class CL0 { public static CL0 operator &(CL0 x, CL0? y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0 x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'bool CL0.operator false(CL0 x)'. // CL0? z1 = x1 && y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "bool CL0.operator false(CL0 x)").WithLocation(10, 19), // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator &(CL0 x, CL0? y)'. // CL0? z1 = x1 && y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL0 CL0.operator &(CL0 x, CL0? y)").WithLocation(10, 19) ); } [Fact] public void BinaryOperator_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1, CL0? y1) { CL0? z1 = x1 && y1; } } class CL0 { public static CL0 operator &(CL0? x, CL0 y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0 x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'bool CL0.operator false(CL0 x)'. // CL0? z1 = x1 && y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "bool CL0.operator false(CL0 x)").WithLocation(10, 19), // (10,25): warning CS8604: Possible null reference argument for parameter 'y' in 'CL0 CL0.operator &(CL0? x, CL0 y)'. // CL0? z1 = x1 && y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y1").WithArguments("y", "CL0 CL0.operator &(CL0? x, CL0 y)").WithLocation(10, 25) ); } [Fact] public void BinaryOperator_06() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1, CL0? y1) { CL0? z1 = x1 && y1; } } class CL0 { public static CL0 operator &(CL0? x, CL0? y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0? x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void BinaryOperator_07() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1, CL0? y1) { CL0? z1 = x1 || y1; } } class CL0 { public static CL0 operator |(CL0? x, CL0? y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0? x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'bool CL0.operator true(CL0 x)'. // CL0? z1 = x1 || y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "bool CL0.operator true(CL0 x)").WithLocation(10, 19) ); } [Fact] public void BinaryOperator_08() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1, CL0? y1) { CL0? z1 = x1 || y1; } } class CL0 { public static CL0 operator |(CL0? x, CL0? y) { return new CL0(); } public static bool operator true(CL0? x) { return false; } public static bool operator false(CL0 x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void BinaryOperator_09() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0 x1, CL0 y1, CL0 z1) { CL0? u1 = x1 && y1 || z1; } } class CL0 { public static CL0? operator &(CL0 x, CL0 y) { return new CL0(); } public static CL0 operator |(CL0 x, CL0 y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0 x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'bool CL0.operator true(CL0 x)'. // CL0? u1 = x1 && y1 || z1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1 && y1").WithArguments("x", "bool CL0.operator true(CL0 x)").WithLocation(10, 19), // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator |(CL0 x, CL0 y)'. // CL0? u1 = x1 && y1 || z1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1 && y1").WithArguments("x", "CL0 CL0.operator |(CL0 x, CL0 y)").WithLocation(10, 19) ); } [Fact] public void BinaryOperator_10() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1, CL0? y1, CL0? z1) { CL0? u1 = x1 && y1 || z1; } void Test2(CL0 x2, CL0? y2, CL0? z2) { CL0? u1 = x2 && y2 || z2; } } class CL0 { public static CL0 operator &(CL0? x, CL0? y) { return new CL0(); } public static CL0 operator |(CL0 x, CL0? y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0? x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void BinaryOperator_11() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(System.Action x1, System.Action y1) { System.Action u1 = x1 + y1; } void Test2(System.Action x2, System.Action y2) { System.Action u2 = x2 + y2 ?? x2; } void Test3(System.Action? x3, System.Action y3) { System.Action u3 = x3 + y3; } void Test4(System.Action? x4, System.Action y4) { System.Action u4 = x4 + y4 ?? y4; } void Test5(System.Action x5, System.Action? y5) { System.Action u5 = x5 + y5; } void Test6(System.Action x6, System.Action? y6) { System.Action u6 = x6 + y6 ?? x6; } void Test7(System.Action? x7, System.Action? y7) { System.Action u7 = x7 + y7; } void Test8(System.Action x8, System.Action y8) { System.Action u8 = x8 - y8; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (40,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action u7 = x7 + y7; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x7 + y7").WithLocation(40, 28), // (45,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action u8 = x8 - y8; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x8 - y8").WithLocation(45, 28) ); } [Fact] public void BinaryOperator_12() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0 x1, CL0 y1) { CL0? u1 = x1 && !y1; } void Test2(bool x2, bool y2) { bool u2 = x2 && !y2; } } class CL0 { public static CL0 operator &(CL0? x, CL0 y) { return new CL0(); } public static bool operator true(CL0? x) { return false; } public static bool operator false(CL0? x) { return false; } public static CL0? operator !(CL0 x) { return null; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,25): warning CS8604: Possible null reference argument for parameter 'y' in 'CL0 CL0.operator &(CL0? x, CL0 y)'. // CL0? u1 = x1 && !y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "!y1").WithArguments("y", "CL0 CL0.operator &(CL0? x, CL0 y)").WithLocation(10, 25) ); } [Fact] public void BinaryOperator_13() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0 x1, CL0 y1) { CL0 z1 = x1 && y1; } } class CL0 { public static CL0? operator &(CL0 x, CL0 y) { return new CL0(); } public static bool operator true(CL0 x) { return false; } public static bool operator false(CL0? x) { return false; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 z1 = x1 && y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1 && y1").WithLocation(10, 18) ); } [Fact] public void BinaryOperator_14() { var source = @"struct S { public static S operator&(S a, S b) => a; public static S operator|(S a, S b) => b; public static bool operator true(S? s) => true; public static bool operator false(S? s) => false; static void And(S x, S? y) { if (x && x) { } if (x && y) { } if (y && x) { } if (y && y) { } } static void Or(S x, S? y) { if (x || x) { } if (x || y) { } if (y || x) { } if (y || y) { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void BinaryOperator_15() { var source = @"struct S { public static S operator+(S a, S b) => a; static void F(S x, S? y) { S? s; s = x + x; s = x + y; s = y + x; s = y + y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void BinaryOperator_15_WithDisallowNull() { var source = @" using System.Diagnostics.CodeAnalysis; struct S { public static S? operator+(S? a, [DisallowNull] S? b) => throw null!; static void F(S? x, S? y) { if (x == null) throw null!; S? s; s = x + x; s = x + y; // 1 s = y + x; s = y + y; // 2 } }"; // Analyze operator call properly (honoring [Disallow|Allow|Maybe|NotNull] attribute annotations) https://github.com/dotnet/roslyn/issues/32671 var comp = CreateCompilation(new[] { source, DisallowNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void BinaryOperator_16() { var source = @"struct S { public static bool operator<(S a, S b) => true; public static bool operator<=(S a, S b) => true; public static bool operator>(S a, S b) => true; public static bool operator>=(S a, S b) => true; public static bool operator==(S a, S b) => true; public static bool operator!=(S a, S b) => true; public override bool Equals(object other) => true; public override int GetHashCode() => 0; static void F(S x, S? y) { if (x < y) { } if (x <= y) { } if (x > y) { } if (x >= y) { } if (x == y) { } if (x != y) { } if (y < x) { } if (y <= x) { } if (y > x) { } if (y >= x) { } if (y == x) { } if (y != x) { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void MethodGroupConversion_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1) { System.Action u1 = x1.M1; } void Test2(CL0 x2) { System.Action u2 = x2.M1; } } class CL0 { public void M1() {} } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,28): warning CS8602: Dereference of a possibly null reference. // System.Action u1 = x1.M1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(10, 28) ); } [Fact] public void MethodGroupConversion_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void M1<T>(T x){} void Test1() { System.Action<string?> u1 = M1<string>; } void Test2() { System.Action<string> u2 = M1<string?>; } void Test3() { System.Action<CL0<string?>> u3 = M1<CL0<string>>; } void Test4() { System.Action<CL0<string>> u4 = M1<CL0<string?>>; } } class CL0<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,37): warning CS8622: Nullability of reference types in type of parameter 'x' of 'void C.M1<string>(string x)' doesn't match the target delegate 'Action<string?>'. // System.Action<string?> u1 = M1<string>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M1<string>").WithArguments("x", "void C.M1<string>(string x)", "System.Action<string?>").WithLocation(12, 37), // (22,42): warning CS8622: Nullability of reference types in type of parameter 'x' of 'void C.M1<CL0<string>>(CL0<string> x)' doesn't match the target delegate 'Action<CL0<string?>>'. // System.Action<CL0<string?>> u3 = M1<CL0<string>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M1<CL0<string>>").WithArguments("x", "void C.M1<CL0<string>>(CL0<string> x)", "System.Action<CL0<string?>>").WithLocation(22, 42), // (27,41): warning CS8622: Nullability of reference types in type of parameter 'x' of 'void C.M1<CL0<string?>>(CL0<string?> x)' doesn't match the target delegate 'Action<CL0<string>>'. // System.Action<CL0<string>> u4 = M1<CL0<string?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "M1<CL0<string?>>").WithArguments("x", "void C.M1<CL0<string?>>(CL0<string?> x)", "System.Action<CL0<string>>").WithLocation(27, 41) ); } [Fact] public void MethodGroupConversion_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { void M1<T>(T x){} void Test1() { System.Action<string?> u1 = (System.Action<string?>)M1<string>; // 1 System.Action<string> u2 = (System.Action<string>)M1<string?>; System.Action<CL0<string?>> u3 = (System.Action<CL0<string?>>)M1<CL0<string>>; // 2 System.Action<CL0<string>> u4 = (System.Action<CL0<string>>)M1<CL0<string?>>; //3 } } class CL0<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,37): warning CS8622: Nullability of reference types in type of parameter 'x' of 'void C.M1<string>(string x)' doesn't match the target delegate 'Action<string?>'. // System.Action<string?> u1 = (System.Action<string?>)M1<string>; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(System.Action<string?>)M1<string>").WithArguments("x", "void C.M1<string>(string x)", "System.Action<string?>").WithLocation(8, 37), // (10,42): warning CS8622: Nullability of reference types in type of parameter 'x' of 'void C.M1<CL0<string>>(CL0<string> x)' doesn't match the target delegate 'Action<CL0<string?>>'. // System.Action<CL0<string?>> u3 = (System.Action<CL0<string?>>)M1<CL0<string>>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(System.Action<CL0<string?>>)M1<CL0<string>>").WithArguments("x", "void C.M1<CL0<string>>(CL0<string> x)", "System.Action<CL0<string?>>").WithLocation(10, 42), // (11,41): warning CS8622: Nullability of reference types in type of parameter 'x' of 'void C.M1<CL0<string?>>(CL0<string?> x)' doesn't match the target delegate 'Action<CL0<string>>'. // System.Action<CL0<string>> u4 = (System.Action<CL0<string>>)M1<CL0<string?>>; //3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(System.Action<CL0<string>>)M1<CL0<string?>>").WithArguments("x", "void C.M1<CL0<string?>>(CL0<string?> x)", "System.Action<CL0<string>>").WithLocation(11, 41) ); } [Fact] public void MethodGroupConversion_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } T M1<T>(){throw new System.Exception();} void Test1() { System.Func<string?> u1 = M1<string>; } void Test2() { System.Func<string> u2 = M1<string?>; } void Test3() { System.Func<CL0<string?>> u3 = M1<CL0<string>>; } void Test4() { System.Func<CL0<string>> u4 = M1<CL0<string?>>; } } class CL0<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (17,34): warning CS8621: Nullability of reference types in return type of 'string? C.M1<string?>()' doesn't match the target delegate 'Func<string>'. // System.Func<string> u2 = M1<string?>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M1<string?>").WithArguments("string? C.M1<string?>()", "System.Func<string>").WithLocation(17, 34), // (22,40): warning CS8621: Nullability of reference types in return type of 'CL0<string> C.M1<CL0<string>>()' doesn't match the target delegate 'Func<CL0<string?>>'. // System.Func<CL0<string?>> u3 = M1<CL0<string>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M1<CL0<string>>").WithArguments("CL0<string> C.M1<CL0<string>>()", "System.Func<CL0<string?>>").WithLocation(22, 40), // (27,39): warning CS8621: Nullability of reference types in return type of 'CL0<string?> C.M1<CL0<string?>>()' doesn't match the target delegate 'Func<CL0<string>>'. // System.Func<CL0<string>> u4 = M1<CL0<string?>>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "M1<CL0<string?>>").WithArguments("CL0<string?> C.M1<CL0<string?>>()", "System.Func<CL0<string>>").WithLocation(27, 39) ); } [Fact] public void MethodGroupConversion_05() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } T M1<T>(){throw new System.Exception();} void Test1() { System.Func<string?> u1 = (System.Func<string?>)M1<string>; System.Func<string> u2 = (System.Func<string>)M1<string?>; // 1 System.Func<CL0<string?>> u3 = (System.Func<CL0<string?>>)M1<CL0<string>>; // 2 System.Func<CL0<string>> u4 = (System.Func<CL0<string>>)M1<CL0<string?>>; // 3 } } class CL0<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,34): warning CS8621: Nullability of reference types in return type of 'string? C.M1<string?>()' doesn't match the target delegate 'Func<string>'. // System.Func<string> u2 = (System.Func<string>)M1<string?>; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "(System.Func<string>)M1<string?>").WithArguments("string? C.M1<string?>()", "System.Func<string>").WithLocation(13, 34), // (14,40): warning CS8621: Nullability of reference types in return type of 'CL0<string> C.M1<CL0<string>>()' doesn't match the target delegate 'Func<CL0<string?>>'. // System.Func<CL0<string?>> u3 = (System.Func<CL0<string?>>)M1<CL0<string>>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "(System.Func<CL0<string?>>)M1<CL0<string>>").WithArguments("CL0<string> C.M1<CL0<string>>()", "System.Func<CL0<string?>>").WithLocation(14, 40), // (15,39): warning CS8621: Nullability of reference types in return type of 'CL0<string?> C.M1<CL0<string?>>()' doesn't match the target delegate 'Func<CL0<string>>'. // System.Func<CL0<string>> u4 = (System.Func<CL0<string>>)M1<CL0<string?>>; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "(System.Func<CL0<string>>)M1<CL0<string?>>").WithArguments("CL0<string?> C.M1<CL0<string?>>()", "System.Func<CL0<string>>").WithLocation(15, 39) ); } [Fact] public void MethodGroupConversion_06() { var source = @"delegate void D<T>(T t); class A { } class B<T> { internal void F(T t) { } } class C { static B<T> Create<T>(T t) => new B<T>(); static void F1(A x, A? y) { D<A> d1; d1 = Create(x).F; d1 = Create(y).F; x = y; // 1 d1 = Create(x).F; } static void F2(A x, A? y) { D<A?> d2; d2 = Create(x).F; // 2 d2 = Create(y).F; x = y; // 3 d2 = Create(x).F; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = y; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(15, 13), // (21,14): warning CS8622: Nullability of reference types in type of parameter 't' of 'void B<A>.F(A t)' doesn't match the target delegate 'D<A?>'. // d2 = Create(x).F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Create(x).F").WithArguments("t", "void B<A>.F(A t)", "D<A?>").WithLocation(21, 14), // (23,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = y; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(23, 13)); } [Fact] public void UnaryOperator_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1) { CL0 u1 = !x1; } void Test2(CL1 x2) { CL1 u2 = !x2; } void Test3(CL2? x3) { CL2 u3 = !x3; } void Test4(CL1 x4) { dynamic y4 = x4; CL1 u4 = !y4; dynamic v4 = !y4 ?? y4; } void Test5(bool x5) { bool u5 = !x5; } } class CL0 { public static CL0 operator !(CL0 x) { return new CL0(); } } class CL1 { public static CL1? operator !(CL1 x) { return new CL1(); } } class CL2 { public static CL2 operator !(CL2? x) { return new CL2(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator !(CL0 x)'. // CL0 u1 = !x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL0 CL0.operator !(CL0 x)").WithLocation(10, 19), // (15,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u2 = !x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "!x2").WithLocation(15, 18) ); } [Fact] public void UnaryOperator_02() { var source = @"struct S { public static S operator~(S s) => s; static void F(S? s) { s = ~s; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Conversion_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1) { CL1 u1 = x1; } void Test2(CL0? x2, CL0 y2) { int u2 = x2; long v2 = x2; int w2 = y2; } void Test3(CL0 x3) { CL2 u3 = x3; } void Test4(CL0 x4) { CL3? u4 = x4; CL3 v4 = u4 ?? new CL3(); } void Test5(dynamic? x5) { CL3 u5 = x5; } void Test6(dynamic? x6) { CL3? u6 = x6; CL3 v6 = u6 ?? new CL3(); } void Test7(CL0? x7) { dynamic u7 = x7; } void Test8(CL0 x8) { dynamic? u8 = x8; dynamic v8 = u8 ?? x8; } void Test9(dynamic? x9) { object u9 = x9; } void Test10(object? x10) { dynamic u10 = x10; } void Test11(CL4? x11) { CL3 u11 = x11; } void Test12(CL3? x12) { CL4 u12 = (CL4)x12; } void Test13(int x13) { object? u13 = x13; object v13 = u13 ?? new object(); } void Test14<T>(T x14) { object u14 = x14; object v14 = ((object)x14) ?? new object(); } void Test15(int? x15) { object u15 = x15; } void Test16() { System.IFormattable? u16 = $""{3}""; object v16 = u16 ?? new object(); } } class CL0 { public static implicit operator CL1(CL0 x) { return new CL1(); } public static implicit operator int(CL0 x) { return 0; } public static implicit operator long(CL0? x) { return 0; } public static implicit operator CL2?(CL0 x) { return new CL2(); } public static implicit operator CL3(CL0? x) { return new CL3(); } } class CL1 {} class CL2 {} class CL3 {} class CL4 : CL3 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0.implicit operator CL1(CL0 x)'. // CL1 u1 = x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL0.implicit operator CL1(CL0 x)").WithLocation(10, 18), // (15,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0.implicit operator int(CL0 x)'. // int u2 = x2; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("x", "CL0.implicit operator int(CL0 x)").WithLocation(15, 18), // (22,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL2 u3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(22, 18), // (33,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL3 u5 = x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5").WithLocation(33, 18), // (44,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // dynamic u7 = x7; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x7").WithLocation(44, 22), // (55,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object u9 = x9; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x9").WithLocation(55, 21), // (60,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // dynamic u10 = x10; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x10").WithLocation(60, 23), // (65,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL3 u11 = x11; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x11").WithLocation(65, 19), // (70,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL4 u12 = (CL4)x12; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(CL4)x12").WithLocation(70, 19), // (81,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object u14 = x14; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x14").WithLocation(81, 22), // (82,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // object v14 = ((object)x14) ?? new object(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)x14").WithLocation(82, 23), // (87,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // object u15 = x15; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x15").WithLocation(87, 22)); } [Fact] public void Conversion_02() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0<string?> x1) { CL0<string> u1 = x1; CL0<string> v1 = (CL0<string>)x1; } } class CL0<T> { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,26): warning CS8619: Nullability of reference types in value of type 'CL0<string?>' doesn't match target type 'CL0<string>'. // CL0<string> u1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("CL0<string?>", "CL0<string>").WithLocation(10, 26), // (11,26): warning CS8619: Nullability of reference types in value of type 'CL0<string?>' doesn't match target type 'CL0<string>'. // CL0<string> v1 = (CL0<string>)x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(CL0<string>)x1").WithArguments("CL0<string?>", "CL0<string>").WithLocation(11, 26) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void ImplicitConversions_01() { var source = @"class A<T> { } class B<T> : A<T> { } class C { static void F1(B<object> x1) { A<object?> y1 = x1; y1 = x1; y1 = x1!; } static void F2(B<object?> x2) { A<object> y2 = x2; y2 = x2; y2 = x2!; } static void F3(B<object>? x3) { A<object?> y3 = x3; y3 = x3; y3 = x3!; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,25): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // A<object?> y1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("B<object>", "A<object?>").WithLocation(7, 25), // (8,14): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // y1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("B<object>", "A<object?>").WithLocation(8, 14), // (13,24): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'A<object>'. // A<object> y2 = x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("B<object?>", "A<object>").WithLocation(13, 24), // (14,14): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'A<object>'. // y2 = x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("B<object?>", "A<object>").WithLocation(14, 14), // (19,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // A<object?> y3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(19, 25), // (19,25): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // A<object?> y3 = x3; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("B<object>", "A<object?>").WithLocation(19, 25), // (20,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(20, 14), // (20,14): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // y3 = x3; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("B<object>", "A<object?>").WithLocation(20, 14) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void ImplicitConversions_02() { var source = @"interface IA<T> { } interface IB<T> : IA<T> { } class C { static void F1(IB<object> x1) { IA<object?> y1 = x1; y1 = x1; y1 = x1!; } static void F2(IB<object?> x2) { IA<object> y2 = x2; y2 = x2; y2 = x2!; } static void F3(IB<object>? x3) { IA<object?> y3 = x3; y3 = x3; y3 = x3!; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,26): warning CS8619: Nullability of reference types in value of type 'IB<object>' doesn't match target type 'IA<object?>'. // IA<object?> y1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("IB<object>", "IA<object?>").WithLocation(7, 26), // (8,14): warning CS8619: Nullability of reference types in value of type 'IB<object>' doesn't match target type 'IA<object?>'. // y1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("IB<object>", "IA<object?>").WithLocation(8, 14), // (13,25): warning CS8619: Nullability of reference types in value of type 'IB<object?>' doesn't match target type 'IA<object>'. // IA<object> y2 = x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("IB<object?>", "IA<object>").WithLocation(13, 25), // (14,14): warning CS8619: Nullability of reference types in value of type 'IB<object?>' doesn't match target type 'IA<object>'. // y2 = x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("IB<object?>", "IA<object>").WithLocation(14, 14), // (19,26): warning CS8600: Converting null literal or possible null value to non-nullable type. // IA<object?> y3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(19, 26), // (19,26): warning CS8619: Nullability of reference types in value of type 'IB<object>' doesn't match target type 'IA<object?>'. // IA<object?> y3 = x3; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("IB<object>", "IA<object?>").WithLocation(19, 26), // (20,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(20, 14), // (20,14): warning CS8619: Nullability of reference types in value of type 'IB<object>' doesn't match target type 'IA<object?>'. // y3 = x3; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x3").WithArguments("IB<object>", "IA<object?>").WithLocation(20, 14)); } [Fact] public void ImplicitConversions_03() { var source = @"interface IOut<out T> { } class C { static void F(IOut<object> x) { IOut<object?> y = x; } static void G(IOut<object?> x) { IOut<object> y = x; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,26): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // IOut<object> y = x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IOut<object?>", "IOut<object>").WithLocation(10, 26)); } [Fact] public void ImplicitConversions_04() { var source = @"interface IIn<in T> { } class C { static void F(IIn<object> x) { IIn<object?> y = x; } static void G(IIn<object?> x) { IIn<object> y = x; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,26): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // IIn<object?> y = x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("IIn<object>", "IIn<object?>").WithLocation(6, 26)); } [Fact] public void ImplicitConversions_05() { var source = @"interface IOut<out T> { } class A<T> : IOut<T> { } class C { static void F(A<string> x) { IOut<object?> y = x; } static void G(A<string?> x) { IOut<object> y = x; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,26): warning CS8619: Nullability of reference types in value of type 'A<string?>' doesn't match target type 'IOut<object>'. // IOut<object> y = x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<string?>", "IOut<object>").WithLocation(11, 26)); } [Fact] public void ImplicitConversions_06() { var source = @"interface IIn<in T> { } interface IOut<out T> { } class A<T> : IIn<object>, IOut<object?> { } class B : IIn<object>, IOut<object?> { } class C { static void F(A<string> a1, B b1) { IIn<object?> y = a1; y = b1; IOut<object?> z = a1; z = b1; } static void G(A<string> a2, B b2) { IIn<object> y = a2; y = b2; IOut<object> z = a2; z = b2; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29897: Report the base types that did not match // rather than the derived or implementing type. For instance, report `'IIn<object>' // doesn't match ... 'IIn<object?>'` rather than `'A<string>' doesn't match ...`. comp.VerifyDiagnostics( // (9,26): warning CS8619: Nullability of reference types in value of type 'A<string>' doesn't match target type 'IIn<object?>'. // IIn<object?> y = a1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1").WithArguments("A<string>", "IIn<object?>").WithLocation(9, 26), // (10,13): warning CS8619: Nullability of reference types in value of type 'B' doesn't match target type 'IIn<object?>'. // y = b1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b1").WithArguments("B", "IIn<object?>").WithLocation(10, 13), // (18,26): warning CS8619: Nullability of reference types in value of type 'A<string>' doesn't match target type 'IOut<object>'. // IOut<object> z = a2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("A<string>", "IOut<object>").WithLocation(18, 26), // (19,13): warning CS8619: Nullability of reference types in value of type 'B' doesn't match target type 'IOut<object>'. // z = b2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b2").WithArguments("B", "IOut<object>").WithLocation(19, 13)); } [Fact, WorkItem(29898, "https://github.com/dotnet/roslyn/issues/29898")] public void ImplicitConversions_07() { var source = @"class A<T> { } class B<T> { public static implicit operator A<T>(B<T> b) => throw null!; } class C { static B<T> F<T>(T t) => throw null!; static void G(A<object?> a) => throw null!; static void Main(object? x) { var y = F(x); G(y); if (x == null) return; var z = F(x); G(z); // warning var z2 = F(x); G(z2!); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,11): warning CS8620: Argument of type 'B<object>' cannot be used for parameter 'a' of type 'A<object?>' in 'void C.G(A<object?> a)' due to differences in the nullability of reference types. // G(z); // warning Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("B<object>", "A<object?>", "a", "void C.G(A<object?> a)").WithLocation(18, 11) ); } [Fact] public void ImplicitConversion_Params() { var source = @"class A<T> { } class B<T> { public static implicit operator A<T>(B<T> b) => throw null!; } class C { static B<T> F<T>(T t) => throw null!; static void G(params A<object>[] a) => throw null!; static void Main(object? x) { var y = F(x); G(y); // 1 if (x == null) return; var z = F(x); G(z); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,11): warning CS8620: Argument of type 'B<object?>' cannot be used for parameter 'a' of type 'A<object>' in 'void C.G(params A<object>[] a)' due to differences in the nullability of reference types. // G(y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("B<object?>", "A<object>", "a", "void C.G(params A<object>[] a)").WithLocation(16, 11) ); } [Fact] public void ImplicitConversion_Typeless() { var source = @" public struct Optional<T> { public static implicit operator Optional<T>(T value) => throw null!; } class C { static void G1(Optional<object> a) => throw null!; static void G2(Optional<object?> a) => throw null!; static void M() { G1(null); // 1 G2(null); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,12): warning CS8625: Cannot convert null literal to non-nullable reference type. // G1(null); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 12) ); } [Fact] public void ImplicitConversion_Typeless_WithConstraint() { var source = @" public struct Optional<T> where T : class { public static implicit operator Optional<T>(T value) => throw null!; } class C { static void G(Optional<object> a) => throw null!; static void M() { G(null); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // G(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 11) ); } [Fact, WorkItem(41763, "https://github.com/dotnet/roslyn/issues/41763")] public void Conversions_EnumToUnderlyingType_SemanticModel() { var source = @" enum E { A = 1, B = (int)A }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); comp.VerifyDiagnostics(); var node = tree.GetRoot().DescendantNodes().OfType<EnumMemberDeclarationSyntax>().ElementAt(1); model.GetSymbolInfo(node.EqualsValue.Value); } [Fact] public void IdentityConversion_LocalDeclaration() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } interface IBoth<in T, out U> { } class C { static void F1(I<object> x1, IIn<object> y1, IOut<object> z1, IBoth<object, object> w1) { I<object?> a1 = x1; IIn<object?> b1 = y1; IOut<object?> c1 = z1; IBoth<object?, object?> d1 = w1; } static void F2(I<object?> x2, IIn<object?> y2, IOut<object?> z2, IBoth<object?, object?> w2) { I<object> a2 = x2; IIn<object> b2 = y2; IOut<object> c2 = z2; IBoth<object, object> d2 = w2; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,25): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // I<object?> a1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("I<object>", "I<object?>").WithLocation(9, 25), // (10,27): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // IIn<object?> b1 = y1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("IIn<object>", "IIn<object?>").WithLocation(10, 27), // (12,38): warning CS8619: Nullability of reference types in value of type 'IBoth<object, object>' doesn't match target type 'IBoth<object?, object?>'. // IBoth<object?, object?> d1 = w1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w1").WithArguments("IBoth<object, object>", "IBoth<object?, object?>").WithLocation(12, 38), // (16,24): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // I<object> a2 = x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("I<object?>", "I<object>").WithLocation(16, 24), // (18,27): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // IOut<object> c2 = z2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "z2").WithArguments("IOut<object?>", "IOut<object>").WithLocation(18, 27), // (19,36): warning CS8619: Nullability of reference types in value of type 'IBoth<object?, object?>' doesn't match target type 'IBoth<object, object>'. // IBoth<object, object> d2 = w2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w2").WithArguments("IBoth<object?, object?>", "IBoth<object, object>").WithLocation(19, 36)); } [Fact] public void IdentityConversion_Assignment() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } interface IBoth<in T, out U> { } class C { static void F1(I<object> x1, IIn<object> y1, IOut<object> z1, IBoth<object, object> w1) { I<object?> a1; a1 = x1; IIn<object?> b1; b1 = y1; IOut<object?> c1; c1 = z1; IBoth<object?, object?> d1; d1 = w1; } static void F2(I<object?> x2, IIn<object?> y2, IOut<object?> z2, IBoth<object?, object?> w2) { I<object> a2; a2 = x2; IIn<object> b2; b2 = y2; IOut<object> c2; c2 = z2; IBoth<object, object> d2; d2 = w2; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,14): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // a1 = x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x1").WithArguments("I<object>", "I<object?>").WithLocation(10, 14), // (12,14): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // b1 = y1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y1").WithArguments("IIn<object>", "IIn<object?>").WithLocation(12, 14), // (16,14): warning CS8619: Nullability of reference types in value of type 'IBoth<object, object>' doesn't match target type 'IBoth<object?, object?>'. // d1 = w1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w1").WithArguments("IBoth<object, object>", "IBoth<object?, object?>").WithLocation(16, 14), // (21,14): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // a2 = x2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x2").WithArguments("I<object?>", "I<object>").WithLocation(21, 14), // (25,14): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // c2 = z2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "z2").WithArguments("IOut<object?>", "IOut<object>").WithLocation(25, 14), // (27,14): warning CS8619: Nullability of reference types in value of type 'IBoth<object?, object?>' doesn't match target type 'IBoth<object, object>'. // d2 = w2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w2").WithArguments("IBoth<object?, object?>", "IBoth<object, object>").WithLocation(27, 14)); } [Fact] public void IdentityConversion_Argument() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(I<object> x, IIn<object> y, IOut<object> z) { G(x, y, z); } static void G(I<object?> x, IIn<object?> y, IOut<object?> z) { F(x, y, z); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,11): warning CS8620: Nullability of reference types in argument of type 'I<object>' doesn't match target type 'I<object?>' for parameter 'x' in 'void C.G(I<object?> x, IIn<object?> y, IOut<object?> z)'. // G(x, y, z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "x", "void C.G(I<object?> x, IIn<object?> y, IOut<object?> z)").WithLocation(8, 11), // (8,14): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'y' in 'void C.G(I<object?> x, IIn<object?> y, IOut<object?> z)'. // G(x, y, z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IIn<object>", "IIn<object?>", "y", "void C.G(I<object?> x, IIn<object?> y, IOut<object?> z)").WithLocation(8, 14), // (12,11): warning CS8620: Nullability of reference types in argument of type 'I<object?>' doesn't match target type 'I<object>' for parameter 'x' in 'void C.F(I<object> x, IIn<object> y, IOut<object> z)'. // F(x, y, z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object?>", "I<object>", "x", "void C.F(I<object> x, IIn<object> y, IOut<object> z)").WithLocation(12, 11), // (12,17): warning CS8620: Nullability of reference types in argument of type 'IOut<object?>' doesn't match target type 'IOut<object>' for parameter 'z' in 'void C.F(I<object> x, IIn<object> y, IOut<object> z)'. // F(x, y, z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IOut<object?>", "IOut<object>", "z", "void C.F(I<object> x, IIn<object> y, IOut<object> z)").WithLocation(12, 17)); } [Fact] public void IdentityConversion_OutArgument() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(out I<object> x, out IIn<object> y, out IOut<object> z) { G(out x, out y, out z); } static void G(out I<object?> x, out IIn<object?> y, out IOut<object?> z) { F(out x, out y, out z); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,15): warning CS8624: Argument of type 'I<object>' cannot be used as an output of type 'I<object?>' for parameter 'x' in 'void C.G(out I<object?> x, out IIn<object?> y, out IOut<object?> z)' due to differences in the nullability of reference types. // G(out x, out y, out z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "x").WithArguments("I<object>", "I<object?>", "x", "void C.G(out I<object?> x, out IIn<object?> y, out IOut<object?> z)").WithLocation(8, 15), // (8,29): warning CS8624: Argument of type 'IOut<object>' cannot be used as an output of type 'IOut<object?>' for parameter 'z' in 'void C.G(out I<object?> x, out IIn<object?> y, out IOut<object?> z)' due to differences in the nullability of reference types. // G(out x, out y, out z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "z").WithArguments("IOut<object>", "IOut<object?>", "z", "void C.G(out I<object?> x, out IIn<object?> y, out IOut<object?> z)").WithLocation(8, 29), // (12,15): warning CS8624: Argument of type 'I<object?>' cannot be used as an output of type 'I<object>' for parameter 'x' in 'void C.F(out I<object> x, out IIn<object> y, out IOut<object> z)' due to differences in the nullability of reference types. // F(out x, out y, out z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "x").WithArguments("I<object?>", "I<object>", "x", "void C.F(out I<object> x, out IIn<object> y, out IOut<object> z)").WithLocation(12, 15), // (12,22): warning CS8624: Argument of type 'IIn<object?>' cannot be used as an output of type 'IIn<object>' for parameter 'y' in 'void C.F(out I<object> x, out IIn<object> y, out IOut<object> z)' due to differences in the nullability of reference types. // F(out x, out y, out z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "y").WithArguments("IIn<object?>", "IIn<object>", "y", "void C.F(out I<object> x, out IIn<object> y, out IOut<object> z)").WithLocation(12, 22) ); } [Fact] public void IdentityConversion_RefArgument() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(ref I<object> x, ref IIn<object> y, ref IOut<object> z) { G(ref x, ref y, ref z); } static void G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z) { F(ref x, ref y, ref z); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,15): warning CS8620: Argument of type 'I<object>' cannot be used as an input of type 'I<object?>' for parameter 'x' in 'void C.G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z)' due to differences in the nullability of reference types. // G(ref x, ref y, ref z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "x", "void C.G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z)").WithLocation(8, 15), // (8,22): warning CS8620: Argument of type 'IIn<object>' cannot be used as an input of type 'IIn<object?>' for parameter 'y' in 'void C.G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z)' due to differences in the nullability of reference types. // G(ref x, ref y, ref z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IIn<object>", "IIn<object?>", "y", "void C.G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z)").WithLocation(8, 22), // (8,29): warning CS8620: Argument of type 'IOut<object>' cannot be used as an input of type 'IOut<object?>' for parameter 'z' in 'void C.G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z)' due to differences in the nullability of reference types. // G(ref x, ref y, ref z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IOut<object>", "IOut<object?>", "z", "void C.G(ref I<object?> x, ref IIn<object?> y, ref IOut<object?> z)").WithLocation(8, 29), // (12,15): warning CS8620: Argument of type 'I<object?>' cannot be used as an input of type 'I<object>' for parameter 'x' in 'void C.F(ref I<object> x, ref IIn<object> y, ref IOut<object> z)' due to differences in the nullability of reference types. // F(ref x, ref y, ref z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object?>", "I<object>", "x", "void C.F(ref I<object> x, ref IIn<object> y, ref IOut<object> z)").WithLocation(12, 15), // (12,22): warning CS8620: Argument of type 'IIn<object?>' cannot be used as an input of type 'IIn<object>' for parameter 'y' in 'void C.F(ref I<object> x, ref IIn<object> y, ref IOut<object> z)' due to differences in the nullability of reference types. // F(ref x, ref y, ref z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IIn<object?>", "IIn<object>", "y", "void C.F(ref I<object> x, ref IIn<object> y, ref IOut<object> z)").WithLocation(12, 22), // (12,29): warning CS8620: Argument of type 'IOut<object?>' cannot be used as an input of type 'IOut<object>' for parameter 'z' in 'void C.F(ref I<object> x, ref IIn<object> y, ref IOut<object> z)' due to differences in the nullability of reference types. // F(ref x, ref y, ref z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IOut<object?>", "IOut<object>", "z", "void C.F(ref I<object> x, ref IIn<object> y, ref IOut<object> z)").WithLocation(12, 29)); } [Fact] public void IdentityConversion_InArgument() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static void F(in I<object> x, in IIn<object> y, in IOut<object> z) { G(in x, in y, in z); } static void G(in I<object?> x, in IIn<object?> y, in IOut<object?> z) { F(in x, in y, in z); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8620: Nullability of reference types in argument of type 'I<object>' doesn't match target type 'I<object?>' for parameter 'x' in 'void C.G(in I<object?> x, in IIn<object?> y, in IOut<object?> z)'. // G(in x, in y, in z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "x", "void C.G(in I<object?> x, in IIn<object?> y, in IOut<object?> z)").WithLocation(8, 14), // (8,20): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'y' in 'void C.G(in I<object?> x, in IIn<object?> y, in IOut<object?> z)'. // G(in x, in y, in z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IIn<object>", "IIn<object?>", "y", "void C.G(in I<object?> x, in IIn<object?> y, in IOut<object?> z)").WithLocation(8, 20), // (12,14): warning CS8620: Nullability of reference types in argument of type 'I<object?>' doesn't match target type 'I<object>' for parameter 'x' in 'void C.F(in I<object> x, in IIn<object> y, in IOut<object> z)'. // F(in x, in y, in z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object?>", "I<object>", "x", "void C.F(in I<object> x, in IIn<object> y, in IOut<object> z)").WithLocation(12, 14), // (12,26): warning CS8620: Nullability of reference types in argument of type 'IOut<object?>' doesn't match target type 'IOut<object>' for parameter 'z' in 'void C.F(in I<object> x, in IIn<object> y, in IOut<object> z)'. // F(in x, in y, in z); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IOut<object?>", "IOut<object>", "z", "void C.F(in I<object> x, in IIn<object> y, in IOut<object> z)").WithLocation(12, 26)); } [Fact] public void IdentityConversion_ExtensionThis() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } static class E { static void F1(object x, object? y) { x.F1A(); y.F1A(); x.F1B(); y.F1B(); // 1 } static void F1A(this object? o) { } static void F1B(this object o) { } static void F2(I<object> x, I<object?> y) { x.F2A(); // 2 y.F2A(); x.F2B(); y.F2B(); // 3 } static void F2A(this I<object?> o) { } static void F2B(this I<object> o) { } static void F3(IIn<object> x, IIn<object?> y) { x.F3A(); // 4 y.F3A(); x.F3B(); y.F3B(); } static void F3A(this IIn<object?> o) { } static void F3B(this IIn<object> o) { } static void F4(IOut<object> x, IOut<object?> y) { x.F4A(); y.F4A(); x.F4B(); y.F4B(); // 5 } static void F4A(this IOut<object?> o) { } static void F4B(this IOut<object> o) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8604: Possible null reference argument for parameter 'o' in 'void E.F1B(object o)'. // y.F1B(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("o", "void E.F1B(object o)").WithLocation(11, 9), // (17,9): warning CS8620: Nullability of reference types in argument of type 'I<object>' doesn't match target type 'I<object?>' for parameter 'o' in 'void E.F2A(I<object?> o)'. // x.F2A(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "o", "void E.F2A(I<object?> o)").WithLocation(17, 9), // (20,9): warning CS8620: Nullability of reference types in argument of type 'I<object?>' doesn't match target type 'I<object>' for parameter 'o' in 'void E.F2B(I<object> o)'. // y.F2B(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object?>", "I<object>", "o", "void E.F2B(I<object> o)").WithLocation(20, 9), // (26,9): warning CS8620: Nullability of reference types in argument of type 'IIn<object>' doesn't match target type 'IIn<object?>' for parameter 'o' in 'void E.F3A(IIn<object?> o)'. // x.F3A(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("IIn<object>", "IIn<object?>", "o", "void E.F3A(IIn<object?> o)").WithLocation(26, 9), // (38,9): warning CS8620: Nullability of reference types in argument of type 'IOut<object?>' doesn't match target type 'IOut<object>' for parameter 'o' in 'void E.F4B(IOut<object> o)'. // y.F4B(); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IOut<object?>", "IOut<object>", "o", "void E.F4B(IOut<object> o)").WithLocation(38, 9)); } // https://github.com/dotnet/roslyn/issues/29899: Clone this method using types from unannotated assemblies // rather than `x!`, particularly because `x!` results in IsNullable=false rather than IsNullable=null. [Fact] public void IdentityConversion_TypeInference_IsNullableNull() { var source = @"class A<T> { } class B { static T F1<T>(T x, T y) { return x; } static void G1(object? x, object y) { F1(x, x!).ToString(); F1(x!, x).ToString(); F1(y, y!).ToString(); F1(y!, y).ToString(); } static T F2<T>(A<T> x, A<T> y) { throw new System.Exception(); } static void G(A<object?> z, A<object> w) { F2(z, z!).ToString(); F2(z!, z).ToString(); F2(w, w!).ToString(); F2(w!, w).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // F1(x, x!).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x, x!)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F1(x!, x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x!, x)").WithLocation(13, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // F2(z, z!).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(z, z!)").WithLocation(23, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // F2(z!, z).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(z!, z)").WithLocation(24, 9)); } [Fact] public void IdentityConversion_IndexerArgumentsOrder() { var source = @"interface I<T> { } class C { static object F(C c, I<string> x, I<object> y) { return c[ y: y, // warn 1 x: x]; } static object G(C c, I<string?> x, I<object?> y) { return c[ y: y, x: x]; // warn 2 } object this[I<string> x, I<object?> y] => new object(); }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,16): warning CS8620: Nullability of reference types in argument of type 'I<object>' doesn't match target type 'I<object?>' for parameter 'y' in 'object C.this[I<string> x, I<object?> y]'. // y: y, // warn 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object>", "I<object?>", "y", "object C.this[I<string> x, I<object?> y]").WithLocation(7, 16), // (14,16): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'x' in 'object C.this[I<string> x, I<object?> y]'. // x: x]; // warn 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<string?>", "I<string>", "x", "object C.this[I<string> x, I<object?> y]").WithLocation(14, 16)); } [Fact] public void IncrementOperator_01() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(CL0? x1) { CL0? u1 = ++x1; CL0 v1 = u1 ?? new CL0(); CL0 w1 = x1 ?? new CL0(); } void Test2(CL0? x2) { CL0 u2 = x2++; CL0 v2 = x2 ?? new CL0(); } void Test3(CL1? x3) { CL1 u3 = --x3; CL1 v3 = x3; } void Test4(CL1 x4) { CL1? u4 = x4--; // Result of increment is nullable, storing it in not nullable parameter. CL1 v4 = u4 ?? new CL1(); CL1 w4 = x4 ?? new CL1(); } void Test5(CL1 x5) { CL1 u5 = --x5; } void Test6(CL1 x6) { x6--; } void Test7() { CL1 x7; x7--; } } class CL0 { public static CL0 operator ++(CL0 x) { return new CL0(); } } class CL1 { public static CL1? operator --(CL1? x) { return new CL1(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,21): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator ++(CL0 x)'. // CL0? u1 = ++x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL0 CL0.operator ++(CL0 x)").WithLocation(10, 21), // (16,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator ++(CL0 x)'. // CL0 u2 = x2++; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("x", "CL0 CL0.operator ++(CL0 x)").WithLocation(16, 18), // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 u2 = x2++; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2++").WithLocation(16, 18), // (21,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u3 = --x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x3").WithLocation(21, 18), // (22,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 v3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(22, 18), // (26,19): warning CS8601: Possible null reference assignment. // CL1? u4 = x4--; // Result of increment is nullable, storing it in not nullable parameter. Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x4--").WithLocation(26, 19), // (32,18): warning CS8601: Possible null reference assignment. // CL1 u5 = --x5; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "--x5").WithLocation(32, 18), // (32,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u5 = --x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x5").WithLocation(32, 18), // (37,9): warning CS8601: Possible null reference assignment. // x6--; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x6--").WithLocation(37, 9), // (43,9): error CS0165: Use of unassigned local variable 'x7' // x7--; Diagnostic(ErrorCode.ERR_UseDefViolation, "x7").WithArguments("x7").WithLocation(43, 9), // (43,9): warning CS8601: Possible null reference assignment. // x7--; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x7--").WithLocation(43, 9) ); } [Fact] public void IncrementOperator_02() { CSharpCompilation c = CreateCompilation( new[] { @"#pragma warning disable 8618 class C { static void Main() { } void Test1() { CL0? u1 = ++x1; CL0 v1 = u1 ?? new CL0(); } void Test2() { CL0 u2 = x2++; } void Test3() { CL1 u3 = --x3; } void Test4() { CL1? u4 = x4--; // Result of increment is nullable, storing it in not nullable property. CL1 v4 = u4 ?? new CL1(); } void Test5(CL1 x5) { CL1 u5 = --x5; } CL0? x1 {get; set;} CL0? x2 {get; set;} CL1? x3 {get; set;} CL1 x4 {get; set;} CL1 x5 {get; set;} } class CL0 { public static CL0 operator ++(CL0 x) { return new CL0(); } } class CL1 { public static CL1? operator --(CL1? x) { return new CL1(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,21): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator ++(CL0 x)'. // CL0? u1 = ++x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL0 CL0.operator ++(CL0 x)").WithLocation(10, 21), // (16,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator ++(CL0 x)'. // CL0 u2 = x2++; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("x", "CL0 CL0.operator ++(CL0 x)").WithLocation(16, 18), // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 u2 = x2++; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2++").WithLocation(16, 18), // (21,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u3 = --x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x3").WithLocation(21, 18), // (26,19): warning CS8601: Possible null reference assignment. // CL1? u4 = x4--; // Result of increment is nullable, storing it in not nullable property. Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x4--").WithLocation(26, 19), // (32,18): warning CS8601: Possible null reference assignment. // CL1 u5 = --x5; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "--x5").WithLocation(32, 18), // (32,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u5 = --x5; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x5").WithLocation(32, 18) ); } [Fact] public void IncrementOperator_03() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(X1 x1) { CL0? u1 = ++x1[0]; CL0 v1 = u1 ?? new CL0(); } void Test2(X1 x2) { CL0 u2 = x2[0]++; } void Test3(X3 x3) { CL1 u3 = --x3[0]; } void Test4(X4 x4) { CL1? u4 = x4[0]--; // Result of increment is nullable, storing it in not nullable parameter. CL1 v4 = u4 ?? new CL1(); } void Test5(X4 x5) { CL1 u5 = --x5[0]; } } class CL0 { public static CL0 operator ++(CL0 x) { return new CL0(); } } class CL1 { public static CL1? operator --(CL1? x) { return new CL1(); } } class X1 { public CL0? this[int x] { get { return null; } set { } } } class X3 { public CL1? this[int x] { get { return null; } set { } } } class X4 { public CL1 this[int x] { get { return new CL1(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,21): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator ++(CL0 x)'. // CL0? u1 = ++x1[0]; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1[0]").WithArguments("x", "CL0 CL0.operator ++(CL0 x)").WithLocation(10, 21), // (16,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL0 CL0.operator ++(CL0 x)'. // CL0 u2 = x2[0]++; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2[0]").WithArguments("x", "CL0 CL0.operator ++(CL0 x)").WithLocation(16, 18), // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 u2 = x2[0]++; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2[0]++").WithLocation(16, 18), // (21,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u3 = --x3[0]; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x3[0]").WithLocation(21, 18), // (26,19): warning CS8601: Possible null reference assignment. // CL1? u4 = x4[0]--; // Result of increment is nullable, storing it in not nullable parameter. Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x4[0]--").WithLocation(26, 19), // (32,18): warning CS8601: Possible null reference assignment. // CL1 u5 = --x5[0]; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "--x5[0]").WithLocation(32, 18), // (32,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u5 = --x5[0]; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x5[0]").WithLocation(32, 18) ); } [Fact] public void IncrementOperator_04() { CSharpCompilation c = CreateCompilation(new[] { @" class C { static void Main() { } void Test1(dynamic? x1) { dynamic? u1 = ++x1; dynamic v1 = u1 ?? new object(); } void Test2(dynamic? x2) { dynamic u2 = x2++; } void Test3(dynamic? x3) { dynamic u3 = --x3; } void Test4(dynamic x4) { dynamic? u4 = x4--; dynamic v4 = u4 ?? new object(); } void Test5(dynamic x5) { dynamic u5 = --x5; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (16,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // dynamic u2 = x2++; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2++").WithLocation(16, 22), // (21,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // dynamic u3 = --x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "--x3").WithLocation(21, 22) ); } [Fact] public void IncrementOperator_05() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(B? x1) { B? u1 = ++x1; B v1 = u1 ?? new B(); } } class A { public static C? operator ++(A x) { return new C(); } } class C : A { public static implicit operator B(C x) { return new B(); } } class B : A { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'C? A.operator ++(A x)'. // B? u1 = ++x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "C? A.operator ++(A x)").WithLocation(10, 19), // (10,17): warning CS8604: Possible null reference argument for parameter 'x' in 'C.implicit operator B(C x)'. // B? u1 = ++x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "++x1").WithArguments("x", "C.implicit operator B(C x)").WithLocation(10, 17) ); } [Fact] public void IncrementOperator_06() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(B x1) { B u1 = ++x1; } } class A { public static C operator ++(A x) { return new C(); } } class C : A { public static implicit operator B?(C x) { return new B(); } } class B : A { } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,16): warning CS8601: Possible null reference assignment. // B u1 = ++x1; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "++x1").WithLocation(10, 16), // (10,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // B u1 = ++x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "++x1").WithLocation(10, 16) ); } [Fact] public void IncrementOperator_07() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(Convertible? x1) { Convertible? u1 = ++x1; Convertible v1 = u1 ?? new Convertible(); } void Test2(int? x2) { var u2 = ++x2; } void Test3(byte x3) { var u3 = ++x3; } } class Convertible { public static implicit operator int(Convertible c) { return 0; } public static implicit operator Convertible(int i) { return new Convertible(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,29): warning CS8604: Possible null reference argument for parameter 'c' in 'Convertible.implicit operator int(Convertible c)'. // Convertible? u1 = ++x1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("c", "Convertible.implicit operator int(Convertible c)").WithLocation(10, 29) ); } [Fact] public void CompoundAssignment_01() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL1? x1, CL0 y1) { CL1? u1 = x1 += y1; // 1, 2 CL1 v1 = u1 ?? new CL1(); CL1 w1 = x1 ?? new CL1(); } } class CL0 { public static CL1 operator +(CL0 x, CL0 y) { return new CL1(); } } class CL1 { public static implicit operator CL0(CL1 x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1.implicit operator CL0(CL1 x)'. // CL1? u1 = x1 += y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL1.implicit operator CL0(CL1 x)").WithLocation(10, 19) ); } [Fact] public void CompoundAssignment_02() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL1? x1, CL0? y1) { CL1? u1 = x1 += y1; // 1, 2 CL1 v1 = u1 ?? new CL1(); CL1 w1 = x1 ?? new CL1(); } } class CL0 { public static CL1 operator +(CL0 x, CL0 y) { return new CL1(); } } class CL1 { public static implicit operator CL0(CL1? x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1 CL0.operator +(CL0 x, CL0 y)'. // CL1? u1 = x1 += y1; // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL1 CL0.operator +(CL0 x, CL0 y)").WithLocation(10, 19), // (10,25): warning CS8604: Possible null reference argument for parameter 'y' in 'CL1 CL0.operator +(CL0 x, CL0 y)'. // CL1? u1 = x1 += y1; // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y1").WithArguments("y", "CL1 CL0.operator +(CL0 x, CL0 y)").WithLocation(10, 25) ); } [Fact] public void CompoundAssignment_03() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL1? x1, CL0? y1) { CL1? u1 = x1 += y1; CL1 v1 = u1 ?? new CL1(); CL1 w1 = x1 ?? new CL1(); } void Test2(CL0? x2, CL0 y2) { CL0 u2 = x2 += y2; CL0 w2 = x2; } void Test3(CL0? x3, CL0 y3) { x3 = new CL0(); CL0 u3 = x3 += y3; CL0 w3 = x3; } void Test4(CL0? x4, CL0 y4) { x4 = new CL0(); x4 += y4; CL0 w4 = x4; } } class CL0 { public static CL1 operator +(CL0 x, CL0? y) { return new CL1(); } } class CL1 { public static implicit operator CL0?(CL1? x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1 CL0.operator +(CL0 x, CL0? y)'. // CL1? u1 = x1 += y1; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL1 CL0.operator +(CL0 x, CL0? y)").WithLocation(10, 19), // (17,18): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1 CL0.operator +(CL0 x, CL0? y)'. // CL0 u2 = x2 += y2; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("x", "CL1 CL0.operator +(CL0 x, CL0? y)").WithLocation(17, 18), // (17,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 u2 = x2 += y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2 += y2").WithLocation(17, 18), // (18,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 w2 = x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(18, 18), // (24,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 u3 = x3 += y3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3 += y3").WithLocation(24, 18), // (25,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 w3 = x3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3").WithLocation(25, 18), // (32,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL0 w4 = x4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x4").WithLocation(32, 18) ); } [Fact] public void CompoundAssignment_04() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL1? x1, CL0? y1) { x1 = new CL1(); CL1? u1 = x1 += y1; CL1 w1 = x1; w1 = u1; } void Test2(CL1 x2, CL0 y2) { CL1 u2 = x2 += y2; CL1 w2 = x2; } void Test3(CL1 x3, CL0 y3) { x3 += y3; } void Test4(CL0? x4, CL0 y4) { CL0? u4 = x4 += y4; CL0 v4 = u4 ?? new CL0(); CL0 w4 = x4 ?? new CL0(); } void Test5(CL0 x5, CL0 y5) { x5 += y5; } void Test6(CL0 y6) { CL1 x6; x6 += y6; } } class CL0 { public static CL1? operator +(CL0 x, CL0? y) { return new CL1(); } } class CL1 { public static implicit operator CL0(CL1 x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 w1 = x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(12, 18), // (13,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // w1 = u1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u1").WithLocation(13, 14), // (18,18): warning CS8601: Possible null reference assignment. // CL1 u2 = x2 += y2; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x2 += y2").WithLocation(18, 18), // (18,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 u2 = x2 += y2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2 += y2").WithLocation(18, 18), // (19,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 w2 = x2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(19, 18), // (24,9): warning CS8601: Possible null reference assignment. // x3 += y3; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x3 += y3").WithLocation(24, 9), // (29,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1? CL0.operator +(CL0 x, CL0? y)'. // CL0? u4 = x4 += y4; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x4").WithArguments("x", "CL1? CL0.operator +(CL0 x, CL0? y)").WithLocation(29, 19), // (29,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1.implicit operator CL0(CL1 x)'. // CL0? u4 = x4 += y4; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x4 += y4").WithArguments("x", "CL1.implicit operator CL0(CL1 x)").WithLocation(29, 19), // (36,9): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1.implicit operator CL0(CL1 x)'. // x5 += y5; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x5 += y5").WithArguments("x", "CL1.implicit operator CL0(CL1 x)").WithLocation(36, 9), // (42,9): error CS0165: Use of unassigned local variable 'x6' // x6 += y6; Diagnostic(ErrorCode.ERR_UseDefViolation, "x6").WithArguments("x6").WithLocation(42, 9), // (42,9): warning CS8601: Possible null reference assignment. // x6 += y6; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x6 += y6").WithLocation(42, 9)); } [Fact] public void CompoundAssignment_05() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(int x1, int y1) { var u1 = x1 += y1; } void Test2(int? x2, int y2) { var u2 = x2 += y2; } void Test3(dynamic? x3, dynamic? y3) { dynamic? u3 = x3 += y3; dynamic v3 = u3; dynamic w3 = u3 ?? v3; } void Test4(dynamic? x4, dynamic? y4) { dynamic u4 = x4 += y4; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } [Fact] public void CompoundAssignment_06() { CSharpCompilation c = CreateCompilation( new[] { @"#pragma warning disable 8618 class Test { static void Main() { } void Test1(CL0 y1) { CL1? u1 = x1 += y1; // 1 CL1 v1 = u1 ?? new CL1(); CL1 w1 = x1 ?? new CL1(); } void Test2(CL0 y2) { CL1? u2 = x2 += y2; CL1 v2 = u2 ?? new CL1(); CL1 w2 = x2 ?? new CL1(); } CL1? x1 {get; set;} CL1 x2 {get; set;} } class CL0 { public static CL1 operator +(CL0 x, CL0 y) { return new CL1(); } } class CL1 { public static implicit operator CL0(CL1 x) { return new CL0(); } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1.implicit operator CL0(CL1 x)'. // CL1? u1 = x1 += y1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1").WithArguments("x", "CL1.implicit operator CL0(CL1 x)").WithLocation(10, 19) ); } [Fact] public void CompoundAssignment_07() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL2 x1, CL0 y1) { CL1? u1 = x1[0] += y1; // 1, 2 CL1 v1 = u1 ?? new CL1(); CL1 w1 = x1[0] ?? new CL1(); } void Test2(CL3 x2, CL0 y2) { CL1? u2 = x2[0] += y2; CL1 v2 = u2 ?? new CL1(); CL1 w2 = x2[0] ?? new CL1(); } } class CL0 { public static CL1 operator +(CL0 x, CL0 y) { return new CL1(); } } class CL1 { public static implicit operator CL0(CL1 x) { return new CL0(); } } class CL2 { public CL1? this[int x] { get { return new CL1(); } set { } } } class CL3 { public CL1 this[int x] { get { return new CL1(); } set { } } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1.implicit operator CL0(CL1 x)'. // CL1? u1 = x1[0] += y1; // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1[0]").WithArguments("x", "CL1.implicit operator CL0(CL1 x)").WithLocation(10, 19), // (10,19): warning CS8604: Possible null reference argument for parameter 'x' in 'CL1 CL0.operator +(CL0 x, CL0 y)'. // CL1? u1 = x1[0] += y1; // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x1[0]").WithArguments("x", "CL1 CL0.operator +(CL0 x, CL0 y)").WithLocation(10, 19) ); } [Fact] public void IdentityConversion_CompoundAssignment() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { public static I<object> operator+(I<object> x, C y) => x; public static IIn<object> operator+(IIn<object> x, C y) => x; public static IOut<object> operator+(IOut<object> x, C y) => x; static void F(C c, I<object> x, I<object?> y) { x += c; y += c; // 1, 2, 3 } static void F(C c, IIn<object> x, IIn<object?> y) { x += c; y += c; // 4 } static void F(C c, IOut<object> x, IOut<object?> y) { x += c; y += c; // 5, 6 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // y += c; // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("I<object?>", "I<object>").WithLocation(12, 9), // (12,9): warning CS8620: Argument of type 'I<object?>' cannot be used for parameter 'x' of type 'I<object>' in 'I<object> C.operator +(I<object> x, C y)' due to differences in the nullability of reference types. // y += c; // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object?>", "I<object>", "x", "I<object> C.operator +(I<object> x, C y)").WithLocation(12, 9), // (12,9): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // y += c; // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y += c").WithArguments("I<object>", "I<object?>").WithLocation(12, 9), // (17,9): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // y += c; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y += c").WithArguments("IIn<object>", "IIn<object?>").WithLocation(17, 9), // (22,9): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // y += c; // 5, 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("IOut<object?>", "IOut<object>").WithLocation(22, 9), // (22,9): warning CS8620: Argument of type 'IOut<object?>' cannot be used for parameter 'x' of type 'IOut<object>' in 'IOut<object> C.operator +(IOut<object> x, C y)' due to differences in the nullability of reference types. // y += c; // 5, 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IOut<object?>", "IOut<object>", "x", "IOut<object> C.operator +(IOut<object> x, C y)").WithLocation(22, 9) ); } [Fact] public void Events_01() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } event System.Action? E1; void Test1() { E1(); } delegate void D2 (object x); event D2 E2; void Test2() { E2(null); } delegate object? D3 (); event D3 E3; void Test3() { object x3 = E3(); } void Test4() { //E1?(); System.Action? x4 = E1; //x4?(); } void Test5() { System.Action x5 = E1; } void Test6(D2? x6) { E2 = x6; } void Test7(D2? x7) { E2 += x7; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // E1(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(12, 9), // (16,14): warning CS8618: Non-nullable event 'E2' is uninitialized. Consider declaring the event as nullable. // event D2 E2; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E2").WithArguments("event", "E2").WithLocation(16, 14), // (20,12): warning CS8625: Cannot convert null literal to non-nullable reference type. // E2(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 12), // (24,14): warning CS8618: Non-nullable event 'E3' is uninitialized. Consider declaring the event as nullable. // event D3 E3; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E3").WithArguments("event", "E3").WithLocation(24, 14), // (28,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x3 = E3(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E3()").WithLocation(28, 21), // (40,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action x5 = E1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E1").WithLocation(40, 28), // (45,14): warning CS8601: Possible null reference assignment. // E2 = x6; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x6").WithLocation(45, 14) ); } // https://github.com/dotnet/roslyn/issues/29901: Events are not tracked for structs. // (This should be fixed if/when struct member state is populated lazily.) [Fact(Skip = "https://github.com/dotnet/roslyn/issues/29901")] [WorkItem(29901, "https://github.com/dotnet/roslyn/issues/29901")] public void Events_02() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } } struct TS1 { event System.Action? E1; TS1(System.Action x1) { E1 = x1; System.Action y1 = E1 ?? x1; E1 = x1; TS1 z1 = this; y1 = z1.E1 ?? x1; } void Test3(System.Action x3) { TS1 s3; s3.E1 = x3; System.Action y3 = s3.E1 ?? x3; s3.E1 = x3; TS1 z3 = s3; y3 = z3.E1 ?? x3; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( ); } // https://github.com/dotnet/roslyn/issues/29901: Events are not tracked for structs. // (This should be fixed if/when struct member state is populated lazily.) [Fact(Skip = "https://github.com/dotnet/roslyn/issues/29901")] [WorkItem(29901, "https://github.com/dotnet/roslyn/issues/29901")] public void Events_03() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } } struct TS2 { event System.Action? E2; TS2(System.Action x2) { this = new TS2(); System.Action z2 = E2; System.Action y2 = E2 ?? x2; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (16,28): warning CS8600: Converting null literal or possible null value to non-nullable type. // System.Action z2 = E2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(16, 28) ); } [Fact] public void Events_04() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL0? x1, System.Action? y1) { System.Action v1 = x1.E1 += y1; } void Test2(CL0? x2, System.Action? y2) { System.Action v2 = x2.E1 -= y2; } } class CL0 { public event System.Action? E1; void Dummy() { var x = E1; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (10,28): error CS0029: Cannot implicitly convert type 'void' to 'System.Action' // System.Action v1 = x1.E1 += y1; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x1.E1 += y1").WithArguments("void", "System.Action").WithLocation(10, 28), // (10,28): warning CS8602: Dereference of a possibly null reference. // System.Action v1 = x1.E1 += y1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(10, 28), // (15,28): error CS0029: Cannot implicitly convert type 'void' to 'System.Action' // System.Action v2 = x2.E1 -= y2; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x2.E1 -= y2").WithArguments("void", "System.Action").WithLocation(15, 28), // (15,28): warning CS8602: Dereference of a possibly null reference. // System.Action v2 = x2.E1 -= y2; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(15, 28) ); } [Fact] public void Events_05() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } public event System.Action E1; void Test1(Test? x1) { System.Action v1 = x1.E1; } } " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (8,32): warning CS8618: Non-nullable event 'E1' is uninitialized. Consider declaring the event as nullable. // public event System.Action E1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(8, 32), // (12,28): warning CS8602: Dereference of a possibly null reference. // System.Action v1 = x1.E1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(12, 28) ); } [Theory] [InlineData("")] [InlineData("static ")] [WorkItem(42557, "https://github.com/dotnet/roslyn/issues/42557")] public void EventAccessor_NonNullableEvent(string modifiers) { var source = @" class C { " + modifiers + @"event System.Action E1 = null!; " + modifiers + @"void M0(System.Action e2) { E1 += e2; E1.Invoke(); } " + modifiers + @"void M1() { E1 += () => { }; E1.Invoke(); } " + modifiers + @"void M2(System.Action? e2) { E1 += e2; E1.Invoke(); } " + modifiers + @"void M3() { E1 += null; E1.Invoke(); } " + modifiers + @"void M4() { E1 -= () => { }; E1.Invoke(); // 1 } " + modifiers + @"void M5(System.Action? e2) { E1 -= e2; E1.Invoke(); // 2 } " + modifiers + @"void M6() { E1 -= null; E1.Invoke(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (33,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(33, 9), // (39,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(39, 9) ); } [Theory] [InlineData("")] [InlineData("static ")] [WorkItem(42557, "https://github.com/dotnet/roslyn/issues/42557")] public void EventAccessor_NullableEvent(string modifiers) { var source = @" class C { " + modifiers + @"event System.Action? E1; " + modifiers + @"void M0(System.Action e2) { E1 += e2; E1.Invoke(); } " + modifiers + @"void M1() { E1 += () => { }; E1.Invoke(); } " + modifiers + @"void M2(System.Action? e2) { E1 += e2; E1.Invoke(); // 1 } " + modifiers + @"void M3() { E1 += null; E1.Invoke(); // 2 } " + modifiers + @"void M4() { E1 -= () => { }; E1.Invoke(); // 3 } " + modifiers + @"void M(System.Action? e2) { E1 -= e2; E1.Invoke(); // 4 } " + modifiers + @"void M() { E1 -= null; E1.Invoke(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (21,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(21, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(27, 9), // (33,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(33, 9), // (39,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(39, 9), // (45,9): warning CS8602: Dereference of a possibly null reference. // E1.Invoke(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "E1").WithLocation(45, 9) ); } [Fact] [WorkItem(42557, "https://github.com/dotnet/roslyn/issues/42557")] public void InvalidEventAssignment_01() { var source = @" using System; class C { event Action? E1; static void M1() { E1 += () => { }; E1.Invoke(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (10,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.E1' // E1 += () => { }; Diagnostic(ErrorCode.ERR_ObjectRequired, "E1").WithArguments("C.E1").WithLocation(10, 9), // (11,9): error CS0120: An object reference is required for the non-static field, method, or property 'C.E1' // E1.Invoke(); Diagnostic(ErrorCode.ERR_ObjectRequired, "E1").WithArguments("C.E1").WithLocation(11, 9) ); } [Fact] [WorkItem(42557, "https://github.com/dotnet/roslyn/issues/42557")] public void InvalidEventAssignment_02() { var source = @" using System; class C { public event Action? E1; } class Program { void M1(bool b) { var c = new C(); if (b) c.E1.Invoke(); c.E1 += () => { }; c.E1.Invoke(); } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (14,18): error CS0070: The event 'C.E1' can only appear on the left hand side of += or -= (except when used from within the type 'C') // if (b) c.E1.Invoke(); Diagnostic(ErrorCode.ERR_BadEventUsage, "E1").WithArguments("C.E1", "C").WithLocation(14, 18), // (16,11): error CS0070: The event 'C.E1' can only appear on the left hand side of += or -= (except when used from within the type 'C') // c.E1.Invoke(); Diagnostic(ErrorCode.ERR_BadEventUsage, "E1").WithArguments("C.E1", "C").WithLocation(16, 11) ); } [Fact] [WorkItem(42557, "https://github.com/dotnet/roslyn/issues/42557")] public void EventAssignment_NoMemberSlot() { var source = @" using System; class C { public event Action? E1; } class Program { C M0() => new C(); void M1() { M0().E1 += () => { }; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (6,26): warning CS0067: The event 'C.E1' is never used // public event Action? E1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("C.E1").WithLocation(6, 26) ); } [WorkItem(31018, "https://github.com/dotnet/roslyn/issues/31018")] [Fact] public void EventAssignment() { var source = @"#pragma warning disable 0067 using System; class A<T> { } class B { event Action<A<object?>> E; static void M1() { var b1 = new B(); b1.E += F1; // 1 b1.E += F2; // 2 b1.E += F3; b1.E += F4; } static void M2(Action<A<object>> f1, Action<A<object>?> f2, Action<A<object?>> f3, Action<A<object?>?> f4) { var b2 = new B(); b2.E += f1; // 3 b2.E += f2; // 4 b2.E += f3; b2.E += f4; } static void M3() { var b3 = new B(); b3.E += (A<object> a) => { }; // 5 b3.E += (A<object>? a) => { }; // 6 b3.E += (A<object?> a) => { }; b3.E += (A<object?>? a) => { }; // 7 } static void F1(A<object> a) { } static void F2(A<object>? a) { } static void F3(A<object?> a) { } static void F4(A<object?>? a) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/31018: Report warnings for // 3 and // 4. comp.VerifyDiagnostics( // (6,30): warning CS8618: Non-nullable event 'E' is uninitialized. Consider declaring the event as nullable. // event Action<A<object?>> E; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E").WithArguments("event", "E").WithLocation(6, 30), // (10,17): warning CS8622: Nullability of reference types in type of parameter 'a' of 'void B.F1(A<object> a)' doesn't match the target delegate 'Action<A<object?>>'. // b1.E += F1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F1").WithArguments("a", "void B.F1(A<object> a)", "System.Action<A<object?>>").WithLocation(10, 17), // (11,17): warning CS8622: Nullability of reference types in type of parameter 'a' of 'void B.F2(A<object>? a)' doesn't match the target delegate 'Action<A<object?>>'. // b1.E += F2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F2").WithArguments("a", "void B.F2(A<object>? a)", "System.Action<A<object?>>").WithLocation(11, 17), // (26,17): warning CS8622: Nullability of reference types in type of parameter 'a' of 'lambda expression' doesn't match the target delegate 'Action<A<object?>>'. // b3.E += (A<object> a) => { }; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(A<object> a) => { }").WithArguments("a", "lambda expression", "System.Action<A<object?>>").WithLocation(26, 17), // (27,17): warning CS8622: Nullability of reference types in type of parameter 'a' of 'lambda expression' doesn't match the target delegate 'Action<A<object?>>'. // b3.E += (A<object>? a) => { }; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(A<object>? a) => { }").WithArguments("a", "lambda expression", "System.Action<A<object?>>").WithLocation(27, 17), // (29,17): warning CS8622: Nullability of reference types in type of parameter 'a' of 'lambda expression' doesn't match the target delegate 'Action<A<object?>>'. // b3.E += (A<object?>? a) => { }; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(A<object?>? a) => { }").WithArguments("a", "lambda expression", "System.Action<A<object?>>").WithLocation(29, 17)); } [Fact] public void AsOperator_01() { CSharpCompilation c = CreateCompilation(new[] { @" class Test { static void Main() { } void Test1(CL1 x1) { object y1 = x1 as object ?? new object(); } void Test2(int x2) { object y2 = x2 as object ?? new object(); } void Test3(CL1? x3) { object y3 = x3 as object; } void Test4(int? x4) { object y4 = x4 as object; } void Test5(object x5) { CL1 y5 = x5 as CL1; } void Test6() { CL1 y6 = null as CL1; } void Test7<T>(T x7) { CL1 y7 = x7 as CL1; } } class CL1 {} " }, options: WithNullableEnable()); c.VerifyDiagnostics( // (20,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y3 = x3 as object; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x3 as object").WithLocation(20, 21), // (25,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y4 = x4 as object; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x4 as object").WithLocation(25, 21), // (30,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 y5 = x5 as CL1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x5 as CL1").WithLocation(30, 18), // (35,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 y6 = null as CL1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null as CL1").WithLocation(35, 18), // (40,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // CL1 y7 = x7 as CL1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x7 as CL1").WithLocation(40, 18) ); } [Fact] public void ReturningValues_IEnumerableT() { var source = @" public class C { System.Collections.Generic.IEnumerable<string> M() { return null; // 1 } public System.Collections.Generic.IEnumerable<string>? M2() { return null; } System.Collections.Generic.IEnumerable<string> M3() => null; // 2 System.Collections.Generic.IEnumerable<string>? M4() => null; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,16): warning CS8603: Possible null reference return. // return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 16), // (12,60): warning CS8603: Possible null reference return. // System.Collections.Generic.IEnumerable<string> M3() => null; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(12, 60) ); var source2 = @" class D { void M(C c) { c.M2() /*T:System.Collections.Generic.IEnumerable<string!>?*/ ; } } "; var comp2 = CreateCompilation(source2, references: new[] { comp.EmitToImageReference() }, options: WithNullableEnable()); comp2.VerifyTypes(); } [Fact] public void Yield_IEnumerableT() { var source = @" public class C { public System.Collections.Generic.IEnumerable<string> M() { yield return null; // 1 yield return """"; yield return null; // 2 yield break; } public System.Collections.Generic.IEnumerable<string?> M2() { yield return null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,22): warning CS8603: Possible null reference return. // yield return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 22), // (8,22): warning CS8603: Possible null reference return. // yield return null; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 22) ); var source2 = @" class D { void M(C c) { c.M() /*T:System.Collections.Generic.IEnumerable<string!>!*/ ; c.M2() /*T:System.Collections.Generic.IEnumerable<string?>!*/ ; } } "; var comp2 = CreateCompilation(source2, references: new[] { comp.EmitToImageReference() }, options: WithNullableEnable()); comp2.VerifyTypes(); } [Fact] public void Yield_IEnumerableT_LocalFunction() { var source = @" class C { void Method() { _ = M(); _ = M2(); System.Collections.Generic.IEnumerable<string> M() { yield return null; // 1 yield return """"; yield return null; // 2 yield break; } System.Collections.Generic.IEnumerable<string?> M2() { yield return null; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,26): warning CS8603: Possible null reference return. // yield return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(11, 26), // (13,26): warning CS8603: Possible null reference return. // yield return null; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(13, 26) ); } [Fact] public void Yield_IEnumerableT_GenericT() { var source = @" class C { System.Collections.Generic.IEnumerable<T> M<T>() { yield return default; // 1 } System.Collections.Generic.IEnumerable<T> M1<T>() where T : class { yield return default; // 2 } System.Collections.Generic.IEnumerable<T> M2<T>() where T : class? { yield return default; // 3 } System.Collections.Generic.IEnumerable<T?> M3<T>() where T : class { yield return default; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (6,22): warning CS8603: Possible null reference return. // yield return default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(6, 22), // (10,22): warning CS8603: Possible null reference return. // yield return default; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(10, 22), // (14,22): warning CS8603: Possible null reference return. // yield return default; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(14, 22) ); } [Fact] public void Yield_IEnumerableT_ErrorValue() { var source = @" class C { System.Collections.Generic.IEnumerable<string> M() { yield return bad; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (6,22): error CS0103: The name 'bad' does not exist in the current context // yield return bad; Diagnostic(ErrorCode.ERR_NameNotInContext, "bad").WithArguments("bad").WithLocation(6, 22) ); } [Fact] public void Yield_IEnumerableT_ErrorValue2() { var source = @" static class C { static System.Collections.Generic.IEnumerable<object> M(object? x) { yield return (C)x; } static System.Collections.Generic.IEnumerable<object?> M(object? y) { yield return (C?)y; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (6,22): error CS0716: Cannot convert to static type 'C' // yield return (C)x; Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)x").WithArguments("C").WithLocation(6, 22), // (6,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // yield return (C)x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)x").WithLocation(6, 22), // (8,60): error CS0111: Type 'C' already defines a member called 'M' with the same parameter types // static System.Collections.Generic.IEnumerable<object?> M(object? y) Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "M").WithArguments("M", "C").WithLocation(8, 60), // (10,22): error CS0716: Cannot convert to static type 'C' // yield return (C?)y; Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C?)y").WithArguments("C").WithLocation(10, 22) ); } [Fact] public void Yield_IEnumerableT_NoValue() { var source = @" class C { System.Collections.Generic.IEnumerable<string> M() { yield return; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (6,15): error CS1627: Expression expected after yield return // yield return; Diagnostic(ErrorCode.ERR_EmptyYield, "return").WithLocation(6, 15) ); } [Fact] public void Yield_IEnumeratorT() { var source = @" class C { System.Collections.Generic.IEnumerator<string> M() { yield return null; // 1 yield return """"; } System.Collections.Generic.IEnumerator<string?> M2() { yield return null; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (6,22): warning CS8603: Possible null reference return. // yield return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 22) ); } [Fact] public void Yield_IEnumeratorT_LocalFunction() { var source = @" class C { void Method() { _ = M(); _ = M2(); System.Collections.Generic.IEnumerator<string> M() { yield return null; // 1 yield return """"; } System.Collections.Generic.IEnumerator<string?> M2() { yield return null; } } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (11,26): warning CS8603: Possible null reference return. // yield return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(11, 26) ); } [Fact] public void Yield_IEnumerable() { var source = @" class C { System.Collections.IEnumerable M() { yield return null; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void Yield_IEnumerator() { var source = @" class C { System.Collections.IEnumerator M() { yield return null; yield return null; } }"; CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact, CompilerTrait(CompilerFeature.AsyncStreams)] public void Yield_IAsyncEnumerable() { var source = @" using System.Collections.Generic; using System.Threading.Tasks; class C { public static async IAsyncEnumerable<string> M() { yield return null; // 1 yield return null; // 2 await Task.Delay(1); yield break; } public static async IAsyncEnumerable<string?> M2() { yield return null; yield return null; await Task.Delay(1); } void Method() { _ = local(); _ = local2(); async IAsyncEnumerable<string> local() { yield return null; // 3 await Task.Delay(1); yield break; } async IAsyncEnumerable<string?> local2() { yield return null; await Task.Delay(1); } } }"; CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, options: WithNullableEnable()).VerifyDiagnostics( // (8,22): warning CS8603: Possible null reference return. // yield return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 22), // (9,22): warning CS8603: Possible null reference return. // yield return null; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(9, 22), // (26,26): warning CS8603: Possible null reference return. // yield return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(26, 26) ); } [Fact, CompilerTrait(CompilerFeature.AsyncStreams)] public void Yield_IAsyncEnumerator() { var source = @" using System.Collections.Generic; using System.Threading.Tasks; class C { async IAsyncEnumerator<string> M() { yield return null; // 1 yield return null; // 2 await Task.Delay(1); yield break; } async IAsyncEnumerator<string?> M2() { yield return null; yield return null; await Task.Delay(1); } void Method() { _ = local(); _ = local2(); async IAsyncEnumerator<string> local() { yield return null; // 3 await Task.Delay(1); } async IAsyncEnumerator<string?> local2() { yield return null; await Task.Delay(1); yield break; } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, AsyncStreamsTypes }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,22): warning CS8603: Possible null reference return. // yield return null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 22), // (9,22): warning CS8603: Possible null reference return. // yield return null; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(9, 22), // (26,26): warning CS8603: Possible null reference return. // yield return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(26, 26) ); } [Fact] public void Await_01() { var source = @" using System; static class Program { static void Main() { } static async void f() { object x = await new D() ?? new object(); } } class D { public Awaiter GetAwaiter() { return new Awaiter(); } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public object GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void Await_02() { var source = @" using System; static class Program { static void Main() { } static async void f() { object x = await new D(); } } class D { public Awaiter GetAwaiter() { return new Awaiter(); } } class Awaiter : System.Runtime.CompilerServices.INotifyCompletion { public void OnCompleted(Action x) { } public object? GetResult() { throw new Exception(); } public bool IsCompleted { get { return true; } } }"; CreateCompilationWithMscorlib45(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (10,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x = await new D(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "await new D()").WithLocation(10, 20) ); } [Fact] public void Await_03() { var source = @"using System.Threading.Tasks; class Program { async void M(Task? x, Task? y) { if (y == null) return; await x; // 1 await y; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // await x; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 15)); } [Fact] public void Await_ProduceResultTypeFromTask() { var source = @" class C { async void M() { var x = await Async(); x.ToString(); } System.Threading.Tasks.Task<string?> Async() => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void Await_CheckNullReceiver() { var source = @" class C { async void M() { await Async(); } System.Threading.Tasks.Task<string>? Async() => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,15): warning CS8602: Dereference of a possibly null reference. // await Async(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "Async()").WithLocation(6, 15) ); } [Fact] public void Await_ExtensionGetAwaiter() { var source = @" public class Awaitable { async void M() { await Async(); } Awaitable? Async() => throw null!; } public static class Extensions { public static System.Runtime.CompilerServices.TaskAwaiter GetAwaiter(this Awaitable? x) => throw null!; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Await_UpdateExpression() { var source = @" class C { async void M(System.Threading.Tasks.Task<string>? task) { await task; // warn await task; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,15): warning CS8602: Dereference of a possibly null reference. // await task; // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "task").WithLocation(6, 15) ); } [Fact] public void Await_LearnFromNullTest() { var source = @" class C { System.Threading.Tasks.Task<string>? M() => throw null!; async System.Threading.Tasks.Task M2(C? c) { await c?.M(); // warn c.ToString(); // no cascade } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8602: Dereference of a possibly null reference. // await c?.M(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c?.M()").WithLocation(7, 15) ); } [Fact, WorkItem(40452, "https://github.com/dotnet/roslyn/issues/40452")] public void Await_CallInferredTypeArgs_01() { var source = @" using System.Threading.Tasks; class C { Task<T> M1<T>(T item) => throw null!; async Task M2(object? obj) { var task = M1(obj); task.Result.ToString(); // 1 (await task).ToString(); // 2 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // task.Result.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "task.Result").WithLocation(11, 9), // (12,10): warning CS8602: Dereference of a possibly null reference. // (await task).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "await task").WithLocation(12, 10)); } [Fact, WorkItem(40452, "https://github.com/dotnet/roslyn/issues/40452")] public void Await_CallInferredTypeArgs_02() { var source = @" using System.Threading.Tasks; class C { static async Task Main() { object? thisIsNull = await Task.Run(GetNull); thisIsNull.ToString(); // 1 } static object? GetNull() => null; } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // thisIsNull.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "thisIsNull").WithLocation(9, 9)); } [Fact] public void ArrayAccess_LearnFromNullTest() { var source = @" class C { string[] field = null!; void M2(C? c) { _ = (c?.field)[0]; // warn c.ToString(); // no cascade } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,14): warning CS8602: Dereference of a possibly null reference. // _ = (c?.field)[0]; // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c?.field").WithLocation(7, 14) ); } [Fact] public void Call_LambdaConsidersNonFinalState() { var source = @" using System; class C { void M(string? maybeNull1, string? maybeNull2, string? maybeNull3) { M1(() => maybeNull1.Length); // 1 M2(() => maybeNull2.Length, maybeNull2 = """"); // 2 M3(maybeNull3 = """", () => maybeNull3.Length); } void M1<T>(Func<T> lambda) => throw null!; void M1(Func<string> lambda) => throw null!; void M2<T>(Func<T> lambda, object o) => throw null!; void M3<T>(object o, Func<T> lambda) => throw null!; }"; var comp = CreateNullableCompilation(new[] { source }); comp.VerifyDiagnostics( // (7,18): warning CS8602: Dereference of a possibly null reference. // M1(() => maybeNull1.Length); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "maybeNull1").WithLocation(7, 18), // (8,18): warning CS8602: Dereference of a possibly null reference. // M2(() => maybeNull2.Length, maybeNull2 = ""); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "maybeNull2").WithLocation(8, 18) ); } [Fact] public void Call_LearnFromNullTest() { var source = @" class C { string M() => throw null!; C field = null!; void M2(C? c) { _ = (c?.field).M(); // warn c.ToString(); // no cascade } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8602: Dereference of a possibly null reference. // _ = (c?.field).M(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c?.field").WithLocation(8, 14) ); } [Fact, WorkItem(36132, "https://github.com/dotnet/roslyn/issues/36132")] public void Call_MethodTypeInferenceUsesNullabilitiesOfConvertedTypes() { var source = @" class A { } class B { public static implicit operator A(B? b) => new A(); } class C { void Test1(A a, B? b) { A t1 = M<A>(a, b); } void Test2(A a, B? b) { A t2 = M(a, b); // unexpected } T M<T>(T t1, T t2) => t2; }"; var comp = CreateNullableCompilation(source); // There should be no diagnostic. See https://github.com/dotnet/roslyn/issues/36132 comp.VerifyDiagnostics( // (14,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // A t2 = M(a, b); // unexpected Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "M(a, b)").WithLocation(14, 16) ); } [Fact] public void Indexer_LearnFromNullTest() { var source = @" class C { string this[int i] => throw null!; C field = null!; void M(C? c) { _ = (c?.field)[0]; // warn c.ToString(); // no cascade } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8602: Dereference of a possibly null reference. // _ = (c?.field)[0]; // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c?.field").WithLocation(8, 14) ); } [Fact] public void MemberAccess_LearnFromNullTest() { var source = @" class C { string this[int i] => throw null!; C field = null!; void M(C? c) { _ = (c?.field).field; // warn c.ToString(); // no cascade } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8602: Dereference of a possibly null reference. // _ = (c?.field).field; // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c?.field").WithLocation(8, 14) ); } [Theory, WorkItem(31906, "https://github.com/dotnet/roslyn/issues/31906")] [InlineData("==")] [InlineData(">")] [InlineData("<")] [InlineData(">=")] [InlineData("<=")] public void LearnFromNullTest_FromOperatorOnConstant(string op) { var source = @" class C { static void F(string? s, string? s2) { if (s?.Length OPERATOR 1) s.ToString(); else s.ToString(); // 1 if (1 OPERATOR s2?.Length) s2.ToString(); else s2.ToString(); // 2 } }"; var comp = CreateCompilation(source.Replace("OPERATOR", op), options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(14, 13) ); } [Fact] public void LearnFromNullTest_IncludingConstants() { var source = @" class C { void F() { const string s1 = """"; if (s1 == null) s1.ToString(); // 1 if (null == s1) s1.ToString(); // 2 if (s1 != null) s1.ToString(); else s1.ToString(); // 3 if (null != s1) s1.ToString(); else s1.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS0162: Unreachable code detected // s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_UnreachableCode, "s1").WithLocation(8, 13), // (11,13): warning CS0162: Unreachable code detected // s1.ToString(); // 2 Diagnostic(ErrorCode.WRN_UnreachableCode, "s1").WithLocation(11, 13), // (16,13): warning CS0162: Unreachable code detected // s1.ToString(); // 3 Diagnostic(ErrorCode.WRN_UnreachableCode, "s1").WithLocation(16, 13), // (21,13): warning CS0162: Unreachable code detected // s1.ToString(); // 4 Diagnostic(ErrorCode.WRN_UnreachableCode, "s1").WithLocation(21, 13) ); } [Fact, WorkItem(31906, "https://github.com/dotnet/roslyn/issues/31906")] public void LearnFromNullTest_NotEqualsConstant() { var source = @" class C { static void F(string? s, string? s2) { if (s?.Length != 1) s.ToString(); // 1 else s.ToString(); if (1 != s2?.Length) s2.ToString(); // 2 else s2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(12, 13) ); } [Fact, WorkItem(31906, "https://github.com/dotnet/roslyn/issues/31906")] public void LearnFromNullTest_FromIsConstant() { var source = @" class C { static void F(string? s) { if (s?.Length is 1) s.ToString(); else s.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 13) ); } [Fact] public void NoPiaObjectCreation_01() { string pia = @" using System; using System.Runtime.InteropServices; [assembly: ImportedFromTypeLib(""GeneralPIA.dll"")] [assembly: Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58257"")] [ComImport()] [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58277"")] [CoClass(typeof(ClassITest28))] public interface ITest28 { } [Guid(""f9c2d51d-4f44-45f0-9eda-c9d599b58278"")] public abstract class ClassITest28 //: ITest28 { public ClassITest28(int x){} } "; var piaCompilation = CreateCompilationWithMscorlib45(pia, options: TestOptions.DebugDll, parseOptions: TestOptions.Regular7); CompileAndVerify(piaCompilation); string source = @" class UsePia { public static void Main() { } void Test1(ITest28 x1) { x1 = new ITest28(); } void Test2(ITest28 x2) { x2 = new ITest28() ?? x2; } }"; var compilation = CreateCompilationWithMscorlib45(new[] { source }, new MetadataReference[] { new CSharpCompilationReference(piaCompilation, embedInteropTypes: true) }, options: WithNullableEnable(TestOptions.DebugExe)); compilation.VerifyDiagnostics( ); } [Fact] public void SymbolDisplay_01() { var source = @" abstract class B { string? F1; event System.Action? E1; string? P1 {get; set;} string?[][,] P2 {get; set;} System.Action<string?> M1(string? x) {return null;} string[]?[,] M2(string[][,]? x) {return null;} void M3(string?* x) {} public abstract string? this[System.Action? x] {get; set;} public static implicit operator B?(int x) { return null; } } delegate string? D1(); delegate string D2(); interface I1<T>{} interface I2<T>{} class C<T> {} class F : C<F?>, I1<C<B?>>, I2<C<B>?> {} "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); var b = compilation.GetTypeByMetadataName("B"); Assert.Equal("System.String? B.F1", b.GetMember("F1").ToTestDisplayString()); Assert.Equal("event System.Action? B.E1", b.GetMember("E1").ToTestDisplayString()); Assert.Equal("System.String? B.P1 { get; set; }", b.GetMember("P1").ToTestDisplayString()); Assert.Equal("System.String?[][,] B.P2 { get; set; }", b.GetMember("P2").ToTestDisplayString()); Assert.Equal("System.Action<System.String?> B.M1(System.String? x)", b.GetMember("M1").ToTestDisplayString()); Assert.Equal("System.String[]?[,] B.M2(System.String[][,]? x)", b.GetMember("M2").ToTestDisplayString()); Assert.Equal("void B.M3(System.String?* x)", b.GetMember("M3").ToTestDisplayString()); Assert.Equal("System.String? B.this[System.Action? x] { get; set; }", b.GetMember("this[]").ToTestDisplayString()); Assert.Equal("B.implicit operator B?(int)", b.GetMember("op_Implicit").ToDisplayString()); Assert.Equal("String? D1()", compilation.GetTypeByMetadataName("D1") .ToDisplayString(new SymbolDisplayFormat(delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier))); Assert.Equal("String D1()", compilation.GetTypeByMetadataName("D1") .ToDisplayString(new SymbolDisplayFormat(delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); Assert.Equal("String! D2()", compilation.GetTypeByMetadataName("D2") .ToDisplayString(new SymbolDisplayFormat(delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); var f = compilation.GetTypeByMetadataName("F"); Assert.Equal("C<F?>", f.BaseType().ToTestDisplayString()); Assert.Equal("I1<C<B?>>", f.Interfaces()[0].ToTestDisplayString()); Assert.Equal("I2<C<B>?>", f.Interfaces()[1].ToTestDisplayString()); } [Fact] public void NullableAttribute_01() { var source = @"#pragma warning disable 8618 public abstract class B { public string? F1; public event System.Action? E1; public string? P1 {get; set;} public string?[][,] P2 {get; set;} public System.Action<string?> M1(string? x) {throw new System.NotImplementedException();} public string[]?[,] M2(string[][,]? x) {throw new System.NotImplementedException();} public abstract string? this[System.Action? x] {get; set;} public static implicit operator B?(int x) {throw new System.NotImplementedException();} public event System.Action? E2 { add { } remove { } } } public delegate string? D1(); public interface I1<T>{} public interface I2<T>{} public class C<T> {} public class F : C<F?>, I1<C<B?>>, I2<C<B>?> {} "; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (5,33): warning CS0067: The event 'B.E1' is never used // public event System.Action? E1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("B.E1").WithLocation(5, 33) ); CompileAndVerify(compilation, symbolValidator: m => { var b = ((PEModuleSymbol)m).GlobalNamespace.GetTypeMember("B"); Assert.Equal("System.String? B.F1", b.GetMember("F1").ToTestDisplayString()); Assert.Equal("event System.Action? B.E1", b.GetMember("E1").ToTestDisplayString()); Assert.Equal("System.String? B.P1 { get; set; }", b.GetMember("P1").ToTestDisplayString()); Assert.Equal("System.String?[][,] B.P2 { get; set; }", b.GetMember("P2").ToTestDisplayString()); Assert.Equal("System.Action<System.String?> B.M1(System.String? x)", b.GetMember("M1").ToTestDisplayString()); Assert.Equal("System.String[]?[,] B.M2(System.String[][,]? x)", b.GetMember("M2").ToTestDisplayString()); Assert.Equal("System.String? B.this[System.Action? x] { get; set; }", b.GetMember("this[]").ToTestDisplayString()); Assert.Equal("B.implicit operator B?(int)", b.GetMember("op_Implicit").ToDisplayString()); Assert.Equal("event System.Action? B.E2", b.GetMember("E2").ToTestDisplayString()); Assert.Equal("String? D1()", compilation.GetTypeByMetadataName("D1") .ToDisplayString(new SymbolDisplayFormat(delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier))); var f = ((PEModuleSymbol)m).GlobalNamespace.GetTypeMember("F"); Assert.Equal("C<F?>", f.BaseType().ToTestDisplayString()); Assert.Equal("I1<C<B?>>", f.Interfaces()[0].ToTestDisplayString()); Assert.Equal("I2<C<B>?>", f.Interfaces()[1].ToTestDisplayString()); }); } [Fact] public void NullableAttribute_02() { CSharpCompilation c0 = CreateCompilation(new[] { @" public class CL0 { public object F1; public object? P1 { get; set;} } " }, options: WithNullableEnable(TestOptions.DebugDll)); string source = @" class C { static void Main() { } void Test1(CL0 x1, object? y1) { x1.F1 = y1; } void Test2(CL0 x2, object y2) { y2 = x2.P1; } } "; var expected = new[] { // (10,17): warning CS8601: Possible null reference assignment. // x1.F1 = y1; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y1").WithLocation(10, 17), // (15,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y2 = x2.P1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2.P1").WithLocation(15, 14) }; CSharpCompilation c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics(expected); c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { c0.ToMetadataReference() }); c.VerifyDiagnostics(expected); } [Fact] public void NullableAttribute_03() { CSharpCompilation c0 = CreateCompilation(new[] { @" public class CL0 { public object F1; } " }, options: WithNullableEnable(TestOptions.DebugDll)); string source = @" class C { static void Main() { } void Test1(CL0 x1, object? y1) { x1.F1 = y1; } } "; var expected = new[] { // (10,17): warning CS8601: Possible null reference assignment. // x1.F1 = y1; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y1").WithLocation(10, 17) }; CSharpCompilation c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { c0.EmitToImageReference() }); c.VerifyDiagnostics(expected); c = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { c0.ToMetadataReference() }); c.VerifyDiagnostics(expected); } [Fact] public void NullableAttribute_04() { var source = @"#pragma warning disable 8618 using System.Runtime.CompilerServices; public abstract class B { [Nullable(0)] public string F1; [Nullable(1)] public event System.Action E1; [Nullable(2)] public string[][,] P2 {get; set;} [return:Nullable(0)] public System.Action<string?> M1(string? x) {throw new System.NotImplementedException();} public string[][,] M2([Nullable(new byte[] {0})] string[][,] x) {throw new System.NotImplementedException();} } public class C<T> {} [Nullable(2)] public class F : C<F> {} "; var compilation = CreateCompilation(new[] { source, NullableAttributeDefinition }, options: WithNullableEnable()); compilation.VerifyDiagnostics( // (7,6): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // [Nullable(1)] public event System.Action E1; Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(1)").WithLocation(7, 6), // (8,6): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // [Nullable(2)] public string[][,] P2 {get; set;} Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(2)").WithLocation(8, 6), // (9,13): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // [return:Nullable(0)] public System.Action<string?> M1(string? x) Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(0)").WithLocation(9, 13), // (11,28): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // public string[][,] M2([Nullable(new byte[] {0})] string[][,] x) Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(new byte[] {0})").WithLocation(11, 28), // (6,6): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // [Nullable(0)] public string F1; Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(0)").WithLocation(6, 6), // (17,2): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // [Nullable(2)] public class F : C<F> Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "Nullable(2)").WithLocation(17, 2), // (7,46): warning CS0067: The event 'B.E1' is never used // [Nullable(1)] public event System.Action E1; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "E1").WithArguments("B.E1").WithLocation(7, 46) ); } [Fact] public void NonNullTypes_02() { string lib = @" using System; #nullable disable public class CL0 { #nullable disable public class CL1 { #nullable enable #pragma warning disable 8618 public Action F1; #nullable enable #pragma warning disable 8618 public Action? F2; #nullable enable #pragma warning disable 8618 public Action P1 { get; set; } #nullable enable public Action? P2 { get; set; } #nullable enable public Action M1() { throw new System.NotImplementedException(); } #nullable enable public Action? M2() { return null; } #nullable enable public void M3(Action x3) {} } } "; string source1 = @"#pragma warning disable 8618 using System; partial class C { partial class B { #nullable enable public event Action E1; #nullable enable public event Action? E2; #nullable enable void Test11(Action? x11) { E1 = x11; } #nullable enable void Test12(Action x12) { x12 = E1 ?? x12; } #nullable enable void Test13(Action x13) { x13 = E2; } } } "; string source2 = @"#pragma warning disable 8618 using System; #nullable disable partial class C { #nullable disable partial class B { #nullable enable void Test21(CL0.CL1 c, Action? x21) { c.F1 = x21; c.P1 = x21; c.M3(x21); } #nullable enable void Test22(CL0.CL1 c, Action x22) { x22 = c.F1 ?? x22; x22 = c.P1 ?? x22; x22 = c.M1() ?? x22; } #nullable enable void Test23(CL0.CL1 c, Action x23) { x23 = c.F2; x23 = c.P2; x23 = c.M2(); } } } "; CSharpCompilation c = CreateCompilation(new[] { lib, source1, source2 }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c.VerifyDiagnostics( // (18,18): warning CS8601: Possible null reference assignment. // E1 = x11; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x11").WithLocation(18, 18), // (30,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x13 = E2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(30, 19), // (13,20): warning CS8601: Possible null reference assignment. // c.F1 = x21; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(13, 20), // (14,20): warning CS8601: Possible null reference assignment. // c.P1 = x21; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(14, 20), // (15,18): warning CS8604: Possible null reference argument for parameter 'x3' in 'void CL1.M3(Action x3)'. // c.M3(x21); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x21").WithArguments("x3", "void CL1.M3(Action x3)").WithLocation(15, 18), // (29,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F2").WithLocation(29, 19), // (30,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.P2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P2").WithLocation(30, 19), // (31,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M2()").WithLocation(31, 19) ); CSharpCompilation c1 = CreateCompilation(new[] { lib }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c1.VerifyDiagnostics(); var expected = new[] { // (13,20): warning CS8601: Possible null reference assignment. // c.F1 = x21; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(13, 20), // (14,20): warning CS8601: Possible null reference assignment. // c.P1 = x21; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(14, 20), // (15,18): warning CS8604: Possible null reference argument for parameter 'x3' in 'void CL1.M3(Action x3)'. // c.M3(x21); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x21").WithArguments("x3", "void CL1.M3(Action x3)").WithLocation(15, 18), // (29,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F2").WithLocation(29, 19), // (30,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.P2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P2").WithLocation(30, 19), // (31,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M2()").WithLocation(31, 19) }; c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c.VerifyDiagnostics(expected); c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c.VerifyDiagnostics(expected); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypes_03() { string lib = @" using System; public class CL0 { public class CL1 { #nullable enable public Action F1 = null!; #nullable enable public Action? F2; #nullable enable public Action P1 { get; set; } = null!; #nullable enable public Action? P2 { get; set; } #nullable enable public Action M1() { throw new System.NotImplementedException(); } #nullable enable public Action? M2() { return null; } #nullable enable public void M3(Action x3) {} } } "; string source1 = @" using System; partial class C { partial class B { #nullable enable public event Action E1; #nullable enable public event Action? E2; #nullable disable void Test11(Action? x11) // 1 { E1 = x11; // 2 } void Test12(Action x12) { x12 = E1 ?? x12; // 3 } void Test13(Action x13) { x13 = E2; } } } "; string source2 = @" using System; partial class C { partial class B { void Test21(CL0.CL1 c, Action? x21) // 4 { c.F1 = x21; // 5 c.P1 = x21; // 6 c.M3(x21); // 7 } void Test22(CL0.CL1 c, Action x22) { x22 = c.F1 ?? x22; // 8 x22 = c.P1 ?? x22; // 9 x22 = c.M1() ?? x22; // 10 } void Test23(CL0.CL1 c, Action x23) { x23 = c.F2; x23 = c.P2; x23 = c.M2(); } } } "; CSharpCompilation c = CreateCompilation(new[] { lib, source1, source2 }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c.VerifyDiagnostics( // (15,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void Test11(Action? x11) // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(15, 27), // (8,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void Test21(CL0.CL1 c, Action? x21) // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 38), // (11,29): warning CS8618: Non-nullable event 'E1' is uninitialized. Consider declaring the event as nullable. // public event Action E1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(11, 29) ); CSharpCompilation c1 = CreateCompilation(new[] { lib }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c1.VerifyDiagnostics(); var expectedDiagnostics = new[] { // (8,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Test21(CL0.CL1 c, Action? x21) // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 38) }; c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c.VerifyDiagnostics(expectedDiagnostics); c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, parseOptions: TestOptions.Regular8, options: WithNullableDisable()); c.VerifyDiagnostics(expectedDiagnostics); expectedDiagnostics = new[] { // (10,20): warning CS8601: Possible null reference assignment. // c.F1 = x21; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(10, 20), // (11,20): warning CS8601: Possible null reference assignment. // c.P1 = x21; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x21").WithLocation(11, 20), // (12,18): warning CS8604: Possible null reference argument for parameter 'x3' in 'void CL1.M3(Action x3)'. // c.M3(x21); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x21").WithArguments("x3", "void CL1.M3(Action x3)").WithLocation(12, 18), // (24,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.F2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F2").WithLocation(24, 19), // (25,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.P2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P2").WithLocation(25, 19), // (26,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.M2(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M2()").WithLocation(26, 19) }; c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics(expectedDiagnostics); c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics(expectedDiagnostics); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypes_04() { string lib = @" using System; #nullable disable public class CL0 { public class CL1 { #nullable enable public Action F1 = null!; #nullable enable public Action? F2; #nullable enable public Action P1 { get; set; } = null!; #nullable enable public Action? P2 { get; set; } #nullable enable public Action M1() { throw new System.NotImplementedException(); } #nullable enable public Action? M2() { return null; } #nullable enable public void M3(Action x3) {} } } "; string source1 = @" using System; partial class C { partial class B { #nullable enable public event Action E1; #nullable enable public event Action? E2; void Test11(Action? x11) // 1 { E1 = x11; // 2 } void Test12(Action x12) { x12 = E1 ?? x12; // 3 } void Test13(Action x13) { x13 = E2; } } } "; string source2 = @" using System; #nullable disable partial class C { partial class B { void Test21(CL0.CL1 c, Action? x21) // 4 { c.F1 = x21; // 5 c.P1 = x21; // 6 c.M3(x21); // 7 } void Test22(CL0.CL1 c, Action x22) { x22 = c.F1 ?? x22; // 8 x22 = c.P1 ?? x22; // 9 x22 = c.M1() ?? x22; // 10 } void Test23(CL0.CL1 c, Action x23) { x23 = c.F2; x23 = c.P2; x23 = c.M2(); } } } "; CSharpCompilation c = CreateCompilation(new[] { lib, source1, source2 }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,29): warning CS8618: Non-nullable event 'E1' is uninitialized. Consider declaring the event as nullable. // public event Action E1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(9, 29), // (9,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void Test21(CL0.CL1 c, Action? x21) // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 38), // (15,18): warning CS8601: Possible null reference assignment. // E1 = x11; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x11").WithLocation(15, 18), // (25,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x13 = E2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(25, 19) ); CSharpCompilation c1 = CreateCompilation(new[] { lib }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c1.VerifyDiagnostics(); var expected = new[] { // (9,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Test21(CL0.CL1 c, Action? x21) // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 38) }; c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics(expected); c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics(expected); } [WorkItem(30840, "https://github.com/dotnet/roslyn/issues/30840")] [Fact] public void NonNullTypes_05() { string lib = @" using System; #nullable enable public class CL0 { #nullable disable public class CL1 { #nullable enable public Action F1 = null!; #nullable enable public Action? F2; #nullable enable public Action P1 { get; set; } = null!; #nullable enable public Action? P2 { get; set; } #nullable enable public Action M1() { throw new System.NotImplementedException(); } #nullable enable public Action? M2() { return null; } #nullable enable public void M3(Action x3) {} } } "; string source1 = @" using System; partial class C { partial class B { #nullable enable public event Action E1; #nullable enable public event Action? E2; void Test11(Action? x11) // 1 { E1 = x11; // 2 } void Test12(Action x12) { x12 = E1 ?? x12; // 3 } void Test13(Action x13) { x13 = E2; } } } "; string source2 = @" using System; #nullable enable partial class C { #nullable disable partial class B { void Test21(CL0.CL1 c, Action? x21) // 4 { c.F1 = x21; // 5 c.P1 = x21; // 6 c.M3(x21); // 7 } void Test22(CL0.CL1 c, Action x22) { x22 = c.F1 ?? x22; // 8 x22 = c.P1 ?? x22; // 9 x22 = c.M1() ?? x22; // 10 } void Test23(CL0.CL1 c, Action x23) { x23 = c.F2; x23 = c.P2; x23 = c.M2(); } } } "; CSharpCompilation c = CreateCompilation(new[] { lib, source1, source2 }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (9,29): warning CS8618: Non-nullable event 'E1' is uninitialized. Consider declaring the event as nullable. // public event Action E1; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E1").WithArguments("event", "E1").WithLocation(9, 29), // (10,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void Test21(CL0.CL1 c, Action? x21) // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 38), // (15,18): warning CS8601: Possible null reference assignment. // E1 = x11; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x11").WithLocation(15, 18), // (25,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x13 = E2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(25, 19) ); CSharpCompilation c1 = CreateCompilation(new[] { lib }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c1.VerifyDiagnostics(); var expected = new[] { // (10,38): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void Test21(CL0.CL1 c, Action? x21) // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 38) }; c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics(expected); c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics(expected); } [Fact] public void NonNullTypes_06() { string lib = @" using System; #nullable enable public class CL0 { #nullable enable public class CL1 { #nullable disable public Action F1 = null!; #nullable disable public Action? F2; #nullable disable public Action P1 { get; set; } = null!; #nullable disable public Action? P2 { get; set; } #nullable disable public Action M1() { throw new System.NotImplementedException(); } #nullable disable public Action? M2() { return null; } #nullable disable public void M3(Action x3) {} } } "; string source1 = @" using System; #nullable enable partial class C { #nullable enable partial class B { #nullable disable public event Action E1; #nullable disable public event Action? E2; #nullable enable void Test11(Action? x11) { E1 = x11; } #nullable enable void Test12(Action x12) { x12 = E1 ?? x12; } #nullable enable void Test13(Action x13) { x13 = E2; // warn 1 } } } "; string source2 = @" using System; partial class C { partial class B { #nullable enable void Test21(CL0.CL1 c, Action? x21) { c.F1 = x21; c.P1 = x21; c.M3(x21); } #nullable enable void Test22(CL0.CL1 c, Action x22) { x22 = c.F1 ?? x22; x22 = c.P1 ?? x22; x22 = c.M1() ?? x22; } #nullable enable void Test23(CL0.CL1 c, Action x23) { x23 = c.F2; // warn 2 x23 = c.P2; // warn 3 x23 = c.M2(); // warn 4 } } } "; CSharpCompilation c = CreateCompilation(new[] { lib, source1, source2 }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (13,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public Action? F2; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 22), // (18,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public Action? P2 { get; set; } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 22), // (23,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public Action? M2() { return null; } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(23, 22), // (13,28): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public event Action? E2; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 28), // (30,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x13 = E2; // warn 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "E2").WithLocation(30, 19), // (27,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.F2; // warn 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F2").WithLocation(27, 19), // (28,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.P2; // warn 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P2").WithLocation(28, 19), // (29,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.M2(); // warn 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M2()").WithLocation(29, 19) ); CSharpCompilation c1 = CreateCompilation(new[] { lib }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c1.VerifyDiagnostics( // (13,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public Action? F2; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 22), // (18,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public Action? P2 { get; set; } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 22), // (23,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public Action? M2() { return null; } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(23, 22) ); c = CreateCompilation(new[] { source2 }, new[] { c1.ToMetadataReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (27,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.F2; // warn 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F2").WithLocation(27, 19), // (28,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.P2; // warn 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P2").WithLocation(28, 19), // (29,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.M2(); // warn 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M2()").WithLocation(29, 19) ); c = CreateCompilation(new[] { source2 }, new[] { c1.EmitToImageReference() }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (27,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.F2; // warn 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F2").WithLocation(27, 19), // (28,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.P2; // warn 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.P2").WithLocation(28, 19), // (29,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // x23 = c.M2(); // warn 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.M2()").WithLocation(29, 19) ); } [Fact] public void Covariance_Interface() { var source = @"interface I<out T> { } class C { static I<string?> F1(I<string> i) => i; static I<object?> F2(I<string> i) => i; static I<string> F3(I<string?> i) => i; static I<object> F4(I<string?> i) => i; }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,42): warning CS8619: Nullability of reference types in value of type 'I<string?>' doesn't match target type 'I<string>'. // static I<string> F3(I<string?> i) => i; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i").WithArguments("I<string?>", "I<string>").WithLocation(6, 42), // (7,42): warning CS8619: Nullability of reference types in value of type 'I<string?>' doesn't match target type 'I<object>'. // static I<object> F4(I<string?> i) => i; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i").WithArguments("I<string?>", "I<object>").WithLocation(7, 42)); } [Fact] public void Contravariance_Interface() { var source = @"interface I<in T> { } class C { static I<string?> F1(I<string> i) => i; static I<string?> F2(I<object> i) => i; static I<string> F3(I<string?> i) => i; static I<string> F4(I<object?> i) => i; }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,42): warning CS8619: Nullability of reference types in value of type 'I<string>' doesn't match target type 'I<string?>'. // static I<string?> F1(I<string> i) => i; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i").WithArguments("I<string>", "I<string?>").WithLocation(4, 42), // (5,42): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<string?>'. // static I<string?> F2(I<object> i) => i; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i").WithArguments("I<object>", "I<string?>").WithLocation(5, 42)); } [Fact] public void Covariance_Delegate() { var source = @"delegate void D<in T>(T t); class C { static void F1(string s) { } static void F2(string? s) { } static void F3(object o) { } static void F4(object? o) { } static void F<T>(D<T> d) { } static void Main() { F<string>(F1); F<string>(F2); F<string>(F3); F<string>(F4); F<string?>(F1); // warning F<string?>(F2); F<string?>(F3); // warning F<string?>(F4); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (15,20): warning CS8622: Nullability of reference types in type of parameter 's' of 'void C.F1(string s)' doesn't match the target delegate 'D<string?>'. // F<string?>(F1); // warning Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F1").WithArguments("s", "void C.F1(string s)", "D<string?>").WithLocation(15, 20), // (17,20): warning CS8622: Nullability of reference types in type of parameter 'o' of 'void C.F3(object o)' doesn't match the target delegate 'D<string?>'. // F<string?>(F3); // warning Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "F3").WithArguments("o", "void C.F3(object o)", "D<string?>").WithLocation(17, 20)); } [Fact] public void Contravariance_Delegate() { var source = @"delegate T D<out T>(); class C { static string F1() => string.Empty; static string? F2() => string.Empty; static object F3() => string.Empty; static object? F4() => string.Empty; static T F<T>(D<T> d) => d(); static void Main() { F<object>(F1); F<object>(F2); // warning F<object>(F3); F<object>(F4); // warning F<object?>(F1); F<object?>(F2); F<object?>(F3); F<object?>(F4); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,19): warning CS8621: Nullability of reference types in return type of 'string? C.F2()' doesn't match the target delegate 'D<object>'. // F<object>(F2); // warning Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F2").WithArguments("string? C.F2()", "D<object>").WithLocation(12, 19), // (14,19): warning CS8621: Nullability of reference types in return type of 'object? C.F4()' doesn't match the target delegate 'D<object>'. // F<object>(F4); // warning Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "F4").WithArguments("object? C.F4()", "D<object>").WithLocation(14, 19)); } [Fact] public void TypeArgumentInference_01() { string source = @" class C { void Main() {} T M1<T>(T? x) where T: class {throw new System.NotImplementedException();} void Test1(string? x1) { M1(x1).ToString(); } void Test2(string?[] x2) { M1(x2)[0].ToString(); } void Test3(CL0<string?>? x3) { M1(x3).P1.ToString(); } void Test11(string? x11) { M1<string?>(x11).ToString(); } void Test12(string?[] x12) { M1<string?[]>(x12)[0].ToString(); } void Test13(CL0<string?>? x13) { M1<CL0<string?>?>(x13).P1.ToString(); } } class CL0<T> { public T P1 {get;set;} } "; CSharpCompilation c = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); c.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // M1(x2)[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x2)[0]").WithLocation(15, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // M1(x3).P1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x3).P1").WithLocation(20, 9), // (25,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.M1<T>(T?)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // M1<string?>(x11).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<string?>").WithArguments("C.M1<T>(T?)", "T", "string?").WithLocation(25, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // M1<string?>(x11).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1<string?>(x11)").WithLocation(25, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // M1<string?[]>(x12)[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1<string?[]>(x12)[0]").WithLocation(30, 9), // (35,9): warning CS8634: The type 'CL0<string?>?' cannot be used as type parameter 'T' in the generic type or method 'C.M1<T>(T?)'. Nullability of type argument 'CL0<string?>?' doesn't match 'class' constraint. // M1<CL0<string?>?>(x13).P1.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<CL0<string?>?>").WithArguments("C.M1<T>(T?)", "T", "CL0<string?>?").WithLocation(35, 9), // (35,9): warning CS8602: Dereference of a possibly null reference. // M1<CL0<string?>?>(x13).P1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1<CL0<string?>?>(x13)").WithLocation(35, 9), // (35,9): warning CS8602: Dereference of a possibly null reference. // M1<CL0<string?>?>(x13).P1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1<CL0<string?>?>(x13).P1").WithLocation(35, 9), // (41,14): warning CS8618: Non-nullable property 'P1' is uninitialized. Consider declaring the property as nullable. // public T P1 {get;set;} Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "P1").WithArguments("property", "P1").WithLocation(41, 14) ); } [Fact] public void TypeArgumentInference_02() { var source = @" class C { T M<T>(T t1, T t2) => t1; const string? FIELD_NULL = null; void M1() { const string? LOCAL_NULL = null; var result1 = M(""a"", default); result1.ToString(); // 1 var result2 = M(""a"", null); result2.ToString(); // 2 var result3 = M(""a"", LOCAL_NULL); result3.ToString(); // 3 var result4 = M(""a"", FIELD_NULL); result4.ToString(); // 4 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // result1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result1").WithLocation(13, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // result2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result2").WithLocation(16, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // result3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result3").WithLocation(19, 9), // (22,9): warning CS8602: Dereference of a possibly null reference. // result4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result4").WithLocation(22, 9) ); } [Fact] public void TypeArgumentInference_03() { var source = @" class C { T M<T>(T t1, T t2) => t1; void M1() { var result1 = M((int?)42, default); result1.Value.ToString(); // 1 var result2 = M((int?)42, null); result2.Value.ToString(); // 2 var result3 = M(42, null); // 3 result3.Value.ToString(); // 4 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,9): warning CS8629: Nullable value type may be null. // result1.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "result1").WithLocation(9, 9), // (12,9): warning CS8629: Nullable value type may be null. // result2.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "result2").WithLocation(12, 9), // (14,29): error CS1503: Argument 2: cannot convert from '<null>' to 'int' // var result3 = M(42, null); // 3 Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("2", "<null>", "int").WithLocation(14, 29), // (15,17): error CS1061: 'int' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'int' could be found (are you missing a using directive or an assembly reference?) // result3.Value.ToString(); // 4 Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Value").WithArguments("int", "Value").WithLocation(15, 17) ); } [Fact] public void TypeArgumentInference_04() { var source = @" class C { T M<T>(T t1, in T t2) => t1; void M1() { var result1 = M(""a"", default); result1.ToString(); // 1 var result2 = M(""a"", null); result2.ToString(); // 2 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // result1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result1").WithLocation(9, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // result2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result2").WithLocation(12, 9) ); } [Fact] public void TypeArgumentInference_05() { var source = @" class C { U M<T, U>(T t1, T t2, U u1, U u2) => u1; void M1() { var result1 = M(""a"", default, new object(), null); result1.ToString(); // 1 var result2 = M(null, ""a"", default, new object()); result2.ToString(); // 2 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // result1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result1").WithLocation(9, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // result2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result2").WithLocation(12, 9) ); } [Fact] public void TypeArgumentInference_06() { var source = @" class C { T M<T>(T t1, (T, int) t2) => t1; void M1() { var result1 = M(""a"", (default, 1)); result1.ToString(); // 1 var result2 = M(""a"", (null, 1)); result2.ToString(); // 2 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // result1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result1").WithLocation(9, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // result2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result2").WithLocation(12, 9) ); } [Fact] public void TypeArgumentInference_07() { var source = @" class C { T M<T>(T t1, T t2) => t1; void M1() { var result1 = M(""a"", #nullable disable default #nullable enable ); result1.ToString(); // 1 var result2 = M(""a"", #nullable disable null #nullable enable ); result2.ToString(); // 2 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // result1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result1").WithLocation(13, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // result2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result2").WithLocation(20, 9) ); } [Fact] public void TypeArgumentInference_08() { var source = @" class C { T M<T>(T t1, T t2) => t1; void M1() { var result1 = M(""a"", default!); result1.ToString(); var result2 = M(""a"", null!); result2.ToString(); var result3 = M(""a"", (default)); result3.ToString(); // 1 var result4 = M(""a"", (null)); result4.ToString(); // 2 } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // result3.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result3").WithLocation(15, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // result4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result4").WithLocation(18, 9) ); } [Fact] public void ExplicitImplementations_LazyMethodChecks() { var source = @"interface I { void M<T>(T? x) where T : class; } class C : I { void I.M<T>(T? x) { } }"; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()).VerifyDiagnostics( // (5,11): error CS0535: 'C' does not implement interface member 'I.M<T>(T?)' // class C : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C", "I.M<T>(T?)").WithLocation(5, 11), // (7,12): error CS0539: 'C.M<T>(T?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I.M<T>(T? x) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "M").WithArguments("C.M<T>(T?)").WithLocation(7, 12), // (7,20): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I.M<T>(T? x) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(7, 20)); var method = compilation.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); var implementations = method.ExplicitInterfaceImplementations; Assert.Empty(implementations); } [Fact] public void ExplicitImplementations_LazyMethodChecks_01() { var source = @"interface I { void M<T>(T? x) where T : class; } class C : I { void I.M<T>(T? x) where T : class{ } }"; var compilation = CreateCompilation(new[] { source }, options: WithNullableEnable()); var method = compilation.GetMember<NamedTypeSymbol>("C").GetMethod("I.M"); var implementations = method.ExplicitInterfaceImplementations; Assert.Equal(new[] { "void I.M<T>(T? x)" }, implementations.SelectAsArray(m => m.ToTestDisplayString())); } [Fact] public void EmptyStructDifferentAssembly() { var sourceA = @"using System.Collections; public struct S { public S(string f, IEnumerable g) { F = f; G = g; } private string F { get; } private IEnumerable G { get; } }"; var compA = CreateCompilation(sourceA, parseOptions: TestOptions.Regular7); var sourceB = @"using System.Collections.Generic; class C { static void Main() { var c = new List<object>(); c.Add(new S(string.Empty, new object[0])); } }"; var compB = CreateCompilation( sourceB, options: TestOptions.ReleaseExe, parseOptions: TestOptions.Regular8, references: new[] { compA.EmitToImageReference() }); CompileAndVerify(compB, expectedOutput: ""); } [Fact] public void EmptyStructField() { var source = @"#pragma warning disable 8618 class A { } struct B { } struct S { public readonly A A; public readonly B B; public S(B b) : this(null, b) { } public S(A a, B b) { this.A = a; this.B = b; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,26): warning CS8625: Cannot convert null literal to non-nullable reference type. // public S(B b) : this(null, b) Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 26)); } [Fact] public void WarningOnConversion_Assignment() { var source = @"#pragma warning disable 8618 class Person { internal string FirstName { get; set; } internal string LastName { get; set; } internal string? MiddleName { get; set; } } class Program { static void F(Person p) { p.LastName = null; p.LastName = (string)null; p.LastName = (string?)null; p.LastName = null as string; p.LastName = null as string?; p.LastName = default(string); p.LastName = default; p.FirstName = p.MiddleName; p.LastName = p.MiddleName ?? null; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // p.LastName = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 22), // (13,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // p.LastName = (string)null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(13, 22), // (13,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // p.LastName = (string)null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string)null").WithLocation(13, 22), // (14,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // p.LastName = (string?)null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string?)null").WithLocation(14, 22), // (15,22): warning CS8601: Possible null reference assignment. // p.LastName = null as string; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "null as string").WithLocation(15, 22), // (16,30): error CS8651: It is not legal to use nullable reference type 'string?' in an as expression; use the underlying type 'string' instead. // p.LastName = null as string?; Diagnostic(ErrorCode.ERR_AsNullableType, "string?").WithArguments("string").WithLocation(16, 30), // (17,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // p.LastName = default(string); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default(string)").WithLocation(17, 22), // (18,22): warning CS8625: Cannot convert null literal to non-nullable reference type. // p.LastName = default; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(18, 22), // (19,23): warning CS8601: Possible null reference assignment. // p.FirstName = p.MiddleName; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "p.MiddleName").WithLocation(19, 23), // (20,22): warning CS8601: Possible null reference assignment. // p.LastName = p.MiddleName ?? null; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "p.MiddleName ?? null").WithLocation(20, 22) ); } [Fact] public void WarningOnConversion_Receiver() { var source = @"#pragma warning disable 8618 class Person { internal string FirstName { get; set; } internal string LastName { get; set; } internal string? MiddleName { get; set; } } class Program { static void F(Person p) { ((string)null).F(); ((string?)null).F(); (null as string).F(); (null as string?).F(); default(string).F(); ((p != null) ? p.MiddleName : null).F(); (p.MiddleName ?? null).F(); } } static class Extensions { internal static void F(this string s) { } }"; var comp = CreateCompilationWithMscorlib45(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,18): error CS8651: It is not legal to use nullable reference type 'string?' in an as expression; use the underlying type 'string' instead. // (null as string?).F(); Diagnostic(ErrorCode.ERR_AsNullableType, "string?").WithArguments("string").WithLocation(15, 18), // (12,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((string)null).F(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(12, 10), // (12,10): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((string)null).F(); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string)null").WithLocation(12, 10), // (13,10): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((string?)null).F(); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string?)null").WithLocation(13, 10), // (14,10): warning CS8604: Possible null reference argument for parameter 's' in 'void Extensions.F(string s)'. // (null as string).F(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "null as string").WithArguments("s", "void Extensions.F(string s)").WithLocation(14, 10), // (16,9): warning CS8625: Cannot convert null literal to non-nullable reference type. // default(string).F(); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default(string)").WithLocation(16, 9), // (17,10): warning CS8604: Possible null reference argument for parameter 's' in 'void Extensions.F(string s)'. // ((p != null) ? p.MiddleName : null).F(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(p != null) ? p.MiddleName : null").WithArguments("s", "void Extensions.F(string s)").WithLocation(17, 10), // (18,10): warning CS8602: Dereference of a possibly null reference. // (p.MiddleName ?? null).F(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p").WithLocation(18, 10), // (18,10): warning CS8604: Possible null reference argument for parameter 's' in 'void Extensions.F(string s)'. // (p.MiddleName ?? null).F(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "p.MiddleName ?? null").WithArguments("s", "void Extensions.F(string s)").WithLocation(18, 10) ); } [Fact] public void WarningOnConversion_Argument() { var source = @"#pragma warning disable 8618 class Person { internal string FirstName { get; set; } internal string LastName { get; set; } internal string? MiddleName { get; set; } } class Program { static void F(Person p) { G(null); G((string)null); G((string?)null); G(null as string); G(null as string?); G(default(string)); G(default); G((p != null) ? p.MiddleName : null); G(p.MiddleName ?? null); } static void G(string name) { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (16,19): error CS8651: It is not legal to use nullable reference type 'string?' in an as expression; use the underlying type 'string' instead. // G(null as string?); Diagnostic(ErrorCode.ERR_AsNullableType, "string?").WithArguments("string").WithLocation(16, 19), // (12,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // G(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 11), // (13,11): warning CS8600: Converting null literal or possible null value to non-nullable type. // G((string)null); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(13, 11), // (13,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // G((string)null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string)null").WithLocation(13, 11), // (14,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // G((string?)null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string?)null").WithLocation(14, 11), // (15,11): warning CS8604: Possible null reference argument for parameter 'name' in 'void Program.G(string name)'. // G(null as string); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "null as string").WithArguments("name", "void Program.G(string name)").WithLocation(15, 11), // (17,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // G(default(string)); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default(string)").WithLocation(17, 11), // (18,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // G(default); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(18, 11), // (19,11): warning CS8604: Possible null reference argument for parameter 'name' in 'void Program.G(string name)'. // G((p != null) ? p.MiddleName : null); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(p != null) ? p.MiddleName : null").WithArguments("name", "void Program.G(string name)").WithLocation(19, 11), // (20,11): warning CS8602: Dereference of a possibly null reference. // G(p.MiddleName ?? null); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p").WithLocation(20, 11), // (20,11): warning CS8604: Possible null reference argument for parameter 'name' in 'void Program.G(string name)'. // G(p.MiddleName ?? null); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "p.MiddleName ?? null").WithArguments("name", "void Program.G(string name)").WithLocation(20, 11) ); } [Fact] public void WarningOnConversion_Return() { var source = @"#pragma warning disable 8618 class Person { internal string FirstName { get; set; } internal string LastName { get; set; } internal string? MiddleName { get; set; } } class Program { static string F1() => null; static string F2() => (string)null; static string F3() => (string?)null; static string F4() => null as string; static string F5() => null as string?; static string F6() => default(string); static string F7() => default; static string F8(Person p) => (p != null) ? p.MiddleName : null; static string F9(Person p) => p.MiddleName ?? null; }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,27): warning CS8603: Possible null reference return. // static string F1() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(10, 27), // (11,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // static string F2() => (string)null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(11, 27), // (11,27): warning CS8603: Possible null reference return. // static string F2() => (string)null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(string)null").WithLocation(11, 27), // (12,27): warning CS8603: Possible null reference return. // static string F3() => (string?)null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(string?)null").WithLocation(12, 27), // (13,27): warning CS8603: Possible null reference return. // static string F4() => null as string; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null as string").WithLocation(13, 27), // (14,35): error CS8651: It is not legal to use nullable reference type 'string?' in an as expression; use the underlying type 'string' instead. // static string F5() => null as string?; Diagnostic(ErrorCode.ERR_AsNullableType, "string?").WithArguments("string").WithLocation(14, 35), // (15,27): warning CS8603: Possible null reference return. // static string F6() => default(string); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(string)").WithLocation(15, 27), // (16,27): warning CS8603: Possible null reference return. // static string F7() => default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(16, 27), // (17,35): warning CS8603: Possible null reference return. // static string F8(Person p) => (p != null) ? p.MiddleName : null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(p != null) ? p.MiddleName : null").WithLocation(17, 35), // (18,35): warning CS8603: Possible null reference return. // static string F9(Person p) => p.MiddleName ?? null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "p.MiddleName ?? null").WithLocation(18, 35) ); } [Fact] public void SuppressNullableWarning() { var source = @"class C { static void F(string? s) // 1 { G(null!); // 2, 3 G((null as string)!); // 4, 5 G(default(string)!); // 6, 7 G(default!); // 8, 9, 10 G(s!); // 11, 12 } static void G(string s) { } }"; var comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular7, skipUsesIsNullable: true); comp.VerifyDiagnostics( // (5,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(null!); // 2, 3 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "null!").WithArguments("nullable reference types", "8.0").WithLocation(5, 11), // (6,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G((null as string)!); // 4, 5 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "(null as string)!").WithArguments("nullable reference types", "8.0").WithLocation(6, 11), // (7,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(default(string)!); // 6, 7 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "default(string)!").WithArguments("nullable reference types", "8.0").WithLocation(7, 11), // (8,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(default!); // 8, 9, 10 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "default!").WithArguments("nullable reference types", "8.0").WithLocation(8, 11), // (8,11): error CS8107: Feature 'default literal' is not available in C# 7.0. Please use language version 7.1 or greater. // G(default!); // 8, 9, 10 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "default").WithArguments("default literal", "7.1").WithLocation(8, 11), // (9,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(s!); // 11, 12 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "s!").WithArguments("nullable reference types", "8.0").WithLocation(9, 11), // (3,25): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // static void F(string? s) // 1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "?").WithArguments("nullable reference types", "8.0").WithLocation(3, 25) ); comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void SuppressNullableWarning_ReferenceType() { var source = @"class C { static C F(C? o) { C other; other = o!; o = other; o!.F(); G(o!); return o!; } void F() { } static void G(C o) { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_Array() { var source = @"class C { static object[] F(object?[] o) { object[] other; other = o!; o = other!; o!.F(); G(o!); return o!; } static void G(object[] o) { } } static class E { internal static void F(this object[] o) { } }"; var comp = CreateCompilationWithMscorlib45( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_ConstructedType() { var source = @"class C { static C<object> F(C<object?> o) { C<object> other; other = o!; // 1 o = other!; // 2 o!.F(); G(o!); // 3 return o!; // 4 } static void G(C<object> o) { } } class C<T> { internal void F() { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29902, "https://github.com/dotnet/roslyn/issues/29902")] public void SuppressNullableWarning_Multiple() { var source = @"class C { static void F(string? s) { G(default!!); G(s!!); G((s!)!); G(((s!)!)!); G(s!!!!!!!); G(s! ! ! ! ! ! !); } static void G(string s) { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,11): error CS8715: Duplicate null suppression operator ('!') // G(default!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "default").WithLocation(5, 11), // (6,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(6, 11), // (7,12): error CS8715: Duplicate null suppression operator ('!') // G((s!)!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(7, 12), // (8,13): error CS8715: Duplicate null suppression operator ('!') // G(((s!)!)!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(8, 13), // (8,13): error CS8715: Duplicate null suppression operator ('!') // G(((s!)!)!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(8, 13), // (9,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!!!!!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(9, 11), // (9,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!!!!!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(9, 11), // (9,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!!!!!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(9, 11), // (9,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!!!!!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(9, 11), // (9,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!!!!!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(9, 11), // (9,11): error CS8715: Duplicate null suppression operator ('!') // G(s!!!!!!!); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(9, 11), // (10,11): error CS8715: Duplicate null suppression operator ('!') // G(s! ! ! ! ! ! !); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(10, 11), // (10,11): error CS8715: Duplicate null suppression operator ('!') // G(s! ! ! ! ! ! !); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(10, 11), // (10,11): error CS8715: Duplicate null suppression operator ('!') // G(s! ! ! ! ! ! !); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(10, 11), // (10,11): error CS8715: Duplicate null suppression operator ('!') // G(s! ! ! ! ! ! !); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(10, 11), // (10,11): error CS8715: Duplicate null suppression operator ('!') // G(s! ! ! ! ! ! !); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(10, 11), // (10,11): error CS8715: Duplicate null suppression operator ('!') // G(s! ! ! ! ! ! !); Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, "s").WithLocation(10, 11) ); } [Fact] [WorkItem(43659, "https://github.com/dotnet/roslyn/issues/43659")] public void SuppressNullableWarning_ConditionalAccess_01() { var source = @" #nullable enable using System; using System.Linq; class Program { static void Main() { int[]? a = null; string? s1 = a?.First().ToString(); Console.Write(s1 == null); string? s2 = a?.First()!.ToString(); Console.Write(s2 == null); string s3 = a?.First().ToString()!; Console.Write(s3 == null); string? s4 = (a?.First()).ToString(); Console.Write(s4 == null); string? s5 = (a?.First())!.ToString(); Console.Write(s5 == null); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "TrueTrueTrueFalseFalse"); } [Fact] [WorkItem(43659, "https://github.com/dotnet/roslyn/issues/43659")] public void SuppressNullableWarning_ConditionalAccess_02() { var source = @" #nullable enable using System.Linq; class Program { static void Main() { int[]? a = null; string? s1 = a?.First()!!.ToString(); // 1 string? s2 = a?.First()!!!!.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (12,24): error CS8715: Duplicate null suppression operator ('!') // string? s1 = a?.First()!!.ToString(); // 1 Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, ".First()", isSuppressed: false).WithLocation(12, 24), // (13,24): error CS8715: Duplicate null suppression operator ('!') // string? s2 = a?.First()!!!!.ToString(); // 2 Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, ".First()", isSuppressed: false).WithLocation(13, 24), // (13,24): error CS8715: Duplicate null suppression operator ('!') // string? s2 = a?.First()!!!!.ToString(); // 2 Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, ".First()", isSuppressed: false).WithLocation(13, 24), // (13,24): error CS8715: Duplicate null suppression operator ('!') // string? s2 = a?.First()!!!!.ToString(); // 2 Diagnostic(ErrorCode.ERR_DuplicateNullSuppression, ".First()", isSuppressed: false).WithLocation(13, 24)); } [Fact] [WorkItem(43659, "https://github.com/dotnet/roslyn/issues/43659")] public void SuppressNullableWarning_ConditionalAccess_03() { var source = @" #nullable enable using System; public class D { } public class C { public D d = null!; } public class B { public C? c; } public class A { public B? b; } class Program { static void Main() { M(new A()); } static void M(A a) { var str = a.b?.c!.d.ToString(); Console.Write(str == null); } }"; var comp = CreateCompilation(source, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "True"); } [Fact] [WorkItem(43659, "https://github.com/dotnet/roslyn/issues/43659")] public void SuppressNullableWarning_ConditionalAccess_04() { var source = @" #nullable enable public class D { } public class C { public D? d; } public class B { public C? c; } public class A { public B? b; } class Program { static void M(A a) { string str1 = a.b?.c!.d.ToString(); // 1, 2 string str2 = a.b?.c!.d!.ToString(); // 3 string str3 = a.b?.c!.d!.ToString()!; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // string str1 = a.b?.c!.d.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "a.b?.c!.d.ToString()", isSuppressed: false).WithLocation(13, 23), // (13,27): warning CS8602: Dereference of a possibly null reference. // string str1 = a.b?.c!.d.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, ".c!.d", isSuppressed: false).WithLocation(13, 27), // (14,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // string str2 = a.b?.c!.d!.ToString(); // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "a.b?.c!.d!.ToString()", isSuppressed: false).WithLocation(14, 23)); } [Fact] public void SuppressNullableWarning_Nested() { var source = @"class C<T> where T : class { static T? F(T t) => t; static T? G(T t) => t; static void M(T? t) { F(G(t!)); F(G(t)!); F(G(t!)!); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,11): warning CS8604: Possible null reference argument for parameter 't' in 'T? C<T>.F(T t)'. // F(G(t!)); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "G(t!)").WithArguments("t", "T? C<T>.F(T t)").WithLocation(7, 11), // (8,13): warning CS8604: Possible null reference argument for parameter 't' in 'T? C<T>.G(T t)'. // F(G(t)!); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("t", "T? C<T>.G(T t)").WithLocation(8, 13)); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_Conditional() { var source = @"class C<T> { } class C { static void F(C<object>? x, C<object?> y, bool c) { C<object> a; a = c ? x : y; // 1 a = c ? y : x; // 2 a = c ? x : y!; // 3 a = c ? x! : y; // 4 a = c ? x! : y!; C<object?> b; b = c ? x : y; // 5 b = c ? x : y!; // 6 b = c ? x! : y; // 7 b = c ? x! : y!; // 8 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // a = c ? x : y; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ? x : y").WithLocation(7, 13), // (7,21): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // a = c ? x : y; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(7, 21), // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // a = c ? y : x; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ? y : x").WithLocation(8, 13), // (8,17): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // a = c ? y : x; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(8, 17), // (9,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // a = c ? x : y!; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ? x : y!").WithLocation(9, 13), // (10,22): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // a = c ? x! : y; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(10, 22), // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // b = c ? x : y; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ? x : y").WithLocation(13, 13), // (13,13): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // b = c ? x : y; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x : y").WithArguments("C<object>", "C<object?>").WithLocation(13, 13), // (13,21): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // b = c ? x : y; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(13, 21), // (14,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // b = c ? x : y!; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c ? x : y!").WithLocation(14, 13), // (14,13): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // b = c ? x : y!; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x : y!").WithArguments("C<object>", "C<object?>").WithLocation(14, 13), // (15,13): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // b = c ? x! : y; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x! : y").WithArguments("C<object>", "C<object?>").WithLocation(15, 13), // (15,22): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // b = c ? x! : y; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(15, 22), // (16,13): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // b = c ? x! : y!; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c ? x! : y!").WithArguments("C<object>", "C<object?>").WithLocation(16, 13) ); } [Fact] public void SuppressNullableWarning_NullCoalescing() { var source = @" class C<T> { static void F(C<object>? x, C<object?> y) { var t1 = x ?? y; // 1 var t2 = y ?? x; // 2 var t3 = x! ?? y; // 3 var t4 = y! ?? x; // 4 var t5 = x ?? y!; var t6 = y ?? x!; var t7 = x! ?? y!; var t8 = y! ?? x!; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,23): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var t1 = x ?? y; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(6, 23), // (7,23): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // var t2 = y ?? x; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<object>", "C<object?>").WithLocation(7, 23), // (8,24): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var t3 = x! ?? y; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(8, 24), // (9,24): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // var t4 = y! ?? x; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<object>", "C<object?>").WithLocation(9, 24)); } [Fact] [WorkItem(30151, "https://github.com/dotnet/roslyn/issues/30151")] [WorkItem(33346, "https://github.com/dotnet/roslyn/issues/33346")] public void SuppressNullableWarning_ArrayInitializer() { var source = @" class C<T> { static void F(C<object>? x, C<object?> y) { var a1 = new[] { x, y }; // 1 _ = a1 /*T:C<object!>?[]!*/; var a2 = new[] { x!, y }; // 2 _ = a2 /*T:C<object!>![]!*/; var a3 = new[] { x, y! }; _ = a3 /*T:C<object!>?[]!*/; var a4 = new[] { x!, y! }; _ = a4 /*T:C<object!>![]!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (6,29): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var a1 = new[] { x, y }; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(6, 29), // (8,30): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var a2 = new[] { x!, y }; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(8, 30)); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_LocalDeclaration() { var source = @" class C<T> { static void F(C<object>? x, C<object?> y) { C<object>? c1 = y; // 1 C<object?> c2 = x; // 2 and 3 C<object>? c3 = y!; // 4 C<object?> c4 = x!; // 5 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,25): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // C<object>? c1 = y; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(6, 25), // (7,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // C<object?> c2 = x; // 2 and 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(7, 25), // (7,25): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // C<object?> c2 = x; // 2 and 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<object>", "C<object?>").WithLocation(7, 25) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_Cast() { var source = @" class C<T> { static void F(C<object>? x, C<object?> y) { var c1 = (C<object>?)y; var c2 = (C<object?>)x; // warn var c3 = (C<object>?)y!; var c4 = (C<object?>)x!; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // var c1 = (C<object>?)y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(C<object>?)y").WithArguments("C<object?>", "C<object>").WithLocation(6, 18), // (7,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // var c2 = (C<object?>)x; // warn Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C<object?>)x").WithLocation(7, 18), // (7,18): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // var c2 = (C<object?>)x; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(C<object?>)x").WithArguments("C<object>", "C<object?>").WithLocation(7, 18) ); } [Fact] public void SuppressNullableWarning_ObjectInitializer() { var source = @" class C<T> { public C<object>? X = null!; public C<object?> Y = null!; static void F(C<object>? x, C<object?> y) { _ = new C<int>() { X = y, Y = x }; _ = new C<int>() { X = y!, Y = x! }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,32): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // _ = new C<int>() { X = y, Y = x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "C<object>").WithLocation(8, 32), // (8,39): warning CS8601: Possible null reference assignment. // _ = new C<int>() { X = y, Y = x }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(8, 39), // (8,39): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // _ = new C<int>() { X = y, Y = x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<object>", "C<object?>").WithLocation(8, 39) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_CollectionInitializer() { var source = @" using System.Collections; class C<T> : IEnumerable { IEnumerator IEnumerable.GetEnumerator() => throw null!; void Add(C<object?> key, params C<object?>[] value) => throw null!; static void F(C<object>? x) { _ = new C<int>() { x, x }; // warn 1 and 2 _ = new C<int>() { x!, x! }; // warn 3 and 4 } } class D<T> : IEnumerable { IEnumerator IEnumerable.GetEnumerator() => throw null!; void Add(D<object>? key, params D<object>?[] value) => throw null!; static void F(D<object?> y) { _ = new D<int>() { y, y }; // warn 5 and 6 _ = new D<int>() { y!, y! }; // warn 7 and 8 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,28): warning CS8620: Argument of type 'D<object?>' cannot be used for parameter 'key' of type 'D<object>' in 'void D<int>.Add(D<object>? key, params D<object>?[] value)' due to differences in the nullability of reference types. // _ = new D<int>() { y, y }; // warn 5 and 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("D<object?>", "D<object>", "key", "void D<int>.Add(D<object>? key, params D<object>?[] value)").WithLocation(19, 28), // (19,32): warning CS8620: Argument of type 'D<object?>' cannot be used for parameter 'key' of type 'D<object>' in 'void D<int>.Add(D<object>? key, params D<object>?[] value)' due to differences in the nullability of reference types. // _ = new D<int>() { y, y }; // warn 5 and 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("D<object?>", "D<object>", "key", "void D<int>.Add(D<object>? key, params D<object>?[] value)").WithLocation(19, 32), // (9,28): warning CS8604: Possible null reference argument for parameter 'key' in 'void C<int>.Add(C<object?> key, params C<object?>[] value)'. // _ = new C<int>() { x, x }; // warn 1 and 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("key", "void C<int>.Add(C<object?> key, params C<object?>[] value)").WithLocation(9, 28), // (9,28): warning CS8620: Argument of type 'C<object>' cannot be used for parameter 'key' of type 'C<object?>' in 'void C<int>.Add(C<object?> key, params C<object?>[] value)' due to differences in the nullability of reference types. // _ = new C<int>() { x, x }; // warn 1 and 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("C<object>", "C<object?>", "key", "void C<int>.Add(C<object?> key, params C<object?>[] value)").WithLocation(9, 28), // (9,31): warning CS8620: Argument of type 'C<object>' cannot be used for parameter 'key' of type 'C<object?>' in 'void C<int>.Add(C<object?> key, params C<object?>[] value)' due to differences in the nullability of reference types. // _ = new C<int>() { x, x }; // warn 1 and 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("C<object>", "C<object?>", "key", "void C<int>.Add(C<object?> key, params C<object?>[] value)").WithLocation(9, 31) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_IdentityConversion() { var source = @"class C<T> { } class C { static void F(C<object?> x, C<object> y) { C<object> a; a = x; // 1 a = x!; // 2 C<object?> b; b = y; // 3 b = y!; // 4 } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,13): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // a = x; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<object?>", "C<object>").WithLocation(7, 13), // (10,13): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // b = y; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object>", "C<object?>").WithLocation(10, 13) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_ImplicitConversion() { var source = @"interface I<T> { } class C<T> : I<T> { } class C { static void F(C<object?> x, C<object> y) { I<object> a; a = x; a = x!; I<object?> b; b = y; b = y!; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,13): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'I<object>'. // a = x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("C<object?>", "I<object>").WithLocation(8, 13), // (11,13): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'I<object?>'. // b = y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object>", "I<object?>").WithLocation(11, 13) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_ImplicitExtensionMethodThisConversion() { var source = @"interface I<T> { } class C<T> : I<T> { } class C { static void F(C<object?> x, C<object> y) { x.F1(); x!.F1(); y.F2(); y!.F2(); } } static class E { internal static void F1(this I<object> o) { } internal static void F2(this I<object?> o) { } }"; var comp = CreateCompilationWithMscorlib45( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,9): warning CS8620: Nullability of reference types in argument of type 'C<object?>' doesn't match target type 'I<object>' for parameter 'o' in 'void E.F1(I<object> o)'. // x.F1(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("C<object?>", "I<object>", "o", "void E.F1(I<object> o)").WithLocation(7, 9), // (9,9): warning CS8620: Nullability of reference types in argument of type 'C<object>' doesn't match target type 'I<object?>' for parameter 'o' in 'void E.F2(I<object?> o)'. // y.F2(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<object>", "I<object?>", "o", "void E.F2(I<object?> o)").WithLocation(9, 9) ); } [Fact] public void SuppressNullableWarning_ImplicitUserDefinedConversion() { var source = @"class A<T> { } class B<T> { public static implicit operator A<T>(B<T> b) => new A<T>(); } class C { static void F(B<object?> b1, B<object> b2) { A<object> a1; a1 = b1; // 1 a1 = b1!; // 2 A<object?> a2; a2 = b2; // 3 a2 = b2!; // 4 } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,14): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'A<object>'. // a1 = b1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b1").WithArguments("A<object?>", "A<object>").WithLocation(11, 14), // (14,14): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'A<object?>'. // a2 = b2; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b2").WithArguments("A<object>", "A<object?>").WithLocation(14, 14) ); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_ExplicitConversion() { var source = @"interface I<T> { } class C<T> { } class C { static void F(C<object?> x, C<object> y) { I<object> a; a = (I<object?>)x; // 1 a = ((I<object?>)x)!; // 2 I<object?> b; b = (I<object>)y; // 3 b = ((I<object>)y)!; // 4 } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,13): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // a = (I<object?>)x; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(I<object?>)x").WithArguments("I<object?>", "I<object>").WithLocation(8, 13), // (11,13): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // b = (I<object>)y; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(I<object>)y").WithArguments("I<object>", "I<object?>").WithLocation(11, 13) ); } [Fact] public void SuppressNullableWarning_Ref() { var source = @"class C { static void F(ref string s, ref string? t) { } static void Main() { string? s = null; string t = """"; F(ref s, ref t); F(ref s!, ref t!); } }"; var comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (10,15): warning CS8601: Possible null reference assignment. // F(ref s, ref t); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(10, 15), // (10,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(ref s, ref t); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(10, 22)); } [Fact] public void SuppressNullableWarning_Ref_WithNestedDifferences() { var source = @" class List<T> { } class C { static void F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d) { } static void F1(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d) { F(ref b, ref c, ref d, ref a); // warnings } static void F2(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d) { F(ref b!, ref c!, ref d!, ref a!); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,15): warning CS8601: Possible null reference assignment. // F(ref b, ref c, ref d, ref a); // warnings Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "b").WithLocation(10, 15), // (10,22): warning CS8620: Argument of type 'List<string?>' cannot be used for parameter 'b' of type 'List<string>' in 'void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)' due to differences in the nullability of reference types. // F(ref b, ref c, ref d, ref a); // warnings Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "c").WithArguments("List<string?>", "List<string>", "b", "void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)").WithLocation(10, 22), // (10,22): warning CS8601: Possible null reference assignment. // F(ref b, ref c, ref d, ref a); // warnings Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c").WithLocation(10, 22), // (10,29): warning CS8601: Possible null reference assignment. // F(ref b, ref c, ref d, ref a); // warnings Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "d").WithLocation(10, 29), // (10,36): warning CS8620: Argument of type 'List<string>' cannot be used for parameter 'd' of type 'List<string?>' in 'void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)' due to differences in the nullability of reference types. // F(ref b, ref c, ref d, ref a); // warnings Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "a").WithArguments("List<string>", "List<string?>", "d", "void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)").WithLocation(10, 36), // (10,36): warning CS8601: Possible null reference assignment. // F(ref b, ref c, ref d, ref a); // warnings Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "a").WithLocation(10, 36)); } [Fact] public void SuppressNullableWarning_Ref_WithUnassignedLocals() { var source = @" class List<T> { } class C { static void F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d) { throw null!; } static void F1() { List<string> a; List<string>? b; List<string?> c; List<string?>? d; F(ref b, ref c, ref d, ref a); } static void F2() { List<string> a; List<string>? b; List<string?> c; List<string?>? d; F(ref b!, ref c!, ref d!, ref a!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,15): error CS0165: Use of unassigned local variable 'b' // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(15, 15), // (15,15): warning CS8601: Possible null reference assignment. // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "b").WithLocation(15, 15), // (15,22): error CS0165: Use of unassigned local variable 'c' // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c").WithLocation(15, 22), // (15,22): warning CS8620: Argument of type 'List<string?>' cannot be used for parameter 'b' of type 'List<string>' in 'void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)' due to differences in the nullability of reference types. // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "c").WithArguments("List<string?>", "List<string>", "b", "void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)").WithLocation(15, 22), // (15,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c").WithLocation(15, 22), // (15,29): error CS0165: Use of unassigned local variable 'd' // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.ERR_UseDefViolation, "d").WithArguments("d").WithLocation(15, 29), // (15,29): warning CS8601: Possible null reference assignment. // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "d").WithLocation(15, 29), // (15,36): error CS0165: Use of unassigned local variable 'a' // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.ERR_UseDefViolation, "a").WithArguments("a").WithLocation(15, 36), // (15,36): warning CS8620: Argument of type 'List<string>' cannot be used for parameter 'd' of type 'List<string?>' in 'void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)' due to differences in the nullability of reference types. // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "a").WithArguments("List<string>", "List<string?>", "d", "void C.F(ref List<string> a, ref List<string>? b, ref List<string?> c, ref List<string?>? d)").WithLocation(15, 36), // (15,36): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(ref b, ref c, ref d, ref a); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "a").WithLocation(15, 36), // (23,15): error CS0165: Use of unassigned local variable 'b' // F(ref b!, ref c!, ref d!, ref a!); Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(23, 15), // (23,23): error CS0165: Use of unassigned local variable 'c' // F(ref b!, ref c!, ref d!, ref a!); Diagnostic(ErrorCode.ERR_UseDefViolation, "c").WithArguments("c").WithLocation(23, 23), // (23,31): error CS0165: Use of unassigned local variable 'd' // F(ref b!, ref c!, ref d!, ref a!); Diagnostic(ErrorCode.ERR_UseDefViolation, "d").WithArguments("d").WithLocation(23, 31), // (23,39): error CS0165: Use of unassigned local variable 'a' // F(ref b!, ref c!, ref d!, ref a!); Diagnostic(ErrorCode.ERR_UseDefViolation, "a").WithArguments("a").WithLocation(23, 39)); } [Fact] public void SuppressNullableWarning_Out_WithNestedDifferences() { var source = @" class List<T> { } class C { static void F(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d) { throw null!; } static void F1(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d) { F(out b, out c, out d, out a); // warn on `c` and `a` } static void F2(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d) { F(out b!, out c!, out d!, out a!); // warn on `c!` and `a!` } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,22): warning CS8601: Possible null reference assignment. // F(out b, out c, out d, out a); // warn on `c` and `a` Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c").WithLocation(11, 22), // (11,22): warning CS8624: Argument of type 'List<string?>' cannot be used as an output of type 'List<string>' for parameter 'b' in 'void C.F(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d)' due to differences in the nullability of reference types. // F(out b, out c, out d, out a); // warn on `c` and `a` Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "c").WithArguments("List<string?>", "List<string>", "b", "void C.F(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d)").WithLocation(11, 22), // (11,36): warning CS8601: Possible null reference assignment. // F(out b, out c, out d, out a); // warn on `c` and `a` Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "a").WithLocation(11, 36), // (11,36): warning CS8624: Argument of type 'List<string>' cannot be used as an output of type 'List<string?>' for parameter 'd' in 'void C.F(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d)' due to differences in the nullability of reference types. // F(out b, out c, out d, out a); // warn on `c` and `a` Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "a").WithArguments("List<string>", "List<string?>", "d", "void C.F(out List<string> a, out List<string>? b, out List<string?> c, out List<string?>? d)").WithLocation(11, 36) ); } [Fact] [WorkItem(27522, "https://github.com/dotnet/roslyn/issues/27522")] public void SuppressNullableWarning_Out() { var source = @"class C { static void F(out string s, out string? t) { s = string.Empty; t = string.Empty; } static ref string RefReturn() => ref (new string[1])[0]; static void Main() { string? s; string t; F(out s, out t); // warn F(out s!, out t!); // ok F(out RefReturn(), out RefReturn()); // warn F(out RefReturn()!, out RefReturn()!); // ok F(out (s!), out (t!)); // errors F(out (s)!, out (t)!); // errors } }"; var comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (18,19): error CS1525: Invalid expression term ',' // F(out (s)!, out (t)!); // errors Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(18, 19), // (18,29): error CS1525: Invalid expression term ')' // F(out (s)!, out (t)!); // errors Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(18, 29), // (18,16): error CS0118: 's' is a variable but is used like a type // F(out (s)!, out (t)!); // errors Diagnostic(ErrorCode.ERR_BadSKknown, "s").WithArguments("s", "variable", "type").WithLocation(18, 16), // (18,26): error CS0118: 't' is a variable but is used like a type // F(out (s)!, out (t)!); // errors Diagnostic(ErrorCode.ERR_BadSKknown, "t").WithArguments("t", "variable", "type").WithLocation(18, 26), // (13,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(out s, out t); // warn Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(13, 22), // (15,32): warning CS8601: Possible null reference assignment. // F(out RefReturn(), out RefReturn()); // warn Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "RefReturn()").WithLocation(15, 32)); } [Fact] [WorkItem(27317, "https://github.com/dotnet/roslyn/pull/27317")] public void RefOutSuppressionInference() { var src = @" class C { void M<T>(ref T t) { } void M2<T>(out T t) => throw null!; void M3<T>(in T t) { } T M4<T>(in T t) => t; void M3() { string? s1 = null; M(ref s1!); s1.ToString(); string? s2 = null; M2(out s2!); s2.ToString(); string? s3 = null; M3(s3!); s3.ToString(); // warn string? s4 = null; M3(in s4!); s4.ToString(); // warn string? s5 = null; s5 = M4(s5!); s5.ToString(); string? s6 = null; s6 = M4(in s6!); s6.ToString(); } }"; var comp = CreateCompilation(src, options: WithNullableEnable(TestOptions.DebugDll)); comp.VerifyDiagnostics( // (21,9): warning CS8602: Dereference of a possibly null reference. // s3.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(21, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(25, 9)); } [Fact] [WorkItem(27522, "https://github.com/dotnet/roslyn/issues/27522")] [WorkItem(29903, "https://github.com/dotnet/roslyn/issues/29903")] public void SuppressNullableWarning_Assignment() { var source = @"class C { static void Main() { string? s = null; string t = string.Empty; t! = s; t! += s; (t!) = s; } }"; var comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular8, options: WithNullableEnable(TestOptions.ReleaseExe)); comp.VerifyDiagnostics( // (7,9): error CS8598: The suppression operator is not allowed in this context // t! = s; Diagnostic(ErrorCode.ERR_IllegalSuppression, "t").WithLocation(7, 9), // (7,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t! = s; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(7, 14), // (8,9): error CS8598: The suppression operator is not allowed in this context // t! += s; Diagnostic(ErrorCode.ERR_IllegalSuppression, "t").WithLocation(8, 9), // (9,10): error CS8598: The suppression operator is not allowed in this context // (t!) = s; Diagnostic(ErrorCode.ERR_IllegalSuppression, "t").WithLocation(9, 10), // (9,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // (t!) = s; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s").WithLocation(9, 16) ); } [Fact] public void SuppressNullableWarning_Conversion() { var source = @"class A { public static implicit operator B(A a) => new B(); } class B { } class C { static void F(A? a) { G((B)a); G((B)a!); } static void G(B b) { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,14): warning CS8604: Possible null reference argument for parameter 'a' in 'A.implicit operator B(A a)'. // G((B)a); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("a", "A.implicit operator B(A a)").WithLocation(12, 14)); } [Fact] [WorkItem(29906, "https://github.com/dotnet/roslyn/issues/29906")] public void SuppressNullableWarning_Condition() { var source = @"class C { static object? F(bool b) { return (b && G(out var o))! ? o : null; } static bool G(out object o) { o = new object(); return true; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Deconstruction() { var source = @" class C<T> { } class C2 { void M(C<string?> c) { // line 1 (string d1, (C<string> d2, string d3)) = (null, (c, null)); // line 2 (string e1, (C<string> e2, string e3)) = (null, (c, null))!; // line 3 (string f1, (C<string> f2, string f3)) = (null, (c, null)!); // line 4 (string g1, (C<string> g2, string g3)) = (null!, (c, null)!); // line 5 (string h1, (C<string> h2, string h3)) = (null!, (c!, null!)); // no warnings // line 6 (string i1, (C<string> i2, string i3)) = default((string, (C<string>, string)))!; // line 7 (string j1, (C<string> j2, string j3)) = (null, default((C<string>, string))!); // line 8 (string k1, (C<string> k2, string k3)) = (null!, default((C<string>, string))!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // line 1 // (10,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string d1, (C<string> d2, string d3)) = (null, (c, null)); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(10, 51), // (10,58): warning CS8619: Nullability of reference types in value of type 'C<string?>' doesn't match target type 'C<string>'. // (string d1, (C<string> d2, string d3)) = (null, (c, null)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c").WithArguments("C<string?>", "C<string>").WithLocation(10, 58), // (10,61): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string d1, (C<string> d2, string d3)) = (null, (c, null)); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(10, 61), // line 2 // (13,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string e1, (C<string> e2, string e3)) = (null, (c, null))!; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 51), // (13,58): warning CS8619: Nullability of reference types in value of type 'C<string?>' doesn't match target type 'C<string>'. // (string e1, (C<string> e2, string e3)) = (null, (c, null))!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c").WithArguments("C<string?>", "C<string>").WithLocation(13, 58), // (13,61): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string e1, (C<string> e2, string e3)) = (null, (c, null))!; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 61), // line 3 // (16,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string f1, (C<string> f2, string f3)) = (null, (c, null)!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 51), // (16,58): warning CS8619: Nullability of reference types in value of type 'C<string?>' doesn't match target type 'C<string>'. // (string f1, (C<string> f2, string f3)) = (null, (c, null)!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c").WithArguments("C<string?>", "C<string>").WithLocation(16, 58), // (16,61): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string f1, (C<string> f2, string f3)) = (null, (c, null)!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 61), // line 4 // (19,59): warning CS8619: Nullability of reference types in value of type 'C<string?>' doesn't match target type 'C<string>'. // (string g1, (C<string> g2, string g3)) = (null!, (c, null)!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c").WithArguments("C<string?>", "C<string>").WithLocation(19, 59), // (19,62): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string g1, (C<string> g2, string g3)) = (null!, (c, null)!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 62), // line 6 // (25,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string i1, (C<string> i2, string i3)) = default((string, (C<string>, string)))!; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((string, (C<string>, string)))").WithLocation(25, 50), // (25,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string i1, (C<string> i2, string i3)) = default((string, (C<string>, string)))!; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((string, (C<string>, string)))").WithLocation(25, 50), // (25,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string i1, (C<string> i2, string i3)) = default((string, (C<string>, string)))!; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((string, (C<string>, string)))").WithLocation(25, 50), // line 7 // (28,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string j1, (C<string> j2, string j3)) = (null, default((C<string>, string))!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(28, 51), // (28,57): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string j1, (C<string> j2, string j3)) = (null, default((C<string>, string))!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((C<string>, string))").WithLocation(28, 57), // (28,57): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string j1, (C<string> j2, string j3)) = (null, default((C<string>, string))!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((C<string>, string))").WithLocation(28, 57), // line 8 // (31,58): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string k1, (C<string> k2, string k3)) = (null!, default((C<string>, string))!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((C<string>, string))").WithLocation(31, 58), // (31,58): warning CS8600: Converting null literal or possible null value to non-nullable type. // (string k1, (C<string> k2, string k3)) = (null!, default((C<string>, string))!); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((C<string>, string))").WithLocation(31, 58) ); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_Tuple() { var source = @" class C<T> { } class C2 { static T Id<T>(T t) => t; void M(C<string?> c) { // line 1 (string, (C<string>, string)) t1 = (null, (c, null)); t1.Item1.ToString(); // warn Id(t1).Item1.ToString(); // no warn // line 2 (string, (C<string>, string)) t2 = (null, (c, null))!; t2.Item1.ToString(); // warn Id(t2).Item1.ToString(); // no warn // line 3 (string, (C<string>, string)) t3 = (null, (c, null)!); t3.Item1.ToString(); // warn Id(t3).Item1.ToString(); // no warn // line 4 (string, (C<string>, string)) t4 = (null, (c, null)!)!; // no warn t4.Item1.ToString(); // warn Id(t4).Item1.ToString(); // no warn // line 5 (string, (C<string>, string)) t5 = (null!, (c, null)!); // no warn t5.Item1.ToString(); // no warn Id(t5).Item1.ToString(); // no warn // line 6 (string, (C<string>, string)) t6 = (null!, (c!, null!)); // warn t6.Item1.ToString(); // no warn Id(t6).Item1.ToString(); // no warn // line 7 (string, (C<string>, string)) t7 = (null!, (c!, null!)!); // no warn t7.Item1.ToString(); // no warn Id(t7).Item1.ToString(); // no warn // line 8 (string, (C<string>, string)) t8 = (null, (c, null))!; // warn t8.Item1.ToString(); // warn Id(t8).Item1.ToString(); // no warn } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // line 1 // (9,51): warning CS8619: Nullability of reference types in value of type '(C<string?> c, string?)' doesn't match target type '(C<string>, string)'. // (string, (C<string>, string)) t1 = (null, (c, null)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(c, null)").WithArguments("(C<string?> c, string?)", "(C<string>, string)").WithLocation(9, 51), // (9,44): warning CS8619: Nullability of reference types in value of type '(string?, (C<string>, string))' doesn't match target type '(string, (C<string>, string))'. // (string, (C<string>, string)) t1 = (null, (c, null)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, (c, null))").WithArguments("(string?, (C<string>, string))", "(string, (C<string>, string))").WithLocation(9, 44), // (10,9): warning CS8602: Dereference of a possibly null reference. // t1.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1.Item1").WithLocation(10, 9), // line 2 // (14,51): warning CS8619: Nullability of reference types in value of type '(C<string?> c, string?)' doesn't match target type '(C<string>, string)'. // (string, (C<string>, string)) t2 = (null, (c, null))!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(c, null)").WithArguments("(C<string?> c, string?)", "(C<string>, string)").WithLocation(14, 51), // (15,9): warning CS8602: Dereference of a possibly null reference. // t2.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2.Item1").WithLocation(15, 9), // line 3 // (19,44): warning CS8619: Nullability of reference types in value of type '(string?, (C<string>, string))' doesn't match target type '(string, (C<string>, string))'. // (string, (C<string>, string)) t3 = (null, (c, null)!); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, (c, null)!)").WithArguments("(string?, (C<string>, string))", "(string, (C<string>, string))").WithLocation(19, 44), // (20,9): warning CS8602: Dereference of a possibly null reference. // t3.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3.Item1").WithLocation(20, 9), // line 4 // (25,9): warning CS8602: Dereference of a possibly null reference. // t4.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t4.Item1").WithLocation(25, 9), // line 6 // (34,52): warning CS8619: Nullability of reference types in value of type '(C<string?>, string)' doesn't match target type '(C<string>, string)'. // (string, (C<string>, string)) t6 = (null!, (c!, null!)); // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(c!, null!)").WithArguments("(C<string?>, string)", "(C<string>, string)").WithLocation(34, 52), // line 8 // (44,51): warning CS8619: Nullability of reference types in value of type '(C<string?> c, string?)' doesn't match target type '(C<string>, string)'. // (string, (C<string>, string)) t8 = (null, (c, null))!; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(c, null)").WithArguments("(C<string?> c, string?)", "(C<string>, string)").WithLocation(44, 51), // (45,9): warning CS8602: Dereference of a possibly null reference. // t8.Item1.ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t8.Item1").WithLocation(45, 9)); CompileAndVerify(comp); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_TupleEquality() { var source = @"class C<T> { static void M((string, C<string>) t, C<string?> c) { _ = t == (null, c); _ = t == (null, c)!; _ = (1, t) == (1, (null, c)); _ = (1, t) == (1, (null, c)!); _ = (1, t) == (1, (null!, c!)); _ = (1, t!) == (1, (null, c)); _ = (t, (null, c)!) == ((null, c)!, t); _ = (t, (null!, c!)) == ((null!, c!), t); _ = (t!, (null, c)) == ((null, c), t!); _ = (t, (null, c))! == ((null, c), t); _ = (t, (null, c)) == ((null, c), t)!; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); CompileAndVerify(comp); } [Fact] public void SuppressNullableWarning_ValueType_01() { var source = @"struct S { static void F() { G(1!); G(((int?)null)!); G(default(S)!); _ = new S2<object>()!; } static void G(object o) { } static void G<T>(T? t) where T : struct { } } struct S2<T> { }"; // Feature enabled. var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); // Feature disabled. comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); // Feature disabled (C# 7). comp = CreateCompilation( new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (5,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(1!); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "1!").WithArguments("nullable reference types", "8.0").WithLocation(5, 11), // (6,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(((int?)null)!); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "((int?)null)!").WithArguments("nullable reference types", "8.0").WithLocation(6, 11), // (7,11): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // G(default(S)!); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "default(S)!").WithArguments("nullable reference types", "8.0").WithLocation(7, 11), // (8,13): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = new S2<object>()!; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "new S2<object>()!").WithArguments("nullable reference types", "8.0").WithLocation(8, 13)); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_ValueType_02() { var source = @"struct S<T> where T : class? { static S<object> F(S<object?> s) => s /*T:S<object?>*/ !; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_UserDefinedConversion() { var source = @" struct S { public static implicit operator C?(S s) => new C(); } class C { void M() { C c = new S()!; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(29642, "https://github.com/dotnet/roslyn/issues/29642")] public void SuppressNullableWarning_UserDefinedConversion_InArrayInitializer() { var source = @" struct S { public static implicit operator C?(S s) => new C(); } class C { void M(C c) { var a = new[] { c, new S()! }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void SuppressNullableWarning_GenericType() { var source = @"struct S { static void F<TStruct, TRef, TUnconstrained>(TStruct tStruct, TRef tRef, TUnconstrained tUnconstrained) where TStruct : struct where TRef : class { _ = tStruct!; _ = tRef!; _ = tUnconstrained!; } }"; // Feature enabled. var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); // Feature disabled. comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); // Feature disabled (C# 7). comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (6,13): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = tStruct!; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "tStruct!").WithArguments("nullable reference types", "8.0").WithLocation(6, 13), // (7,13): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = tRef!; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "tRef!").WithArguments("nullable reference types", "8.0").WithLocation(7, 13), // (8,13): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // _ = tUnconstrained!; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "tUnconstrained!").WithArguments("nullable reference types", "8.0").WithLocation(8, 13) ); } [Fact] public void SuppressNullableWarning_TypeParameters_01() { var source = @"class C { static void F1<T1>(T1 t1) { default(T1).ToString(); // 1 default(T1)!.ToString(); t1.ToString(); // 2 t1!.ToString(); } static void F2<T2>(T2 t2) where T2 : class { default(T2).ToString(); // 3 default(T2)!.ToString(); // 4 t2.ToString(); t2!.ToString(); } static void F3<T3>(T3 t3) where T3 : struct { default(T3).ToString(); default(T3)!.ToString(); t3.ToString(); t3!.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // default(T1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T1)").WithLocation(5, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(7, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // default(T2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T2)").WithLocation(12, 9) ); } [Fact] public void SuppressNullableWarning_TypeParameters_02() { var source = @"abstract class A<T> { internal abstract void F<U>(out T t, out U u) where U : T; } class B1<T> : A<T> where T : class { internal override void F<U>(out T t1, out U u1) { t1 = default(T)!; t1 = default!; u1 = default(U)!; u1 = default!; } } class B2<T> : A<T> where T : struct { internal override void F<U>(out T t2, out U u2) { t2 = default(T)!; // 1 t2 = default!; // 2 u2 = default(U)!; // 3 u2 = default!; // 4 } } class B3<T> : A<T> { internal override void F<U>(out T t3, out U u3) { t3 = default(T)!; t3 = default!; u3 = default(U)!; u3 = default!; } } class B4 : A<object> { internal override void F<U>(out object t4, out U u4) { t4 = default(object)!; t4 = default!; u4 = default(U)!; u4 = default!; } } class B5 : A<int> { internal override void F<U>(out int t5, out U u5) { t5 = default(int)!; // 5 t5 = default!; // 6 u5 = default(U)!; // 7 u5 = default!; // 8 } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); // https://github.com/dotnet/roslyn/issues/29907: Report error for `default!`. comp.VerifyDiagnostics(); } [Fact] public void SuppressNullableWarning_NonNullOperand() { var source = @"class C { static void F(string? s) { G(""""!); G((new string('a', 1))!); G((s ?? """")!); } static void G(string s) { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void SuppressNullableWarning_InvalidOperand() { var source = @"class C { static void F(C c) { G(F!); G(c.P!); } static void G(object o) { } object P { set { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,11): error CS0154: The property or indexer 'C.P' cannot be used in this context because it lacks the get accessor // G(c.P!); Diagnostic(ErrorCode.ERR_PropertyLacksGet, "c.P").WithArguments("C.P").WithLocation(6, 11) ); } [Fact] public void SuppressNullableWarning_InvalidArrayInitializer() { var source = @"class C { static void F() { var a = new object[] { new object(), F! }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31370, "https://github.com/dotnet/roslyn/issues/31370")] public void SuppressNullableWarning_IndexedProperty() { var source0 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Class A Public ReadOnly Property P(i As Integer) As Object Get Return Nothing End Get End Property Public ReadOnly Property Q(Optional i As Integer = 0) As Object Get Return Nothing End Get End Property End Class"; var ref0 = BasicCompilationUtils.CompileToMetadata(source0); var source = @"class B { static object F(A a, int i) { if (i > 0) { return a.P!; } return a.Q!; } }"; var comp = CreateCompilation( new[] { source }, new[] { ref0 }, parseOptions: TestOptions.Regular8, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,20): error CS0856: Indexed property 'A.P' has non-optional arguments which must be provided // return a.P!; Diagnostic(ErrorCode.ERR_IndexedPropertyRequiresParams, "a.P").WithArguments("A.P").WithLocation(7, 20)); } [Fact] public void LocalTypeInference() { var source = @"class C { static void F(string? s, string? t) { if (s != null) { var x = s; G(x); // no warning x = t; } else { var y = s; G(y); // warning y = t; } } static void G(string s) { } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (14,15): warning CS8604: Possible null reference argument for parameter 's' in 'void C.G(string s)'. // G(y); // warning Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("s", "void C.G(string s)").WithLocation(14, 15)); } [Fact] public void AssignmentInCondition_01() { var source = @"class C { object P => null; static void F(object o) { C? c; while ((c = o as C) != null) { o = c.P; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,17): warning CS8603: Possible null reference return. // object P => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(3, 17)); } [Fact] public void AssignmentInCondition_02() { var source = @"class C { object? P => null; static void F(object? o) { C? c; while ((c = o as C) != null) { o = c.P; } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void StructAsNullableInterface() { var source = @"interface I { void F(); } struct S : I { void I.F() { } } class C { static void F(I? i) { i.F(); } static void Main() { F(new S()); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // i.F(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "i").WithLocation(15, 9)); } [Fact] public void IsNull() { var source = @"class C { static void F1(object o) { } static void F2(object o) { } static void G(object? o) { if (o is null) { F1(o); } else { F2(o); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,16): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F1(object o)'. // F1(o); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.F1(object o)").WithLocation(9, 16)); } [Fact] public void IsInvalidConstant() { var source = @"class C { static void F(object o) { } static void G(object? o) { if (o is F) { F(o); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): error CS0150: A constant value is expected // if (o is F) Diagnostic(ErrorCode.ERR_ConstantExpected, "F").WithLocation(6, 18), // (8,15): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // F(o); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.F(object o)").WithLocation(8, 15)); } [Fact] public void Feature() { var source = @"class C { static object F() => null; static object F(object? o) => o; }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8.WithFeature("staticNullChecking")); comp.VerifyDiagnostics( // (3,26): warning CS8603: Possible null reference return. // static object F() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(3, 26), // (4,35): warning CS8603: Possible null reference return. // static object F(object? o) => o; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(4, 35)); comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8.WithFeature("staticNullChecking", "0")); comp.VerifyDiagnostics( // (3,26): warning CS8603: Possible null reference return. // static object F() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(3, 26), // (4,35): warning CS8603: Possible null reference return. // static object F(object? o) => o; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(4, 35)); comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8.WithFeature("staticNullChecking", "1")); comp.VerifyDiagnostics( // (3,26): warning CS8603: Possible null reference return. // static object F() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(3, 26), // (4,35): warning CS8603: Possible null reference return. // static object F(object? o) => o; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(4, 35)); } [Fact] public void AllowMemberOptOut() { var source1 = @"partial class C { #nullable disable static void F(object o) { } }"; var source2 = @"partial class C { static void G(object o) { } static void M(object? o) { F(o); G(o); } }"; var comp = CreateCompilation( new[] { source1, source2 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,25): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static void M(object? o) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 25) ); comp = CreateCompilation( new[] { source1, source2 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,11): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.G(object o)'. // G(o); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "void C.G(object o)").WithLocation(9, 11)); } [Fact] public void InferLocalNullability() { var source = @"class C { static string? F(string s) => s; static void G(string s) { string x; x = F(s); F(x); string? y = s; y = F(y); F(y); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = F(s); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F(s)").WithLocation(7, 13), // (8,11): warning CS8604: Possible null reference argument for parameter 's' in 'string? C.F(string s)'. // F(x); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("s", "string? C.F(string s)").WithLocation(8, 11), // (11,11): warning CS8604: Possible null reference argument for parameter 's' in 'string? C.F(string s)'. // F(y); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("s", "string? C.F(string s)").WithLocation(11, 11)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var declarator = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().First(); var symbol = model.GetDeclaredSymbol(declarator).GetSymbol<LocalSymbol>(); Assert.Equal("System.String!", symbol.TypeWithAnnotations.ToTestDisplayString(true)); } [Fact] public void InferLocalType_UsedInDeclaration() { var source = @"using System; using System.Collections.Generic; class C { static T F<T>(IEnumerable<T> e) { throw new NotImplementedException(); } static void G() { var a = new[] { F(a) }; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,27): error CS0841: Cannot use local variable 'a' before it is declared // var a = new[] { F(a) }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "a").WithArguments("a").WithLocation(11, 27)); } [Fact] public void InferLocalType_UsedInDeclaration_Script() { var source = @"using System; using System.Collections.Generic; static T F<T>(IEnumerable<T> e) { throw new NotImplementedException(); } var a = new[] { F(a) };"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp8)); comp.VerifyDiagnostics( // (7,5): error CS7019: Type of 'a' cannot be inferred since its initializer directly or indirectly refers to the definition. // var a = new[] { F(a) }; Diagnostic(ErrorCode.ERR_RecursivelyTypedVariable, "a").WithArguments("a").WithLocation(7, 5)); } [Fact] public void InferLocalType_UsedBeforeDeclaration() { var source = @"using System; using System.Collections.Generic; class C { static T F<T>(IEnumerable<T> e) { throw new NotImplementedException(); } static void G() { var a = new[] { F(b) }; var b = a; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,27): error CS0841: Cannot use local variable 'b' before it is declared // var a = new[] { F(b) }; Diagnostic(ErrorCode.ERR_VariableUsedBeforeDeclaration, "b").WithArguments("b").WithLocation(11, 27)); } [Fact] public void InferLocalType_OutVarError() { var source = @"using System; using System.Collections.Generic; class C { static T F<T>(IEnumerable<T> e) { throw new NotImplementedException(); } static void G() { dynamic d = null!; d.F(out var v); F(v).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,21): error CS8197: Cannot infer the type of implicitly-typed out variable 'v'. // d.F(out var v); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "v").WithArguments("v").WithLocation(12, 21)); } [Fact] public void InferLocalType_OutVarError_Script() { var source = @"using System; using System.Collections.Generic; static T F<T>(IEnumerable<T> e) { throw new NotImplementedException(); } dynamic d = null!; d.F(out var v); F(v).ToString();"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, parseOptions: TestOptions.Script.WithLanguageVersion(LanguageVersion.CSharp8)); comp.VerifyDiagnostics( // (8,13): error CS8197: Cannot infer the type of implicitly-typed out variable 'v'. // d.F(out var v); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedOutVariable, "v").WithArguments("v").WithLocation(8, 13) ); } /// <summary> /// Default value for non-nullable parameter /// should not result in a warning at the call site. /// </summary> [WorkItem(26626, "https://github.com/dotnet/roslyn/issues/26626")] [Fact] public void ParameterDefaultValue_FromMetadata() { var source0 = @"public class C { public static void F(object o = null) { } }"; var comp0 = CreateCompilation( new[] { source0 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp0.VerifyDiagnostics( // (3,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // public static void F(object o = null) Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(3, 37) ); var ref0 = comp0.EmitToImageReference(); var source1 = @"class Program { static void Main() { C.F(); C.F(null); } }"; var comp1 = CreateCompilation( new[] { source1 }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, references: new[] { ref0 }); comp1.VerifyDiagnostics( // (6,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // C.F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 13)); } [Fact] public void ParameterDefaultValue_WithSuppression() { var source0 = @"class C { void F(object o = null!) { } }"; var comp = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [WorkItem(26626, "https://github.com/dotnet/roslyn/issues/26626")] [Fact] public void ParameterDefaultValue_01() { var source = @"class C { const string? S0 = null; const string? S1 = """"; static string? F() => string.Empty; static void F0(string s = null) { } // 1 static void F1(string s = default) { } // 2 static void F2(string s = default(string)) { } // 3 static void F3( string x = (string)null, // 4, 5 string y = (string?)null) { } // 6 static void F4(string s = S0) { } // 7 static void F5(string s = S1) { } // 8 static void F6(string s = F()) { } // 9 static void M() { F0(); F1(); F2(); F3(); F4(); F5(); F6(); F0(null); // 10 F0(string.Empty); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F0(string s = null) { } // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 31), // (7,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F1(string s = default) { } // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(7, 31), // (8,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F2(string s = default(string)) { } // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default(string)").WithLocation(8, 31), // (10,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // string x = (string)null, // 4, 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(10, 20), // (10,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // string x = (string)null, // 4, 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string)null").WithLocation(10, 20), // (11,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // string y = (string?)null) { } // 6 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string?)null").WithLocation(11, 20), // (12,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F4(string s = S0) { } // 7 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "S0").WithLocation(12, 31), // (13,31): warning CS8601: Possible null reference assignment. // static void F5(string s = S1) { } // 8 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "S1").WithLocation(13, 31), // (14,31): error CS1736: Default parameter value for 's' must be a compile-time constant // static void F6(string s = F()) { } // 9 Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "F()").WithArguments("s").WithLocation(14, 31), // (14,31): warning CS8601: Possible null reference assignment. // static void F6(string s = F()) { } // 9 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "F()").WithLocation(14, 31), // (24,12): warning CS8625: Cannot convert null literal to non-nullable reference type. // F0(null); // 10 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(24, 12) ); } [WorkItem(26626, "https://github.com/dotnet/roslyn/issues/26626")] [Fact] public void ParameterDefaultValue_02() { var source = @"class C { const string? S0 = null; static void F0(string s = null!) { } static void F1( string x = (string)null!, string y = ((string)null)!) { } // 1 static void F2( string x = default!, string y = default(string)!) { } static void F3(string s = S0!) { } static void F4(string x = (string)null) { } // 2, 3 static void F5(string? y = (string)null) { } // 4 static void M() { F0(); F1(); F2(); F3(); F1(x: null); // 5 F1(y: null); // 6 F2(null!, null); // 7 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // string y = ((string)null)!) { } // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(7, 21), // (12,31): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F4(string x = (string)null) { } // 2, 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(12, 31), // (12,31): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F4(string x = (string)null) { } // 2, 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "(string)null").WithLocation(12, 31), // (13,32): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F5(string? y = (string)null) { } // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(13, 32), // (20,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F1(x: null); // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 15), // (21,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F1(y: null); // 6 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 15), // (22,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // F2(null!, null); // 7 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(22, 19) ); } [WorkItem(26626, "https://github.com/dotnet/roslyn/issues/26626")] [WorkItem(29910, "https://github.com/dotnet/roslyn/issues/29910")] [Fact] public void ParameterDefaultValue_03() { var source = @"interface I { } class C : I { } class P { static void F0<T>(T t = default) { } // 1 static void F1<T>(T t = null) where T : class { } // 2 static void F2<T>(T t = default) where T : struct { } static void F3<T>(T t = default) where T : new() { } // 3 static void F4<T>(T t = null) where T : C { } // 4 static void F5<T>(T t = default) where T : I { } // 5 static void F6<T, U>(T t = default) where T : U { } // 6 static void G0() { F0<object>(); F0<object>(default); // 7 F0(new object()); F1<object>(); F1<object>(default); // 8 F1(new object()); F2<int>(); F2<int>(default); F2(2); F3<object>(); F3<object>(default); // 9 F3(new object()); F4<C>(); F4<C>(default); // 10 F4(new C()); F5<I>(); F5<I>(default); // 11 F5(new C()); F6<object, object>(); F6<object, object>(default); // 12 F6<object, object>(new object()); } static void G0<T>() { F0<T>(); F0<T>(default); // 13 F6<T, T>(); F6<T, T>(default); // 14 } static void G1<T>() where T : class { F0<T>(); F0<T>(default); // 15 F1<T>(); F1<T>(default); // 16 F6<T, T>(); F6<T, T>(default); // 17 } static void G2<T>() where T : struct { F0<T>(); F0<T>(default); F2<T>(); F2<T>(default); F3<T>(); F3<T>(default); F6<T, T>(); F6<T, T>(default); } static void G3<T>() where T : new() { F0<T>(); F0<T>(default); // 18 F0<T>(new T()); F3<T>(); F3<T>(default); // 19 F3<T>(new T()); F6<T, T>(); F6<T, T>(default); // 20 F6<T, T>(new T()); } static void G4<T>() where T : C { F0<T>(); F0<T>(default); // 21 F1<T>(); F1<T>(default); // 22 F4<T>(); F4<T>(default); // 23 F5<T>(); F5<T>(default); // 24 F6<T, T>(); F6<T, T>(default); // 25 } static void G5<T>() where T : I { F0<T>(); F0<T>(default); // 26 F5<T>(); F5<T>(default); // 27 F6<T, T>(); F6<T, T>(default); // 28 } static void G6<T, U>() where T : U { F0<T>(); F0<T>(default); // 29 F6<T, U>(); F6<T, U>(default); // 30 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,29): warning CS8601: Possible null reference assignment. // static void F0<T>(T t = default) { } // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(5, 29), // (6,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F1<T>(T t = null) where T : class { } // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 29), // (8,29): warning CS8601: Possible null reference assignment. // static void F3<T>(T t = default) where T : new() { } // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(8, 29), // (9,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F4<T>(T t = null) where T : C { } // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(9, 29), // (10,29): warning CS8601: Possible null reference assignment. // static void F5<T>(T t = default) where T : I { } // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(10, 29), // (11,32): warning CS8601: Possible null reference assignment. // static void F6<T, U>(T t = default) where T : U { } // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(11, 32), // (15,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // F0<object>(default); // 7 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(15, 20), // (18,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // F1<object>(default); // 8 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(18, 20), // (24,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // F3<object>(default); // 9 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(24, 20), // (27,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F4<C>(default); // 10 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(27, 15), // (30,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F5<I>(default); // 11 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(30, 15), // (33,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // F6<object, object>(default); // 12 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(33, 28), // (39,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F0<T>(T t = default(T))'. // F0<T>(default); // 13 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F0<T>(T t = default(T))").WithLocation(39, 15), // (41,18): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F6<T, T>(T t = default(T))'. // F6<T, T>(default); // 14 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F6<T, T>(T t = default(T))").WithLocation(41, 18), // (46,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F0<T>(default); // 15 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(46, 15), // (48,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F1<T>(default); // 16 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(48, 15), // (50,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // F6<T, T>(default); // 17 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(50, 18), // (66,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F0<T>(T t = default(T))'. // F0<T>(default); // 18 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F0<T>(T t = default(T))").WithLocation(66, 15), // (69,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F3<T>(T t = default(T))'. // F3<T>(default); // 19 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F3<T>(T t = default(T))").WithLocation(69, 15), // (72,18): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F6<T, T>(T t = default(T))'. // F6<T, T>(default); // 20 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F6<T, T>(T t = default(T))").WithLocation(72, 18), // (78,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F0<T>(default); // 21 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(78, 15), // (80,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F1<T>(default); // 22 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(80, 15), // (82,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F4<T>(default); // 23 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(82, 15), // (84,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F5<T>(default); // 24 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(84, 15), // (86,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // F6<T, T>(default); // 25 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(86, 18), // (91,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F0<T>(T t = default(T))'. // F0<T>(default); // 26 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F0<T>(T t = default(T))").WithLocation(91, 15), // (93,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F5<T>(T t = default(T))'. // F5<T>(default); // 27 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F5<T>(T t = default(T))").WithLocation(93, 15), // (95,18): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F6<T, T>(T t = default(T))'. // F6<T, T>(default); // 28 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F6<T, T>(T t = default(T))").WithLocation(95, 18), // (100,15): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F0<T>(T t = default(T))'. // F0<T>(default); // 29 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F0<T>(T t = default(T))").WithLocation(100, 15), // (102,18): warning CS8604: Possible null reference argument for parameter 't' in 'void P.F6<T, U>(T t = default(T))'. // F6<T, U>(default); // 30 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void P.F6<T, U>(T t = default(T))").WithLocation(102, 18) ); // No warnings with C#7.3. comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); comp.VerifyDiagnostics( // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.3", "8.0").WithLocation(1, 1) ); } [Fact] public void NonNullTypesInCSharp7_InSource() { var source = @" #nullable enable public class C { public static string field; } public class D { #nullable enable public static string field; #nullable enable public static string Method(string s) => throw null; #nullable enable public static string Property { get; set; } #nullable enable public static event System.Action Event; #nullable disable void M() { C.field = null; D.field = null; D.Method(null); D.Property = null; D.Event(); } } "; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7, skipUsesIsNullable: true); comp.VerifyDiagnostics( // (2,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(2, 2), // (9,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(9, 2), // (12,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(12, 2), // (15,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(15, 2), // (18,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(18, 2), // (20,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.0. Please use language version 8.0 or greater. // #nullable disable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(20, 2) ); } [Fact] public void NonNullTypesInCSharp7_FromMetadata() { var libSource = @"#nullable enable #pragma warning disable 8618 public class C { public static string field; } public class D { #nullable enable public static string field; #nullable enable public static string Method(string s) => throw null!; #nullable enable public static string Property { get; set; } #nullable enable public static event System.Action Event; } "; var libComp = CreateCompilation(new[] { libSource }); libComp.VerifyDiagnostics( // (19,39): warning CS0067: The event 'D.Event' is never used // public static event System.Action Event; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "Event").WithArguments("D.Event").WithLocation(19, 39) ); var source = @" class Client { void M() { C.field = null; D.field = null; D.Method(null); D.Property = null; D.Event(); } } "; var comp = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() }, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics( // (10,11): error CS0079: The event 'D.Event' can only appear on the left hand side of += or -= // D.Event(); Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "Event").WithArguments("D.Event").WithLocation(10, 11) ); var comp2 = CreateCompilation(source, references: new[] { libComp.EmitToImageReference() }); comp2.VerifyDiagnostics( // (10,11): error CS0079: The event 'D.Event' can only appear on the left hand side of += or -= // D.Event(); Diagnostic(ErrorCode.ERR_BadEventUsageNoField, "Event").WithArguments("D.Event").WithLocation(10, 11) ); } [WorkItem(26626, "https://github.com/dotnet/roslyn/issues/26626")] [Fact] public void ParameterDefaultValue_04() { var source = @"partial class C { static partial void F(object? x = null, object y = null); static partial void F(object? x, object y) { } static partial void G(object x, object? y); static partial void G(object x = null, object? y = null) { } static void M() { F(); G(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,34): warning CS1066: The default value specified for parameter 'x' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // static partial void G(object x = null, object? y = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "x").WithArguments("x").WithLocation(6, 34), // (6,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // static partial void G(object x = null, object? y = null) { } Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 38), // (6,52): warning CS1066: The default value specified for parameter 'y' will have no effect because it applies to a member that is used in contexts that do not allow optional arguments // static partial void G(object x = null, object? y = null) { } Diagnostic(ErrorCode.WRN_DefaultValueForUnconsumedLocation, "y").WithArguments("y").WithLocation(6, 52), // (3,56): warning CS8625: Cannot convert null literal to non-nullable reference type. // static partial void F(object? x = null, object y = null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(3, 56), // (10,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'x' of 'C.G(object, object?)' // G(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "G").WithArguments("x", "C.G(object, object?)").WithLocation(10, 9) ); } [WorkItem(40818, "https://github.com/dotnet/roslyn/issues/40818")] [Fact] public void ParameterDefaultValue_05() { var source = @" class C { T M1<T>(T t = default) // 1 => t; T M2<T>(T t = default) where T : class? // 2 => t; T M3<T>(T t = default) where T : class // 3 => t; T M4<T>(T t = default) where T : notnull // 4 => t; T M5<T>(T? t = default) where T : struct => t.Value; // 5 T M6<T>(T? t = default(T)) where T : struct // 6 => t.Value; // 7 }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); var expected = new[] { // (4,19): warning CS8601: Possible null reference assignment. // T M1<T>(T t = default) // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(4, 19), // (7,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // T M2<T>(T t = default) where T : class? // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(7, 19), // (10,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // T M3<T>(T t = default) where T : class // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(10, 19), // (13,19): warning CS8601: Possible null reference assignment. // T M4<T>(T t = default) where T : notnull // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(13, 19), // (17,12): warning CS8629: Nullable value type may be null. // => t.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(17, 12), // (19,16): error CS1770: A value of type 'T' cannot be used as default parameter for nullable parameter 't' because 'T' is not a simple type // T M6<T>(T? t = default(T)) where T : struct // 6 Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "t").WithArguments("T", "t").WithLocation(19, 16), // (20,12): warning CS8629: Nullable value type may be null. // => t.Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(20, 12) }; comp.VerifyDiagnostics(expected); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(expected); } [WorkItem(40818, "https://github.com/dotnet/roslyn/issues/40818")] [WorkItem(40975, "https://github.com/dotnet/roslyn/issues/40975")] [Fact] public void ParameterDefaultValue_06() { var source = @" using System.Diagnostics.CodeAnalysis; class C { string M1(string? s = null) => s; // 1 string M2(string? s = ""a"") => s; // 2 int M3(int? i = null) => i.Value; // 3 int M4(int? i = 1) => i.Value; // 4 string M5([AllowNull] string s = null) => s; // 5 string M6([AllowNull] string s = ""a"") => s; // 6 int M7([DisallowNull] int? i = null) // 7 => i.Value; int M8([DisallowNull] int? i = 1) => i.Value; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,12): warning CS8603: Possible null reference return. // => s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(7, 12), // (10,12): warning CS8603: Possible null reference return. // => s; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(10, 12), // (13,12): warning CS8629: Nullable value type may be null. // => i.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(13, 12), // (16,12): warning CS8629: Nullable value type may be null. // => i.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(16, 12), // (19,12): warning CS8603: Possible null reference return. // => s; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(19, 12), // (22,12): warning CS8603: Possible null reference return. // => s; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(22, 12), // (24,36): warning CS8607: A possible null value may not be used for a type marked with [NotNull] or [DisallowNull] // int M7([DisallowNull] int? i = null) // 7 Diagnostic(ErrorCode.WRN_DisallowNullAttributeForbidsMaybeNullAssignment, "null").WithLocation(24, 36) ); } [Fact, WorkItem(47344, "https://github.com/dotnet/roslyn/issues/47344")] public void ParameterDefaultValue_07() { var source = @" record Rec1<T>(T t = default) // 1, 2 { } record Rec2<T>(T t = default) // 2 { T t { get; } = t; } record Rec3<T>(T t = default) // 3, 4 { T t { get; } = default!; } "; var comp = CreateCompilation(new[] { source, IsExternalInitTypeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (2,22): warning CS8601: Possible null reference assignment. // record Rec1<T>(T t = default) // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(2, 22), // (6,22): warning CS8601: Possible null reference assignment. // record Rec2<T>(T t = default) // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(6, 22), // (11,18): warning CS8907: Parameter 't' is unread. Did you forget to use it to initialize the property with that name? // record Rec3<T>(T t = default) // 3, 4 Diagnostic(ErrorCode.WRN_UnreadRecordParameter, "t").WithArguments("t").WithLocation(11, 18), // (11,22): warning CS8601: Possible null reference assignment. // record Rec3<T>(T t = default) // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(11, 22) ); } [Fact, WorkItem(43399, "https://github.com/dotnet/roslyn/issues/43399")] public void ParameterDefaultValue_08() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; public class C { public void M1([Optional, DefaultParameterValue(null)] object obj) // 1 { obj.ToString(); } public void M2([Optional, DefaultParameterValue(default(object))] object obj) // 2 { obj.ToString(); } public void M3([Optional, DefaultParameterValue(""a"")] object obj) { obj.ToString(); } public void M4([AllowNull, Optional, DefaultParameterValue(null)] object obj) { obj.ToString(); // 3 } public void M5([Optional, DefaultParameterValue((object)null)] object obj) // 4, 5 { obj.ToString(); } } "; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // public void M1([Optional, DefaultParameterValue(null)] object obj) // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "[Optional, DefaultParameterValue(null)] object obj").WithLocation(7, 20), // (11,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // public void M2([Optional, DefaultParameterValue(default(object))] object obj) // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "[Optional, DefaultParameterValue(default(object))] object obj").WithLocation(11, 20), // (21,9): warning CS8602: Dereference of a possibly null reference. // obj.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(21, 9), // (23,20): warning CS8625: Cannot convert null literal to non-nullable reference type. // public void M5([Optional, DefaultParameterValue((object)null)] object obj) // 3, 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "[Optional, DefaultParameterValue((object)null)] object obj").WithLocation(23, 20), // (23,53): warning CS8600: Converting null literal or possible null value to non-nullable type. // public void M5([Optional, DefaultParameterValue((object)null)] object obj) // 3, 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)null").WithLocation(23, 53) ); } [Fact, WorkItem(43399, "https://github.com/dotnet/roslyn/issues/43399")] public void ParameterDefaultValue_09() { var source = @" using System.Runtime.InteropServices; public class C { public void M1([Optional, DefaultParameterValue(null!)] object obj) { obj.ToString(); } public void M2([Optional, DefaultParameterValue(default)] object obj) { obj.ToString(); } public void M3([Optional, DefaultParameterValue(null)] object obj = null) { obj.ToString(); } } "; // 'M1' doesn't seem like a scenario where an error or warning should be given. // However, we can't round trip the concept that the parameter default value was suppressed. // Therefore even if we fixed this, this usage could result in strange corner case behaviors when // emitting the method to metadata and calling it in source. var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,31): error CS8017: The parameter has multiple distinct default values. // public void M1([Optional, DefaultParameterValue(null!)] object obj) Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "DefaultParameterValue(null!)").WithLocation(5, 31), // (9,31): error CS8017: The parameter has multiple distinct default values. // public void M2([Optional, DefaultParameterValue(default)] object obj) Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "DefaultParameterValue(default)").WithLocation(9, 31), // (13,21): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute // public void M3([Optional, DefaultParameterValue(null)] object obj = null) Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "Optional").WithLocation(13, 21), // (13,31): error CS1745: Cannot specify default parameter value in conjunction with DefaultParameterAttribute or OptionalAttribute // public void M3([Optional, DefaultParameterValue(null)] object obj = null) Diagnostic(ErrorCode.ERR_DefaultValueUsedWithAttributes, "DefaultParameterValue").WithLocation(13, 31), // (13,73): warning CS8625: Cannot convert null literal to non-nullable reference type. // public void M3([Optional, DefaultParameterValue(null)] object obj = null) Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 73), // (13,73): error CS8017: The parameter has multiple distinct default values. // public void M3([Optional, DefaultParameterValue(null)] object obj = null) Diagnostic(ErrorCode.ERR_ParamDefaultValueDiffersFromAttribute, "null").WithLocation(13, 73) ); } [Fact, WorkItem(48847, "https://github.com/dotnet/roslyn/issues/48847")] public void ParameterDefaultValue_10() { var source = @" public abstract class C1 { public abstract void M1(string s = null); // 1 public abstract void M2(string? s = null); } public interface I1 { void M1(string s = null); // 2 void M2(string? s = null); } public delegate void D1(string s = null); // 3 public delegate void D2(string? s = null); "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,40): warning CS8625: Cannot convert null literal to non-nullable reference type. // public abstract void M1(string s = null); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 40), // (10,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // void M1(string s = null); // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 24), // (14,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // public delegate void D1(string s = null); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 36) ); } [Fact, WorkItem(48844, "https://github.com/dotnet/roslyn/issues/48844")] public void ParameterDefaultValue_11() { var source = @" delegate void D1<T>(T t = default); // 1 delegate void D2<T>(T? t = default); class C { void M() { D1<string> d1 = str => str.ToString(); d1(); D2<string> d2 = str => str.ToString(); // 2 d2(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (2,27): warning CS8601: Possible null reference assignment. // delegate void D1<T>(T t = default); // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(2, 27), // (12,32): warning CS8602: Dereference of a possibly null reference. // D2<string> d2 = str => str.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "str").WithLocation(12, 32) ); } [Fact, WorkItem(48848, "https://github.com/dotnet/roslyn/issues/48848")] public void ParameterDefaultValue_12() { var source = @" public class Base1<T> { public virtual void M(T t = default) { } // 1 } public class Override1 : Base1<string> { public override void M(string s) { } } public class Base2<T> { public virtual void M(T? t = default) { } } public class Override2 : Base2<string> { public override void M(string s) { } // 2 } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,33): warning CS8601: Possible null reference assignment. // public virtual void M(T t = default) { } // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(4, 33), // (19,26): warning CS8765: Nullability of type of parameter 's' doesn't match overridden member (possibly because of nullability attributes). // public override void M(string s) { } // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("s").WithLocation(19, 26) ); } [Fact] public void InvalidThrowTerm() { var source = @"class C { static string F(string s) => s + throw new System.Exception(); }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (3,38): error CS1525: Invalid expression term 'throw' // static string F(string s) => s + throw new System.Exception(); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "throw new System.Exception()").WithArguments("throw").WithLocation(3, 38)); } [Fact] public void UnboxingConversion_01() { var source = @"using System.Collections.Generic; class Program { static IEnumerator<T> M<T>() => default(T); }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,37): error CS0266: Cannot implicitly convert type 'T' to 'System.Collections.Generic.IEnumerator<T>'. An explicit conversion exists (are you missing a cast?) // static IEnumerator<T> M<T>() => default(T); Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "default(T)").WithArguments("T", "System.Collections.Generic.IEnumerator<T>").WithLocation(4, 37), // (4,37): warning CS8603: Possible null reference return. // static IEnumerator<T> M<T>() => default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(4, 37) ); } [Fact] [WorkItem(33359, "https://github.com/dotnet/roslyn/issues/33359")] public void UnboxingConversion_02() { var source = @"class C { interface I { } struct S : I { } static void Main() { M<S, I?>(null); } static void M<T, V>(V v) where T : struct, V { var t = ((T) v); // 1 } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (13,18): warning CS8605: Unboxing a possibly null value. // var t = ((T) v); // 1 Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(T) v").WithLocation(13, 18)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_03() { var source = @"public interface I { } public struct S : I { static void M1(I? i) { S s = (S)i; // 1 _ = i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8605: Unboxing a possibly null value. // S s = (S)i; // 1 Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(S)i").WithLocation(7, 15)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_04() { var source = @"public interface I { } public struct S : I { static void M1(I? i) { S s = (S)i!; _ = i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_05() { var source = @"public interface I { } public class C { public I? i = new S(); } public struct S : I { static void M1(C? c) { S s = (S)c?.i; // 1 _ = c.ToString(); _ = c.i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,15): warning CS8605: Unboxing a possibly null value. // S s = (S)c?.i; // 1 Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(S)c?.i").WithLocation(12, 15)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_06() { var source = @"public interface I { } public class C { public I? i = new S(); } public struct S : I { static void M1(C? c) { S? s = (S?)c?.i; _ = c.ToString(); // 1 _ = c.i.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(13, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = c.i.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.i").WithLocation(14, 13)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_07() { var source = @"public interface I { } public struct S : I { static void M1(I? i) { S s = (S)i; // 1 _ = i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8605: Unboxing a possibly null value. // S s = (S)i; // 1 Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(S)i").WithLocation(7, 15)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_08() { var source = @"public interface I { } public class C { static void M1<T>(I? i) { T t = (T)i; _ = i.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t = (T)i; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)i").WithLocation(7, 15), // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = i.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "i").WithLocation(8, 13)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void UnboxingConversion_09() { var source = @"public interface I { } public class C { static void M1<T>(I? i) where T : struct { T t = (T)i; // 1 _ = i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8605: Unboxing a possibly null value. // T t = (T)i; // 1 Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(T)i").WithLocation(7, 15)); } [Fact] public void DeconstructionConversion_NoDeconstructMethod() { var source = @"class C { static void F(C c) { var (x, y) = c; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,22): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // var (x, y) = c; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "c").WithArguments("C", "Deconstruct").WithLocation(5, 22), // (5,22): error CS8129: No suitable Deconstruct instance or extension method was found for type 'C', with 2 out parameters and a void return type. // var (x, y) = c; Diagnostic(ErrorCode.ERR_MissingDeconstruct, "c").WithArguments("C", "2").WithLocation(5, 22), // (5,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = c; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(5, 14), // (5,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = c; Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(5, 17)); } [Fact] [WorkItem(29916, "https://github.com/dotnet/roslyn/issues/29916")] public void ConditionalAccessDelegateInvoke() { var source = @"using System; class C<T> { static T F(Func<T>? f) { return f?.Invoke(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,17): error CS0023: Operator '?' cannot be applied to operand of type 'T' // return f?.Invoke(); Diagnostic(ErrorCode.ERR_BadUnaryOp, "?").WithArguments("?", "T").WithLocation(6, 17) ); } [Fact] public void NonNullTypes_DecodeAttributeCycle_01() { var source = @"using System.Runtime.InteropServices; interface I { int P { get; } } [StructLayout(LayoutKind.Auto)] struct S : I { int I.P => 0; }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void NonNullTypes_DecodeAttributeCycle_01_WithEvent() { var source = @"using System; using System.Runtime.InteropServices; interface I { event Func<int> E; } [StructLayout(LayoutKind.Auto)] struct S : I { event Func<int> I.E { add => throw null!; remove => throw null!; } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void NonNullTypes_DecodeAttributeCycle_02() { var source = @"[A(P)] class A : System.Attribute { string P => null; }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (1,4): error CS0120: An object reference is required for the non-static field, method, or property 'A.P' // [A(P)] Diagnostic(ErrorCode.ERR_ObjectRequired, "P").WithArguments("A.P").WithLocation(1, 4), // (1,2): error CS1729: 'A' does not contain a constructor that takes 1 arguments // [A(P)] Diagnostic(ErrorCode.ERR_BadCtorArgCount, "A(P)").WithArguments("A", "1").WithLocation(1, 2), // (4,17): warning CS8603: Possible null reference return. // string P => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(4, 17)); } [Fact] [WorkItem(29954, "https://github.com/dotnet/roslyn/issues/29954")] public void UnassignedOutParameterClass() { var source = @"class C { static void G(out C? c) { c.ToString(); // 1 c = null; c.ToString(); // 2 c = new C(); c.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS0269: Use of unassigned out parameter 'c' // c.ToString(); // 1 Diagnostic(ErrorCode.ERR_UseDefViolationOut, "c").WithArguments("c").WithLocation(5, 9), // (5,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(5, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(7, 9)); } [Fact] public void UnassignedOutParameterClassField() { var source = @"class C { #pragma warning disable 0649 object? F; static void G(out C c) { object o = c.F; c.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,20): error CS0269: Use of unassigned out parameter 'c' // object o = c.F; Diagnostic(ErrorCode.ERR_UseDefViolationOut, "c").WithArguments("c").WithLocation(7, 20), // (5,17): error CS0177: The out parameter 'c' must be assigned to before control leaves the current method // static void G(out C c) Diagnostic(ErrorCode.ERR_ParamUnassigned, "G").WithArguments("c").WithLocation(5, 17), // (7,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object o = c.F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.F").WithLocation(7, 20), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F").WithLocation(8, 9)); } [Fact] public void UnassignedOutParameterStructField() { var source = @"struct S { #pragma warning disable 0649 object? F; static void G(out S s) { object o = s.F; s.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,20): error CS0170: Use of possibly unassigned field 'F' // object o = s.F; Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.F").WithArguments("F").WithLocation(7, 20), // (5,17): error CS0177: The out parameter 's' must be assigned to before control leaves the current method // static void G(out S s) Diagnostic(ErrorCode.ERR_ParamUnassigned, "G").WithArguments("s").WithLocation(5, 17), // (7,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object o = s.F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s.F").WithLocation(7, 20), // (8,9): warning CS8602: Dereference of a possibly null reference. // s.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.F").WithLocation(8, 9) ); } [Fact] public void UnassignedLocalField() { var source = @"class C { static void F() { S s; C c; c = s.F; s.F.ToString(); } } struct S { internal C? F; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): error CS0170: Use of possibly unassigned field 'F' // c = s.F; Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.F").WithArguments("F").WithLocation(7, 13), // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = s.F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s.F").WithLocation(7, 13), // (8,9): warning CS8602: Dereference of a possibly null reference. // s.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.F").WithLocation(8, 9), // (13,17): warning CS0649: Field 'S.F' is never assigned to, and will always have its default value null // internal C? F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("S.F", "null").WithLocation(13, 17) ); } [Fact] public void UnassignedLocalField_Conditional() { var source = @"class C { static void F(bool b) { S s; object o; if (b) { s.F = new object(); s.G = new object(); } else { o = s.F; } o = s.G; } } struct S { internal object? F; internal object? G; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): error CS0170: Use of possibly unassigned field 'F' // o = s.F; Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.F").WithArguments("F").WithLocation(14, 17), // (14,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = s.F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s.F").WithLocation(14, 17), // (16,13): error CS0170: Use of possibly unassigned field 'G' // o = s.G; Diagnostic(ErrorCode.ERR_UseDefViolationField, "s.G").WithArguments("G").WithLocation(16, 13), // (16,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = s.G; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s.G").WithLocation(16, 13) ); } [Fact] public void UnassignedLocalProperty() { var source = @"class C { static void F() { S s; C c; c = s.P; s.P.ToString(); } } struct S { internal C? P { get => null; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = s.P; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s.P").WithLocation(7, 13), // (8,9): warning CS8602: Dereference of a possibly null reference. // s.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.P").WithLocation(8, 9)); } [Fact] public void UnassignedClassAutoProperty() { var source = @"class C { object? P { get; } void M(out object o) { o = P; P.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8601: Possible null reference assignment. // o = P; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "P").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "P").WithLocation(7, 9)); } [Fact] public void UnassignedClassAutoProperty_Constructor() { var source = @"class C { object? P { get; } C(out object o) { o = P; P.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8601: Possible null reference assignment. // o = P; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "P").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "P").WithLocation(7, 9)); } [Fact] public void UnassignedStructAutoProperty() { var source = @"struct S { object? P { get; } void M(out object o) { o = P; P.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8601: Possible null reference assignment. // o = P; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "P").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "P").WithLocation(7, 9)); } [Fact] public void UnassignedStructAutoProperty_Constructor() { var source = @"struct S { object? P { get; } S(out object o) { o = P; P.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): error CS8079: Use of possibly unassigned auto-implemented property 'P' // o = P; Diagnostic(ErrorCode.ERR_UseDefViolationProperty, "P").WithArguments("P").WithLocation(6, 13), // (4,5): error CS0843: Auto-implemented property 'S.P' must be fully assigned before control is returned to the caller. // S(out object o) Diagnostic(ErrorCode.ERR_UnassignedThisAutoProperty, "S").WithArguments("S.P").WithLocation(4, 5), // (6,13): warning CS8601: Possible null reference assignment. // o = P; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "P").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "P").WithLocation(7, 9) ); } [Fact] public void ParameterField_Class() { var source = @"class C { #pragma warning disable 0649 object? F; static void M(C x) { C y = x; object z = y.F; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object z = y.F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y.F").WithLocation(8, 20)); } [Fact] public void ParameterField_Struct() { var source = @"struct S { #pragma warning disable 0649 object? F; static void M(S x) { S y = x; object z = y.F; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object z = y.F; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y.F").WithLocation(8, 20)); } [Fact] public void InstanceFieldStructTypeExpressionReceiver() { var source = @"struct S { #pragma warning disable 0649 object? F; void M() { S.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): error CS0120: An object reference is required for the non-static field, method, or property 'S.F' // S.F.ToString(); Diagnostic(ErrorCode.ERR_ObjectRequired, "S.F").WithArguments("S.F").WithLocation(7, 9)); } [Fact] public void InstanceFieldPrimitiveRecursiveStruct() { var source = @"#pragma warning disable 0649 namespace System { public class Object { public int GetHashCode() => 0; } public abstract class ValueType { } public struct Void { } public struct Int32 { Int32 _value; object? _f; void M() { _value = _f.GetHashCode(); } } public class String { } public struct Boolean { } public struct Enum { } public class Exception { } public class Attribute { } public class AttributeUsageAttribute : Attribute { public AttributeUsageAttribute(AttributeTargets validOn) => throw null!; public bool AllowMultiple { get; set; } } public enum AttributeTargets { Assembly = 1, Module = 2, Class = 4, Struct = 8, Enum = 16, Constructor = 32, Method = 64, Property = 128, Field = 256, Event = 512, Interface = 1024, Parameter = 2048, Delegate = 4096, ReturnValue = 8192, GenericParameter = 16384, All = 32767 } public class ObsoleteAttribute : Attribute { public ObsoleteAttribute(string message) => throw null!; } }"; var comp = CreateEmptyCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,22): warning CS8602: Dereference of a possibly null reference. // _value = _f.GetHashCode(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "_f").WithLocation(16, 22) ); } [Fact] public void Pointer() { var source = @"class C { static unsafe void F(int* p) { *p = 0; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(TestOptions.UnsafeReleaseDll)); comp.VerifyDiagnostics(); } [Fact] public void TaskMethodReturningNull() { var source = @"using System.Threading.Tasks; class C { static Task F0() => null; static Task<string> F1() => null; static Task<string?> F2() { return null; } static Task<T> F3<T>() { return default; } static Task<T> F4<T>() { return default(Task<T>); } static Task<T> F5<T>() where T : class { return null; } static Task<T?> F6<T>() where T : class => null; static Task? G0() => null; static Task<string>? G1() => null; static Task<T>? G3<T>() { return default; } static Task<T?>? G6<T>() where T : class => null; }"; var comp = CreateCompilationWithMscorlib46(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,25): warning CS8603: Possible null reference return. // static Task F0() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(4, 25), // (5,33): warning CS8603: Possible null reference return. // static Task<string> F1() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(5, 33), // (6,40): warning CS8603: Possible null reference return. // static Task<string?> F2() { return null; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 40), // (7,37): warning CS8603: Possible null reference return. // static Task<T> F3<T>() { return default; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(7, 37), // (8,37): warning CS8603: Possible null reference return. // static Task<T> F4<T>() { return default(Task<T>); } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(Task<T>)").WithLocation(8, 37), // (9,53): warning CS8603: Possible null reference return. // static Task<T> F5<T>() where T : class { return null; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(9, 53), // (10,48): warning CS8603: Possible null reference return. // static Task<T?> F6<T>() where T : class => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(10, 48)); } // https://github.com/dotnet/roslyn/issues/29957: Should not report WRN_NullReferenceReturn for F0. [WorkItem(23275, "https://github.com/dotnet/roslyn/issues/23275")] [WorkItem(29957, "https://github.com/dotnet/roslyn/issues/29957")] [Fact] public void AsyncTaskMethodReturningNull() { var source = @"#pragma warning disable 1998 using System.Threading.Tasks; class C { static async Task F0() { return null; } static async Task<string> F1() => null; static async Task<string?> F2() { return null; } static async Task<T> F3<T>() { return default; } static async Task<T> F4<T>() { return default(T); } static async Task<T> F5<T>() where T : class { return null; } static async Task<T?> F6<T>() where T : class => null; static async Task? G0() { return null; } static async Task<string>? G1() => null; static async Task<T>? G3<T>() { return default; } static async Task<T?>? G6<T>() where T : class => null; }"; var comp = CreateCompilationWithMscorlib46(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,30): error CS1997: Since 'C.F0()' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'? // static async Task F0() { return null; } Diagnostic(ErrorCode.ERR_TaskRetNoObjectRequired, "return").WithArguments("C.F0()").WithLocation(5, 30), // (6,39): warning CS8603: Possible null reference return. // static async Task<string> F1() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(6, 39), // (8,43): warning CS8603: Possible null reference return. // static async Task<T> F3<T>() { return default; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(8, 43), // (9,43): warning CS8603: Possible null reference return. // static async Task<T> F4<T>() { return default(T); } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(9, 43), // (10,59): warning CS8603: Possible null reference return. // static async Task<T> F5<T>() where T : class { return null; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(10, 59), // (12,31): error CS1997: Since 'C.G0()' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'? // static async Task? G0() { return null; } Diagnostic(ErrorCode.ERR_TaskRetNoObjectRequired, "return").WithArguments("C.G0()").WithLocation(12, 31), // (13,40): warning CS8603: Possible null reference return. // static async Task<string>? G1() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(13, 40), // (14,44): warning CS8603: Possible null reference return. // static async Task<T>? G3<T>() { return default; } Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(14, 44)); } [Fact] public void IncrementWithErrors() { var source = @"using System.Threading.Tasks; class C { static async Task<int> F(ref int i) { return await Task.Run(() => i++); } }"; var comp = CreateCompilationWithMscorlib46(source); comp.VerifyDiagnostics( // (4,38): error CS1988: Async methods cannot have ref or out parameters // static async Task<int> F(ref int i) Diagnostic(ErrorCode.ERR_BadAsyncArgType, "i").WithLocation(4, 38), // (6,37): error CS1628: Cannot use ref or out parameter 'i' inside an anonymous method, lambda expression, or query expression // return await Task.Run(() => i++); Diagnostic(ErrorCode.ERR_AnonDelegateCantUse, "i").WithArguments("i").WithLocation(6, 37)); } [Fact] public void NullCastToValueType() { var source = @"struct S { } class C { static void M() { S s = (S)null; s.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,15): error CS0037: Cannot convert null to 'S' because it is a non-nullable value type // S s = (S)null; Diagnostic(ErrorCode.ERR_ValueCantBeNull, "(S)null").WithArguments("S").WithLocation(6, 15)); } [Fact] public void NullCastToUnannotatableReferenceTypedTypeParameter() { var source = @"struct S { } class C { static T M1<T>() where T: class? { return (T)null; // 1 } static T M2<T>() where T: C? { return (T)null; // 2 } static T M3<T>() where T: class? { return null; // 3 } static T M4<T>() where T: C? { return null; // 4 } static T M5<T>() where T: class? { return (T)null!; } static T M6<T>() where T: C? { return (T)null!; } static T M7<T>() where T: class? { return null!; } static T M8<T>() where T: C? { return null!; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,16): warning CS8603: Possible null reference return. // return (T)null; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)null").WithLocation(6, 16), // (10,16): warning CS8603: Possible null reference return. // return (T)null; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)null").WithLocation(10, 16), // (14,16): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(14, 16), // (18,16): warning CS8603: Possible null reference return. // return null; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(18, 16)); } [Fact] public void LiftedUserDefinedConversion() { var source = @"#pragma warning disable 0649 struct A<T> { public static implicit operator B<T>(A<T> a) => new B<T>(); } struct B<T> { internal T F; } class C { static void F(A<object>? x, A<object?>? y) { B<object>? z = x; z?.F.ToString(); B<object?>? w = y; w?.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,11): warning CS8602: Dereference of a possibly null reference. // w?.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, ".F").WithLocation(17, 11)); } [Fact] public void LiftedBinaryOperator() { var source = @"struct A<T> { public static A<T> operator +(A<T> a1, A<T> a2) => throw null!; } class C2 { static void F(A<object>? x, A<object>? y) { var sum1 = (x + y)/*T:A<object!>?*/; sum1.ToString(); if (x == null || y == null) return; var sum2 = (x + y)/*T:A<object!>?*/; sum2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void GroupBy() { var source = @"using System.Linq; class Program { static void Main() { var items = from i in Enumerable.Range(0, 3) group (long)i by i; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } // Tests for NullableWalker.HasImplicitTypeArguments. [Fact] public void ExplicitTypeArguments() { var source = @"interface I<T> { } class C { C P => throw new System.Exception(); I<T> F<T>(T t) { throw new System.Exception(); } static void M(C c) { c.P.F<object>(string.Empty); (new[]{ c })[0].F<object>(string.Empty); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void MultipleConversions_01() { var source = @"class A { public static implicit operator C(A a) => new C(); } class B : A { } class C { static void F(B? x, B y) { C c; c = x; // (ImplicitUserDefined)(ImplicitReference) c = y; // (ImplicitUserDefined)(ImplicitReference) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8604: Possible null reference argument for parameter 'a' in 'A.implicit operator C(A a)'. // c = x; // (ImplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("a", "A.implicit operator C(A a)").WithLocation(13, 13)); } [Fact] public void MultipleConversions_02() { var source = @"class A { } class B : A { } class C { public static implicit operator B?(C c) => null; static void F(C c) { A a = c; // (ImplicitReference)(ImplicitUserDefined) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // A a = c; // (ImplicitReference)(ImplicitUserDefined) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c").WithLocation(12, 15)); } [Fact] public void MultipleConversions_03() { var source = @"struct S<T> { public static implicit operator S<T>(T t) => default; static void M() { S<object> s = true; // (ImplicitUserDefined)(Boxing) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void MultipleConversions_04() { var source = @"struct S<T> { public static implicit operator T(S<T> s) => throw new System.Exception(); static void M() { bool b = new S<object>(); // (Unboxing)(ExplicitUserDefined) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): error CS0266: Cannot implicitly convert type 'S<object>' to 'bool'. An explicit conversion exists (are you missing a cast?) // bool b = new S<object>(); // (Unboxing)(ExplicitUserDefined) Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "new S<object>()").WithArguments("S<object>", "bool").WithLocation(6, 18)); } [Fact] public void MultipleConversions_Explicit_01() { var source = @"class A { public static explicit operator C(A a) => new C(); } class B : A { } class C { static void F1(B b1) { C? c; c = (C)b1; // (ExplicitUserDefined)(ImplicitReference) c = (C?)b1; // (ExplicitUserDefined)(ImplicitReference) } static void F2(bool flag, B? b2) { C? c; if (flag) c = (C)b2; // (ExplicitUserDefined)(ImplicitReference) if (flag) c = (C?)b2; // (ExplicitUserDefined)(ImplicitReference) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,26): warning CS8604: Possible null reference argument for parameter 'a' in 'A.explicit operator C(A a)'. // if (flag) c = (C)b2; // (ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b2").WithArguments("a", "A.explicit operator C(A a)").WithLocation(19, 26), // (20,27): warning CS8604: Possible null reference argument for parameter 'a' in 'A.explicit operator C(A a)'. // if (flag) c = (C?)b2; // (ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b2").WithArguments("a", "A.explicit operator C(A a)").WithLocation(20, 27)); } [Fact] public void MultipleConversions_Explicit_02() { var source = @"class A { public static explicit operator C?(A? a) => new D(); } class B : A { } class C { } class D : C { } class P { static void F1(A a1, B b1) { C? c; c = (C)a1; // (ExplicitUserDefined) c = (C?)a1; // (ExplicitUserDefined) c = (C)b1; // (ExplicitUserDefined)(ImplicitReference) c = (C?)b1; // (ExplicitUserDefined)(ImplicitReference) c = (C)(B)a1; c = (C)(B?)a1; c = (C?)(B)a1; c = (C?)(B?)a1; D? d; d = (D)a1; // (ExplicitReference)(ExplicitUserDefined) d = (D?)a1; // (ExplicitReference)(ExplicitUserDefined) d = (D)b1; // (ExplicitReference)(ExplicitUserDefined)(ImplicitReference) d = (D?)b1; // (ExplicitReference)(ExplicitUserDefined)(ImplicitReference) } static void F2(A? a2, B? b2) { C? c; c = (C)a2; // (ExplicitUserDefined) c = (C?)a2; // (ExplicitUserDefined) c = (C)b2; // (ExplicitUserDefined)(ImplicitReference) c = (C?)b2; // (ExplicitUserDefined)(ImplicitReference) D? d; d = (D)a2; // (ExplicitReference)(ExplicitUserDefined) d = (D?)a2; // (ExplicitReference)(ExplicitUserDefined) d = (D)b2; // (ExplicitReference)(ExplicitUserDefined)(ImplicitReference) d = (D?)b2; // (ExplicitReference)(ExplicitUserDefined)(ImplicitReference) d = (D)(A)b2; d = (D)(A?)b2; d = (D?)(A)b2; d = (D?)(A?)b2; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = (C)a1; // (ExplicitUserDefined) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)a1").WithLocation(13, 13), // (15,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = (C)b1; // (ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)b1").WithLocation(15, 13), // (17,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = (C)(B)a1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)(B)a1").WithLocation(17, 13), // (18,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = (C)(B?)a1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)(B?)a1").WithLocation(18, 13), // (22,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)a1; // (ExplicitReference)(ExplicitUserDefined) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(D)a1").WithLocation(22, 13), // (24,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)b1; // (ExplicitReference)(ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(D)b1").WithLocation(24, 13), // (30,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = (C)a2; // (ExplicitUserDefined) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)a2").WithLocation(30, 13), // (32,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // c = (C)b2; // (ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)b2").WithLocation(32, 13), // (35,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)a2; // (ExplicitReference)(ExplicitUserDefined) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(D)a2").WithLocation(35, 13), // (37,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)b2; // (ExplicitReference)(ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(D)b2").WithLocation(37, 13), // (39,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)(A)b2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(A)b2").WithLocation(39, 16), // (39,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)(A)b2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(D)(A)b2").WithLocation(39, 13), // (40,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D)(A?)b2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(D)(A?)b2").WithLocation(40, 13), // (41,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // d = (D?)(A)b2; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(A)b2").WithLocation(41, 17)); } [Fact] public void MultipleConversions_Explicit_03() { var source = @"class A { public static explicit operator S(A a) => new S(); } class B : A { } struct S { } class C { static void F(bool flag, B? b) { S? s; if (flag) s = (S)b; // (ExplicitUserDefined)(ImplicitReference) if (flag) s = (S?)b; // (ImplicitNullable)(ExplicitUserDefined)(ImplicitReference) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,26): warning CS8604: Possible null reference argument for parameter 'a' in 'A.explicit operator S(A a)'. // if (flag) s = (S)b; // (ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b").WithArguments("a", "A.explicit operator S(A a)").WithLocation(12, 26), // (13,27): warning CS8604: Possible null reference argument for parameter 'a' in 'A.explicit operator S(A a)'. // if (flag) s = (S?)b; // (ImplicitNullable)(ExplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b").WithArguments("a", "A.explicit operator S(A a)").WithLocation(13, 27)); } [Fact] [WorkItem(29960, "https://github.com/dotnet/roslyn/issues/29960")] public void MultipleConversions_Explicit_04() { var source = @"struct S { public static explicit operator A?(S s) => throw null!; } class A { internal void F() { } } class B : A { } class C { static void F(S s) { var b1 = (B)s; b1.F(); B b2 = (B)s; b2.F(); A a = (B)s; a.F(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29960: Should only report one WRN_ConvertingNullableToNonNullable // warning for `B b2 = (B)s;` and `A a = (B)s;`. comp.VerifyDiagnostics( // (16,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // var b1 = (B)s; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)s").WithLocation(16, 18), // (17,9): warning CS8602: Dereference of a possibly null reference. // b1.F(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1").WithLocation(17, 9), // (18,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // B b2 = (B)s; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)s").WithLocation(18, 16), // (19,9): warning CS8602: Dereference of a possibly null reference. // b2.F(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b2").WithLocation(19, 9), // (20,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // A a = (B)s; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)s").WithLocation(20, 15), // (20,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // A a = (B)s; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)s").WithLocation(20, 15), // (21,9): warning CS8602: Dereference of a possibly null reference. // a.F(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(21, 9)); } [Fact] [WorkItem(29699, "https://github.com/dotnet/roslyn/issues/29699")] public void MultipleTupleConversions_01() { var source = @"class A { public static implicit operator C(A a) => new C(); } class B : A { } class C { static void F((B?, B) x, (B, B?) y, (B, B) z) { (C, C?) c; c = x; // (ImplicitTuple)(ImplicitUserDefined)(ImplicitReference) c = y; // (ImplicitTuple)(ImplicitUserDefined)(ImplicitReference) c = z; // (ImplicitTuple)(ImplicitUserDefined)(ImplicitReference) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8604: Possible null reference argument for parameter 'a' in 'A.implicit operator C(A a)'. // c = x; // (ImplicitTuple)(ImplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("a", "A.implicit operator C(A a)").WithLocation(13, 13), // (13,13): warning CS8619: Nullability of reference types in value of type '(B?, B)' doesn't match target type '(C, C?)'. // c = x; // (ImplicitTuple)(ImplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("(B?, B)", "(C, C?)").WithLocation(13, 13), // (14,13): warning CS8604: Possible null reference argument for parameter 'a' in 'A.implicit operator C(A a)'. // c = y; // (ImplicitTuple)(ImplicitUserDefined)(ImplicitReference) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("a", "A.implicit operator C(A a)").WithLocation(14, 13)); } [Fact] public void MultipleTupleConversions_02() { var source = @"class A { } class B : A { } class C { public static implicit operator B(C c) => new C(); static void F(C? x, C y) { (A, A?) t = (x, y); // (ImplicitTuple)(ImplicitReference)(ImplicitUserDefined) } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,17): warning CS0219: The variable 't' is assigned but its value is never used // (A, A?) t = (x, y); // (ImplicitTuple)(ImplicitReference)(ImplicitUserDefined) Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "t").WithArguments("t").WithLocation(12, 17), // (12,22): warning CS8604: Possible null reference argument for parameter 'c' in 'C.implicit operator B(C c)'. // (A, A?) t = (x, y); // (ImplicitTuple)(ImplicitReference)(ImplicitUserDefined) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("c", "C.implicit operator B(C c)").WithLocation(12, 22)); } [Fact] [WorkItem(29966, "https://github.com/dotnet/roslyn/issues/29966")] public void Conversions_ImplicitTupleLiteral_01() { var source = @"#pragma warning disable 0219 interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class A<T> : I<T> { } class B<T> : IIn<T> { } class C<T> : IOut<T> { } static class E { static void F1(string x, string? y) { (string, string) t1 = (x, y); // 1 (string?, string?) u1 = (x, y); (object, object) v1 = (x, y); // 2 (object?, object?) w1 = (x, y); F1A((x, y)); // 3 F1B((x, y)); F1C((x, y)); // 4 F1D((x, y)); } static void F1A((string, string) t) { } static void F1B((string?, string?) t) { } static void F1C((object, object) t) { } static void F1D((object?, object?) t) { } static void F2(A<object> x, A<object?> y) { (A<object>, A<object>) t2 = (x, y); // 5 (A<object?>, A<object?>) u2 = (x, y); // 6 (I<object>, I<object>) v2 = (x, y); // 7 (I<object?>, I<object?>) w2 = (x, y); // 8 F2A((x, y)); // 9 F2B((x, y)); // 10 F2C((x, y)); // 11 F2D((x, y)); // 12 } static void F2A((A<object>, A<object>) t) { } static void F2B((A<object?>, A<object?>) t) { } static void F2C((I<object>, I<object>) t) { } static void F2D((I<object?>, I<object?>) t) { } static void F3(B<object> x, B<object?> y) { (B<object>, B<object>) t3 = (x, y); // 13 (B<object?>, B<object?>) u3 = (x, y); // 14 (IIn<object>, IIn<object>) v3 = (x, y); (IIn<object?>, IIn<object?>) w3 = (x, y); // 15 F3A((x, y)); F3B((x, y)); // 16 } static void F3A((IIn<object>, IIn<object>) t) { } static void F3B((IIn<object?>, IIn<object?>) t) { } static void F4(C<object> x, C<object?> y) { (C<object>, C<object>) t4 = (x, y); // 17 (C<object?>, C<object?>) u4 = (x, y); // 18 (IOut<object>, IOut<object>) v4 = (x, y); // 19 (IOut<object?>, IOut<object?>) w4 = (x, y); F4A((x, y)); // 20 F4B((x, y)); } static void F4A((IOut<object>, IOut<object>) t) { } static void F4B((IOut<object?>, IOut<object?>) t) { } static void F5<T, U>(U u) where U : T { (T, T) t5 = (u, default(T)); // 21 (object, object) v5 = (default(T), u); // 22 (object?, object?) w5 = (default(T), u); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29966: Report WRN_NullabilityMismatchInArgument rather than ...Assignment. comp.VerifyDiagnostics( // (12,31): warning CS8619: Nullability of reference types in value of type '(string x, string? y)' doesn't match target type '(string, string)'. // (string, string) t1 = (x, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(string x, string? y)", "(string, string)").WithLocation(12, 31), // (14,31): warning CS8619: Nullability of reference types in value of type '(object x, object? y)' doesn't match target type '(object, object)'. // (object, object) v1 = (x, y); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(object x, object? y)", "(object, object)").WithLocation(14, 31), // (16,13): warning CS8620: Argument of type '(string x, string? y)' cannot be used for parameter 't' of type '(string, string)' in 'void E.F1A((string, string) t)' due to differences in the nullability of reference types. // F1A((x, y)); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(string x, string? y)", "(string, string)", "t", "void E.F1A((string, string) t)").WithLocation(16, 13), // (18,13): warning CS8620: Argument of type '(object x, object? y)' cannot be used for parameter 't' of type '(object, object)' in 'void E.F1C((object, object) t)' due to differences in the nullability of reference types. // F1C((x, y)); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(object x, object? y)", "(object, object)", "t", "void E.F1C((object, object) t)").WithLocation(18, 13), // (27,37): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?> y)' doesn't match target type '(A<object>, A<object>)'. // (A<object>, A<object>) t2 = (x, y); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object>, A<object>)").WithLocation(27, 37), // (28,39): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?> y)' doesn't match target type '(A<object?>, A<object?>)'. // (A<object?>, A<object?>) u2 = (x, y); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object?>, A<object?>)").WithLocation(28, 39), // (29,41): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'I<object>'. // (I<object>, I<object>) v2 = (x, y); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object?>", "I<object>").WithLocation(29, 41), // (30,40): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'I<object?>'. // (I<object?>, I<object?>) w2 = (x, y); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "I<object?>").WithLocation(30, 40), // (31,13): warning CS8620: Argument of type '(A<object> x, A<object?> y)' cannot be used for parameter 't' of type '(A<object>, A<object>)' in 'void E.F2A((A<object>, A<object>) t)' due to differences in the nullability of reference types. // F2A((x, y)); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object>, A<object>)", "t", "void E.F2A((A<object>, A<object>) t)").WithLocation(31, 13), // (32,13): warning CS8620: Argument of type '(A<object> x, A<object?> y)' cannot be used for parameter 't' of type '(A<object?>, A<object?>)' in 'void E.F2B((A<object?>, A<object?>) t)' due to differences in the nullability of reference types. // F2B((x, y)); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object?>, A<object?>)", "t", "void E.F2B((A<object?>, A<object?>) t)").WithLocation(32, 13), // (33,17): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'I<object>'. // F2C((x, y)); // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object?>", "I<object>").WithLocation(33, 17), // (34,14): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'I<object?>'. // F2D((x, y)); // 12 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "I<object?>").WithLocation(34, 14), // (42,37): warning CS8619: Nullability of reference types in value of type '(B<object> x, B<object?> y)' doesn't match target type '(B<object>, B<object>)'. // (B<object>, B<object>) t3 = (x, y); // 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(B<object> x, B<object?> y)", "(B<object>, B<object>)").WithLocation(42, 37), // (43,39): warning CS8619: Nullability of reference types in value of type '(B<object> x, B<object?> y)' doesn't match target type '(B<object?>, B<object?>)'. // (B<object?>, B<object?>) u3 = (x, y); // 14 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(B<object> x, B<object?> y)", "(B<object?>, B<object?>)").WithLocation(43, 39), // (45,44): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'IIn<object?>'. // (IIn<object?>, IIn<object?>) w3 = (x, y); // 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object>", "IIn<object?>").WithLocation(45, 44), // (47,14): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'IIn<object?>'. // F3B((x, y)); // 16 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object>", "IIn<object?>").WithLocation(47, 14), // (53,37): warning CS8619: Nullability of reference types in value of type '(C<object> x, C<object?> y)' doesn't match target type '(C<object>, C<object>)'. // (C<object>, C<object>) t4 = (x, y); // 17 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(C<object> x, C<object?> y)", "(C<object>, C<object>)").WithLocation(53, 37), // (54,39): warning CS8619: Nullability of reference types in value of type '(C<object> x, C<object?> y)' doesn't match target type '(C<object?>, C<object?>)'. // (C<object?>, C<object?>) u4 = (x, y); // 18 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(C<object> x, C<object?> y)", "(C<object?>, C<object?>)").WithLocation(54, 39), // (55,47): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'IOut<object>'. // (IOut<object>, IOut<object>) v4 = (x, y); // 19 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "IOut<object>").WithLocation(55, 47), // (57,17): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'IOut<object>'. // F4A((x, y)); // 20 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "IOut<object>").WithLocation(57, 17), // (64,22): warning CS8619: Nullability of reference types in value of type '(T u, T?)' doesn't match target type '(T, T)'. // (T, T) t5 = (u, default(T)); // 21 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(u, default(T))").WithArguments("(T u, T?)", "(T, T)").WithLocation(64, 22), // (65,31): warning CS8619: Nullability of reference types in value of type '(object?, object? u)' doesn't match target type '(object, object)'. // (object, object) v5 = (default(T), u); // 22 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default(T), u)").WithArguments("(object?, object? u)", "(object, object)").WithLocation(65, 31)); } [Fact] public void Conversions_ImplicitTupleLiteral_02() { var source = @"#pragma warning disable 0219 interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class A<T> : I<T> { } class B<T> : IIn<T> { } class C<T> : IOut<T> { } static class E { static void F1(string x, string? y) { (string, string)? t1 = (x, y); // 1 (string?, string?)? u1 = (x, y); (object, object)? v1 = (x, y); // 2 (object?, object?)? w1 = (x, y); } static void F2(A<object> x, A<object?> y) { (A<object>, A<object>)? t2 = (x, y); // 3 (A<object?>, A<object?>)? u2 = (x, y); // 4 (I<object>, I<object>)? v2 = (x, y); // 5 (I<object?>, I<object?>)? w2 = (x, y); // 6 } static void F3(B<object> x, B<object?> y) { (IIn<object>, IIn<object>)? v3 = (x, y); (IIn<object?>, IIn<object?>)? w3 = (x, y); // 7 } static void F4(C<object> x, C<object?> y) { (IOut<object>, IOut<object>)? v4 = (x, y); // 8 (IOut<object?>, IOut<object?>)? w4 = (x, y); } static void F5<T, U>(U u) where U : T { (T, T)? t5 = (u, default(T)); // 9 (object, object)? v5 = (default(T), u); // 10 (object?, object?)? w5 = (default(T), u); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,32): warning CS8619: Nullability of reference types in value of type '(string x, string? y)' doesn't match target type '(string, string)?'. // (string, string)? t1 = (x, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(string x, string? y)", "(string, string)?").WithLocation(12, 32), // (14,32): warning CS8619: Nullability of reference types in value of type '(object x, object? y)' doesn't match target type '(object, object)?'. // (object, object)? v1 = (x, y); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(object x, object? y)", "(object, object)?").WithLocation(14, 32), // (19,38): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?> y)' doesn't match target type '(A<object>, A<object>)?'. // (A<object>, A<object>)? t2 = (x, y); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object>, A<object>)?").WithLocation(19, 38), // (20,40): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?> y)' doesn't match target type '(A<object?>, A<object?>)?'. // (A<object?>, A<object?>)? u2 = (x, y); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object?>, A<object?>)?").WithLocation(20, 40), // (21,42): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'I<object>'. // (I<object>, I<object>)? v2 = (x, y); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object?>", "I<object>").WithLocation(21, 42), // (22,41): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'I<object?>'. // (I<object?>, I<object?>)? w2 = (x, y); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "I<object?>").WithLocation(22, 41), // (27,45): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'IIn<object?>'. // (IIn<object?>, IIn<object?>)? w3 = (x, y); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object>", "IIn<object?>").WithLocation(27, 45), // (31,48): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'IOut<object>'. // (IOut<object>, IOut<object>)? v4 = (x, y); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "IOut<object>").WithLocation(31, 48), // (36,23): warning CS8619: Nullability of reference types in value of type '(T u, T?)' doesn't match target type '(T, T)?'. // (T, T)? t5 = (u, default(T)); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(u, default(T))").WithArguments("(T u, T?)", "(T, T)?").WithLocation(36, 23), // (37,32): warning CS8619: Nullability of reference types in value of type '(object?, object? u)' doesn't match target type '(object, object)?'. // (object, object)? v5 = (default(T), u); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default(T), u)").WithArguments("(object?, object? u)", "(object, object)?").WithLocation(37, 32)); } [Fact] public void Conversions_ImplicitTuple() { var source = @"#pragma warning disable 0219 interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class A<T> : I<T> { } class B<T> : IIn<T> { } class C<T> : IOut<T> { } class D { static void F1((string x, string?) a1) { (string, string) t1 = a1; // 1 (string?, string?) u1 = a1; (object, object) v1 = a1; // 2 (object?, object?) w1 = a1; } static void F2((A<object> x, A<object?>) a2) { (A<object>, A<object>) t2 = a2; // 3 (A<object?>, A<object?>) u2 = a2; // 4 (I<object>, I<object>) v2 = a2; // 5 (I<object?>, I<object?>) w2 = a2; // 6 } static void F3((B<object> x, B<object?>) a3) { (IIn<object>, IIn<object>) v3 = a3; (IIn<object?>, IIn<object?>) w3 = a3; // 7 } static void F4((C<object> x, C<object?>) a4) { (IOut<object>, IOut<object>) v4 = a4; // 8 (IOut<object?>, IOut<object?>) w4 = a4; } static void F5<T, U>((U, U) a5) where U : T { (U, T) t5 = a5; (object, object) v5 = a5; // 9 (object?, object?) w5 = a5; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,31): warning CS8619: Nullability of reference types in value of type '(string x, string?)' doesn't match target type '(string, string)'. // (string, string) t1 = a1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1").WithArguments("(string x, string?)", "(string, string)").WithLocation(12, 31), // (14,31): warning CS8619: Nullability of reference types in value of type '(string x, string?)' doesn't match target type '(object, object)'. // (object, object) v1 = a1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1").WithArguments("(string x, string?)", "(object, object)").WithLocation(14, 31), // (19,37): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(A<object>, A<object>)'. // (A<object>, A<object>) t2 = a2; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("(A<object> x, A<object?>)", "(A<object>, A<object>)").WithLocation(19, 37), // (20,39): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(A<object?>, A<object?>)'. // (A<object?>, A<object?>) u2 = a2; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("(A<object> x, A<object?>)", "(A<object?>, A<object?>)").WithLocation(20, 39), // (21,37): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(I<object>, I<object>)'. // (I<object>, I<object>) v2 = a2; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("(A<object> x, A<object?>)", "(I<object>, I<object>)").WithLocation(21, 37), // (22,39): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(I<object?>, I<object?>)'. // (I<object?>, I<object?>) w2 = a2; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("(A<object> x, A<object?>)", "(I<object?>, I<object?>)").WithLocation(22, 39), // (27,43): warning CS8619: Nullability of reference types in value of type '(B<object> x, B<object?>)' doesn't match target type '(IIn<object?>, IIn<object?>)'. // (IIn<object?>, IIn<object?>) w3 = a3; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a3").WithArguments("(B<object> x, B<object?>)", "(IIn<object?>, IIn<object?>)").WithLocation(27, 43), // (31,43): warning CS8619: Nullability of reference types in value of type '(C<object> x, C<object?>)' doesn't match target type '(IOut<object>, IOut<object>)'. // (IOut<object>, IOut<object>) v4 = a4; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a4").WithArguments("(C<object> x, C<object?>)", "(IOut<object>, IOut<object>)").WithLocation(31, 43), // (37,31): warning CS8619: Nullability of reference types in value of type '(U, U)' doesn't match target type '(object, object)'. // (object, object) v5 = a5; // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a5").WithArguments("(U, U)", "(object, object)").WithLocation(37, 31)); } [Fact] public void Conversions_ExplicitTupleLiteral_01() { var source = @"#pragma warning disable 0219 interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } sealed class A<T> : I<T> { } sealed class B<T> : IIn<T> { } sealed class C<T> : IOut<T> { } class D { static void F1(string x, string? y) { var t1 = ((string, string))(x, y); // 1 var u1 = ((string?, string?))(x, y); var v1 = ((object, object))(x, y); // 2 var w1 = ((object?, object?))(x, y); } static void F2(A<object> x, A<object?> y) { var t2 = ((A<object>, A<object>))(x, y); // 3 var u2 = ((A<object?>, A<object?>))(x, y); // 4 var v2 = ((I<object>, I<object>))(x, y); // 5 var w2 = ((I<object?>, I<object?>))(x, y); // 6 } static void F3(B<object> x, B<object?> y) { var v3 = ((IIn<object>, IIn<object>))(x, y); var w3 = ((IIn<object?>, IIn<object?>))(x, y); // 7 } static void F4(C<object> x, C<object?> y) { var v4 = ((IOut<object>, IOut<object>))(x, y); // 8 var w4 = ((IOut<object?>, IOut<object?>))(x, y); } static void F5<T, U>(T t) where U : T { var t5 = ((U, U))(t, default(T)); // 9 var v5 = ((object, object))(default(T), t); // 10 var w5 = ((object?, object?))(default(T), t); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,18): warning CS8619: Nullability of reference types in value of type '(string x, string? y)' doesn't match target type '(string, string)'. // var t1 = ((string, string))(x, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((string, string))(x, y)").WithArguments("(string x, string? y)", "(string, string)").WithLocation(12, 18), // (14,18): warning CS8619: Nullability of reference types in value of type '(object x, object? y)' doesn't match target type '(object, object)'. // var v1 = ((object, object))(x, y); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, object))(x, y)").WithArguments("(object x, object? y)", "(object, object)").WithLocation(14, 18), // (14,40): warning CS8600: Converting null literal or possible null value to non-nullable type. // var v1 = ((object, object))(x, y); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(14, 40), // (19,18): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?> y)' doesn't match target type '(A<object>, A<object>)'. // var t2 = ((A<object>, A<object>))(x, y); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((A<object>, A<object>))(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object>, A<object>)").WithLocation(19, 18), // (20,18): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?> y)' doesn't match target type '(A<object?>, A<object?>)'. // var u2 = ((A<object?>, A<object?>))(x, y); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((A<object?>, A<object?>))(x, y)").WithArguments("(A<object> x, A<object?> y)", "(A<object?>, A<object?>)").WithLocation(20, 18), // (21,46): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'I<object>'. // var v2 = ((I<object>, I<object>))(x, y); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object?>", "I<object>").WithLocation(21, 46), // (22,45): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'I<object?>'. // var w2 = ((I<object?>, I<object?>))(x, y); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "I<object?>").WithLocation(22, 45), // (27,49): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'IIn<object?>'. // var w3 = ((IIn<object?>, IIn<object?>))(x, y); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object>", "IIn<object?>").WithLocation(27, 49), // (31,52): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'IOut<object>'. // var v4 = ((IOut<object>, IOut<object>))(x, y); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "IOut<object>").WithLocation(31, 52), // (36,18): warning CS8619: Nullability of reference types in value of type '(U? t, U?)' doesn't match target type '(U, U)'. // var t5 = ((U, U))(t, default(T)); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((U, U))(t, default(T))").WithArguments("(U? t, U?)", "(U, U)").WithLocation(36, 18), // (37,18): warning CS8619: Nullability of reference types in value of type '(object?, object? t)' doesn't match target type '(object, object)'. // var v5 = ((object, object))(default(T), t); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, object))(default(T), t)").WithArguments("(object?, object? t)", "(object, object)").WithLocation(37, 18), // (37,37): warning CS8600: Converting null literal or possible null value to non-nullable type. // var v5 = ((object, object))(default(T), t); // 10 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(T)").WithLocation(37, 37), // (37,49): warning CS8600: Converting null literal or possible null value to non-nullable type. // var v5 = ((object, object))(default(T), t); // 10 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(37, 49)); } [Fact] public void Conversions_ExplicitTupleLiteral_02() { var source = @"#pragma warning disable 0219 interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } sealed class A<T> : I<T> { } sealed class B<T> : IIn<T> { } sealed class C<T> : IOut<T> { } class D { static void F1(string x, string? y) { var t1 = ((string, string)?)(x, y); // 1 var u1 = ((string?, string?)?)(x, y); var v1 = ((object, object)?)(x, y); // 2 var w1 = ((object?, object?)?)(x, y); } static void F2(A<object> x, A<object?> y) { var t2 = ((A<object>, A<object>)?)(x, y); // 3 var u2 = ((A<object?>, A<object?>)?)(x, y); // 4 var v2 = ((I<object>, I<object>)?)(x, y); // 5 var w2 = ((I<object?>, I<object?>)?)(x, y); // 6 } static void F3(B<object> x, B<object?> y) { var v3 = ((IIn<object>, IIn<object>)?)(x, y); var w3 = ((IIn<object?>, IIn<object?>)?)(x, y); // 7 } static void F4(C<object> x, C<object?> y) { var v4 = ((IOut<object>, IOut<object>)?)(x, y); // 8 var w4 = ((IOut<object?>, IOut<object?>)?)(x, y); } static void F5<T, U>(T t) where U : T { var t5 = ((U, U)?)(t, default(T)); // 9 var v5 = ((object, object)?)(default(T), t); // 10 var w5 = ((object?, object?)?)(default(T), t); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,18): warning CS8619: Nullability of reference types in value of type '(string x, string? y)' doesn't match target type '(string, string)?'. // var t1 = ((string, string)?)(x, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((string, string)?)(x, y)").WithArguments("(string x, string? y)", "(string, string)?").WithLocation(12, 18), // (12,41): warning CS8600: Converting null literal or possible null value to non-nullable type. // var t1 = ((string, string)?)(x, y); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(12, 41), // (14,18): warning CS8619: Nullability of reference types in value of type '(object x, object? y)' doesn't match target type '(object, object)?'. // var v1 = ((object, object)?)(x, y); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, object)?)(x, y)").WithArguments("(object x, object? y)", "(object, object)?").WithLocation(14, 18), // (14,41): warning CS8600: Converting null literal or possible null value to non-nullable type. // var v1 = ((object, object)?)(x, y); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(14, 41), // (19,47): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'A<object>'. // var t2 = ((A<object>, A<object>)?)(x, y); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object?>", "A<object>").WithLocation(19, 47), // (20,46): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'A<object?>'. // var u2 = ((A<object?>, A<object?>)?)(x, y); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "A<object?>").WithLocation(20, 46), // (21,47): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'I<object>'. // var v2 = ((I<object>, I<object>)?)(x, y); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object?>", "I<object>").WithLocation(21, 47), // (22,46): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'I<object?>'. // var w2 = ((I<object?>, I<object?>)?)(x, y); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("A<object>", "I<object?>").WithLocation(22, 46), // (27,50): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'IIn<object?>'. // var w3 = ((IIn<object?>, IIn<object?>)?)(x, y); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("B<object>", "IIn<object?>").WithLocation(27, 50), // (31,53): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'IOut<object>'. // var v4 = ((IOut<object>, IOut<object>)?)(x, y); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("C<object?>", "IOut<object>").WithLocation(31, 53), // (36,18): warning CS8619: Nullability of reference types in value of type '(U? t, U?)' doesn't match target type '(U, U)?'. // var t5 = ((U, U)?)(t, default(T)); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((U, U)?)(t, default(T))").WithArguments("(U? t, U?)", "(U, U)?").WithLocation(36, 18), // (37,18): warning CS8619: Nullability of reference types in value of type '(object?, object? t)' doesn't match target type '(object, object)?'. // var v5 = ((object, object)?)(default(T), t); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, object)?)(default(T), t)").WithArguments("(object?, object? t)", "(object, object)?").WithLocation(37, 18), // (37,38): warning CS8600: Converting null literal or possible null value to non-nullable type. // var v5 = ((object, object)?)(default(T), t); // 10 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(T)").WithLocation(37, 38), // (37,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // var v5 = ((object, object)?)(default(T), t); // 10 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(37, 50)); } [Fact] public void Conversions_ExplicitTuple() { var source = @"#pragma warning disable 0219 interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } sealed class A<T> : I<T> { } sealed class B<T> : IIn<T> { } sealed class C<T> : IOut<T> { } class D { static void F1((string x, string?) a1) { var t1 = ((string, string))a1; // 1 var u1 = ((string?, string?))a1; var v1 = ((object, object))a1; // 2 var w1 = ((object?, object?))a1; } static void F2((A<object> x, A<object?>) a2) { var t2 = ((A<object>, A<object>))a2; // 3 var u2 = ((A<object?>, A<object?>))a2; // 4 var v2 = ((I<object>, I<object>))a2; // 5 var w2 = ((I<object?>, I<object?>))a2; // 6 } static void F3((B<object> x, B<object?>) a3) { var v3 = ((IIn<object>, IIn<object>))a3; var w3 = ((IIn<object?>, IIn<object?>))a3; // 7 } static void F4((C<object> x, C<object?>) a4) { var v4 = ((IOut<object>, IOut<object>))a4; // 8 var w4 = ((IOut<object?>, IOut<object?>))a4; } static void F5<T, U>((T, T) a5) where U : T { var t5 = ((U, U))a5; var v5 = ((object, object))default((T, T)); // 9 var w5 = ((object?, object?))default((T, T)); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,18): warning CS8619: Nullability of reference types in value of type '(string x, string?)' doesn't match target type '(string, string)'. // var t1 = ((string, string))a1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((string, string))a1").WithArguments("(string x, string?)", "(string, string)").WithLocation(12, 18), // (14,18): warning CS8619: Nullability of reference types in value of type '(string x, string?)' doesn't match target type '(object, object)'. // var v1 = ((object, object))a1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, object))a1").WithArguments("(string x, string?)", "(object, object)").WithLocation(14, 18), // (19,18): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(A<object>, A<object>)'. // var t2 = ((A<object>, A<object>))a2; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((A<object>, A<object>))a2").WithArguments("(A<object> x, A<object?>)", "(A<object>, A<object>)").WithLocation(19, 18), // (20,18): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(A<object?>, A<object?>)'. // var u2 = ((A<object?>, A<object?>))a2; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((A<object?>, A<object?>))a2").WithArguments("(A<object> x, A<object?>)", "(A<object?>, A<object?>)").WithLocation(20, 18), // (21,18): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(I<object>, I<object>)'. // var v2 = ((I<object>, I<object>))a2; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((I<object>, I<object>))a2").WithArguments("(A<object> x, A<object?>)", "(I<object>, I<object>)").WithLocation(21, 18), // (22,18): warning CS8619: Nullability of reference types in value of type '(A<object> x, A<object?>)' doesn't match target type '(I<object?>, I<object?>)'. // var w2 = ((I<object?>, I<object?>))a2; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((I<object?>, I<object?>))a2").WithArguments("(A<object> x, A<object?>)", "(I<object?>, I<object?>)").WithLocation(22, 18), // (27,18): warning CS8619: Nullability of reference types in value of type '(B<object> x, B<object?>)' doesn't match target type '(IIn<object?>, IIn<object?>)'. // var w3 = ((IIn<object?>, IIn<object?>))a3; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((IIn<object?>, IIn<object?>))a3").WithArguments("(B<object> x, B<object?>)", "(IIn<object?>, IIn<object?>)").WithLocation(27, 18), // (31,18): warning CS8619: Nullability of reference types in value of type '(C<object> x, C<object?>)' doesn't match target type '(IOut<object>, IOut<object>)'. // var v4 = ((IOut<object>, IOut<object>))a4; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((IOut<object>, IOut<object>))a4").WithArguments("(C<object> x, C<object?>)", "(IOut<object>, IOut<object>)").WithLocation(31, 18), // (37,18): warning CS8619: Nullability of reference types in value of type '(T, T)' doesn't match target type '(object, object)'. // var v5 = ((object, object))default((T, T)); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, object))default((T, T))").WithArguments("(T, T)", "(object, object)").WithLocation(37, 18)); } [Fact] [WorkItem(29966, "https://github.com/dotnet/roslyn/issues/29966")] public void Conversions_ImplicitTupleLiteral_ExtensionThis() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class A<T> : I<T> { } class B<T> : IIn<T> { } class C<T> : IOut<T> { } static class E { static void F1(string x, string? y) { (x, y).F1A(); // 1 (x, y).F1B(); } static void F1A(this (object, object) t) { } static void F1B(this (object?, object?) t) { } static void F2(A<object> x, A<object?> y) { (x, y).F2A(); // 2 (x, y).F2B(); // 3 } static void F2A(this (I<object>, I<object>) t) { } static void F2B(this (I<object?>, I<object?>) t) { } static void F3(B<object> x, B<object?> y) { (x, y).F3A(); (x, y).F3B(); // 4 } static void F3A(this (IIn<object>, IIn<object>) t) { } static void F3B(this (IIn<object?>, IIn<object?>) t) { } static void F4(C<object> x, C<object?> y) { (x, y).F4A(); // 5 (x, y).F4B(); } static void F4A(this (IOut<object>, IOut<object>) t) { } static void F4B(this (IOut<object?>, IOut<object?>) t) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8620: Argument of type '(string x, string? y)' cannot be used for parameter 't' of type '(object, object)' in 'void E.F1A((object, object) t)' due to differences in the nullability of reference types. // (x, y).F1A(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(string x, string? y)", "(object, object)", "t", "void E.F1A((object, object) t)").WithLocation(11, 9), // (18,9): warning CS8620: Argument of type '(A<object> x, A<object?> y)' cannot be used for parameter 't' of type '(I<object>, I<object>)' in 'void E.F2A((I<object>, I<object>) t)' due to differences in the nullability of reference types. // (x, y).F2A(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(I<object>, I<object>)", "t", "void E.F2A((I<object>, I<object>) t)").WithLocation(18, 9), // (19,9): warning CS8620: Argument of type '(A<object> x, A<object?> y)' cannot be used for parameter 't' of type '(I<object?>, I<object?>)' in 'void E.F2B((I<object?>, I<object?>) t)' due to differences in the nullability of reference types. // (x, y).F2B(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(A<object> x, A<object?> y)", "(I<object?>, I<object?>)", "t", "void E.F2B((I<object?>, I<object?>) t)").WithLocation(19, 9), // (26,9): warning CS8620: Argument of type '(B<object> x, B<object?> y)' cannot be used for parameter 't' of type '(IIn<object?>, IIn<object?>)' in 'void E.F3B((IIn<object?>, IIn<object?>) t)' due to differences in the nullability of reference types. // (x, y).F3B(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(B<object> x, B<object?> y)", "(IIn<object?>, IIn<object?>)", "t", "void E.F3B((IIn<object?>, IIn<object?>) t)").WithLocation(26, 9), // (32,9): warning CS8620: Argument of type '(C<object> x, C<object?> y)' cannot be used for parameter 't' of type '(IOut<object>, IOut<object>)' in 'void E.F4A((IOut<object>, IOut<object>) t)' due to differences in the nullability of reference types. // (x, y).F4A(); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y)").WithArguments("(C<object> x, C<object?> y)", "(IOut<object>, IOut<object>)", "t", "void E.F4A((IOut<object>, IOut<object>) t)").WithLocation(32, 9)); } [Fact] public void Conversions_ImplicitTuple_ExtensionThis_01() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class A<T> : I<T> { } class B<T> : IIn<T> { } class C<T> : IOut<T> { } static class E { static void F1((string x, string?) t1) { t1.F1A(); // 1 t1.F1B(); } static void F1A(this (object, object) t) { } static void F1B(this (object?, object?) t) { } static void F2((A<object>, A<object?>) t2) { t2.F2A(); // 2 t2.F2B(); // 3 } static void F2A(this (I<object>, I<object>) t) { } static void F2B(this (I<object?>, I<object?>) t) { } static void F3((B<object>, B<object?>) t3) { t3.F3A(); t3.F3B(); // 4 } static void F3A(this (IIn<object>, IIn<object>) t) { } static void F3B(this (IIn<object?>, IIn<object?>) t) { } static void F4((C<object>, C<object?>) t4) { t4.F4A(); // 5 t4.F4B(); } static void F4A(this (IOut<object>, IOut<object>) t) { } static void F4B(this (IOut<object?>, IOut<object?>) t) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8620: Nullability of reference types in argument of type '(string x, string?)' doesn't match target type '(object, object)' for parameter 't' in 'void E.F1A((object, object) t)'. // t1.F1A(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t1").WithArguments("(string x, string?)", "(object, object)", "t", "void E.F1A((object, object) t)").WithLocation(11, 9), // (18,9): warning CS8620: Nullability of reference types in argument of type '(A<object>, A<object?>)' doesn't match target type '(I<object>, I<object>)' for parameter 't' in 'void E.F2A((I<object>, I<object>) t)'. // t2.F2A(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t2").WithArguments("(A<object>, A<object?>)", "(I<object>, I<object>)", "t", "void E.F2A((I<object>, I<object>) t)").WithLocation(18, 9), // (19,9): warning CS8620: Nullability of reference types in argument of type '(A<object>, A<object?>)' doesn't match target type '(I<object?>, I<object?>)' for parameter 't' in 'void E.F2B((I<object?>, I<object?>) t)'. // t2.F2B(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t2").WithArguments("(A<object>, A<object?>)", "(I<object?>, I<object?>)", "t", "void E.F2B((I<object?>, I<object?>) t)").WithLocation(19, 9), // (26,9): warning CS8620: Nullability of reference types in argument of type '(B<object>, B<object?>)' doesn't match target type '(IIn<object?>, IIn<object?>)' for parameter 't' in 'void E.F3B((IIn<object?>, IIn<object?>) t)'. // t3.F3B(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t3").WithArguments("(B<object>, B<object?>)", "(IIn<object?>, IIn<object?>)", "t", "void E.F3B((IIn<object?>, IIn<object?>) t)").WithLocation(26, 9), // (32,9): warning CS8620: Nullability of reference types in argument of type '(C<object>, C<object?>)' doesn't match target type '(IOut<object>, IOut<object>)' for parameter 't' in 'void E.F4A((IOut<object>, IOut<object>) t)'. // t4.F4A(); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t4").WithArguments("(C<object>, C<object?>)", "(IOut<object>, IOut<object>)", "t", "void E.F4A((IOut<object>, IOut<object>) t)").WithLocation(32, 9)); } [Fact] public void Conversions_ImplicitTuple_ExtensionThis_02() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } static class E { static void F1((string, string)? t1) { t1.F1A(); // 1 t1.F1B(); } static void F1A(this (string?, string?)? t) { } static void F1B(this (string, string)? t) { } static void F2((I<object?>, I<object?>)? t2) { t2.F2A(); t2.F2B(); // 2 } static void F2A(this (I<object?>, I<object?>)? t) { } static void F2B(this (I<object>, I<object>)? t) { } static void F3((IIn<object?>, IIn<object?>)? t3) { t3.F3A(); t3.F3B(); // 3 } static void F3A(this (IIn<object?>, IIn<object?>)? t) { } static void F3B(this (IIn<object>, IIn<object>)? t) { } static void F4((IOut<object?>, IOut<object?>)? t4) { t4.F4A(); t4.F4B(); // 4 } static void F4A(this (IOut<object?>, IOut<object?>)? t) { } static void F4B(this (IOut<object>, IOut<object>)? t) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8620: Nullability of reference types in argument of type '(string, string)?' doesn't match target type '(string?, string?)?' for parameter 't' in 'void E.F1A((string?, string?)? t)'. // t1.F1A(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t1").WithArguments("(string, string)?", "(string?, string?)?", "t", "void E.F1A((string?, string?)? t)").WithLocation(8, 9), // (16,9): warning CS8620: Nullability of reference types in argument of type '(I<object?>, I<object?>)?' doesn't match target type '(I<object>, I<object>)?' for parameter 't' in 'void E.F2B((I<object>, I<object>)? t)'. // t2.F2B(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t2").WithArguments("(I<object?>, I<object?>)?", "(I<object>, I<object>)?", "t", "void E.F2B((I<object>, I<object>)? t)").WithLocation(16, 9), // (23,9): warning CS8620: Nullability of reference types in argument of type '(IIn<object?>, IIn<object?>)?' doesn't match target type '(IIn<object>, IIn<object>)?' for parameter 't' in 'void E.F3B((IIn<object>, IIn<object>)? t)'. // t3.F3B(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t3").WithArguments("(IIn<object?>, IIn<object?>)?", "(IIn<object>, IIn<object>)?", "t", "void E.F3B((IIn<object>, IIn<object>)? t)").WithLocation(23, 9), // (30,9): warning CS8620: Nullability of reference types in argument of type '(IOut<object?>, IOut<object?>)?' doesn't match target type '(IOut<object>, IOut<object>)?' for parameter 't' in 'void E.F4B((IOut<object>, IOut<object>)? t)'. // t4.F4B(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t4").WithArguments("(IOut<object?>, IOut<object?>)?", "(IOut<object>, IOut<object>)?", "t", "void E.F4B((IOut<object>, IOut<object>)? t)").WithLocation(30, 9)); } [Fact] public void Conversions_ImplicitTuple_ExtensionThis_03() { var source = @"static class E { static void F((string, (string, string)?) t) { t.FA(); // 1 t.FB(); FA(t); FB(t); } static void FA(this (object, (string?, string?)?) t) { } static void FB(this (object, (string, string)?) t) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8620: Nullability of reference types in argument of type '(string, (string, string)?)' doesn't match target type '(object, (string?, string?)?)' for parameter 't' in 'void E.FA((object, (string?, string?)?) t)'. // t.FA(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t").WithArguments("(string, (string, string)?)", "(object, (string?, string?)?)", "t", "void E.FA((object, (string?, string?)?) t)").WithLocation(5, 9)); } [Fact] public void TupleTypeInference_01() { var source = @"class C { static (T, T) F<T>((T, T) t) => t; static void G(string x, string? y) { F((x, x)).Item2.ToString(); F((x, y)).Item2.ToString(); F((y, x)).Item2.ToString(); F((y, y)).Item2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F((x, y)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F((x, y)).Item2").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F((y, x)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F((y, x)).Item2").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F((y, y)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F((y, y)).Item2").WithLocation(9, 9)); } [Fact] public void TupleTypeInference_02() { var source = @"class C { static (T, T) F<T>((T, T?) t) where T : class => (t.Item1, t.Item1); static void G(string x, string? y) { F((x, x)).Item2.ToString(); F((x, y)).Item2.ToString(); F((y, x)).Item2.ToString(); F((y, y)).Item2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>((T, T?))'. Nullability of type argument 'string?' doesn't match 'class' constraint. // F((y, x)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>((T, T?))", "T", "string?").WithLocation(8, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F((y, x)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F((y, x)).Item2").WithLocation(8, 9), // (9,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>((T, T?))'. Nullability of type argument 'string?' doesn't match 'class' constraint. // F((y, y)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>((T, T?))", "T", "string?").WithLocation(9, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F((y, y)).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F((y, y)).Item2").WithLocation(9, 9)); } [Fact] public void TupleTypeInference_03() { var source = @"class C { static T F<T>((T, T?) t) where T : class => t.Item1; static void G((string, string) x, (string, string?) y, (string?, string) z, (string?, string?) w) { F(x).ToString(); F(y).ToString(); F(z).ToString(); F(w).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>((T, T?))'. Nullability of type argument 'string?' doesn't match 'class' constraint. // F(z).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>((T, T?))", "T", "string?").WithLocation(8, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F(z).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(z)").WithLocation(8, 9), // (9,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>((T, T?))'. Nullability of type argument 'string?' doesn't match 'class' constraint. // F(w).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>((T, T?))", "T", "string?").WithLocation(9, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F(w).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(w)").WithLocation(9, 9)); } [Fact] public void TupleTypeInference_04_Ref() { var source = @"class C { static T F<T>(ref (T, T?) t) where T : class => throw new System.Exception(); static void G(string x, string? y) { (string, string) t1 = (x, x); F(ref t1).ToString(); (string, string?) t2 = (x, y); F(ref t2).ToString(); (string?, string) t3 = (y, x); F(ref t3).ToString(); (string?, string?) t4 = (y, y); F(ref t4).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,15): warning CS8620: Argument of type '(string, string)' cannot be used as an input of type '(string, string?)' for parameter 't' in 'string C.F<string>(ref (string, string?) t)' due to differences in the nullability of reference types. // F(ref t1).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t1").WithArguments("(string, string)", "(string, string?)", "t", "string C.F<string>(ref (string, string?) t)").WithLocation(7, 15), // (11,15): warning CS8620: Argument of type '(string?, string)' cannot be used as an input of type '(string, string?)' for parameter 't' in 'string C.F<string>(ref (string, string?) t)' due to differences in the nullability of reference types. // F(ref t3).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t3").WithArguments("(string?, string)", "(string, string?)", "t", "string C.F<string>(ref (string, string?) t)").WithLocation(11, 15), // (13,15): warning CS8620: Argument of type '(string?, string?)' cannot be used as an input of type '(string, string?)' for parameter 't' in 'string C.F<string>(ref (string, string?) t)' due to differences in the nullability of reference types. // F(ref t4).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t4").WithArguments("(string?, string?)", "(string, string?)", "t", "string C.F<string>(ref (string, string?) t)").WithLocation(13, 15)); } [Fact] public void TupleTypeInference_04_Out() { var source = @"class C { static T F<T>(out (T, T?) t) where T : class => throw new System.Exception(); static void G() { F(out (string, string) t1).ToString(); F(out (string, string?) t2).ToString(); F(out (string?, string) t3).ToString(); F(out (string?, string?) t4).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,15): warning CS8624: Argument of type '(string, string)' cannot be used as an output of type '(string, string?)' for parameter 't' in 'string C.F<string>(out (string, string?) t)' due to differences in the nullability of reference types. // F(out (string, string) t1).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "(string, string) t1").WithArguments("(string, string)", "(string, string?)", "t", "string C.F<string>(out (string, string?) t)").WithLocation(6, 15), // (8,15): warning CS8624: Argument of type '(string?, string)' cannot be used as an output of type '(string, string?)' for parameter 't' in 'string C.F<string>(out (string, string?) t)' due to differences in the nullability of reference types. // F(out (string?, string) t3).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "(string?, string) t3").WithArguments("(string?, string)", "(string, string?)", "t", "string C.F<string>(out (string, string?) t)").WithLocation(8, 15), // (9,15): warning CS8624: Argument of type '(string?, string?)' cannot be used as an output of type '(string, string?)' for parameter 't' in 'string C.F<string>(out (string, string?) t)' due to differences in the nullability of reference types. // F(out (string?, string?) t4).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgumentForOutput, "(string?, string?) t4").WithArguments("(string?, string?)", "(string, string?)", "t", "string C.F<string>(out (string, string?) t)").WithLocation(9, 15)); } [Fact] public void TupleTypeInference_05() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>(I<(T, T?)> t) where T : class => throw new System.Exception(); static void G(I<(string, string)> x, I<(string, string?)> y, I<(string?, string)> z, I<(string?, string?)> w) { F(x).ToString(); F(y).ToString(); F(z).ToString(); F(w).ToString(); } static T F<T>(IIn<(T, T?)> t) where T : class => throw new System.Exception(); static void G(IIn<(string, string)> x, IIn<(string, string?)> y, IIn<(string?, string)> z, IIn<(string?, string?)> w) { F(x).ToString(); F(y).ToString(); F(z).ToString(); F(w).ToString(); } static T F<T>(IOut<(T, T?)> t) where T : class => throw new System.Exception(); static void G(IOut<(string, string)> x, IOut<(string, string?)> y, IOut<(string?, string)> z, IOut<(string?, string?)> w) { F(x).ToString(); F(y).ToString(); F(z).ToString(); F(w).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): warning CS8620: Nullability of reference types in argument of type 'I<(string, string)>' doesn't match target type 'I<(string, string?)>' for parameter 't' in 'string C.F<string>(I<(string, string?)> t)'. // F(x).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<(string, string)>", "I<(string, string?)>", "t", "string C.F<string>(I<(string, string?)> t)").WithLocation(9, 11), // (11,11): warning CS8620: Nullability of reference types in argument of type 'I<(string?, string)>' doesn't match target type 'I<(string, string?)>' for parameter 't' in 'string C.F<string>(I<(string, string?)> t)'. // F(z).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("I<(string?, string)>", "I<(string, string?)>", "t", "string C.F<string>(I<(string, string?)> t)").WithLocation(11, 11), // (12,11): warning CS8620: Nullability of reference types in argument of type 'I<(string?, string?)>' doesn't match target type 'I<(string, string?)>' for parameter 't' in 'string C.F<string>(I<(string, string?)> t)'. // F(w).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "w").WithArguments("I<(string?, string?)>", "I<(string, string?)>", "t", "string C.F<string>(I<(string, string?)> t)").WithLocation(12, 11), // (17,11): warning CS8620: Nullability of reference types in argument of type 'IIn<(string, string)>' doesn't match target type 'IIn<(string, string?)>' for parameter 't' in 'string C.F<string>(IIn<(string, string?)> t)'. // F(x).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("IIn<(string, string)>", "IIn<(string, string?)>", "t", "string C.F<string>(IIn<(string, string?)> t)").WithLocation(17, 11), // (19,11): warning CS8620: Nullability of reference types in argument of type 'IIn<(string?, string)>' doesn't match target type 'IIn<(string, string?)>' for parameter 't' in 'string C.F<string>(IIn<(string, string?)> t)'. // F(z).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IIn<(string?, string)>", "IIn<(string, string?)>", "t", "string C.F<string>(IIn<(string, string?)> t)").WithLocation(19, 11), // (20,11): warning CS8620: Nullability of reference types in argument of type 'IIn<(string?, string?)>' doesn't match target type 'IIn<(string, string?)>' for parameter 't' in 'string C.F<string>(IIn<(string, string?)> t)'. // F(w).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "w").WithArguments("IIn<(string?, string?)>", "IIn<(string, string?)>", "t", "string C.F<string>(IIn<(string, string?)> t)").WithLocation(20, 11), // (25,11): warning CS8620: Nullability of reference types in argument of type 'IOut<(string, string)>' doesn't match target type 'IOut<(string, string?)>' for parameter 't' in 'string C.F<string>(IOut<(string, string?)> t)'. // F(x).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("IOut<(string, string)>", "IOut<(string, string?)>", "t", "string C.F<string>(IOut<(string, string?)> t)").WithLocation(25, 11), // (27,11): warning CS8620: Nullability of reference types in argument of type 'IOut<(string?, string)>' doesn't match target type 'IOut<(string, string?)>' for parameter 't' in 'string C.F<string>(IOut<(string, string?)> t)'. // F(z).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IOut<(string?, string)>", "IOut<(string, string?)>", "t", "string C.F<string>(IOut<(string, string?)> t)").WithLocation(27, 11), // (28,11): warning CS8620: Nullability of reference types in argument of type 'IOut<(string?, string?)>' doesn't match target type 'IOut<(string, string?)>' for parameter 't' in 'string C.F<string>(IOut<(string, string?)> t)'. // F(w).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "w").WithArguments("IOut<(string?, string?)>", "IOut<(string, string?)>", "t", "string C.F<string>(IOut<(string, string?)> t)").WithLocation(28, 11) ); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void TupleTypeInference_06() { var source = @"class C { static void F(object? x, object? y) { if (y != null) { ((object? x, object? y), object? z) t = ((x, y), y); t.Item1.Item1.ToString(); t.Item1.Item2.ToString(); t.Item2.ToString(); t.Item1.x.ToString(); // warning already reported for t.Item1.Item1 t.Item1.y.ToString(); // warning already reported for t.Item1.Item2 t.z.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // t.Item1.Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1.Item1").WithLocation(8, 13)); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void TupleTypeInference_07() { var source = @"class C { static void F(object? x, object? y) { if (y != null) { (object? _1, object? _2, object? _3, object? _4, object? _5, object? _6, object? _7, object? _8, object? _9, object? _10) t = (null, null, null, null, null, null, null, x, null, y); t._7.ToString(); t._8.ToString(); t.Rest.Item1.ToString(); // warning already reported for t._8 t.Rest.Item2.ToString(); t._9.ToString(); // warning already reported for t.Rest.Item2 t._10.ToString(); t.Rest.Item3.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // t._7.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t._7").WithLocation(8, 13), // (9,13): warning CS8602: Dereference of a possibly null reference. // t._8.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t._8").WithLocation(9, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(11, 13)); } [Fact] [WorkItem(35157, "https://github.com/dotnet/roslyn/issues/35157")] public void TupleTypeInference_08() { var source = @" class C { void M() { _ = (null, 2); _ = (null, (2, 3)); _ = (null, (null, (2, 3))); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = (null, 2); Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(6, 9), // (7,9): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = (null, (2, 3)); Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(7, 9), // (8,9): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = (null, (null, (2, 3))); Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(8, 9) ); } [Fact] public void TupleTypeInference_09() { var source = @" using System; class C { C(long arg) {} void M() { int i = 0; Func<(C, C)> action = () => (new(i), new(i)); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_01() { var source = @"class Program { static void F() { (object? a, string) t = (default(object), default(string)) /*T:(object?, string?)*/; // 1 (object, string? b) u = t; // 2 _ = t/*T:(object? a, string!)*/; _ = u/*T:(object!, string? b)*/; t.Item1.ToString(); // 3 t.Item2.ToString(); // 4 u.Item1.ToString(); // 5 u.Item2.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,33): warning CS8619: Nullability of reference types in value of type '(object?, string?)' doesn't match target type '(object? a, string)'. // (object? a, string) t = (default(object), default(string)) /*T:(object?, string?)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default(object), default(string))").WithArguments("(object?, string?)", "(object? a, string)").WithLocation(5, 33), // (6,33): warning CS8619: Nullability of reference types in value of type '(object? a, string)' doesn't match target type '(object, string? b)'. // (object, string? b) u = t; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("(object? a, string)", "(object, string? b)").WithLocation(6, 33), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2").WithLocation(12, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_02() { var source = @"class Program { static void F(object? x, object y) { (object x, object? y, object? z) t = (null, x, y); // 1 _ = t/*T:(object! x, object? y, object? z)*/; t.x.ToString(); // 2 t.y.ToString(); // 3 t.z.ToString(); if (x == null) return; (object x, object y) u = (x, default(object))/*T:(object! x, object?)*/; // 4 _ = u/*T:(object! x, object! y)*/; u.x.ToString(); u.y.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (5,46): warning CS8619: Nullability of reference types in value of type '(object?, object? x, object y)' doesn't match target type '(object x, object? y, object? z)'. // (object x, object? y, object? z) t = (null, x, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, x, y)").WithArguments("(object?, object? x, object y)", "(object x, object? y, object? z)").WithLocation(5, 46), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.x").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.y").WithLocation(8, 9), // (11,34): warning CS8619: Nullability of reference types in value of type '(object x, object?)' doesn't match target type '(object x, object y)'. // (object x, object y) u = (x, default(object))/*T:(object! x, object?)*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, default(object))").WithArguments("(object x, object?)", "(object x, object y)").WithLocation(11, 34), // (14,9): warning CS8602: Dereference of a possibly null reference. // u.y.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.y").WithLocation(14, 9)); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_03() { var source = @"class A { internal object? F; } class B : A { } class Program { static void F1() { (A, A?) t1 = (null, new A() { F = 1 }); // 1 (A x, A? y) u1 = t1; u1.x.ToString(); // 2 u1.y.ToString(); u1.y.F.ToString(); } static void F2() { (A, A?) t2 = (null, new B() { F = 2 }); // 3 (A x, A? y) u2 = t2; u2.x.ToString(); // 4 u2.y.ToString(); u2.y.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,22): warning CS8619: Nullability of reference types in value of type '(A?, A)' doesn't match target type '(A, A?)'. // (A, A?) t1 = (null, new A() { F = 1 }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, new A() { F = 1 })").WithArguments("(A?, A)", "(A, A?)").WithLocation(12, 22), // (14,9): warning CS8602: Dereference of a possibly null reference. // u1.x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u1.x").WithLocation(14, 9), // (20,22): warning CS8619: Nullability of reference types in value of type '(A?, A)' doesn't match target type '(A, A?)'. // (A, A?) t2 = (null, new B() { F = 2 }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, new B() { F = 2 })").WithArguments("(A?, A)", "(A, A?)").WithLocation(20, 22), // (22,9): warning CS8602: Dereference of a possibly null reference. // u2.x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.x").WithLocation(22, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_04() { var source = @"class Program { static void F(object? x, string? y) { (object?, string) t = (x, y)/*T:(object? x, string? y)*/; // 1 (object, string?) u = t; // 2 t.Item1.ToString(); // 3 t.Item2.ToString(); // 4 u.Item1.ToString(); // 5 u.Item2.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,31): warning CS8619: Nullability of reference types in value of type '(object? x, string? y)' doesn't match target type '(object?, string)'. // (object?, string) t = (x, y)/*T:(object? x, string? y)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(object? x, string? y)", "(object?, string)").WithLocation(5, 31), // (6,31): warning CS8619: Nullability of reference types in value of type '(object?, string)' doesn't match target type '(object, string?)'. // (object, string?) u = t; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("(object?, string)", "(object, string?)").WithLocation(6, 31), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2").WithLocation(10, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_05() { var source = @"class Program { static void F(object x, string? y) { (object?, string) t = (x, y)/*T:(object! x, string? y)*/; // 1 (object a, string? b) u = t; // 2 t.Item1.ToString(); t.Item2.ToString(); // 3 u.Item1.ToString(); u.Item2.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,31): warning CS8619: Nullability of reference types in value of type '(object x, string? y)' doesn't match target type '(object?, string)'. // (object?, string) t = (x, y)/*T:(object! x, string? y)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(object x, string? y)", "(object?, string)").WithLocation(5, 31), // (6,35): warning CS8619: Nullability of reference types in value of type '(object?, string)' doesn't match target type '(object a, string? b)'. // (object a, string? b) u = t; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("(object?, string)", "(object a, string? b)").WithLocation(6, 35), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2").WithLocation(10, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_06() { var source = @"class Program { static void F(string x, string? y) { (object, string) t = ((object, string))(x, y)/*T:(string! x, string? y)*/; // 1 (object a, string?) u = ((string, string?))t; (object?, object b) v = ((object?, object))t; t.Item1.ToString(); t.Item2.ToString(); u.Item1.ToString(); u.Item2.ToString(); // 2 v.Item1.ToString(); // 3 v.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,30): warning CS8619: Nullability of reference types in value of type '(object x, string? y)' doesn't match target type '(object, string)'. // (object, string) t = ((object, string))(x, y)/*T:(string! x, string? y)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((object, string))(x, y)").WithArguments("(object x, string? y)", "(object, string)").WithLocation(5, 30), // (5,52): warning CS8600: Converting null literal or possible null value to non-nullable type. // (object, string) t = ((object, string))(x, y)/*T:(string! x, string? y)*/; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(5, 52), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // v.Item1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v.Item1").WithLocation(12, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_07() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C<T> { internal T F; } class Program { static void F<T>(C<T> x, C<T> y) { if (y.F == null) return; var t = (x, y); var u = t; t.Item1.F.ToString(); // 1 t.Item2.F.ToString(); u.Item1.F.ToString(); // 2 u.Item2.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1.F").WithLocation(14, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1.F").WithLocation(16, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_08() { var source = @"class Program { static void F(bool b, object x, object? y) { (object?, object, object?, object, object?, (object, object?), object, object, object?, object) t = (x, x, x, y, y, (y, x), x, x, y, y)/*T:(object!, object!, object!, object?, object?, (object? y, object! x), object!, object!, object?, object?)*/; // 1 t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 2 t.Item5.ToString(); // 3 t.Item6.Item1.ToString(); // 4 t.Item6.Item2.ToString(); t.Item7.ToString(); if (b) { t.Item8.ToString(); t.Item9.ToString(); // 5 t.Item10.ToString(); // 6 } else { t.Rest.Item1.ToString(); t.Rest.Item2.ToString(); // 7 t.Rest.Item3.ToString(); // 8 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8619: Nullability of reference types in value of type '(object, object, object, object?, object?, (object? y, object x), object, object, object?, object?)' doesn't match target type '(object?, object, object?, object, object?, (object, object?), object, object, object?, object)'. // (x, x, x, y, y, (y, x), x, x, y, y)/*T:(object!, object!, object!, object?, object?, (object? y, object! x), object!, object!, object?, object?)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, x, x, y, y, (y, x), x, x, y, y)").WithArguments("(object, object, object, object?, object?, (object? y, object x), object, object, object?, object?)", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object)").WithLocation(6, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(12, 9), // (18,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(18, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(19, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(24, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(25, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_09() { var source = @"class Program { static void F(bool b, object x) { (object?, object, object?, object, object?, (object, object?), object, object, object?, object) t = (x, x, x, default(object), default(object), default((object, object?)), x, x, default(object), default(object))/*T:(object!, object!, object!, object?, object?, (object!, object?), object!, object!, object?, object?)*/; // 1 t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 2 t.Item5.ToString(); // 3 t.Item6.Item1.ToString(); // 4 t.Item6.Item2.ToString(); // 5 t.Item7.ToString(); if (b) { t.Item8.ToString(); t.Item9.ToString(); // 6 t.Item10.ToString(); // 7 } else { t.Rest.Item1.ToString(); t.Rest.Item2.ToString(); // 8 t.Rest.Item3.ToString(); // 9 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8619: Nullability of reference types in value of type '(object, object, object, object?, object?, (object, object?), object, object, object?, object?)' doesn't match target type '(object?, object, object?, object, object?, (object, object?), object, object, object?, object)'. // (x, x, x, default(object), default(object), default((object, object?)), x, x, default(object), default(object))/*T:(object!, object!, object!, object?, object?, (object!, object?), object!, object!, object?, object?)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, x, x, default(object), default(object), default((object, object?)), x, x, default(object), default(object))").WithArguments("(object, object, object, object?, object?, (object, object?), object, object, object?, object?)", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object)").WithLocation(6, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item2").WithLocation(13, 9), // (18,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(18, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(19, 13), // (24,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(24, 13), // (25,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(25, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_10() { // https://github.com/dotnet/roslyn/issues/35010: LValueType.TypeSymbol and RValueType.Type do not agree for the null literal var source = @"using System; class Program { static void F(object x, string y) { (object, string?) t = new ValueTuple<object?, string>(null, """") { Item1 = x }; // 1 (object?, string) u = new ValueTuple<object?, string>() { Item2 = y }; t.Item1.ToString(); t.Item2.ToString(); u.Item1.ToString(); // 2 u.Item1.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,31): warning CS8619: Nullability of reference types in value of type '(object?, string)' doesn't match target type '(object, string?)'. // (object, string?) t = new ValueTuple<object?, string>(null, "") { Item1 = x }; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new ValueTuple<object?, string>(null, """") { Item1 = x }").WithArguments("(object?, string)", "(object, string?)").WithLocation(6, 31), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(10, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_11() { var source = @"using System; class Program { static void F(bool b, object x, object? y) { var t = new ValueTuple<object?, object, object?, object, object?, ValueTuple<object, object?>, object, ValueTuple<object, object?, object>>( x, x, x, b ? y : null!, // 1 y, new ValueTuple<object, object?>(b ? y : null!, x), // 2 x, new ValueTuple<object, object?, object>(x, b ? y : null!, b ? y : null!))/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; // 3 t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 4 t.Item5.ToString(); // 5 t.Item6.Item1.ToString(); // 6 t.Item6.Item2.ToString(); t.Item7.ToString(); if (b) { t.Item8.ToString(); t.Item9.ToString(); // 7 t.Item10.ToString(); // 8 } else { t.Rest.Item1.ToString(); t.Rest.Item2.ToString(); // 9 t.Rest.Item3.ToString(); // 10 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8604: Possible null reference argument for parameter 'item4' in '(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)'. // b ? y : null!, // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? y : null!").WithArguments("item4", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)").WithLocation(10, 13), // (12,45): warning CS8604: Possible null reference argument for parameter 'item1' in '(object, object?).ValueTuple(object item1, object? item2)'. // new ValueTuple<object, object?>(b ? y : null!, x), // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? y : null!").WithArguments("item1", "(object, object?).ValueTuple(object item1, object? item2)").WithLocation(12, 45), // (14,71): warning CS8604: Possible null reference argument for parameter 'item3' in '(object, object?, object).ValueTuple(object item1, object? item2, object item3)'. // new ValueTuple<object, object?, object>(x, b ? y : null!, b ? y : null!))/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? y : null!").WithArguments("item3", "(object, object?, object).ValueTuple(object item1, object? item2, object item3)").WithLocation(14, 71), // (18,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(20, 9), // (26,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(26, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(27, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(32, 13), // (33,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(33, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_12() { var source = @"using System; class Program { static void F(bool b, object x) { var t = new ValueTuple<object?, object, object?, object, object?, ValueTuple<object, object?>, object, ValueTuple<object, object?, object>>( x, x, x, default, // 1 default, default, x, default)/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 2 t.Item5.ToString(); // 3 t.Item6.Item1.ToString(); // 4 t.Item6.Item2.ToString(); // 5 t.Item7.ToString(); if (b) { t.Item8.ToString(); // 6 t.Item9.ToString(); // 7 t.Item10.ToString(); // 8 } else { t.Rest.Item1.ToString(); // 9 t.Rest.Item2.ToString(); // 10 t.Rest.Item3.ToString(); // 11 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // default, // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(10, 13), // (18,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(20, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item2").WithLocation(21, 9), // (25,13): warning CS8602: Dereference of a possibly null reference. // t.Item8.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item8").WithLocation(25, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(26, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(27, 13), // (31,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item1.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item1").WithLocation(31, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(32, 13), // (33,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(33, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_13() { var source = @"using System; class Program { static void F(bool b, object x, object? y) { var t = new ValueTuple<object?, object, object?, object, object?, (object, object?), object, (object, object?, object)>( x, x, x, y, // 1 y, (y, x), // 2 x, (x, y, y))/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; // 3 t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 4 t.Item5.ToString(); // 5 t.Item6.Item1.ToString(); // 6 t.Item6.Item2.ToString(); t.Item7.ToString(); if (b) { t.Item8.ToString(); t.Item9.ToString(); // 7 t.Item10.ToString(); // 8 } else { t.Rest.Item1.ToString(); t.Rest.Item2.ToString(); // 9 t.Rest.Item3.ToString(); // 10 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8604: Possible null reference argument for parameter 'item4' in '(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)'. // y, // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("item4", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)").WithLocation(10, 13), // (12,13): warning CS8620: Argument of type '(object? y, object x)' cannot be used for parameter 'item6' of type '(object, object?)' in '(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)' due to differences in the nullability of reference types. // (y, x), // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, x)").WithArguments("(object? y, object x)", "(object, object?)", "item6", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)").WithLocation(12, 13), // (14,13): warning CS8620: Argument of type '(object x, object?, object?)' cannot be used for parameter 'rest' of type '(object, object?, object)' in '(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)' due to differences in the nullability of reference types. // (x, y, y))/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(x, y, y)").WithArguments("(object x, object?, object?)", "(object, object?, object)", "rest", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)").WithLocation(14, 13), // (18,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(20, 9), // (26,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(26, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(27, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(32, 13), // (33,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(33, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_14() { var source = @"using System; class Program { static void F(bool b, object x) { var t = new ValueTuple<object?, object, object?, object, object?, (object, object?), object, (object, object?, object)>( x, x, x, default, // 1 default, default, x, default)/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 2 t.Item5.ToString(); // 3 t.Item6.Item1.ToString(); // 4 t.Item6.Item2.ToString(); // 5 t.Item7.ToString(); if (b) { t.Item8.ToString(); // 6 t.Item9.ToString(); // 7 t.Item10.ToString(); // 8 } else { t.Rest.Item1.ToString(); // 9 t.Rest.Item2.ToString(); // 10 t.Rest.Item3.ToString(); // 11 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // default, // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(10, 13), // (18,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(20, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item2").WithLocation(21, 9), // (25,13): warning CS8602: Dereference of a possibly null reference. // t.Item8.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item8").WithLocation(25, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(26, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(27, 13), // (31,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item1.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item1").WithLocation(31, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(32, 13), // (33,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(33, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_15() { var source = @"using System; class Program { static void F(object x, string? y) { var t = new ValueTuple<object?, string>(1); var u = new ValueTuple<object?, string>(null, null, 3); t.Item1.ToString(); // 1 t.Item2.ToString(); u.Item1.ToString(); // 2 u.Item1.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,21): error CS7036: There is no argument given that corresponds to the required formal parameter 'item2' of '(object?, string).ValueTuple(object?, string)' // var t = new ValueTuple<object?, string>(1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "ValueTuple<object?, string>").WithArguments("item2", "(object?, string).ValueTuple(object?, string)").WithLocation(6, 21), // (7,21): error CS1729: '(object?, string)' does not contain a constructor that takes 3 arguments // var u = new ValueTuple<object?, string>(null, null, 3); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "ValueTuple<object?, string>").WithArguments("(object?, string)", "3").WithLocation(7, 21), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(10, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_16() { var source = @"class Program { static object F(object? x, object y, string z, string w) { throw null!; } static void G(bool b, string s, (string?, string?) t) { (string? x, string? y) u; (string? x, string? y) v; _ = b ? F( t.Item1 = s, u = t, u.x.ToString(), u.y.ToString()) : // 1 F( t.Item2 = s, v = t, v.x.ToString(), // 2 v.y.ToString()); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,17): warning CS8602: Dereference of a possibly null reference. // u.y.ToString()) : // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.y").WithLocation(16, 17), // (20,17): warning CS8602: Dereference of a possibly null reference. // v.x.ToString(), // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v.x").WithLocation(20, 17)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_17() { var source = @"class C { (object x, (string? z, object w) y) F; static void M(C c, (object? x, (string z, object? w) y) t) { c.F = t; // 1 (object, (string?, object)) u = c.F/*T:(object! x, (string? z, object! w) y)*/; c.F.x.ToString(); // 2 c.F.y.z.ToString(); c.F.y.w.ToString(); // 3 u.Item1.ToString(); // 4 u.Item2.Item1.ToString(); u.Item2.Item2.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,15): warning CS8619: Nullability of reference types in value of type '(object? x, (string z, object? w) y)' doesn't match target type '(object x, (string? z, object w) y)'. // c.F = t; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("(object? x, (string z, object? w) y)", "(object x, (string? z, object w) y)").WithLocation(6, 15), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.F.x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F.x").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.F.y.w.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F.y.w").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(11, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.Item2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2.Item2").WithLocation(13, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Tuple_Assignment_18() { var source = @"class Program { static void F(string s) { (object, object?)? t = (null, s); // 1 (object?, object?) u = t.Value; t.Value.Item1.ToString(); // 2 t.Value.Item2.ToString(); u.Item1.ToString(); // 3 u.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,32): warning CS8619: Nullability of reference types in value of type '(object?, object s)' doesn't match target type '(object, object?)?'. // (object, object?)? t = (null, s); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, s)").WithArguments("(object?, object s)", "(object, object?)?").WithLocation(5, 32), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.Value.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Value.Item1").WithLocation(7, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(9, 9)); } [Fact] public void Tuple_Assignment_19() { var source = @"class C { static void F() { (string, string?) t = t; t.Item1.ToString(); t.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,31): error CS0165: Use of unassigned local variable 't' // (string, string?) t = t; Diagnostic(ErrorCode.ERR_UseDefViolation, "t").WithArguments("t").WithLocation(5, 31), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(7, 9)); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_20() { var source = @"class C { static void G(object? x, object? y) { F = (x, y); } static (object?, object?) G() { return ((object?, object?))F; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS0103: The name 'F' does not exist in the current context // F = (x, y); Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(5, 9), // (9,36): error CS0103: The name 'F' does not exist in the current context // return ((object?, object?))F; Diagnostic(ErrorCode.ERR_NameNotInContext, "F").WithArguments("F").WithLocation(9, 36)); } [Fact] [WorkItem(35010, "https://github.com/dotnet/roslyn/issues/35010")] public void Tuple_Assignment_21() { var source = @" #pragma warning disable CS0219 class C { static void F(string? x, string? y) { (object a, long b) t = (x, 0)/*T:(string? x, int)*/; // 1 (object a, (long b, object c)) t2 = (x, (0, y)/*T:(int, string? y)*/)/*T:(string? x, (int, string? y))*/; // 2, 3 (object a, (long b, object c)) t3 = (x!, (0, y!)/*T:(int, string!)*/)/*T:(string!, (int, string!))*/; (int b, string? c)? t4 = null; (object? a, (long b, object? c)?) t5 = (x, t4)/*T:(string? x, (int b, string? c)? t4)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,32): warning CS8619: Nullability of reference types in value of type '(object? x, long)' doesn't match target type '(object a, long b)'. // (object a, long b) t = (x, 0)/*T:(string? x, int)*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, 0)").WithArguments("(object? x, long)", "(object a, long b)").WithLocation(7, 32), // (8,45): warning CS8619: Nullability of reference types in value of type '(object? x, (long b, object c))' doesn't match target type '(object a, (long b, object c))'. // (object a, (long b, object c)) t2 = (x, (0, y)/*T:(int, string? y)*/)/*T:(string? x, (int, string! y))*/; // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, (0, y)/*T:(int, string? y)*/)").WithArguments("(object? x, (long b, object c))", "(object a, (long b, object c))").WithLocation(8, 45), // (8,49): warning CS8619: Nullability of reference types in value of type '(long, object? y)' doesn't match target type '(long b, object c)'. // (object a, (long b, object c)) t2 = (x, (0, y)/*T:(int, string? y)*/)/*T:(string? x, (int, string! y))*/; // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(0, y)").WithArguments("(long, object? y)", "(long b, object c)").WithLocation(8, 49) ); comp.VerifyTypes(); } [Fact] [WorkItem(35010, "https://github.com/dotnet/roslyn/issues/35010")] public void Tuple_Assignment_22() { var source = @" #pragma warning disable CS0219 class C { static void F(string? x) { (C, C)/*T:(C!, C!)*/ b = (x, x)/*T:(string?, string?)*/; } public static implicit operator C(string? a) { return new C(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_23() { var source = @"class Program { static void F() { (object? a, string) t = (default, default) /*T:<null>!*/; // 1 (object, string? b) u = t; // 2 _ = t/*T:(object? a, string!)*/; _ = u/*T:(object!, string? b)*/; t.Item1.ToString(); // 3 t.Item2.ToString(); // 4 u.Item1.ToString(); // 5 u.Item2.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,33): warning CS8619: Nullability of reference types in value of type '(object?, string?)' doesn't match target type '(object? a, string)'. // (object? a, string) t = (default, default) /*T:<null>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default, default)").WithArguments("(object?, string?)", "(object? a, string)").WithLocation(5, 33), // (6,33): warning CS8619: Nullability of reference types in value of type '(object? a, string)' doesn't match target type '(object, string? b)'. // (object, string? b) u = t; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("(object? a, string)", "(object, string? b)").WithLocation(6, 33), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2").WithLocation(12, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] public void Tuple_Assignment_24() { var source = @"class Program { static void F(object? x, object y) { (object x, object? y, object? z) t = (null, x, y); // 1 _ = t/*T:(object! x, object? y, object? z)*/; t.x.ToString(); // 2 t.y.ToString(); // 3 t.z.ToString(); if (x == null) return; (object x, object y) u = (x, default)/*T:<null>!*/; // 4 _ = u/*T:(object! x, object! y)*/; u.x.ToString(); u.y.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (5,46): warning CS8619: Nullability of reference types in value of type '(object?, object? x, object y)' doesn't match target type '(object x, object? y, object? z)'. // (object x, object? y, object? z) t = (null, x, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, x, y)").WithArguments("(object?, object? x, object y)", "(object x, object? y, object? z)").WithLocation(5, 46), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.x").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.y").WithLocation(8, 9), // (11,34): warning CS8619: Nullability of reference types in value of type '(object x, object?)' doesn't match target type '(object x, object y)'. // (object x, object y) u = (x, default)/*T:<null>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, default)").WithArguments("(object x, object?)", "(object x, object y)").WithLocation(11, 34), // (14,9): warning CS8602: Dereference of a possibly null reference. // u.y.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.y").WithLocation(14, 9)); } [Fact] [WorkItem(46206, "https://github.com/dotnet/roslyn/issues/46206")] public void Tuple_Assignment_25() { var source = @"using System; class Program { static void F(object x, string y) { (object, string?) t = new ValueTuple<object?, string>(item2: """", item1: null) { Item1 = x }; t.Item1.ToString(); t.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,31): warning CS8619: Nullability of reference types in value of type '(object?, string)' doesn't match target type '(object, string?)'. // (object, string?) t = new ValueTuple<object?, string>(item2: "", item1: null) { Item1 = x }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new ValueTuple<object?, string>(item2: """", item1: null) { Item1 = x }").WithArguments("(object?, string)", "(object, string?)").WithLocation(6, 31)); } [Fact] [WorkItem(46206, "https://github.com/dotnet/roslyn/issues/46206")] public void Tuple_Assignment_26() { var source = @"using System; class Program { static void F(bool b, object x, object? y) { var t = new ValueTuple<object?, object, object?, object, object?, ValueTuple<object, object?>, object, ValueTuple<object, object?, object>>( x, x, x, b ? y : x, // 1 y, new ValueTuple<object, object?>(b ? y : x, x), // 2, rest: new ValueTuple<object, object?, object>(x, b ? y : x, b ? y : x), // 3 item7: y)/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; // 4 t.Item1.ToString(); t.Item2.ToString(); t.Item3.ToString(); t.Item4.ToString(); // 5 t.Item5.ToString(); // 6 t.Item6.Item1.ToString(); // 7 t.Item6.Item2.ToString(); t.Item7.ToString(); // 8 if (b) { t.Item8.ToString(); t.Item9.ToString(); // 9 t.Item10.ToString(); // 10 } else { t.Rest.Item1.ToString(); t.Rest.Item2.ToString(); // 11 t.Rest.Item3.ToString(); // 12 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8604: Possible null reference argument for parameter 'item4' in '(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)'. // b ? y : x, // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? y : x").WithArguments("item4", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)").WithLocation(10, 13), // (12,45): warning CS8604: Possible null reference argument for parameter 'item1' in '(object, object?).ValueTuple(object item1, object? item2)'. // new ValueTuple<object, object?>(b ? y : x, x), // 2, Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? y : x").WithArguments("item1", "(object, object?).ValueTuple(object item1, object? item2)").WithLocation(12, 45), // (13,73): warning CS8604: Possible null reference argument for parameter 'item3' in '(object, object?, object).ValueTuple(object item1, object? item2, object item3)'. // rest: new ValueTuple<object, object?, object>(x, b ? y : x, b ? y : x), // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b ? y : x").WithArguments("item3", "(object, object?, object).ValueTuple(object item1, object? item2, object item3)").WithLocation(13, 73), // (14,20): warning CS8604: Possible null reference argument for parameter 'item7' in '(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)'. // item7: y)/*T:(object?, object!, object?, object!, object?, (object!, object?), object!, object!, object?, object!)*/; // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("item7", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object).ValueTuple(object? item1, object item2, object? item3, object item4, object? item5, (object, object?) item6, object item7, (object, object?, object) rest)").WithLocation(14, 20), // (18,9): warning CS8602: Dereference of a possibly null reference. // t.Item4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item4").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // t.Item5.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item5").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // t.Item6.Item1.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item6.Item1").WithLocation(20, 9), // (22,9): warning CS8602: Dereference of a possibly null reference. // t.Item7.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item7").WithLocation(22, 9), // (26,13): warning CS8602: Dereference of a possibly null reference. // t.Item9.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item9").WithLocation(26, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // t.Item10.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item10").WithLocation(27, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item2.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item2").WithLocation(32, 13), // (33,13): warning CS8602: Dereference of a possibly null reference. // t.Rest.Item3.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Rest.Item3").WithLocation(33, 13)); } [Fact] [WorkItem(32338, "https://github.com/dotnet/roslyn/issues/32338")] public void CopyStructUnconstrainedFieldNullability_01() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void M<T>(T t) { var x = new S<T>() { F = t }; var y = x; y.F.ToString(); // 1 if (t == null) return; x = new S<T>() { F = t }; var z = x; z.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(12, 9)); } [Fact] [WorkItem(32338, "https://github.com/dotnet/roslyn/issues/32338")] public void CopyStructUnconstrainedFieldNullability_02() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void M<T>(S<T> x) { var y = x; y.F.ToString(); // 1 if (x.F == null) return; var z = x; z.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(11, 9)); } [Fact] [WorkItem(29970, "https://github.com/dotnet/roslyn/issues/29970")] [WorkItem(32338, "https://github.com/dotnet/roslyn/issues/32338")] public void CopyTupleUnconstrainedElementNullability_01() { var source = @"class Program { static void M<T, U>(T t, U u) { var x = (t, u); var y = x; y.Item1.ToString(); // 1 if (t == null) return; x = (t, u); var z = x; z.Item1.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // y.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Item1").WithLocation(7, 9)); } [Fact] [WorkItem(32338, "https://github.com/dotnet/roslyn/issues/32338")] public void CopyTupleUnconstrainedElementNullability_02() { var source = @"class Program { static void M<T, U>((T, U) x) { var y = x; y.Item1.ToString(); // 1 if (x.Item1 == null) return; var z = x; z.Item1.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // y.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Item1").WithLocation(6, 9)); } [Fact] [WorkItem(32703, "https://github.com/dotnet/roslyn/issues/32703")] [WorkItem(31395, "https://github.com/dotnet/roslyn/issues/31395")] public void CopyClassFields() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C { internal object? F; internal object G; } class Program { static void F(C x) { if (x.F == null) return; if (x.G != null) return; C y = x; x.F.ToString(); x.G.ToString(); // 1 y.F.ToString(); y.G.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,9): warning CS8602: Dereference of a possibly null reference. // x.G.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.G").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // y.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.G").WithLocation(18, 9)); } [Fact] [WorkItem(32703, "https://github.com/dotnet/roslyn/issues/32703")] public void CopyStructFields() { var source = @"#pragma warning disable 0649 struct S { internal object? F; internal object G; } class Program { static void F(S x) { if (x.F == null) return; if (x.G != null) return; S y = x; x.F.ToString(); x.G.ToString(); // 1 y.F.ToString(); y.G.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // x.G.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.G").WithLocation(15, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // y.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.G").WithLocation(17, 9) ); } [Fact] [WorkItem(32703, "https://github.com/dotnet/roslyn/issues/32703")] public void CopyNullableStructFields() { var source = @"#pragma warning disable 0649 struct S { internal object? F; internal object G; } class Program { static void F(S? x) { if (x == null) return; if (x.Value.F == null) return; if (x.Value.G != null) return; S? y = x; x.Value.F.ToString(); x.Value.G.ToString(); // 1 y.Value.F.ToString(); y.Value.G.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,9): warning CS8602: Dereference of a possibly null reference. // x.Value.G.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.G").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // y.Value.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.G").WithLocation(18, 9) ); } [Fact] [WorkItem(31395, "https://github.com/dotnet/roslyn/issues/31395")] public void NestedAssignment() { var source = @"class C { internal C? F; internal C G = null!; } class Program { static void F1() { var x1 = new C() { F = new C(), G = null }; // 1 var y1 = new C() { F = x1, G = (x1 = new C()) }; y1.F.F.ToString(); y1.F.G.ToString(); // 2 y1.G.F.ToString(); // 3 y1.G.G.ToString(); } static void F2() { var x2 = new C() { F = new C(), G = null }; // 4 var y2 = new C() { G = x2, F = (x2 = new C()) }; y2.F.F.ToString(); // 5 y2.F.G.ToString(); y2.G.F.ToString(); y2.G.G.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,45): warning CS8625: Cannot convert null literal to non-nullable reference type. // var x1 = new C() { F = new C(), G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 45), // (13,9): warning CS8602: Dereference of a possibly null reference. // y1.F.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1.F.G").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // y1.G.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1.G.F").WithLocation(14, 9), // (19,45): warning CS8625: Cannot convert null literal to non-nullable reference type. // var x2 = new C() { F = new C(), G = null }; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 45), // (21,9): warning CS8602: Dereference of a possibly null reference. // y2.F.F.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2.F.F").WithLocation(21, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // y2.G.G.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2.G.G").WithLocation(24, 9)); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void ConditionalAccessIsAPureTest() { var source = @" class C { void F(object o) { if (o?.ToString() != null) o.ToString(); else o.ToString(); // 1 o.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(9, 13) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void ConditionalAccessIsAPureTest_Generic() { var source = @" class C { void F<T>(T t) { if (t is null) return; if (t?.ToString() != null) t.ToString(); else t.ToString(); // 1 t.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(11, 13) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void ConditionalAccessIsAPureTest_Indexer() { var source = @" class C { void F(C c) { if (c?[0] == true) c.ToString(); else c.ToString(); // 1 c.ToString(); } bool this[int i] => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(9, 13) ); } [Fact] [WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] [WorkItem(34018, "https://github.com/dotnet/roslyn/issues/34018")] public void ConditionalAccessIsAPureTest_InFinally_01() { var source = @" class C { void F(object o) { try { } finally { if (o?.ToString() != null) o.ToString(); } o.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(34018, "https://github.com/dotnet/roslyn/issues/34018")] public void ConditionalAccessIsAPureTest_InFinally_02() { var source = @" class C { void F() { C? c = null; try { c = new C(); } finally { if (c != null) c.Cleanup(); } c.Operation(); // ok } void Cleanup() {} void Operation() {} }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void NullCoalescingIsAPureTest() { var source = @" class C { void F(string s, string s2) { _ = s ?? s.ToString(); // 1 _ = s2 ?? null; s2.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): warning CS8602: Dereference of a possibly null reference. // _ = s ?? s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 18), // (9,9): warning CS8602: Dereference of a possibly null reference. // s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(9, 9) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void NullCoalescingAssignmentIsAPureTest() { var source = @" class C { void F(string s, string s2) { s ??= s.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,15): warning CS8602: Dereference of a possibly null reference. // s ??= s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(6, 15) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void NullComparisonIsAPureTest() { var source = @" class C { void F(C x, C y) { if (x == null) x.ToString(); // 1 else x.ToString(); if (null != y) y.ToString(); else y.ToString(); // 2 } public static bool operator==(C? one, C? two) => throw null!; public static bool operator!=(C? one, C? two) => throw null!; public override bool Equals(object o) => throw null!; public override int GetHashCode() => throw null!; }"; // `x == null` is a "pure test" even when it binds to a user-defined operator, // so affects both branches var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(14, 13) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void NullComparisonIsAPureTest_IntroducesMaybeNull() { var source = @" class C { void F(C x, C y) { if (x == null) { } x.ToString(); // 1 if (null != y) { } y.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(10, 9) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void NullComparisonIsAPureTest_WithCast() { var source = @" class C { void F(object x, object y) { if ((string)x == null) x.ToString(); // 1 else x.ToString(); if (null != (string)y) y.ToString(); else y.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(14, 13) ); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void IsNullIsAPureTest() { var source = @" class C { void F(C x) { if (x is null) x.ToString(); // 1 else x.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 13) ); } // https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-12-18.md [Fact] public void OtherComparisonsAsPureNullTests_01() { var source = @"#nullable enable using System; using System_Object = System.Object; class E { } class Program { static void F1(E e) { if (e is object) return; e.ToString(); // 1 } static void F2(E e) { if (e is Object) return; e.ToString(); // 2 } static void F3(E e) { if (e is System.Object) return; e.ToString(); // 3 } static void F4(E e) { if (e is System_Object) return; e.ToString(); // 4 } static void F5(E e) { if (e is object _) return; e.ToString(); } static void F6(E e) { if (e is object x) return; e.ToString(); } static void F7(E e) { if (e is dynamic) return; e.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // e.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(10, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // e.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(15, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // e.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(20, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // e.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(25, 9), // (39,13): warning CS1981: Using 'is' to test compatibility with 'dynamic' is essentially identical to testing compatibility with 'Object' and will succeed for all non-null values // if (e is dynamic) return; Diagnostic(ErrorCode.WRN_IsDynamicIsConfusing, "e is dynamic").WithArguments("is", "dynamic", "Object").WithLocation(39, 13)); } [Fact] public void OtherComparisonsAsPureNullTests_02() { var source = @"#nullable enable class Program { static void F1(string s) { if (s is string) return; s.ToString(); } static void F2(string s) { if (s is string _) return; s.ToString(); } static void F3(string s) { if (s is string x) return; s.ToString(); } static void F4(object o) { if (o is string x) return; o.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } // https://github.com/dotnet/csharplang/blob/main/meetings/2019/LDM-2019-12-18.md [Fact] public void OtherComparisonsAsPureNullTests_03() { var source = @"#nullable enable #pragma warning disable 649 class E { public void Deconstruct() => throw null!; internal Pair? F; } class Pair { public void Deconstruct(out int x, out int y) => throw null!; } class Program { static void F1(E e) { if (e is { }) return; e.ToString(); // 1 } static void F2(E e) { if (e is { } _) return; e.ToString(); } static void F3(E e) { if (e is { } x) return; e.ToString(); } static void F4(E e) { if (e is E { }) return; e.ToString(); } static void F5(E e) { if (e is object { }) return; e.ToString(); } static void F6(E e) { if (e is { F: null }) return; e.ToString(); } static void F7(E e) { if (e is ( )) return; e.ToString(); } static void F8(E e) { if (e is ( ) { }) return; e.ToString(); } static void F9(E e) { if (e is { F: (1, 2) }) return; e.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,9): warning CS8602: Dereference of a possibly null reference. // e.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(17, 9)); } [Fact] public void OtherComparisonsAsPureNullTests_04() { var source = @"#nullable enable #pragma warning disable 649 class E { internal object F; } class Program { static void F0(E e) { e.F.ToString(); } static void F1(E e) { if (e is { F: null }) return; e.F.ToString(); } static void F2(E e) { if (e is E { F: 2 }) return; e.F.ToString(); } static void F3(E e) { if (e is { F: { } }) return; e.F.ToString(); // 1 } static void F4(E e) { if (e is { F: { } } _) return; e.F.ToString(); // 2 } static void F5(E e) { if (e is { F: { } } x) return; e.F.ToString(); // 3 } static void F6(E e) { if (e is E { F: { } }) return; e.F.ToString(); // 4 } static void F7(E e) { if (e is { F: object _ }) return; e.F.ToString(); } static void F8(E e) { if (e is { F: object x }) { x.ToString(); return; } e.F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,21): warning CS8618: Non-nullable field 'F' is uninitialized. Consider declaring the field as nullable. // internal object F; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "F").WithArguments("field", "F").WithLocation(5, 21), // (26,9): warning CS8602: Dereference of a possibly null reference. // e.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.F").WithLocation(26, 9), // (31,9): warning CS8602: Dereference of a possibly null reference. // e.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.F").WithLocation(31, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // e.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.F").WithLocation(36, 9), // (41,9): warning CS8602: Dereference of a possibly null reference. // e.F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.F").WithLocation(41, 9)); } [Fact] public void OtherComparisonsAsPureNullTests_05() { var source = @"#nullable enable class E { } class Program { static void F(E e) { switch (e) { case { }: return; } e.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // e.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(13, 9)); } [Fact] public void OtherComparisonsAsPureNullTests_06() { var source = @"#nullable enable class E { } class Program { static void F(E e) { switch (e) { case var x when e.ToString() == null: // 1 break; case { }: break; } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,29): warning CS8602: Dereference of a possibly null reference. // case var x when e.ToString() == null: // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(11, 29)); } [Theory] [InlineData("null")] [InlineData("not null")] [InlineData("{}")] public void OtherComparisonsAsPureNullTests_ExtendedProperties_PureNullTest(string pureTest) { var source = $@"#nullable enable class E {{ public E Property1 {{ get; set; }} = null!; public object Property2 {{ get; set; }} = null!; }} class Program {{ static void F(E e) {{ switch (e) {{ case var x when e.Property1.Property2.ToString() == null: // 1 break; case {{ Property1.Property2: {pureTest} }}: break; }} }} }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.RegularWithExtendedPropertyPatterns); comp.VerifyDiagnostics( // (13,29): warning CS8602: Dereference of a possibly null reference. // case var x when e.Property1.Property2.ToString() == null: // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e.Property1.Property2").WithLocation(13, 29)); } [Fact, WorkItem(33526, "https://github.com/dotnet/roslyn/issues/33526")] public void OtherComparisonsAreNotPureTest() { var source = @" class C { void F(C x) { if (x is D) { } x.ToString(); } } class D : C { } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ImplicitNullable_01() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { S? x = new S() { F = 1, G = null }; // 1 S? y = x; x.Value.F.ToString(); x.Value.G.ToString(); // 2 y.Value.F.ToString(); y.Value.G.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S? x = new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 37), // (13,9): warning CS8602: Dereference of a possibly null reference. // x.Value.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.G").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.Value.G.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.G").WithLocation(15, 9)); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ImplicitNullable_02() { var source = @"class Program { static void F(int? x) { long? y = x; if (x == null) return; long? z = x; x.Value.ToString(); y.Value.ToString(); // 1 z.Value.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8629: Nullable value type may be null. // y.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(9, 9) ); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ImplicitNullable_03() { var source = @"class Program { static void F(int x) { int? y = x; long? z = x; y.Value.ToString(); z.Value.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ImplicitNullable_04() { var source = @"class Program { static void F1(long x1) { int? y1 = x1; // 1 y1.Value.ToString(); } static void F2(long? x2) { int? y2 = x2; // 2 y2.Value.ToString(); // 3 } static void F3(long? x3) { if (x3 == null) return; int? y3 = x3; // 4 y3.Value.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,19): error CS0266: Cannot implicitly convert type 'long' to 'int?'. An explicit conversion exists (are you missing a cast?) // int? y1 = x1; // 1 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x1").WithArguments("long", "int?").WithLocation(5, 19), // (10,19): error CS0266: Cannot implicitly convert type 'long?' to 'int?'. An explicit conversion exists (are you missing a cast?) // int? y2 = x2; // 2 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x2").WithArguments("long?", "int?").WithLocation(10, 19), // (11,9): warning CS8629: Nullable value type may be null. // y2.Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y2").WithLocation(11, 9), // (16,19): error CS0266: Cannot implicitly convert type 'long?' to 'int?'. An explicit conversion exists (are you missing a cast?) // int? y3 = x3; // 4 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x3").WithArguments("long?", "int?").WithLocation(16, 19) ); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ImplicitNullable_05() { var source = @"#pragma warning disable 0649 struct A { internal object? F; } struct B { internal object? F; } class Program { static void F1() { A a1 = new A(); B? b1 = a1; // 1 _ = b1.Value; b1.Value.F.ToString(); // 2 } static void F2() { A? a2 = new A() { F = 2 }; B? b2 = a2; // 3 _ = b2.Value; b2.Value.F.ToString(); // 4 } static void F3(A? a3) { B? b3 = a3; // 5 _ = b3.Value; // 6 b3.Value.F.ToString(); // 7 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,17): error CS0029: Cannot implicitly convert type 'A' to 'B?' // B? b1 = a1; // 1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "a1").WithArguments("A", "B?").WithLocation(15, 17), // (17,9): warning CS8602: Dereference of a possibly null reference. // b1.Value.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1.Value.F").WithLocation(17, 9), // (22,17): error CS0029: Cannot implicitly convert type 'A?' to 'B?' // B? b2 = a2; // 3 Diagnostic(ErrorCode.ERR_NoImplicitConv, "a2").WithArguments("A?", "B?").WithLocation(22, 17), // (24,9): warning CS8602: Dereference of a possibly null reference. // b2.Value.F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b2.Value.F").WithLocation(24, 9), // (28,17): error CS0029: Cannot implicitly convert type 'A?' to 'B?' // B? b3 = a3; // 5 Diagnostic(ErrorCode.ERR_NoImplicitConv, "a3").WithArguments("A?", "B?").WithLocation(28, 17), // (29,13): warning CS8629: Nullable value type may be null. // _ = b3.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "b3").WithLocation(29, 13), // (30,9): warning CS8602: Dereference of a possibly null reference. // b3.Value.F.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b3.Value.F").WithLocation(30, 9) ); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ExplicitNullable_01() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { S x = new S() { F = 1, G = null }; // 1 var y = (S?)x; y.Value.F.ToString(); y.Value.G.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // S x = new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 36), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.Value.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.G").WithLocation(13, 9)); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ExplicitNullable_02() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { S? x = new S() { F = 1, G = null }; // 1 S y = (S)x; y.F.ToString(); y.G.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S? x = new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 37), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.G").WithLocation(13, 9)); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ExplicitNullable_03() { var source = @"class Program { static void F(int? x) { long? y = (long?)x; if (x == null) return; long? z = (long?)x; x.Value.ToString(); y.Value.ToString(); // 1 z.Value.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8629: Nullable value type may be null. // y.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(9, 9) ); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ExplicitNullable_04() { var source = @"class Program { static void F(long? x) { int? y = (int?)x; if (x == null) return; int? z = (int?)x; x.Value.ToString(); y.Value.ToString(); // 1 z.Value.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8629: Nullable value type may be null. // y.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(9, 9) ); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Conversions_ExplicitNullable_05() { var source = @"class Program { static void F1(int? x1) { int y1 = (int)x1; // 1 } static void F2(int? x2) { if (x2 == null) return; int y2 = (int)x2; } static void F3(int? x3) { long y3 = (long)x3; // 2 } static void F4(int? x4) { if (x4 == null) return; long y4 = (long)x4; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,18): warning CS8629: Nullable value type may be null. // int y1 = (int)x1; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int)x1").WithLocation(5, 18), // (14,19): warning CS8629: Nullable value type may be null. // long y3 = (long)x3; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(long)x3").WithLocation(14, 19)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void Conversions_ExplicitNullable_06() { var source = @"class C { int? i = null; static void F1(C? c) { int i1 = (int)c?.i; // 1 _ = c.ToString(); _ = c.i.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,18): warning CS8629: Nullable value type may be null. // int i1 = (int)c?.i; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int)c?.i").WithLocation(7, 18)); } [Fact] [WorkItem(38170, "https://github.com/dotnet/roslyn/issues/38170")] public void Conversions_ExplicitNullable_07() { var source = @"class C { int? i = null; static void F1(C? c) { int? i1 = (int?)c?.i; _ = c.ToString(); // 1 _ = c.i.Value.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 13), // (9,13): warning CS8629: Nullable value type may be null. // _ = c.i.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.i").WithLocation(9, 13)); } [Fact] [WorkItem(35334, "https://github.com/dotnet/roslyn/issues/35334")] public void Conversions_ExplicitNullable_UserDefinedIntroducingNullability() { var source = @" class A { public static explicit operator B(A a) => throw null!; } class B { void M(A a) { var b = ((B?)a)/*T:B?*/; b.ToString(); // 1 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(8, 9)); } [Fact] [WorkItem(32531, "https://github.com/dotnet/roslyn/issues/32531")] public void Tuple_Conversions_ImplicitNullable_01() { var source = @"struct S { internal object? F; } class Program { static void F() { S x = new S(); S y = new S() { F = 1 }; (S, S) t = (x, y); (S? x, S? y) u = t; (S?, S?) v = (x, y); t.Item1.F.ToString(); // 1 t.Item2.F.ToString(); u.x.Value.F.ToString(); // 2 u.y.Value.F.ToString(); v.Item1.Value.F.ToString(); // 3 v.Item2.Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1.F").WithLocation(14, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // u.x.Value.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.x.Value.F").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // v.Item1.Value.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "v.Item1.Value.F").WithLocation(18, 9) ); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Tuple_Conversions_ImplicitNullable_02() { var source = @"struct S { internal object? F; } class Program { static void F() { S x = new S(); S y = new S() { F = 1 }; (S, S) t = (x, y); (S a, S b)? u = t; t.Item1.F.ToString(); // 1 t.Item2.F.ToString(); u.Value.a.F.ToString(); // 2 u.Value.b.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1.F").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // u.Value.a.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Value.a.F").WithLocation(15, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Tuple_Conversions_ImplicitReference() { var source = @"class Program { static void F(string x, string? y) { (object?, string?) t = (x, y); (object? a, object? b) u = t; t.Item1.ToString(); t.Item2.ToString(); // 1 u.a.ToString(); // 2 u.b.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // u.a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.a").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.b.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.b").WithLocation(10, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Tuple_Conversions_ImplicitDynamic() { var source = @"class Program { static void F(object x, object? y) { (object?, dynamic?) t = (x, y); (dynamic? a, object? b) u = t; t.Item1.ToString(); t.Item2.ToString(); // 1 u.a.ToString(); u.b.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.b.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.b").WithLocation(10, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Tuple_Conversions_Boxing() { var source = @"class Program { static void F<T, U, V>(T x, U y, V? z) where U : struct where V : struct { (object, object, object) t = (x, y, z); // 1 t.Item1.ToString(); // 2 t.Item2.ToString(); t.Item3.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,38): warning CS8619: Nullability of reference types in value of type '(object? x, object y, object? z)' doesn't match target type '(object, object, object)'. // (object, object, object) t = (x, y, z); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y, z)").WithArguments("(object? x, object y, object? z)", "(object, object, object)").WithLocation(7, 38), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // t.Item3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item3").WithLocation(10, 9)); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_Default_01() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F<T, U, V>() where U : class where V : struct { default(S<T>).F/*T:T*/.ToString(); // 1 default(S<U>).F/*T:U?*/.ToString(); // 2 _ = default(S<V?>).F/*T:V?*/.Value; // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // default(S<T>).F/*T:T*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(S<T>).F").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // default(S<U>).F/*T:U?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(S<U>).F").WithLocation(13, 9), // (14,13): warning CS8629: Nullable value type may be null. // _ = default(S<V?>).F/*T:V?*/.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "default(S<V?>).F").WithLocation(14, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_Default_02() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F<T, U, V>() where U : class where V : struct { new S<T>().F/*T:T*/.ToString(); // 1 new S<U>().F/*T:U?*/.ToString(); // 2 _ = new S<V?>().F/*T:V?*/.Value; // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // new S<T>().F/*T:T*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new S<T>().F").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // new S<U>().F/*T:U?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new S<U>().F").WithLocation(13, 9), // (14,13): warning CS8629: Nullable value type may be null. // _ = new S<V?>().F/*T:V?*/.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new S<V?>().F").WithLocation(14, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_Default_03() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F() { S<object> x = default; S<object> y = x; x.F/*T:object?*/.ToString(); // 1 y.F/*T:object?*/.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.F/*T:object?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(13, 9)); comp.VerifyTypes(); } [Fact] public void StructField_Default_04() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F() { S<int?> x = default; S<int?> y = x; _ = x.F.Value; // 1 _ = y.F.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,13): warning CS8629: Nullable value type may be null. // _ = x.F.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x.F").WithLocation(12, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = y.F.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y.F").WithLocation(13, 13) ); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_Default_05() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F() { var x = new S<object>(); var y = x; x.F/*T:object?*/.ToString(); // 1 y.F/*T:object?*/.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.F/*T:object?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(13, 9)); comp.VerifyTypes(); } [Fact] public void StructField_Default_06() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F() { var x = new S<int?>(); var y = x; _ = x.F.Value; // 1 _ = y.F.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,13): warning CS8629: Nullable value type may be null. // _ = x.F.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x.F").WithLocation(12, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = y.F.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y.F").WithLocation(13, 13) ); } [Fact] public void StructField_Default_07() { var source = @"#pragma warning disable 649 struct S<T, U> { internal T F; internal U G; } class Program { static void F(object a, string b) { var x = new S<object, string>() { F = a }; x.F/*T:object!*/.ToString(); x.G/*T:string?*/.ToString(); // 1 var y = new S<object, string>() { G = b }; y.F/*T:object?*/.ToString(); // 2 y.G/*T:string!*/.ToString(); var z = new S<object, string>() { F = default, G = default }; // 3, 4 z.F/*T:object?*/.ToString(); // 5 z.G/*T:string?*/.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // x.G/*T:string?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.G").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.F/*T:object?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(15, 9), // (17,47): warning CS8625: Cannot convert null literal to non-nullable reference type. // var z = new S<object, string>() { F = default, G = default }; // 3, 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(17, 47), // (17,60): warning CS8625: Cannot convert null literal to non-nullable reference type. // var z = new S<object, string>() { F = default, G = default }; // 3, 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(17, 60), // (18,9): warning CS8602: Dereference of a possibly null reference. // z.F/*T:object?*/.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.F").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // z.G/*T:string?*/.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.G").WithLocation(19, 9)); comp.VerifyTypes(); } [Fact] public void StructField_Default_ParameterlessConstructor() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; internal S() { F = default!; } internal S(T t) { F = t; } } class Program { static void F() { var x = default(S<object>); x.F/*T:object?*/.ToString(); // 1 var y = new S<object>(); y.F/*T:object!*/.ToString(); var z = new S<object>(1); z.F/*T:object!*/.ToString(); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,14): error CS8773: Feature 'parameterless struct constructors' is not available in C# 9.0. Please use language version 10.0 or greater. // internal S() { F = default!; } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion9, "S").WithArguments("parameterless struct constructors", "10.0").WithLocation(5, 14), // (5,14): error CS8938: The parameterless struct constructor must be 'public'. // internal S() { F = default!; } Diagnostic(ErrorCode.ERR_NonPublicParameterlessStructConstructor, "S").WithLocation(5, 14), // (13,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(13, 9)); comp.VerifyTypes(); } [Fact] public void StructField_Default_NoType() { var source = @"class Program { static void F() { _ = default/*T:!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,13): error CS8716: There is no target type for the default literal. // _ = default/*T:!*/.ToString(); Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(5, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_ParameterDefaultValue_01() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F1<T1>(S<T1> x1 = default) { var y1 = x1; x1.F/*T:T1*/.ToString(); // 1 y1.F/*T:T1*/.ToString(); // 2 } static void F2<T2>(S<T2> x2 = default) where T2 : class { var y2 = x2; x2.F/*T:T2?*/.ToString(); // 3 y2.F/*T:T2?*/.ToString(); // 4 } static void F3<T3>(S<T3?> x3 = default) where T3 : struct { var y3 = x3; _ = x3.F/*T:T3?*/.Value; // 5 _ = y3.F/*T:T3?*/.Value; // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // x1.F/*T:T1*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1.F").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // y1.F/*T:T1*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1.F").WithLocation(12, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // x2.F/*T:T2?*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2.F").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // y2.F/*T:T2?*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2.F").WithLocation(18, 9), // (23,13): warning CS8629: Nullable value type may be null. // _ = x3.F/*T:T3?*/.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x3.F").WithLocation(23, 13), // (24,13): warning CS8629: Nullable value type may be null. // _ = y3.F/*T:T3?*/.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y3.F").WithLocation(24, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_ParameterDefaultValue_02() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; internal S(T t) { F = t; } } class Program { static void F<T>(S<T> x = new S<T>(), S<T> y = null, S<T> z = new S<T>(default)) where T : class { x.F/*T:T?*/.ToString(); // 1 y.F/*T:T!*/.ToString(); z.F/*T:T!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,48): error CS1750: A value of type '<null>' cannot be used as a default parameter because there are no standard conversions to type 'S<T>' // static void F<T>(S<T> x = new S<T>(), S<T> y = null, S<T> z = new S<T>(default)) where T : class Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "y").WithArguments("<null>", "S<T>").WithLocation(9, 48), // (9,67): error CS1736: Default parameter value for 'z' must be a compile-time constant // static void F<T>(S<T> x = new S<T>(), S<T> y = null, S<T> z = new S<T>(default)) where T : class Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "new S<T>(default)").WithArguments("z").WithLocation(9, 67), // (9,76): warning CS8625: Cannot convert null literal to non-nullable reference type. // static void F<T>(S<T> x = new S<T>(), S<T> y = null, S<T> z = new S<T>(default)) where T : class Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(9, 76), // (11,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:T?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(11, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_ParameterDefaultValue_03() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F<T>(S<T> x = /*missing*/, S<T> y = default) where T : class { x.F/*T:T!*/.ToString(); y.F/*T:T?*/.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,42): error CS1525: Invalid expression term ',' // static void F<T>(S<T> x = /*missing*/, S<T> y = default) where T : class Diagnostic(ErrorCode.ERR_InvalidExprTerm, ",").WithArguments(",").WithLocation(8, 42), // (11,9): warning CS8602: Dereference of a possibly null reference. // y.F/*T:T?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(11, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_ParameterDefaultValue_04() { var source = @"#pragma warning disable 649 struct S<T> { internal T F; } class Program { static void F<T>(S<T>? x = default(S<T>)) where T : class { if (x == null) return; var y = x.Value; y.F/*T:T!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,28): error CS1770: A value of type 'S<T>' cannot be used as default parameter for nullable parameter 'x' because 'S<T>' is not a simple type // static void F<T>(S<T>? x = default(S<T>)) where T : class Diagnostic(ErrorCode.ERR_NoConversionForNubDefaultParam, "x").WithArguments("S<T>", "x").WithLocation(8, 28)); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void StructField_Default_Nested() { var source = @"#pragma warning disable 649 struct S { internal S(int i) { S1 = null!; T = default; } internal object S1; internal T T; } struct T { internal object T1; } class Program { static void F1() { // default S s1 = default; s1.S1.ToString(); // 1 s1.T.T1.ToString(); // 2 } static void F2() { // default constructor S s2 = new S(); s2.S1.ToString(); // 3 s2.T.T1.ToString(); // 4 } static void F3() { // explicit constructor S s3 = new S(0); s3.S1.ToString(); s3.T.T1.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (22,9): warning CS8602: Dereference of a possibly null reference. // s1.S1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1.S1").WithLocation(22, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // s1.T.T1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1.T.T1").WithLocation(23, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // s2.S1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2.S1").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // s2.T.T1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2.T.T1").WithLocation(30, 9)); } [Fact] public void StructField_Cycle_Default() { // Nullability of F is treated as object!, even for default instances, because a struct with cycles // is not a "trackable" struct type (see EmptyStructTypeCache.IsTrackableStructType). var source = @"#pragma warning disable 649 struct S { internal S Next; internal object F; } class Program { static void F() { default(S).F/*T:object!*/.ToString(); S x = default; S y = x; x.F/*T:object!*/.ToString(); x.Next.F/*T:object!*/.ToString(); y.F/*T:object!*/.ToString(); y.Next.F/*T:object!*/.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,16): error CS0523: Struct member 'S.Next' of type 'S' causes a cycle in the struct layout // internal S Next; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "Next").WithArguments("S.Next", "S").WithLocation(4, 16)); comp.VerifyTypes(); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructProperty_Cycle_Default() { var source = @"#pragma warning disable 649 struct S { internal S Next { get => throw null!; set { } } internal object F; } class Program { static void F() { S x = default; S y = x; x.F/*T:object?*/.ToString(); // 1 x.Next.F/*T:object!*/.ToString(); y.F/*T:object?*/.ToString(); // 2 y.Next.F/*T:object!*/.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(17, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // y.F/*T:object?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(19, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructProperty_Cycle() { var source = @"struct S { internal object? F; internal S P { get { return this; } set { this = value; } } } class Program { static void M(S s) { s.F = 2; for (int i = 0; i < 3; i++) { s.P = s; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructField_Cycle_01() { var source = @"#pragma warning disable 649 struct S { internal S F; internal object? P => null; } class Program { static void F(S x, S y) { if (y.P == null) return; x.P.ToString(); // 1 y.P.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,16): error CS0523: Struct member 'S.F' of type 'S' causes a cycle in the struct layout // internal S F; Diagnostic(ErrorCode.ERR_StructLayoutCycle, "F").WithArguments("S.F", "S").WithLocation(4, 16), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.P").WithLocation(12, 9)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructField_Cycle_02() { var source0 = @".class public sealed S extends [mscorlib]System.ValueType { .field public valuetype [mscorlib]System.Nullable`1<valuetype S> F }"; var ref0 = CompileIL(source0); var source = @"class Program { static void F(S x, S y) { if (y.F == null) return; _ = x.F.Value; // 1 _ = y.F.Value; } }"; var comp = CreateCompilation(new[] { source }, new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8629: Nullable value type may be null. // _ = x.F.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x.F").WithLocation(6, 13)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructField_Cycle_03() { var source0 = @".class public sealed S extends [mscorlib]System.ValueType { .field public valuetype S F .field public object G }"; var ref0 = CompileIL(source0); var source = @"class Program { static void F(S s) { s.G = null; s.G.ToString(); // 1 } }"; var comp = CreateCompilation(new[] { source }, new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.G.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.G").WithLocation(6, 9)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructField_Cycle_04() { var source0 = @".class public sealed S extends [mscorlib]System.ValueType { .field public valuetype S F .method public instance object get_P() { ldnull ret } .method public instance void set_P(object 'value') { ret } .property instance object P() { .get instance object S::get_P() .set instance void S::set_P(object) } }"; var ref0 = CompileIL(source0); var source = @"class Program { static void F(S s) { s.P = null; s.P.ToString(); // 1 } }"; var comp = CreateCompilation(new[] { source }, new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void StructPropertyNoBackingField() { var source0 = @".class public sealed S extends [mscorlib]System.ValueType { .method public instance object get_P() { ldnull ret } .method public instance void set_P(object 'value') { ret } .property instance object P() { .get instance object S::get_P() .set instance void S::set_P(object) } }"; var ref0 = CompileIL(source0); var source = @"class Program { static void F(S s) { s.P = null; s.P.ToString(); // 1 } }"; var comp = CreateCompilation(new[] { source }, new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // s.P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.P").WithLocation(6, 9)); } // `default` expression in a split state. [Fact] public void IsPattern_DefaultTrackableStruct() { var source = @"#pragma warning disable 649 struct S { internal object F; } class Program { static void F() { if (default(S) is default) { } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,27): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (default(S) is default) { } Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(10, 27)); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_Default_01() { var source = @"class Program { static void F() { default((object?, string))/*T:(object?, string!)*/.Item2.ToString(); // 1 _ = default((int, int?))/*T:(int, int?)*/.Item2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // default((object?, string))/*T:(object?, string!)*/.Item2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default((object?, string))/*T:(object?, string!)*/.Item2").WithLocation(5, 9), // (6,13): warning CS8629: Nullable value type may be null. // _ = default((int, int?))/*T:(int, int?)*/.Item2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "default((int, int?))/*T:(int, int?)*/.Item2").WithLocation(6, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_Default_02() { var source = @"using System; class Program { static void F1() { new ValueTuple<object?, string>()/*T:(object?, string!)*/.Item2.ToString(); // 1 _ = new ValueTuple<int, int?>()/*T:(int, int?)*/.Item2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // new ValueTuple<object?, string>()/*T:(object?, string!)*/.Item2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new ValueTuple<object?, string>()/*T:(object?, string!)*/.Item2").WithLocation(6, 9), // (7,13): warning CS8629: Nullable value type may be null. // _ = new ValueTuple<int, int?>()/*T:(int, int?)*/.Item2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "new ValueTuple<int, int?>()/*T:(int, int?)*/.Item2").WithLocation(7, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_Default_03() { var source = @"class Program { static void F() { (object, (object?, string)) t = default/*CT:(object!, (object?, string!))*/; (object, (object?, string)) u = t; t.Item1/*T:object?*/.ToString(); // 1 t.Item2.Item2/*T:string?*/.ToString(); // 2 u.Item1/*T:object?*/.ToString(); // 3 u.Item2.Item2/*T:string?*/.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // t.Item1/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.Item2/*T:string?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2.Item2").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // u.Item1/*T:object?*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.Item2/*T:string?*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2.Item2").WithLocation(10, 9)); comp.VerifyTypes(); } [Fact] public void Tuple_Default_04() { var source = @"class Program { static void F() { (int, int?) t = default/*CT:(int, int?)*/; (int, int?) u = t; _ = t.Item2.Value; // 1 _ = u.Item2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8629: Nullable value type may be null. // _ = t.Item2.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t.Item2").WithLocation(7, 13), // (8,13): warning CS8629: Nullable value type may be null. // _ = u.Item2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "u.Item2").WithLocation(8, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_Default_05() { var source = @"using System; class Program { static void F1() { var t = new ValueTuple<object, ValueTuple<object?, string>>()/*T:(object!, (object?, string!))*/; var u = t; t.Item1/*T:object?*/.ToString(); // 1 t.Item2.Item2/*T:string?*/.ToString(); // 2 u.Item1/*T:object?*/.ToString(); // 3 u.Item2.Item2/*T:string?*/.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.Item1/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.Item2/*T:string?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2.Item2").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.Item1/*T:object?*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.Item2.Item2/*T:string?*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2.Item2").WithLocation(11, 9)); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_Default_06() { var source = @"using System; class Program { static void F1() { var t = new ValueTuple<int, int?>()/*T:(int, int?)*/; var u = t; _ = t.Item2.Value; // 1 _ = u.Item2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8629: Nullable value type may be null. // _ = t.Item2.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t.Item2").WithLocation(8, 13), // (9,13): warning CS8629: Nullable value type may be null. // _ = u.Item2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "u.Item2").WithLocation(9, 13) ); comp.VerifyTypes(); } [Fact, WorkItem(33344, "https://github.com/dotnet/roslyn/issues/33344")] public void Tuple_Default_07() { var source = @" #nullable enable class C { void M() { (object?, string?) tuple = default/*CT:(object?, string?)*/; tuple.Item1.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // tuple.Item1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "tuple.Item1").WithLocation(8, 9)); comp.VerifyTypes(); } [Fact] public void Tuple_Default_NoType() { var source = @"class Program { static void F(object? x, bool b) { _ = (default, default)/*T:<null>!*/.Item1.ToString(); _ = (x, default)/*T:<null>!*/.Item2.ToString(); (b switch { _ => null }).ToString(); (b ? null : null).ToString(); (new()).ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,14): error CS8716: There is no target type for the default literal. // _ = (default, default)/*T:<null>!*/.Item1.ToString(); Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(5, 14), // (5,23): error CS8716: There is no target type for the default literal. // _ = (default, default)/*T:<null>!*/.Item1.ToString(); Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(5, 23), // (6,17): error CS8716: There is no target type for the default literal. // _ = (x, default)/*T:<null>!*/.Item2.ToString(); Diagnostic(ErrorCode.ERR_DefaultLiteralNoTargetType, "default").WithLocation(6, 17), // (7,12): error CS8506: No best type was found for the switch expression. // (b switch { _ => null }).ToString(); Diagnostic(ErrorCode.ERR_SwitchExpressionNoBestType, "switch").WithLocation(7, 12), // (8,10): error CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and '<null>' // (b ? null : null).ToString(); Diagnostic(ErrorCode.ERR_InvalidQM, "b ? null : null").WithArguments("<null>", "<null>").WithLocation(8, 10), // (9,10): error CS8754: There is no target type for 'new()' // (new()).ToString(); Diagnostic(ErrorCode.ERR_ImplicitObjectCreationNoTargetType, "new()").WithArguments("new()").WithLocation(9, 10) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_ParameterDefaultValue_01() { var source = @"class Program { static void F<T, U, V>((T x, U y, V? z) t = default) where U : class where V : struct { var u = t/*T:(T x, U! y, V? z)*/; t.x/*T:T*/.ToString(); // 1 t.y/*T:U?*/.ToString(); // 2 _ = t.z/*T:V?*/.Value; // 3 u.x/*T:T*/.ToString(); // 4 u.y/*T:U?*/.ToString(); // 5 _ = u.z/*T:V?*/.Value; // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.x/*T:T*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.x").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.y/*T:U?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.y").WithLocation(9, 9), // (10,13): warning CS8629: Nullable value type may be null. // _ = t.z/*T:V?*/.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t.z").WithLocation(10, 13), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.x/*T:T*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.x").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // u.y/*T:U?*/.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.y").WithLocation(12, 9), // (13,13): warning CS8629: Nullable value type may be null. // _ = u.z/*T:V?*/.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "u.z").WithLocation(13, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(30731, "https://github.com/dotnet/roslyn/issues/30731")] public void Tuple_ParameterDefaultValue_02() { var source = @"class Program { static void F<T, U, V>( (T, U, V?) x = new System.ValueTuple<T, U, V?>(), (T, U, V?) y = null, (T, U, V?) z = (default(T), new U(), new V())) where U : class, new() where V : struct { x.Item1/*T:T*/.ToString(); // 1 x.Item2/*T:U?*/.ToString(); // 2 _ = x.Item3/*T:V?*/.Value; // 3 y.Item1/*T:T*/.ToString(); // 4 y.Item2/*T:U!*/.ToString(); _ = y.Item3/*T:V?*/.Value; // 5 z.Item1/*T:T*/.ToString(); // 6 z.Item2/*T:U!*/.ToString(); _ = z.Item3/*T:V?*/.Value; // 7 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): error CS1750: A value of type '<null>' cannot be used as a default parameter because there are no standard conversions to type '(T, U, V?)' // (T, U, V?) y = null, Diagnostic(ErrorCode.ERR_NoConversionForDefaultParam, "y").WithArguments("<null>", "(T, U, V?)").WithLocation(5, 20), // (6,24): error CS1736: Default parameter value for 'z' must be a compile-time constant // (T, U, V?) z = (default(T), new U(), new V())) Diagnostic(ErrorCode.ERR_DefaultValueMustBeConstant, "(default(T), new U(), new V())").WithArguments("z").WithLocation(6, 24), // (6,24): warning CS8619: Nullability of reference types in value of type '(T?, U, V?)' doesn't match target type '(T, U, V?)'. // (T, U, V?) z = (default(T), new U(), new V())) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default(T), new U(), new V())").WithArguments("(T?, U, V?)", "(T, U, V?)").WithLocation(6, 24), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.Item1/*T:T*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Item1").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // x.Item2/*T:U?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Item2").WithLocation(11, 9), // (12,13): warning CS8629: Nullable value type may be null. // _ = x.Item3/*T:V?*/.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x.Item3").WithLocation(12, 13), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.Item1/*T:T*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Item1").WithLocation(13, 9), // (15,13): warning CS8629: Nullable value type may be null. // _ = y.Item3/*T:V?*/.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y.Item3").WithLocation(15, 13), // (16,9): warning CS8602: Dereference of a possibly null reference. // z.Item1/*T:T*/.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.Item1").WithLocation(16, 9), // (18,13): warning CS8629: Nullable value type may be null. // _ = z.Item3/*T:V?*/.Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "z.Item3").WithLocation(18, 13) ); comp.VerifyTypes(); } [Fact] public void Tuple_Constructor() { var source = @"class C { C((string x, string? y) t) { } static void M(string x, string? y) { C c; c = new C((x, x)); c = new C((x, y)); c = new C((y, x)); // 1 c = new C((y, y)); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,19): warning CS8620: Nullability of reference types in argument of type '(string? y, string x)' doesn't match target type '(string x, string? y)' for parameter 't' in 'C.C((string x, string? y) t)'. // c = new C((y, x)); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, x)").WithArguments("(string? y, string x)", "(string x, string? y)", "t", "C.C((string x, string? y) t)").WithLocation(9, 19), // (10,19): warning CS8620: Nullability of reference types in argument of type '(string?, string?)' doesn't match target type '(string x, string? y)' for parameter 't' in 'C.C((string x, string? y) t)'. // c = new C((y, y)); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, y)").WithArguments("(string?, string?)", "(string x, string? y)", "t", "C.C((string x, string? y) t)").WithLocation(10, 19)); } [Fact] public void Tuple_Indexer() { var source = @"class C { object? this[(string x, string? y) t] => null; static void M(string x, string? y) { var c = new C(); object? o; o = c[(x, x)]; o = c[(x, y)]; o = c[(y, x)]; // 1 o = c[(y, y)]; // 2 var t = (y, x); o = c[t]; // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,15): warning CS8620: Nullability of reference types in argument of type '(string? y, string x)' doesn't match target type '(string x, string? y)' for parameter 't' in 'object? C.this[(string x, string? y) t]'. // o = c[(y, x)]; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, x)").WithArguments("(string? y, string x)", "(string x, string? y)", "t", "object? C.this[(string x, string? y) t]").WithLocation(10, 15), // (11,15): warning CS8620: Nullability of reference types in argument of type '(string?, string?)' doesn't match target type '(string x, string? y)' for parameter 't' in 'object? C.this[(string x, string? y) t]'. // o = c[(y, y)]; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, y)").WithArguments("(string?, string?)", "(string x, string? y)", "t", "object? C.this[(string x, string? y) t]").WithLocation(11, 15), // (13,15): warning CS8620: Nullability of reference types in argument of type '(string? y, string x)' doesn't match target type '(string x, string? y)' for parameter 't' in 'object? C.this[(string x, string? y) t]'. // o = c[t]; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "t").WithArguments("(string? y, string x)", "(string x, string? y)", "t", "object? C.this[(string x, string? y) t]").WithLocation(13, 15)); } [Fact] public void Tuple_CollectionInitializer() { var source = @"using System.Collections.Generic; class C { static void M(string x, string? y) { var c = new List<(string, string?)> { (x, x), (x, y), (y, x), // 1 (y, y), // 2 }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8620: Nullability of reference types in argument of type '(string? y, string x)' doesn't match target type '(string, string?)' for parameter 'item' in 'void List<(string, string?)>.Add((string, string?) item)'. // (y, x), // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, x)").WithArguments("(string? y, string x)", "(string, string?)", "item", "void List<(string, string?)>.Add((string, string?) item)").WithLocation(10, 13), // (11,13): warning CS8620: Nullability of reference types in argument of type '(string?, string?)' doesn't match target type '(string, string?)' for parameter 'item' in 'void List<(string, string?)>.Add((string, string?) item)'. // (y, y), // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "(y, y)").WithArguments("(string?, string?)", "(string, string?)", "item", "void List<(string, string?)>.Add((string, string?) item)").WithLocation(11, 13)); } [Fact] public void Tuple_Method() { var source = @"class C { static void F(object? x, object? y) { if (x == null) return; (x, y).ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Tuple_OtherMembers_01() { var source = @"internal delegate T D<T>(); namespace System { public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) { Item1 = item1; Item2 = item2; F1 = item1; E2 = null; } public T1 Item1; public T2 Item2; internal T1 F1; internal T1 P1 => Item1; internal event D<T2>? E2; } } class C { static void F(object? x) { var y = (x, x); y.F1.ToString(); // 1 y.P1.ToString(); // 2 y.E2?.Invoke().ToString(); // 3 if (x == null) return; var z = (x, x); z.F1.ToString(); z.P1.ToString(); z.E2?.Invoke().ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), targetFramework: TargetFramework.Mscorlib46); comp.VerifyDiagnostics( // (27,11): error CS0070: The event '(object, object).E2' can only appear on the left hand side of += or -= (except when used from within the type '(object, object)') // y.E2?.Invoke().ToString(); // 3 Diagnostic(ErrorCode.ERR_BadEventUsage, "E2").WithArguments("(object, object).E2", "(object, object)").WithLocation(27, 11), // (32,11): error CS0070: The event '(object, object).E2' can only appear on the left hand side of += or -= (except when used from within the type '(object, object)') // z.E2?.Invoke().ToString(); Diagnostic(ErrorCode.ERR_BadEventUsage, "E2").WithArguments("(object, object).E2", "(object, object)").WithLocation(32, 11), // (25,9): warning CS8602: Dereference of a possibly null reference. // y.F1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F1").WithLocation(25, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // y.P1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.P1").WithLocation(26, 9)); } [Fact] public void Tuple_OtherMembers_02() { // https://github.com/dotnet/roslyn/issues/33578 // Cannot test Derived<T> since tuple types are considered sealed and the base type // is dropped: "error CS0509: 'Derived<T>': cannot derive from sealed type '(T, T)'". var source = @"namespace System { public class Base<T> { public Base(T t) { F = t; } public T F; } public class ValueTuple<T1, T2> : Base<T1> { public ValueTuple(T1 item1, T2 item2) : base(item1) { Item1 = item1; Item2 = item2; } public T1 Item1; public T2 Item2; } //public class Derived<T> : ValueTuple<T, T> //{ // public Derived(T t) : base(t, t) { } // public T P { get; set; } //} } class C { static void F(object? x) { var y = (x, x); y.F.ToString(); // 1 y.Item2.ToString(); // 2 if (x == null) return; var z = (x, x); z.F.ToString(); z.Item2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), targetFramework: TargetFramework.Mscorlib46); comp.VerifyDiagnostics( // (29,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // y.Item2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Item2").WithLocation(30, 9)); } [Fact] public void Tuple_OtherMembers_03() { var source = @"namespace System { public class Object { public string ToString() => throw null!; public object? F; } public class String { } public abstract class ValueType { public object? P { get; set; } } public struct Void { } public struct Boolean { } public struct Enum { } public class Attribute { } public struct Int32 { } public class Exception { } public class AttributeUsageAttribute : Attribute { public AttributeUsageAttribute(AttributeTargets validOn) => throw null!; public bool AllowMultiple { get; set; } } public enum AttributeTargets { Assembly = 1, Module = 2, Class = 4, Struct = 8, Enum = 16, Constructor = 32, Method = 64, Property = 128, Field = 256, Event = 512, Interface = 1024, Parameter = 2048, Delegate = 4096, ReturnValue = 8192, GenericParameter = 16384, All = 32767 } public class ObsoleteAttribute : Attribute { public ObsoleteAttribute(string message) => throw null!; } public struct ValueTuple<T1, T2> { public ValueTuple(T1 item1, T2 item2) => throw null; } } class C { static void M(object x) { var y = (x, x); y.F.ToString(); y.P.ToString(); } }"; var comp = CreateEmptyCompilation(source); comp.VerifyDiagnostics( // (6,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public object? F; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 22), // (11,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public object? P { get; set; } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 22) ); var comp2 = CreateEmptyCompilation(new[] { source }, options: WithNullableEnable()); comp2.VerifyDiagnostics( // (36,22): warning CS8597: Thrown value may be null. // => throw null; Diagnostic(ErrorCode.WRN_ThrowPossibleNull, "null").WithLocation(36, 22), // (45,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(45, 9), // (46,9): warning CS8602: Dereference of a possibly null reference. // y.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.P").WithLocation(46, 9)); } [Fact] public void TypeInference_TupleNameDifferences_01() { var source = @"class C<T> { } static class E { public static T F<T>(this C<T> c, T t) => t; } class C { static void F(object o) { var c = new C<(object x, int y)>(); c.F((o, -1)).x.ToString(); } }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics( // (13,22): error CS1061: '(object, int)' does not contain a definition for 'x' and no extension method 'x' accepting a first argument of type '(object, int)' could be found (are you missing a using directive or an assembly reference?) // c.F((o, -1)).x.ToString(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "x").WithArguments("(object, int)", "x").WithLocation(13, 22)); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,22): error CS1061: '(object, int)' does not contain a definition for 'x' and no extension method 'x' accepting a first argument of type '(object, int)' could be found (are you missing a using directive or an assembly reference?) // c.F((o, -1)).x.ToString(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "x").WithArguments("(object, int)", "x").WithLocation(13, 22)); } [Fact] public void TypeInference_TupleNameDifferences_02() { var source = @"class C<T> { } static class E { public static T F<T>(this C<T> c, T t) => t; } class C { static void F(object o) { var c = new C<(object? x, int y)>(); c.F((o, -1))/*T:(object?, int)*/.x.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,42): error CS1061: '(object, int)' does not contain a definition for 'x' and no accessible extension method 'x' accepting a first argument of type '(object, int)' could be found (are you missing a using directive or an assembly reference?) // c.F((o, -1))/*T:(object?, int)*/.x.ToString(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "x").WithArguments("(object, int)", "x").WithLocation(13, 42)); comp.VerifyTypes(); } [Fact] public void TypeInference_DynamicDifferences_01() { var source = @"class C<T> { } static class E { public static T F<T>(this C<T> c, T t) => t; } class C { static void F(dynamic x, object y) { var c = new C<(object, object)>(); c.F((x, y))/*T:(dynamic!, object!)*/.Item1.G(); } }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void TypeInference_DynamicDifferences_02() { var source = @"class C<T> { } static class E { public static T F<T>(this C<T> c, T t) => t; } class C { static void F(dynamic x, object y) { var c = new C<(object, object?)>(); c.F((x, y))/*T:(dynamic!, object?)*/.Item1.G(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } // Assert failure in ConversionsBase.IsValidExtensionMethodThisArgConversion. [WorkItem(22317, "https://github.com/dotnet/roslyn/issues/22317")] [Fact(Skip = "22317")] public void TypeInference_DynamicDifferences_03() { var source = @"interface I<T> { } static class E { public static T F<T>(this I<T> i, T t) => t; } class C { static void F(I<object> i, dynamic? d) { i.F(d).G(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): error CS1929: 'I<object>' does not contain a definition for 'F' and the best extension method overload 'E.F<T>(I<T>, T)' requires a receiver of type 'I<T>' // i.F(d).G(); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "i").WithArguments("I<object>", "F", "E.F<T>(I<T>, T)", "I<T>").WithLocation(12, 9)); } [Fact] public void NullableConversionAndNullCoalescingOperator_01() { var source = @"#pragma warning disable 0649 struct S { short F; static ushort G(S? s) { return (ushort)(s?.F ?? 0); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableConversionAndNullCoalescingOperator_02() { var source = @"struct S { public static implicit operator int(S s) => 0; } class P { static int F(S? x, int y) => x ?? y; static int G(S x, int? y) => y ?? x; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ConstrainedToTypeParameter_01() { var source = @"class C<T, U> where U : T { }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ConstrainedToTypeParameter_02() { var source = @"class C<T> where T : C<T> { }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ArrayElementConversion() { var source = @"class C { static object F() => new sbyte[] { -1 }; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void TrackNonNullableLocals() { var source = @"class C { static void F(object x) { object y = x; x.ToString(); // 1 y.ToString(); // 2 x = null; y = x; x.ToString(); // 3 y.ToString(); // 4 x = null; y = x; if (x == null) return; if (y == null) return; x.ToString(); // 5 y.ToString(); // 6 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(8, 13), // (9,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(9, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 9), // (12,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 13), // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(13, 13)); } [Fact] public void TrackNonNullableFieldsAndProperties() { var source = @"#pragma warning disable 8618 class C { object F; object P { get; set; } static void M(C c) { c.F.ToString(); // 1 c.P.ToString(); // 2 c.F = null; c.P = null; c.F.ToString(); // 3 c.P.ToString(); // 4 if (c.F == null) return; if (c.P == null) return; c.F.ToString(); // 5 c.P.ToString(); // 6 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.F = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 15), // (11,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.P = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 15), // (12,9): warning CS8602: Dereference of a possibly null reference. // c.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(13, 9)); } [Fact] public void TrackNonNullableFields_ObjectInitializer() { var source = @"class C<T> { internal T F = default!; } class Program { static void F1(object? x1) { C<object> c1; c1 = new C<object>() { F = x1 }; // 1 c1 = new C<object>() { F = c1.F }; // 2 c1.F.ToString(); // 3 } static void F2<T>() { C<T> c2; c2 = new C<T>() { F = default }; // 4 c2 = new C<T>() { F = c2.F }; // 5 c2.F.ToString(); // 6 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,36): warning CS8601: Possible null reference assignment. // c1 = new C<object>() { F = x1 }; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x1").WithLocation(10, 36), // (11,36): warning CS8601: Possible null reference assignment. // c1 = new C<object>() { F = c1.F }; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c1.F").WithLocation(11, 36), // (12,9): warning CS8602: Dereference of a possibly null reference. // c1.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.F").WithLocation(12, 9), // (17,31): warning CS8601: Possible null reference assignment. // c2 = new C<T>() { F = default }; // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(17, 31), // (18,31): warning CS8601: Possible null reference assignment. // c2 = new C<T>() { F = c2.F }; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c2.F").WithLocation(18, 31), // (19,9): warning CS8602: Dereference of a possibly null reference. // c2.F.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2.F").WithLocation(19, 9)); } [Fact] public void TrackUnannotatedFieldsAndProperties() { var source0 = @"public class C { public object F; public object P { get; set; } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var source1 = @"class P { static void M(C c, object? o) { c.F.ToString(); c.P.ToString(); c.F = o; c.P = o; c.F.ToString(); // 1 c.P.ToString(); // 2 c.F = o; c.P = o; if (c.F == null) return; if (c.P == null) return; c.F.ToString(); c.P.ToString(); } }"; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { comp0.EmitToImageReference() }); comp1.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.P").WithLocation(10, 9)); } /// <summary> /// Assignment warnings for local and parameters should be distinct from /// fields and properties because the former may be warnings from legacy /// method bodies and it should be possible to disable those warnings separately. /// </summary> [Fact] public void AssignmentWarningsDistinctForLocalsAndParameters() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C { internal object F; internal object P { get; set; } } class P { static void F(out object? x) { x = null; } static void Local() { object? y = null; object x1 = null; x1 = y; F(out x1); } static void Parameter(object x2) { object? y = null; x2 = null; x2 = y; F(out x2); } static void OutParameter(out object x3) { object? y = null; x3 = null; x3 = y; F(out x3); } static void RefParameter(ref object x4) { object? y = null; x4 = null; x4 = y; F(out x4); } static void Field() { var c = new C(); object? y = null; c.F = null; c.F = y; F(out c.F); } static void Property() { var c = new C(); object? y = null; c.P = null; c.P = y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object x1 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(17, 21), // (18,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = y; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(18, 14), // (19,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(out x1); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x1").WithLocation(19, 15), // (24,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(24, 14), // (25,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x2 = y; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(25, 14), // (26,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // F(out x2); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(26, 15), // (31,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // x3 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(31, 14), // (32,14): warning CS8601: Possible null reference assignment. // x3 = y; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(32, 14), // (33,15): warning CS8601: Possible null reference assignment. // F(out x3); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x3").WithLocation(33, 15), // (38,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // x4 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(38, 14), // (39,14): warning CS8601: Possible null reference assignment. // x4 = y; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(39, 14), // (40,15): warning CS8601: Possible null reference assignment. // F(out x4); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x4").WithLocation(40, 15), // (46,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.F = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(46, 15), // (47,15): warning CS8601: Possible null reference assignment. // c.F = y; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(47, 15), // (48,15): warning CS8601: Possible null reference assignment. // F(out c.F); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c.F").WithLocation(48, 15), // (54,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.P = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(54, 15), // (55,15): warning CS8601: Possible null reference assignment. // c.P = y; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(55, 15)); } /// <summary> /// Explicit cast does not cast away top-level nullability. /// </summary> [Fact] public void ExplicitCast() { var source = @"#pragma warning disable 0649 class A<T> { internal T F; } class B1 : A<string> { } class B2 : A<string?> { } class C { static void F0() { ((A<string>)null).F.ToString(); ((A<string>?)null).F.ToString(); ((A<string?>)default).F.ToString(); ((A<string?>?)default).F.ToString(); } static void F1(A<string> x1, A<string>? y1) { ((B2?)x1).F.ToString(); ((B2)y1).F.ToString(); } static void F2(B1 x2, B1? y2) { ((A<string?>?)x2).F.ToString(); ((A<string?>)y2).F.ToString(); } static void F3(A<string?> x3, A<string?>? y3) { ((B2?)x3).F.ToString(); ((B2)y3).F.ToString(); } static void F4(B2 x4, B2? y4) { ((A<string>?)x4).F.ToString(); ((A<string>)y4).F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,16): warning CS8618: Non-nullable field 'F' is uninitialized. Consider declaring the field as nullable. // internal T F; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "F").WithArguments("field", "F").WithLocation(4, 16), // (12,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((A<string>)null).F.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(A<string>)null").WithLocation(12, 10), // (12,10): warning CS8602: Dereference of a possibly null reference. // ((A<string>)null).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string>)null").WithLocation(12, 10), // (13,10): warning CS8602: Dereference of a possibly null reference. // ((A<string>?)null).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string>?)null").WithLocation(13, 10), // (14,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((A<string?>)default).F.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(A<string?>)default").WithLocation(14, 10), // (14,10): warning CS8602: Dereference of a possibly null reference. // ((A<string?>)default).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string?>)default").WithLocation(14, 10), // (14,9): warning CS8602: Dereference of a possibly null reference. // ((A<string?>)default).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((A<string?>)default).F").WithLocation(14, 9), // (15,10): warning CS8602: Dereference of a possibly null reference. // ((A<string?>?)default).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string?>?)default").WithLocation(15, 10), // (15,9): warning CS8602: Dereference of a possibly null reference. // ((A<string?>?)default).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((A<string?>?)default).F").WithLocation(15, 9), // (19,10): warning CS8619: Nullability of reference types in value of type 'A<string>' doesn't match target type 'B2'. // ((B2?)x1).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B2?)x1").WithArguments("A<string>", "B2").WithLocation(19, 10), // (19,10): warning CS8602: Dereference of a possibly null reference. // ((B2?)x1).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(B2?)x1").WithLocation(19, 10), // (19,9): warning CS8602: Dereference of a possibly null reference. // ((B2?)x1).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((B2?)x1).F").WithLocation(19, 9), // (20,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((B2)y1).F.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B2)y1").WithLocation(20, 10), // (20,10): warning CS8619: Nullability of reference types in value of type 'A<string>' doesn't match target type 'B2'. // ((B2)y1).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B2)y1").WithArguments("A<string>", "B2").WithLocation(20, 10), // (20,10): warning CS8602: Dereference of a possibly null reference. // ((B2)y1).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(B2)y1").WithLocation(20, 10), // (20,9): warning CS8602: Dereference of a possibly null reference. // ((B2)y1).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((B2)y1).F").WithLocation(20, 9), // (24,10): warning CS8619: Nullability of reference types in value of type 'B1' doesn't match target type 'A<string?>'. // ((A<string?>?)x2).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<string?>?)x2").WithArguments("B1", "A<string?>").WithLocation(24, 10), // (24,10): warning CS8602: Dereference of a possibly null reference. // ((A<string?>?)x2).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string?>?)x2").WithLocation(24, 10), // (24,9): warning CS8602: Dereference of a possibly null reference. // ((A<string?>?)x2).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((A<string?>?)x2).F").WithLocation(24, 9), // (25,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((A<string?>)y2).F.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(A<string?>)y2").WithLocation(25, 10), // (25,10): warning CS8619: Nullability of reference types in value of type 'B1' doesn't match target type 'A<string?>'. // ((A<string?>)y2).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<string?>)y2").WithArguments("B1", "A<string?>").WithLocation(25, 10), // (25,10): warning CS8602: Dereference of a possibly null reference. // ((A<string?>)y2).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string?>)y2").WithLocation(25, 10), // (25,9): warning CS8602: Dereference of a possibly null reference. // ((A<string?>)y2).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((A<string?>)y2).F").WithLocation(25, 9), // (29,10): warning CS8602: Dereference of a possibly null reference. // ((B2?)x3).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(B2?)x3").WithLocation(29, 10), // (29,9): warning CS8602: Dereference of a possibly null reference. // ((B2?)x3).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((B2?)x3).F").WithLocation(29, 9), // (30,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((B2)y3).F.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B2)y3").WithLocation(30, 10), // (30,10): warning CS8602: Dereference of a possibly null reference. // ((B2)y3).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(B2)y3").WithLocation(30, 10), // (30,9): warning CS8602: Dereference of a possibly null reference. // ((B2)y3).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((B2)y3).F").WithLocation(30, 9), // (34,10): warning CS8619: Nullability of reference types in value of type 'B2' doesn't match target type 'A<string>'. // ((A<string>?)x4).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<string>?)x4").WithArguments("B2", "A<string>").WithLocation(34, 10), // (34,10): warning CS8602: Dereference of a possibly null reference. // ((A<string>?)x4).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string>?)x4").WithLocation(34, 10), // (35,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((A<string>)y4).F.ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(A<string>)y4").WithLocation(35, 10), // (35,10): warning CS8619: Nullability of reference types in value of type 'B2' doesn't match target type 'A<string>'. // ((A<string>)y4).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<string>)y4").WithArguments("B2", "A<string>").WithLocation(35, 10), // (35,10): warning CS8602: Dereference of a possibly null reference. // ((A<string>)y4).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(A<string>)y4").WithLocation(35, 10) ); } [Fact] public void ExplicitCast_NestedNullability_01() { var source = @"class A<T> { } class B<T> : A<T> { } class C { static void F1(A<object> x1, A<object?> y1) { object o; o = (B<object>)x1; o = (B<object?>)x1; // 1 o = (B<object>)y1; // 2 o = (B<object?>)y1; } static void F2(B<object> x2, B<object?> y2) { object o; o = (A<object>)x2; o = (A<object?>)x2; // 3 o = (A<object>)y2; // 4 o = (A<object?>)y2; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'B<object?>'. // o = (B<object?>)x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<object?>)x1").WithArguments("A<object>", "B<object?>").WithLocation(9, 13), // (10,13): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'B<object>'. // o = (B<object>)y1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<object>)y1").WithArguments("A<object?>", "B<object>").WithLocation(10, 13), // (17,13): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'A<object?>'. // o = (A<object?>)x2; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<object?>)x2").WithArguments("B<object>", "A<object?>").WithLocation(17, 13), // (18,13): warning CS8619: Nullability of reference types in value of type 'B<object?>' doesn't match target type 'A<object>'. // o = (A<object>)y2; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<object>)y2").WithArguments("B<object?>", "A<object>").WithLocation(18, 13)); } [Fact] public void ExplicitCast_NestedNullability_02() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class A<T> : I<T> { } class B<T> : IIn<T> { } class C<T> : IOut<T> { } class D { static void F1(A<object> x1, A<object?> y1) { object o; o = (I<object>)x1; o = (I<object?>)x1; o = (I<object>)y1; o = (I<object?>)y1; } static void F2(I<object> x2, I<object?> y2) { object o; o = (A<object>)x2; o = (A<object?>)x2; o = (A<object>)y2; o = (A<object?>)y2; } static void F3(B<object> x3, B<object?> y3) { object o; o = (IIn<object>)x3; o = (IIn<object?>)x3; o = (IIn<object>)y3; o = (IIn<object?>)y3; } static void F4(IIn<object> x4, IIn<object?> y4) { object o; o = (B<object>)x4; o = (B<object?>)x4; o = (B<object>)y4; o = (B<object?>)y4; } static void F5(C<object> x5, C<object?> y5) { object o; o = (IOut<object>)x5; o = (IOut<object?>)x5; o = (IOut<object>)y5; o = (IOut<object?>)y5; } static void F6(IOut<object> x6, IOut<object?> y6) { object o; o = (C<object>)x6; o = (C<object?>)x6; o = (C<object>)y6; o = (C<object?>)y6; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ExplicitCast_NestedNullability_03() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } sealed class A<T> : I<T> { } sealed class B<T> : IIn<T> { } sealed class C<T> : IOut<T> { } class D { static void F1(A<object> x1, A<object?> y1) { object o; o = (I<object>)x1; o = (I<object?>)x1; // 1 o = (I<object>)y1; // 2 o = (I<object?>)y1; } static void F2(I<object> x2, I<object?> y2) { object o; o = (A<object>)x2; o = (A<object?>)x2; // 3 o = (A<object>)y2; // 4 o = (A<object?>)y2; } static void F3(B<object> x3, B<object?> y3) { object o; o = (IIn<object>)x3; o = (IIn<object?>)x3; // 5 o = (IIn<object>)y3; o = (IIn<object?>)y3; } static void F4(IIn<object> x4, IIn<object?> y4) { object o; o = (B<object>)x4; o = (B<object?>)x4; o = (B<object>)y4; // 6 o = (B<object?>)y4; } static void F5(C<object> x5, C<object?> y5) { object o; o = (IOut<object>)x5; o = (IOut<object?>)x5; o = (IOut<object>)y5; // 7 o = (IOut<object?>)y5; } static void F6(IOut<object> x6, IOut<object?> y6) { object o; o = (C<object>)x6; o = (C<object?>)x6; // 8 o = (C<object>)y6; o = (C<object?>)y6; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'I<object?>'. // o = (I<object?>)x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(I<object?>)x1").WithArguments("A<object>", "I<object?>").WithLocation(13, 13), // (14,13): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'I<object>'. // o = (I<object>)y1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(I<object>)y1").WithArguments("A<object?>", "I<object>").WithLocation(14, 13), // (21,13): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'A<object?>'. // o = (A<object?>)x2; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<object?>)x2").WithArguments("I<object>", "A<object?>").WithLocation(21, 13), // (22,13): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'A<object>'. // o = (A<object>)y2; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<object>)y2").WithArguments("I<object?>", "A<object>").WithLocation(22, 13), // (29,13): warning CS8619: Nullability of reference types in value of type 'B<object>' doesn't match target type 'IIn<object?>'. // o = (IIn<object?>)x3; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(IIn<object?>)x3").WithArguments("B<object>", "IIn<object?>").WithLocation(29, 13), // (38,13): warning CS8619: Nullability of reference types in value of type 'IIn<object?>' doesn't match target type 'B<object>'. // o = (B<object>)y4; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<object>)y4").WithArguments("IIn<object?>", "B<object>").WithLocation(38, 13), // (46,13): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'IOut<object>'. // o = (IOut<object>)y5; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(IOut<object>)y5").WithArguments("C<object?>", "IOut<object>").WithLocation(46, 13), // (53,13): warning CS8619: Nullability of reference types in value of type 'IOut<object>' doesn't match target type 'C<object?>'. // o = (C<object?>)x6; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(C<object?>)x6").WithArguments("IOut<object>", "C<object?>").WithLocation(53, 13)); } [Fact] [WorkItem(35334, "https://github.com/dotnet/roslyn/issues/35334")] public void ExplicitCast_UserDefined_01() { var source = @"class A1 { public static implicit operator B?(A1? a) => new B(); } class A2 { public static implicit operator B?(A2 a) => new B(); } class A3 { public static implicit operator B(A3? a) => new B(); } class A4 { public static implicit operator B(A4 a) => new B(); } class B { } class C { static bool flag; static void F1(A1? x1, A1 y1) { B? b; if (flag) b = ((B)x1)/*T:B?*/; if (flag) b = ((B?)x1)/*T:B?*/; if (flag) b = ((B)y1)/*T:B?*/; if (flag) b = ((B?)y1)/*T:B?*/; } static void F2(A2? x2, A2 y2) { B? b; if (flag) b = ((B)x2)/*T:B?*/; if (flag) b = ((B?)x2)/*T:B?*/; if (flag) b = ((B)y2)/*T:B?*/; if (flag) b = ((B?)y2)/*T:B?*/; } static void F3(A3? x3, A3 y3) { B? b; if (flag) b = ((B)x3)/*T:B!*/; if (flag) b = ((B?)x3)/*T:B?*/; if (flag) b = ((B)y3)/*T:B!*/; if (flag) b = ((B?)y3)/*T:B?*/; } static void F4(A4? x4, A4 y4) { B? b; if (flag) b = ((B)x4)/*T:B!*/; if (flag) b = ((B?)x4)/*T:B?*/; if (flag) b = ((B)y4)/*T:B!*/; if (flag) b = ((B?)y4)/*T:B?*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (24,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (flag) b = ((B)x1)/*T:B?*/; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)x1").WithLocation(24, 24), // (26,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (flag) b = ((B)y1)/*T:B?*/; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)y1").WithLocation(26, 24), // (32,27): warning CS8604: Possible null reference argument for parameter 'a' in 'A2.implicit operator B?(A2 a)'. // if (flag) b = ((B)x2)/*T:B?*/; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("a", "A2.implicit operator B?(A2 a)").WithLocation(32, 27), // (32,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (flag) b = ((B)x2)/*T:B?*/; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)x2").WithLocation(32, 24), // (33,28): warning CS8604: Possible null reference argument for parameter 'a' in 'A2.implicit operator B?(A2 a)'. // if (flag) b = ((B?)x2)/*T:B?*/; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("a", "A2.implicit operator B?(A2 a)").WithLocation(33, 28), // (34,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (flag) b = ((B)y2)/*T:B?*/; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(B)y2").WithLocation(34, 24), // (48,27): warning CS8604: Possible null reference argument for parameter 'a' in 'A4.implicit operator B(A4 a)'. // if (flag) b = ((B)x4)/*T:B!*/; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x4").WithArguments("a", "A4.implicit operator B(A4 a)").WithLocation(48, 27), // (49,28): warning CS8604: Possible null reference argument for parameter 'a' in 'A4.implicit operator B(A4 a)'. // if (flag) b = ((B?)x4)/*T:B?*/; Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x4").WithArguments("a", "A4.implicit operator B(A4 a)").WithLocation(49, 28), // (20,17): warning CS0649: Field 'C.flag' is never assigned to, and will always have its default value false // static bool flag; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "flag").WithArguments("C.flag", "false").WithLocation(20, 17)); comp.VerifyTypes(); } [Fact] public void ExplicitCast_UserDefined_02() { var source = @"class A<T> where T : class? { } class B { public static implicit operator A<string?>(B b) => throw null!; } class C { public static implicit operator A<string>(C c) => throw null!; static void F1(B x1) { var y1 = (A<string?>)x1; var z1 = (A<string>)x1; // 1 } static void F2(C x2) { var y2 = (A<string?>)x2; // 2 var z2 = (A<string>)x2; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,18): warning CS8619: Nullability of reference types in value of type 'A<string?>' doesn't match target type 'A<string>'. // var z1 = (A<string>)x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<string>)x1").WithArguments("A<string?>", "A<string>").WithLocation(14, 18), // (18,18): warning CS8619: Nullability of reference types in value of type 'A<string>' doesn't match target type 'A<string?>'. // var y2 = (A<string?>)x2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(A<string?>)x2").WithArguments("A<string>", "A<string?>").WithLocation(18, 18)); } [Fact] public void ExplicitCast_UserDefined_03() { var source = @"class A1<T> where T : class { public static implicit operator B<T?>(A1<T> a) => throw null!; } class A2<T> where T : class { public static implicit operator B<T>(A2<T> a) => throw null!; } class B<T> { } class C<T> where T : class { static void F1(A1<T?> x1, A1<T> y1) { B<T?> x; B<T> y; x = ((B<T?>)x1)/*T:B<T?>!*/; y = ((B<T>)x1)/*T:B<T!>!*/; x = ((B<T?>)y1)/*T:B<T?>!*/; y = ((B<T>)y1)/*T:B<T!>!*/; } static void F2(A2<T?> x2, A2<T> y2) { B<T?> x; B<T> y; x = ((B<T?>)x2)/*T:B<T?>!*/; y = ((B<T>)x2)/*T:B<T!>!*/; x = ((B<T?>)y2)/*T:B<T?>!*/; y = ((B<T>)y2)/*T:B<T!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,27): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'A1<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // static void F1(A1<T?> x1, A1<T> y1) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "x1").WithArguments("A1<T>", "T", "T?").WithLocation(12, 27), // (17,14): warning CS8619: Nullability of reference types in value of type 'B<T?>' doesn't match target type 'B<T>'. // y = ((B<T>)x1)/*T:B<T!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<T>)x1").WithArguments("B<T?>", "B<T>").WithLocation(17, 14), // (19,14): warning CS8619: Nullability of reference types in value of type 'B<T?>' doesn't match target type 'B<T>'. // y = ((B<T>)y1)/*T:B<T!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<T>)y1").WithArguments("B<T?>", "B<T>").WithLocation(19, 14), // (21,27): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'A2<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // static void F2(A2<T?> x2, A2<T> y2) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "x2").WithArguments("A2<T>", "T", "T?").WithLocation(21, 27), // (26,14): warning CS8619: Nullability of reference types in value of type 'B<T?>' doesn't match target type 'B<T>'. // y = ((B<T>)x2)/*T:B<T!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<T>)x2").WithArguments("B<T?>", "B<T>").WithLocation(26, 14), // (27,14): warning CS8619: Nullability of reference types in value of type 'B<T>' doesn't match target type 'B<T?>'. // x = ((B<T?>)y2)/*T:B<T?>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(B<T?>)y2").WithArguments("B<T>", "B<T?>").WithLocation(27, 14)); comp.VerifyTypes(); } [Fact] public void ExplicitCast_StaticType() { var source = @"static class C { static object F(object? x) => (C)x; static object? G(object? y) => (C?)y; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,35): error CS0716: Cannot convert to static type 'C' // static object F(object? x) => (C)x; Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C)x").WithArguments("C").WithLocation(3, 35), // (3,35): warning CS8600: Converting null literal or possible null value to non-nullable type. // static object F(object? x) => (C)x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)x").WithLocation(3, 35), // (4,36): error CS0716: Cannot convert to static type 'C' // static object? G(object? y) => (C?)y; Diagnostic(ErrorCode.ERR_ConvertToStaticClass, "(C?)y").WithArguments("C").WithLocation(4, 36) ); } [Fact] public void ForEach_01() { var source = @"class Enumerable { public Enumerator GetEnumerator() => new Enumerator(); } class Enumerator { public object Current => throw null!; public bool MoveNext() => false; } class C { static void F(Enumerable e) { foreach (var x in e) x.ToString(); foreach (string y in e) y.ToString(); foreach (string? z in e) z.ToString(); // 1 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,13): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(19, 13)); } [Fact, WorkItem(40164, "https://github.com/dotnet/roslyn/issues/40164")] public void ForEach_02() { var source = @"class Enumerable { public Enumerator GetEnumerator() => new Enumerator(); } class Enumerator { public object? Current => throw null!; public bool MoveNext() => false; } class C { static void F(Enumerable e) { foreach (var x in e) x.ToString(); foreach (object y in e) y.ToString(); foreach (object? z in e) z.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 13), // (16,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (object y in e) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(16, 25), // (17,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(17, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(19, 13)); } [Fact, WorkItem(40164, "https://github.com/dotnet/roslyn/issues/40164")] public void ForEach_03() { var source = @"using System.Collections; namespace System { public class Object { public string ToString() => throw null!; } public abstract class ValueType { } public struct Void { } public struct Boolean { } public class String { } public struct Enum { } public class Attribute { } public struct Int32 { } public class AttributeUsageAttribute : Attribute { public AttributeUsageAttribute(AttributeTargets validOn) => throw null!; public bool AllowMultiple { get; set; } } public enum AttributeTargets { Assembly = 1, Module = 2, Class = 4, Struct = 8, Enum = 16, Constructor = 32, Method = 64, Property = 128, Field = 256, Event = 512, Interface = 1024, Parameter = 2048, Delegate = 4096, ReturnValue = 8192, GenericParameter = 16384, All = 32767 } public class ObsoleteAttribute : Attribute { public ObsoleteAttribute(string message) => throw null!; } public class Exception { } } namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { object? Current { get; } bool MoveNext(); } } class Enumerable : IEnumerable { IEnumerator IEnumerable.GetEnumerator() => throw null!; } class C { static void F(Enumerable e) { foreach (var x in e) x.ToString(); foreach (object y in e) y.ToString(); } static void G(IEnumerable e) { foreach (var z in e) z.ToString(); foreach (object w in e) w.ToString(); } }"; var comp = CreateEmptyCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (51,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(51, 13), // (52,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (object y in e) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(52, 25), // (53,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(53, 13), // (58,13): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(58, 13), // (59,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (object w in e) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "w").WithLocation(59, 25), // (60,13): warning CS8602: Dereference of a possibly null reference. // w.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w").WithLocation(60, 13)); } // z.ToString() should warn if IEnumerator.Current is annotated as `object?`. [Fact] public void ForEach_04() { var source = @"using System.Collections; using System.Collections.Generic; class C { static void F(IEnumerable<object?> cx, object?[] cy) { foreach (var x in cx) x.ToString(); foreach (object? y in cy) y.ToString(); foreach (object? z in (IEnumerable)cx) z.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13), // (10,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(10, 13)); } [Fact] public void ForEach_05() { var source = @"class C { static void F1(dynamic c) { foreach (var x in c) x.ToString(); foreach (object? y in c) y.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void ForEach_06() { var source = @"using System.Collections; using System.Collections.Generic; class C<T> : IEnumerable<T> where T : class { IEnumerator<T> IEnumerable<T>.GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } class P { static void F<T>(C<T?> c) where T : class { foreach (var x in c) x.ToString(); foreach (T? y in c) y.ToString(); foreach (T z in c) z.ToString(); foreach (object w in c) w.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,28): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // static void F<T>(C<T?> c) where T : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "c").WithArguments("C<T>", "T", "T?").WithLocation(10, 28), // (13,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(15, 13), // (16,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (T z in c) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z").WithLocation(16, 20), // (17,13): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(17, 13), // (18,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (object w in c) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "w").WithLocation(18, 25), // (19,13): warning CS8602: Dereference of a possibly null reference. // w.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w").WithLocation(19, 13)); } [Fact] public void ForEach_07() { var source = @"struct S<T> where T : class { public E<T> GetEnumerator() => new E<T>(); } struct E<T> where T : class { public T Current => throw null!; public bool MoveNext() => false; } class P { static void F1<T>() where T : class { foreach (var x1 in new S<T>()) x1.ToString(); foreach (T y1 in new S<T>()) y1.ToString(); foreach (T? z1 in new S<T>()) z1.ToString(); foreach (object? w1 in new S<T>()) w1.ToString(); } static void F2<T>() where T : class { foreach (var x2 in new S<T?>()) x2.ToString(); foreach (T y2 in new S<T?>()) y2.ToString(); foreach (T? z2 in new S<T?>()) z2.ToString(); foreach (object? w2 in new S<T?>()) w2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (25,34): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'S<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // foreach (var x2 in new S<T?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "T?").WithArguments("S<T>", "T", "T?").WithLocation(25, 34), // (26,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(26, 13), // (27,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (T y2 in new S<T?>()) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y2").WithLocation(27, 20), // (27,32): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'S<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // foreach (T y2 in new S<T?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "T?").WithArguments("S<T>", "T", "T?").WithLocation(27, 32), // (28,13): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(28, 13), // (29,33): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'S<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // foreach (T? z2 in new S<T?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "T?").WithArguments("S<T>", "T", "T?").WithLocation(29, 33), // (30,13): warning CS8602: Dereference of a possibly null reference. // z2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2").WithLocation(30, 13), // (31,38): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'S<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // foreach (object? w2 in new S<T?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "T?").WithArguments("S<T>", "T", "T?").WithLocation(31, 38), // (32,13): warning CS8602: Dereference of a possibly null reference. // w2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w2").WithLocation(32, 13)); } [Fact] public void ForEach_08() { var source = @"using System.Collections.Generic; interface I<T> { T P { get; } } interface IIn<in T> { } interface IOut<out T> { T P { get; } } static class C { static void F1(IEnumerable<I<object>> x1, IEnumerable<I<object?>> y1) { foreach (I<object?> a1 in x1) a1.P.ToString(); foreach (I<object> b1 in y1) b1.P.ToString(); } static void F2(IEnumerable<IIn<object>> x2, IEnumerable<IIn<object?>> y2) { foreach (IIn<object?> a2 in x2) ; foreach (IIn<object> b2 in y2) ; } static void F3(IEnumerable<IOut<object>> x3, IEnumerable<IOut<object?>> y3) { foreach (IOut<object?> a3 in x3) a3.P.ToString(); foreach (IOut<object> b3 in y3) b3.P.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,29): warning CS8619: Nullability of reference types in value of type 'I<object>' doesn't match target type 'I<object?>'. // foreach (I<object?> a1 in x1) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a1").WithArguments("I<object>", "I<object?>").WithLocation(9, 29), // (10,13): warning CS8602: Dereference of a possibly null reference. // a1.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a1.P").WithLocation(10, 13), // (11,28): warning CS8619: Nullability of reference types in value of type 'I<object?>' doesn't match target type 'I<object>'. // foreach (I<object> b1 in y1) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b1").WithArguments("I<object?>", "I<object>").WithLocation(11, 28), // (16,31): warning CS8619: Nullability of reference types in value of type 'IIn<object>' doesn't match target type 'IIn<object?>'. // foreach (IIn<object?> a2 in x2) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a2").WithArguments("IIn<object>", "IIn<object?>").WithLocation(16, 31), // (24,13): warning CS8602: Dereference of a possibly null reference. // a3.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a3.P").WithLocation(24, 13), // (25,31): warning CS8619: Nullability of reference types in value of type 'IOut<object?>' doesn't match target type 'IOut<object>'. // foreach (IOut<object> b3 in y3) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b3").WithArguments("IOut<object?>", "IOut<object>").WithLocation(25, 31)); } [Fact] public void ForEach_09() { var source = @"class A { } class B : A { } class C { static void F(A?[] c) { foreach (var a1 in c) a1.ToString(); foreach (A? a2 in c) a2.ToString(); foreach (A a3 in c) a3.ToString(); foreach (B? b1 in c) b1.ToString(); foreach (B b2 in c) b2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // a1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a1").WithLocation(8, 13), // (10,13): warning CS8602: Dereference of a possibly null reference. // a2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2").WithLocation(10, 13), // (11,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (A a3 in c) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "a3").WithLocation(11, 20), // (12,13): warning CS8602: Dereference of a possibly null reference. // a3.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a3").WithLocation(12, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // b1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b1").WithLocation(14, 13), // (15,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (B b2 in c) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b2").WithLocation(15, 20), // (16,13): warning CS8602: Dereference of a possibly null reference. // b2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b2").WithLocation(16, 13)); } [Fact] [WorkItem(29971, "https://github.com/dotnet/roslyn/issues/29971")] public void ForEach_10() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class A<T> { internal T F; } class B : A<object> { } class C { static void F(A<object?>[] c) { foreach (var a1 in c) a1.F.ToString(); foreach (A<object?> a2 in c) a2.F.ToString(); foreach (A<object> a3 in c) a3.F.ToString(); foreach (B b1 in c) b1.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // a1.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a1.F").WithLocation(13, 13), // (15,13): warning CS8602: Dereference of a possibly null reference. // a2.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2.F").WithLocation(15, 13), // (16,28): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'A<object>'. // foreach (A<object> a3 in c) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a3").WithArguments("A<object?>", "A<object>").WithLocation(16, 28), // (18,20): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'B'. // foreach (B b1 in c) Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b1").WithArguments("A<object?>", "B").WithLocation(18, 20)); } [Fact] [WorkItem(29971, "https://github.com/dotnet/roslyn/issues/29971")] public void ForEach_11() { var source = @"using System.Collections.Generic; class A { public static implicit operator B?(A a) => null; } class B { } class C { static void F(IEnumerable<A> e) { foreach (var x in e) x.ToString(); foreach (B y in e) y.ToString(); foreach (B? z in e) { z.ToString(); if (z != null) z.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (B y in e) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(15, 20), // (16,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(16, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(19, 13)); } [WorkItem(23493, "https://github.com/dotnet/roslyn/issues/23493")] [Fact] public void ForEach_12() { var source = @"using System.Collections; using System.Collections.Generic; class C { static void F() { foreach (var x in (IEnumerable?)null) // 1 { } foreach (var y in (IEnumerable<object>)default) // 2 { } foreach (var z in default(IEnumerable)) // 3 { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,27): error CS0186: Use of null is not valid in this context // foreach (var x in (IEnumerable?)null) // 1 Diagnostic(ErrorCode.ERR_NullNotValid, "(IEnumerable?)null").WithLocation(7, 27), // (10,27): error CS0186: Use of null is not valid in this context // foreach (var y in (IEnumerable<object>)default) // 2 Diagnostic(ErrorCode.ERR_NullNotValid, "(IEnumerable<object>)default").WithLocation(10, 27), // (13,27): error CS0186: Use of null is not valid in this context // foreach (var z in default(IEnumerable)) // 3 Diagnostic(ErrorCode.ERR_NullNotValid, "default(IEnumerable)").WithLocation(13, 27), // (7,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in (IEnumerable?)null) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable?)null").WithLocation(7, 27), // (10,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var y in (IEnumerable<object>)default) // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IEnumerable<object>)default").WithLocation(10, 27), // (10,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in (IEnumerable<object>)default) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable<object>)default").WithLocation(10, 27)); } [WorkItem(23493, "https://github.com/dotnet/roslyn/issues/23493")] [Fact] public void ForEach_13() { var source = @"using System.Collections; using System.Collections.Generic; class C { static void F1(object[]? c1) { foreach (var x in c1) // 1 { } foreach (var z in c1) // no cascade { } } static void F2(object[]? c1) { foreach (var y in (IEnumerable)c1) // 2 { } } static void F3(object[]? c1) { if (c1 == null) return; foreach (var z in c1) { } } static void F4(IList<object>? c2) { foreach (var x in c2) // 3 { } } static void F5(IList<object>? c2) { foreach (var y in (IEnumerable?)c2) // 4 { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in c1) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(7, 27), // (16,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var y in (IEnumerable)c1) // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IEnumerable)c1").WithLocation(16, 27), // (16,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in (IEnumerable)c1) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable)c1").WithLocation(16, 27), // (29,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in c2) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(29, 27), // (35,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in (IEnumerable?)c2) // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable?)c2").WithLocation(35, 27)); } [WorkItem(23493, "https://github.com/dotnet/roslyn/issues/23493")] [Fact] public void ForEach_14() { var source = @"using System.Collections; using System.Collections.Generic; class C { static void F1<T>(T t1) where T : class?, IEnumerable<object>? { foreach (var x in t1) // 1 { } } static void F2<T>(T t1) where T : class?, IEnumerable<object>? { foreach (var y in (IEnumerable<object>?)t1) // 2 { } } static void F3<T>(T t1) where T : class?, IEnumerable<object>? { foreach (var z in (IEnumerable<object>)t1) // 3 { } } static void F4<T>(T t2) where T : class? { foreach (var w in (IEnumerable?)t2) // 4 { } } static void F5<T>(T t2) where T : class? { foreach (var v in (IEnumerable)t2) // 5 { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in t1) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(7, 27), // (13,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in (IEnumerable<object>?)t1) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable<object>?)t1").WithLocation(13, 27), // (19,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var z in (IEnumerable<object>)t1) // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IEnumerable<object>)t1").WithLocation(19, 27), // (19,27): warning CS8602: Dereference of a possibly null reference. // foreach (var z in (IEnumerable<object>)t1) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable<object>)t1").WithLocation(19, 27), // (25,27): warning CS8602: Dereference of a possibly null reference. // foreach (var w in (IEnumerable?)t2) // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable?)t2").WithLocation(25, 27), // (31,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var v in (IEnumerable)t2) // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IEnumerable)t2").WithLocation(31, 27), // (31,27): warning CS8602: Dereference of a possibly null reference. // foreach (var v in (IEnumerable)t2) // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable)t2").WithLocation(31, 27)); } [WorkItem(23493, "https://github.com/dotnet/roslyn/issues/23493")] [Fact] public void ForEach_15() { var source = @"using System.Collections; using System.Collections.Generic; class C { static void F1<T>(T t1) where T : IEnumerable? { foreach (var x in t1) // 1 { } foreach (var x in t1) // no cascade { } } static void F2<T>(T t1) where T : IEnumerable? { foreach (var w in (IEnumerable?)t1) // 2 { } } static void F3<T>(T t1) where T : IEnumerable? { foreach (var v in (IEnumerable)t1) // 3 { } } static void F4<T>(T t2) { foreach (var y in (IEnumerable<object>?)t2) // 4 { } } static void F5<T>(T t2) { foreach (var z in (IEnumerable<object>)t2) // 5 { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in t1) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(7, 27), // (16,27): warning CS8602: Dereference of a possibly null reference. // foreach (var w in (IEnumerable?)t1) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable?)t1").WithLocation(16, 27), // (22,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var v in (IEnumerable)t1) // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IEnumerable)t1").WithLocation(22, 27), // (22,27): warning CS8602: Dereference of a possibly null reference. // foreach (var v in (IEnumerable)t1) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable)t1").WithLocation(22, 27), // (28,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in (IEnumerable<object>?)t2) // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable<object>?)t2").WithLocation(28, 27), // (34,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var z in (IEnumerable<object>)t2) // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(IEnumerable<object>)t2").WithLocation(34, 27), // (34,27): warning CS8602: Dereference of a possibly null reference. // foreach (var z in (IEnumerable<object>)t2) // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable<object>)t2").WithLocation(34, 27)); } [Fact] [WorkItem(29972, "https://github.com/dotnet/roslyn/issues/29972")] public void ForEach_16() { var source = @"using System.Collections; class Enumerable : IEnumerable { public IEnumerator? GetEnumerator() => null; } class C { static void F1(Enumerable e) { foreach (var x in e) // 1 { } foreach (var y in (IEnumerable?)e) // 2 { } foreach (var z in (IEnumerable)e) { } } static void F2(Enumerable? e) { foreach (var x in e) // 3 { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in e) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(10, 27), // (13,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in (IEnumerable?)e) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(IEnumerable?)e").WithLocation(13, 27), // (22,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in e) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(22, 27)); } [Fact] [WorkItem(29972, "https://github.com/dotnet/roslyn/issues/29972")] public void ForEach_17() { var source = @" class C { void M1<EnumerableType, EnumeratorType, T>(EnumerableType e) where EnumerableType : Enumerable<EnumeratorType, T> where EnumeratorType : I<T>? { foreach (var t in e) // 1 { t.ToString(); // 2 } } void M2<EnumerableType, EnumeratorType, T>(EnumerableType e) where EnumerableType : Enumerable<EnumeratorType, T> where EnumeratorType : I<T> { foreach (var t in e) { t.ToString(); // 3 } } } interface Enumerable<E, T> where E : I<T>? { E GetEnumerator(); } interface I<T> { T Current { get; } bool MoveNext(); } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,27): warning CS8602: Dereference of a possibly null reference. // foreach (var t in e) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(8, 27), // (10,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(10, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(19, 13)); } [Fact] [WorkItem(34667, "https://github.com/dotnet/roslyn/issues/34667")] public void ForEach_18() { var source = @" using System.Collections.Generic; class Program { static void Main() { } static void F(IEnumerable<object[]?[]> source) { foreach (object[][] item in source) { } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,29): warning CS8619: Nullability of reference types in value of type 'object[]?[]' doesn't match target type 'object[][]'. // foreach (object[][] item in source) { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "item").WithArguments("object[]?[]", "object[][]").WithLocation(10, 29)); } [Fact] [WorkItem(35151, "https://github.com/dotnet/roslyn/issues/35151")] public void ForEach_19() { var source = @" using System.Collections; class C { void M1(IEnumerator e) { var enumerable1 = Create(e); foreach (var i in enumerable1) { } e = null; // 1 var enumerable2 = Create(e); foreach (var i in enumerable2) // 2 { } } void M2(IEnumerator? e) { var enumerable1 = Create(e); foreach (var i in enumerable1) // 3 { } if (e == null) return; var enumerable2 = Create(e); foreach (var i in enumerable2) { } } void M3<TEnumerator>(TEnumerator e) where TEnumerator : IEnumerator { var enumerable1 = Create(e); foreach (var i in enumerable1) { } e = default; var enumerable2 = Create(e); foreach (var i in enumerable2) // 4 { } } void M4<TEnumerator>(TEnumerator e) where TEnumerator : IEnumerator? { var enumerable1 = Create(e); foreach (var i in enumerable1) // 5 { } if (e == null) return; var enumerable2 = Create(e); foreach (var i in enumerable2) // 6 { } } static Enumerable<T> Create<T>(T t) where T : IEnumerator? => throw null!; } class Enumerable<T> where T : IEnumerator? { public T GetEnumerator() => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // e = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 13), // (14,27): warning CS8602: Dereference of a possibly null reference. // foreach (var i in enumerable2) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "enumerable2").WithLocation(14, 27), // (22,27): warning CS8602: Dereference of a possibly null reference. // foreach (var i in enumerable1) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "enumerable1").WithLocation(22, 27), // (42,27): warning CS8602: Dereference of a possibly null reference. // foreach (var i in enumerable2) // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "enumerable2").WithLocation(42, 27), // (50,27): warning CS8602: Dereference of a possibly null reference. // foreach (var i in enumerable1) // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "enumerable1").WithLocation(50, 27), // (56,27): warning CS8602: Dereference of a possibly null reference. // foreach (var i in enumerable2) // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "enumerable2").WithLocation(56, 27)); } [Fact] [WorkItem(35151, "https://github.com/dotnet/roslyn/issues/35151")] public void ForEach_20() { var source = @" using System.Collections.Generic; class C { void M1(string e) { var enumerable1 = Create(e); foreach (var s in enumerable1) { s.ToString(); } e = null; // 1 var enumerable2 = Create(e); foreach (var s in enumerable2) { s.ToString(); // 2 } } void M2(string? e) { var enumerable1 = Create(e); foreach (var s in enumerable1) { s.ToString(); // 3 } if (e == null) return; var enumerable2 = Create(e); foreach (var s in enumerable2) { s.ToString(); } } static Enumerable<IEnumerator<U>, U> Create<U>(U u) => throw null!; } class Enumerable<T, U> where T : IEnumerator<U>? { public T GetEnumerator() => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // e = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 13), // (17,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 13), // (26,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(26, 13)); } [Fact] [WorkItem(35151, "https://github.com/dotnet/roslyn/issues/35151")] public void ForEach_21() { var source = @" using System.Collections; using System.Collections.Generic; class C { void M1(string e) { var enumerable1 = Create(e); foreach (var s in enumerable1) { s.ToString(); } e = null; // 1 var enumerable2 = Create(e); foreach (var s in enumerable2) { s.ToString(); // 2 } } void M2(string? e) { var enumerable1 = Create(e); foreach (var s in enumerable1) { s.ToString(); // 3 } if (e == null) return; var enumerable2 = Create(e); foreach (var s in enumerable2) { s.ToString(); } } static Enumerable<T> Create<T>(T t) => throw null!; } class Enumerable<T> : IEnumerable<T> { public IEnumerator<T> GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // e = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(15, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(19, 13), // (28,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(28, 13)); } [Fact] [WorkItem(35151, "https://github.com/dotnet/roslyn/issues/35151")] public void ForEach_22() { var source = @" using System.Collections; using System.Collections.Generic; class C { void M1(string e) { var enumerable1 = Create(e); foreach (var s in enumerable1) { s.ToString(); } e = null; // 1 var enumerable2 = Create(e); foreach (var s in enumerable2) { s.ToString(); // 2 } } void M2(string? e) { var enumerable1 = Create(e); foreach (var s in enumerable1) { s.ToString(); // 3 } if (e == null) return; var enumerable2 = Create(e); foreach (var s in enumerable2) { s.ToString(); } } static Enumerable<T> Create<T>(T t) => throw null!; } class Enumerable<T> : IEnumerable<T> { IEnumerator<T> IEnumerable<T>.GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // e = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(15, 13), // (19,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(19, 13), // (28,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(28, 13)); } [Fact] [WorkItem(33257, "https://github.com/dotnet/roslyn/issues/33257")] [WorkItem(35151, "https://github.com/dotnet/roslyn/issues/35151")] public void ForEach_23() { var source = @" class C { void M(string? s) { var l1 = new[] { s }; foreach (var x in l1) { x.ToString(); // 1 } if (s == null) return; var l2 = new[] { s }; foreach (var x in l2) { x.ToString(); } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(9, 13)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_24() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; struct S<T> { public E<T> GetEnumerator() => new E<T>(); } struct E<T> { [MaybeNull]public T Current => default; public bool MoveNext() => false; } class Program { static T F1<T>() { foreach (var t1 in new S<T>()) return t1; // 1 foreach (T t2 in new S<T>()) return t2; // 2 throw null!; } static object F2<T>() { foreach (object o1 in new S<T>()) // 3 return o1; // 4 foreach (object? o2 in new S<T>()) return o2; // 5 throw null!; } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (17,20): warning CS8603: Possible null reference return. // return t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(17, 20), // (18,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (T t2 in new S<T>()) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t2").WithLocation(18, 20), // (19,20): warning CS8603: Possible null reference return. // return t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(19, 20), // (24,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (object o1 in new S<T>()) // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "o1").WithLocation(24, 25), // (25,20): warning CS8603: Possible null reference return. // return o1; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o1").WithLocation(25, 20), // (27,20): warning CS8603: Possible null reference return. // return o2; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o2").WithLocation(27, 20)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_25() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; struct S<T> { public E<T> GetAsyncEnumerator() => new E<T>(); } class E<T> { [MaybeNull]public T Current => default; public ValueTask<bool> MoveNextAsync() => default; public ValueTask DisposeAsync() => default; } class Program { static async Task<T> F1<T>() { await foreach (var t1 in new S<T>()) return t1; // 1 await foreach (T t2 in new S<T>()) return t2; // 2 throw null!; } static async Task<object> F2<T>() { await foreach (object o1 in new S<T>()) // 3 return o1; // 4 await foreach (object? o2 in new S<T>()) return o2; // 5 throw null!; } }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (19,20): warning CS8603: Possible null reference return. // return t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(19, 20), // (20,26): warning CS8600: Converting null literal or possible null value to non-nullable type. // await foreach (T t2 in new S<T>()) Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t2").WithLocation(20, 26), // (21,20): warning CS8603: Possible null reference return. // return t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(21, 20), // (26,31): warning CS8600: Converting null literal or possible null value to non-nullable type. // await foreach (object o1 in new S<T>()) // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "o1").WithLocation(26, 31), // (27,20): warning CS8603: Possible null reference return. // return o1; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o1").WithLocation(27, 20), // (29,20): warning CS8603: Possible null reference return. // return o2; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o2").WithLocation(29, 20)); } [Fact, WorkItem(39736, "https://github.com/dotnet/roslyn/issues/39736")] public void Foreach_TuplesThroughFunction() { var source = @" using System.Collections.Generic; class Alpha { public string Value { get; set; } = """"; public override string ToString() => Value; } class C { void M() { var items3 = new List<(int? Index, Alpha? Alpha)>() { (0, new Alpha { Value = ""A"" }), (1, new Alpha { Value = ""B"" }), (2, new Alpha { Value = ""C"" }) }; foreach (var indexAndAlpha in Identity(items3)) { var (index, alpha) = indexAndAlpha; index/*T:int?*/.ToString(); alpha/*T:Alpha?*/.ToString(); // 1 } foreach (var (index, alpha) in Identity(items3)) { index/*T:int?*/.ToString(); alpha/*T:Alpha!*/.ToString(); // Should warn, be Alpha? } } IEnumerable<T> Identity<T>(IEnumerable<T> ie) => ie; } "; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/39736, missing the warning on the alpha dereference // from the deconstruction case comp.VerifyDiagnostics( // (23,13): warning CS8602: Dereference of a possibly null reference. // alpha.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "alpha").WithLocation(23, 13)); comp.VerifyTypes(); } [Fact] [WorkItem(33257, "https://github.com/dotnet/roslyn/issues/33257")] public void ForEach_Span() { var source = @" using System; class C { void M1(Span<string> s1, Span<string?> s2) { foreach (var s in s1) { s.ToString(); } foreach (var s in s2) { s.ToString(); // 1 } } } "; var comp = CreateCompilationWithMscorlibAndSpan(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 13)); } [Fact] [WorkItem(35151, "https://github.com/dotnet/roslyn/issues/35151")] public void ForEach_StringNotIEnumerable() { // In some frameworks, System.String doesn't implement IEnumerable, but for compat reasons the compiler // will still allow foreach'ing over these strings. var systemSource = @" namespace System { public class Object { } public struct Void { } public class ValueType { } public struct Boolean { } public struct Int32 { } public class Exception { } public struct Char { public string ToString() => throw null!; } public class String { public int Length { get; } [System.Runtime.CompilerServices.IndexerName(""Chars"")] public char this[int i] => throw null!; } public interface IDisposable { void Dispose(); } public abstract class Attribute { protected Attribute() { } } } namespace System.Runtime.CompilerServices { using System; public sealed class IndexerNameAttribute: Attribute { public IndexerNameAttribute(String indexerName) {} } } namespace System.Reflection { using System; public sealed class DefaultMemberAttribute : Attribute { public DefaultMemberAttribute(String memberName) {} } } namespace System.Collections { public interface IEnumerable { IEnumerator GetEnumerator(); } public interface IEnumerator { object Current { get; } bool MoveNext(); } }"; var source = @" class C { void M(string s, string? s2) { foreach (var c in s) { c.ToString(); } s = null; // 1 foreach (var c in s) // 2 { c.ToString(); } foreach (var c in s2) // 3 { c.ToString(); } foreach (var c in (string)null) // 4 { } } }"; var comp = CreateEmptyCompilation(new[] { source, systemSource }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 13), // (12,27): warning CS8602: Dereference of a possibly null reference. // foreach (var c in s) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 27), // (17,27): warning CS8602: Dereference of a possibly null reference. // foreach (var c in s2) // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(17, 27), // (22,27): error CS0186: Use of null is not valid in this context // foreach (var c in (string)null) // 4 Diagnostic(ErrorCode.ERR_NullNotValid, "(string)null").WithLocation(22, 27), // (22,27): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach (var c in (string)null) // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)null").WithLocation(22, 27), // (22,27): warning CS8602: Dereference of a possibly null reference. // foreach (var c in (string)null) // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(string)null").WithLocation(22, 27)); } [Fact] public void ForEach_UnconstrainedTypeParameter() { var source = @"class C<T> { void M(T parameter) { foreach (T local in new[] { parameter }) { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Theory] [InlineData("System.Collections.IEnumerator?")] [InlineData("System.Collections.Generic.IEnumerator<object>?")] [WorkItem(38233, "https://github.com/dotnet/roslyn/issues/38233")] public void ForEach_NullableGetEnumerator_01(string enumeratorType) { var source = $@" class C {{ public {enumeratorType} GetEnumerator() => throw null!; static void M1(C c) {{ foreach (var obj in c) // 1 {{ }} }} static void M2(C c) {{ foreach (var obj in c!) {{ }} }} }}"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,29): warning CS8602: Dereference of a possibly null reference. // foreach (var obj in c) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 29)); } [Theory] [InlineData("System.Collections.IEnumerator?")] [InlineData("System.Collections.Generic.IEnumerator<object>?")] [WorkItem(38233, "https://github.com/dotnet/roslyn/issues/38233")] public void ForEach_NullableGetEnumerator_02(string enumeratorType) { var source = $@" class C {{ public {enumeratorType} GetEnumerator() => throw null!; static void M1(C? c) {{ foreach (var obj in c) // 1 {{ }} }} static void M2(C? c) {{ C c2 = c!; foreach (var obj in c2) // 2 {{ }} }} static void M3(C? c) {{ foreach (var obj in c!) {{ }} }} }}"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,29): warning CS8602: Dereference of a possibly null reference. // foreach (var obj in c) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 29), // (16,29): warning CS8602: Dereference of a possibly null reference. // foreach (var obj in c2) // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(16, 29)); } [Fact] [WorkItem(38233, "https://github.com/dotnet/roslyn/issues/38233")] public void ForEach_NullableGetEnumerator_03() { var source = @" class Enumerator { public object Current => null!; public bool MoveNext() => false; } class Enumerable { public Enumerator? GetEnumerator() => null; static void M1(Enumerable e) { foreach (var obj in e) // 1 { } } static void M2(Enumerable e) { foreach (var obj in e!) { } } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,29): warning CS8602: Dereference of a possibly null reference. // foreach (var obj in e) // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "e").WithLocation(13, 29)); } [Fact] [WorkItem(38233, "https://github.com/dotnet/roslyn/issues/38233")] public void ForEach_NullableGetEnumerator_04() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { foreach(var s in new A()) { _ = s.ToString(); } } [return: MaybeNull] public IEnumerator<string> GetEnumerator() => throw null!; }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,26): warning CS8602: Dereference of a possibly null reference. // foreach(var s in new A()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A()").WithLocation(8, 26) ); } [Fact] [WorkItem(38233, "https://github.com/dotnet/roslyn/issues/38233")] public void ForEach_NullableGetEnumerator_05() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { foreach(var s in new A()) { _ = s.ToString(); } } [return: NotNull] public IEnumerator<string>? GetEnumerator() => throw null!; }"; var comp = CreateCompilation(new[] { source, NotNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator1() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<string?>()) { _ = s.ToString(); } } } static class Extensions { public static IEnumerator<T> GetEnumerator<T>(this A<T> a) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator2() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<string>()) { _ = s.ToString(); } } } static class Extensions { public static IEnumerator<T> GetEnumerator<T>(this A<T> a) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator3() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<string>()) { _ = s.ToString(); // 1 } foreach(var s in new A<string?>()) { _ = s.ToString(); // 2 } } } static class Extensions { public static IEnumerator<T?> GetEnumerator<T>(this A<T> a) where T : class => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17), // (12,26): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'Extensions.GetEnumerator<T>(A<T>)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // foreach(var s in new A<string?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "new A<string?>()").WithArguments("Extensions.GetEnumerator<T>(A<T>)", "T", "string?").WithLocation(12, 26), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator4() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<string>()) { _ = s.ToString(); // 1 } foreach(var s in new A<string?>()) { _ = s.ToString(); // 2 } } } static class Extensions { public static IEnumerator<T> GetEnumerator<T>(this A<T> a) where T : notnull => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,26): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'Extensions.GetEnumerator<T>(A<T>)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // foreach(var s in new A<string?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "new A<string?>()").WithArguments("Extensions.GetEnumerator<T>(A<T>)", "T", "string?").WithLocation(12, 26), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator5() { var source = @" using System.Collections.Generic; class A { public static void M() { A? a = null; foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IEnumerator<string> GetEnumerator(this A a) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,26): warning CS8604: Possible null reference argument for parameter 'a' in 'IEnumerator<string> Extensions.GetEnumerator(A a)'. // foreach(var s in a) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("a", "IEnumerator<string> Extensions.GetEnumerator(A a)").WithLocation(8, 26)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator6() { var source = @" using System.Collections.Generic; class A { public static void M() { A? a = null; foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IEnumerator<string> GetEnumerator(this A? a) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): warning CS8602: Dereference of a possibly null reference. // _ = a.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(11, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator7() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { A? a = null; foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IEnumerator<string> GetEnumerator([NotNull] this A? a) => throw null!; }"; var comp = CreateCompilation(new[] { source, NotNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator8() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { A a = new A(); foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IEnumerator<string> GetEnumerator([MaybeNull] this A a) => throw null!; }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,17): warning CS8602: Dereference of a possibly null reference. // _ = a.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(12, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator9() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { A? a = null; foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); // 1 } } } static class Extensions { public static IEnumerator<string> GetEnumerator([AllowNull] this A a) => throw null!; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,17): warning CS8602: Dereference of a possibly null reference. // _ = a.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(12, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator10() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { A? a = null; foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IEnumerator<string> GetEnumerator([DisallowNull] this A? a) => throw null!; }"; var comp = CreateCompilation(new[] { source, DisallowNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,26): warning CS8604: Possible null reference argument for parameter 'a' in 'IEnumerator<string> Extensions.GetEnumerator(A? a)'. // foreach(var s in a) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("a", "IEnumerator<string> Extensions.GetEnumerator(A? a)").WithLocation(9, 26)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator11() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<IEnumerator<string>?>()) { _ = s.ToString(); } } } static class Extensions { public static T GetEnumerator<T>(this A<T> a) where T : IEnumerator<string>? => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,26): warning CS8602: Dereference of a possibly null reference. // foreach(var s in new A<IEnumerator<string>?>()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A<IEnumerator<string>?>()").WithLocation(7, 26)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator12() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<IEnumerator<string>?>()) { _ = s.ToString(); // 1 } foreach(var s in new A<IEnumerator<string?>?>()) { _ = s.ToString(); // 2 } } } static class Extensions { public static T GetEnumerator<T>(this A<T?> a) where T : class, IEnumerator<string?> => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator13() { var source = @" using System.Collections.Generic; class A<T> { public static void M() { foreach(var s in new A<IEnumerator<string>?>()) { _ = s.ToString(); } } } static class Extensions { public static T GetEnumerator<T>(this A<T> a) where T : IEnumerator<string> => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,26): warning CS8631: The type 'System.Collections.Generic.IEnumerator<string>?' cannot be used as type parameter 'T' in the generic type or method 'Extensions.GetEnumerator<T>(A<T>)'. Nullability of type argument 'System.Collections.Generic.IEnumerator<string>?' doesn't match constraint type 'System.Collections.Generic.IEnumerator<string>'. // foreach(var s in new A<IEnumerator<string>?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "new A<IEnumerator<string>?>()").WithArguments("Extensions.GetEnumerator<T>(A<T>)", "System.Collections.Generic.IEnumerator<string>", "T", "System.Collections.Generic.IEnumerator<string>?").WithLocation(7, 26), // (7,26): warning CS8602: Dereference of a possibly null reference. // foreach(var s in new A<IEnumerator<string>?>()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A<IEnumerator<string>?>()").WithLocation(7, 26) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator14() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { foreach(var s in new A()) { _ = s.ToString(); } } } static class Extensions { [return: MaybeNull] public static IEnumerator<string> GetEnumerator(this A a) => throw null!; }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,26): warning CS8602: Dereference of a possibly null reference. // foreach(var s in new A()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A()").WithLocation(8, 26) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator15() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static void M() { foreach(var s in new A()) { _ = s.ToString(); } } } static class Extensions { [return: NotNull] public static IEnumerator<string>? GetEnumerator(this A a) => throw null!; }"; var comp = CreateCompilation(new[] { source, NotNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void ForEach_ExtensionGetEnumerator16() { var source = @" using System.Collections.Generic; #nullable enable public class C<T> { static void M(C<string> c) { foreach (var i in c) { } } } #nullable disable public static class CExt { public static IEnumerator<int> GetEnumerator<T>(this C<T> c, T t = default) => throw null; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,27): warning CS8620: Argument of type 'C<string>' cannot be used for parameter 'c' of type 'C<string?>' in 'IEnumerator<int> CExt.GetEnumerator<string?>(C<string?> c, string? t = null)' due to differences in the nullability of reference types. // foreach (var i in c) Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "c").WithArguments("C<string>", "C<string?>", "c", "IEnumerator<int> CExt.GetEnumerator<string?>(C<string?> c, string? t = null)").WithLocation(8, 27) ); } [Fact] public void ForEach_ExtensionGetEnumerator17() { var source = @" using System.Collections.Generic; #nullable enable public class C { static void M(C c) { foreach (var i in c) { } } } public static class CExt { public static IEnumerator<int> GetEnumerator(this C c, string t = default) => throw null!; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,71): warning CS8625: Cannot convert null literal to non-nullable reference type. // public static IEnumerator<int> GetEnumerator(this C c, string t = default) => throw null!; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(15, 71) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator1() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<string?>()) { _ = s.ToString(); } } } static class Extensions { public static IAsyncEnumerator<T> GetAsyncEnumerator<T>(this A<T> a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator2() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<string>()) { _ = s.ToString(); } } } static class Extensions { public static IAsyncEnumerator<T> GetAsyncEnumerator<T>(this A<T> a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator3() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<string>()) { _ = s.ToString(); // 1 } await foreach(var s in new A<string?>()) { _ = s.ToString(); // 2 } } } static class Extensions { public static IAsyncEnumerator<T?> GetAsyncEnumerator<T>(this A<T> a) where T : class => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17), // (12,32): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'Extensions.GetAsyncEnumerator<T>(A<T>)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // await foreach(var s in new A<string?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "new A<string?>()").WithArguments("Extensions.GetAsyncEnumerator<T>(A<T>)", "T", "string?").WithLocation(12, 32), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator4() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<string>()) { _ = s.ToString(); // 1 } await foreach(var s in new A<string?>()) { _ = s.ToString(); // 2 } } } static class Extensions { public static IAsyncEnumerator<T> GetAsyncEnumerator<T>(this A<T> a) where T : notnull => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,32): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'Extensions.GetAsyncEnumerator<T>(A<T>)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // await foreach(var s in new A<string?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "new A<string?>()").WithArguments("Extensions.GetAsyncEnumerator<T>(A<T>)", "T", "string?").WithLocation(12, 32), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator5() { var source = @" using System.Collections.Generic; class A { public static async void M() { A? a = null; await foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IAsyncEnumerator<string> GetAsyncEnumerator(this A a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,32): warning CS8604: Possible null reference argument for parameter 'a' in 'IAsyncEnumerator<string> Extensions.GetAsyncEnumerator(A a)'. // await foreach(var s in a) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("a", "IAsyncEnumerator<string> Extensions.GetAsyncEnumerator(A a)").WithLocation(8, 32) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator6() { var source = @" using System.Collections.Generic; class A { public static async void M() { A? a = null; await foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IAsyncEnumerator<string> GetAsyncEnumerator(this A? a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,17): warning CS8602: Dereference of a possibly null reference. // _ = a.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(11, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator7() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static async void M() { A? a = null; await foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IAsyncEnumerator<string> GetAsyncEnumerator([NotNull] this A? a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable, NotNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator8() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static async void M() { A a = new A(); await foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IAsyncEnumerator<string> GetAsyncEnumerator([MaybeNull] this A a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable, MaybeNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,17): warning CS8602: Dereference of a possibly null reference. // _ = a.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(12, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator9() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static async void M() { A? a = null; await foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); // 1 } } } static class Extensions { public static IAsyncEnumerator<string> GetAsyncEnumerator([AllowNull] this A a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable, AllowNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (12,17): warning CS8602: Dereference of a possibly null reference. // _ = a.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(12, 17)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator10() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static async void M() { A? a = null; await foreach(var s in a) { _ = s.ToString(); _ = a.ToString(); } } } static class Extensions { public static IAsyncEnumerator<string> GetAsyncEnumerator([DisallowNull] this A? a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable, DisallowNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,32): warning CS8604: Possible null reference argument for parameter 'a' in 'IAsyncEnumerator<string> Extensions.GetAsyncEnumerator(A? a)'. // await foreach(var s in a) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a").WithArguments("a", "IAsyncEnumerator<string> Extensions.GetAsyncEnumerator(A? a)").WithLocation(9, 32) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator11() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<IAsyncEnumerator<string>?>()) { _ = s.ToString(); } } } static class Extensions { public static T GetAsyncEnumerator<T>(this A<T> a) where T : IAsyncEnumerator<string>? => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,32): warning CS8602: Dereference of a possibly null reference. // await foreach(var s in new A<IAsyncEnumerator<string>?>()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A<IAsyncEnumerator<string>?>()").WithLocation(7, 32) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator12() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<IAsyncEnumerator<string>?>()) { _ = s.ToString(); // 1 } await foreach(var s in new A<IAsyncEnumerator<string?>?>()) { _ = s.ToString(); // 2 } } } static class Extensions { public static T GetAsyncEnumerator<T>(this A<T?> a) where T : class, IAsyncEnumerator<string?> => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator13() { var source = @" using System.Collections.Generic; class A<T> { public static async void M() { await foreach(var s in new A<IAsyncEnumerator<string>?>()) { _ = s.ToString(); } } } static class Extensions { public static T GetAsyncEnumerator<T>(this A<T> a) where T : IAsyncEnumerator<string> => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,32): warning CS8631: The type 'System.Collections.Generic.IAsyncEnumerator<string>?' cannot be used as type parameter 'T' in the generic type or method 'Extensions.GetAsyncEnumerator<T>(A<T>)'. Nullability of type argument 'System.Collections.Generic.IAsyncEnumerator<string>?' doesn't match constraint type 'System.Collections.Generic.IAsyncEnumerator<string>'. // await foreach(var s in new A<IAsyncEnumerator<string>?>()) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "new A<IAsyncEnumerator<string>?>()").WithArguments("Extensions.GetAsyncEnumerator<T>(A<T>)", "System.Collections.Generic.IAsyncEnumerator<string>", "T", "System.Collections.Generic.IAsyncEnumerator<string>?").WithLocation(7, 32), // (7,32): warning CS8602: Dereference of a possibly null reference. // await foreach(var s in new A<IAsyncEnumerator<string>?>()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A<IAsyncEnumerator<string>?>()").WithLocation(7, 32) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator14() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static async void M() { await foreach(var s in new A()) { _ = s.ToString(); } } } static class Extensions { [return: MaybeNull] public static IAsyncEnumerator<string> GetAsyncEnumerator(this A a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable, MaybeNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,32): warning CS8602: Dereference of a possibly null reference. // await foreach(var s in new A()) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "new A()").WithLocation(8, 32) ); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetAsyncEnumerator15() { var source = @" using System.Diagnostics.CodeAnalysis; using System.Collections.Generic; class A { public static async void M() { await foreach(var s in new A()) { _ = s.ToString(); } } } static class Extensions { [return: NotNull] public static IAsyncEnumerator<string>? GetAsyncEnumerator(this A a) => throw null!; }"; var comp = CreateCompilationWithTasksExtensions(new[] { source, s_IAsyncEnumerable, NotNullAttributeDefinition }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator_Suppressions1() { var source = @" using System.Collections.Generic; class A { public static void M() { foreach(var s in new A()!) { _ = s.ToString(); } } } static class Extensions { public static IEnumerator<string>? GetEnumerator(this A a) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void ForEach_ExtensionGetEnumerator_Suppressions2() { var source = @" using System.Collections.Generic; class A { public static void M() { var a = default(A); foreach(var s in a!) { _ = s.ToString(); } } } static class Extensions { public static IEnumerator<string> GetEnumerator(this A a) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_01() { var source = @"class A { } class B { } class C { static void F<T>(T? t) where T : A { } static void G(B? b) { F(b); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,9): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>(T?)'. There is no implicit reference conversion from 'B' to 'A'. // F(b); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "F").WithArguments("C.F<T>(T?)", "A", "T", "B").WithLocation(8, 9)); } [Fact] public void TypeInference_02() { var source = @"interface I<T> { } class C { static T F<T>(I<T> t) { throw new System.Exception(); } static void G(I<string> x, I<string?> y) { F(x).ToString(); F(y).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // F(y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y)").WithLocation(11, 9)); } [Fact] public void TypeInference_03() { var source = @"interface I<T> { } class C { static T F1<T>(I<T?> t) { throw new System.Exception(); } static void G1(I<string> x1, I<string?> y1) { F1(x1).ToString(); // 1 F1(y1).ToString(); } static T F2<T>(I<T?> t) where T : class { throw new System.Exception(); } static void G2(I<string> x2, I<string?> y2) { F2(x2).ToString(); // 2 F2(y2).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static T F1<T>(I<T?> t) Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 22), // (10,12): warning CS8620: Argument of type 'I<string>' cannot be used for parameter 't' of type 'I<string?>' in 'string C.F1<string>(I<string?> t)' due to differences in the nullability of reference types. // F1(x1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1").WithArguments("I<string>", "I<string?>", "t", "string C.F1<string>(I<string?> t)").WithLocation(10, 12), // (19,12): warning CS8620: Argument of type 'I<string>' cannot be used for parameter 't' of type 'I<string?>' in 'string C.F2<string>(I<string?> t)' due to differences in the nullability of reference types. // F2(x2).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x2").WithArguments("I<string>", "I<string?>", "t", "string C.F2<string>(I<string?> t)").WithLocation(19, 12)); } [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] [Fact] public void TypeInference_LowerBounds_TopLevelNullability_01() { var source0 = @"public class A { public static A F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static void G(A? x, A y) { var z = A.F; F(x, x)/*T:A?*/; F(x, y)/*T:A?*/; F(x, z)/*T:A?*/; F(y, x)/*T:A?*/; F(y, y)/*T:A!*/; F(y, z)/*T:A!*/; F(z, x)/*T:A?*/; F(z, y)/*T:A!*/; F(z, z)/*T:A!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_LowerBounds_TopLevelNullability_02() { var source = @"class C { static T F<T>(T x, T y) => throw null!; static void G<T, U>(T t, U u) where T : class? where U : class, T { F(t, t)/*T:T*/; F(t, u)/*T:T*/; F(u, t)/*T:T*/; F(u, u)/*T:U!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [WorkItem(27961, "https://github.com/dotnet/roslyn/issues/27961")] [Fact] public void TypeInference_ExactBounds_TopLevelNullability_01() { var source0 = @"public class A { public static A F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(out T x, out T y) => throw null!; static void G(A? x, A y) { var z = A.F; F(out x, out x)/*T:A?*/; F(out x, out y)/*T:A!*/; F(out x, out z)/*T:A?*/; F(out y, out x)/*T:A!*/; F(out y, out y)/*T:A!*/; F(out y, out z)/*T:A!*/; F(out z, out x)/*T:A?*/; F(out z, out y)/*T:A!*/; F(out z, out z)/*T:A?*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void TypeInference_LowerBounds_NestedNullability_Variant_01() { var source0 = @"public class A { public static I<string> F; public static IIn<string> FIn; public static IOut<string> FOut; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static void G1(I<string> x1, I<string?> y1) { var z1 = A.F/*T:I<string>!*/; F(x1, x1)/*T:I<string!>!*/; F(x1, y1)/*T:I<string!>!*/; // 1 F(x1, z1)/*T:I<string!>!*/; F(y1, x1)/*T:I<string!>!*/; // 2 F(y1, y1)/*T:I<string?>!*/; F(y1, z1)/*T:I<string?>!*/; F(z1, x1)/*T:I<string!>!*/; F(z1, y1)/*T:I<string?>!*/; F(z1, z1)/*T:I<string>!*/; } static void G2(IIn<string> x2, IIn<string?> y2) { var z2 = A.FIn/*T:IIn<string>!*/; F(x2, x2)/*T:IIn<string!>!*/; F(x2, y2)/*T:IIn<string!>!*/; F(x2, z2)/*T:IIn<string!>!*/; F(y2, x2)/*T:IIn<string!>!*/; F(y2, y2)/*T:IIn<string?>!*/; F(y2, z2)/*T:IIn<string>!*/; F(z2, x2)/*T:IIn<string!>!*/; F(z2, y2)/*T:IIn<string>!*/; F(z2, z2)/*T:IIn<string>!*/; } static void G3(IOut<string> x3, IOut<string?> y3) { var z3 = A.FOut/*T:IOut<string>!*/; F(x3, x3)/*T:IOut<string!>!*/; F(x3, y3)/*T:IOut<string?>!*/; F(x3, z3)/*T:IOut<string>!*/; F(y3, x3)/*T:IOut<string?>!*/; F(y3, y3)/*T:IOut<string?>!*/; F(y3, z3)/*T:IOut<string?>!*/; F(z3, x3)/*T:IOut<string>!*/; F(z3, y3)/*T:IOut<string?>!*/; F(z3, z3)/*T:IOut<string>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (8,15): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'y' in 'I<string> C.F<I<string>>(I<string> x, I<string> y)'. // F(x1, y1)/*T:I<string!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<string?>", "I<string>", "y", "I<string> C.F<I<string>>(I<string> x, I<string> y)").WithLocation(8, 15), // (10,11): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'x' in 'I<string> C.F<I<string>>(I<string> x, I<string> y)'. // F(y1, x1)/*T:I<string!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<string?>", "I<string>", "x", "I<string> C.F<I<string>>(I<string> x, I<string> y)").WithLocation(10, 11) ); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void TypeInference_LowerBounds_NestedNullability_Variant_02() { var source0 = @"public class A { public static B<string> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"public interface IOut<out T, out U> { } class C { static T F<T>(T x, T y) => throw null!; static T F<T>(T x, T y, T z) => throw null!; static IOut<T, U> CreateIOut<T, U>(B<T> t, B<U> u) => throw null!; static void G(B<string> x, B<string?> y) { var z = A.F/*T:B<string>!*/; var xx = CreateIOut(x, x)/*T:IOut<string!, string!>!*/; var xy = CreateIOut(x, y)/*T:IOut<string!, string?>!*/; var xz = CreateIOut(x, z)/*T:IOut<string!, string>!*/; F(xx, xy)/*T:IOut<string!, string?>!*/; F(xx, xz)/*T:IOut<string!, string>!*/; F(CreateIOut(y, x), xx)/*T:IOut<string?, string!>!*/; F(CreateIOut(y, z), CreateIOut(z, x))/*T:IOut<string?, string>!*/; F(xx, xy, xz)/*T:IOut<string!, string?>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void TypeInference_LowerBounds_NestedNullability_Variant_03() { var source0 = @"public class A { public static I<string> F; public static IIn<string> FIn; public static IOut<string> FOut; } public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static I<T> Create1<T>(T t) => throw null!; static void G1(I<IOut<string?>> x1, I<IOut<string>> y1) { var z1 = Create1(A.FOut)/*T:I<IOut<string>!>!*/; F(x1, x1)/*T:I<IOut<string?>!>!*/; F(x1, y1)/*T:I<IOut<string!>!>!*/; // 1 F(x1, z1)/*T:I<IOut<string?>!>!*/; F(y1, x1)/*T:I<IOut<string!>!>!*/; // 2 F(y1, y1)/*T:I<IOut<string!>!>!*/; F(y1, z1)/*T:I<IOut<string!>!>!*/; F(z1, x1)/*T:I<IOut<string?>!>!*/; F(z1, y1)/*T:I<IOut<string!>!>!*/; F(z1, z1)/*T:I<IOut<string>!>!*/; } static IOut<T> Create2<T>(T t) => throw null!; static void G2(IOut<IIn<string?>> x2, IOut<IIn<string>> y2) { var z2 = Create2(A.FIn)/*T:IOut<IIn<string>!>!*/; F(x2, x2)/*T:IOut<IIn<string?>!>!*/; F(x2, y2)/*T:IOut<IIn<string!>!>!*/; F(x2, z2)/*T:IOut<IIn<string>!>!*/; F(y2, x2)/*T:IOut<IIn<string!>!>!*/; F(y2, y2)/*T:IOut<IIn<string!>!>!*/; F(y2, z2)/*T:IOut<IIn<string!>!>!*/; F(z2, x2)/*T:IOut<IIn<string>!>!*/; F(z2, y2)/*T:IOut<IIn<string!>!>!*/; F(z2, z2)/*T:IOut<IIn<string>!>!*/; } static IIn<T> Create3<T>(T t) => throw null!; static void G3(IIn<IOut<string?>> x3, IIn<IOut<string>> y3) { var z3 = Create3(A.FOut)/*T:IIn<IOut<string>!>!*/; F(x3, x3)/*T:IIn<IOut<string?>!>!*/; F(x3, y3)/*T:IIn<IOut<string!>!>!*/; F(x3, z3)/*T:IIn<IOut<string>!>!*/; F(y3, x3)/*T:IIn<IOut<string!>!>!*/; F(y3, y3)/*T:IIn<IOut<string!>!>!*/; F(y3, z3)/*T:IIn<IOut<string!>!>!*/; F(z3, x3)/*T:IIn<IOut<string>!>!*/; F(z3, y3)/*T:IIn<IOut<string!>!>!*/; F(z3, z3)/*T:IIn<IOut<string>!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (9,11): warning CS8620: Nullability of reference types in argument of type 'I<IOut<string?>>' doesn't match target type 'I<IOut<string>>' for parameter 'x' in 'I<IOut<string>> C.F<I<IOut<string>>>(I<IOut<string>> x, I<IOut<string>> y)'. // F(x1, y1)/*T:I<IOut<string!>!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1").WithArguments("I<IOut<string?>>", "I<IOut<string>>", "x", "I<IOut<string>> C.F<I<IOut<string>>>(I<IOut<string>> x, I<IOut<string>> y)").WithLocation(9, 11), // (11,15): warning CS8620: Nullability of reference types in argument of type 'I<IOut<string?>>' doesn't match target type 'I<IOut<string>>' for parameter 'y' in 'I<IOut<string>> C.F<I<IOut<string>>>(I<IOut<string>> x, I<IOut<string>> y)'. // F(y1, x1)/*T:I<IOut<string!>!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1").WithArguments("I<IOut<string?>>", "I<IOut<string>>", "y", "I<IOut<string>> C.F<I<IOut<string>>>(I<IOut<string>> x, I<IOut<string>> y)").WithLocation(11, 15) ); } [Fact] public void TypeInference_ExactBounds_TopLevelNullability_02() { var source0 = @"public class A { public static B<string> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(B<T> x, B<T> y) => throw null!; static void G(B<string?> x, B<string> y) { var z = A.F/*T:B<string>!*/; F(x, x)/*T:string?*/; F(x, y)/*T:string!*/; // 1 F(x, z)/*T:string?*/; F(y, x)/*T:string!*/; // 2 F(y, y)/*T:string!*/; F(y, z)/*T:string!*/; F(z, x)/*T:string?*/; F(z, y)/*T:string!*/; F(z, z)/*T:string!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (8,11): warning CS8620: Nullability of reference types in argument of type 'B<string?>' doesn't match target type 'B<string>' for parameter 'x' in 'string C.F<string>(B<string> x, B<string> y)'. // F(x, y)/*T:string!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<string?>", "B<string>", "x", "string C.F<string>(B<string> x, B<string> y)").WithLocation(8, 11), // (10,14): warning CS8620: Nullability of reference types in argument of type 'B<string?>' doesn't match target type 'B<string>' for parameter 'y' in 'string C.F<string>(B<string> x, B<string> y)'. // F(y, x)/*T:string!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<string?>", "B<string>", "y", "string C.F<string>(B<string> x, B<string> y)").WithLocation(10, 14) ); } [Fact] public void TypeInference_ExactBounds_NestedNullability() { var source0 = @"public class A { public static B<object> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class Program { static T F<T>(T x, T y, T z) => throw null!; static void G(B<object?> x, B<object> y) { var z = A.F/*T:B<object>!*/; F(x, x, x)/*T:B<object?>!*/; F(x, x, y)/*T:B<object!>!*/; // 1 2 F(x, x, z)/*T:B<object?>!*/; F(x, y, x)/*T:B<object!>!*/; // 3 4 F(x, y, y)/*T:B<object!>!*/; // 5 F(x, y, z)/*T:B<object!>!*/; // 6 F(x, z, x)/*T:B<object?>!*/; F(x, z, y)/*T:B<object!>!*/; // 7 F(x, z, z)/*T:B<object?>!*/; F(y, x, x)/*T:B<object!>!*/; // 8 9 F(y, x, y)/*T:B<object!>!*/; // 10 F(y, x, z)/*T:B<object!>!*/; // 11 F(y, y, x)/*T:B<object!>!*/; // 12 F(y, y, y)/*T:B<object!>!*/; F(y, y, z)/*T:B<object!>!*/; F(y, z, x)/*T:B<object!>!*/; // 13 F(y, z, y)/*T:B<object!>!*/; F(y, z, z)/*T:B<object!>!*/; F(z, x, x)/*T:B<object?>!*/; F(z, x, y)/*T:B<object!>!*/; // 14 F(z, x, z)/*T:B<object?>!*/; F(z, y, x)/*T:B<object!>!*/; // 15 F(z, y, y)/*T:B<object!>!*/; F(z, y, z)/*T:B<object!>!*/; F(z, z, x)/*T:B<object?>!*/; F(z, z, y)/*T:B<object!>!*/; F(z, z, z)/*T:B<object>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,11): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'x' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, x, y)/*T:B<object!>!*/; // 1 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "x", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(8, 11), // (8,14): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'y' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, x, y)/*T:B<object!>!*/; // 1 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "y", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(8, 14), // (10,11): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'x' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, y, x)/*T:B<object!>!*/; // 3 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "x", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(10, 11), // (10,17): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'z' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, y, x)/*T:B<object!>!*/; // 3 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "z", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(10, 17), // (11,11): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'x' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, y, y)/*T:B<object!>!*/; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "x", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(11, 11), // (12,11): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'x' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, y, z)/*T:B<object!>!*/; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "x", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(12, 11), // (14,11): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'x' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(x, z, y)/*T:B<object!>!*/; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "x", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(14, 11), // (16,14): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'y' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(y, x, x)/*T:B<object!>!*/; // 8 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "y", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(16, 14), // (16,17): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'z' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(y, x, x)/*T:B<object!>!*/; // 8 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "z", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(16, 17), // (17,14): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'y' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(y, x, y)/*T:B<object!>!*/; // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "y", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(17, 14), // (18,14): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'y' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(y, x, z)/*T:B<object!>!*/; // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "y", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(18, 14), // (19,17): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'z' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(y, y, x)/*T:B<object!>!*/; // 12 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "z", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(19, 17), // (22,17): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'z' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(y, z, x)/*T:B<object!>!*/; // 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "z", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(22, 17), // (26,14): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'y' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(z, x, y)/*T:B<object!>!*/; // 14 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "y", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(26, 14), // (28,17): warning CS8620: Nullability of reference types in argument of type 'B<object?>' doesn't match target type 'B<object>' for parameter 'z' in 'B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)'. // F(z, y, x)/*T:B<object!>!*/; // 15 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?>", "B<object>", "z", "B<object> Program.F<B<object>>(B<object> x, B<object> y, B<object> z)").WithLocation(28, 17) ); comp.VerifyTypes(); } [Fact] public void TypeInference_ExactAndLowerBounds_TopLevelNullability() { var source0 = @"public class A { public static B<string> F; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, B<T> y) => throw null!; static B<T> CreateB<T>(T t) => throw null!; static void G(string? x, string y) { var z = A.F /*T:B<string>!*/; F(x, CreateB(x))/*T:string?*/; F(x, CreateB(y))/*T:string?*/; // 1 F(x, z)/*T:string?*/; F(y, CreateB(x))/*T:string?*/; F(y, CreateB(y))/*T:string!*/; F(y, z)/*T:string!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (9,14): warning CS8620: Nullability of reference types in argument of type 'B<string>' doesn't match target type 'B<string?>' for parameter 'y' in 'string? C.F<string?>(string? x, B<string?> y)'. // F(x, CreateB(y))/*T:string?*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "CreateB(y)").WithArguments("B<string>", "B<string?>", "y", "string? C.F<string?>(string? x, B<string?> y)").WithLocation(9, 14) ); } [Fact] public void TypeInference_ExactAndUpperBounds_TopLevelNullability() { var source0 = @"public class A { public static IIn<string> FIn; public static B<string> FB; } public interface IIn<in T> { } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(IIn<T> x, B<T> y) => throw null!; static IIn<T> CreateIIn<T>(T t) => throw null!; static B<T> CreateB<T>(T t) => throw null!; static void G(string? x, string y) { var zin = A.FIn/*T:IIn<string>!*/; var zb = A.FB/*T:B<string>!*/; F(CreateIIn(x), CreateB(x))/*T:string?*/; F(CreateIIn(x), CreateB(y))/*T:string!*/; F(CreateIIn(x), zb)/*T:string!*/; F(CreateIIn(y), CreateB(x))/*T:string!*/; // 1 F(CreateIIn(y), CreateB(y))/*T:string!*/; F(CreateIIn(y), zb)/*T:string!*/; F(zin, CreateB(x))/*T:string!*/; F(zin, CreateB(y))/*T:string!*/; F(zin, zb)/*T:string!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (13,25): warning CS8620: Nullability of reference types in argument of type 'B<string?>' doesn't match target type 'B<string>' for parameter 'y' in 'string C.F<string>(IIn<string> x, B<string> y)'. // F(CreateIIn(y), CreateB(x))/*T:string!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "CreateB(x)").WithArguments("B<string?>", "B<string>", "y", "string C.F<string>(IIn<string> x, B<string> y)").WithLocation(13, 25) ); comp.VerifyTypes(); } [Fact] [WorkItem(29837, "https://github.com/dotnet/roslyn/issues/29837")] public void TypeInference_MixedBounds_NestedNullability() { var source0 = @"public class A { public static IIn<object, string> F1; public static IOut<object, string> F2; } public interface IIn<in T, U> { } public interface IOut<T, out U> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static void F1(bool b, IIn<object, string> x1, IIn<object?, string?> y1) { var z1 = A.F1/*T:IIn<object, string>!*/; F(x1, x1)/*T:IIn<object!, string!>!*/; F(x1, y1)/*T:IIn<object!, string!>!*/; // 1 F(x1, z1)/*T:IIn<object!, string!>!*/; F(y1, x1)/*T:IIn<object!, string!>!*/; // 2 F(y1, y1)/*T:IIn<object?, string?>!*/; F(y1, z1)/*T:IIn<object, string?>!*/; F(z1, x1)/*T:IIn<object!, string!>!*/; F(z1, y1)/*T:IIn<object, string?>!*/; F(z1, z1)/*T:IIn<object, string>!*/; } static void F2(bool b, IOut<object, string> x2, IOut<object?, string?> y2) { var z2 = A.F2/*T:IOut<object, string>!*/; F(x2, x2)/*T:IOut<object!, string!>!*/; F(x2, y2)/*T:IOut<object!, string?>!*/; // 3 F(x2, z2)/*T:IOut<object!, string>!*/; F(y2, x2)/*T:IOut<object!, string?>!*/; // 4 F(y2, y2)/*T:IOut<object?, string?>!*/; F(y2, z2)/*T:IOut<object?, string?>!*/; F(z2, x2)/*T:IOut<object!, string>!*/; F(z2, y2)/*T:IOut<object?, string?>!*/; F(z2, z2)/*T:IOut<object, string>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (8,15): warning CS8620: Nullability of reference types in argument of type 'IIn<object?, string?>' doesn't match target type 'IIn<object, string>' for parameter 'y' in 'IIn<object, string> C.F<IIn<object, string>>(IIn<object, string> x, IIn<object, string> y)'. // F(x1, y1)/*T:IIn<object!, string!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("IIn<object?, string?>", "IIn<object, string>", "y", "IIn<object, string> C.F<IIn<object, string>>(IIn<object, string> x, IIn<object, string> y)").WithLocation(8, 15), // (10,11): warning CS8620: Nullability of reference types in argument of type 'IIn<object?, string?>' doesn't match target type 'IIn<object, string>' for parameter 'x' in 'IIn<object, string> C.F<IIn<object, string>>(IIn<object, string> x, IIn<object, string> y)'. // F(y1, x1)/*T:IIn<object!, string!>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("IIn<object?, string?>", "IIn<object, string>", "x", "IIn<object, string> C.F<IIn<object, string>>(IIn<object, string> x, IIn<object, string> y)").WithLocation(10, 11), // (21,15): warning CS8620: Nullability of reference types in argument of type 'IOut<object?, string?>' doesn't match target type 'IOut<object, string?>' for parameter 'y' in 'IOut<object, string?> C.F<IOut<object, string?>>(IOut<object, string?> x, IOut<object, string?> y)'. // F(x2, y2)/*T:IOut<object!, string?>!*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y2").WithArguments("IOut<object?, string?>", "IOut<object, string?>", "y", "IOut<object, string?> C.F<IOut<object, string?>>(IOut<object, string?> x, IOut<object, string?> y)").WithLocation(21, 15), // (23,11): warning CS8620: Nullability of reference types in argument of type 'IOut<object?, string?>' doesn't match target type 'IOut<object, string?>' for parameter 'x' in 'IOut<object, string?> C.F<IOut<object, string?>>(IOut<object, string?> x, IOut<object, string?> y)'. // F(y2, x2)/*T:IOut<object!, string?>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y2").WithArguments("IOut<object?, string?>", "IOut<object, string?>", "x", "IOut<object, string?> C.F<IOut<object, string?>>(IOut<object, string?> x, IOut<object, string?> y)").WithLocation(23, 11) ); } [Fact] public void TypeInference_LowerBounds_NestedNullability_MismatchedTypes() { var source = @"interface IOut<out T> { } class Program { static T F<T>(T x, T y) => throw null!; static void G(IOut<object> x, IOut<string?> y) { F(x, y)/*T:IOut<object!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // Ideally we'd infer IOut<object?> but the spec doesn't require merging nullability // across distinct types (in this case, the lower bounds IOut<object!> and IOut<string?>). // Instead, method type inference infers IOut<object!> and a warning is reported // converting the second argument to the inferred parameter type. comp.VerifyTypes(); comp.VerifyDiagnostics( // (7,14): warning CS8620: Nullability of reference types in argument of type 'IOut<string?>' doesn't match target type 'IOut<object>' for parameter 'y' in 'IOut<object> Program.F<IOut<object>>(IOut<object> x, IOut<object> y)'. // F(x, y); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IOut<string?>", "IOut<object>", "y", "IOut<object> Program.F<IOut<object>>(IOut<object> x, IOut<object> y)").WithLocation(7, 14)); } [Fact] public void TypeInference_LowerAndUpperBounds_NestedNullability() { var source = @"interface IIn<in T> { } interface IOut<out T> { } class Program { static T FIn<T>(T x, T y, IIn<T> z) => throw null!; static T FOut<T>(T x, T y, IOut<T> z) => throw null!; static IIn<T> CreateIIn<T>(T t) => throw null!; static IOut<T> CreateIOut<T>(T t) => throw null!; static void G1(IIn<string?> x1, IIn<string> y1) { FIn(x1, y1, CreateIIn(x1))/*T:IIn<string!>!*/; // 1 FIn(x1, y1, CreateIIn(y1))/*T:IIn<string!>!*/; FOut(x1, y1, CreateIOut(x1))/*T:IIn<string!>!*/; FOut(x1, y1, CreateIOut(y1))/*T:IIn<string!>!*/; } static void G2(IOut<string?> x2, IOut<string> y2) { FIn(x2, y2, CreateIIn(x2))/*T:IOut<string?>!*/; FIn(x2, y2, CreateIIn(y2))/*T:IOut<string?>!*/; // 2 FOut(x2, y2, CreateIOut(x2))/*T:IOut<string?>!*/; FOut(x2, y2, CreateIOut(y2))/*T:IOut<string?>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // Ideally we'd fail to infer nullability for // 1 and // 2 rather than inferring the // wrong nullability and then reporting a warning converting the arguments. // (See MethodTypeInferrer.TryMergeAndReplaceIfStillCandidate which ignores // the variance used merging earlier candidates when merging later candidates.) comp.VerifyTypes(); comp.VerifyDiagnostics( // (11,21): warning CS8620: Nullability of reference types in argument of type 'IIn<IIn<string?>>' doesn't match target type 'IIn<IIn<string>>' for parameter 'z' in 'IIn<string> Program.FIn<IIn<string>>(IIn<string> x, IIn<string> y, IIn<IIn<string>> z)'. // FIn(x1, y1, CreateIIn(x1))/*T:IIn<string!>!*/; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "CreateIIn(x1)").WithArguments("IIn<IIn<string?>>", "IIn<IIn<string>>", "z", "IIn<string> Program.FIn<IIn<string>>(IIn<string> x, IIn<string> y, IIn<IIn<string>> z)").WithLocation(11, 21), // (19,21): warning CS8620: Nullability of reference types in argument of type 'IIn<IOut<string>>' doesn't match target type 'IIn<IOut<string?>>' for parameter 'z' in 'IOut<string?> Program.FIn<IOut<string?>>(IOut<string?> x, IOut<string?> y, IIn<IOut<string?>> z)'. // FIn(x2, y2, CreateIIn(y2))/*T:IOut<string?>!*/; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "CreateIIn(y2)").WithArguments("IIn<IOut<string>>", "IIn<IOut<string?>>", "z", "IOut<string?> Program.FIn<IOut<string?>>(IOut<string?> x, IOut<string?> y, IIn<IOut<string?>> z)").WithLocation(19, 21)); } [Fact] public void TypeInference_05() { var source = @"class C { static T F<T>(T x, T? y) where T : class => x; static void G(C? x, C y) { F(x, x).ToString(); F(x, y).ToString(); F(y, x).ToString(); F(y, y).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8634: The type 'C?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>(T, T?)'. Nullability of type argument 'C?' doesn't match 'class' constraint. // F(x, x).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>(T, T?)", "T", "C?").WithLocation(6, 9), // (6,9): warning CS8602: Dereference of a possibly null reference. // F(x, x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x, x)").WithLocation(6, 9), // (7,9): warning CS8634: The type 'C?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>(T, T?)'. Nullability of type argument 'C?' doesn't match 'class' constraint. // F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>(T, T?)", "T", "C?").WithLocation(7, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // F(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x, y)").WithLocation(7, 9)); } [Fact] public void TypeInference_06() { var source = @"class C { static T F<T, U>(T t, U u) where U : T => t; static void G(C? x, C y) { F(x, x).ToString(); // warning: may be null F(x, y).ToString(); // warning may be null F(y, x).ToString(); // warning: x does not satisfy U constraint F(y, y).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // F(x, x).ToString(); // warning: may be null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x, x)").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // F(x, y).ToString(); // warning may be null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x, y)").WithLocation(7, 9), // (8,9): warning CS8631: The type 'C?' cannot be used as type parameter 'U' in the generic type or method 'C.F<T, U>(T, U)'. Nullability of type argument 'C?' doesn't match constraint type 'C'. // F(y, x).ToString(); // warning: x does not satisfy U constraint Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F").WithArguments("C.F<T, U>(T, U)", "C", "U", "C?").WithLocation(8, 9)); } [Fact] public void TypeInference_LowerBounds_NestedNullability_MismatchedNullability() { var source0 = @"public class A { public static A<object> F; public static A<string> G; } public class A<T> { } public class B<T, U> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static B<T, U> CreateB<T, U>(A<T> t, A<U> u) => throw null!; static void G(A<object?> t1, A<object> t2, A<string?> u1, A<string> u2) { var t3 = A.F/*T:A<object>!*/; var u3 = A.G/*T:A<string>!*/; var x = CreateB(t1, u2)/*T:B<object?, string!>!*/; var y = CreateB(t2, u1)/*T:B<object!, string?>!*/; var z = CreateB(t1, u3)/*T:B<object?, string>!*/; var w = CreateB(t3, u2)/*T:B<object, string!>!*/; F(x, y)/*T:B<object!, string!>!*/; F(x, z)/*T:B<object?, string!>!*/; F(x, w)/*T:B<object?, string!>!*/; F(y, z)/*T:B<object!, string?>!*/; F(y, w)/*T:B<object!, string!>!*/; F(w, z)/*T:B<object?, string!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (13,11): warning CS8620: Nullability of reference types in argument of type 'B<object?, string>' doesn't match target type 'B<object, string>' for parameter 'x' in 'B<object, string> C.F<B<object, string>>(B<object, string> x, B<object, string> y)'. // F(x, y)/*T:B<object!, string!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("B<object?, string>", "B<object, string>", "x", "B<object, string> C.F<B<object, string>>(B<object, string> x, B<object, string> y)").WithLocation(13, 11), // (13,14): warning CS8620: Nullability of reference types in argument of type 'B<object, string?>' doesn't match target type 'B<object, string>' for parameter 'y' in 'B<object, string> C.F<B<object, string>>(B<object, string> x, B<object, string> y)'. // F(x, y)/*T:B<object!, string!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("B<object, string?>", "B<object, string>", "y", "B<object, string> C.F<B<object, string>>(B<object, string> x, B<object, string> y)").WithLocation(13, 14), // (16,14): warning CS8620: Nullability of reference types in argument of type 'B<object?, string>' doesn't match target type 'B<object, string?>' for parameter 'y' in 'B<object, string?> C.F<B<object, string?>>(B<object, string?> x, B<object, string?> y)'. // F(y, z)/*T:B<object!, string?>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("B<object?, string>", "B<object, string?>", "y", "B<object, string?> C.F<B<object, string?>>(B<object, string?> x, B<object, string?> y)").WithLocation(16, 14), // (17,11): warning CS8620: Nullability of reference types in argument of type 'B<object, string?>' doesn't match target type 'B<object, string>' for parameter 'x' in 'B<object, string> C.F<B<object, string>>(B<object, string> x, B<object, string> y)'. // F(y, w)/*T:B<object!, string!>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("B<object, string?>", "B<object, string>", "x", "B<object, string> C.F<B<object, string>>(B<object, string> x, B<object, string> y)").WithLocation(17, 11) ); } [Fact] public void TypeInference_UpperBounds_NestedNullability_MismatchedNullability() { var source0 = @"public class A { public static X<object> F; public static X<string> G; } public interface IIn<in T> { } public class B<T, U> { } public class X<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(IIn<T> x, IIn<T> y) => throw null!; static IIn<B<T, U>> CreateB<T, U>(X<T> t, X<U> u) => throw null!; static void G(X<object?> t1, X<object> t2, X<string?> u1, X<string> u2) { var t3 = A.F/*T:X<object>!*/; var u3 = A.G/*T:X<string>!*/; var x = CreateB(t1, u2)/*T:IIn<B<object?, string!>!>!*/; var y = CreateB(t2, u1)/*T:IIn<B<object!, string?>!>!*/; var z = CreateB(t1, u3)/*T:IIn<B<object?, string>!>!*/; var w = CreateB(t3, u2)/*T:IIn<B<object, string!>!>!*/; F(x, y)/*T:B<object!, string!>!*/; // 1 2 F(x, z)/*T:B<object?, string!>!*/; F(x, w)/*T:B<object?, string!>!*/; F(y, z)/*T:B<object!, string?>!*/; // 3 F(y, w)/*T:B<object!, string!>!*/; // 4 F(w, z)/*T:B<object?, string!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (13,11): warning CS8620: Nullability of reference types in argument of type 'IIn<B<object?, string>>' doesn't match target type 'IIn<B<object, string>>' for parameter 'x' in 'B<object, string> C.F<B<object, string>>(IIn<B<object, string>> x, IIn<B<object, string>> y)'. // F(x, y)/*T:B<object!, string!>!*/; // 1 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("IIn<B<object?, string>>", "IIn<B<object, string>>", "x", "B<object, string> C.F<B<object, string>>(IIn<B<object, string>> x, IIn<B<object, string>> y)").WithLocation(13, 11), // (13,14): warning CS8620: Nullability of reference types in argument of type 'IIn<B<object, string?>>' doesn't match target type 'IIn<B<object, string>>' for parameter 'y' in 'B<object, string> C.F<B<object, string>>(IIn<B<object, string>> x, IIn<B<object, string>> y)'. // F(x, y)/*T:B<object!, string!>!*/; // 1 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IIn<B<object, string?>>", "IIn<B<object, string>>", "y", "B<object, string> C.F<B<object, string>>(IIn<B<object, string>> x, IIn<B<object, string>> y)").WithLocation(13, 14), // (16,14): warning CS8620: Nullability of reference types in argument of type 'IIn<B<object?, string>>' doesn't match target type 'IIn<B<object, string?>>' for parameter 'y' in 'B<object, string?> C.F<B<object, string?>>(IIn<B<object, string?>> x, IIn<B<object, string?>> y)'. // F(y, z)/*T:B<object!, string?>!*/; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("IIn<B<object?, string>>", "IIn<B<object, string?>>", "y", "B<object, string?> C.F<B<object, string?>>(IIn<B<object, string?>> x, IIn<B<object, string?>> y)").WithLocation(16, 14), // (17,11): warning CS8620: Nullability of reference types in argument of type 'IIn<B<object, string?>>' doesn't match target type 'IIn<B<object, string>>' for parameter 'x' in 'B<object, string> C.F<B<object, string>>(IIn<B<object, string>> x, IIn<B<object, string>> y)'. // F(y, w)/*T:B<object!, string!>!*/; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("IIn<B<object, string?>>", "IIn<B<object, string>>", "x", "B<object, string> C.F<B<object, string>>(IIn<B<object, string>> x, IIn<B<object, string>> y)").WithLocation(17, 11) ); } [Fact] public void TypeInference_LowerBounds_NestedNullability_TypeParameters() { var source = @"interface IOut<out T> { } class C { static T F<T>(T x, T y) => throw null!; static void G<T>(IOut<T?> x, IOut<T> y) where T : class { F(x, x)/*T:IOut<T?>!*/; F(x, y)/*T:IOut<T?>!*/; F(y, x)/*T:IOut<T?>!*/; F(y, y)/*T:IOut<T!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] [WorkItem(33346, "https://github.com/dotnet/roslyn/issues/33346")] public void TypeInference_LowerBounds_NestedNullability_Arrays() { var source0 = @"public class A { public static string[] F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static void G(string?[] x, string[] y) { var z = A.F/*T:string[]!*/; F(x, x)/*T:string?[]!*/; F(x, y)/*T:string?[]!*/; F(x, z)/*T:string?[]!*/; F(y, x)/*T:string?[]!*/; F(y, y)/*T:string![]!*/; F(y, z)/*T:string[]!*/; F(z, x)/*T:string?[]!*/; F(z, y)/*T:string[]!*/; F(z, z)/*T:string[]!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_LowerBounds_NestedNullability_Dynamic() { var source = @"interface IOut<out T> { } class C { static T F<T>(T x, T y) => throw null!; static void G(IOut<dynamic?> x, IOut<dynamic> y) { F(x, x)/*T:IOut<dynamic?>!*/; F(x, y)/*T:IOut<dynamic?>!*/; F(y, x)/*T:IOut<dynamic?>!*/; F(y, y)/*T:IOut<dynamic!>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_LowerBounds_NestedNullability_Pointers() { var source = @"unsafe class C { static T F<T>(T x, T y) => throw null!; static void G(object?* x, object* y) // 1 { _ = z/*T:object**/; F(x, x)/*T:object?**/; // 2 F(x, y)/*T:object!**/; // 3 F(x, z)/*T:object?**/; // 4 F(y, x)/*T:object!**/; // 5 F(y, y)/*T:object!**/; // 6 F(y, z)/*T:object!**/; // 7 F(z, x)/*T:object?**/; // 8 F(z, y)/*T:object!**/; // 9 F(z, z)/*T:object**/; // 10 } #nullable disable public static object* z = null; // 11 }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(TestOptions.UnsafeDebugDll)); comp.VerifyTypes(); comp.VerifyDiagnostics( // (4,28): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // static void G(object?* x, object* y) // 1 Diagnostic(ErrorCode.ERR_ManagedAddr, "x").WithArguments("object").WithLocation(4, 28), // (4,39): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // static void G(object?* x, object* y) // 1 Diagnostic(ErrorCode.ERR_ManagedAddr, "y").WithArguments("object").WithLocation(4, 39), // (7,9): error CS0306: The type 'object*' may not be used as a type argument // F(x, x)/*T:object?**/; // 2 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(7, 9), // (8,9): error CS0306: The type 'object*' may not be used as a type argument // F(x, y)/*T:object!**/; // 3 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(8, 9), // (9,9): error CS0306: The type 'object*' may not be used as a type argument // F(x, z)/*T:object?**/; // 4 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(9, 9), // (10,9): error CS0306: The type 'object*' may not be used as a type argument // F(y, x)/*T:object!**/; // 5 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(10, 9), // (11,9): error CS0306: The type 'object*' may not be used as a type argument // F(y, y)/*T:object!**/; // 6 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(11, 9), // (12,9): error CS0306: The type 'object*' may not be used as a type argument // F(y, z)/*T:object!**/; // 7 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(12, 9), // (13,9): error CS0306: The type 'object*' may not be used as a type argument // F(z, x)/*T:object?**/; // 8 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(13, 9), // (14,9): error CS0306: The type 'object*' may not be used as a type argument // F(z, y)/*T:object!**/; // 9 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(14, 9), // (15,9): error CS0306: The type 'object*' may not be used as a type argument // F(z, z)/*T:object**/; // 10 Diagnostic(ErrorCode.ERR_BadTypeArgument, "F").WithArguments("object*").WithLocation(15, 9), // (20,27): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('object') // public static object* z = null; // 11 Diagnostic(ErrorCode.ERR_ManagedAddr, "z").WithArguments("object").WithLocation(20, 27) ); } [Fact] public void TypeInference_LowerBounds_NestedNullability_Tuples() { var source0 = @"public class A { public static B<object> F; public static B<string> G; } public class B<T> { } "; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static (T, U) Create<T, U>(B<T> t, B<U> u) => throw null!; static void G(B<object?> t1, B<object> t2, B<string?> u1, B<string> u2) { var t3 = A.F/*T:B<object>!*/; var u3 = A.G/*T:B<string>!*/; var x = Create(t1, u2)/*T:(object?, string!)*/; var y = Create(t2, u1)/*T:(object!, string?)*/; var z = Create(t1, u3)/*T:(object?, string)*/; var w = Create(t3, u2)/*T:(object, string!)*/; F(x, y)/*T:(object?, string?)*/; F(x, z)/*T:(object?, string)*/; F(x, w)/*T:(object?, string!)*/; F(y, z)/*T:(object?, string?)*/; F(y, w)/*T:(object, string?)*/; F(w, z)/*T:(object?, string)*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_LowerBounds_NestedNullability_Tuples_Variant() { var source0 = @"public class A { public static (object, string) F; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>(T x, T y) => throw null!; static I<T> CreateI<T>(T t) => throw null!; static void G1(I<(object, string)> x1, I<(object?, string?)> y1) { var z1 = CreateI(A.F)/*T:I<(object, string)>!*/; F(x1, x1)/*T:I<(object!, string!)>!*/; F(x1, y1)/*T:I<(object!, string!)>!*/; F(x1, z1)/*T:I<(object!, string!)>!*/; F(y1, x1)/*T:I<(object!, string!)>!*/; F(y1, y1)/*T:I<(object?, string?)>!*/; F(y1, z1)/*T:I<(object?, string?)>!*/; F(z1, x1)/*T:I<(object!, string!)>!*/; F(z1, y1)/*T:I<(object?, string?)>!*/; F(z1, z1)/*T:I<(object, string)>!*/; } static IIn<T> CreateIIn<T>(T t) => throw null!; static void G2(IIn<(object, string)> x2, IIn<(object?, string?)> y2) { var z2 = CreateIIn(A.F)/*T:IIn<(object, string)>!*/; F(x2, x2)/*T:IIn<(object!, string!)>!*/; F(x2, y2)/*T:IIn<(object!, string!)>!*/; F(x2, z2)/*T:IIn<(object!, string!)>!*/; F(y2, x2)/*T:IIn<(object!, string!)>!*/; F(y2, y2)/*T:IIn<(object?, string?)>!*/; F(y2, z2)/*T:IIn<(object, string)>!*/; F(z2, x2)/*T:IIn<(object!, string!)>!*/; F(z2, y2)/*T:IIn<(object, string)>!*/; F(z2, z2)/*T:IIn<(object, string)>!*/; } static IOut<T> CreateIOut<T>(T t) => throw null!; static void G3(IOut<(object, string)> x3, IOut<(object?, string?)> y3) { var z3 = CreateIOut(A.F)/*T:IOut<(object, string)>!*/; F(x3, x3)/*T:IOut<(object!, string!)>!*/; F(x3, y3)/*T:IOut<(object?, string?)>!*/; F(x3, z3)/*T:IOut<(object, string)>!*/; F(y3, x3)/*T:IOut<(object?, string?)>!*/; F(y3, y3)/*T:IOut<(object?, string?)>!*/; F(y3, z3)/*T:IOut<(object?, string?)>!*/; F(z3, x3)/*T:IOut<(object, string)>!*/; F(z3, y3)/*T:IOut<(object?, string?)>!*/; F(z3, z3)/*T:IOut<(object, string)>!*/; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (12,15): warning CS8620: Nullability of reference types in argument of type 'I<(object?, string?)>' doesn't match target type 'I<(object, string)>' for parameter 'y' in 'I<(object, string)> C.F<I<(object, string)>>(I<(object, string)> x, I<(object, string)> y)'. // F(x1, y1)/*T:I<(object, string)>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<(object?, string?)>", "I<(object, string)>", "y", "I<(object, string)> C.F<I<(object, string)>>(I<(object, string)> x, I<(object, string)> y)").WithLocation(12, 15), // (14,11): warning CS8620: Nullability of reference types in argument of type 'I<(object?, string?)>' doesn't match target type 'I<(object, string)>' for parameter 'x' in 'I<(object, string)> C.F<I<(object, string)>>(I<(object, string)> x, I<(object, string)> y)'. // F(y1, x1)/*T:I<(object, string)>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<(object?, string?)>", "I<(object, string)>", "x", "I<(object, string)> C.F<I<(object, string)>>(I<(object, string)> x, I<(object, string)> y)").WithLocation(14, 11), // (26,15): warning CS8620: Nullability of reference types in argument of type 'IIn<(object?, string?)>' doesn't match target type 'IIn<(object, string)>' for parameter 'y' in 'IIn<(object, string)> C.F<IIn<(object, string)>>(IIn<(object, string)> x, IIn<(object, string)> y)'. // F(x2, y2)/*T:IIn<(object!, string!)>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y2").WithArguments("IIn<(object?, string?)>", "IIn<(object, string)>", "y", "IIn<(object, string)> C.F<IIn<(object, string)>>(IIn<(object, string)> x, IIn<(object, string)> y)").WithLocation(26, 15), // (28,11): warning CS8620: Nullability of reference types in argument of type 'IIn<(object?, string?)>' doesn't match target type 'IIn<(object, string)>' for parameter 'x' in 'IIn<(object, string)> C.F<IIn<(object, string)>>(IIn<(object, string)> x, IIn<(object, string)> y)'. // F(y2, x2)/*T:IIn<(object!, string!)>!*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y2").WithArguments("IIn<(object?, string?)>", "IIn<(object, string)>", "x", "IIn<(object, string)> C.F<IIn<(object, string)>>(IIn<(object, string)> x, IIn<(object, string)> y)").WithLocation(28, 11), // (40,11): warning CS8620: Nullability of reference types in argument of type 'IOut<(object, string)>' doesn't match target type 'IOut<(object?, string?)>' for parameter 'x' in 'IOut<(object?, string?)> C.F<IOut<(object?, string?)>>(IOut<(object?, string?)> x, IOut<(object?, string?)> y)'. // F(x3, y3)/*T:IOut<(object?, string?)>?*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x3").WithArguments("IOut<(object, string)>", "IOut<(object?, string?)>", "x", "IOut<(object?, string?)> C.F<IOut<(object?, string?)>>(IOut<(object?, string?)> x, IOut<(object?, string?)> y)").WithLocation(40, 11), // (42,15): warning CS8620: Nullability of reference types in argument of type 'IOut<(object, string)>' doesn't match target type 'IOut<(object?, string?)>' for parameter 'y' in 'IOut<(object?, string?)> C.F<IOut<(object?, string?)>>(IOut<(object?, string?)> x, IOut<(object?, string?)> y)'. // F(y3, x3)/*T:IOut<(object?, string?)>?*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x3").WithArguments("IOut<(object, string)>", "IOut<(object?, string?)>", "y", "IOut<(object?, string?)> C.F<IOut<(object?, string?)>>(IOut<(object?, string?)> x, IOut<(object?, string?)> y)").WithLocation(42, 15)); } [Fact] public void Assignment_NestedNullability_MismatchedNullability() { var source0 = @"public class A { public static object F; public static string G; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class B<T, U> { } class C { static B<T, U> CreateB<T, U>(T t, U u) => throw null!; static void G(object? t1, object t2, string? u1, string u2) { var t3 = A.F/*T:object!*/; var u3 = A.G/*T:string!*/; var x0 = CreateB(t1, u2)/*T:B<object?, string!>!*/; var y0 = CreateB(t2, u1)/*T:B<object!, string?>!*/; var z0 = CreateB(t1, u3)/*T:B<object?, string!>!*/; var w0 = CreateB(t3, u2)/*T:B<object!, string!>!*/; var x = x0; var y = y0; var z = z0; var w = w0; x = y0; // 1 x = z0; x = w0; // 2 y = z0; // 3 y = w0; // 4 w = z0; // 5 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (17,13): warning CS8619: Nullability of reference types in value of type 'B<object, string?>' doesn't match target type 'B<object?, string>'. // x = y0; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y0").WithArguments("B<object, string?>", "B<object?, string>").WithLocation(17, 13), // (19,13): warning CS8619: Nullability of reference types in value of type 'B<object, string>' doesn't match target type 'B<object?, string>'. // x = w0; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w0").WithArguments("B<object, string>", "B<object?, string>").WithLocation(19, 13), // (20,13): warning CS8619: Nullability of reference types in value of type 'B<object?, string>' doesn't match target type 'B<object, string?>'. // y = z0; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "z0").WithArguments("B<object?, string>", "B<object, string?>").WithLocation(20, 13), // (21,13): warning CS8619: Nullability of reference types in value of type 'B<object, string>' doesn't match target type 'B<object, string?>'. // y = w0; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "w0").WithArguments("B<object, string>", "B<object, string?>").WithLocation(21, 13), // (22,13): warning CS8619: Nullability of reference types in value of type 'B<object?, string>' doesn't match target type 'B<object, string>'. // w = z0; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "z0").WithArguments("B<object?, string>", "B<object, string>").WithLocation(22, 13) ); } [Fact] public void TypeInference_09() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>(I<T> x, I<T> y) { throw new System.Exception(); } static void G1(I<string> x1, I<string?> y1) { F(x1, x1)/*T:string!*/.ToString(); F(x1, y1)/*T:string!*/.ToString(); F(y1, x1)/*T:string!*/.ToString(); F(y1, y1)/*T:string?*/.ToString(); } static T F<T>(IIn<T> x, IIn<T> y) { throw new System.Exception(); } static void G2(IIn<string> x2, IIn<string?> y2) { F(x2, x2)/*T:string!*/.ToString(); F(x2, y2)/*T:string!*/.ToString(); F(y2, x2)/*T:string!*/.ToString(); F(y2, y2)/*T:string?*/.ToString(); } static T F<T>(IOut<T> x, IOut<T> y) { throw new System.Exception(); } static void G3(IOut<string> x3, IOut<string?> y3) { F(x3, x3)/*T:string!*/.ToString(); F(x3, y3)/*T:string?*/.ToString(); F(y3, x3)/*T:string?*/.ToString(); F(y3, y3)/*T:string?*/.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyTypes(); comp.VerifyDiagnostics( // (13,15): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'y' in 'string C.F<string>(I<string> x, I<string> y)'. // F(x1, y1)/*T:string!*/.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<string?>", "I<string>", "y", "string C.F<string>(I<string> x, I<string> y)").WithLocation(13, 15), // (14,11): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'x' in 'string C.F<string>(I<string> x, I<string> y)'. // F(y1, x1)/*T:string!*/.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<string?>", "I<string>", "x", "string C.F<string>(I<string> x, I<string> y)").WithLocation(14, 11), // (15,9): warning CS8602: Dereference of a possibly null reference. // F(y1, y1)/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y1, y1)").WithLocation(15, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // F(y2, y2)/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y2, y2)").WithLocation(26, 9), // (35,9): warning CS8602: Dereference of a possibly null reference. // F(x3, y3)/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x3, y3)").WithLocation(35, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // F(y3, x3)/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y3, x3)").WithLocation(36, 9), // (37,9): warning CS8602: Dereference of a possibly null reference. // F(y3, y3)/*T:string?*/.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y3, y3)").WithLocation(37, 9)); } [Fact] public void TypeInference_10() { var source = @"interface I<T> { } interface IIn<in T> { } interface IOut<out T> { } class C { static T F<T>(I<T> x, I<T?> y) where T : class { throw new System.Exception(); } static void G1(I<string> x1, I<string?> y1) { F(x1, x1).ToString(); // 1 F(x1, y1).ToString(); F(y1, x1).ToString(); // 2 and 3 F(y1, y1).ToString(); // 4 } static T F<T>(IIn<T> x, IIn<T?> y) where T : class { throw new System.Exception(); } static void G2(IIn<string> x2, IIn<string?> y2) { F(x2, x2).ToString(); // 5 F(x2, y2).ToString(); F(y2, x2).ToString(); // 6 F(y2, y2).ToString(); } static T F<T>(IOut<T> x, IOut<T?> y) where T : class { throw new System.Exception(); } static void G3(IOut<string> x3, IOut<string?> y3) { F(x3, x3).ToString(); F(x3, y3).ToString(); F(y3, x3).ToString(); // 7 F(y3, y3).ToString(); // 8 } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,15): warning CS8620: Nullability of reference types in argument of type 'I<string>' doesn't match target type 'I<string?>' for parameter 'y' in 'string C.F<string>(I<string> x, I<string?> y)'. // F(x1, x1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1").WithArguments("I<string>", "I<string?>", "y", "string C.F<string>(I<string> x, I<string?> y)").WithLocation(12, 15), // (14,11): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'x' in 'string C.F<string>(I<string> x, I<string?> y)'. // F(y1, x1).ToString(); // 2 and 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<string?>", "I<string>", "x", "string C.F<string>(I<string> x, I<string?> y)").WithLocation(14, 11), // (14,15): warning CS8620: Nullability of reference types in argument of type 'I<string>' doesn't match target type 'I<string?>' for parameter 'y' in 'string C.F<string>(I<string> x, I<string?> y)'. // F(y1, x1).ToString(); // 2 and 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x1").WithArguments("I<string>", "I<string?>", "y", "string C.F<string>(I<string> x, I<string?> y)").WithLocation(14, 15), // (15,11): warning CS8620: Nullability of reference types in argument of type 'I<string?>' doesn't match target type 'I<string>' for parameter 'x' in 'string C.F<string>(I<string> x, I<string?> y)'. // F(y1, y1).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("I<string?>", "I<string>", "x", "string C.F<string>(I<string> x, I<string?> y)").WithLocation(15, 11), // (23,15): warning CS8620: Nullability of reference types in argument of type 'IIn<string>' doesn't match target type 'IIn<string?>' for parameter 'y' in 'string C.F<string>(IIn<string> x, IIn<string?> y)'. // F(x2, x2).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x2").WithArguments("IIn<string>", "IIn<string?>", "y", "string C.F<string>(IIn<string> x, IIn<string?> y)").WithLocation(23, 15), // (25,15): warning CS8620: Nullability of reference types in argument of type 'IIn<string>' doesn't match target type 'IIn<string?>' for parameter 'y' in 'string C.F<string>(IIn<string> x, IIn<string?> y)'. // F(y2, x2).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x2").WithArguments("IIn<string>", "IIn<string?>", "y", "string C.F<string>(IIn<string> x, IIn<string?> y)").WithLocation(25, 15), // (36,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>(IOut<T>, IOut<T?>)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // F(y3, x3).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>(IOut<T>, IOut<T?>)", "T", "string?").WithLocation(36, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // F(y3, x3).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y3, x3)").WithLocation(36, 9), // (37,9): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>(IOut<T>, IOut<T?>)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // F(y3, y3).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F").WithArguments("C.F<T>(IOut<T>, IOut<T?>)", "T", "string?").WithLocation(37, 9), // (37,9): warning CS8602: Dereference of a possibly null reference. // F(y3, y3).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y3, y3)").WithLocation(37, 9)); } [Fact] public void TypeInference_11() { var source0 = @"public class A<T> { public T F; } public class UnknownNull { public A<object> A1; }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source1 = @"#pragma warning disable 8618 public class MaybeNull { public A<object?> A2; } public class NotNull { public A<object> A3; }"; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { ref0 }); comp1.VerifyDiagnostics(); var ref1 = comp1.EmitToImageReference(); var source = @"class C { static T F<T>(T x, T y) => throw null!; static void F1(UnknownNull x1, UnknownNull y1) { F(x1.A1, y1.A1)/*T:A<object>!*/.F.ToString(); } static void F2(UnknownNull x2, MaybeNull y2) { F(x2.A1, y2.A2)/*T:A<object?>!*/.F.ToString(); } static void F3(MaybeNull x3, UnknownNull y3) { F(x3.A2, y3.A1)/*T:A<object?>!*/.F.ToString(); } static void F4(MaybeNull x4, MaybeNull y4) { F(x4.A2, y4.A2)/*T:A<object?>!*/.F.ToString(); } static void F5(UnknownNull x5, NotNull y5) { F(x5.A1, y5.A3)/*T:A<object!>!*/.F.ToString(); } static void F6(NotNull x6, UnknownNull y6) { F(x6.A3, y6.A1)/*T:A<object!>!*/.F.ToString(); } static void F7(MaybeNull x7, NotNull y7) { F(x7.A2, y7.A3)/*T:A<object!>!*/.F.ToString(); } static void F8(NotNull x8, MaybeNull y8) { F(x8.A3, y8.A2)/*T:A<object!>!*/.F.ToString(); } static void F9(NotNull x9, NotNull y9) { F(x9.A3, y9.A3)/*T:A<object!>!*/.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0, ref1 }); comp.VerifyTypes(); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(x2.A1, y2.A2)/*T:A<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x2.A1, y2.A2)/*T:A<object?>!*/.F").WithLocation(10, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F(x3.A2, y3.A1)/*T:A<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x3.A2, y3.A1)/*T:A<object?>!*/.F").WithLocation(14, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F(x4.A2, y4.A2)/*T:A<object?>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x4.A2, y4.A2)/*T:A<object?>!*/.F").WithLocation(18, 9), // (30,11): warning CS8620: Nullability of reference types in argument of type 'A<object?>' doesn't match target type 'A<object>' for parameter 'x' in 'A<object> C.F<A<object>>(A<object> x, A<object> y)'. // F(x7.A2, y7.A3)/*T:A<object!>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x7.A2").WithArguments("A<object?>", "A<object>", "x", "A<object> C.F<A<object>>(A<object> x, A<object> y)").WithLocation(30, 11), // (34,18): warning CS8620: Nullability of reference types in argument of type 'A<object?>' doesn't match target type 'A<object>' for parameter 'y' in 'A<object> C.F<A<object>>(A<object> x, A<object> y)'. // F(x8.A3, y8.A2)/*T:A<object!>!*/.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y8.A2").WithArguments("A<object?>", "A<object>", "y", "A<object> C.F<A<object>>(A<object> x, A<object> y)").WithLocation(34, 18) ); } [Fact] public void TypeInference_12() { var source = @"class C<T> { internal T F; } class C { static C<T> Create<T>(T t) { return new C<T>(); } static void F(object? x) { if (x == null) { Create(x).F = null; var y = Create(x); y.F = null; } else { Create(x).F = null; // warn var y = Create(x); y.F = null; // warn } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,16): warning CS8618: Non-nullable field 'F' is uninitialized. Consider declaring the field as nullable. // internal T F; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "F").WithArguments("field", "F").WithLocation(3, 16), // (21,27): warning CS8625: Cannot convert null literal to non-nullable reference type. // Create(x).F = null; // warn Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 27), // (23,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // y.F = null; // warn Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(23, 19)); } [Fact] [WorkItem(49472, "https://github.com/dotnet/roslyn/issues/49472")] public void TypeInference_13() { var source = @"#nullable enable using System; using System.Collections.Generic; static class Program { static void Main() { var d1 = new Dictionary<string, string?>(); var d2 = d1.ToDictionary(kv => kv.Key, kv => kv.Value); d2[""""].ToString(); } static Dictionary<TKey, TValue> ToDictionary<TSource, TKey, TValue>(this IEnumerable<TSource> e, Func<TSource, TKey> k, Func<TSource, TValue> v) { return new Dictionary<TKey, TValue>(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // d2[""].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, @"d2[""""]").WithLocation(10, 9)); var syntaxTree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(syntaxTree); var localDeclaration = syntaxTree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ElementAt(1); var symbol = model.GetDeclaredSymbol(localDeclaration); Assert.Equal("System.Collections.Generic.Dictionary<System.String!, System.String?>? d2", symbol.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void TypeInference_ArgumentOrder() { var source = @"interface I<T> { T P { get; } } class C { static T F<T, U>(I<T> x, I<U> y) => x.P; static void M(I<object?> x, I<string> y) { F(y: y, x: x).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // F(y: y, x: x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y: y, x: x)").WithLocation(10, 9)); } [Fact] public void TypeInference_Local() { var source = @"class C { static T F<T>(T t) => t; static void G() { object x = new object(); object? y = x; F(x).ToString(); F(y).ToString(); y = null; F(y).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // F(y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y)").WithLocation(11, 9)); } [Fact] public void TypeInference_Call() { var source = @"class C { static T F<T>(T t) => t; static object F1() => new object(); static object? F2() => null; static void G() { F(F1()).ToString(); F(F2()).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F(F2()).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(F2())").WithLocation(9, 9)); } [Fact] public void TypeInference_Property() { var source = @"class C { static T F<T>(T t) => t; static object P => new object(); static object? Q => null; static void G() { F(P).ToString(); F(Q).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F(Q).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(Q)").WithLocation(9, 9)); } [Fact] public void TypeInference_FieldAccess() { var source = @"class C { static T F<T>(T t) => t; static object F1 = new object(); static object? F2 = null; static void G() { F(F1).ToString(); F(F2).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F(F2).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(F2)").WithLocation(9, 9)); } [Fact] public void TypeInference_Literal() { var source = @"class C { static T F<T>(T t) => t; static void G() { F(0).ToString(); F('A').ToString(); F(""B"").ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_Default() { var source = @"class C { static T F<T>(T t) => t; static void G() { F(default(object)).ToString(); F(default(int)).ToString(); F(default(string)).ToString(); F(default).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,9): error CS0411: The type arguments for method 'C.F<T>(T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // F(default).ToString(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "F").WithArguments("C.F<T>(T)").WithLocation(9, 9), // (6,9): warning CS8602: Dereference of a possibly null reference. // F(default(object)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(default(object))").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F(default(string)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(default(string))").WithLocation(8, 9)); } [Fact] public void TypeInference_Tuple_01() { var source = @"class C { static (T, U) F<T, U>((T, U) t) => t; static void G(string x, string? y) { var t = (x, y); F(t).Item1.ToString(); F(t).Item2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F(t).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(t).Item2").WithLocation(8, 9)); } [Fact] public void TypeInference_Tuple_02() { var source = @"class C { static T F<T>(T t) => t; static void G(string x, string? y) { var t = (x, y); F(t).Item1.ToString(); F(t).Item2.ToString(); F(t).x.ToString(); F(t).y.ToString(); var u = (a: x, b: y); F(u).Item1.ToString(); F(u).Item2.ToString(); F(u).a.ToString(); F(u).b.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F(t).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(t).Item2").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F(t).y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(t).y").WithLocation(10, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F(u).Item2.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(u).Item2").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F(u).b.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(u).b").WithLocation(15, 9)); } [Fact] public void TypeInference_Tuple_03() { var source = @"class C { static void F(object? x, object? y) { if (x == null) return; var t = (x, y); t.x.ToString(); t.y.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.y").WithLocation(8, 9)); } [Fact] public void TypeInference_ObjectCreation() { var source = @"class C { static T F<T>(T t) => t; static void G() { F(new C { }).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_DelegateCreation() { var source = @"delegate void D(); class C { static T F<T>(T t) => t; static void G() { F(new D(G)).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_BinaryOperator() { var source = @"class C { static T F<T>(T t) => t; static void G(string x, string? y) { F(x + x).ToString(); F(x + y).ToString(); F(y + x).ToString(); F(y + y).ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [Fact] public void TypeInference_NullCoalescingOperator() { var source = @"class C { static T F<T>(T t) => t; static void G(int i, object x, object? y) { switch (i) { case 1: F(x ?? x).ToString(); break; case 2: F(x ?? y).ToString(); break; case 3: F(y ?? x).ToString(); break; case 4: F(y ?? y).ToString(); break; } } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // F(x ?? x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x ?? x)").WithLocation(9, 17), // (12,17): warning CS8602: Dereference of a possibly null reference. // F(x ?? y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(x ?? y)").WithLocation(12, 17), // (18,17): warning CS8602: Dereference of a possibly null reference. // F(y ?? y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(y ?? y)").WithLocation(18, 17)); } [Fact] public void Members_Fields() { var source = @"#pragma warning disable 0649 class C { internal string? F; } class Program { static void F(C a) { G(a.F); if (a.F != null) G(a.F); C b = new C(); G(b.F); if (b.F != null) G(b.F); } static void G(string s) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.G(string s)'. // G(a.F); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a.F").WithArguments("s", "void Program.G(string s)").WithLocation(10, 11), // (13,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.G(string s)'. // G(b.F); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b.F").WithArguments("s", "void Program.G(string s)").WithLocation(13, 11)); } [Fact] public void Members_Fields_UnconstrainedType() { var source = @" class C<T> { internal T field = default; static void F(C<T> a, bool c) { if (c) a.field.ToString(); // 1 else if (a.field != null) a.field.ToString(); C<T> b = new C<T>(); if (c) b.field.ToString(); // 2 else if (b.field != null) b.field.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,24): warning CS8601: Possible null reference assignment. // internal T field = default; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(4, 24), // (8,16): warning CS8602: Dereference of a possibly null reference. // if (c) a.field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.field").WithLocation(8, 16), // (11,16): warning CS8602: Dereference of a possibly null reference. // if (c) b.field.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.field").WithLocation(11, 16)); } [Fact] public void Members_AutoProperties() { var source = @"class C { internal string? P { get; set; } } class Program { static void F(C a) { G(a.P); if (a.P != null) G(a.P); C b = new C(); G(b.P); if (b.P != null) G(b.P); } static void G(string s) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.G(string s)'. // G(a.P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a.P").WithArguments("s", "void Program.G(string s)").WithLocation(9, 11), // (12,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.G(string s)'. // G(b.P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b.P").WithArguments("s", "void Program.G(string s)").WithLocation(12, 11)); } [Fact] public void Members_Properties() { var source = @"class C { internal string? P { get { throw new System.Exception(); } set { } } } class Program { static void F(C a) { G(a.P); if (a.P != null) G(a.P); C b = new C(); G(b.P); if (b.P != null) G(b.P); } static void G(string s) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.G(string s)'. // G(a.P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a.P").WithArguments("s", "void Program.G(string s)").WithLocation(9, 11), // (12,11): warning CS8604: Possible null reference argument for parameter 's' in 'void Program.G(string s)'. // G(b.P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b.P").WithArguments("s", "void Program.G(string s)").WithLocation(12, 11)); } [Fact] public void Members_AutoPropertyFromConstructor() { var source = @"class A { protected static void F(string s) { } protected string? P { get; set; } protected A() { F(P); if (P != null) F(P); } } class B : A { B() { F(this.P); if (this.P != null) F(this.P); F(base.P); if (base.P != null) F(base.P); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,11): warning CS8604: Possible null reference argument for parameter 's' in 'void A.F(string s)'. // F(this.P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "this.P").WithArguments("s", "void A.F(string s)").WithLocation(17, 11), // (19,11): warning CS8604: Possible null reference argument for parameter 's' in 'void A.F(string s)'. // F(base.P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "base.P").WithArguments("s", "void A.F(string s)").WithLocation(19, 11), // (9,11): warning CS8604: Possible null reference argument for parameter 's' in 'void A.F(string s)'. // F(P); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "P").WithArguments("s", "void A.F(string s)").WithLocation(9, 11)); } [Fact] public void ModifyMembers_01() { var source = @"#pragma warning disable 0649 class C { object? F; static void M(C c) { if (c.F == null) return; c = new C(); c.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F").WithLocation(9, 9)); } [Fact] public void ModifyMembers_02() { var source = @"#pragma warning disable 0649 class A { internal C? C; } class B { internal A? A; } class C { internal B? B; } class Program { static void F() { object o; C? c = new C(); c.B = new B(); c.B.A = new A(); o = c.B.A; // 1 c.B.A = null; o = c.B.A; // 2 c.B = new B(); o = c.B.A; // 3 c.B = null; o = c.B.A; // 4 c = new C(); o = c.B.A; // 5 c = null; o = c.B.A; // 6 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (24,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.A; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.A").WithLocation(24, 13), // (26,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.A; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.A").WithLocation(26, 13), // (28,13): warning CS8602: Dereference of a possibly null reference. // o = c.B.A; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.B").WithLocation(28, 13), // (28,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.A; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.A").WithLocation(28, 13), // (30,13): warning CS8602: Dereference of a possibly null reference. // o = c.B.A; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.B").WithLocation(30, 13), // (30,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.A; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.A").WithLocation(30, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // o = c.B.A; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(32, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // o = c.B.A; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.B").WithLocation(32, 13), // (32,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.A; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.A").WithLocation(32, 13)); } [Fact] public void ModifyMembers_03() { var source = @"#pragma warning disable 0649 struct S { internal object? F; } class C { internal C? A; internal S B; } class Program { static void M() { object o; C c = new C(); o = c.A.A; // 1 o = c.B.F; // 1 c.A = new C(); c.B = new S(); o = c.A.A; // 2 o = c.B.F; // 2 c.A.A = new C(); c.B.F = new C(); o = c.A.A; // 3 o = c.B.F; // 3 c.A = new C(); c.B = new S(); o = c.A.A; // 4 o = c.B.F; // 4 c = new C(); o = c.A.A; // 5 o = c.B.F; // 5 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,13): warning CS8602: Dereference of a possibly null reference. // o = c.A.A; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.A").WithLocation(17, 13), // (17,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(17, 13), // (18,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.F; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.F").WithLocation(18, 13), // (21,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(21, 13), // (22,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.F; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.F").WithLocation(22, 13), // (29,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(29, 13), // (30,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.F; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.F").WithLocation(30, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // o = c.A.A; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.A").WithLocation(32, 13), // (32,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(32, 13), // (33,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.F; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.F").WithLocation(33, 13)); } [Fact] public void ModifyMembers_Properties() { var source = @"#pragma warning disable 0649 struct S { internal object? P { get; set; } } class C { internal C? A { get; set; } internal S B; } class Program { static void M() { object o; C c = new C(); o = c.A.A; // 1 o = c.B.P; // 1 c.A = new C(); c.B = new S(); o = c.A.A; // 2 o = c.B.P; // 2 c.A.A = new C(); c.B.P = new C(); o = c.A.A; // 3 o = c.B.P; // 3 c.A = new C(); c.B = new S(); o = c.A.A; // 4 o = c.B.P; // 4 c = new C(); o = c.A.A; // 5 o = c.B.P; // 5 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,13): warning CS8602: Dereference of a possibly null reference. // o = c.A.A; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.A").WithLocation(17, 13), // (17,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(17, 13), // (18,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.P; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.P").WithLocation(18, 13), // (21,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(21, 13), // (22,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.P; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.P").WithLocation(22, 13), // (29,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(29, 13), // (30,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.P; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.P").WithLocation(30, 13), // (32,13): warning CS8602: Dereference of a possibly null reference. // o = c.A.A; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.A").WithLocation(32, 13), // (32,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.A.A; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.A.A").WithLocation(32, 13), // (33,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = c.B.P; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c.B.P").WithLocation(33, 13)); } [Fact] public void ModifyMembers_Struct() { var source = @"#pragma warning disable 0649 struct A { internal object? F; } struct B { internal A A; internal object? G; } class Program { static void F() { object o; B b = new B(); b.G = new object(); b.A.F = new object(); o = b.G; // 1 o = b.A.F; // 1 b.A = default(A); o = b.G; // 2 o = b.A.F; // 2 b = default(B); o = b.G; // 3 o = b.A.F; // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = b.A.F; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b.A.F").WithLocation(23, 13), // (25,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = b.G; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b.G").WithLocation(25, 13), // (26,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = b.A.F; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "b.A.F").WithLocation(26, 13)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void ModifyMembers_StructPropertyExplicitAccessors() { var source = @"#pragma warning disable 0649 struct S { private object? _p; internal object? P { get { return _p; } set { _p = value; } } } class C { S F; void M() { object o; o = F.P; // 1 F.P = new object(); o = F.P; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = F.P; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F.P").WithLocation(13, 13)); } [Fact] public void ModifyMembers_StructProperty() { var source = @"#pragma warning disable 0649 public struct S { public object? P { get; set; } } class C { S F; void M() { object o; o = F.P; // 1 F.P = new object(); o = F.P; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = F.P; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F.P").WithLocation(12, 13)); } [Fact] public void ModifyMembers_StructPropertyFromMetadata() { var source0 = @"public struct S { public object? P { get; set; } }"; var comp0 = CreateCompilation(source0); var ref0 = comp0.EmitToImageReference(); var source = @"#pragma warning disable 0649 class C { S F; void M() { object o; o = F.P; // 1 F.P = new object(); o = F.P; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = F.P; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F.P").WithLocation(8, 13)); } [Fact] public void ModifyMembers_ClassPropertyNoBackingField() { var source = @"#pragma warning disable 0649 class C { object? P { get { return null; } set { } } void M() { object o; o = P; // 1 P = new object(); o = P; // 2 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = P; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "P").WithLocation(8, 13)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void ModifyMembers_StructPropertyNoBackingField_01() { var source = @"#pragma warning disable 0649 struct S { internal object? P { get { return null; } set { } } } class C { S F; void M() { object o; o = F.P; // 1 F.P = new object(); o = F.P; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // o = F.P; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F.P").WithLocation(12, 13)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void ModifyMembers_StructPropertyNoBackingField_02() { var source = @"struct S<T> { internal T P => throw null!; } class Program { static S<T> Create<T>(T t) { return new S<T>(); } static void F<T>() where T : class, new() { T? x = null; var sx = Create(x); sx.P.ToString(); T? y = new T(); var sy = Create(y); sy.P.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Possible dereference of a null reference. // sx.P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "sx.P").WithLocation(15, 9)); } // Calling a method should reset the state for members. [Fact] [WorkItem(29975, "https://github.com/dotnet/roslyn/issues/29975")] public void Members_CallMethod() { var source = @"#pragma warning disable 0649 class A { internal object? P { get; set; } } class B { internal A? Q { get; set; } } class Program { static void M() { object o; B b = new B() { Q = new A() { P = new object() } }; o = b.Q.P; // 1 b.Q.P.ToString(); o = b.Q.P; // 2 b.Q.ToString(); o = b.Q.P; // 3 b = new B() { Q = new A() { P = new object() } }; o = b.Q.P; // 4 b.ToString(); o = b.Q.P; // 5 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29975: Should report warnings. comp.VerifyDiagnostics(/*...*/); } [Fact] public void Members_ObjectInitializer() { var source = @"#pragma warning disable 0649 class A { internal object? F1; internal object? F2; } class B { internal A? G; } class Program { static void F() { (new B() { G = new A() { F1 = new object() } }).G.F1.ToString(); B b; b = new B() { G = new A() { F1 = new object() } }; b.G.F1.ToString(); // 1 b.G.F2.ToString(); // 1 b = new B() { G = new A() { F2 = new object() } }; b.G.F1.ToString(); // 2 b.G.F2.ToString(); // 2 b = new B() { G = new A() }; b.G.F1.ToString(); // 3 b.G.F2.ToString(); // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // b.G.F2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F2").WithLocation(19, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // b.G.F1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F1").WithLocation(21, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // b.G.F1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F1").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // b.G.F2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F2").WithLocation(25, 9)); } [Fact] public void Members_ObjectInitializer_Struct() { var source = @"#pragma warning disable 0649 struct A { internal object? F1; internal object? F2; } struct B { internal A G; } class Program { static void F() { (new B() { G = new A() { F1 = new object() } }).G.F1.ToString(); B b; b = new B() { G = new A() { F1 = new object() } }; b.G.F1.ToString(); // 1 b.G.F2.ToString(); // 1 b = new B() { G = new A() { F2 = new object() } }; b.G.F1.ToString(); // 2 b.G.F2.ToString(); // 2 b = new B() { G = new A() }; b.G.F1.ToString(); // 3 b.G.F2.ToString(); // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // b.G.F2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F2").WithLocation(19, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // b.G.F1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F1").WithLocation(21, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // b.G.F1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F1").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // b.G.F2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.G.F2").WithLocation(25, 9)); } [Fact] public void Members_ObjectInitializer_Properties() { var source = @"#pragma warning disable 0649 class A { internal object? P1 { get; set; } internal object? P2 { get; set; } } class B { internal A? Q { get; set; } } class Program { static void F() { (new B() { Q = new A() { P1 = new object() } }).Q.P1.ToString(); B b; b = new B() { Q = new A() { P1 = new object() } }; b.Q.P1.ToString(); // 1 b.Q.P2.ToString(); // 1 b = new B() { Q = new A() { P2 = new object() } }; b.Q.P1.ToString(); // 2 b.Q.P2.ToString(); // 2 b = new B() { Q = new A() }; b.Q.P1.ToString(); // 3 b.Q.P2.ToString(); // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // b.Q.P2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Q.P2").WithLocation(19, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // b.Q.P1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Q.P1").WithLocation(21, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // b.Q.P1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Q.P1").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // b.Q.P2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.Q.P2").WithLocation(25, 9)); } [Fact] public void Members_ObjectInitializer_Events() { var source = @"delegate void D(); class C { event D? E; static void F() { C c; c = new C() { }; c.E.Invoke(); // warning c = new C() { E = F }; c.E.Invoke(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c.E.Invoke(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.E").WithLocation(9, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Members_ObjectInitializer_DerivedType() { var source = @"#pragma warning disable 0649 class A { internal A? F; } class B : A { internal object? G; } class Program { static void Main() { A a; a = new B() { F = new A(), G = new object() }; a.F.ToString(); a = new A(); a.F.ToString(); // 1 a = new B() { F = new B() { F = new A() } }; a.F.ToString(); a.F.F.ToString(); a = new B() { G = new object() }; a.F.ToString(); // 2 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // a.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.F").WithLocation(18, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // a.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.F").WithLocation(23, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Members_Assignment() { var source = @"#pragma warning disable 0649 class A { internal A? F; } class B : A { internal object? G; } class Program { static void Main() { B b = new B(); A a; a = b; a.F.ToString(); // 1 b.F = new A(); a = b; a.F.ToString(); b = new B() { F = new B() { F = new A() } }; a = b; a.F.ToString(); a.F.F.ToString(); b = new B() { G = new object() }; a = b; a.F.ToString(); // 2 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,9): warning CS8602: Dereference of a possibly null reference. // a.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.F").WithLocation(17, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // a.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.F").WithLocation(27, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_01() { var source = @"class A { internal object? FA; } class B : A { internal object FB = new object(); } class Program { static void F() { A a = new B() { FA = 1 }; a.FA.ToString(); a = new B() { FA = 2, FB = null }; // 1 ((B)a).FA.ToString(); // 2 ((B)a).FB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // a = new B() { FA = 2, FB = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 36), // (16,9): warning CS8602: Dereference of a possibly null reference. // ((B)a).FA.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((B)a).FA").WithLocation(16, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_02() { var source = @"class A { internal object? FA; } class B : A { internal object FB = new object(); } class Program { static void F() { B b = new B() { FA = 1 }; A a = b; a.FA.ToString(); a = new B() { FB = null }; // 1 b = (B)a; b.FB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // a = new B() { FB = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 28)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_03() { var source = @"interface IA { object? PA { get; set; } } interface IB : IA { object PB { get; set; } } class Program { static void F(IB b) { b.PA = 1; b.PB = null; // 1 ((IA)b).PA.ToString(); ((IB)(object)b).PB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // b.PB = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 16)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_04() { var source = @"interface IA { object? PA { get; set; } } interface IB : IA { object PB { get; set; } } class Program { static void F(IB b) { b.PA = 1; b.PB = null; // 1 object o = b; b = o; // 2 b.PA.ToString(); // 3 b = (IB)o; b.PB.ToString(); ((IB)o).PA.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // b.PB = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 16), // (16,13): error CS0266: Cannot implicitly convert type 'object' to 'IB'. An explicit conversion exists (are you missing a cast?) // b = o; // 2 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "o").WithArguments("object", "IB").WithLocation(16, 13), // (17,9): warning CS8602: Dereference of a possibly null reference. // b.PA.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.PA").WithLocation(17, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // ((IB)o).PA.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((IB)o).PA").WithLocation(20, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_05() { var source = @"#pragma warning disable 0649 class C { internal object? F; } class Program { static void F(object x, object? y) { if (((C)x).F != null) ((C)x).F.ToString(); // 1 if (((C?)y)?.F != null) ((C)y).F.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // ((C)x).F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((C)x).F").WithLocation(11, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // ((C)y).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((C)y).F").WithLocation(13, 13) ); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_06() { var source = @"class C { internal object F() => null!; } class Program { static void F(object? x) { if (((C?)x)?.F() != null) ((C)x).F().ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_07() { var source = @"interface I { object? P { get; } } class Program { static void F(object x, object? y) { if (((I)x).P != null) ((I)x).P.ToString(); // 1 if (((I?)y)?.P != null) ((I)y).P.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // ((I)x).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((I)x).P").WithLocation(10, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // ((I)y).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((I)y).P").WithLocation(12, 13) ); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_08() { var source = @"interface I { object F(); } class Program { static void F(object? x) { if (((I?)x)?.F() != null) ((I)x).F().ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_09() { var source = @"class A { internal bool? F; } class B : A { } class Program { static void M(bool b1, bool b2) { A a; if (b1 ? b2 && (a = new B() { F = true }).F.Value : false) { } if (true ? b2 && (a = new B() { F = false }).F.Value : false) { } if (false ? false : b2 && (a = new B() { F = b1 }).F.Value) { } if (false ? b2 && (a = new B() { F = null }).F.Value : true) { } _ = (a = new B() { F = null }).F.Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (25,13): warning CS8629: Nullable value type may be null. // _ = (a = new B() { F = null }).F.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(a = new B() { F = null }).F").WithLocation(25, 13)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_ReferenceConversions_10() { var source = @"class A { internal object? FA; } class B : A { internal object FB = new object(); } class Program { static void F() { A a = new B() { FB = null }; // 1 a = new A() { FA = 1 }; a.FA.ToString(); ((B)a).FB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,30): warning CS8625: Cannot convert null literal to non-nullable reference type. // A a = new B() { FB = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 30)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Conversions_NullableConversions_01() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F4<T>() where T : struct, I { T? t = new T() { P = 4, Q = null }; // 1 t.Value.P.ToString(); t.Value.Q.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // T? t = new T() { P = 4, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 37), // (12,9): warning CS8602: Dereference of a possibly null reference. // t.Value.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Value.Q").WithLocation(12, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_NullableConversions_02() { var source = @"class C { internal object? F; internal object G = null!; } class Program { static void F() { (C, C)? t = (new C() { F = 1 }, new C() { G = null }); // 1 (((C, C))t).Item1.F.ToString(); (((C, C))t).Item2.G.ToString(); // 2 (C, C)? u = (new C() { F = 2 }, new C() { G = null }); // 3 ((C)u.Value.Item1).F.ToString(); ((C)u.Value.Item2).G.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,55): warning CS8625: Cannot convert null literal to non-nullable reference type. // (C, C)? t = (new C() { F = 1 }, new C() { G = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 55), // (12,9): warning CS8602: Dereference of a possibly null reference. // (((C, C))t).Item2.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(((C, C))t).Item2.G").WithLocation(12, 9), // (13,55): warning CS8625: Cannot convert null literal to non-nullable reference type. // (C, C)? u = (new C() { F = 2 }, new C() { G = null }); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 55), // (15,9): warning CS8602: Dereference of a possibly null reference. // ((C)u.Value.Item2).G.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((C)u.Value.Item2).G").WithLocation(15, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Conversions_NullableConversions_03() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { (S, S)? t = (new S() { F = 1 }, new S() { G = null }); // 1 (((S, S))t).Item1.F.ToString(); (((S, S))t).Item2.G.ToString(); // 2 (S, S)? u = (new S() { F = 2 }, new S() { G = null }); // 3 ((S)u.Value.Item1).F.ToString(); ((S)u.Value.Item2).G.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,55): warning CS8625: Cannot convert null literal to non-nullable reference type. // (S, S)? t = (new S() { F = 1 }, new S() { G = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 55), // (12,9): warning CS8602: Dereference of a possibly null reference. // (((S, S))t).Item2.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(((S, S))t).Item2.G").WithLocation(12, 9), // (13,55): warning CS8625: Cannot convert null literal to non-nullable reference type. // (S, S)? u = (new S() { F = 2 }, new S() { G = null }); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 55), // (15,9): warning CS8602: Dereference of a possibly null reference. // ((S)u.Value.Item2).G.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((S)u.Value.Item2).G").WithLocation(15, 9)); } [Fact] public void Conversions_NullableConversions_04() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F1(string x1) { S y1 = new S() { F = 1, G = null }; // 1 (object, S)? t1 = (x1, y1); t1.Value.Item2.F.ToString(); t1.Value.Item2.G.ToString(); // 2 } static void F2(string x2) { S y2 = new S() { F = 1, G = null }; // 3 var t2 = ((object, S)?)(x2, y2); t2.Value.Item2.F.ToString(); t2.Value.Item2.G.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S y1 = new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 37), // (13,9): warning CS8602: Dereference of a possibly null reference. // t1.Value.Item2.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1.Value.Item2.G").WithLocation(13, 9), // (17,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S y2 = new S() { F = 1, G = null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(17, 37), // (20,9): warning CS8602: Dereference of a possibly null reference. // t2.Value.Item2.G.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2.Value.Item2.G").WithLocation(20, 9)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void Conversions_NullableConversions_05() { var source = @"struct S { internal object? P { get; set; } internal object Q { get; set; } } class Program { static void Main() { S? s = new S() { P = 1, Q = null }; // 1 s.Value.P.ToString(); s.Value.Q.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S? s = new S() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 37), // (12,9): warning CS8602: Dereference of a possibly null reference. // s.Value.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.Value.Q").WithLocation(12, 9)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void Conversions_NullableConversions_06() { var source = @"struct S { private object? _p; private object _q; internal object? P { get { return _p; } set { _p = value; } } internal object Q { get { return _q; } set { _q = value; } } } class Program { static void Main() { S? s = new S() { P = 1, Q = null }; // 1 s.Value.P.ToString(); s.Value.Q.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S? s = new S() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(12, 37), // (14,9): warning CS8602: Dereference of a possibly null reference. // s.Value.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.Value.Q").WithLocation(14, 9)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void Conversions_NullableConversions_07() { var source = @"struct S { internal object? P { get { return 1; } set { } } internal object Q { get { return 2; } set { } } } class Program { static void Main() { S? s = new S() { P = 1, Q = null }; // 1 s.Value.P.ToString(); s.Value.Q.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // S? s = new S() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 37), // (12,9): warning CS8602: Dereference of a possibly null reference. // s.Value.Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.Value.Q").WithLocation(12, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_TupleConversions_01() { var source = @"class A { internal object? FA; } class B : A { internal object FB = new object(); } class Program { static void F() { (B, object) t = (new B() { FA = 1 }, new B() { FB = null }); // 1 t.Item1.FA.ToString(); ((A)t.Item1).FA.ToString(); ((B)t.Item2).FB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,61): warning CS8625: Cannot convert null literal to non-nullable reference type. // (B, object) t = (new B() { FA = 1 }, new B() { FB = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 61)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_TupleConversions_02() { var source = @"class A { internal object? FA; } class B : A { internal object FB = new object(); } class Program { static void F() { (B, object) t = (new B() { FA = 1 }, new B() { FB = null }); // 1 (((A, A))t).Item1.FA.ToString(); // 2 (((B, B))t).Item2.FB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,61): warning CS8625: Cannot convert null literal to non-nullable reference type. // (B, object) t = (new B() { FA = 1 }, new B() { FB = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 61), // (14,9): warning CS8602: Dereference of a possibly null reference. // (((A, A))t).Item1.FA.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(((A, A))t).Item1.FA").WithLocation(14, 9)); } [Fact] [WorkItem(29977, "https://github.com/dotnet/roslyn/issues/29977")] public void Conversions_TupleConversions_03() { var source = @"class A { internal object? FA; } class B : A { internal object FB = new object(); } class Program { static void F() { B b = new B() { FA = 1, FB = null }; // 1 (B, (A, A)) t; t = (b, (b, b)); t.Item1.FB.ToString(); // 2 t.Item2.Item1.FA.ToString(); t = ((B, (A, A)))(b, (b, b)); t.Item1.FB.ToString(); t.Item2.Item1.FA.ToString(); // 3 (A, (B, B)) u; u = t; // 4 u.Item1.FA.ToString(); // 5 u.Item2.Item2.FB.ToString(); u = ((A, (B, B)))t; u.Item1.FA.ToString(); // 6 u.Item2.Item2.FB.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,38): warning CS8625: Cannot convert null literal to non-nullable reference type. // B b = new B() { FA = 1, FB = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 38), // (16,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.FB.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1.FB").WithLocation(16, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.Item1.FA.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2.Item1.FA").WithLocation(20, 9), // (22,13): error CS0266: Cannot implicitly convert type '(B, (A, A))' to '(A, (B, B))'. An explicit conversion exists (are you missing a cast?) // u = t; // 4 Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "t").WithArguments("(B, (A, A))", "(A, (B, B))").WithLocation(22, 13), // (23,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.FA.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1.FA").WithLocation(23, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // u.Item1.FA.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item1.FA").WithLocation(26, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(34086, "https://github.com/dotnet/roslyn/issues/34086")] public void Conversions_TupleConversions_04() { var source = @"class C { internal object? F; } class Program { static void F() { (object, object)? t = (new C() { F = 1 }, new object()); (((C, object))t).Item1.F.ToString(); // 1 (object, object)? u = (new C() { F = 2 }, new object()); ((C)u.Value.Item1).F.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/34086: Track state across Nullable<T> conversions with nested conversions. comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // (((C, object))t).Item1.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(((C, object))t).Item1.F").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // ((C)u.Value.Item1).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((C)u.Value.Item1).F").WithLocation(12, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(34086, "https://github.com/dotnet/roslyn/issues/34086")] public void Conversions_TupleConversions_05() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { (S?, object?) t = (new S() { F = 1 }, new S() { G = null }); // 1 (((S, S))t).Item1.F.ToString(); (((S, S))t).Item2.G.ToString(); // 2 (S?, object?) u = (new S() { F = 2 }, new S() { G = null }); // 3 u.Item1.Value.F.ToString(); ((S?)u.Item2).Value.G.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/34086: Track state across Nullable<T> conversions with nested conversions. comp.VerifyDiagnostics( // (10,61): warning CS8625: Cannot convert null literal to non-nullable reference type. // (S?, object?) t = (new S() { F = 1 }, new S() { G = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 61), // (11,9): warning CS8602: Dereference of a possibly null reference. // (((S, S))t).Item1.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(((S, S))t).Item1.F").WithLocation(11, 9), // (11,10): warning CS8619: Nullability of reference types in value of type '(S?, object?)' doesn't match target type '(S, S)'. // (((S, S))t).Item1.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((S, S))t").WithArguments("(S?, object?)", "(S, S)").WithLocation(11, 10), // (12,10): warning CS8619: Nullability of reference types in value of type '(S?, object?)' doesn't match target type '(S, S)'. // (((S, S))t).Item2.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((S, S))t").WithArguments("(S?, object?)", "(S, S)").WithLocation(12, 10), // (13,61): warning CS8625: Cannot convert null literal to non-nullable reference type. // (S?, object?) u = (new S() { F = 2 }, new S() { G = null }); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 61)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Conversions_TupleConversions_06() { var source = @"class Program { static void F1((object?, object) t1) { var u1 = ((string, string))t1; // 1 u1.Item1.ToString(); u1.Item1.ToString(); } static void F2((object?, object) t2) { var u2 = ((string?, string?))t2; u2.Item1.ToString(); // 2 u2.Item2.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,18): warning CS8619: Nullability of reference types in value of type '(object?, object)' doesn't match target type '(string, string)'. // var u1 = ((string, string))t1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((string, string))t1").WithArguments("(object?, object)", "(string, string)").WithLocation(5, 18), // (12,9): warning CS8602: Dereference of a possibly null reference. // u2.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.Item1").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // u2.Item2.ToString(); /// 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.Item2").WithLocation(13, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Conversions_TupleConversions_07() { var source = @"class A { public static implicit operator B?(A a) => null; } class B { } class Program { static void F(A a, B b) { (B, B) t = (a, b); // 1 t.Item1.ToString(); // 2 t.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,20): warning CS8619: Nullability of reference types in value of type '(B? a, B b)' doesn't match target type '(B, B)'. // (B, B) t = (a, b); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(a, b)").WithArguments("(B? a, B b)", "(B, B)").WithLocation(12, 20), // (13,9): warning CS8602: Possible dereference of a null reference. // t.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(13, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] public void Conversions_TupleConversions_08() { var source = @"class A { public static implicit operator B?(A a) => null; } class B { } class Program { static void F(A a, B b) { var t = ((B, B))(b, a); // 1, 2 t.Item1.ToString(); t.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,17): warning CS8619: Nullability of reference types in value of type '(B b, B? a)' doesn't match target type '(B, B)'. // var t = ((B, B))(b, a); // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((B, B))(b, a)").WithArguments("(B b, B? a)", "(B, B)").WithLocation(12, 17), // (12,29): warning CS8600: Converting null literal or possible null value to non-nullable type. // var t = ((B, B))(b, a); // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "a").WithLocation(12, 29)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_09() { var source = @"class A { public static implicit operator B?(A a) => null; } class B { } struct S { internal object? F; } class Program { static void F1() { (B, S) t1 = (new A(), new S() { F = 1 }); // 1 t1.Item1.ToString(); // 2 t1.Item2.F.ToString(); } static void F2() { (A, S?) t2 = (new A(), new S() { F = 2 }); t2.Item1.ToString(); t2.Item2.Value.F.ToString(); } static void F3() { (B, S?) t3 = (new A(), new S() { F = 3 }); // 3 t3.Item1.ToString(); // 4 t3.Item2.Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,21): warning CS8619: Nullability of reference types in value of type '(B?, S)' doesn't match target type '(B, S)'. // (B, S) t1 = (new A(), new S() { F = 1 }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(new A(), new S() { F = 1 })").WithArguments("(B?, S)", "(B, S)").WithLocation(16, 21), // (17,9): warning CS8602: Possible dereference of a null reference. // t1.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1.Item1").WithLocation(17, 9), // (28,22): warning CS8619: Nullability of reference types in value of type '(B?, S?)' doesn't match target type '(B, S?)'. // (B, S?) t3 = (new A(), new S() { F = 3 }); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(new A(), new S() { F = 3 })").WithArguments("(B?, S?)", "(B, S?)").WithLocation(28, 22), // (29,9): warning CS8602: Possible dereference of a null reference. // t3.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3.Item1").WithLocation(29, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_10() { var source = @"class A { public static implicit operator B?(A a) => null; } class B { } struct S { internal object? F; } class Program { static void F1() { var t1 = ((S, B))(new S() { F = 1 }, new A()); // 1, 2 t1.Item1.F.ToString(); // 3 t1.Item2.ToString(); } static void F2() { var t2 = ((S?, A))(new S() { F = 2 }, new A()); t2.Item1.Value.F.ToString(); // 4, 5 t2.Item2.ToString(); } static void F3() { var t3 = ((S?, B))(new S() { F = 3 }, new A()); // 6, 7 t3.Item1.Value.F.ToString(); // 8, 9 t3.Item2.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,18): warning CS8619: Nullability of reference types in value of type '(S, B?)' doesn't match target type '(S, B)'. // var t1 = ((S, B))(new S() { F = 1 }, new A()); // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((S, B))(new S() { F = 1 }, new A())").WithArguments("(S, B?)", "(S, B)").WithLocation(16, 18), // (16,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // var t1 = ((S, B))(new S() { F = 1 }, new A()); // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "new A()").WithLocation(16, 46), // (17,9): warning CS8602: Dereference of a possibly null reference. // t1.Item1.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1.Item1.F").WithLocation(17, 9), // (23,9): warning CS8629: Nullable value type may be null. // t2.Item1.Value.F.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2.Item1").WithLocation(23, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // t2.Item1.Value.F.ToString(); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2.Item1.Value.F").WithLocation(23, 9), // (28,18): warning CS8619: Nullability of reference types in value of type '(S?, B?)' doesn't match target type '(S?, B)'. // var t3 = ((S?, B))(new S() { F = 3 }, new A()); // 6, 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((S?, B))(new S() { F = 3 }, new A())").WithArguments("(S?, B?)", "(S?, B)").WithLocation(28, 18), // (28,47): warning CS8600: Converting null literal or possible null value to non-nullable type. // var t3 = ((S?, B))(new S() { F = 3 }, new A()); // 6, 7 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "new A()").WithLocation(28, 47), // (29,9): warning CS8629: Nullable value type may be null. // t3.Item1.Value.F.ToString(); // 8, 9 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t3.Item1").WithLocation(29, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // t3.Item1.Value.F.ToString(); // 8, 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3.Item1.Value.F").WithLocation(29, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_11() { var source = @"class A { public static implicit operator B?(A a) => null; } class B { } struct S { internal object? F; } class Program { static void F1() { (A, S) t1 = (new A(), new S() { F = 1 }); (B, S?) u1 = t1; // 1 u1.Item1.ToString(); // 2 u1.Item2.Value.F.ToString(); } static void F2() { (A, S) t2 = (new A(), new S() { F = 2 }); var u2 = ((B, S?))t2; // 3 u2.Item1.ToString(); // 4 u2.Item2.Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/34495: Improve warning message to reference user-defined conversion and t1.Item1 or t2.Item1. comp.VerifyDiagnostics( // (17,22): warning CS8601: Possible null reference assignment. // (B, S?) u1 = t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t1").WithLocation(17, 22), // (18,9): warning CS8602: Possible dereference of a null reference. // u1.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u1.Item1").WithLocation(18, 9), // (24,18): warning CS8601: Possible null reference assignment. // var u2 = ((B, S?))t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "((B, S?))t2").WithLocation(24, 18), // (25,9): warning CS8602: Possible dereference of a null reference. // u2.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.Item1").WithLocation(25, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_12() { var source = @"#pragma warning disable 0649 class A { public static implicit operator B?(A a) => null; } class B { } struct S { internal object? F; } class Program { static void F1() { (int, (A, S)) t1 = (1, (new A(), new S() { F = 1 })); (object x, (B, S?) y) u1 = t1; // 1 u1.y.Item1.ToString(); // 2 u1.y.Item2.Value.F.ToString(); } static void F2() { (int, (A, S)) t2 = (2, (new A(), new S() { F = 2 })); var u2 = ((object x, (B, S?) y))t2; // 3 u2.y.Item1.ToString(); // 4 u2.y.Item2.Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/34495: Improve warning message to reference user-defined conversion and t1.Item2.Item1 or t2.Item2.Item1. comp.VerifyDiagnostics( // (18,36): warning CS8601: Possible null reference assignment. // (object x, (B, S?) y) u1 = t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t1").WithLocation(18, 36), // (19,9): warning CS8602: Possible dereference of a null reference. // u1.y.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u1.y.Item1").WithLocation(19, 9), // (25,18): warning CS8601: Possible null reference assignment. // var u2 = ((object x, (B, S?) y))t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "((object x, (B, S?) y))t2").WithLocation(25, 18), // (26,9): warning CS8602: Possible dereference of a null reference. // u2.y.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.y.Item1").WithLocation(26, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_13() { var source = @"class A { public static implicit operator B(A a) => throw null!; } class B { } struct S { internal object? F; internal object G; } class Program { static void F() { A x = new A(); S y = new S() { F = 1, G = null }; // 1 var t = (x, y, x, y, x, y, x, y, x, y); (B?, S?, B?, S?, B?, S?, B?, S?, B?, S?) u = t; u.Item1.ToString(); u.Item2.Value.F.ToString(); u.Item2.Value.G.ToString(); // 2 u.Item9.ToString(); u.Item10.Value.F.ToString(); u.Item10.Value.G.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,36): warning CS8625: Cannot convert null literal to non-nullable reference type. // S y = new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(18, 36), // (23,9): warning CS8602: Possible dereference of a null reference. // u.Item2.Value.G.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item2.Value.G").WithLocation(23, 9), // (26,9): warning CS8602: Possible dereference of a null reference. // u.Item10.Value.G.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.Item10.Value.G").WithLocation(26, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_14() { var source = @"class A { public static implicit operator A?(int i) => new A(); } class B { public static implicit operator B(int i) => new B(); } class Program { static void F1((int, int) t1) { (A, B?) u1 = t1; // 1 u1.Item1.ToString(); // 2 u1.Item2.ToString(); } static void F2((int, int) t2) { var u2 = ((B?, A))t2; // 3 u2.Item1.ToString(); // 4 u2.Item2.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/34495: Improve warning message to reference user-defined conversion and t1.Item2 or t2.Item1. comp.VerifyDiagnostics( // (13,22): warning CS8601: Possible null reference assignment. // (A, B?) u1 = t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t1").WithLocation(13, 22), // (14,9): warning CS8602: Dereference of a possibly null reference. // u1.Item1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u1.Item1").WithLocation(14, 9), // (19,18): warning CS8601: Possible null reference assignment. // var u2 = ((B?, A))t2; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "((B?, A))t2").WithLocation(19, 18), // (20,9): warning CS8602: Dereference of a possibly null reference. // u2.Item1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.Item1").WithLocation(20, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // u2.Item2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u2.Item2").WithLocation(21, 9)); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_15() { var source = @"class A { public static implicit operator A?(int i) => new A(); } class B { public static implicit operator B(int i) => new B(); } struct S { public static implicit operator S((A, B?) t) => default; } class Program { static void F1((int, int) t) { F2(t); // 1 F3(t); // 2 } static void F2((A, B?) t) { } static void F3(S? s) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32599: Handle tuple element conversions. comp.VerifyDiagnostics(); } [Fact] [WorkItem(32599, "https://github.com/dotnet/roslyn/issues/32599")] [WorkItem(32600, "https://github.com/dotnet/roslyn/issues/32600")] public void Conversions_TupleConversions_16() { var source = @"class A { } class B { public static implicit operator B?(A a) => new B(); } struct S { public static implicit operator (A?, A)(S s) => default; } class Program { static void F1(S s) { F2(s); // 1 F3(s); // 2 } static void F2((A, A?)? t) { } static void F3((B?, B) t) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32599: Handle tuple element conversions. // Diagnostics on user-defined conversions need improvement: https://github.com/dotnet/roslyn/issues/31798 comp.VerifyDiagnostics( // (16,12): warning CS8620: Argument of type 'S' cannot be used for parameter 't' of type '(A, A?)?' in 'void Program.F2((A, A?)? t)' due to differences in the nullability of reference types. // F2(s); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s").WithArguments("S", "(A, A?)?", "t", "void Program.F2((A, A?)? t)").WithLocation(16, 12)); } [Fact] public void Conversions_BoxingConversions_01() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { object o = new S() { F = 1, G = null }; // 1 ((S)o).F.ToString(); // 2 ((S)o).G.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,41): warning CS8625: Cannot convert null literal to non-nullable reference type. // object o = new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 41), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((S)o).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((S)o).F").WithLocation(11, 9)); } [Fact] public void Conversions_BoxingConversions_02() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { ((S)(object)new S() { F = 1 }).F.ToString(); // 1 ((S)(object)new S() { G = null }).F.ToString(); // 2, 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // ((S)(object)new S() { F = 1 }).F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((S)(object)new S() { F = 1 }).F").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((S)(object)new S() { G = null }).F.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((S)(object)new S() { G = null }).F").WithLocation(11, 9), // (11,35): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((S)(object)new S() { G = null }).F.ToString(); // 2, 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 35) ); } [Fact] public void Conversions_BoxingConversions_03() { var source = @"struct S { internal object? F; internal object G; } class Program { static void F() { object? o = (S?)new S() { F = 1, G = null }; // 1 ((S?)o).Value.F.ToString(); // 2 ((S?)o).Value.G.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,46): warning CS8625: Cannot convert null literal to non-nullable reference type. // object? o = (S?)new S() { F = 1, G = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 46), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((S?)o).Value.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((S?)o).Value.F").WithLocation(11, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Conversions_BoxingConversions_04() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F1<T>() where T : I, new() { object o1 = new T() { P = 1, Q = null }; // 1 ((T)o1).P.ToString(); // 2 ((T)o1).Q.ToString(); } static void F2<T>() where T : class, I, new() { object o2 = new T() { P = 2, Q = null }; // 3 ((T)o2).P.ToString(); // 4 ((T)o2).Q.ToString(); } static void F3<T>() where T : struct, I { object o3 = new T() { P = 3, Q = null }; // 5 ((T)o3).P.ToString(); // 6 ((T)o3).Q.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,42): warning CS8625: Cannot convert null literal to non-nullable reference type. // object o1 = new T() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 42), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((T)o1).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T)o1).P").WithLocation(11, 9), // (16,42): warning CS8625: Cannot convert null literal to non-nullable reference type. // object o2 = new T() { P = 2, Q = null }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 42), // (17,9): warning CS8602: Dereference of a possibly null reference. // ((T)o2).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T)o2).P").WithLocation(17, 9), // (22,42): warning CS8625: Cannot convert null literal to non-nullable reference type. // object o3 = new T() { P = 3, Q = null }; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(22, 42), // (23,9): warning CS8602: Dereference of a possibly null reference. // ((T)o3).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T)o3).P").WithLocation(23, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Conversions_BoxingConversions_05() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F1<T1>() where T1 : I, new() { ((T1)(object)new T1() { P = 1 }).P.ToString(); // 1 ((T1)(object)new T1() { Q = null }).Q.ToString(); // 2 } static void F2<T2>() where T2 : class, I, new() { ((T2)(object)new T2() { P = 2 }).P.ToString(); // 3 ((T2)(object)new T2() { Q = null }).Q.ToString(); // 4 } static void F3<T3>() where T3 : struct, I { ((T3)(object)new T3() { P = 3 }).P.ToString(); // 5 ((T3)(object)new T3() { Q = null }).Q.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // ((T1)(object)new T1() { P = 1 }).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T1)(object)new T1() { P = 1 }).P").WithLocation(10, 9), // (11,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((T1)(object)new T1() { Q = null }).Q.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 37), // (15,9): warning CS8602: Dereference of a possibly null reference. // ((T2)(object)new T2() { P = 2 }).P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T2)(object)new T2() { P = 2 }).P").WithLocation(15, 9), // (16,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((T2)(object)new T2() { Q = null }).Q.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 37), // (20,9): warning CS8602: Dereference of a possibly null reference. // ((T3)(object)new T3() { P = 3 }).P.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T3)(object)new T3() { P = 3 }).P").WithLocation(20, 9), // (21,37): warning CS8625: Cannot convert null literal to non-nullable reference type. // ((T3)(object)new T3() { Q = null }).Q.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 37)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Conversions_BoxingConversions_06() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F1<T>() where T : I, new() { (object, object) t1 = (new T() { P = 1 }, new T() { Q = null }); // 1 ((T)t1.Item1).P.ToString(); // 2 (((T, T))t1).Item2.Q.ToString(); } static void F2<T>() where T : class, I, new() { (object, object) t2 = (new T() { P = 2 }, new T() { Q = null }); // 3 ((T)t2.Item1).P.ToString(); // 4 (((T, T))t2).Item2.Q.ToString(); } static void F3<T>() where T : struct, I { (object, object) t3 = (new T() { P = 3 }, new T() { Q = null }); // 5 ((T)t3.Item1).P.ToString(); // 6 (((T, T))t3).Item2.Q.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,65): warning CS8625: Cannot convert null literal to non-nullable reference type. // (object, object) t1 = (new T() { P = 1 }, new T() { Q = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 65), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((T)t1.Item1).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T)t1.Item1).P").WithLocation(11, 9), // (16,65): warning CS8625: Cannot convert null literal to non-nullable reference type. // (object, object) t2 = (new T() { P = 2 }, new T() { Q = null }); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 65), // (17,9): warning CS8602: Dereference of a possibly null reference. // ((T)t2.Item1).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T)t2.Item1).P").WithLocation(17, 9), // (22,65): warning CS8625: Cannot convert null literal to non-nullable reference type. // (object, object) t3 = (new T() { P = 3 }, new T() { Q = null }); // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(22, 65), // (23,9): warning CS8602: Dereference of a possibly null reference. // ((T)t3.Item1).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T)t3.Item1).P").WithLocation(23, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Conversions_BoxingConversions_07() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F<T>() where T : struct, I { object o = (T?)new T() { P = 1, Q = null }; // 1 ((T?)o).Value.P.ToString(); // 2 ((T?)o).Value.Q.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,45): warning CS8625: Cannot convert null literal to non-nullable reference type. // object o = (T?)new T() { P = 1, Q = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 45), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((T?)o).Value.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T?)o).Value.P").WithLocation(11, 9)); } [Fact] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] [WorkItem(34086, "https://github.com/dotnet/roslyn/issues/34086")] public void Conversions_BoxingConversions_08() { var source = @"interface I { object? P { get; set; } object Q { get; set; } } class Program { static void F<T>() where T : struct, I { (object, object) t = ((T?, T?))(new T() { P = 1 }, new T() { Q = null }); // 1 ((T?)t.Item1).Value.P.ToString(); // 2 (((T?, T?))t).Item2.Value.Q.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,30): warning CS8619: Nullability of reference types in value of type '(T?, T?)' doesn't match target type '(object, object)'. // (object, object) t = ((T?, T?))(new T() { P = 1 }, new T() { Q = null }); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "((T?, T?))(new T() { P = 1 }, new T() { Q = null })").WithArguments("(T?, T?)", "(object, object)").WithLocation(10, 30), // (10,74): warning CS8625: Cannot convert null literal to non-nullable reference type. // (object, object) t = ((T?, T?))(new T() { P = 1 }, new T() { Q = null }); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 74), // (11,9): warning CS8602: Dereference of a possibly null reference. // ((T?)t.Item1).Value.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "((T?)t.Item1).Value.P").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // (((T?, T?))t).Item2.Value.Q.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(((T?, T?))t).Item2").WithLocation(12, 9)); } [Fact] public void Members_FieldCycle_01() { var source = @"class C { C? F; void M() { F = this; F.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F.F").WithLocation(7, 9)); } [Fact] public void Members_FieldCycle_02() { var source = @"class C { C? F; void M() { F = new C() { F = this }; F.F.ToString(); F.F.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F.F.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F.F.F").WithLocation(8, 9)); } [Fact] public void Members_FieldCycle_03() { var source = @"class C { C? F; static void M() { var x = new C(); x.F = x; var y = new C() { F = x }; y.F.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Members_FieldCycle_04() { var source = @"class C { C? F; static void M(C x) { object? y = x; for (int i = 0; i < 3; i++) { x.F = x; y = null; } x.F.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // x.F.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(12, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // x.F.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F.F").WithLocation(12, 9)); } [Fact] public void Members_FieldCycle_05() { var source = @"class C { C? F; static void M(C x) { (x.F, _) = (x, 0); x.F.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.F.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F.F").WithLocation(7, 9)); } [Fact] public void Members_FieldCycle_06() { var source = @"#pragma warning disable 0649 class A { internal B B = default!; } class B { internal A? A; } class Program { static void M(A a) { a.B.A = a; a.B.A.B.A.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // a.B.A.B.A.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.B.A.B.A").WithLocation(15, 9)); } [Fact] [WorkItem(33908, "https://github.com/dotnet/roslyn/issues/33908")] public void Members_FieldCycle_07() { var source = @"#pragma warning disable 8618 class C { C F; static void M() { C x = null; while (true) { C y = new C() { F = x }; x = y; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,7): warning CS0414: The field 'C.F' is assigned but its value is never used // C F; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("C.F").WithLocation(4, 7), // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // C x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 15), // (10,33): warning CS8601: Possible null reference assignment. // C y = new C() { F = x }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(10, 33)); } [Fact] [WorkItem(33908, "https://github.com/dotnet/roslyn/issues/33908")] public void Members_FieldCycle_08() { var source = @"#pragma warning disable 8618 class C { C F; static void M() { C x = null; while (true) { C y = new C() { F = x }; x = new C() { F = y }; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,7): warning CS0414: The field 'C.F' is assigned but its value is never used // C F; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("C.F").WithLocation(4, 7), // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // C x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 15), // (10,33): warning CS8601: Possible null reference assignment. // C y = new C() { F = x }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(10, 33)); } [Fact] [WorkItem(33908, "https://github.com/dotnet/roslyn/issues/33908")] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Members_FieldCycle_09() { var source = @"#pragma warning disable 8618 class C<T> { internal T F; } class Program { static void F<T>() where T : C<T>, new() { T x = default; while (true) { T y = new T() { F = x }; x = y; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(10, 15), // (13,33): warning CS8601: Possible null reference assignment. // T y = new T() { F = x }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(13, 33)); } [Fact] [WorkItem(33908, "https://github.com/dotnet/roslyn/issues/33908")] [WorkItem(33387, "https://github.com/dotnet/roslyn/issues/33387")] public void Members_FieldCycle_10() { var source = @"interface I<T> { T P { get; set; } } class Program { static void F1<T>() where T : I<T>, new() { T x1 = default; while (true) { T y1 = new T() { P = x1 }; x1 = y1; } } static void F2<T>() where T : class, I<T>, new() { T x2 = default; while (true) { T y2 = new T() { P = x2 }; x2 = y2; } } static void F3<T>() where T : struct, I<T> { T x3 = default; while (true) { T y3 = new T() { P = x3 }; x3 = y3; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (12,34): warning CS8601: Possible null reference assignment. // T y1 = new T() { P = x1 }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x1").WithLocation(12, 34), // (18,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x2 = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(18, 16), // (21,34): warning CS8601: Possible null reference assignment. // T y2 = new T() { P = x2 }; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x2").WithLocation(21, 34)); } [Fact] public void Members_FieldCycle_Struct() { var source = @"struct S { internal C F; internal C? G; } class C { internal S S; static void Main() { var s = new S() { F = new C(), G = new C() }; s.F.S = s; s.G.S = s; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } // Valid struct since the property is not backed by a field. [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void Members_PropertyCycle_Struct() { var source = @"#pragma warning disable 0649 struct S { internal S(object? f) { F = f; } internal object? F; internal S P { get { return new S(F); } set { F = value.F; } } } class C { static void M(S s) { s.P.F.ToString(); // 1 if (s.P.F == null) return; s.P.F.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // s.P.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.P.F").WithLocation(19, 9)); } [Fact] [WorkItem(29619, "https://github.com/dotnet/roslyn/issues/29619")] public void Members_StructProperty_Default() { var source = @"#pragma warning disable 0649 struct S { internal object F; private object _p; internal object P { get { return _p; } set { _p = value; } } internal object Q { get; set; } } class Program { static void Main() { S s = default; s.F.ToString(); // 1 s.P.ToString(); s.Q.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // s.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.F").WithLocation(14, 9)); } [Fact] public void Members_StaticField_Struct() { var source = @"struct S<T> where T : class { internal T F; internal T? G; internal static S<T> Instance = new S<T>(); } class Program { static void F<T>() where T : class, new() { S<T>.Instance.F = null; // 1 S<T>.Instance.G = new T(); S<T>.Instance.F.ToString(); // 2 S<T>.Instance.G.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,27): warning CS8625: Cannot convert null literal to non-nullable reference or unconstrained type parameter. // S<T>.Instance.F = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 27), // (13,9): warning CS8602: Dereference of a possibly null reference. // S<T>.Instance.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "S<T>.Instance.F").WithLocation(13, 9)); } [Fact] public void Members_DefaultConstructor_Class() { var source = @"#pragma warning disable 649 #pragma warning disable 8618 class A { internal object? A1; internal object A2; } class B { internal B() { B2 = null!; } internal object? B1; internal object B2; } class Program { static void Main() { A a = new A(); a.A1.ToString(); // 1 a.A2.ToString(); B b = new B(); b.B1.ToString(); // 2 b.B2.ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (22,9): warning CS8602: Dereference of a possibly null reference. // a.A1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.A1").WithLocation(22, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // b.B1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.B1").WithLocation(25, 9)); } [Fact] public void SelectAnonymousType() { var source = @"using System.Collections.Generic; using System.Linq; class C { int? E; static void F(IEnumerable<C> c) { const int F = 0; c.Select(o => new { E = o.E ?? F }); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,10): warning CS0649: Field 'C.E' is never assigned to, and will always have its default value // int? E; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "E").WithArguments("C.E", "").WithLocation(5, 10)); } [Fact] public void Constraints_01() { var source = @"interface I<T> { T P { get; set; } } class A { } class B { static void F1<T>(T t1) where T : A { t1.ToString(); t1 = default; // 1 } static void F2<T>(T t2) where T : A? { t2.ToString(); // 2 t2 = default; } static void F3<T>(T t3) where T : I<T> { t3.P.ToString(); t3 = default; } static void F4<T>(T t4) where T : I<T>? { t4.P.ToString(); // 3 and 4 t4.P = default; // 5 t4 = default; } static void F5<T>(T t5) where T : I<T?> { t5.P.ToString(); // 6 and 7 t5.P = default; t5 = default; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // t1 = default; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(11, 14), // (15,9): warning CS8602: Dereference of a possibly null reference. // t2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(15, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // t4.P.ToString(); // 3 and 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t4").WithLocation(25, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // t4.P.ToString(); // 3 and 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t4.P").WithLocation(25, 9), // (26,16): warning CS8601: Possible null reference assignment. // t4.P = default; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(26, 16), // (29,41): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F5<T>(T t5) where T : I<T?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(29, 41), // (31,9): warning CS8602: Dereference of a possibly null reference. // t5.P.ToString(); // 6 and 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t5.P").WithLocation(31, 9) ); } [Fact] public void Constraints_02() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : class { } public static void F2<T2>(T2 t2) where T2 : class? { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var b = m.GlobalNamespace.GetMember("B"); if (isSource) { Assert.Empty(b.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", b.GetAttributes().First().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : class!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.ReferenceTypeConstraintIsNullable); Assert.Empty(t1.GetAttributes()); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T2>(T2 t2) where T2 : class?", f2.ToDisplayString(SymbolDisplayFormat.TestFormat.WithGenericsOptions(SymbolDisplayFormat.TestFormat.GenericsOptions | SymbolDisplayGenericsOptions.IncludeTypeConstraints))); Assert.Equal("void B.F2<T2>(T2 t2) where T2 : class", f2.ToDisplayString(SymbolDisplayFormat.TestFormat.WithGenericsOptions(SymbolDisplayFormat.TestFormat.GenericsOptions | SymbolDisplayGenericsOptions.IncludeTypeConstraints). WithMiscellaneousOptions(SymbolDisplayFormat.TestFormatWithConstraints.MiscellaneousOptions & ~(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier)))); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t2.GetAttributes().Single().ToString()); } } } [Fact] public void Constraints_03() { var source = @" class A<T1> where T1 : class { public static void F1(T1? t1) { } } class B<T2> where T2 : class? { public static void F2(T2 t2) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var a = (NamedTypeSymbol)m.GlobalNamespace.GetMember("A"); Assert.Equal("A<T1> where T1 : class!", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = a.TypeParameters[0]; Assert.False(t1.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(1)", t1.GetAttributes().Single().ToString()); } var b = (NamedTypeSymbol)m.GlobalNamespace.GetMember("B"); Assert.Equal("B<T2> where T2 : class?", b.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = b.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t2.GetAttributes().Single().ToString()); } } } [Fact] public void Constraints_04() { var source = @" #pragma warning disable CS8321 class B { public static void Test() { void F1<T1>(T1? t1) where T1 : class { } void F2<T2>(T2 t2) where T2 : class? { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var localSyntaxes = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToArray(); Assert.Equal(2, localSyntaxes.Length); var f1 = model.GetDeclaredSymbol(localSyntaxes[0]).GetSymbol<LocalFunctionSymbol>(); Assert.Equal("void F1<T1>(T1? t1) where T1 : class!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.ReferenceTypeConstraintIsNullable); Assert.Empty(t1.GetAttributes()); var f2 = model.GetDeclaredSymbol(localSyntaxes[1]).GetSymbol<LocalFunctionSymbol>(); Assert.Equal("void F2<T2>(T2 t2) where T2 : class?", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); Assert.Empty(t2.GetAttributes()); } [Fact] public void Constraints_05() { var source = @" #pragma warning disable CS8321 class B<T1> where T1 : class? { public static void F2<T2>(T2 t2) where T2 : class? { void F3<T3>(T3 t3) where T3 : class? { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,29): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // class B<T1> where T1 : class? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 29), // (6,54): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static void F2<T2>(T2 t2) where T2 : class? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(6, 54), // (8,44): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void F3<T3>(T3 t3) where T3 : class? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 44) ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var b = (NamedTypeSymbol)m.GlobalNamespace.GetMember("B"); Assert.Equal("B<T1> where T1 : class?", b.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = b.TypeParameters[0]; Assert.True(t1.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t1.GetAttributes().Single().ToString()); } var f2 = (MethodSymbol)b.GetMember("F2"); Assert.Equal("void B<T1>.F2<T2>(T2 t2) where T2 : class?", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t2.GetAttributes().Single().ToString()); } } comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); var expected = new[] { // (4,29): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // class B<T1> where T1 : class? Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(4, 29), // (6,54): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // public static void F2<T2>(T2 t2) where T2 : class? Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(6, 54), // (8,44): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // void F3<T3>(T3 t3) where T3 : class? Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(8, 44) }; comp.VerifyDiagnostics(expected); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); comp.VerifyDiagnostics(expected .Concat(new[] { // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.3", "8.0").WithLocation(1, 1), }).ToArray() ); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8, skipUsesIsNullable: true); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular9, skipUsesIsNullable: true); comp.VerifyDiagnostics(); } [Fact] public void Constraints_06() { var source = @" #pragma warning disable CS8321 class B<T1> where T1 : class? { public static void F1(T1? t1) {} public static void F2<T2>(T2? t2) where T2 : class? { void F3<T3>(T3? t3) where T3 : class? { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F2<T2>(T2? t2) where T2 : class? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(9, 31), // (6,27): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F1(T1? t1) Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T1?").WithArguments("9.0").WithLocation(6, 27), // (11,21): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F3<T3>(T3? t3) where T3 : class? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T3?").WithArguments("9.0").WithLocation(11, 21) ); } [Fact] public void Constraints_07() { var source = @" class B { public static void F1<T11, T12>(T12? t1) where T11 : class where T12 : T11 {} public static void F2<T21, T22>(T22? t1) where T21 : class where T22 : class, T21 {} public static void F3<T31, T32>(T32? t1) where T31 : B where T32 : T31 {} public static void F4<T41, T42>(T42? t1) where T41 : B where T42 : T41? {} }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,37): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F1<T11, T12>(T12? t1) where T11 : class where T12 : T11 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T12?").WithArguments("9.0").WithLocation(4, 37), // (13,37): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F4<T41, T42>(T42? t1) where T41 : B where T42 : T41? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T42?").WithArguments("9.0").WithLocation(13, 37) ); } [Fact] public void Constraints_08() { var source = @" #pragma warning disable CS8321 class B<T11, T12> where T12 : T11? { public static void F2<T21, T22>() where T22 : T21? { void F3<T31, T32>() where T32 : T31? { } } public static void F4<T4>() where T4 : T4? {} }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class B<T11, T12> where T12 : T11? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T11?").WithArguments("9.0").WithLocation(4, 31), // (6,51): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F2<T21, T22>() where T22 : T21? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T21?").WithArguments("9.0").WithLocation(6, 51), // (8,41): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F3<T31, T32>() where T32 : T31? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T31?").WithArguments("9.0").WithLocation(8, 41), // (13,27): error CS0454: Circular constraint dependency involving 'T4' and 'T4' // public static void F4<T4>() where T4 : T4? Diagnostic(ErrorCode.ERR_CircularConstraint, "T4").WithArguments("T4", "T4").WithLocation(13, 27), // (13,44): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F4<T4>() where T4 : T4? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T4?").WithArguments("9.0").WithLocation(13, 44) ); } [Fact] public void Constraints_09() { var source = @" class B { public static void F1<T1>() where T1 : Node<T1>? {} public static void F2<T2>() where T2 : Node<T2?> {} public static void F3<T3>() where T3 : Node<T3?>? {} } class Node<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,49): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T3>() where T3 : Node<T3?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T3?").WithArguments("9.0").WithLocation(10, 49) ); } [Fact] public void Constraints_10() { var source = @" class B { public static void F1<T1>() where T1 : class, Node<T1>? {} public static void F2<T2>() where T2 : class, Node<T2?> {} public static void F3<T3>() where T3 : class, Node<T3?>? {} } class Node<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,51): error CS0450: 'Node<T2?>': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F2<T2>() where T2 : class, Node<T2?> Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "Node<T2?>").WithArguments("Node<T2?>").WithLocation(7, 51), // (10,51): error CS0450: 'Node<T3?>': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F3<T3>() where T3 : class, Node<T3?>? Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "Node<T3?>?").WithArguments("Node<T3?>").WithLocation(10, 51), // (4,51): error CS0450: 'Node<T1>': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F1<T1>() where T1 : class, Node<T1>? Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "Node<T1>?").WithArguments("Node<T1>").WithLocation(4, 51) ); } [Fact] public void Constraints_11() { var source = @" class B { public static void F1<T1>() where T1 : class?, Node<T1>? {} public static void F2<T2>() where T2 : class?, Node<T2?> {} public static void F3<T3>() where T3 : class?, Node<T3?>? {} } class Node<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,57): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F2<T2>() where T2 : class?, Node<T2?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(7, 57), // (7,52): error CS0450: 'Node<T2?>': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F2<T2>() where T2 : class?, Node<T2?> Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "Node<T2?>").WithArguments("Node<T2?>").WithLocation(7, 52), // (10,57): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T3>() where T3 : class?, Node<T3?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T3?").WithArguments("9.0").WithLocation(10, 57), // (10,52): error CS0450: 'Node<T3?>': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F3<T3>() where T3 : class?, Node<T3?>? Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "Node<T3?>?").WithArguments("Node<T3?>").WithLocation(10, 52), // (4,52): error CS0450: 'Node<T1>': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F1<T1>() where T1 : class?, Node<T1>? Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "Node<T1>?").WithArguments("Node<T1>").WithLocation(4, 52) ); } [Fact] public void Constraints_12() { var source = @" class B { public static void F1<T1>() where T1 : INode<T1>? {} public static void F2<T2>() where T2 : INode<T2?> {} public static void F3<T3>() where T3 : INode<T3?>? {} } interface INode<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,50): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F2<T2>() where T2 : INode<T2?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(7, 50), // (10,50): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T3>() where T3 : INode<T3?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T3?").WithArguments("9.0").WithLocation(10, 50) ); } [Fact] public void Constraints_13() { var source = @" class B { public static void F1<T1>() where T1 : class, INode<T1>? {} public static void F2<T2>() where T2 : class, INode<T2?> {} public static void F3<T3>() where T3 : class, INode<T3?>? {} } interface INode<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); } [Fact] public void Constraints_14() { var source = @" class B { public static void F1<T1>() where T1 : class?, INode<T1>? {} public static void F2<T2>() where T2 : class?, INode<T2?> {} public static void F3<T3>() where T3 : class?, INode<T3?>? {} } interface INode<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,58): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T3>() where T3 : class?, INode<T3?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T3?").WithArguments("9.0").WithLocation(10, 58) ); } [Fact] public void Constraints_15() { var source = @" class B { public static void F1<T11, T12>() where T11 : INode where T12 : class?, T11, INode<T12?> {} public static void F2<T21, T22>() where T21 : INode? where T22 : class?, T21, INode<T22?> {} public static void F3<T31, T32>() where T31 : INode? where T32 : class?, T31, INode<T32?>? {} public static void F4<T41, T42>() where T41 : INode? where T42 : class?, T41?, INode<T42?>? {} } interface INode {} interface INode<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,89): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T31, T32>() where T31 : INode? where T32 : class?, T31, INode<T32?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T32?").WithArguments("9.0").WithLocation(10, 89), // (13,78): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F4<T41, T42>() where T41 : INode? where T42 : class?, T41?, INode<T42?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T41?").WithArguments("9.0").WithLocation(13, 78), // (13,90): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F4<T41, T42>() where T41 : INode? where T42 : class?, T41?, INode<T42?>? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T42?").WithArguments("9.0").WithLocation(13, 90) ); } [Fact] public void Constraints_16() { var source = @" class B { public static void F1<T11, T12>(T12? t1) where T11 : INode where T12 : class?, T11 {} public static void F2<T21, T22>(T22? t2) where T21 : INode? where T22 : class?, T21 {} public static void F3<T31, T32>(T32? t1) where T31 : INode where T32 : class?, T31? {} } interface INode {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,37): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F2<T21, T22>(T22? t2) where T21 : INode? where T22 : class?, T21 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T22?").WithArguments("9.0").WithLocation(7, 37), // (10,37): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T31, T32>(T32? t1) where T31 : INode where T32 : class?, T31? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T32?").WithArguments("9.0").WithLocation(10, 37), // (10,84): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F3<T31, T32>(T32? t1) where T31 : INode where T32 : class?, T31? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T31?").WithArguments("9.0").WithLocation(10, 84) ); } [Fact] public void Constraints_17() { var source = @" #pragma warning disable CS8321 class B<[System.Runtime.CompilerServices.Nullable(0)] T1> { public static void F2<[System.Runtime.CompilerServices.Nullable(1)] T2>(T2 t2) { void F3<[System.Runtime.CompilerServices.Nullable(2)] T3>(T3 t3) { } } }"; var comp = CreateCompilation(new[] { source, NullableAttributeDefinition }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,10): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // class B<[System.Runtime.CompilerServices.Nullable(0)] T1> Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "System.Runtime.CompilerServices.Nullable(0)").WithLocation(4, 10), // (6,28): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // public static void F2<[System.Runtime.CompilerServices.Nullable(1)] T2>(T2 t2) Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "System.Runtime.CompilerServices.Nullable(1)").WithLocation(6, 28), // (8,18): error CS8623: Explicit application of 'System.Runtime.CompilerServices.NullableAttribute' is not allowed. // void F3<[System.Runtime.CompilerServices.Nullable(2)] T3>(T3 t3) Diagnostic(ErrorCode.ERR_ExplicitNullableAttribute, "System.Runtime.CompilerServices.Nullable(2)").WithLocation(8, 18) ); } [Fact] public void Constraints_18() { var source = @" class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } class B : A<int> { public override void F1<T11>(T11? t1) { } public override void F2<T22>(T22 t2) { } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,26): error CS0115: 'B.F1<T11>(T11?)': no suitable method found to override // public override void F1<T11>(T11? t1) where T : class Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B.F1<T11>(T11?)").WithLocation(15, 26), // (15,39): error CS0453: The type 'T11' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<T11>(T11? t1) where T : class Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t1").WithArguments("System.Nullable<T>", "T", "T11").WithLocation(15, 39)); } [Fact] public void Constraints_19() { var source1 = @" public class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var source2 = @" class B : A<int> { public override void F1<T11>(T11? t1) { } public override void F2<T22>(T22 t2) { } } "; var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }) .VerifyDiagnostics( // (4,26): error CS0115: 'B.F1<T11>(T11?)': no suitable method found to override // public override void F1<T11>(T11? t1) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B.F1<T11>(T11?)").WithLocation(4, 26), // (4,39): error CS0453: The type 'T11' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<T11>(T11? t1) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t1").WithArguments("System.Nullable<T>", "T", "T11").WithLocation(4, 39)); } [Fact] public void Constraints_20() { var source1 = @" public class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var source3 = @" class B : A<int> { public override void F1<T11>(T11? t1) { } public override void F2<T22>(T22 t2) { } } "; var comp3 = CreateCompilation(new[] { source3 }, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (4,26): error CS0115: 'B.F1<T11>(T11?)': no suitable method found to override // public override void F1<T11>(T11? t1) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B.F1<T11>(T11?)").WithLocation(4, 26), // (4,39): error CS0453: The type 'T11' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<T11>(T11? t1) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t1").WithArguments("System.Nullable<T>", "T", "T11").WithLocation(4, 39)); } [Fact] public void Constraints_21() { var source1 = @" public class A<T> { public virtual void F1<T1>() where T1 : class { } public virtual void F2<T2>() where T2 : class? { } } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var source2 = @" class B : A<int> { public override void F1<T11>() { } public override void F2<T22>() { } } "; var comp2 = CreateCompilation(new[] { source2 }, references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", bf2.GetAttributes().Single().ToString()); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); } } [Fact] public void Constraints_22() { var source = @" class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } class B : A<int> { public override void F1<T11>(T11? t1) { } public override void F2<T22>(T22 t2) { } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,26): error CS0115: 'B.F1<T11>(T11?)': no suitable method found to override // public override void F1<T11>(T11? t1) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B.F1<T11>(T11?)").WithLocation(15, 26), // (15,39): error CS0453: The type 'T11' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<T11>(T11? t1) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t1").WithArguments("System.Nullable<T>", "T", "T11").WithLocation(15, 39)); var bf1 = (MethodSymbol)comp.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>(T11? t1)", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.IsReferenceType); Assert.Null(bf1.OverriddenMethod); var bf2 = (MethodSymbol)comp.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>(T22 t2) where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); var af2 = bf2.OverriddenMethod; Assert.Equal("void A<System.Int32>.F2<T2>(T2 t2) where T2 : class?", af2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = af2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); } [Fact] public void Constraints_23() { var source1 = @" public interface IA { void F1<T1>() where T1 : class?; void F2<T2>() where T2 : class; void F3<T3>() where T3 : C1<C2>; void F4<T4>() where T4 : C1<C2>; void F5<T51, T52>() where T51 : class where T52 : C1<T51>; void F6<T61, T62>() where T61 : class where T62 : C1<T61?>; } public class C1<T> {} public class C2 {} "; var source2 = @" class B : IA { public void F1<T11>() where T11 : class { } public void F2<T22>() where T22 : class? { } public void F3<T33>() where T33 : C1<C2?> { } public void F4<T44>() where T44 : C1<C2>? { } public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> { } public void F6<T661, T662>() where T661 : class where T662 : C1<T661> { } } class D : IA { public void F1<T111>() where T111 : class? { } public void F2<T222>() where T222 : class { } public void F3<T333>() where T333 : C1<C2> { } public void F4<T444>() where T444 : C1<C2> { } public void F5<T5551, T5552>() where T5551 : class where T5552 : C1<T5551> { } public void F6<T6661, T6662>() where T6661 : class where T6662 : C1<T6661?> { } } "; var comp1 = CreateCompilation(new[] { source2, source1 }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T11' of method 'B.F1<T11>()' doesn't match the constraints for type parameter 'T1' of interface method 'IA.F1<T1>()'. Consider using an explicit interface implementation instead. // public void F1<T11>() where T11 : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("T11", "B.F1<T11>()", "T1", "IA.F1<T1>()").WithLocation(4, 17), // (8,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA.F2<T2>()").WithLocation(8, 17), // (12,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1<C2?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA.F3<T3>()").WithLocation(12, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'T44' of method 'B.F4<T44>()' doesn't match the constraints for type parameter 'T4' of interface method 'IA.F4<T4>()'. Consider using an explicit interface implementation instead. // public void F4<T44>() where T44 : C1<C2>? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T44", "B.F4<T44>()", "T4", "IA.F4<T4>()").WithLocation(16, 17), // (20,17): warning CS8633: Nullability in constraints for type parameter 'T552' of method 'B.F5<T551, T552>()' doesn't match the constraints for type parameter 'T52' of interface method 'IA.F5<T51, T52>()'. Consider using an explicit interface implementation instead. // public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F5").WithArguments("T552", "B.F5<T551, T552>()", "T52", "IA.F5<T51, T52>()").WithLocation(20, 17), // (24,17): warning CS8633: Nullability in constraints for type parameter 'T662' of method 'B.F6<T661, T662>()' doesn't match the constraints for type parameter 'T62' of interface method 'IA.F6<T61, T62>()'. Consider using an explicit interface implementation instead. // public void F6<T661, T662>() where T661 : class where T662 : C1<T661> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F6").WithArguments("T662", "B.F6<T661, T662>()", "T62", "IA.F6<T61, T62>()").WithLocation(24, 17) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", bf2.GetAttributes().Single().ToString()); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); var bf3 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F3"); Assert.Equal("void B.F3<T33>() where T33 : C1<C2?>!", bf3.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); var bf4 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F4"); Assert.Equal("void B.F4<T44>() where T44 : C1<C2!>?", bf4.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } var comp2 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); comp2.VerifyDiagnostics( ); var comp3 = CreateCompilation(new[] { source2 }, references: new[] { comp2.ToMetadataReference() }, options: WithNullable(NullableContextOptions.Warnings), parseOptions: TestOptions.Regular8); comp3.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (8,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA.F2<T2>()").WithLocation(8, 17), // (12,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1<C2?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA.F3<T3>()").WithLocation(12, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'T44' of method 'B.F4<T44>()' doesn't match the constraints for type parameter 'T4' of interface method 'IA.F4<T4>()'. Consider using an explicit interface implementation instead. // public void F4<T44>() where T44 : C1<C2>? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T44", "B.F4<T44>()", "T4", "IA.F4<T4>()").WithLocation(16, 17), // (20,17): warning CS8633: Nullability in constraints for type parameter 'T552' of method 'B.F5<T551, T552>()' doesn't match the constraints for type parameter 'T52' of interface method 'IA.F5<T51, T52>()'. Consider using an explicit interface implementation instead. // public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F5").WithArguments("T552", "B.F5<T551, T552>()", "T52", "IA.F5<T51, T52>()").WithLocation(20, 17), // (20,69): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T551?").WithArguments("9.0").WithLocation(20, 69), // (51,73): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F6<T6661, T6662>() where T6661 : class where T6662 : C1<T6661?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T6661?").WithArguments("9.0").WithLocation(51, 73) ); var comp4 = CreateCompilation(new[] { source1 }); var comp5 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp4.ToMetadataReference() }); comp5.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T11' of method 'B.F1<T11>()' doesn't match the constraints for type parameter 'T1' of interface method 'IA.F1<T1>()'. Consider using an explicit interface implementation instead. // public void F1<T11>() where T11 : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("T11", "B.F1<T11>()", "T1", "IA.F1<T1>()").WithLocation(4, 17), // (24,17): warning CS8633: Nullability in constraints for type parameter 'T662' of method 'B.F6<T661, T662>()' doesn't match the constraints for type parameter 'T62' of interface method 'IA.F6<T61, T62>()'. Consider using an explicit interface implementation instead. // public void F6<T661, T662>() where T661 : class where T662 : C1<T661> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F6").WithArguments("T662", "B.F6<T661, T662>()", "T62", "IA.F6<T61, T62>()").WithLocation(24, 17) ); } [Fact] public void Constraints_24() { var source = @" interface IA { void F1<T1>() where T1 : class; void F2<T2>() where T2 : class?; } class B : IA { void IA.F1<T11>() { } void IA.F2<T22>() { } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All))); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F1"); Assert.Equal("void B.IA.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F2"); Assert.Equal("void B.IA.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", bf2.GetAttributes().Single().ToString()); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); } } [Fact] public void Constraints_25() { var source1 = @" public interface IA { void F1<T1>() where T1 : class; void F2<T2>() where T2 : class?; } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var source2 = @" class B : IA { void IA.F1<T11>() { } void IA.F2<T22>() { } } "; var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)), references: new[] { comp1.EmitToImageReference() }); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F1"); Assert.Equal("void B.IA.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F2"); Assert.Equal("void B.IA.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { CSharpAttributeData nullableAttribute = bf2.GetAttributes().Single(); Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", nullableAttribute.ToString()); Assert.Same(m, nullableAttribute.AttributeClass.ContainingModule); Assert.Equal(Accessibility.Internal, nullableAttribute.AttributeClass.DeclaredAccessibility); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); } } [Fact] public void Constraints_26() { var source1 = @" public interface IA { void F1<T1>() where T1 : class; void F2<T2>() where T2 : class?; } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var comp2 = CreateCompilation(NullableContextAttributeDefinition); var source3 = @" class B : IA { void IA.F1<T11>() { } void IA.F2<T22>() { } } "; var comp3 = CreateCompilation(new[] { source3 }, options: WithNullableEnable(TestOptions.ReleaseDll.WithMetadataImportOptions(MetadataImportOptions.All)), references: new[] { comp1.EmitToImageReference(), comp2.EmitToImageReference() }); comp3.VerifyDiagnostics( ); CompileAndVerify(comp3, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F1"); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } Assert.Equal("void B.IA.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F2"); Assert.Equal("void B.IA.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { CSharpAttributeData nullableAttribute = bf2.GetAttributes().Single(); Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", nullableAttribute.ToString()); Assert.NotEqual(m, nullableAttribute.AttributeClass.ContainingModule); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); } } [Fact] public void Constraints_27() { var source1 = @" public interface IA { void F1<T1>() where T1 : class; void F2<T2>() where T2 : class?; } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var source2 = @" class B : IA { void IA.F1<T11>() { } void IA.F2<T22>() { } } "; var comp2 = CreateCompilation(new[] { source2 }, references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F1"); Assert.Equal("void B.IA.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.IA.F2"); Assert.Equal("void B.IA.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", bf2.GetAttributes().Single().ToString()); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); } } [Fact] public void Constraints_28() { var source = @" interface IA { void F1<T1>(T1? t1) where T1 : class; void F2<T2>(T2 t2) where T2 : class?; } class B : IA { void IA.F1<T11>(T11? t1) where T11 : class? { } void IA.F2<T22>(T22 t2) where T22 : class { } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,42): error CS0460: Constraints for override and explicit interface implementation methods are inherited from the base method, so they cannot be specified directly, except for either a 'class', or a 'struct' constraint. // void IA.F1<T11>(T11? t1) where T11 : class? Diagnostic(ErrorCode.ERR_OverrideWithConstraints, "class?").WithLocation(10, 42)); var bf1 = (MethodSymbol)comp.GlobalNamespace.GetMember("B.IA.F1"); Assert.Equal("void B.IA.F1<T11>(T11? t1) where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.True(t11.IsReferenceType); var bf2 = (MethodSymbol)comp.GlobalNamespace.GetMember("B.IA.F2"); Assert.Equal("void B.IA.F2<T22>(T22 t2) where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); } [Fact] public void Constraints_29() { var source = @" class B { public static void F2<T2>() where T2 : class? { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T2>() where T2 : class?", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(f2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", f2.GetAttributes().Single().ToString()); } TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); Assert.Empty(t2.GetAttributes()); } } [Fact] public void Constraints_30() { var source = @" class B<T2> where T2 : class? { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var b = (NamedTypeSymbol)m.GlobalNamespace.GetMember("B"); Assert.Equal("B<T2> where T2 : class?", b.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = b.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t2.GetAttributes().Single().ToString()); } } } [Fact] public void Constraints_31() { var source = @" #pragma warning disable CS8321 class B { public static void Test() { void F2<T2>() where T2 : class? { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var localSyntaxes = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>().ToArray(); Assert.Equal(1, localSyntaxes.Length); var f2 = model.GetDeclaredSymbol(localSyntaxes[0]).GetSymbol<LocalFunctionSymbol>(); Assert.Equal("void F2<T2>() where T2 : class?", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); Assert.Empty(t2.GetAttributes()); } [Fact] public void Constraints_32() { var source = @" #pragma warning disable CS8321 class B<T1> where T1 : struct? { public static void F2<T2>(T2 t2) where T2 : struct? { void F3<T3>(T3 t3) where T3 : struct? { } } }"; var comp = CreateCompilation(source); var expected = new[] { // (4,30): error CS1073: Unexpected token '?' // class B<T1> where T1 : struct? Diagnostic(ErrorCode.ERR_UnexpectedToken, "?").WithArguments("?").WithLocation(4, 30), // (6,55): error CS1073: Unexpected token '?' // public static void F2<T2>(T2 t2) where T2 : struct? Diagnostic(ErrorCode.ERR_UnexpectedToken, "?").WithArguments("?").WithLocation(6, 55), // (8,45): error CS1073: Unexpected token '?' // void F3<T3>(T3 t3) where T3 : struct? Diagnostic(ErrorCode.ERR_UnexpectedToken, "?").WithArguments("?").WithLocation(8, 45) }; comp.VerifyDiagnostics(expected); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(expected); comp = CreateCompilation(source, parseOptions: TestOptions.Regular7_3); comp.VerifyDiagnostics(expected); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); comp.VerifyDiagnostics(expected .Concat(new[] { // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.3", "8.0").WithLocation(1, 1) }).ToArray() ); } [Fact] public void Constraints_33() { var source = @" interface IA<TA> { } class C<TC> where TC : IA<object>, IA<object?> { } class B<TB> where TB : IA<object?>, IA<object> { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,36): error CS0405: Duplicate constraint 'IA<object>' for type parameter 'TC' // class C<TC> where TC : IA<object>, IA<object?> Diagnostic(ErrorCode.ERR_DuplicateBound, "IA<object?>").WithArguments("IA<object>", "TC").WithLocation(5, 36), // (8,37): error CS0405: Duplicate constraint 'IA<object>' for type parameter 'TB' // class B<TB> where TB : IA<object?>, IA<object> Diagnostic(ErrorCode.ERR_DuplicateBound, "IA<object>").WithArguments("IA<object>", "TB").WithLocation(8, 37) ); } [Fact] public void Constraints_34() { var source = @" interface IA<TA> { } class B<TB> where TB : IA<object>?, IA<object> { } class C<TC> where TC : IA<object>, IA<object>? { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,37): error CS0405: Duplicate constraint 'IA<object>' for type parameter 'TB' // class B<TB> where TB : IA<object>?, IA<object> Diagnostic(ErrorCode.ERR_DuplicateBound, "IA<object>").WithArguments("IA<object>", "TB").WithLocation(5, 37), // (8,36): error CS0405: Duplicate constraint 'IA<object>' for type parameter 'TC' // class C<TC> where TC : IA<object>, IA<object>? Diagnostic(ErrorCode.ERR_DuplicateBound, "IA<object>?").WithArguments("IA<object>", "TC").WithLocation(8, 36) ); } [Fact] public void Constraints_35() { var source1 = @" public interface IA<S> { void F1<T1>() where T1 : class?; void F2<T2>() where T2 : class; void F3<T3>() where T3 : C1<C2>; void F4<T4>() where T4 : C1<C2>; void F5<T51, T52>() where T51 : class where T52 : C1<T51>; void F6<T61, T62>() where T61 : class where T62 : C1<T61?>; } public class C1<T> {} public class C2 {} "; var source2 = @" class B : IA<string> { public void F1<T11>() where T11 : class { } public void F2<T22>() where T22 : class? { } public void F3<T33>() where T33 : C1<C2?> { } public void F4<T44>() where T44 : C1<C2>? { } public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> { } public void F6<T661, T662>() where T661 : class where T662 : C1<T661> { } } class D : IA<string> { public void F1<T111>() where T111 : class? { } public void F2<T222>() where T222 : class { } public void F3<T333>() where T333 : C1<C2> { } public void F4<T444>() where T444 : C1<C2> { } public void F5<T5551, T5552>() where T5551 : class where T5552 : C1<T5551> { } public void F6<T6661, T6662>() where T6661 : class where T6662 : C1<T6661?> { } } "; var comp1 = CreateCompilation(new[] { source2, source1 }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T11' of method 'B.F1<T11>()' doesn't match the constraints for type parameter 'T1' of interface method 'IA<string>.F1<T1>()'. Consider using an explicit interface implementation instead. // public void F1<T11>() where T11 : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("T11", "B.F1<T11>()", "T1", "IA<string>.F1<T1>()").WithLocation(4, 17), // (8,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA<string>.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA<string>.F2<T2>()").WithLocation(8, 17), // (12,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA<string>.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1<C2?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA<string>.F3<T3>()").WithLocation(12, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'T44' of method 'B.F4<T44>()' doesn't match the constraints for type parameter 'T4' of interface method 'IA<string>.F4<T4>()'. Consider using an explicit interface implementation instead. // public void F4<T44>() where T44 : C1<C2>? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T44", "B.F4<T44>()", "T4", "IA<string>.F4<T4>()").WithLocation(16, 17), // (20,17): warning CS8633: Nullability in constraints for type parameter 'T552' of method 'B.F5<T551, T552>()' doesn't match the constraints for type parameter 'T52' of interface method 'IA<string>.F5<T51, T52>()'. Consider using an explicit interface implementation instead. // public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F5").WithArguments("T552", "B.F5<T551, T552>()", "T52", "IA<string>.F5<T51, T52>()").WithLocation(20, 17), // (24,17): warning CS8633: Nullability in constraints for type parameter 'T662' of method 'B.F6<T661, T662>()' doesn't match the constraints for type parameter 'T62' of interface method 'IA<string>.F6<T61, T62>()'. Consider using an explicit interface implementation instead. // public void F6<T661, T662>() where T661 : class where T662 : C1<T661> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F6").WithArguments("T662", "B.F6<T661, T662>()", "T62", "IA<string>.F6<T61, T62>()").WithLocation(24, 17) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>() where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>() where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(bf2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", bf2.GetAttributes().Single().ToString()); } TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); Assert.Empty(t22.GetAttributes()); var bf3 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F3"); Assert.Equal("void B.F3<T33>() where T33 : C1<C2?>!", bf3.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); var bf4 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F4"); Assert.Equal("void B.F4<T44>() where T44 : C1<C2!>?", bf4.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } var comp2 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); comp2.VerifyDiagnostics( ); var comp3 = CreateCompilation(new[] { source2 }, references: new[] { comp2.ToMetadataReference() }, options: WithNullable(NullableContextOptions.Warnings), parseOptions: TestOptions.Regular8); comp3.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (8,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA<string>.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA<string>.F2<T2>()").WithLocation(8, 17), // (12,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA<string>.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1<C2?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA<string>.F3<T3>()").WithLocation(12, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'T44' of method 'B.F4<T44>()' doesn't match the constraints for type parameter 'T4' of interface method 'IA<string>.F4<T4>()'. Consider using an explicit interface implementation instead. // public void F4<T44>() where T44 : C1<C2>? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T44", "B.F4<T44>()", "T4", "IA<string>.F4<T4>()").WithLocation(16, 17), // (20,17): warning CS8633: Nullability in constraints for type parameter 'T552' of method 'B.F5<T551, T552>()' doesn't match the constraints for type parameter 'T52' of interface method 'IA<string>.F5<T51, T52>()'. Consider using an explicit interface implementation instead. // public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F5").WithArguments("T552", "B.F5<T551, T552>()", "T52", "IA<string>.F5<T51, T52>()").WithLocation(20, 17), // (20,69): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F5<T551, T552>() where T551 : class where T552 : C1<T551?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T551?").WithArguments("9.0").WithLocation(20, 69), // (51,73): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F6<T6661, T6662>() where T6661 : class where T6662 : C1<T6661?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T6661?").WithArguments("9.0").WithLocation(51, 73) ); var comp4 = CreateCompilation(new[] { source1 }); var comp5 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp4.ToMetadataReference() }); comp5.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T11' of method 'B.F1<T11>()' doesn't match the constraints for type parameter 'T1' of interface method 'IA<string>.F1<T1>()'. Consider using an explicit interface implementation instead. // public void F1<T11>() where T11 : class Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("T11", "B.F1<T11>()", "T1", "IA<string>.F1<T1>()").WithLocation(4, 17), // (24,17): warning CS8633: Nullability in constraints for type parameter 'T662' of method 'B.F6<T661, T662>()' doesn't match the constraints for type parameter 'T62' of interface method 'IA<string>.F6<T61, T62>()'. Consider using an explicit interface implementation instead. // public void F6<T661, T662>() where T661 : class where T662 : C1<T661> Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F6").WithArguments("T662", "B.F6<T661, T662>()", "T62", "IA<string>.F6<T61, T62>()").WithLocation(24, 17) ); } [Fact] public void Constraints_36() { var source1 = @" public interface IA { void F1<T1>() where T1 : class?, IB, IC?; void F2<T2>() where T2 : class, IB?, IC?; void F3<T3>() where T3 : class?, IB?, IC; void F4<T41, T42>() where T41 : class where T42 : T41?, IB, IC?; void F5<T51, T52>() where T51 : class where T52 : T51, IB?, IC?; void F6<T61, T62>() where T61 : class where T62 : T61?, IB?, IC; void F7<T71, T72>() where T71 : class? where T72 : T71, IB, IC?; void F8<T81, T82>() where T81 : class where T82 : T81, IB?, IC?; void F9<T91, T92>() where T91 : class? where T92 : T91, IB?, IC; } public interface IB {} public interface IC {} "; var source2 = @" class B : IA { public void F1<T11>() where T11 : class, IB, IC { } public void F2<T22>() where T22 : class, IB, IC { } public void F3<T33>() where T33 : class, IB, IC { } public void F4<T441, T442>() where T441 : class where T442 : T441, IB, IC { } public void F5<T551, T552>() where T551 : class where T552 : T551, IB, IC { } public void F6<T661, T662>() where T661 : class where T662 : T661, IB, IC { } public void F7<T771, T772>() where T771 : class where T772 : T771, IB, IC { } public void F8<T881, T882>() where T881 : class where T882 : T881, IB, IC { } public void F9<T991, T992>() where T991 : class where T992 : T991, IB, IC { } } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); var expected = new[] { // (28,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : class where T772 : T771, IB, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(28, 17), // (36,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : class where T992 : T991, IB, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(36, 17) }; comp2.VerifyDiagnostics(expected); var comp3 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp3.VerifyDiagnostics(expected); var comp4 = CreateCompilation(new[] { source2 }, options: WithNullableDisable(), references: new[] { comp1.ToMetadataReference() }); comp4.VerifyDiagnostics(); var comp5 = CreateCompilation(new[] { source2 }, options: WithNullableDisable(), references: new[] { comp1.EmitToImageReference() }); comp5.VerifyDiagnostics(); var comp6 = CreateCompilation(new[] { source1 }, options: WithNullableDisable(), parseOptions: TestOptions.Regular8); comp6.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (7,55): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F4<T41, T42>() where T41 : class where T42 : T41?, IB, IC?; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T41?").WithArguments("9.0").WithLocation(7, 55), // (9,55): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F6<T61, T62>() where T61 : class where T62 : T61?, IB?, IC; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T61?").WithArguments("9.0").WithLocation(9, 55) ); var comp7 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp6.ToMetadataReference() }); comp7.VerifyDiagnostics(expected); var comp9 = CreateCompilation(new[] { source2 }, options: WithNullableDisable(), references: new[] { comp6.ToMetadataReference() }); comp9.VerifyDiagnostics(); } [Fact] public void Constraints_37() { var source = @" public interface IA { void F1<T1>() where T1 : class, IB, IC; void F2<T2>() where T2 : class, IB, IC; void F3<T3>() where T3 : class, IB, IC; void F4<T41, T42>() where T41 : class where T42 : T41, IB, IC; void F5<T51, T52>() where T51 : class where T52 : T51, IB, IC; void F6<T61, T62>() where T61 : class where T62 : T61, IB, IC; void F7<T71, T72>() where T71 : class where T72 : T71, IB, IC; void F8<T81, T82>() where T81 : class where T82 : T81, IB, IC; void F9<T91, T92>() where T91 : class where T92 : T91, IB, IC; } public interface IB {} public interface IC {} class B : IA { public void F1<T11>() where T11 : class?, IB, IC? { } public void F2<T22>() where T22 : class, IB?, IC? { } public void F3<T33>() where T33 : class?, IB?, IC { } public void F4<T441, T442>() where T441 : class where T442 : T441?, IB, IC? { } public void F5<T551, T552>() where T551 : class where T552 : T551, IB?, IC? { } public void F6<T661, T662>() where T661 : class where T662 : T661?, IB?, IC { } public void F7<T771, T772>() where T771 : class? where T772 : T771, IB, IC? { } public void F8<T881, T882>() where T881 : class where T882 : T881, IB?, IC? { } public void F9<T991, T992>() where T991 : class? where T992 : T991, IB?, IC { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (55,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : class? where T992 : T991, IB?, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(55, 17), // (47,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : class? where T772 : T771, IB, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(47, 17) ); } [Fact] public void Constraints_38() { var source = @" public interface IA { void F1<T1>() where T1 : ID?, IB, IC?; void F2<T2>() where T2 : ID, IB?, IC?; void F3<T3>() where T3 : ID?, IB?, IC; void F4<T41, T42>() where T41 : ID where T42 : T41?, IB, IC?; void F5<T51, T52>() where T51 : ID where T52 : T51, IB?, IC?; void F6<T61, T62>() where T61 : ID where T62 : T61?, IB?, IC; void F7<T71, T72>() where T71 : ID? where T72 : T71, IB, IC?; void F8<T81, T82>() where T81 : ID where T82 : T81, IB?, IC?; void F9<T91, T92>() where T91 : ID? where T92 : T91, IB?, IC; } public interface IB {} public interface IC {} public interface ID {} class B : IA { public void F1<T11>() where T11 : ID, IB, IC { } public void F2<T22>() where T22 : ID, IB, IC { } public void F3<T33>() where T33 : ID, IB, IC { } public void F4<T441, T442>() where T441 : ID where T442 : T441, IB, IC { } public void F5<T551, T552>() where T551 : ID where T552 : T551, IB, IC { } public void F6<T661, T662>() where T661 : ID where T662 : T661, IB, IC { } public void F7<T771, T772>() where T771 : ID where T772 : T771, IB, IC { } public void F8<T881, T882>() where T881 : ID where T882 : T881, IB, IC { } public void F9<T991, T992>() where T991 : ID where T992 : T991, IB, IC { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp1.VerifyDiagnostics( // (7,52): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F4<T41, T42>() where T41 : ID where T42 : T41?, IB, IC?; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T41?").WithArguments("9.0").WithLocation(7, 52), // (9,52): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F6<T61, T62>() where T61 : ID where T62 : T61?, IB?, IC; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T61?").WithArguments("9.0").WithLocation(9, 52), // (58,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : ID where T992 : T991, IB, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(58, 17), // (50,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : ID where T772 : T771, IB, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(50, 17) ); } [Fact] public void Constraints_39() { var source = @" public interface IA { void F1<T1>() where T1 : ID, IB, IC; void F2<T2>() where T2 : ID, IB, IC; void F3<T3>() where T3 : ID, IB, IC; void F4<T41, T42>() where T41 : ID where T42 : T41, IB, IC; void F5<T51, T52>() where T51 : ID where T52 : T51, IB, IC; void F6<T61, T62>() where T61 : ID where T62 : T61, IB, IC; void F7<T71, T72>() where T71 : ID where T72 : T71, IB, IC; void F8<T81, T82>() where T81 : ID where T82 : T81, IB, IC; void F9<T91, T92>() where T91 : ID where T92 : T91, IB, IC; } public interface IB {} public interface IC {} public interface ID {} class B : IA { public void F1<T11>() where T11 : ID?, IB, IC? { } public void F2<T22>() where T22 : ID, IB?, IC? { } public void F3<T33>() where T33 : ID?, IB?, IC { } public void F4<T441, T442>() where T441 : ID where T442 : T441?, IB, IC? { } public void F5<T551, T552>() where T551 : ID where T552 : T551, IB?, IC? { } public void F6<T661, T662>() where T661 : ID where T662 : T661?, IB?, IC { } public void F7<T771, T772>() where T771 : ID? where T772 : T771, IB, IC? { } public void F8<T881, T882>() where T881 : ID where T882 : T881, IB?, IC? { } public void F9<T991, T992>() where T991 : ID? where T992 : T991, IB?, IC { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp1.VerifyDiagnostics( // (38,63): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F4<T441, T442>() where T441 : ID where T442 : T441?, IB, IC? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T441?").WithArguments("9.0").WithLocation(38, 63), // (46,63): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F6<T661, T662>() where T661 : ID where T662 : T661?, IB?, IC Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T661?").WithArguments("9.0").WithLocation(46, 63), // (58,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : ID? where T992 : T991, IB?, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(58, 17), // (50,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : ID? where T772 : T771, IB, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(50, 17) ); } [Fact] public void Constraints_40() { var source = @" public interface IA { void F1<T1>() where T1 : D?, IB, IC?; void F2<T2>() where T2 : D, IB?, IC?; void F3<T3>() where T3 : D?, IB?, IC; void F4<T41, T42>() where T41 : D where T42 : T41?, IB, IC?; void F5<T51, T52>() where T51 : D where T52 : T51, IB?, IC?; void F6<T61, T62>() where T61 : D where T62 : T61?, IB?, IC; void F7<T71, T72>() where T71 : D? where T72 : T71, IB, IC?; void F8<T81, T82>() where T81 : D where T82 : T81, IB?, IC?; void F9<T91, T92>() where T91 : D? where T92 : T91, IB?, IC; } public interface IB {} public interface IC {} public class D {} class B : IA { public void F1<T11>() where T11 : D, IB, IC { } public void F2<T22>() where T22 : D, IB, IC { } public void F3<T33>() where T33 : D, IB, IC { } public void F4<T441, T442>() where T441 : D where T442 : T441, IB, IC { } public void F5<T551, T552>() where T551 : D where T552 : T551, IB, IC { } public void F6<T661, T662>() where T661 : D where T662 : T661, IB, IC { } public void F7<T771, T772>() where T771 : D where T772 : T771, IB, IC { } public void F8<T881, T882>() where T881 : D where T882 : T881, IB, IC { } public void F9<T991, T992>() where T991 : D where T992 : T991, IB, IC { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (58,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : D where T992 : T991, IB, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(58, 17), // (50,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : D where T772 : T771, IB, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(50, 17) ); } [Fact] public void Constraints_41() { var source = @" public interface IA { void F1<T1>() where T1 : D, IB, IC; void F2<T2>() where T2 : D, IB, IC; void F3<T3>() where T3 : D, IB, IC; void F4<T41, T42>() where T41 : D where T42 : T41, IB, IC; void F5<T51, T52>() where T51 : D where T52 : T51, IB, IC; void F6<T61, T62>() where T61 : D where T62 : T61, IB, IC; void F7<T71, T72>() where T71 : D where T72 : T71, IB, IC; void F8<T81, T82>() where T81 : D where T82 : T81, IB, IC; void F9<T91, T92>() where T91 : D where T92 : T91, IB, IC; } public interface IB {} public interface IC {} public class D {} class B : IA { public void F1<T11>() where T11 : D?, IB, IC? { } public void F2<T22>() where T22 : D, IB?, IC? { } public void F3<T33>() where T33 : D?, IB?, IC { } public void F4<T441, T442>() where T441 : D where T442 : T441?, IB, IC? { } public void F5<T551, T552>() where T551 : D where T552 : T551, IB?, IC? { } public void F6<T661, T662>() where T661 : D where T662 : T661?, IB?, IC { } public void F7<T771, T772>() where T771 : D? where T772 : T771, IB, IC? { } public void F8<T881, T882>() where T881 : D where T882 : T881, IB?, IC? { } public void F9<T991, T992>() where T991 : D? where T992 : T991, IB?, IC { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (58,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : D? where T992 : T991, IB?, IC Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(58, 17), // (50,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : D? where T772 : T771, IB, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(50, 17) ); } [Fact] public void Constraints_42() { var source = @" public interface IA { void F1<T1>() where T1 : class?, IB?, IC?; void F2<T2>() where T2 : class?, IB?, IC?; void F3<T3>() where T3 : class?, IB?, IC?; void F4<T41, T42>() where T41 : class? where T42 : T41, IB?, IC?; void F5<T51, T52>() where T51 : class? where T52 : T51, IB?, IC?; void F6<T61, T62>() where T61 : class? where T62 : T61, IB?, IC?; void F7<T71, T72>() where T71 : class where T72 : T71?, IB?, IC?; void F8<T81, T82>() where T81 : class where T82 : T81?, IB?, IC?; void F9<T91, T92>() where T91 : class where T92 : T91?, IB?, IC?; } public interface IB {} public interface IC {} class B : IA { public void F1<T11>() where T11 : class?, IB?, IC? { } public void F2<T22>() where T22 : class?, IB?, IC? { } public void F3<T33>() where T33 : class?, IB?, IC? { } public void F4<T441, T442>() where T441 : class where T442 : T441?, IB?, IC? { } public void F5<T551, T552>() where T551 : class where T552 : T551?, IB?, IC? { } public void F6<T661, T662>() where T661 : class where T662 : T661?, IB?, IC? { } public void F7<T771, T772>() where T771 : class? where T772 : T771, IB?, IC? { } public void F8<T881, T882>() where T881 : class? where T882 : T881, IB?, IC? { } public void F9<T991, T992>() where T991 : class? where T992 : T991, IB?, IC? { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (55,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : class? where T992 : T991, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(55, 17), // (35,17): warning CS8633: Nullability in constraints for type parameter 'T441' of method 'B.F4<T441, T442>()' doesn't match the constraints for type parameter 'T41' of interface method 'IA.F4<T41, T42>()'. Consider using an explicit interface implementation instead. // public void F4<T441, T442>() where T441 : class where T442 : T441?, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T441", "B.F4<T441, T442>()", "T41", "IA.F4<T41, T42>()").WithLocation(35, 17), // (39,17): warning CS8633: Nullability in constraints for type parameter 'T551' of method 'B.F5<T551, T552>()' doesn't match the constraints for type parameter 'T51' of interface method 'IA.F5<T51, T52>()'. Consider using an explicit interface implementation instead. // public void F5<T551, T552>() where T551 : class where T552 : T551?, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F5").WithArguments("T551", "B.F5<T551, T552>()", "T51", "IA.F5<T51, T52>()").WithLocation(39, 17), // (43,17): warning CS8633: Nullability in constraints for type parameter 'T661' of method 'B.F6<T661, T662>()' doesn't match the constraints for type parameter 'T61' of interface method 'IA.F6<T61, T62>()'. Consider using an explicit interface implementation instead. // public void F6<T661, T662>() where T661 : class where T662 : T661?, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F6").WithArguments("T661", "B.F6<T661, T662>()", "T61", "IA.F6<T61, T62>()").WithLocation(43, 17), // (47,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : class? where T772 : T771, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(47, 17), // (51,17): warning CS8633: Nullability in constraints for type parameter 'T881' of method 'B.F8<T881, T882>()' doesn't match the constraints for type parameter 'T81' of interface method 'IA.F8<T81, T82>()'. Consider using an explicit interface implementation instead. // public void F8<T881, T882>() where T881 : class? where T882 : T881, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F8").WithArguments("T881", "B.F8<T881, T882>()", "T81", "IA.F8<T81, T82>()").WithLocation(51, 17) ); } [Fact] public void Constraints_43() { var source = @" public interface IA { void F7<T71, T72>() where T71 : class where T72 : T71?, IB?, IC?; void F8<T81, T82>() where T81 : class where T82 : T81?, IB?, IC?; void F9<T91, T92>() where T91 : class where T92 : T91?, IB?, IC?; } public interface IB {} public interface IC {} class B : IA { public void F7<T771, T772>() where T771 : class? where T772 : T771?, IB?, IC? { } public void F8<T881, T882>() where T881 : class? where T882 : T881?, IB?, IC? { } public void F9<T991, T992>() where T991 : class? where T992 : T991?, IB?, IC? { } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp1.VerifyDiagnostics( // (25,67): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F9<T991, T992>() where T991 : class? where T992 : T991?, IB?, IC? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T991?").WithArguments("9.0").WithLocation(25, 67), // (21,67): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F8<T881, T882>() where T881 : class? where T882 : T881?, IB?, IC? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T881?").WithArguments("9.0").WithLocation(21, 67), // (17,67): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public void F7<T771, T772>() where T771 : class? where T772 : T771?, IB?, IC? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T771?").WithArguments("9.0").WithLocation(17, 67), // (25,17): warning CS8633: Nullability in constraints for type parameter 'T991' of method 'B.F9<T991, T992>()' doesn't match the constraints for type parameter 'T91' of interface method 'IA.F9<T91, T92>()'. Consider using an explicit interface implementation instead. // public void F9<T991, T992>() where T991 : class? where T992 : T991?, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F9").WithArguments("T991", "B.F9<T991, T992>()", "T91", "IA.F9<T91, T92>()").WithLocation(25, 17), // (21,17): warning CS8633: Nullability in constraints for type parameter 'T881' of method 'B.F8<T881, T882>()' doesn't match the constraints for type parameter 'T81' of interface method 'IA.F8<T81, T82>()'. Consider using an explicit interface implementation instead. // public void F8<T881, T882>() where T881 : class? where T882 : T881?, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F8").WithArguments("T881", "B.F8<T881, T882>()", "T81", "IA.F8<T81, T82>()").WithLocation(21, 17), // (17,17): warning CS8633: Nullability in constraints for type parameter 'T771' of method 'B.F7<T771, T772>()' doesn't match the constraints for type parameter 'T71' of interface method 'IA.F7<T71, T72>()'. Consider using an explicit interface implementation instead. // public void F7<T771, T772>() where T771 : class? where T772 : T771?, IB?, IC? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F7").WithArguments("T771", "B.F7<T771, T772>()", "T71", "IA.F7<T71, T72>()").WithLocation(17, 17) ); } [Fact] public void Constraints_44() { var source1 = @" public interface IA { void F1<T1>() where T1 : class?, IB?; void F2<T2>() where T2 : class, IB?; void F3<T3>() where T3 : C1, IB?; void F4<T4>() where T4 : C1?, IB?; } public class C1 {} public interface IB {} "; var source2 = @" class B : IA { public void F1<T11>() where T11 : class, IB? { } public void F2<T22>() where T22 : class?, IB? { } public void F3<T33>() where T33 : C1?, IB? { } public void F4<T44>() where T44 : C1, IB? { } } class D : IA { public void F1<T111>() where T111 : class?, IB? { } public void F2<T222>() where T222 : class, IB? { } public void F3<T333>() where T333 : C1, IB? { } public void F4<T444>() where T444 : C1?, IB? { } } "; var comp1 = CreateCompilation(new[] { source2, source1 }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T11' of method 'B.F1<T11>()' doesn't match the constraints for type parameter 'T1' of interface method 'IA.F1<T1>()'. Consider using an explicit interface implementation instead. // public void F1<T11>() where T11 : class, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("T11", "B.F1<T11>()", "T1", "IA.F1<T1>()").WithLocation(4, 17), // (8,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA.F2<T2>()").WithLocation(8, 17), // (12,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA.F3<T3>()").WithLocation(12, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'T44' of method 'B.F4<T44>()' doesn't match the constraints for type parameter 'T4' of interface method 'IA.F4<T4>()'. Consider using an explicit interface implementation instead. // public void F4<T44>() where T44 : C1, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T44", "B.F4<T44>()", "T4", "IA.F4<T4>()").WithLocation(16, 17) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.True(t11.IsNotNullable); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.False(t22.IsNotNullable); var bf3 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F3"); TypeParameterSymbol t33 = bf3.TypeParameters[0]; Assert.False(t33.IsNotNullable); var bf4 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F4"); TypeParameterSymbol t44 = bf4.TypeParameters[0]; Assert.True(t44.IsNotNullable); } var comp2 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); comp2.VerifyDiagnostics( ); var comp3 = CreateCompilation(new[] { source2 }, references: new[] { comp2.ToMetadataReference() }, options: WithNullable(NullableContextOptions.Warnings)); comp3.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (8,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA.F2<T2>()").WithLocation(8, 17), // (12,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA.F3<T3>()").WithLocation(12, 17) ); symbolValidator2(comp3.SourceModule); void symbolValidator2(ModuleSymbol m) { var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.Null(t11.IsNotNullable); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.False(t22.IsNotNullable); var bf3 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F3"); TypeParameterSymbol t33 = bf3.TypeParameters[0]; Assert.False(t33.IsNotNullable); var bf4 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F4"); TypeParameterSymbol t44 = bf4.TypeParameters[0]; Assert.Null(t44.IsNotNullable); } var comp4 = CreateCompilation(new[] { source1 }); var comp5 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp4.ToMetadataReference() }); comp5.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T11' of method 'B.F1<T11>()' doesn't match the constraints for type parameter 'T1' of interface method 'IA.F1<T1>()'. Consider using an explicit interface implementation instead. // public void F1<T11>() where T11 : class, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("T11", "B.F1<T11>()", "T1", "IA.F1<T1>()").WithLocation(4, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'T44' of method 'B.F4<T44>()' doesn't match the constraints for type parameter 'T4' of interface method 'IA.F4<T4>()'. Consider using an explicit interface implementation instead. // public void F4<T44>() where T44 : C1, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F4").WithArguments("T44", "B.F4<T44>()", "T4", "IA.F4<T4>()").WithLocation(16, 17) ); symbolValidator1(comp5.SourceModule); var comp6 = CreateCompilation(new[] { source2 }, references: new[] { comp4.ToMetadataReference() }); comp6.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( ); symbolValidator2(comp6.SourceModule); } [Fact] public void Constraints_45() { var source1 = @" public interface IA { void F2<T2>() where T2 : class?, IB; void F3<T3>() where T3 : C1?, IB; } public class C1 {} public interface IB {} "; var source2 = @" class B : IA { public void F2<T22>() where T22 : class?, IB? { } public void F3<T33>() where T33 : C1?, IB? { } } class D : IA { public void F2<T222>() where T222 : class?, IB { } public void F3<T333>() where T333 : C1?, IB { } } "; var comp1 = CreateCompilation(new[] { source2, source1 }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA.F2<T2>()").WithLocation(4, 17), // (8,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA.F3<T3>()").WithLocation(8, 17) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("D.F2"); TypeParameterSymbol t222 = bf2.TypeParameters[0]; Assert.True(t222.IsNotNullable); var bf3 = (MethodSymbol)m.GlobalNamespace.GetMember("D.F3"); TypeParameterSymbol t333 = bf3.TypeParameters[0]; Assert.True(t333.IsNotNullable); } var comp2 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); comp2.VerifyDiagnostics( ); var comp3 = CreateCompilation(new[] { source2 }, references: new[] { comp2.ToMetadataReference() }, options: WithNullable(NullableContextOptions.Warnings)); comp3.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (4,17): warning CS8633: Nullability in constraints for type parameter 'T22' of method 'B.F2<T22>()' doesn't match the constraints for type parameter 'T2' of interface method 'IA.F2<T2>()'. Consider using an explicit interface implementation instead. // public void F2<T22>() where T22 : class?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("T22", "B.F2<T22>()", "T2", "IA.F2<T2>()").WithLocation(4, 17), // (8,17): warning CS8633: Nullability in constraints for type parameter 'T33' of method 'B.F3<T33>()' doesn't match the constraints for type parameter 'T3' of interface method 'IA.F3<T3>()'. Consider using an explicit interface implementation instead. // public void F3<T33>() where T33 : C1?, IB? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F3").WithArguments("T33", "B.F3<T33>()", "T3", "IA.F3<T3>()").WithLocation(8, 17) ); symbolValidator2(comp3.SourceModule); void symbolValidator2(ModuleSymbol m) { var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("D.F2"); TypeParameterSymbol t222 = bf2.TypeParameters[0]; Assert.Null(t222.IsNotNullable); var bf3 = (MethodSymbol)m.GlobalNamespace.GetMember("D.F3"); TypeParameterSymbol t333 = bf3.TypeParameters[0]; Assert.Null(t333.IsNotNullable); } var comp4 = CreateCompilation(new[] { source1 }); var comp5 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp4.ToMetadataReference() }); comp5.VerifyDiagnostics( ); symbolValidator1(comp5.SourceModule); var comp6 = CreateCompilation(new[] { source2 }, references: new[] { comp4.ToMetadataReference() }); comp6.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( ); symbolValidator2(comp6.SourceModule); } [Fact] public void Constraints_46() { var source = @" class B { public static void F1<T1>() where T1 : notnull { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>() where T1 : notnull", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(f1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", f1.GetAttributes().Single().ToString()); } TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.IsReferenceType); Assert.True(t1.IsNotNullable); var attributes = t1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_47() { var source = @" class B { public static void F1<T1>() where T1 : notnull { } }"; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>() where T1 : notnull", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(f1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", f1.GetAttributes().Single().ToString()); } TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.IsReferenceType); Assert.True(t1.HasNotNullConstraint); Assert.True(t1.IsNotNullable); var attributes = t1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_48() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : object? { } public static void F2<T2>(T2? t2) where T2 : System.Object? { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F1<T1>(T1? t1) where T1 : object? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T1?").WithArguments("9.0").WithLocation(4, 31), // (4,50): error CS0702: Constraint cannot be special class 'object' // public static void F1<T1>(T1? t1) where T1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(4, 50), // (8,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F2<T2>(T2? t2) where T2 : System.Object? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(8, 31), // (8,50): error CS0702: Constraint cannot be special class 'object' // public static void F2<T2>(T2? t2) where T2 : System.Object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "System.Object?").WithArguments("object").WithLocation(8, 50) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1)", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.IsReferenceType); Assert.False(t1.IsNotNullable); Assert.Empty(t1.GetAttributes()); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T2>(T2? t2)", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.False(t2.IsReferenceType); Assert.False(t2.IsNotNullable); Assert.Empty(t2.GetAttributes()); } [Fact] public void Constraints_49() { var source = @" class B { public static void F1<T1>() where T1 : notnull { } }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7_3); var expected = new[] { // (4,44): error CS8652: The feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // public static void F1<T1>() where T1 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(4, 44) }; comp.VerifyDiagnostics(expected); { var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>() where T1 : notnull", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.IsReferenceType); Assert.True(t1.IsNotNullable); Assert.Empty(t1.GetAttributes()); } comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); comp.VerifyDiagnostics(expected .Concat(new[] { // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.3. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.3", "8.0").WithLocation(1, 1), }).ToArray() ); { var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>() where T1 : notnull", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.False(t1.IsReferenceType); Assert.True(t1.IsNotNullable); Assert.Empty(t1.GetAttributes()); } } [Fact] public void Constraints_50() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : notnull { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F1<T1>(T1? t1) where T1 : notnull Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T1?").WithArguments("9.0").WithLocation(4, 31) ); } [Fact] public void Constraints_51() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : struct, notnull { } public static void F2<T2>(T2? t2) where T2 : notnull, struct { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,59): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F2<T2>(T2? t2) where T2 : notnull, struct Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(8, 59), // (4,58): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F1<T1>(T1? t1) where T1 : struct, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(4, 58) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : struct", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsValueType); Assert.True(t1.HasNotNullConstraint); Assert.True(t1.IsNotNullable); Assert.Empty(t1.GetAttributes()); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T2>(T2? t2) where T2 : struct", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.IsValueType); Assert.True(t2.HasNotNullConstraint); Assert.True(t2.IsNotNullable); Assert.Empty(t2.GetAttributes()); } [Fact] public void Constraints_52() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : class, notnull { } public static void F2<T2>(T2? t2) where T2 : notnull, class { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,57): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F1<T1>(T1? t1) where T1 : class, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(4, 57), // (8,59): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F2<T2>(T2? t2) where T2 : notnull, class Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(8, 59) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : class!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.True(t1.IsNotNullable); Assert.Empty(t1.GetAttributes()); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T2>(T2? t2) where T2 : class!", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.IsReferenceType); Assert.True(t2.IsNotNullable); Assert.Empty(t2.GetAttributes()); } [Fact] public void Constraints_53() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : class?, notnull { } public static void F2<T2>(T2? t2) where T2 : notnull, class? { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); Assert.True(((MethodSymbol)comp.SourceModule.GlobalNamespace.GetMember("B.F1")).TypeParameters[0].IsNotNullable); comp.VerifyDiagnostics( // (4,58): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F1<T1>(T1? t1) where T1 : class?, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(4, 58), // (8,59): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F2<T2>(T2? t2) where T2 : notnull, class? Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class?").WithLocation(8, 59) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : class?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.True(t1.IsNotNullable); Assert.Empty(t1.GetAttributes()); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T2>(T2? t2) where T2 : class?", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = f2.TypeParameters[0]; Assert.True(t2.IsReferenceType); Assert.True(t2.IsNotNullable); Assert.Empty(t2.GetAttributes()); } [Fact] public void Constraints_54() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : class?, B { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static void F1<T1>(T1? t1) where T1 : class?, B Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T1?").WithArguments("9.0").WithLocation(4, 31), // (4,58): error CS0450: 'B': cannot specify both a constraint class and the 'class' or 'struct' constraint // public static void F1<T1>(T1? t1) where T1 : class?, B Diagnostic(ErrorCode.ERR_RefValBoundWithClass, "B").WithArguments("B").WithLocation(4, 58) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : class?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.False(t1.IsNotNullable); } [Fact] public void Constraints_55() { var source = @" interface I<TI> { void F1<TF1>(TF1 x) where TF1 : TI; } class A : I<object> { void I<object>.F1<TF1A>(TF1A x) {} } class B : I<object?> { void I<object?>.F1<TF1B>(TF1B x) {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var af1 = (MethodSymbol)m.GlobalNamespace.GetMember("A.I<System.Object>.F1"); Assert.Equal("I<System.Object>.F1", af1.Name); Assert.Equal("I<System.Object>.F1", af1.MetadataName); if (isSource) { Assert.Equal("void A.I<System.Object!>.F1<TF1A>(TF1A x) where TF1A : System.Object!", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void A.I<System.Object>.F1<TF1A>(TF1A x) where TF1A : System.Object!", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", af1.GetAttributes().Single().ToString()); } TypeParameterSymbol at1 = af1.TypeParameters[0]; Assert.False(at1.IsReferenceType); Assert.True(at1.IsNotNullable); if (isSource) { Assert.Empty(at1.GetAttributes()); Assert.Equal("void I<System.Object!>.F1<TF1>(TF1 x) where TF1 : System.Object!", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(0)", at1.GetAttributes().Single().ToString()); var impl = af1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I<System.Object>.F1<TF1>(TF1 x)", impl.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(impl.TypeParameters[0].IsNotNullable); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.I<System.Object>.F1"); Assert.Equal("I<System.Object>.F1", bf1.Name); Assert.Equal("I<System.Object>.F1", bf1.MetadataName); if (isSource) { Assert.Equal("void B.I<System.Object?>.F1<TF1B>(TF1B x)", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void B.I<System.Object>.F1<TF1B>(TF1B x)", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", bf1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = bf1.TypeParameters[0]; Assert.False(tf1.IsReferenceType); Assert.False(tf1.IsNotNullable); if (isSource) { Assert.Empty(tf1.GetAttributes()); Assert.Equal("void I<System.Object?>.F1<TF1>(TF1 x)", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { var attributes = tf1.GetAttributes(); Assert.Equal(1, attributes.Length); Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", attributes[0].ToString()); var impl = bf1.ExplicitInterfaceImplementations.Single(); Assert.Equal("void I<System.Object>.F1<TF1>(TF1 x)", impl.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(impl.TypeParameters[0].IsNotNullable); } } } [Fact] public void Constraints_56() { var source = @" interface I<TI> { void F1<TF1>(TF1 x) where TF1 : TI; } class A : I<A> { void I<A>.F1<TF1A>(TF1A x) {} } class B : I<A?> { void I<A?>.F1<TF1B>(TF1B x) {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var af1 = (MethodSymbol)m.GlobalNamespace.GetMember("A.I<A>.F1"); Assert.Equal("I<A>.F1", af1.Name); Assert.Equal("I<A>.F1", af1.MetadataName); if (isSource) { Assert.Equal("void A.I<A!>.F1<TF1A>(TF1A! x) where TF1A : A!", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void A.I<A>.F1<TF1A>(TF1A! x) where TF1A : A!", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", af1.GetAttributes().Single().ToString()); } TypeParameterSymbol at1 = af1.TypeParameters[0]; Assert.True(at1.IsReferenceType); Assert.True(at1.IsNotNullable); if (isSource) { Assert.Empty(at1.GetAttributes()); Assert.Equal("void I<A!>.F1<TF1>(TF1 x) where TF1 : A!", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(0)", at1.GetAttributes().Single().ToString()); Assert.Equal("void I<A>.F1<TF1>(TF1 x) where TF1 : A", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.I<A>.F1"); Assert.Equal("I<A>.F1", bf1.Name); Assert.Equal("I<A>.F1", bf1.MetadataName); if (isSource) { Assert.Equal("void B.I<A?>.F1<TF1B>(TF1B x) where TF1B : A?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void B.I<A>.F1<TF1B>(TF1B x) where TF1B : A?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Empty(bf1.GetAttributes()); } TypeParameterSymbol tf1 = bf1.TypeParameters[0]; Assert.True(tf1.IsReferenceType); Assert.False(tf1.IsNotNullable); if (isSource) { Assert.Empty(tf1.GetAttributes()); Assert.Equal("void I<A?>.F1<TF1>(TF1 x) where TF1 : A?", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Empty(tf1.GetAttributes()); Assert.Equal("void I<A>.F1<TF1>(TF1 x) where TF1 : A", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } } } [Fact] public void Constraints_57() { var source = @" interface I<TI> { void F1<TF1>(TF1 x) where TF1 : class?, TI; } class A : I<object> { void I<object>.F1<TF1A>(TF1A x) {} } class B : I<object?> { void I<object?>.F1<TF1B>(TF1B x) {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var af1 = (MethodSymbol)m.GlobalNamespace.GetMember("A.I<System.Object>.F1"); Assert.Equal("I<System.Object>.F1", af1.Name); Assert.Equal("I<System.Object>.F1", af1.MetadataName); if (isSource) { Assert.Equal("void A.I<System.Object!>.F1<TF1A>(TF1A! x) where TF1A : class?, System.Object!", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void A.I<System.Object>.F1<TF1A>(TF1A! x) where TF1A : class?, System.Object!", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } TypeParameterSymbol at1 = af1.TypeParameters[0]; Assert.True(at1.IsReferenceType); Assert.True(at1.IsNotNullable); if (isSource) { Assert.Equal("void I<System.Object!>.F1<TF1>(TF1 x) where TF1 : class?, System.Object!", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void I<System.Object>.F1<TF1>(TF1 x) where TF1 : class?, System.Object", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.I<System.Object>.F1"); Assert.Equal("I<System.Object>.F1", bf1.Name); Assert.Equal("I<System.Object>.F1", bf1.MetadataName); if (isSource) { Assert.Equal("void B.I<System.Object?>.F1<TF1B>(TF1B x) where TF1B : class?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void B.I<System.Object>.F1<TF1B>(TF1B x) where TF1B : class?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } TypeParameterSymbol tf1 = bf1.TypeParameters[0]; Assert.True(tf1.IsReferenceType); Assert.False(tf1.IsNotNullable); if (isSource) { Assert.Equal("void I<System.Object?>.F1<TF1>(TF1 x) where TF1 : class?", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void I<System.Object>.F1<TF1>(TF1 x) where TF1 : class?, System.Object", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } } } [Fact] public void Constraints_58() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : B, notnull { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,53): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // public static void F1<T1>(T1? t1) where T1 : B, notnull Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(4, 53) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : notnull, B!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.True(t1.IsNotNullable); } [Fact] public void Constraints_59() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : notnull, B? { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : notnull, B?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.True(t1.HasNotNullConstraint); Assert.True(t1.IsNotNullable); } } [Fact] public void Constraints_60() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : notnull, B { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : notnull, B!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.True(t1.IsNotNullable); } [Fact] public void Constraints_61() { var source = @" class B { public static void F1<T1>(T1? t1) where T1 : object?, B { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,50): error CS0702: Constraint cannot be special class 'object' // public static void F1<T1>(T1? t1) where T1 : object?, B Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(4, 50) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T1>(T1? t1) where T1 : B!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = f1.TypeParameters[0]; Assert.True(t1.IsReferenceType); Assert.True(t1.IsNotNullable); } [Fact] public void Constraints_62() { var source = @" interface I<TI> { void F1<TF1>(TF1 x) where TF1 : B?, TI; } class A : I<object> { void I<object>.F1<TF1A>(TF1A x) {} } class B : I<object?> { void I<object?>.F1<TF1B>(TF1B x) {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var af1 = (MethodSymbol)m.GlobalNamespace.GetMember("A.I<System.Object>.F1"); Assert.Equal("I<System.Object>.F1", af1.Name); Assert.Equal("I<System.Object>.F1", af1.MetadataName); if (isSource) { Assert.Equal("void A.I<System.Object!>.F1<TF1A>(TF1A! x) where TF1A : System.Object!, B?", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void A.I<System.Object>.F1<TF1A>(TF1A! x) where TF1A : System.Object!, B?", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } TypeParameterSymbol at1 = af1.TypeParameters[0]; Assert.True(at1.IsReferenceType); Assert.True(at1.IsNotNullable); if (isSource) { Assert.Equal("void I<System.Object!>.F1<TF1>(TF1 x) where TF1 : System.Object!, B?", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void I<System.Object>.F1<TF1>(TF1 x) where TF1 : System.Object, B?", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.I<System.Object>.F1"); Assert.Equal("I<System.Object>.F1", bf1.Name); Assert.Equal("I<System.Object>.F1", bf1.MetadataName); if (isSource) { Assert.Equal("void B.I<System.Object?>.F1<TF1B>(TF1B x) where TF1B : B?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void B.I<System.Object>.F1<TF1B>(TF1B x) where TF1B : B?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } TypeParameterSymbol tf1 = bf1.TypeParameters[0]; Assert.True(tf1.IsReferenceType); Assert.False(tf1.IsNotNullable); if (isSource) { Assert.Equal("void I<System.Object?>.F1<TF1>(TF1 x) where TF1 : B?", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void I<System.Object>.F1<TF1>(TF1 x) where TF1 : System.Object, B?", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } } } [Fact] public void Constraints_63() { var source = @" interface I<TI1, TI2> { void F1<TF1>(TF1 x) where TF1 : TI1, TI2; } class A : I<object, B?> { void I<object, B?>.F1<TF1A>(TF1A x) {} } class B : I<object?, B?> { void I<object?, B?>.F1<TF1B>(TF1B x) {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var af1 = (MethodSymbol)m.GlobalNamespace.GetMember("A.I<System.Object,B>.F1"); Assert.Equal("I<System.Object,B>.F1", af1.Name); Assert.Equal("I<System.Object,B>.F1", af1.MetadataName); if (isSource) { Assert.Equal("void A.I<System.Object!, B?>.F1<TF1A>(TF1A! x) where TF1A : System.Object!, B?", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void A.I<System.Object, B>.F1<TF1A>(TF1A! x) where TF1A : System.Object!, B?", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } TypeParameterSymbol at1 = af1.TypeParameters[0]; Assert.True(at1.IsReferenceType); Assert.True(at1.IsNotNullable); if (isSource) { Assert.Equal("void I<System.Object!, B?>.F1<TF1>(TF1 x) where TF1 : System.Object!, B?", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void I<System.Object, B>.F1<TF1>(TF1 x) where TF1 : B", af1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.I<System.Object,B>.F1"); Assert.Equal("I<System.Object,B>.F1", bf1.Name); Assert.Equal("I<System.Object,B>.F1", bf1.MetadataName); if (isSource) { Assert.Equal("void B.I<System.Object?, B?>.F1<TF1B>(TF1B x) where TF1B : B?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void B.I<System.Object, B>.F1<TF1B>(TF1B x) where TF1B : B?", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } TypeParameterSymbol tf1 = bf1.TypeParameters[0]; Assert.True(tf1.IsReferenceType); Assert.False(tf1.IsNotNullable); if (isSource) { Assert.Equal("void I<System.Object?, B?>.F1<TF1>(TF1 x) where TF1 : B?", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } else { Assert.Equal("void I<System.Object, B>.F1<TF1>(TF1 x) where TF1 : B", bf1.ExplicitInterfaceImplementations.Single().ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } } } [Fact] public void Constraints_64() { var source = @" interface I1 { void F1<TF1>(); void F2<TF2>() where TF2 : notnull; void F3<TF3>() where TF3 : notnull; void F4<TF4>() where TF4 : I3; void F5<TF5>() where TF5 : I3; void F6<TF6>() where TF6 : I3?; void F7<TF7>() where TF7 : notnull, I3; void F8<TF8>() where TF8 : notnull, I3; void F9<TF9>() where TF9 : notnull, I3; void F10<TF10>() where TF10 : notnull, I3?; void F11<TF11>() where TF11 : notnull, I3?; void F12<TF12>() where TF12 : notnull, I3?; void F13<TF13>() where TF13 : notnull, I3?; } public interface I3 { } class A : I1 { public void F1<TF1A>() where TF1A : notnull {} public void F2<TF2A>() {} public void F3<TF3A>() where TF3A : notnull {} public void F4<TF4A>() where TF4A : notnull, I3 {} public void F5<TF5A>() where TF5A : notnull, I3? {} public void F6<TF6A>() where TF6A : notnull, I3? {} public void F7<TF7A>() where TF7A : I3 {} public void F8<TF8A>() where TF8A : I3? {} public void F9<TF9A>() where TF9A : notnull, I3 {} public void F10<TF10A>() where TF10A : I3 {} public void F11<TF11A>() where TF11A : I3? {} public void F12<TF12A>() where TF12A : notnull, I3 {} public void F13<TF13A>() where TF13A : notnull, I3? {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (25,17): warning CS8633: Nullability in constraints for type parameter 'TF1A' of method 'A.F1<TF1A>()' doesn't match the constraints for type parameter 'TF1' of interface method 'I1.F1<TF1>()'. Consider using an explicit interface implementation instead. // public void F1<TF1A>() where TF1A : notnull Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("TF1A", "A.F1<TF1A>()", "TF1", "I1.F1<TF1>()").WithLocation(25, 17), // (27,17): warning CS8633: Nullability in constraints for type parameter 'TF2A' of method 'A.F2<TF2A>()' doesn't match the constraints for type parameter 'TF2' of interface method 'I1.F2<TF2>()'. Consider using an explicit interface implementation instead. // public void F2<TF2A>() Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("TF2A", "A.F2<TF2A>()", "TF2", "I1.F2<TF2>()").WithLocation(27, 17), // (35,17): warning CS8633: Nullability in constraints for type parameter 'TF6A' of method 'A.F6<TF6A>()' doesn't match the constraints for type parameter 'TF6' of interface method 'I1.F6<TF6>()'. Consider using an explicit interface implementation instead. // public void F6<TF6A>() where TF6A : notnull, I3? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F6").WithArguments("TF6A", "A.F6<TF6A>()", "TF6", "I1.F6<TF6>()").WithLocation(35, 17), // (39,17): warning CS8633: Nullability in constraints for type parameter 'TF8A' of method 'A.F8<TF8A>()' doesn't match the constraints for type parameter 'TF8' of interface method 'I1.F8<TF8>()'. Consider using an explicit interface implementation instead. // public void F8<TF8A>() where TF8A : I3? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F8").WithArguments("TF8A", "A.F8<TF8A>()", "TF8", "I1.F8<TF8>()").WithLocation(39, 17), // (45,17): warning CS8633: Nullability in constraints for type parameter 'TF11A' of method 'A.F11<TF11A>()' doesn't match the constraints for type parameter 'TF11' of interface method 'I1.F11<TF11>()'. Consider using an explicit interface implementation instead. // public void F11<TF11A>() where TF11A : I3? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F11").WithArguments("TF11A", "A.F11<TF11A>()", "TF11", "I1.F11<TF11>()").WithLocation(45, 17) ); } [Fact] public void Constraints_65() { var source1 = @" public interface I1 { void F1<TF1>(); void F2<TF2>() where TF2 : notnull; void F3<TF3>() where TF3 : notnull; void F4<TF4>() where TF4 : I3; void F5<TF5>() where TF5 : I3; void F7<TF7>() where TF7 : notnull, I3; void F8<TF8>() where TF8 : notnull, I3; void F9<TF9>() where TF9 : notnull, I3; } public interface I3 { } "; var source2 = @" class A : I1 { public void F1<TF1A>() where TF1A : notnull {} public void F2<TF2A>() {} public void F3<TF3A>() where TF3A : notnull {} public void F4<TF4A>() where TF4A : notnull, I3 {} public void F5<TF5A>() where TF5A : notnull, I3? {} public void F7<TF7A>() where TF7A : I3 {} public void F8<TF8A>() where TF8A : I3? {} public void F9<TF9A>() where TF9A : notnull, I3 {} } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); foreach (var reference in new[] { comp1.ToMetadataReference(), comp1.EmitToImageReference() }) { var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { reference }); comp2.VerifyDiagnostics( // (6,17): warning CS8633: Nullability in constraints for type parameter 'TF2A' of method 'A.F2<TF2A>()' doesn't match the constraints for type parameter 'TF2' of interface method 'I1.F2<TF2>()'. Consider using an explicit interface implementation instead. // public void F2<TF2A>() Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F2").WithArguments("TF2A", "A.F2<TF2A>()", "TF2", "I1.F2<TF2>()").WithLocation(6, 17), // (16,17): warning CS8633: Nullability in constraints for type parameter 'TF8A' of method 'A.F8<TF8A>()' doesn't match the constraints for type parameter 'TF8' of interface method 'I1.F8<TF8>()'. Consider using an explicit interface implementation instead. // public void F8<TF8A>() where TF8A : I3? Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F8").WithArguments("TF8A", "A.F8<TF8A>()", "TF8", "I1.F8<TF8>()").WithLocation(16, 17) ); } string il = @" .class interface public abstract auto ansi I1 { .method public hidebysig newslot abstract virtual instance void F1<TF1>() cil managed { } // end of method I1::F1 } // end of class I1"; string source3 = @" class A : I1 { public void F1<TF1A>() where TF1A : notnull {} } "; var comp3 = CreateCompilationWithIL(new[] { source3 }, il, options: WithNullableEnable()); comp3.VerifyDiagnostics(); } [Fact] public void Constraints_66() { var source1 = @" public interface I1 { void F1<TF1>(); void F2<TF2>() where TF2 : notnull; void F3<TF3>() where TF3 : notnull; void F4<TF4>() where TF4 : I3; void F7<TF7>() where TF7 : notnull, I3; void F9<TF9>() where TF9 : notnull, I3; void F10<TF10>() where TF10 : notnull, I3?; void F12<TF12>() where TF12 : notnull, I3?; } public interface I3 { } "; var source2 = @" class A : I1 { public void F1<TF1A>() where TF1A : notnull {} public void F2<TF2A>() {} public void F3<TF3A>() where TF3A : notnull {} public void F4<TF4A>() where TF4A : notnull, I3 {} public void F7<TF7A>() where TF7A : I3 {} public void F9<TF9A>() where TF9A : notnull, I3 {} public void F10<TF10A>() where TF10A : I3 {} public void F12<TF12A>() where TF12A : notnull, I3 {} } "; var comp1 = CreateCompilation(source1, options: WithNullableEnable()); foreach (var reference in new[] { comp1.ToMetadataReference(), comp1.EmitToImageReference() }) { var comp2 = CreateCompilation(source2, options: WithNullable(NullableContextOptions.Warnings), references: new[] { reference }); comp2.VerifyDiagnostics( // (4,17): warning CS8633: Nullability in constraints for type parameter 'TF1A' of method 'A.F1<TF1A>()' doesn't match the constraints for type parameter 'TF1' of interface method 'I1.F1<TF1>()'. Consider using an explicit interface implementation instead. // public void F1<TF1A>() where TF1A : notnull Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnImplicitImplementation, "F1").WithArguments("TF1A", "A.F1<TF1A>()", "TF1", "I1.F1<TF1>()").WithLocation(4, 17) ); } } [Fact] public void Constraints_67() { var source = @" class A { public void F1<TF1>(object x1, TF1 y1, TF1 z1 ) where TF1 : notnull { y1.ToString(); x1 = z1; } public void F2<TF2>(object x2, TF2 y2, TF2 z2 ) where TF2 : class { y2.ToString(); x2 = z2; } public void F3<TF3>(object x3, TF3 y3, TF3 z3 ) where TF3 : class? { y3.ToString(); x3 = z3; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // y3.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y3").WithLocation(18, 9), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x3 = z3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "z3").WithLocation(19, 14) ); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_68() { var source = @" #nullable enable class A { } class C<T> where T : A { C<A?> M(C<A?> c1) { return c1; } } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,11): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // C<A?> M(C<A?> c1) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M").WithArguments("C<T>", "A", "T", "A?").WithLocation(6, 11), // (6,19): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // C<A?> M(C<A?> c1) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "c1").WithArguments("C<T>", "A", "T", "A?").WithLocation(6, 19)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_69() { var source = @" #nullable enable class C<T> where T : notnull { } interface I { C<object?> Property { get; } // 1 C<object?> Method(C<object?> p); // 2 } class C2 : I { public C<object?> Field = new C<object?>(); // 3 C<object?> Property => Field; // 4 C<object?> Method(C<object?> p) => Field; // 5 C<object?> I.Property => Field; // 6 C<object?> I.Method(C<object?> p) => Field; // 7 } delegate C<object?> D(C<object?> p); // 8 "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,16): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> Property { get; } // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Property").WithArguments("C<T>", "T", "object?").WithLocation(6, 16), // (7,16): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> Method(C<object?> p); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Method").WithArguments("C<T>", "T", "object?").WithLocation(7, 16), // (7,34): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> Method(C<object?> p); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("C<T>", "T", "object?").WithLocation(7, 34), // (11,23): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // public C<object?> Field = new C<object?>(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Field").WithArguments("C<T>", "T", "object?").WithLocation(11, 23), // (11,37): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // public C<object?> Field = new C<object?>(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "object?").WithArguments("C<T>", "T", "object?").WithLocation(11, 37), // (12,16): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> Property => Field; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Property").WithArguments("C<T>", "T", "object?").WithLocation(12, 16), // (13,16): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> Method(C<object?> p) => Field; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Method").WithArguments("C<T>", "T", "object?").WithLocation(13, 16), // (13,34): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> Method(C<object?> p) => Field; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("C<T>", "T", "object?").WithLocation(13, 34), // (15,18): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> I.Property => Field; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Property").WithArguments("C<T>", "T", "object?").WithLocation(15, 18), // (16,18): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> I.Method(C<object?> p) => Field; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "Method").WithArguments("C<T>", "T", "object?").WithLocation(16, 18), // (16,36): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // C<object?> I.Method(C<object?> p) => Field; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("C<T>", "T", "object?").WithLocation(16, 36), // (19,12): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // delegate C<object?> D(C<object?> p); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "object?").WithArguments("C<T>", "T", "object?").WithLocation(19, 12), // (19,25): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // delegate C<object?> D(C<object?> p); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "object?").WithArguments("C<T>", "T", "object?").WithLocation(19, 25)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_70() { var source = @" #nullable enable class C<T> where T : class { } interface I { C<object?> Property { get; } // 1 C<object?> Method(C<object?> p); // 2 } class C2 : I { public C<object?> Field = new C<object?>(); // 3 C<object?> Property => Field; // 4 C<object?> Method(C<object?> p) => Field; // 5 C<object?> I.Property => Field; // 6 C<object?> I.Method(C<object?> p) => Field; // 7 } delegate C<object?> D(C<object?> p); // 8 "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,16): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> Property { get; } // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Property").WithArguments("C<T>", "T", "object?").WithLocation(6, 16), // (7,16): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> Method(C<object?> p); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Method").WithArguments("C<T>", "T", "object?").WithLocation(7, 16), // (7,34): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> Method(C<object?> p); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "p").WithArguments("C<T>", "T", "object?").WithLocation(7, 34), // (11,23): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // public C<object?> Field = new C<object?>(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Field").WithArguments("C<T>", "T", "object?").WithLocation(11, 23), // (11,37): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // public C<object?> Field = new C<object?>(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T>", "T", "object?").WithLocation(11, 37), // (12,16): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> Property => Field; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Property").WithArguments("C<T>", "T", "object?").WithLocation(12, 16), // (13,16): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> Method(C<object?> p) => Field; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Method").WithArguments("C<T>", "T", "object?").WithLocation(13, 16), // (13,34): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> Method(C<object?> p) => Field; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "p").WithArguments("C<T>", "T", "object?").WithLocation(13, 34), // (15,18): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> I.Property => Field; // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Property").WithArguments("C<T>", "T", "object?").WithLocation(15, 18), // (16,18): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> I.Method(C<object?> p) => Field; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Method").WithArguments("C<T>", "T", "object?").WithLocation(16, 18), // (16,36): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // C<object?> I.Method(C<object?> p) => Field; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "p").WithArguments("C<T>", "T", "object?").WithLocation(16, 36), // (19,12): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // delegate C<object?> D(C<object?> p); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T>", "T", "object?").WithLocation(19, 12), // (19,25): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // delegate C<object?> D(C<object?> p); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T>", "T", "object?").WithLocation(19, 25)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_71() { var source = @" #nullable enable #pragma warning disable 8019 using static C1<A>; using static C1<A?>; // 1 using static C2<A>; using static C2<A?>; using static C3<A>; // 2 using static C3<A?>; using static C4<A>; using static C4<A?>; class A { } static class C1<T> where T : A { } static class C2<T> where T : A? { } static class C3<T> where T : class { } static class C4<T> where T : class? { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,14): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C1<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // using static C1<A?>; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "C1<A?>").WithArguments("C1<T>", "A", "T", "A?").WithLocation(6, 14), // (10,14): warning CS8634: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C3<T>'. Nullability of type argument 'A?' doesn't match 'class' constraint. // using static C3<A?>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "C3<A?>").WithArguments("C3<T>", "T", "A?").WithLocation(10, 14)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_72() { var source = @" #nullable enable #pragma warning disable 8019 using D1 = C1<A>; using D2 = C1<A?>; // 1 using D3 = C2<A>; using D4 = C2<A?>; using D5 = C3<A>; // 2 using D6 = C3<A?>; using D7 = C4<A>; using D8 = C4<A?>; class A { } static class C1<T> where T : A { } static class C2<T> where T : A? { } static class C3<T> where T : class { } static class C4<T> where T : class? { } "; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics( // (6,7): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C1<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // using D2 = C1<A?>; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "D2").WithArguments("C1<T>", "A", "T", "A?").WithLocation(6, 7), // (10,7): warning CS8634: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C3<T>'. Nullability of type argument 'A?' doesn't match 'class' constraint. // using D6 = C3<A?>; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "D6").WithArguments("C3<T>", "T", "A?").WithLocation(10, 7)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_73() { var source = @" #nullable enable class C<T> { void M1((string, string?) p) { } // 1 void M2((string, string) p) { } void M3(C<(string, string?)> p) { } // 2 void M4(C<(string, string)> p) { } } "; var compilation = CreateCompilation(new[] { Tuple2NonNullable, source }, targetFramework: TargetFramework.Mscorlib46); compilation.VerifyDiagnostics( // (4,31): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // void M1((string, string?) p) { } // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("(T1, T2)", "T2", "string?").WithLocation(4, 31), // (6,34): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // void M3(C<(string, string?)> p) { } // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("(T1, T2)", "T2", "string?").WithLocation(6, 34)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_74() { var source = @" #nullable enable class C<T> where T : notnull { } class D1 { D1((string, string?) p) { } // 1 D1(C<(string, string?)> p) { } // 2 D1(C<string?> p) { } // 3 } class D2 { D2((string, string) p) { } D2(C<(string, string)> p) { } D2(C<string> p) { } } "; var compilation = CreateCompilation(new[] { Tuple2NonNullable, source }, targetFramework: TargetFramework.Mscorlib46); compilation.VerifyDiagnostics( // (5,26): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // D1((string, string?) p) { } // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("(T1, T2)", "T2", "string?").WithLocation(5, 26), // (6,29): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // D1(C<(string, string?)> p) { } // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("(T1, T2)", "T2", "string?").WithLocation(6, 29), // (7,19): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // D1(C<string?> p) { } // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "p").WithArguments("C<T>", "T", "string?").WithLocation(7, 19)); } [Fact] [WorkItem(32953, "https://github.com/dotnet/roslyn/issues/32953")] public void Constraints_75() { var source = @" #nullable enable class C<T> where T : notnull { } class D1 { public static implicit operator D1(C<string> c) => new D1(); public static implicit operator C<string>(D1 D1) => new C<string>(); } class D2 { public static implicit operator D2(C<string?> c) => new D2(); // 1 public static implicit operator C<string?>(D2 D2) => new C<string?>(); // 2, 3 } "; var compilation = CreateCompilation(source, targetFramework: TargetFramework.Mscorlib46); compilation.VerifyDiagnostics( // (9,51): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // public static implicit operator D2(C<string?> c) => new D2(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "c").WithArguments("C<T>", "T", "string?").WithLocation(9, 51), // (10,37): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // public static implicit operator C<string?>(D2 D2) => new C<string?>(); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "C<string?>").WithArguments("C<T>", "T", "string?").WithLocation(10, 37), // (10,64): warning CS8714: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'C<T>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // public static implicit operator C<string?>(D2 D2) => new C<string?>(); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("C<T>", "T", "string?").WithLocation(10, 64)); } [Fact] [WorkItem(33303, "https://github.com/dotnet/roslyn/issues/33303")] public void Constraints_76() { var source = @" #nullable enable #pragma warning disable 8600, 219 class C { void TupleLiterals() { string s1 = string.Empty; string? s2 = null; var t1 = (s1, s1); var t2 = (s1, s2); // 1 var t3 = (s2, s1); // 2 var t4 = (s2, s2); // 3, 4 var t5 = ((string)null, s1); // 5 var t6 = ((string)null, s1, s1, s1, s1, s1, s1, (string)null, (string)null); // 6, 7, 8 } } "; var compilation = CreateCompilation(new[] { Tuple2NonNullable, TupleRestNonNullable, source }, targetFramework: TargetFramework.Mscorlib46); compilation.VerifyDiagnostics( // (9,23): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t2 = (s1, s2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "s2").WithArguments("(T1, T2)", "T2", "string?").WithLocation(9, 23), // (10,19): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t3 = (s2, s1); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "s2").WithArguments("(T1, T2)", "T1", "string?").WithLocation(10, 19), // (11,19): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t4 = (s2, s2); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "s2").WithArguments("(T1, T2)", "T1", "string?").WithLocation(11, 19), // (11,23): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t4 = (s2, s2); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "s2").WithArguments("(T1, T2)", "T2", "string?").WithLocation(11, 23), // (12,19): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t5 = ((string)null, s1); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "(string)null").WithArguments("(T1, T2)", "T1", "string?").WithLocation(12, 19), // (13,19): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t6 = ((string)null, s1, s1, s1, s1, s1, s1, (string)null, (string)null); // 6, 7, 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "(string)null").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "T1", "string?").WithLocation(13, 19), // (13,57): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t6 = ((string)null, s1, s1, s1, s1, s1, s1, (string)null, (string)null); // 6, 7, 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "(string)null").WithArguments("(T1, T2)", "T1", "string?").WithLocation(13, 57), // (13,71): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // var t6 = ((string)null, s1, s1, s1, s1, s1, s1, (string)null, (string)null); // 6, 7, 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "(string)null").WithArguments("(T1, T2)", "T2", "string?").WithLocation(13, 71) ); } [Fact] [WorkItem(33303, "https://github.com/dotnet/roslyn/issues/33303")] public void Constraints_77() { var source = @" using System; #nullable enable #pragma warning disable 168 class C { void TupleTypes() { (string?, string) t1; (string?, string, string, string, string, string, string, string, string?) t2; Type t3 = typeof((string?, string)); Type t4 = typeof((string?, string, string, string, string, string, string, string, string?)); } } "; var compilation = CreateCompilation(new[] { Tuple2NonNullable, TupleRestNonNullable, source }, targetFramework: TargetFramework.Mscorlib46); compilation.VerifyDiagnostics( // (7,10): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // (string?, string) t1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("(T1, T2)", "T1", "string?").WithLocation(7, 10), // (8,10): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // (string?, string, string, string, string, string, string, string, string?) t2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "T1", "string?").WithLocation(8, 10), // (8,75): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // (string?, string, string, string, string, string, string, string, string?) t2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("(T1, T2)", "T2", "string?").WithLocation(8, 75), // (9,27): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // Type t3 = typeof((string?, string)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("(T1, T2)", "T1", "string?").WithLocation(9, 27), // (10,27): warning CS8714: The type 'string?' cannot be used as type parameter 'T1' in the generic type or method 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // Type t4 = typeof((string?, string, string, string, string, string, string, string, string?)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest>", "T1", "string?").WithLocation(10, 27), // (10,92): warning CS8714: The type 'string?' cannot be used as type parameter 'T2' in the generic type or method '(T1, T2)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // Type t4 = typeof((string?, string, string, string, string, string, string, string, string?)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("(T1, T2)", "T2", "string?").WithLocation(10, 92) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33011")] [WorkItem(33303, "https://github.com/dotnet/roslyn/issues/33303")] public void Constraints_78() { var source = @" #nullable enable #pragma warning disable 8600 class C { void Deconstruction() { string s1; string? s2; C c = new C(); (s1, s1) = ("""", """"); (s2, s1) = ((string)null, """"); var v1 = (s2, s1) = ((string)null, """"); // 1 var v2 = (s1, s1) = ((string)null, """"); // 2 (s2, s1) = c; (string? s3, string s4) = c; var v2 = (s2, s1) = c; // 3 } public void Deconstruct(out string? s1, out string s2) { s1 = null; s2 = string.Empty; } } "; var compilation = CreateCompilation(new[] { Tuple2NonNullable, source }, targetFramework: TargetFramework.Mscorlib46); compilation.VerifyDiagnostics( ); } [Fact] [WorkItem(33303, "https://github.com/dotnet/roslyn/issues/33303")] public void Constraints_79() { var source = @" using System; #nullable enable #pragma warning disable 168 class C { void TupleTypes() { (string?, string) t1; Type t2 = typeof((string?, string)); } } "; var compilation = CreateCompilation(new[] { Tuple2NonNullable, TupleRestNonNullable, source }, targetFramework: TargetFramework.Mscorlib46, parseOptions: TestOptions.Regular7_3, skipUsesIsNullable: true); compilation.VerifyDiagnostics( // (3,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(3, 2), // (4,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(4, 2), // (4,2): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // #nullable enable Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(4, 2), // (6,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T1 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(6, 20), // (7,16): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // (string?, string) t1; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(7, 16), // (7,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T1 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(7, 20), // (7,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T2 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(7, 20), // (8,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T2 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(8, 20), // (8,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T3 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(8, 20), // (8,33): error CS8370: Feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // Type t2 = typeof((string?, string)); Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "?").WithArguments("nullable reference types", "8.0").WithLocation(8, 33), // (9,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T4 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(9, 20), // (10,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T5 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(10, 20), // (11,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T6 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(11, 20), // (12,20): error CS8370: Feature 'notnull generic type constraint' is not available in C# 7.3. Please use language version 8.0 or greater. // where T7 : notnull Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "notnull").WithArguments("notnull generic type constraint", "8.0").WithLocation(12, 20)); } [Fact] public void Constraints_80() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>()", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } var source2 = @" #nullable disable public interface I1 { void F1<TF1, TF2>() where TF2 : class; } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator2, symbolValidator: symbolValidator2); void symbolValidator2(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1, TF2>() where TF2 : class", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); foreach (TypeParameterSymbol tf1 in f1.TypeParameters) { Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } } [Fact] public void Constraints_81() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : new(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : new()", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_82() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : class; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : class", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_83() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : struct; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : struct", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_84() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : unmanaged; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : unmanaged", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_85() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : I1; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : I1", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_86() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : class?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (5,37): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void F1<TF1>() where TF1 : class?; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 37) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetMember("I1"); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : class?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_87() { var source1 = @" #nullable disable public interface I1 { void F1<TF1>() where TF1 : I1?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (5,34): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // void F1<TF1>() where TF1 : I1?; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 34) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : I1?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_88() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetMember("I1"); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>()", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } var source2 = @" #nullable enable public interface I1 { void F1<TF1, TF2>() where TF1 : class?; } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator2, symbolValidator: symbolValidator2); void symbolValidator2(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetMember("I1"); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1, TF2>() where TF1 : class?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); foreach (TypeParameterSymbol tf1 in f1.TypeParameters) { Assert.False(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } } [Fact] public void Constraints_89() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : new(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetMember("I1"); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : new()", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_90() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : class; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetMember("I1"); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", i1.GetAttributes().Single().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : class!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_91() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : struct; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : struct", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_92() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : unmanaged; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : unmanaged", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_93() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : I1; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : I1!", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_94() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : class?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetMember("I1"); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : class?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_95() { var source1 = @" #nullable enable public interface I1 { void F1<TF1>() where TF1 : I1?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("I1.F1"); Assert.Equal("void I1.F1<TF1>() where TF1 : I1?", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = f1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_96() { var source1 = @" #nullable disable public interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } var source2 = @" #nullable disable public interface I1<TF1, TF2> where TF2 : class { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator2, symbolValidator: symbolValidator2); void symbolValidator2(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1, TF2> where TF2 : class", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); foreach (TypeParameterSymbol tf1 in i1.TypeParameters) { Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } } [Fact] public void Constraints_97() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : new() { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : new()", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_98() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : class { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : class", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_99() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : struct { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : struct", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_100() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : unmanaged { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : unmanaged", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_101() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_102() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : class? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (3,43): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public interface I1<TF1> where TF1 : class? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 43) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : class?", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_103() { var source1 = @" #nullable disable public interface I1<TF1> where TF1 : I1<TF1>? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (3,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public interface I1<TF1> where TF1 : I1<TF1>? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 45) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : I1<TF1>?", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.Empty(tf1.GetAttributes()); } } [Fact] public void Constraints_104() { var source1 = @" #nullable enable public interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } var source2 = @" #nullable enable public interface I1<TF1, TF2> where TF1 : class? { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator2, symbolValidator: symbolValidator2); void symbolValidator2(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1, TF2> where TF1 : class?", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } foreach (TypeParameterSymbol tf1 in i1.TypeParameters) { Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } } [Fact] public void Constraints_105() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : new() { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : new()", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_106() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : class { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : class!", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_107() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : struct { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : struct", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_108() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : unmanaged { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : unmanaged", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_109() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : I1<TF1>!", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_110() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : class? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : class?", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_111() { var source1 = @" #nullable enable public interface I1<TF1> where TF1 : I1<TF1>? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1> where TF1 : I1<TF1>?", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_112() { var source1 = @" #nullable disable #nullable enable warnings partial interface I1<TF1> { } partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.Null(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_113() { var source1 = @" #nullable enable partial interface I1<TF1> { } partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_114() { var source1 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> { } #nullable enable partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_115() { var source1 = @" #nullable enable partial interface I1<TF1> { } #nullable disable #nullable enable warnings partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator1, symbolValidator: symbolValidator1); void symbolValidator1(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var i1 = m.GlobalNamespace.GetTypeMember("I1"); Assert.Equal("I1<TF1>", i1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); if (isSource) { Assert.Empty(i1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(2)", i1.GetAttributes().Single().ToString()); } TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var attributes = tf1.GetAttributes(); Assert.Empty(attributes); } } [Fact] public void Constraints_116() { var source1 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> { } partial interface I1<TF1> where TF1 : notnull { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.HasNotNullConstraint); Assert.True(tf1.IsNotNullable); var source2 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : new() { } partial interface I1<TF1> where TF1 : notnull, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,19): error CS0265: Partial declarations of 'I1<TF1>' have inconsistent constraints for type parameter 'TF1' // partial interface I1<TF1> where TF1 : new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<TF1>", "TF1").WithLocation(3, 19) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.HasNotNullConstraint); Assert.Null(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : notnull, new() { } partial interface I1<TF1> where TF1 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (3,19): error CS0265: Partial declarations of 'I1<TF1>' have inconsistent constraints for type parameter 'TF1' // partial interface I1<TF1> where TF1 : notnull, new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<TF1>", "TF1").WithLocation(3, 19) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.True(tf1.HasNotNullConstraint); Assert.True(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); } [Fact] public void Constraints_117() { var source1 = @" #nullable enable partial interface I1<TF1> { } partial interface I1<TF1> where TF1 : notnull { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.HasNotNullConstraint); Assert.True(tf1.IsNotNullable); var source2 = @" #nullable enable partial interface I1<TF1> where TF1 : new() { } partial interface I1<TF1> where TF1 : notnull, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,19): error CS0265: Partial declarations of 'I1<TF1>' have inconsistent constraints for type parameter 'TF1' // partial interface I1<TF1> where TF1 : new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<TF1>", "TF1").WithLocation(3, 19) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.HasNotNullConstraint); Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); } [Fact] public void Constraints_118() { var source1 = @" #nullable disable #nullable enable warnings partial interface I1<TF1> { } #nullable enable partial interface I1<TF1> where TF1 : notnull { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var source2 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : new() { } #nullable enable partial interface I1<TF1> where TF1 : notnull, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,19): error CS0265: Partial declarations of 'I1<TF1>' have inconsistent constraints for type parameter 'TF1' // partial interface I1<TF1> where TF1 : new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<TF1>", "TF1").WithLocation(3, 19) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.HasNotNullConstraint); Assert.Null(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @" #nullable enable partial interface I1<TF1> where TF1 : notnull, new() { } #nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (3,19): error CS0265: Partial declarations of 'I1<TF1>' have inconsistent constraints for type parameter 'TF1' // partial interface I1<TF1> where TF1 : notnull, new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<TF1>", "TF1").WithLocation(3, 19) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.True(tf1.HasNotNullConstraint); Assert.True(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); } [Fact] public void Constraints_119() { var source1 = @" #nullable enable partial interface I1<TF1> { } #nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : notnull { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.True(tf1.IsNotNullable); var source2 = @" #nullable enable partial interface I1<TF1> where TF1 : new() { } #nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : notnull, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,19): error CS0265: Partial declarations of 'I1<TF1>' have inconsistent constraints for type parameter 'TF1' // partial interface I1<TF1> where TF1 : new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<TF1>", "TF1").WithLocation(3, 19) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); } [Fact] public void Constraints_120() { var source1 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> { } partial interface I1<TF1> where TF1 : object? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (7,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 39), // (7,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 45) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : new() { } partial interface I1<TF1> where TF1 : object?, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (7,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 39), // (7,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 45) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @"#nullable disable #nullable enable warnings partial interface I1<TF1, TF2> where TF2 : new() { } partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (7,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 44), // (7,50): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 50) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.Null(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] public void Constraints_121() { var source1 = @" #nullable enable partial interface I1<TF1> { } partial interface I1<TF1> where TF1 : object? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (7,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 39) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @" #nullable enable partial interface I1<TF1> where TF1 : new() { } partial interface I1<TF1> where TF1 : object?, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (7,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 39) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @" #nullable enable partial interface I1<TF1, TF2> where TF2 : new() { } partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (7,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 44) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.False(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_122() { var source1 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> { } #nullable enable partial interface I1<TF1> where TF1 : object? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (8,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 39) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : new() { } #nullable enable partial interface I1<TF1> where TF1 : object?, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (8,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 39) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @"#nullable disable #nullable enable warnings partial interface I1<TF1, TF2> where TF2 : new() { } #nullable enable partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (8,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 44) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.False(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_123() { var source1 = @" #nullable enable partial interface I1<TF1> { } #nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : object? { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (8,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 39), // (8,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 45) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @" #nullable enable partial interface I1<TF1> where TF1 : new() { } #nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : object?, new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (8,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 39), // (8,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 45) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @" #nullable enable partial interface I1<TF1, TF2> where TF2 : new() { } #nullable disable #nullable enable warnings partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (8,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 44), // (8,50): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 50) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.False(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] public void Constraints_124() { var source1 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : object? { } partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39), // (3,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 45) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : object?, new() { } partial interface I1<TF1> where TF1 : new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39), // (3,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 45) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @"#nullable disable #nullable enable warnings partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } partial interface I1<TF1, TF2> where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (3,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 44), // (3,50): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 50) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.Null(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] public void Constraints_125() { var source1 = @" #nullable enable partial interface I1<TF1> where TF1 : object? { } partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @" #nullable enable partial interface I1<TF1> where TF1 : object?, new() { } partial interface I1<TF1> where TF1 : new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @" #nullable enable partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } partial interface I1<TF1, TF2> where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (3,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 44) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.False(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_126() { var source1 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : object? { } #nullable enable partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39), // (3,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 45) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @"#nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : object?, new() { } #nullable enable partial interface I1<TF1> where TF1 : new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39), // (3,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 45) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @"#nullable disable #nullable enable warnings partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } #nullable enable partial interface I1<TF1, TF2> where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (3,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 44), // (3,50): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 50) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.False(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_127() { var source1 = @" #nullable enable partial interface I1<TF1> where TF1 : object? { } #nullable disable #nullable enable warnings partial interface I1<TF1> { } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39) ); var i1 = comp1.GlobalNamespace.GetTypeMember("I1"); TypeParameterSymbol tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); var source2 = @" #nullable enable partial interface I1<TF1> where TF1 : object?, new() { } #nullable disable #nullable enable warnings partial interface I1<TF1> where TF1 : new() { } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics( // (3,39): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1> where TF1 : object?, new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 39) ); i1 = comp2.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); Assert.True(tf1.HasConstructorConstraint); var source3 = @" #nullable enable partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() { } #nullable disable #nullable enable warnings partial interface I1<TF1, TF2> where TF2 : new() { } "; var comp3 = CreateCompilation(source3); comp3.VerifyDiagnostics( // (3,44): error CS0702: Constraint cannot be special class 'object' // partial interface I1<TF1, TF2> where TF1 : object? where TF2 : new() Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(3, 44) ); i1 = comp3.GlobalNamespace.GetTypeMember("I1"); tf1 = i1.TypeParameters[0]; Assert.False(tf1.IsNotNullable); TypeParameterSymbol tf2 = i1.TypeParameters[1]; Assert.False(tf2.IsNotNullable); Assert.True(tf2.HasConstructorConstraint); } [Fact] public void Constraints_128() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>(); partial void M1<TF1>() { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); } [Fact] public void Constraints_129() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>(); partial void M1<TF1>() { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_130() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>(); #nullable enable partial void M1<TF1>() { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.Null(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); var source2 = @" partial class A { #nullable enable partial void M1<TF1>() { } #nullable disable #nullable enable warnings partial void M1<TF1>(); } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); m1 = comp2.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.Null(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_131() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>(); #nullable disable #nullable enable warnings partial void M1<TF1>() { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.Null(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); var source2 = @"#nullable disable partial class A { #nullable enable warnings partial void M1<TF1>() { } #nullable enable partial void M1<TF1>(); } "; var comp2 = CreateCompilation(source2); comp2.VerifyDiagnostics(); m1 = comp2.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.Null(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] public void Constraints_132() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>(); partial void M1<TF1>() where TF1 : notnull { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_133() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>(); partial void M1<TF1>() where TF1 : notnull { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (7,14): warning CS8667: Partial method declarations of 'A.M1<TF1>()' have inconsistent nullability in constraints for type parameter 'TF1' // partial void M1<TF1>() where TF1 : notnull Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, "M1").WithArguments("A.M1<TF1>()", "TF1").WithLocation(7, 14) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.True(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_134() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>(); #nullable enable partial void M1<TF1>() where TF1 : notnull { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.Null(m1.TypeParameters[0].IsNotNullable); Assert.True(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_135() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>(); #nullable disable #nullable enable warnings partial void M1<TF1>() where TF1 : notnull { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (8,14): warning CS8667: Partial method declarations of 'A.M1<TF1>()' have inconsistent nullability in constraints for type parameter 'TF1' // partial void M1<TF1>() where TF1 : notnull Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, "M1").WithArguments("A.M1<TF1>()", "TF1").WithLocation(8, 14) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.True(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_136() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>(); partial void M1<TF1>() where TF1 : object? { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (7,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 36), // (7,42): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial void M1<TF1>() where TF1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 42) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.Null(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_137() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>(); partial void M1<TF1>() where TF1 : object? { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (7,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(7, 36) ); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_138() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>(); #nullable enable partial void M1<TF1>() where TF1 : object? { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (8,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 36) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.Null(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] public void Constraints_139() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>(); #nullable disable #nullable enable warnings partial void M1<TF1>() where TF1 : object? { } } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (8,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(8, 36), // (8,42): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial void M1<TF1>() where TF1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 42) ); } [Fact] public void Constraints_140() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>() { } partial void M1<TF1>(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); } [Fact] public void Constraints_141() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>() { } partial void M1<TF1>(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_142() { var source1 = @"#nullable disable partial class A { #nullable enable warnings partial void M1<TF1>() { } #nullable enable partial void M1<TF1>(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.Null(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_143() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>() { } #nullable disable #nullable enable warnings partial void M1<TF1>(); } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.Null(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] public void Constraints_144() { var source1 = @" partial class A { #nullable disable #nullable enable warnings partial void M1<TF1>() { } partial void M1<TF1>() where TF1 : notnull; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_145() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>() { } partial void M1<TF1>() where TF1 : notnull; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (5,14): warning CS8667: Partial method declarations of 'A.M1<TF1>()' have inconsistent nullability in constraints for type parameter 'TF1' // partial void M1<TF1>() Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, "M1").WithArguments("A.M1<TF1>()", "TF1").WithLocation(5, 14) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.True(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_146() { var source1 = @"#nullable disable partial class A { #nullable enable warnings partial void M1<TF1>() { } #nullable enable partial void M1<TF1>() where TF1 : notnull; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics(); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.True(m1.TypeParameters[0].IsNotNullable); Assert.Null(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_147() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>() { } #nullable disable #nullable enable warnings partial void M1<TF1>() where TF1 : notnull; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (5,14): warning CS8667: Partial method declarations of 'A.M1<TF1>()' have inconsistent nullability in constraints for type parameter 'TF1' // partial void M1<TF1>() Diagnostic(ErrorCode.WRN_NullabilityMismatchInConstraintsOnPartialImplementation, "M1").WithArguments("A.M1<TF1>()", "TF1").WithLocation(5, 14) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.True(m1.TypeParameters[0].IsNotNullable); Assert.False(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_148() { var source1 = @"#nullable disable partial class A { #nullable enable warnings partial void M1<TF1>() { } partial void M1<TF1>() where TF1 : object?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (9,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object?; Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(9, 36), // (9,42): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial void M1<TF1>() where TF1 : object?; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 42) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.Null(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] public void Constraints_149() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>() { } partial void M1<TF1>() where TF1 : object?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (9,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object?; Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(9, 36) ); } [Fact] [WorkItem(30229, "https://github.com/dotnet/roslyn/issues/30229")] public void Constraints_150() { var source1 = @"#nullable disable partial class A { #nullable enable warnings partial void M1<TF1>() { } #nullable enable partial void M1<TF1>() where TF1 : object?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (10,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object?; Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(10, 36) ); var m1 = comp1.GlobalNamespace.GetMember<MethodSymbol>("A.M1"); Assert.False(m1.TypeParameters[0].IsNotNullable); Assert.Null(m1.PartialImplementationPart.TypeParameters[0].IsNotNullable); } [Fact] public void Constraints_151() { var source1 = @" partial class A { #nullable enable partial void M1<TF1>() { } #nullable disable #nullable enable warnings partial void M1<TF1>() where TF1 : object?; } "; var comp1 = CreateCompilation(source1); comp1.VerifyDiagnostics( // (10,36): error CS0702: Constraint cannot be special class 'object' // partial void M1<TF1>() where TF1 : object?; Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(10, 36), // (10,42): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // partial void M1<TF1>() where TF1 : object?; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(10, 42) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/34798")] public void Constraints_152() { var source = @" class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } class B : A<int> { public override void F1<T11>(T11? t1) where T11 : class { } public override void F2<T22>(T22 t2) { } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); CompileAndVerify(comp, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>(T11? t1) where T11 : class", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t11.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(1)", t11.GetAttributes().Single().ToString()); } var af1 = bf1.OverriddenMethod; Assert.Equal("void A<System.Int32>.F1<T1>(T1? t1) where T1 : class", af1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t1 = af1.TypeParameters[0]; Assert.False(t1.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t1.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(1)", t1.GetAttributes().Single().ToString()); } var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>(T22 t2) where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t22.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t22.GetAttributes().Single().ToString()); } var af2 = bf2.OverriddenMethod; Assert.Equal("void A<System.Int32>.F2<T2>(T2 t2) where T2 : class?", af2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t2 = af2.TypeParameters[0]; Assert.True(t2.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t2.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", t2.GetAttributes().Single().ToString()); } } } [Fact] public void Constraints_153() { var source1 = @" public class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var source2 = @" class B : A<int> { public override void F1<T11>(T11? t1) where T11 : class { } public override void F2<T22>(T22 t2) { } } "; var comp2 = CreateCompilation(new[] { source2 }, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var b = m.GlobalNamespace.GetMember("B"); if (isSource) { Assert.Empty(b.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", b.GetAttributes().First().ToString()); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>(T11? t1) where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>(T22 t2) where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t22.GetAttributes()); } else { CSharpAttributeData nullableAttribute = t22.GetAttributes().Single(); Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", nullableAttribute.ToString()); Assert.Same(m, nullableAttribute.AttributeClass.ContainingModule); Assert.Equal(Accessibility.Internal, nullableAttribute.AttributeClass.DeclaredAccessibility); } } } [Fact] public void Constraints_154() { var source1 = @" public class A<T> { public virtual void F1<T1>(T1? t1) where T1 : class { } public virtual void F2<T2>(T2 t2) where T2 : class? { } } "; var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable()); var comp2 = CreateCompilation(NullableAttributeDefinition); var source3 = @" class B : A<int> { public override void F1<T11>(T11? t1) where T11 : class { } public override void F2<T22>(T22 t2) { } } "; var comp3 = CreateCompilation(new[] { source3 }, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference(), comp2.EmitToImageReference() }, parseOptions: TestOptions.Regular8); CompileAndVerify(comp3, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { bool isSource = !(m is PEModuleSymbol); var b = m.GlobalNamespace.GetMember("B"); if (isSource) { Assert.Empty(b.GetAttributes()); } else { Assert.Equal("System.Runtime.CompilerServices.NullableContextAttribute(1)", b.GetAttributes().First().ToString()); } var bf1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B.F1<T11>(T11? t1) where T11 : class!", bf1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t11 = bf1.TypeParameters[0]; Assert.False(t11.ReferenceTypeConstraintIsNullable); Assert.Empty(t11.GetAttributes()); var bf2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B.F2<T22>(T22 t2) where T22 : class?", bf2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol t22 = bf2.TypeParameters[0]; Assert.True(t22.ReferenceTypeConstraintIsNullable); if (isSource) { Assert.Empty(t22.GetAttributes()); } else { CSharpAttributeData nullableAttribute = t22.GetAttributes().Single(); Assert.Equal("System.Runtime.CompilerServices.NullableAttribute(2)", nullableAttribute.ToString()); Assert.NotEqual(m, nullableAttribute.AttributeClass.ContainingModule); } } } [Fact] public void DynamicConstraint_01() { var source = @" class B<S> { public static void F1<T1>(T1 t1) where T1 : dynamic { } public static void F2<T2>(T2 t2) where T2 : B<dynamic> { } }"; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (4,49): error CS1967: Constraint cannot be the dynamic type // public static void F1<T1>(T1 t1) where T1 : dynamic Diagnostic(ErrorCode.ERR_DynamicTypeAsBound, "dynamic").WithLocation(4, 49), // (8,49): error CS1968: Constraint cannot be a dynamic type 'B<dynamic>' // public static void F2<T2>(T2 t2) where T2 : B<dynamic> Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "B<dynamic>").WithArguments("B<dynamic>").WithLocation(8, 49) ); var m = comp.SourceModule; var f1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F1"); Assert.Equal("void B<S>.F1<T1>(T1 t1)", f1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); var f2 = (MethodSymbol)m.GlobalNamespace.GetMember("B.F2"); Assert.Equal("void B<S>.F2<T2>(T2 t2)", f2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); } [Fact] [WorkItem(36276, "https://github.com/dotnet/roslyn/issues/36276")] public void DynamicConstraint_02() { var source1 = @" #nullable enable class Test1<T> { public virtual void M1<S>() where S : T { } } class Test2 : Test1<dynamic> { public override void M1<S>() { } void Test() { base.M1<object?>(); this.M1<object?>(); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (18,9): warning CS8631: The type 'object?' cannot be used as type parameter 'S' in the generic type or method 'Test1<dynamic>.M1<S>()'. Nullability of type argument 'object?' doesn't match constraint type 'object'. // base.M1<object?>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "base.M1<object?>").WithArguments("Test1<dynamic>.M1<S>()", "object", "S", "object?").WithLocation(18, 9), // (19,9): warning CS8631: The type 'object?' cannot be used as type parameter 'S' in the generic type or method 'Test2.M1<S>()'. Nullability of type argument 'object?' doesn't match constraint type 'object'. // this.M1<object?>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "this.M1<object?>").WithArguments("Test2.M1<S>()", "object", "S", "object?").WithLocation(19, 9) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>() where S : System.Object!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); var baseM1 = m1.OverriddenMethod; Assert.Equal("void Test1<dynamic!>.M1<S>() where S : System.Object!", baseM1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(baseM1.TypeParameters[0].IsNotNullable); } } [Fact] [WorkItem(36276, "https://github.com/dotnet/roslyn/issues/36276")] public void DynamicConstraint_03() { var source1 = @" #nullable disable class Test1<T> { public virtual void M1<S>() where S : T { } } class Test2 : Test1<dynamic> { public override void M1<S>() { } void Test() { #nullable enable base.M1<object?>(); this.M1<object?>(); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>()", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); var baseM1 = m1.OverriddenMethod; Assert.Equal("void Test1<dynamic>.M1<S>()", baseM1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(baseM1.TypeParameters[0].IsNotNullable); } } [Fact] public void DynamicConstraint_04() { var source1 = @" #nullable enable class Test1<T> { public virtual void M1<S>() where S : T { } } class Test2 : Test1<Test1<dynamic>> { public override void M1<S>() { } void Test() { base.M1<Test1<object?>>(); this.M1<Test1<object?>>(); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (18,9): warning CS8631: The type 'Test1<object?>' cannot be used as type parameter 'S' in the generic type or method 'Test1<Test1<dynamic>>.M1<S>()'. Nullability of type argument 'Test1<object?>' doesn't match constraint type 'Test1<object>'. // base.M1<Test1<object?>>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "base.M1<Test1<object?>>").WithArguments("Test1<Test1<dynamic>>.M1<S>()", "Test1<object>", "S", "Test1<object?>").WithLocation(18, 9), // (19,9): warning CS8631: The type 'Test1<object?>' cannot be used as type parameter 'S' in the generic type or method 'Test2.M1<S>()'. Nullability of type argument 'Test1<object?>' doesn't match constraint type 'Test1<object>'. // this.M1<Test1<object?>>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "this.M1<Test1<object?>>").WithArguments("Test2.M1<S>()", "Test1<object>", "S", "Test1<object?>").WithLocation(19, 9) ); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>() where S : Test1<System.Object!>!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); var baseM1 = m1.OverriddenMethod; Assert.Equal("void Test1<Test1<dynamic!>!>.M1<S>() where S : Test1<System.Object!>!", baseM1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(baseM1.TypeParameters[0].IsNotNullable); } } [Fact] public void DynamicConstraint_05() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : I1?, T {} } public interface I1 {} public class Test2 : Test1<dynamic> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); var baseM1 = m1.OverriddenMethod; Assert.Equal("void Test1<dynamic!>.M1<S>(S x) where S : System.Object!, I1?", baseM1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(baseM1.TypeParameters[0].IsNotNullable); } } [Fact] public void NotNullConstraint_01() { var source1 = @" #nullable enable public class A { void Test(int? a, int? b) { M<int?>(a); M(a); if (b == null) return; b.Value.ToString(); M(b); } void M<T> (T x) where T : notnull { ((object)x).ToString(); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (7,9): warning CS8714: The type 'int?' cannot be used as type parameter 'T' in the generic type or method 'A.M<T>(T)'. Nullability of type argument 'int?' doesn't match 'notnull' constraint. // M<int?>(a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M<int?>").WithArguments("A.M<T>(T)", "T", "int?").WithLocation(7, 9), // (8,9): warning CS8714: The type 'int?' cannot be used as type parameter 'T' in the generic type or method 'A.M<T>(T)'. Nullability of type argument 'int?' doesn't match 'notnull' constraint. // M(a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M").WithArguments("A.M<T>(T)", "T", "int?").WithLocation(8, 9), // (11,9): warning CS8714: The type 'int?' cannot be used as type parameter 'T' in the generic type or method 'A.M<T>(T)'. Nullability of type argument 'int?' doesn't match 'notnull' constraint. // M(b); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M").WithArguments("A.M<T>(T)", "T", "int?").WithLocation(11, 9) ); } [Fact] public void NotNullConstraint_02() { var source1 = @" #nullable enable public class A<T> where T : notnull { public void M<S> (S x) where S : T { ((object)x).ToString(); } } public class B : A<System.ValueType> { void Test(int? a, int? b) { M<int?>(a); M(a); if (b == null) return; b.Value.ToString(); M(b); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (15,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'A<ValueType>.M<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M<int?>(a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M<int?>").WithArguments("A<System.ValueType>.M<S>(S)", "System.ValueType", "S", "int?").WithLocation(15, 9), // (16,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'A<ValueType>.M<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M(a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M").WithArguments("A<System.ValueType>.M<S>(S)", "System.ValueType", "S", "int?").WithLocation(16, 9), // (19,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'A<ValueType>.M<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M(b); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M").WithArguments("A<System.ValueType>.M<S>(S)", "System.ValueType", "S", "int?").WithLocation(19, 9) ); } [Fact] public void NotNullConstraint_03() { var source1 = @" #nullable enable public class A<T> { public void M<S> (S x) where S : T { ((object)x).ToString(); } } public class B : A<System.ValueType> { void Test(int? a, int? b) { M<int?>(a); M(a); if (b == null) return; b.Value.ToString(); M(b); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (7,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((object)x).ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)x").WithLocation(7, 10), // (7,10): warning CS8602: Dereference of a possibly null reference. // ((object)x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object)x").WithLocation(7, 10), // (15,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'A<ValueType>.M<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M<int?>(a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M<int?>").WithArguments("A<System.ValueType>.M<S>(S)", "System.ValueType", "S", "int?").WithLocation(15, 9), // (16,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'A<ValueType>.M<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M(a); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M").WithArguments("A<System.ValueType>.M<S>(S)", "System.ValueType", "S", "int?").WithLocation(16, 9), // (19,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'A<ValueType>.M<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M(b); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M").WithArguments("A<System.ValueType>.M<S>(S)", "System.ValueType", "S", "int?").WithLocation(19, 9) ); } [Fact] public void NotNullConstraint_04() { var source1 = @" #nullable enable public class A<T> { public void M<S> (S x) where S : T { ((object)x).ToString(); } } public class B : A<System.ValueType?> { void Test(int? a, int? b) { M<int?>(a); M(a); if (b == null) return; b.Value.ToString(); M(b); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (7,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((object)x).ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)x").WithLocation(7, 10), // (7,10): warning CS8602: Dereference of a possibly null reference. // ((object)x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object)x").WithLocation(7, 10) ); } [Fact] public void NotNullConstraint_05() { var source1 = @" #nullable enable public class A<T> where T : notnull { public void M<S> (S x) where S : T { ((object)x).ToString(); } } public class B : A<System.ValueType?> { void Test(int? a, int? b) { M<int?>(a); M(a); if (b == null) return; b.Value.ToString(); M(b); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (11,14): warning CS8714: The type 'System.ValueType?' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. Nullability of type argument 'System.ValueType?' doesn't match 'notnull' constraint. // public class B : A<System.ValueType?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "B").WithArguments("A<T>", "T", "System.ValueType?").WithLocation(11, 14) ); } [Fact] public void NotNullConstraint_06() { var source1 = @" #nullable enable public class A<T> where T : notnull { public void M<S>(S? x, S y, S? z) where S : class, T { M<S?>(x); M(x); if (z == null) return; M(z); } public void M<S>(S x) where S : T { ((object)x).ToString(); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (7,9): warning CS8631: The type 'S?' cannot be used as type parameter 'S' in the generic type or method 'A<T>.M<S>(S)'. Nullability of type argument 'S?' doesn't match constraint type 'T'. // M<S?>(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M<S?>").WithArguments("A<T>.M<S>(S)", "T", "S", "S?").WithLocation(7, 9), // (8,9): warning CS8631: The type 'S?' cannot be used as type parameter 'S' in the generic type or method 'A<T>.M<S>(S)'. Nullability of type argument 'S?' doesn't match constraint type 'T'. // M(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M").WithArguments("A<T>.M<S>(S)", "T", "S", "S?").WithLocation(8, 9) ); } [Fact] [WorkItem(36005, "https://github.com/dotnet/roslyn/issues/36005")] public void NotNullConstraint_07() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : T { } public virtual void M2(T x) { } } public class Test2 : Test1<System.ValueType> { public override void M1<S>(S x) { object y = x; y.ToString(); } public override void M2(System.ValueType x) { } public void Test() { int? x = null; M1<int?>(x); // 1 M2(x); // 2 } } public class Test3 : Test1<object> { public override void M1<S>(S x) { object y = x; y.ToString(); } public override void M2(object x) { } public void Test() { int? x = null; M1<int?>(x); // 3 M2(x); // 4 } } public class Test4 : Test1<int?> { public override void M1<S>(S x) { object y = x; // 5 y.ToString(); // 6 } public override void M2(int? x) { } public void Test() { int? x = null; M1<int?>(x); M2(x); } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (26,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'Test2.M1<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M1<int?>(x); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<int?>").WithArguments("Test2.M1<S>(S)", "System.ValueType", "S", "int?").WithLocation(26, 9), // (27,12): warning CS8604: Possible null reference argument for parameter 'x' in 'void Test2.M2(ValueType x)'. // M2(x); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "void Test2.M2(ValueType x)").WithLocation(27, 12), // (46,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'Test3.M1<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'object'. // M1<int?>(x); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<int?>").WithArguments("Test3.M1<S>(S)", "object", "S", "int?").WithLocation(46, 9), // (47,12): warning CS8604: Possible null reference argument for parameter 'x' in 'void Test3.M2(object x)'. // M2(x); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "void Test3.M2(object x)").WithLocation(47, 12), // (55,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = x; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(55, 20), // (56,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(56, 9) ); var source2 = @" #nullable enable public class Test22 : Test2 { public override void M1<S>(S x) { object y = x; y.ToString(); } public new void Test() { int? x = null; M1<int?>(x); // 1 M2(x); // 2 } } public class Test33 : Test3 { public override void M1<S>(S x) { object y = x; y.ToString(); } public new void Test() { int? x = null; M1<int?>(x); // 3 M2(x); // 4 } } public class Test44 : Test4 { public override void M1<S>(S x) { object y = x; // 5 y.ToString(); // 6 } public new void Test() { int? x = null; M1<int?>(x); M2(x); } } "; var comp2 = CreateCompilation(new[] { source2 }, references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics( // (14,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'Test22.M1<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'System.ValueType'. // M1<int?>(x); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<int?>").WithArguments("Test22.M1<S>(S)", "System.ValueType", "S", "int?").WithLocation(14, 9), // (15,12): warning CS8604: Possible null reference argument for parameter 'x' in 'void Test2.M2(ValueType x)'. // M2(x); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "void Test2.M2(ValueType x)").WithLocation(15, 12), // (29,9): warning CS8631: The type 'int?' cannot be used as type parameter 'S' in the generic type or method 'Test33.M1<S>(S)'. Nullability of type argument 'int?' doesn't match constraint type 'object'. // M1<int?>(x); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<int?>").WithArguments("Test33.M1<S>(S)", "object", "S", "int?").WithLocation(29, 9), // (30,12): warning CS8604: Possible null reference argument for parameter 'x' in 'void Test3.M2(object x)'. // M2(x); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "void Test3.M2(object x)").WithLocation(30, 12), // (38,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = x; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(38, 20), // (39,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(39, 9) ); } [Fact] public void NotNullConstraint_08() { var source1 = @" #nullable enable public class A { void M<T> (T x) where T : notnull? { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (5,31): error CS0246: The type or namespace name 'notnull' could not be found (are you missing a using directive or an assembly reference?) // void M<T> (T x) where T : notnull? Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "notnull").WithArguments("notnull").WithLocation(5, 31), // (5,31): error CS0701: 'notnull?' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void M<T> (T x) where T : notnull? Diagnostic(ErrorCode.ERR_BadBoundType, "notnull?").WithArguments("notnull?").WithLocation(5, 31) ); } [Fact] public void NotNullConstraint_09() { var source1 = @" #nullable enable public class A { void M<T>() where T : notnull { } void Test() { M<notnull>(); M<object>(); M<notnull?>(); } } class notnull {} "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (12,9): error CS0311: The type 'object' cannot be used as type parameter 'T' in the generic type or method 'A.M<T>()'. There is no implicit reference conversion from 'object' to 'notnull'. // M<object>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M<object>").WithArguments("A.M<T>()", "notnull", "T", "object").WithLocation(12, 9), // (13,9): warning CS8631: The type 'notnull?' cannot be used as type parameter 'T' in the generic type or method 'A.M<T>()'. Nullability of type argument 'notnull?' doesn't match constraint type 'notnull'. // M<notnull?>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M<notnull?>").WithArguments("A.M<T>()", "notnull", "T", "notnull?").WithLocation(13, 9) ); } [Fact] public void NotNullConstraint_10() { var source1 = @" #nullable enable public class A { void M<T>() where T : notnull? { } void Test() { M<notnull>(); M<object>(); M<notnull?>(); } } class notnull {} "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (12,9): error CS0311: The type 'object' cannot be used as type parameter 'T' in the generic type or method 'A.M<T>()'. There is no implicit reference conversion from 'object' to 'notnull'. // M<object>(); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M<object>").WithArguments("A.M<T>()", "notnull", "T", "object").WithLocation(12, 9) ); } [Fact] public void NotNullConstraint_11() { var source1 = @" #nullable enable public class A { void M<notnull>() where notnull : notnull { } void Test() { M<notnull>(); M<object>(); M<notnull?>(); } } class notnull {} "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (5,12): error CS0454: Circular constraint dependency involving 'notnull' and 'notnull' // void M<notnull>() where notnull : notnull Diagnostic(ErrorCode.ERR_CircularConstraint, "notnull").WithArguments("notnull", "notnull").WithLocation(5, 12) ); } [Fact] public void NotNullConstraint_12() { var source1 = @" #nullable enable public class A { void M<notnull>() where notnull : notnull? { } void Test() { M<notnull>(); M<object>(); M<notnull?>(); } } class notnull {} "; var comp1 = CreateCompilation(new[] { source1 }, parseOptions: TestOptions.Regular8); comp1.VerifyDiagnostics( // (5,12): error CS0454: Circular constraint dependency involving 'notnull' and 'notnull' // void M<notnull>() where notnull : notnull? Diagnostic(ErrorCode.ERR_CircularConstraint, "notnull").WithArguments("notnull", "notnull").WithLocation(5, 12), // (5,39): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void M<notnull>() where notnull : notnull? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "notnull?").WithArguments("9.0").WithLocation(5, 39) ); } [Fact] public void NotNullConstraint_13() { var source1 = @" #nullable enable public class A { void M<notnull>() where notnull : notnull { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics( // (5,12): error CS0454: Circular constraint dependency involving 'notnull' and 'notnull' // void M<notnull>() where notnull : notnull Diagnostic(ErrorCode.ERR_CircularConstraint, "notnull").WithArguments("notnull", "notnull").WithLocation(5, 12) ); } [Fact] public void NotNullConstraint_14() { var source1 = @" #nullable enable public class A { void M<notnull>() where notnull : notnull? { } } "; var comp1 = CreateCompilation(new[] { source1 }, parseOptions: TestOptions.Regular8); comp1.VerifyDiagnostics( // (5,12): error CS0454: Circular constraint dependency involving 'notnull' and 'notnull' // void M<notnull>() where notnull : notnull? Diagnostic(ErrorCode.ERR_CircularConstraint, "notnull").WithArguments("notnull", "notnull").WithLocation(5, 12), // (5,39): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void M<notnull>() where notnull : notnull? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "notnull?").WithArguments("9.0").WithLocation(5, 39) ); } [Fact] [WorkItem(46410, "https://github.com/dotnet/roslyn/issues/46410")] public void NotNullConstraint_15() { var source = @"#nullable enable abstract class A<T, U> where T : notnull { internal static void M<V>(V v) where V : T { } internal abstract void F<V>(V v) where V : U; } class B : A<System.ValueType, int?> { internal override void F<T>(T t) { M<T>(t); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8631: The type 'T' cannot be used as type parameter 'V' in the generic type or method 'A<ValueType, int?>.M<V>(V)'. Nullability of type argument 'T' doesn't match constraint type 'System.ValueType'. // M<T>(t); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M<T>").WithArguments("A<System.ValueType, int?>.M<V>(V)", "System.ValueType", "V", "T").WithLocation(11, 9)); } [Fact] public void ObjectConstraint_01() { var source = @" class B { public static void F1<T1>() where T1 : object { } public static void F2<T2>() where T2 : System.Object { } }"; foreach (var options in new[] { WithNullableEnable(), WithNullableDisable() }) { var comp1 = CreateCompilation(new[] { source }, options: options); comp1.VerifyDiagnostics( // (4,44): error CS0702: Constraint cannot be special class 'object' // public static void F1<T1>() where T1 : object Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object").WithArguments("object").WithLocation(4, 44), // (8,44): error CS0702: Constraint cannot be special class 'object' // public static void F2<T2>() where T2 : System.Object Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "System.Object").WithArguments("object").WithLocation(8, 44) ); } } [Fact] public void ObjectConstraint_02() { var source = @" class B { public static void F1<T1>() where T1 : object? { } public static void F2<T2>() where T2 : System.Object? { } }"; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (4,44): error CS0702: Constraint cannot be special class 'object' // public static void F1<T1>() where T1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(4, 44), // (8,44): error CS0702: Constraint cannot be special class 'object' // public static void F2<T2>() where T2 : System.Object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "System.Object?").WithArguments("object").WithLocation(8, 44) ); var comp2 = CreateCompilation(new[] { source }, options: WithNullableDisable()); comp2.VerifyDiagnostics( // (4,44): error CS0702: Constraint cannot be special class 'object' // public static void F1<T1>() where T1 : object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "object?").WithArguments("object").WithLocation(4, 44), // (4,50): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static void F1<T1>() where T1 : object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 50), // (8,44): error CS0702: Constraint cannot be special class 'object' // public static void F2<T2>() where T2 : System.Object? Diagnostic(ErrorCode.ERR_SpecialTypeAsBound, "System.Object?").WithArguments("object").WithLocation(8, 44), // (8,57): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public static void F2<T2>() where T2 : System.Object? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 57) ); } [Fact] public void ObjectConstraint_03() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : T {} } public class Test2 : Test1<object> { } public class Test3 : Test1<object> { public override void M1<S>(S x) { } } public class Test4 : Test1<object?> { } public class Test5 : Test1<object?> { public override void M1<S>(S x) { } } #nullable disable public class Test6 : Test1<object> { } public class Test7 : Test1<object> { #nullable enable public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); var source2 = @" #nullable enable public class Test21 : Test2 { public void Test() { M1<object?>(new object()); // 1 } } public class Test22 : Test2 { public override void M1<S>(S x) { x.ToString(); x = default; } public void Test() { M1<object?>(new object()); // 2 } } public class Test31 : Test3 { public void Test() { M1<object?>(new object()); // 3 } } public class Test32 : Test3 { public override void M1<S>(S x) { x.ToString(); x = default; } public void Test() { M1<object?>(new object()); // 4 } } public class Test41 : Test4 { public void Test() { M1<object?>(new object()); } } public class Test42 : Test4 { public override void M1<S>(S x) { x.ToString(); // 5 x = default; } public void Test() { M1<object?>(new object()); } } public class Test51 : Test5 { public void Test() { M1<object?>(new object()); } } public class Test52 : Test5 { public override void M1<S>(S x) { x.ToString(); // 6 x = default; } public void Test() { M1<object?>(new object()); } } public class Test61 : Test6 { public void Test() { M1<object?>(new object()); } } public class Test62 : Test6 { public override void M1<S>(S x) { x.ToString(); x = default; } public void Test() { M1<object?>(new object()); } } public class Test71 : Test7 { public void Test() { M1<object?>(new object()); } } public class Test72 : Test7 { public override void M1<S>(S x) { x.ToString(); x = default; } public void Test() { M1<object?>(new object()); } } "; foreach (var reference in new[] { comp1.ToMetadataReference(), comp1.EmitToImageReference() }) { var comp2 = CreateCompilation(new[] { source2 }, references: new[] { reference }, parseOptions: TestOptions.Regular8); comp2.VerifyDiagnostics( // (7,9): warning CS8631: The type 'object?' cannot be used as type parameter 'S' in the generic type or method 'Test1<object>.M1<S>(S)'. Nullability of type argument 'object?' doesn't match constraint type 'object'. // M1<object?>(new object()); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<object?>").WithArguments("Test1<object>.M1<S>(S)", "object", "S", "object?").WithLocation(7, 9), // (21,9): warning CS8631: The type 'object?' cannot be used as type parameter 'S' in the generic type or method 'Test22.M1<S>(S)'. Nullability of type argument 'object?' doesn't match constraint type 'object'. // M1<object?>(new object()); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<object?>").WithArguments("Test22.M1<S>(S)", "object", "S", "object?").WithLocation(21, 9), // (29,9): warning CS8631: The type 'object?' cannot be used as type parameter 'S' in the generic type or method 'Test3.M1<S>(S)'. Nullability of type argument 'object?' doesn't match constraint type 'object'. // M1<object?>(new object()); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<object?>").WithArguments("Test3.M1<S>(S)", "object", "S", "object?").WithLocation(29, 9), // (43,9): warning CS8631: The type 'object?' cannot be used as type parameter 'S' in the generic type or method 'Test32.M1<S>(S)'. Nullability of type argument 'object?' doesn't match constraint type 'object'. // M1<object?>(new object()); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<object?>").WithArguments("Test32.M1<S>(S)", "object", "S", "object?").WithLocation(43, 9), // (59,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(59, 9), // (81,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(81, 9) ); } } [Fact] public void ObjectConstraint_04() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : T {} } public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x)", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_05() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : T {} } #nullable enable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_06() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : T {} } #nullable enable public class Test2 : Test1<object?> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x)", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.False(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_07() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : I1, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_08() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : I1?, T {} } public interface I1 {} #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_09() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : I1, T {} } public interface I1 {} #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_10() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : I1, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_11() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : I1?, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_12() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : I1, T {} } public interface I1 {} #nullable enable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!, I1", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_13() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : class, T {} } public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : class", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_14() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : class?, T {} } #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : class?, System.Object", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_15() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : class, T {} } #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : class!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_16() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : class, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S! x) where S : class!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_17() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : class?, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S! x) where S : class?, System.Object!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_18() { var source1 = @" #nullable disable public class Test1<T> { public virtual void M1<S>(S x) where S : class, T {} } public interface I1 {} #nullable enable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S! x) where S : class, System.Object!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_19() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : notnull, T {} } #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : notnull", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_20() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : notnull, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : notnull", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_21() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : struct, T {} } #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : struct", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_22() { var source1 = @" #nullable enable public class Test1<T> { public virtual void M1<S>(S x) where S : struct, T {} } public interface I1 {} public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : struct", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_23() { var source1 = @" #nullable disable public class Test1<T, U> { public virtual void M1<S>(S x) where S : U, T {} } public class Test2 : Test1<object, int> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Int32", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_24() { var source1 = @" #nullable enable public class Test1<T, U> { public virtual void M1<S>(S x) where S : U, T {} } public class Test2 : Test1<object, int> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Int32", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_25() { var source1 = @" #nullable disable public class Test1<T, U> { public virtual void M1<S>(S x) where S : U, T {} } public class Test2 : Test1<object, int?> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object, System.Int32?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_26() { var source1 = @" #nullable enable public class Test1<T, U> { public virtual void M1<S>(S x) where S : U, T {} } public class Test2 : Test1<object, int?> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!, System.Int32?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_27() { string il = @" .class private auto ansi sealed beforefieldinit Microsoft.CodeAnalysis.EmbeddedAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void Microsoft.CodeAnalysis.EmbeddedAttribute::.ctor() = ( 01 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ret } // end of method EmbeddedAttribute::.ctor } // end of class Microsoft.CodeAnalysis.EmbeddedAttribute .class private auto ansi sealed beforefieldinit System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::.ctor() = ( 01 00 00 00 ) .custom instance void Microsoft.CodeAnalysis.EmbeddedAttribute::.ctor() = ( 01 00 00 00 ) .field public initonly uint8[] NullableFlags .method public hidebysig specialname rtspecialname instance void .ctor(uint8 A_1) cil managed { // Code size 24 (0x18) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ldarg.0 IL_0008: ldc.i4.1 IL_0009: newarr [mscorlib]System.Byte IL_000e: dup IL_000f: ldc.i4.0 IL_0010: ldarg.1 IL_0011: stelem.i1 IL_0012: stfld uint8[] System.Runtime.CompilerServices.NullableAttribute::NullableFlags IL_0017: ret } // end of method NullableAttribute::.ctor .method public hidebysig specialname rtspecialname instance void .ctor(uint8[] A_1) cil managed { // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: ldarg.0 IL_0008: ldarg.1 IL_0009: stfld uint8[] System.Runtime.CompilerServices.NullableAttribute::NullableFlags IL_000e: ret } // end of method NullableAttribute::.ctor } // end of class System.Runtime.CompilerServices.NullableAttribute .class interface public abstract auto ansi I1 { } // end of class I1 .class public auto ansi beforefieldinit Test2 extends class [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void class [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Test2::.ctor .method public hidebysig instance void M1<([mscorlib]System.Object) S>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M1 .method public hidebysig instance void M2<(I1, [mscorlib]System.Object) S>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M2 .method public hidebysig instance void M3<class ([mscorlib]System.Object) S>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M3 .method public hidebysig virtual instance void M4<class ([mscorlib]System.Object) S>(!!S x) cil managed { .param type S .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 02 00 00 ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M4 .method public hidebysig virtual instance void M5<class ([mscorlib]System.Object) S>(!!S x) cil managed { .param type S .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 01 00 00 ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M5 .method public hidebysig virtual instance void M6<([mscorlib]System.Object) S>(!!S x) cil managed { .param type S .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 01 00 00 ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M6 .method public hidebysig instance void M7<S>(!!S x) cil managed { .param type S .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 02 00 00 ) .param [1] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 01 00 00 ) // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M7 .method public hidebysig instance void M8<valuetype .ctor ([mscorlib]System.Object, [mscorlib]System.ValueType) S>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M8 .method public hidebysig virtual instance void M9<([mscorlib]System.Int32, [mscorlib]System.Object) S>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M9 .method public hidebysig virtual instance void M10<(valuetype [mscorlib]System.Nullable`1<int32>, [mscorlib]System.Object) S>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M10 } // end of class Test2 "; var compilation = CreateCompilationWithIL(new[] { "" }, il, options: WithNullableEnable()); var m1 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x)", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); var m2 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M2"); Assert.Equal("void Test2.M2<S>(S x) where S : I1", m2.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m2.TypeParameters[0].IsNotNullable); var m3 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M3"); Assert.Equal("void Test2.M3<S>(S x) where S : class", m3.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m3.TypeParameters[0].IsNotNullable); var m4 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M4"); Assert.Equal("void Test2.M4<S>(S x) where S : class?, System.Object", m4.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m4.TypeParameters[0].IsNotNullable); var m5 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M5"); Assert.Equal("void Test2.M5<S>(S x) where S : class!", m5.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m5.TypeParameters[0].IsNotNullable); var m6 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M6"); Assert.Equal("void Test2.M6<S>(S x) where S : notnull", m6.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m6.TypeParameters[0].IsNotNullable); var m7 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M7"); Assert.Equal("void Test2.M7<S>(S x)", m7.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.False(m7.TypeParameters[0].IsNotNullable); var m8 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M8"); Assert.Equal("void Test2.M8<S>(S x) where S : struct", m8.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m8.TypeParameters[0].IsNotNullable); var m9 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M9"); Assert.Equal("void Test2.M9<S>(S x) where S : System.Int32", m9.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m9.TypeParameters[0].IsNotNullable); var m10 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M10"); Assert.Equal("void Test2.M10<S>(S x) where S : System.Object, System.Int32?", m10.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m10.TypeParameters[0].IsNotNullable); } [Fact] public void ObjectConstraint_28() { string il = @" .class public auto ansi beforefieldinit Test2 extends class [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void class [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Test2::.ctor .method public hidebysig instance void M1<([mscorlib]System.Object, !!S) S,U>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M1 } // end of class Test2 "; var compilation = CreateCompilationWithIL(new[] { "" }, il, options: WithNullableEnable()); var m1 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S, U>(S x) where S : System.Object", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } [Fact] public void ObjectConstraint_29() { string il = @" .class public auto ansi beforefieldinit Test2 extends class [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void class [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method Test2::.ctor .method public hidebysig instance void M1<([mscorlib]System.Object, !!U) S, (!!S) U>(!!S x) cil managed { // Code size 2 (0x2) .maxstack 8 IL_0000: nop IL_0001: ret } // end of method Test2::M1 } // end of class Test2 "; var compilation = CreateCompilationWithIL(new[] { "" }, il, options: WithNullableEnable()); var m1 = (MethodSymbol)compilation.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S, U>(S x) where S : System.Object, U", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } [Fact] public void ObjectConstraint_30() { var source1 = @" #nullable disable public class Test1<T> { #nullable enable public virtual void M1<S>(S x) where S : class?, T {} } #nullable disable public class Test2 : Test1<object> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : class?, System.Object", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_31() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable disable object, #nullable enable object? > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_32() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< object?, #nullable disable object > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_33() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable disable object, #nullable enable object > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_34() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< object, #nullable disable object > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : System.Object!, I1?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_35() { var source1 = @" #nullable disable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : T1, T2 {} } public class Test2<T> : Test1<object, T> { public override void M1<S>(S x) { } } #nullable enable public class Test3 : Test2<Test3?> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var t2m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2<T>.M1<S>(S x) where S : T", t2m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(t2m1.TypeParameters[0].IsNotNullable); var t3m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test3.M1"); Assert.Equal("void Test3.M1<S>(S x) where S : System.Object, Test3?", t3m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(t3m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_36() { var source1 = @" #nullable disable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : T1, T2 {} } public class Test2<T> : Test1<object, T> { public override void M1<S>(S x) { } } "; var source2 = @" #nullable enable public class Test3 : Test2<Test3?> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); var comp2 = CreateCompilation(new[] { source2 }, references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); CompileAndVerify(comp2, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var t3m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test3.M1"); Assert.Equal("void Test3.M1<S>(S x) where S : System.Object, Test3?", t3m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(t3m1.TypeParameters[0].IsNotNullable); } } [Fact] public void ObjectConstraint_37() { var source1 = @" #nullable disable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : T1, T2 {} } public class Test2<T> : Test1<object, T> where T : struct { public override void M1<S>(S x) { } } #nullable enable public class Test3 : Test2<int> { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var t2m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2<T>.M1<S>(S x) where S : T", t2m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(t2m1.TypeParameters[0].IsNotNullable); var t3m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test3.M1"); Assert.Equal("void Test3.M1<S>(S x) where S : System.Int32", t3m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(t3m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_01() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable disable string, #nullable enable string? > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1?, System.String", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_02() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< string?, #nullable disable string > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1?, System.String", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_03() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable disable string, #nullable enable string > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S! x) where S : I1?, System.String!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_04() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< string, #nullable disable string > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1?, System.String!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_05() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable enable string?, string? > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1?, System.String?", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.False(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_06() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable enable string, string > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S! x) where S : I1?, System.String!", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.True(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void DuplicateConstraintsIgnoringTopLevelNullability_07() { var source1 = @" #nullable enable public class Test1<T1, T2> { public virtual void M1<S>(S x) where S : I1?, T1, T2 {} } public interface I1 {} public class Test2 : Test1< #nullable disable string, string > { public override void M1<S>(S x) { } } "; var comp1 = CreateCompilation(new[] { source1 }); comp1.VerifyDiagnostics(); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("Test2.M1"); Assert.Equal("void Test2.M1<S>(S x) where S : I1?, System.String", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); Assert.Null(m1.TypeParameters[0].IsNotNullable); } } [Fact] public void UnconstrainedTypeParameter_Local() { var source = @" #pragma warning disable CS0168 class B { public static void F1<T1>() { T1? x; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,9): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T1? x; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T1?").WithArguments("9.0").WithLocation(7, 9) ); } [Fact] public void ConstraintsChecks_01() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : ID<string> { } public interface IB : IA<ID<string?>> // 1 {} public interface IC : IA<ID<string>?> // 2 {} public interface IE : IA<ID<string>> {} public interface ID<T> {} class B { public void Test1() { IA<ID<string?>> x1; // 3 IA<ID<string>?> y1; // 4 IA<ID<string>> z1; } public void M1<TM1>(TM1 x) where TM1: ID<string> {} public void Test2(ID<string?> a2, ID<string> b2, ID<string>? c2) { M1(a2); // 5 M1(b2); M1(c2); // 6 M1<ID<string?>>(a2); // 7 M1<ID<string?>>(b2); // 8 M1<ID<string>?>(b2); // 9 M1<ID<string>>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8631: The type 'ID<string?>' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'ID<string?>' doesn't match constraint type 'ID<string>'. // public interface IB : IA<ID<string?>> // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "IB").WithArguments("IA<TA>", "ID<string>", "TA", "ID<string?>").WithLocation(8, 18), // (11,18): warning CS8631: The type 'ID<string>?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'ID<string>?' doesn't match constraint type 'ID<string>'. // public interface IC : IA<ID<string>?> // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "IC").WithArguments("IA<TA>", "ID<string>", "TA", "ID<string>?").WithLocation(11, 18), // (24,12): warning CS8631: The type 'ID<string?>' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'ID<string?>' doesn't match constraint type 'ID<string>'. // IA<ID<string?>> x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "ID<string?>").WithArguments("IA<TA>", "ID<string>", "TA", "ID<string?>").WithLocation(24, 12), // (25,12): warning CS8631: The type 'ID<string>?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'ID<string>?' doesn't match constraint type 'ID<string>'. // IA<ID<string>?> y1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "ID<string>?").WithArguments("IA<TA>", "ID<string>", "TA", "ID<string>?").WithLocation(25, 12), // (34,9): warning CS8631: The type 'ID<string?>' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'ID<string?>' doesn't match constraint type 'ID<string>'. // M1(a2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B.M1<TM1>(TM1)", "ID<string>", "TM1", "ID<string?>").WithLocation(34, 9), // (36,9): warning CS8631: The type 'ID<string>?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'ID<string>?' doesn't match constraint type 'ID<string>'. // M1(c2); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B.M1<TM1>(TM1)", "ID<string>", "TM1", "ID<string>?").WithLocation(36, 9), // (37,9): warning CS8631: The type 'ID<string?>' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'ID<string?>' doesn't match constraint type 'ID<string>'. // M1<ID<string?>>(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<ID<string?>>").WithArguments("B.M1<TM1>(TM1)", "ID<string>", "TM1", "ID<string?>").WithLocation(37, 9), // (38,9): warning CS8631: The type 'ID<string?>' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'ID<string?>' doesn't match constraint type 'ID<string>'. // M1<ID<string?>>(b2); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<ID<string?>>").WithArguments("B.M1<TM1>(TM1)", "ID<string>", "TM1", "ID<string?>").WithLocation(38, 9), // (38,25): warning CS8620: Nullability of reference types in argument of type 'ID<string>' doesn't match target type 'ID<string?>' for parameter 'x' in 'void B.M1<ID<string?>>(ID<string?> x)'. // M1<ID<string?>>(b2); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b2").WithArguments("ID<string>", "ID<string?>", "x", "void B.M1<ID<string?>>(ID<string?> x)").WithLocation(38, 25), // (39,9): warning CS8631: The type 'ID<string>?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'ID<string>?' doesn't match constraint type 'ID<string>'. // M1<ID<string>?>(b2); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<ID<string>?>").WithArguments("B.M1<TM1>(TM1)", "ID<string>", "TM1", "ID<string>?").WithLocation(39, 9) ); } [Fact] public void ConstraintsChecks_02() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class { } public interface IB : IA<string?> // 1 {} public interface IC : IA<string> {} class B { public void Test1() { IA<string?> x1; // 2 IA<string> z1; } public void M1<TM1>(TM1 x) where TM1: class {} public void Test2(string? a2, string b2) { M1(a2); // 3 M1(b2); M1<string?>(a2); // 4 M1<string?>(b2); // 5 M1<string>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8634: The type 'string?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // public interface IB : IA<string?> // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "IB").WithArguments("IA<TA>", "TA", "string?").WithLocation(8, 18), // (18,12): warning CS8634: The type 'string?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // IA<string?> x1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("IA<TA>", "TA", "string?").WithLocation(18, 12), // (27,9): warning CS8634: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // M1(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(27, 9), // (29,9): warning CS8634: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // M1<string?>(a2); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<string?>").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(29, 9), // (30,9): warning CS8634: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'class' constraint. // M1<string?>(b2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<string?>").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(30, 9) ); } [Fact] public void ConstraintsChecks_03() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : ID<string>? { } public interface IC : IA<ID<string>?> {} public interface IE : IA<ID<string>> {} public interface ID<T> {} class B { public void Test1() { IA<ID<string>?> y1; IA<ID<string>> z1; } public void M1<TM1>(TM1 x) where TM1: ID<string>? {} public void Test2(ID<string> b2, ID<string>? c2) { M1(b2); M1(c2); M1<ID<string>?>(c2); M1<ID<string>>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( ); } [Fact] public void ConstraintsChecks_04() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class? { } public interface IB : IA<string?> {} public interface IC : IA<string> {} class B { public void Test1() { IA<string?> x1; IA<string> z1; } public void M1<TM1>(TM1 x) where TM1: class? {} public void Test2(string? a2, string b2) { M1(a2); M1(b2); M1<string?>(a2); M1<string>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( ); } [Fact] public void ConstraintsChecks_05() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : ID<string> { } public interface IB<TIB> : IA<TIB> where TIB : ID<string?> // 1 {} public interface IC<TIC> : IA<TIC> where TIC : ID<string>? // 2 {} public interface IE<TIE> : IA<TIE> where TIE : ID<string> {} public interface ID<T> {} class B<TB1, TB2, TB3> where TB1 : ID<string?> where TB2 : ID<string>? where TB3 : ID<string> { public void Test1() { IA<TB1> x1; // 3 IA<TB2> y1; // 4 IA<TB3> z1; } public void M1<TM1>(TM1 x) where TM1: ID<string> {} public void Test2(TB1 a2, TB3 b2, TB2 c2) { M1(a2); // 5 M1(b2); M1(c2); // 6 M1<TB1>(a2); // 7 M1<TB2>(c2); // 8 M1<TB3>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8631: The type 'TIB' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIB' doesn't match constraint type 'ID<string>'. // public interface IB<TIB> : IA<TIB> where TIB : ID<string?> // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "IB").WithArguments("IA<TA>", "ID<string>", "TA", "TIB").WithLocation(8, 18), // (11,18): warning CS8631: The type 'TIC' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIC' doesn't match constraint type 'ID<string>'. // public interface IC<TIC> : IA<TIC> where TIC : ID<string>? // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "IC").WithArguments("IA<TA>", "ID<string>", "TA", "TIC").WithLocation(11, 18), // (24,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // IA<TB1> x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "ID<string>", "TA", "TB1").WithLocation(24, 12), // (25,12): warning CS8631: The type 'TB2' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // IA<TB2> y1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB2").WithArguments("IA<TA>", "ID<string>", "TA", "TB2").WithLocation(25, 12), // (34,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1(a2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(34, 9), // (36,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1(c2); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(36, 9), // (37,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1<TB1>(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(37, 9), // (38,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1<TB2>(c2); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB2>").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(38, 9) ); } [Fact] public void ConstraintsChecks_06() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class { } public interface IB<TIB> : IA<TIB> where TIB : C? // 1 {} public interface IC<TIC> : IA<TIC> where TIC : C {} public class C {} class B<TB1, TB2> where TB1 : C? where TB2 : C { public void Test1() { IA<TB1> x1; // 2 IA<TB2> z1; } public void M1<TM1>(TM1 x) where TM1: class {} public void Test2(TB1 a2, TB2 b2) { M1(a2); // 3 M1(b2); M1<TB1>(a2); // 4 M1<TB2>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8634: The type 'TIB' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIB' doesn't match 'class' constraint. // public interface IB<TIB> : IA<TIB> where TIB : C? // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "IB").WithArguments("IA<TA>", "TA", "TIB").WithLocation(8, 18), // (21,12): warning CS8634: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // IA<TB1> x1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(21, 12), // (30,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(30, 9), // (32,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1<TB1>(a2); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<TB1>").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(32, 9) ); } [Fact] public void ConstraintsChecks_07() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : ID<string>? { } public interface IC<TIC> : IA<TIC> where TIC : ID<string>? {} public interface IE<TIE> : IA<TIE> where TIE : ID<string> {} public interface ID<T> {} class B<TB2, TB3> where TB2 : ID<string>? where TB3 : ID<string> { public void Test1() { IA<TB2> y1; IA<TB3> z1; } public void M1<TM1>(TM1 x) where TM1: ID<string>? {} public void Test2(TB3 b2, TB2 c2) { M1(b2); M1(c2); M1<TB2>(c2); M1<TB3>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics(); } [Fact] public void ConstraintsChecks_08() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class? { } public interface IB<TIB> : IA<TIB> where TIB : C? {} public interface IC<TIC> : IA<TIC> where TIC : C {} public class C {} class B<TB1, TB2> where TB1 : C? where TB2 : C { public void Test1() { IA<TB1> x1; IA<TB2> z1; } public void M1<TM1>(TM1 x) where TM1: class? {} public void Test2(TB1 a2, TB2 b2) { M1(a2); M1(b2); M1<TB1>(a2); M1<TB2>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics(); } [Fact] public void ConstraintsChecks_09() { var source = @" #pragma warning disable CS0168 #nullable disable public interface IA<TA> where TA : ID<string> { } #nullable enable public interface IC : IA<ID<string>?> {} public interface IE : IA<ID<string>> {} public interface ID<T> {} class B { public void Test1() { IA<ID<string>?> y1; IA<ID<string>> z1; } #nullable disable public void M1<TM1>(TM1 x) where TM1: ID<string> {} #nullable enable public void Test2(ID<string> b2, ID<string>? c2) { M1(b2); M1(c2); M1<ID<string>?>(c2); M1<ID<string>>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( ); } [Fact] public void ConstraintsChecks_10() { var source = @" #pragma warning disable CS0168 #nullable disable public interface IA<TA> where TA : class { } #nullable enable public interface IB : IA<string?> {} public interface IC : IA<string> {} class B { public void Test1() { IA<string?> x1; IA<string> z1; } #nullable disable public void M1<TM1>(TM1 x) where TM1: class {} #nullable enable public void Test2(string? a2, string b2) { M1(a2); M1(b2); M1<string?>(a2); M1<string?>(b2); M1<string>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); CompileAndVerify(comp1, sourceSymbolValidator: symbolValidator, symbolValidator: symbolValidator); void symbolValidator(ModuleSymbol m) { var m1 = (MethodSymbol)m.GlobalNamespace.GetMember("B.M1"); Assert.Equal("void B.M1<TM1>(TM1 x) where TM1 : class", m1.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); TypeParameterSymbol tm1 = m1.TypeParameters[0]; Assert.Null(tm1.ReferenceTypeConstraintIsNullable); Assert.Empty(tm1.GetAttributes()); } } [Fact] public void ConstraintsChecks_11() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : ID<string> { } #nullable disable public interface IB<TIB> : IA<TIB> where TIB : ID<string?> // 1 {} #nullable disable public interface IC<TIC> : IA<TIC> where TIC : ID<string>? // 2 {} #nullable disable public interface IE<TIE> : IA<TIE> where TIE : ID<string> // 3 {} #nullable enable public interface ID<T> {} #nullable disable class B<TB1, TB2, TB3> where TB1 : ID<string?> where TB2 : ID<string>? where TB3 : ID<string> { #nullable enable public void Test1() { IA<TB1> x1; // 4 IA<TB2> y1; // 5 IA<TB3> z1; // 6 } #nullable enable public void M1<TM1>(TM1 x) where TM1: ID<string> {} #nullable enable public void Test2(TB1 a2, TB3 b2, TB2 c2) { M1(a2); // 7 M1(b2); // 8 M1(c2); // 9 M1<TB1>(a2); // 10 M1<TB2>(c2); // 11 M1<TB3>(b2); // 12 } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29678: Constraint violations are not reported for type references outside of method bodies. comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (24,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // IA<TB1> x1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "ID<string>", "TA", "TB1").WithLocation(24, 12), // (25,12): warning CS8631: The type 'TB2' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // IA<TB2> y1; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB2").WithArguments("IA<TA>", "ID<string>", "TA", "TB2").WithLocation(25, 12), // (34,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(34, 9), // (36,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1(c2); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(36, 9), // (37,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1<TB1>(a2); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(37, 9), // (38,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1<TB2>(c2); // 11 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB2>").WithArguments("B<TB1, TB2, TB3>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(38, 9) ); } [Fact] public void ConstraintsChecks_12() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class { } #nullable disable public interface IB<TIB> : IA<TIB> where TIB : C? // 1 {} #nullable disable public interface IC<TIC> : IA<TIC> where TIC : C // 2 {} #nullable enable public class C {} #nullable disable class B<TB1, TB2> where TB1 : C? where TB2 : C { #nullable enable public void Test1() { IA<TB1> x1; // 3 IA<TB2> z1; // 4 } #nullable enable public void M1<TM1>(TM1 x) where TM1: class {} #nullable enable public void Test2(TB1 a2, TB2 b2) { M1(a2); // 5 M1(b2); // 6 M1<TB1>(a2); // 7 M1<TB2>(b2); // 8 } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29678: Constraint violations are not reported for type references outside of method bodies. comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (21,12): warning CS8634: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // IA<TB1> x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(21, 12), // (30,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1(a2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(30, 9), // (32,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1<TB1>(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<TB1>").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(32, 9) ); } [Fact] public void ConstraintsChecks_13() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class { } public interface IB<TIB> : IA<TIB> where TIB : class? // 1 {} public interface IC<TIC> : IA<TIC> where TIC : class {} class B<TB1, TB2> where TB1 : class? where TB2 : class { public void Test1() { IA<TB1> x1; // 2 IA<TB2> z1; } public void M1<TM1>(TM1 x) where TM1: class {} public void Test2(TB1 a2, TB2 b2) { M1(a2); // 3 M1(b2); M1<TB1>(a2); // 4 M1<TB2>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8634: The type 'TIB' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIB' doesn't match 'class' constraint. // public interface IB<TIB> : IA<TIB> where TIB : class? // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "IB").WithArguments("IA<TA>", "TA", "TIB").WithLocation(8, 18), // (18,12): warning CS8634: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // IA<TB1> x1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(18, 12), // (27,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(27, 9), // (29,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1<TB1>(a2); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<TB1>").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(29, 9) ); } [Fact] public void ConstraintsChecks_14() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class? { } public interface IB<TIB> : IA<TIB> where TIB : class? {} public interface IC<TIC> : IA<TIC> where TIC : class {} class B<TB1, TB2> where TB1 : class? where TB2 : class { public void Test1() { IA<TB1> x1; IA<TB2> z1; } public void M1<TM1>(TM1 x) where TM1: class? {} public void Test2(TB1 a2, TB2 b2) { M1(a2); M1(b2); M1<TB1>(a2); M1<TB2>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics(); } [Fact] public void ConstraintsChecks_15() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class { } #nullable disable public interface IB<TIB> : IA<TIB> where TIB : class? // 1 {} #nullable disable public interface IC<TIC> : IA<TIC> where TIC : class // 2 {} #nullable disable class B<TB1, TB2> where TB1 : class? where TB2 : class { #nullable enable public void Test1() { IA<TB1> x1; // 3 IA<TB2> z1; // 4 } #nullable enable public void M1<TM1>(TM1 x) where TM1: class {} #nullable enable public void Test2(TB1 a2, TB2 b2) { M1(a2); // 5 M1(b2); // 6 M1<TB1>(a2); // 7 M1<TB2>(b2); // 8 } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29678: Constraint violations are not reported for type references outside of method bodies. comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (18,12): warning CS8634: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // IA<TB1> x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(18, 12), // (27,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1(a2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(27, 9), // (29,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1<TB1>(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<TB1>").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(29, 9) ); } [Fact] public void ConstraintsChecks_16() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : IE?, ID<string>, IF? { } public interface IB<TIB> : IA<TIB> where TIB : IE?, ID<string?>, IF? // 1 {} public interface IC<TIC> : IA<TIC> where TIC : IE?, ID<string>?, IF? // 2 {} public interface IE<TIE> : IA<TIE> where TIE : IE?, ID<string>, IF? {} public interface ID<T> {} class B<TB1, TB2, TB3, TB4> where TB1 : IE?, ID<string?>, IF? where TB2 : IE?, ID<string>?, IF? where TB3 : IE?, ID<string>, IF? where TB4 : IE, ID<string>?, IF? { public void Test1() { IA<TB1> x1; // 3 IA<TB2> y1; // 4 IA<TB3> z1; IA<TB4> u1; } public void M1<TM1>(TM1 x) where TM1: IE?, ID<string>, IF? {} public void Test2(TB1 a2, TB3 b2, TB2 c2, TB4 d2) { M1(a2); // 5 M1(b2); M1(c2); // 6 M1(d2); M1<TB1>(a2); // 7 M1<TB2>(c2); // 8 M1<TB3>(b2); M1<TB4>(d2); } } public interface IE {} public interface IF {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8631: The type 'TIB' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIB' doesn't match constraint type 'ID<string>'. // public interface IB<TIB> : IA<TIB> where TIB : IE?, ID<string?>, IF? // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "IB").WithArguments("IA<TA>", "ID<string>", "TA", "TIB").WithLocation(8, 18), // (11,18): warning CS8631: The type 'TIC' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIC' doesn't match constraint type 'ID<string>'. // public interface IC<TIC> : IA<TIC> where TIC : IE?, ID<string>?, IF? // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "IC").WithArguments("IA<TA>", "ID<string>", "TA", "TIC").WithLocation(11, 18), // (28,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // IA<TB1> x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "ID<string>", "TA", "TB1").WithLocation(28, 12), // (29,12): warning CS8631: The type 'TB2' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // IA<TB2> y1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB2").WithArguments("IA<TA>", "ID<string>", "TA", "TB2").WithLocation(29, 12), // (39,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1(a2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(39, 9), // (41,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1(c2); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(41, 9), // (43,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1<TB1>(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(43, 9), // (44,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1<TB2>(c2); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB2>").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(44, 9) ); } [Fact] public void ConstraintsChecks_17() { var source = @" #pragma warning disable CS0168 #nullable disable public interface IA<TA> where TA : IE?, ID<string>, IF? { } #nullable enable public interface IB<TIB> : IA<TIB> where TIB : IE?, ID<string?>, IF? {} public interface IC<TIC> : IA<TIC> where TIC : IE?, ID<string>?, IF? {} public interface IE<TIE> : IA<TIE> where TIE : IE?, ID<string>, IF? {} public interface ID<T> {} class B<TB1, TB2, TB3, TB4> where TB1 : IE?, ID<string?>, IF? where TB2 : IE?, ID<string>?, IF? where TB3 : IE?, ID<string>, IF? where TB4 : IE, ID<string>?, IF? { public void Test1() { IA<TB1> x1; IA<TB2> y1; IA<TB3> z1; IA<TB4> u1; } #nullable disable public void M1<TM1>(TM1 x) where TM1: IE?, ID<string>, IF? {} #nullable enable public void Test2(TB1 a2, TB3 b2, TB2 c2, TB4 d2) { M1(a2); M1(b2); M1(c2); M1(d2); M1<TB1>(a2); M1<TB2>(c2); M1<TB3>(b2); M1<TB4>(d2); } } public interface IE {} public interface IF {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify(); } [Fact] public void ConstraintsChecks_18() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : IE?, ID<string>, IF? { } #nullable disable public interface IB<TIB> : IA<TIB> where TIB : IE?, ID<string?>, IF? // 1 {} #nullable disable public interface IC<TIC> : IA<TIC> where TIC : IE?, ID<string>?, IF? // 2 {} #nullable disable public interface IE<TIE> : IA<TIE> where TIE : IE?, ID<string>, IF? // 3 {} #nullable enable public interface ID<T> {} #nullable disable class B<TB1, TB2, TB3, TB4> where TB1 : IE?, ID<string?>, IF? where TB2 : IE?, ID<string>?, IF? where TB3 : IE?, ID<string>, IF? where TB4 : IE, ID<string>?, IF? { #nullable enable public void Test1() { IA<TB1> x1; // 4 IA<TB2> y1; // 5 IA<TB3> z1; // 6 IA<TB4> u1; // 7 } #nullable enable public void M1<TM1>(TM1 x) where TM1: IE?, ID<string>, IF? {} #nullable enable public void Test2(TB1 a2, TB3 b2, TB2 c2, TB4 d2) { M1(a2); // 8 M1(b2); // 9 M1(c2); // 10 M1(d2); // 11 M1<TB1>(a2); // 12 M1<TB2>(c2); // 13 M1<TB3>(b2); // 14 M1<TB4>(d2); // 15 } } public interface IE {} public interface IF {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29678: Constraint violations are not reported for type references outside of method bodies. comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (33,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // IA<TB1> x1; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "ID<string>", "TA", "TB1").WithLocation(33, 12), // (34,12): warning CS8631: The type 'TB2' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // IA<TB2> y1; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB2").WithArguments("IA<TA>", "ID<string>", "TA", "TB2").WithLocation(34, 12), // (46,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1(a2); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(46, 9), // (48,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1(c2); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(48, 9), // (50,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'ID<string>'. // M1<TB1>(a2); // 12 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB1").WithLocation(50, 9), // (51,9): warning CS8631: The type 'TB2' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)'. Nullability of type argument 'TB2' doesn't match constraint type 'ID<string>'. // M1<TB2>(c2); // 13 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB2>").WithArguments("B<TB1, TB2, TB3, TB4>.M1<TM1>(TM1)", "ID<string>", "TM1", "TB2").WithLocation(51, 9) ); } [Fact] public void ConstraintsChecks_19() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : class, IB, IC { } class B<TB1> where TB1 : class?, IB?, IC? { public void Test1() { IA<TB1> x1; // 1 } public void M1<TM1>(TM1 x) where TM1: class, IB, IC {} public void Test2(TB1 a2) { M1(a2); // 2 M1<TB1>(a2); // 3 } } public interface IB {} public interface IC {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (12,12): warning CS8634: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // IA<TB1> x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(12, 12), // (12,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'IB'. // IA<TB1> x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "IB", "TA", "TB1").WithLocation(12, 12), // (12,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'IC'. // IA<TB1> x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "IC", "TA", "TB1").WithLocation(12, 12), // (20,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1(a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("B<TB1>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(20, 9), // (20,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IB'. // M1(a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1>(TM1)", "IB", "TM1", "TB1").WithLocation(20, 9), // (20,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IC'. // M1(a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1>(TM1)", "IC", "TM1", "TB1").WithLocation(20, 9), // (21,9): warning CS8634: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'class' constraint. // M1<TB1>(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<TB1>").WithArguments("B<TB1>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(21, 9), // (21,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IB'. // M1<TB1>(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1>.M1<TM1>(TM1)", "IB", "TM1", "TB1").WithLocation(21, 9), // (21,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IC'. // M1<TB1>(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1>.M1<TM1>(TM1)", "IC", "TM1", "TB1").WithLocation(21, 9) ); } [Fact] public void ConstraintsChecks_20() { var source = @" class B<TB1> where TB1 : class, IB? { public void M1<TM1, TM2>(TM1 x, TM2 y) where TM2 : TM1 {} public void Test2(TB1? a2, TB1 b2) { M1(b2, a2); // 1 M1<TB1, TB1?>(b2, a2); // 2 } } public interface IB {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (9,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1(b2, a2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(9, 9), // (10,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1<TB1, TB1?>(b2, a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1, TB1?>").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(10, 9) ); } [Fact] public void ConstraintsChecks_21() { var source = @" class B<TB1> where TB1 : class?, IB { public void M1<TM1, TM2>(TM1 x, TM2 y) where TM2 : TM1 {} public void Test2(TB1? a2, TB1 b2) { M1(b2, a2); // 1 M1<TB1, TB1?>(b2, a2); // 2 } } public interface IB {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (9,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1(b2, a2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(9, 9), // (10,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1<TB1, TB1?>(b2, a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1, TB1?>").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(10, 9) ); } [Fact] public void ConstraintsChecks_22() { var source = @" class B<TB1> where TB1 : class, IB? { #nullable disable public void M1<TM1, TM2>(TM1 x, TM2 y) where TM2 : TM1 {} #nullable enable public void Test2(TB1? a2, TB1 b2) { M1(b2, a2); // 1 M1<TB1, TB1?>(b2, a2); // 2 } } public interface IB {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (9,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1(b2, a2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(9, 9), // (10,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1<TB1, TB1?>(b2, a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1, TB1?>").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(10, 9) ); } [Fact] public void ConstraintsChecks_23() { var source = @" class B<TB1> where TB1 : A?, IB, IC? { public void M1<TM1, TM2>(TM1 x, TM2 y) where TM2 : TM1 {} public void Test2(TB1? a2, TB1 b2) { M1(b2, a2); // 1 M1<TB1, TB1?>(b2, a2); // 2 } } public class A {} public interface IB {} public interface IC {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (9,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1(b2, a2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(9, 9), // (10,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1<TB1, TB1?>(b2, a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1, TB1?>").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(10, 9) ); } [Fact] public void ConstraintsChecks_24() { var source = @" class B<TB1> where TB1 : A?, IB, IC? { #nullable disable public void M1<TM1, TM2>(TM1 x, TM2 y) where TM2 : TM1 {} #nullable enable public void Test2(TB1? a2, TB1 b2) { M1(b2, a2); // 1 M1<TB1, TB1?>(b2, a2); // 2 } } public class A {} public interface IB {} public interface IC {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (9,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1(b2, a2); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(9, 9), // (10,9): warning CS8631: The type 'TB1?' cannot be used as type parameter 'TM2' in the generic type or method 'B<TB1>.M1<TM1, TM2>(TM1, TM2)'. Nullability of type argument 'TB1?' doesn't match constraint type 'TB1'. // M1<TB1, TB1?>(b2, a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1, TB1?>").WithArguments("B<TB1>.M1<TM1, TM2>(TM1, TM2)", "TB1", "TM2", "TB1?").WithLocation(10, 9) ); } [Fact] public void ConstraintsChecks_25() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : notnull { } public interface IB : IA<string?> // 1 {} public interface IC : IA<string> {} class B { public void Test1() { IA<string?> x1; // 2 IA<string> z1; } public void M1<TM1>(TM1 x) where TM1: notnull {} public void Test2(string? a2, string b2) { M1(a2); // 3 M1(b2); M1<string?>(a2); // 4 M1<string?>(b2); // 5 M1<string>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8714: The type 'string?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // public interface IB : IA<string?> // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "IB").WithArguments("IA<TA>", "TA", "string?").WithLocation(8, 18), // (18,12): warning CS8714: The type 'string?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // IA<string?> x1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("IA<TA>", "TA", "string?").WithLocation(18, 12), // (27,9): warning CS8714: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M1(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(27, 9), // (29,9): warning CS8714: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M1<string?>(a2); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<string?>").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(29, 9), // (30,9): warning CS8714: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M1<string?>(b2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<string?>").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(30, 9) ); } [Fact] public void ConstraintsChecks_26() { var source = @" #pragma warning disable CS0168 #nullable disable public interface IA<TA> where TA : notnull { } #nullable enable public interface IB : IA<string?> {} public interface IC : IA<string> {} class B { public void Test1() { IA<string?> x1; IA<string> z1; } #nullable disable public void M1<TM1>(TM1 x) where TM1: notnull {} #nullable enable public void Test2(string? a2, string b2) { M1(a2); M1(b2); M1<string?>(a2); M1<string?>(b2); M1<string>(b2); } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (8,18): warning CS8714: The type 'string?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // public interface IB : IA<string?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "IB").WithArguments("IA<TA>", "TA", "string?").WithLocation(8, 18), // (18,12): warning CS8714: The type 'string?' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // IA<string?> x1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "string?").WithArguments("IA<TA>", "TA", "string?").WithLocation(18, 12), // (27,9): warning CS8714: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M1(a2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(27, 9), // (29,9): warning CS8714: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M1<string?>(a2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<string?>").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(29, 9), // (30,9): warning CS8714: The type 'string?' cannot be used as type parameter 'TM1' in the generic type or method 'B.M1<TM1>(TM1)'. Nullability of type argument 'string?' doesn't match 'notnull' constraint. // M1<string?>(b2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<string?>").WithArguments("B.M1<TM1>(TM1)", "TM1", "string?").WithLocation(30, 9) ); } [Fact] [WorkItem(34843, "https://github.com/dotnet/roslyn/issues/34843")] public void ConstraintsChecks_27() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : notnull { } #nullable disable public interface IB<TIB> : IA<TIB> where TIB : C? // 1 {} #nullable disable public interface IC<TIC> : IA<TIC> where TIC : C // 2 {} public class C {} #nullable disable class B<TB1, TB2> where TB1 : C? where TB2 : C { #nullable enable public void Test1() { IA<TB1> x1; // 3 IA<TB2> z1; // 4 } #nullable enable public void M1<TM1>(TM1 x) where TM1: notnull {} #nullable enable public void Test2(TB1 a2, TB2 b2) { M1(a2); // 5 M1(b2); // 6 M1<TB1>(a2); // 7 M1<TB2>(b2); // 8 } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29678: Constraint violations are not reported for type references outside of method bodies. comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify( // (21,12): warning CS8714: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // IA<TB1> x1; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(21, 12), // (30,9): warning CS8714: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // M1(a2); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(30, 9), // (32,9): warning CS8714: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1, TB2>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // M1<TB1>(a2); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<TB1>").WithArguments("B<TB1, TB2>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(32, 9) ); } [Fact] public void ConstraintsChecks_28() { var source0 = @" public interface IA<TA> where TA : notnull { } public class A { public void M1<TM1>(TM1 x) where TM1: notnull {} } "; var source1 = @" #pragma warning disable CS0168 public interface IB<TIB> : IA<TIB> // 1 {} public interface IC<TIC> : IA<TIC> where TIC : notnull {} class B<TB1, TB2> : A where TB2 : notnull { public void Test1() { IA<TB1> x1; // 2 IA<TB2> z1; } public void Test2(TB1 a2, TB2 b2) { M1(a2); // 3 M1(b2); M1<TB1>(a2); // 4 M1<TB2>(b2); } } "; var comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); foreach (var reference in new[] { comp0.ToMetadataReference(), comp0.EmitToImageReference() }) { var comp1 = CreateCompilation(new[] { source1 }, options: WithNullableEnable(), references: new[] { reference }); comp1.VerifyDiagnostics( // (4,18): warning CS8714: The type 'TIB' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TIB' doesn't match 'notnull' constraint. // public interface IB<TIB> : IA<TIB> // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "IB").WithArguments("IA<TA>", "TA", "TIB").WithLocation(4, 18), // (14,12): warning CS8714: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // IA<TB1> x1; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(14, 12), // (20,9): warning CS8714: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'A.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // M1(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("A.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(20, 9), // (22,9): warning CS8714: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'A.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // M1<TB1>(a2); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<TB1>").WithArguments("A.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(22, 9) ); } } [Fact] public void ConstraintsChecks_29() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : notnull { } #nullable disable public interface IB<TIB> : IA<TIB> // 1 {} #nullable disable public interface IC<TIC> : IA<TIC> where TIC : notnull // 2 {} #nullable disable class B<TB1, TB2> where TB2 : notnull { #nullable enable public void Test1() { IA<TB1> x1; // 3 IA<TB2> z1; // 4 } #nullable enable public void M1<TM1>(TM1 x) where TM1: notnull {} #nullable enable public void Test2(TB1 a2, TB2 b2) { M1(a2); // 5 M1(b2); // 6 M1<TB1>(a2); // 7 M1<TB2>(b2); // 8 } } "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29678: Constraint violations are not reported for type references outside of method bodies. comp1.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_MissingNonNullTypesContextForAnnotation).Verify(); } [Fact] public void ConstraintsChecks_30() { var source = @" #pragma warning disable CS0168 public interface IA<TA> where TA : notnull, IB, IC { } class B<TB1> where TB1 : IB?, IC? { public void Test1() { IA<TB1> x1; // 1 } public void M1<TM1>(TM1 x) where TM1: notnull, IB, IC {} public void Test2(TB1 a2) { M1(a2); // 2 M1<TB1>(a2); // 3 } } public interface IB {} public interface IC {} "; var comp1 = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp1.VerifyDiagnostics( // (12,12): warning CS8714: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // IA<TB1> x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "TB1").WithArguments("IA<TA>", "TA", "TB1").WithLocation(12, 12), // (12,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'IB'. // IA<TB1> x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "IB", "TA", "TB1").WithLocation(12, 12), // (12,12): warning CS8631: The type 'TB1' cannot be used as type parameter 'TA' in the generic type or method 'IA<TA>'. Nullability of type argument 'TB1' doesn't match constraint type 'IC'. // IA<TB1> x1; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "TB1").WithArguments("IA<TA>", "IC", "TA", "TB1").WithLocation(12, 12), // (20,9): warning CS8714: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // M1(a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("B<TB1>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(20, 9), // (20,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IB'. // M1(a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1>(TM1)", "IB", "TM1", "TB1").WithLocation(20, 9), // (20,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IC'. // M1(a2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1").WithArguments("B<TB1>.M1<TM1>(TM1)", "IC", "TM1", "TB1").WithLocation(20, 9), // (21,9): warning CS8714: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match 'notnull' constraint. // M1<TB1>(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<TB1>").WithArguments("B<TB1>.M1<TM1>(TM1)", "TM1", "TB1").WithLocation(21, 9), // (21,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IB'. // M1<TB1>(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1>.M1<TM1>(TM1)", "IB", "TM1", "TB1").WithLocation(21, 9), // (21,9): warning CS8631: The type 'TB1' cannot be used as type parameter 'TM1' in the generic type or method 'B<TB1>.M1<TM1>(TM1)'. Nullability of type argument 'TB1' doesn't match constraint type 'IC'. // M1<TB1>(a2); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M1<TB1>").WithArguments("B<TB1>.M1<TM1>(TM1)", "IC", "TM1", "TB1").WithLocation(21, 9) ); } [Fact] [WorkItem(34892, "https://github.com/dotnet/roslyn/issues/34892")] public void ConstraintsChecks_31() { var source = @" #nullable enable public class AA { public void M3<T3>(T3 z) where T3 : class { } public void M4<T4>(T4 z) where T4 : AA { } #nullable disable public void F1<T1>(T1 x) where T1 : class { #nullable enable M3<T1>(x); } #nullable disable public void F2<T2>(T2 x) where T2 : AA { #nullable enable M4<T2>(x); } } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics(); } [Fact] [WorkItem(34844, "https://github.com/dotnet/roslyn/issues/34844")] public void ConstraintsChecks_32() { var source = @" #pragma warning disable CS0649 #nullable disable class A<T1, T2, T3> where T2 : class where T3 : notnull { T1 F1; T2 F2; T3 F3; B F4; #nullable enable void M3() { C.Test<T1>(); C.Test<T2>(); C.Test<T3>(); } void M4() { D.Test(F1); D.Test(F2); D.Test(F3); D.Test(F4); } } class B {} class C { public static void Test<T>() where T : notnull {} } class D { public static void Test<T>(T x) where T : notnull {} } "; var comp1 = CreateCompilation(source); comp1.VerifyDiagnostics(); } [Fact] [WorkItem(29981, "https://github.com/dotnet/roslyn/issues/29981")] public void UnconstrainedTypeParameter_MayBeNonNullable() { var source = @"class C1<T1> { static object? NullableObject() => null; static T1 F1() => default; // warn: return type T1 may be non-null static T1 F2() => default(T1); // warn: return type T1 may be non-null static T1 F4() { T1 t1 = (T1)NullableObject(); return t1; } } class C2<T2> where T2 : class { static object? NullableObject() => null; static T2 F1() => default; // warn: return type T2 may be non-null static T2 F2() => default(T2); // warn: return type T2 may be non-null static T2 F4() { T2 t2 = (T2)NullableObject(); // warn: T2 may be non-null return t2; } } class C3<T3> where T3 : new() { static object? NullableObject() => null; static T3 F1() => default; // warn: return type T3 may be non-null static T3 F2() => default(T3); // warn: return type T3 may be non-null static T3 F3() => new T3(); static T3 F4() { T3 t = (T3)NullableObject(); // warn: T3 may be non-null return t3; } } class C4<T4> where T4 : I { static object? NullableObject() => null; static T4 F1() => default; // warn: return type T4 may be non-null static T4 F2() => default(T4); // warn: return type T4 may be non-null static T4 F4() { T4 t4 = (T4)NullableObject(); // warn: T4 may be non-null return t4; } } class C5<T5> where T5 : A { static object? NullableObject() => null; static T5 F1() => default; // warn: return type T5 may be non-null static T5 F2() => default(T5); // warn: return type T5 may be non-null static T5 F4() { T5 t5 = (T5)NullableObject(); // warn: T5 may be non-null return t5; } } interface I { } class A { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T1 t1 = (T1)NullableObject(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T1)NullableObject()").WithLocation(8, 17), // (9,16): warning CS8603: Possible null reference return. // return t1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(9, 16), // (15,23): warning CS8603: Possible null reference return. // static T2 F1() => default; // warn: return type T2 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(15, 23), // (16,23): warning CS8603: Possible null reference return. // static T2 F2() => default(T2); // warn: return type T2 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T2)").WithLocation(16, 23), // (19,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T2 t2 = (T2)NullableObject(); // warn: T2 may be non-null Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T2)NullableObject()").WithLocation(19, 17), // (20,16): warning CS8603: Possible null reference return. // return t2; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(20, 16), // (26,23): warning CS8603: Possible null reference return. // static T3 F1() => default; // warn: return type T3 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(26, 23), // (27,23): warning CS8603: Possible null reference return. // static T3 F2() => default(T3); // warn: return type T3 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T3)").WithLocation(27, 23), // (31,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T3 t = (T3)NullableObject(); // warn: T3 may be non-null Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T3)NullableObject()").WithLocation(31, 16), // (32,16): error CS0103: The name 't3' does not exist in the current context // return t3; Diagnostic(ErrorCode.ERR_NameNotInContext, "t3").WithArguments("t3").WithLocation(32, 16), // (38,23): warning CS8603: Possible null reference return. // static T4 F1() => default; // warn: return type T4 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(38, 23), // (39,23): warning CS8603: Possible null reference return. // static T4 F2() => default(T4); // warn: return type T4 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T4)").WithLocation(39, 23), // (42,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T4 t4 = (T4)NullableObject(); // warn: T4 may be non-null Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T4)NullableObject()").WithLocation(42, 17), // (43,16): warning CS8603: Possible null reference return. // return t4; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t4").WithLocation(43, 16), // (49,23): warning CS8603: Possible null reference return. // static T5 F1() => default; // warn: return type T5 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(49, 23), // (50,23): warning CS8603: Possible null reference return. // static T5 F2() => default(T5); // warn: return type T5 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T5)").WithLocation(50, 23), // (53,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T5 t5 = (T5)NullableObject(); // warn: T5 may be non-null Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T5)NullableObject()").WithLocation(53, 17), // (54,16): warning CS8603: Possible null reference return. // return t5; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t5").WithLocation(54, 16), // (4,23): warning CS8603: Possible null reference return. // static T1 F1() => default; // warn: return type T1 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(4, 23), // (5,23): warning CS8603: Possible null reference return. // static T1 F2() => default(T1); // warn: return type T1 may be non-null Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T1)").WithLocation(5, 23)); } [Fact] public void UnconstrainedTypeParameter_MayBeNullable_01() { var source = @"class C { static void F(object o) { } static void F1<T1>(bool b, T1 t1) { if (b) F(t1); if (b) F((object)t1); t1.ToString(); } static void F2<T2>(bool b, T2 t2) where T2 : struct { if (b) F(t2); if (b) F((object)t2); t2.ToString(); } static void F3<T3>(bool b, T3 t3) where T3 : class { if (b) F(t3); if (b) F((object)t3); t3.ToString(); } static void F4<T4>(bool b, T4 t4) where T4 : new() { if (b) F(t4); if (b) F((object)t4); t4.ToString(); } static void F5<T5>(bool b, T5 t5) where T5 : I { if (b) F(t5); if (b) F((object)t5); t5.ToString(); } static void F6<T6>(bool b, T6 t6) where T6 : A { if (b) F(t6); if (b) F((object)t6); t6.ToString(); } } interface I { } class A { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // if (b) F(t1); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t1").WithArguments("o", "void C.F(object o)").WithLocation(8, 18), // (9,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (b) F((object)t1); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t1").WithLocation(9, 18), // (9,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // if (b) F((object)t1); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(object)t1").WithArguments("o", "void C.F(object o)").WithLocation(9, 18), // (10,9): warning CS8602: Dereference of a possibly null reference. // t1.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(10, 9), // (26,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // if (b) F(t4); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t4").WithArguments("o", "void C.F(object o)").WithLocation(26, 18), // (27,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (b) F((object)t4); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t4").WithLocation(27, 18), // (27,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // if (b) F((object)t4); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(object)t4").WithArguments("o", "void C.F(object o)").WithLocation(27, 18), // (28,9): warning CS8602: Dereference of a possibly null reference. // t4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t4").WithLocation(28, 9) ); } [Fact] public void UnconstrainedTypeParameter_MayBeNullable_02() { var source = @"class C { static void F1<T1>(T1 x1) { object? y1; y1 = (object?)x1; y1 = (object)x1; // warn: T1 may be null } static void F2<T2>(T2 x2) where T2 : class { object? y2; y2 = (object?)x2; y2 = (object)x2; } static void F3<T3>(T3 x3) where T3 : new() { object? y3; y3 = (object?)x3; y3 = (object)x3; // warn unless new() constraint implies non-nullable y3 = (object)new T3(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y1 = (object)x1; // warn: T1 may be null Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)x1").WithLocation(7, 14), // (19,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y3 = (object)x3; // warn unless new() constraint implies non-nullable Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)x3").WithLocation(19, 14) ); } [Fact] public void UnconstrainedTypeParameter_Return_01() { var source = @"class C { static object? F01<T>(T t) => t; static object? F02<T>(T t) where T : class => t; static object? F03<T>(T t) where T : struct => t; static object? F04<T>(T t) where T : new() => t; static object? F05<T, U>(U u) where U : T => u; static object? F06<T, U>(U u) where U : class, T => u; static object? F07<T, U>(U u) where U : struct, T => u; static object? F08<T, U>(U u) where U : T, new() => u; static object? F09<T>(T t) => (object?)t; static object? F10<T>(T t) where T : class => (object?)t; static object? F11<T>(T t) where T : struct => (object?)t; static object? F12<T>(T t) where T : new() => (object?)t; static object? F13<T, U>(U u) where U : T => (object?)u; static object? F14<T, U>(U u) where U : class, T => (object?)u; static object? F15<T, U>(U u) where U : struct, T => (object?)u; static object? F16<T, U>(U u) where U : T, new() => (object?)u; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void UnconstrainedTypeParameter_Return_02() { var source = @"class C { static object F01<T>(T t) => t; static object F02<T>(T t) where T : class => t; static object F03<T>(T t) where T : struct => t; static object F04<T>(T t) where T : new() => t; static object F05<T, U>(U u) where U : T => u; static object F06<T, U>(U u) where U : class, T => u; static object F07<T, U>(U u) where U : struct, T => u; static object F08<T, U>(U u) where U : T, new() => u; static object F09<T>(T t) => (object)t; static object F10<T>(T t) where T : class => (object)t; static object F11<T>(T t) where T : struct => (object)t; static object F12<T>(T t) where T : new() => (object)t; static object F13<T, U>(U u) where U : T => (object)u; static object F14<T, U>(U u) where U : class, T => (object)u; static object F15<T, U>(U u) where U : struct, T => (object)u; static object F16<T, U>(U u) where U : T, new() => (object)u; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,34): warning CS8603: Possible null reference return. // static object F01<T>(T t) => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(3, 34), // (6,50): warning CS8603: Possible null reference return. // static object F04<T>(T t) where T : new() => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 50), // (7,49): warning CS8603: Possible null reference return. // static object F05<T, U>(U u) where U : T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(7, 49), // (10,56): warning CS8603: Possible null reference return. // static object F08<T, U>(U u) where U : T, new() => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 56), // (11,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // static object F09<T>(T t) => (object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(11, 34), // (11,34): warning CS8603: Possible null reference return. // static object F09<T>(T t) => (object)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(object)t").WithLocation(11, 34), // (14,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // static object F12<T>(T t) where T : new() => (object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(14, 50), // (14,50): warning CS8603: Possible null reference return. // static object F12<T>(T t) where T : new() => (object)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(object)t").WithLocation(14, 50), // (15,49): warning CS8600: Converting null literal or possible null value to non-nullable type. // static object F13<T, U>(U u) where U : T => (object)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)u").WithLocation(15, 49), // (15,49): warning CS8603: Possible null reference return. // static object F13<T, U>(U u) where U : T => (object)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(object)u").WithLocation(15, 49), // (18,56): warning CS8600: Converting null literal or possible null value to non-nullable type. // static object F16<T, U>(U u) where U : T, new() => (object)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)u").WithLocation(18, 56), // (18,56): warning CS8603: Possible null reference return. // static object F16<T, U>(U u) where U : T, new() => (object)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(object)u").WithLocation(18, 56)); } [Fact] public void UnconstrainedTypeParameter_Return_03() { var source = @"class C { static T F01<T>(T t) => t; static T F02<T>(T t) where T : class => t; static T F03<T>(T t) where T : struct => t; static T F04<T>(T t) where T : new() => t; static T F05<T, U>(U u) where U : T => u; static T F06<T, U>(U u) where U : class, T => u; static T F07<T, U>(U u) where U : struct, T => u; static T F08<T, U>(U u) where U : T, new() => u; static T F09<T>(T t) => (T)t; static T F10<T>(T t) where T : class => (T)t; static T F11<T>(T t) where T : struct => (T)t; static T F12<T>(T t) where T : new() => (T)t; static T F13<T, U>(U u) where U : T => (T)u; static T F14<T, U>(U u) where U : class, T => (T)u; static T F15<T, U>(U u) where U : struct, T => (T)u; static T F16<T, U>(U u) where U : T, new() => (T)u; static U F17<T, U>(T t) where U : T => (U)t; // W on return static U F18<T, U>(T t) where U : class, T => (U)t; // W on cast, W on return static U F19<T, U>(T t) where U : struct, T => (U)t; static U F20<T, U>(T t) where U : T, new() => (U)t; // W on return static U F21<T, U>(T t) => (U)(object)t; // W on cast, W on return }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,44): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F17<T, U>(T t) where U : T => (U)t; // W on return Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(19, 44), // (19,44): warning CS8603: Possible null reference return. // static U F17<T, U>(T t) where U : T => (U)t; // W on return Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(19, 44), // (20,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F18<T, U>(T t) where U : class, T => (U)t; // W on cast, W on return Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(20, 51), // (20,51): warning CS8603: Possible null reference return. // static U F18<T, U>(T t) where U : class, T => (U)t; // W on cast, W on return Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(20, 51), // (21,52): warning CS8605: Unboxing a possibly null value. // static U F19<T, U>(T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(21, 52), // (22,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F20<T, U>(T t) where U : T, new() => (U)t; // W on return Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 51), // (22,51): warning CS8603: Possible null reference return. // static U F20<T, U>(T t) where U : T, new() => (U)t; // W on return Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(22, 51), // (23,32): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>(T t) => (U)(object)t; // W on cast, W on return Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)t").WithLocation(23, 32), // (23,32): warning CS8603: Possible null reference return. // static U F21<T, U>(T t) => (U)(object)t; // W on cast, W on return Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)(object)t").WithLocation(23, 32), // (23,35): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>(T t) => (U)(object)t; // W on cast, W on return Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(23, 35)); } [Fact] public void UnconstrainedTypeParameter_Uninitialized() { var source = @" class C { static void F1<T>() { T t; t.ToString(); // 1 } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): error CS0165: Use of unassigned local variable 't' // t.ToString(); // 1 Diagnostic(ErrorCode.ERR_UseDefViolation, "t").WithArguments("t").WithLocation(7, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(7, 9)); } [Fact] [WorkItem(29981, "https://github.com/dotnet/roslyn/issues/29981")] public void UnconstrainedTypeParameter_OutVariable() { var source = @" class C { static void F1<T>(out T t) => t = default; // 1 static void F2<T>(out T t) => t = default(T); // 2 static void F3<T>(T t1, out T t2) => t2 = t1; static void F4<T, U>(U u, out T t) where U : T => t = u; static void F5<T, U>(U u, out T t) where T : U => t = (T)u; // 3 static void F6<T, U>(U u, out T t) => t = (T)(object)u; // 4 } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,39): warning CS8601: Possible null reference assignment. // static void F1<T>(out T t) => t = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(4, 39), // (5,39): warning CS8601: Possible null reference assignment. // static void F2<T>(out T t) => t = default(T); // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default(T)").WithLocation(5, 39), // (8,59): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F5<T, U>(U u, out T t) where T : U => t = (T)u; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(8, 59), // (8,59): warning CS8601: Possible null reference assignment. // static void F5<T, U>(U u, out T t) where T : U => t = (T)u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "(T)u").WithLocation(8, 59), // (9,47): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F6<T, U>(U u, out T t) => t = (T)(object)u; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)(object)u").WithLocation(9, 47), // (9,47): warning CS8601: Possible null reference assignment. // static void F6<T, U>(U u, out T t) => t = (T)(object)u; // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "(T)(object)u").WithLocation(9, 47), // (9,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F6<T, U>(U u, out T t) => t = (T)(object)u; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)u").WithLocation(9, 50)); } [Fact] [WorkItem(29983, "https://github.com/dotnet/roslyn/issues/29983")] public void UnconstrainedTypeParameter_TypeInferenceThroughCall() { var source = @" class C { static T Copy<T>(T t) => t; static void CopyOut<T>(T t1, out T t2) => t2 = t1; static void CopyOutInherit<T1, T2>(T1 t1, out T2 t2) where T1 : T2 => t2 = t1; static void M<U>(U u) { var x1 = Copy(u); x1.ToString(); // 1 CopyOut(u, out var x2); x2.ToString(); // 2 CopyOut(u, out U x3); x3.ToString(); // 3 if (u == null) throw null!; var x4 = Copy(u); x4.ToString(); CopyOut(u, out var x5); x5.ToString(); CopyOut(u, out U x6); x6.ToString(); CopyOutInherit(u, out var x7); x7.ToString(); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29983: Should not report warning for `x6.ToString()`. comp.VerifyDiagnostics( // (29,9): error CS0411: The type arguments for method 'C.CopyOutInherit<T1, T2>(T1, out T2)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // CopyOutInherit(u, out var x7); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "CopyOutInherit").WithArguments("C.CopyOutInherit<T1, T2>(T1, out T2)").WithLocation(29, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(10, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(13, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(16, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // x4.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(21, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // x5.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x5").WithLocation(24, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // x6.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x6").WithLocation(27, 9)); } [Fact] [WorkItem(29993, "https://github.com/dotnet/roslyn/issues/29993")] public void TypeParameter_Return_01() { var source = @" class C { static U F1<T, U>(T t) => (U)(object)t; // 1 and 2 static U F2<T, U>(T t) where U : class => (U)(object)t; // 3, 4 and 5 static U F3<T, U>(T t) where U : struct => (U)(object)t; // 6 static U F4<T, U>(T t) where T : class => (U)(object)t; static U F5<T, U>(T t) where T : struct => (U)(object)t; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/29993: Errors are different than expected. comp.VerifyDiagnostics( // (4,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F1<T, U>(T t) => (U)(object)t; // 1 and 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(4, 34), // (4,31): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F1<T, U>(T t) => (U)(object)t; // 1 and 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)t").WithLocation(4, 31), // (4,31): warning CS8603: Possible null reference return. // static U F1<T, U>(T t) => (U)(object)t; // 1 and 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)(object)t").WithLocation(4, 31), // (5,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F2<T, U>(T t) where U : class => (U)(object)t; // 3, 4 and 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(5, 50), // (5,47): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F2<T, U>(T t) where U : class => (U)(object)t; // 3, 4 and 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)t").WithLocation(5, 47), // (5,47): warning CS8603: Possible null reference return. // static U F2<T, U>(T t) where U : class => (U)(object)t; // 3, 4 and 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)(object)t").WithLocation(5, 47), // (6,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F3<T, U>(T t) where U : struct => (U)(object)t; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(6, 51), // (6,48): warning CS8605: Unboxing a possibly null value. // static U F3<T, U>(T t) where U : struct => (U)(object)t; // 6 Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)(object)t").WithLocation(6, 48) ); } [Fact] public void TrackUnconstrainedTypeParameter_LocalsAndParameters() { var source = @"class C { static void F0<T>() { default(T).ToString(); // 1 default(T)?.ToString(); } static void F1<T>() { T x1 = default; x1.ToString(); // 3 x1!.ToString(); x1?.ToString(); if (x1 != null) x1.ToString(); T y1 = x1; y1.ToString(); // 4 } static void F2<T>(T x2, T[] a2) { x2.ToString(); // 5 x2!.ToString(); x2?.ToString(); if (x2 != null) x2.ToString(); T y2 = x2; y2.ToString(); // 6 a2[0].ToString(); // 7 } static void F3<T>() where T : new() { T x3 = new T(); x3.ToString(); x3!.ToString(); var a3 = new[] { new T() }; a3[0].ToString(); // 8 } static T F4<T>(T x4) { T y4 = x4; return y4; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // default(T).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T)").WithLocation(5, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(16, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(20, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(25, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // a2[0].ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2[0]").WithLocation(26, 9), // (34,9): warning CS8602: Dereference of a possibly null reference. // a3[0].ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a3[0]").WithLocation(34, 9) ); } [Fact] public void TrackUnconstrainedTypeParameter_ExplicitCast() { var source = @"class C { static void F(object o) { } static void F1<T1>(T1 t1) { F((object)t1); if (t1 != null) F((object)t1); } static void F2<T2>(T2 t2) where T2 : class { F((object)t2); if (t2 != null) F((object)t2); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,11): warning CS8600: Converting null literal or possible null value to non-nullable type. // F((object)t1); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t1").WithLocation(8, 11), // (8,11): warning CS8604: Possible null reference argument for parameter 'o' in 'void C.F(object o)'. // F((object)t1); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(object)t1").WithArguments("o", "void C.F(object o)").WithLocation(8, 11) ); } [Fact] public void NullableT_BaseAndInterfaces() { var source = @"interface IA<T> { } interface IB<T> : IA<T?> { } interface IC<T> { } class A<T> { } class B<T> : A<(T, T?)> { } class C<T, U, V> : A<T?>, IA<U>, IC<V> { } class D<T, U, V> : A<T>, IA<U?>, IC<V> { } class E<T, U, V> : A<T>, IA<U>, IC<V?> { } class P { static void F1(IB<object> o) { } static void F2(B<object> o) { } static void F3(C<object, object, object> o) { } static void F4(D<object, object, object> o) { } static void F5(E<object, object, object> o) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (2,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // interface IB<T> : IA<T?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(2, 22), // (5,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class B<T> : A<(T, T?)> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 20), // (6,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C<T, U, V> : A<T?>, IA<U>, IC<V> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(6, 22), // (7,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class D<T, U, V> : A<T>, IA<U?>, IC<V> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(7, 29), // (8,36): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class E<T, U, V> : A<T>, IA<U>, IC<V?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "V?").WithArguments("9.0").WithLocation(8, 36) ); } [Fact] public void NullableT_Constraints() { var source = @"interface I<T, U> where U : T? { } class A<T> { } class B { static void F<T, U>() where U : A<T?> { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (1,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // interface I<T, U> where U : T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(1, 29), // (5,39): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F<T, U>() where U : A<T?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 39) ); } [Fact] [WorkItem(29995, "https://github.com/dotnet/roslyn/issues/29995")] public void NullableT_Members() { var source = @"using System; #pragma warning disable 0067 #pragma warning disable 0169 #pragma warning disable 8618 delegate T? D<T>(); class A<T> { } class B<T> { const object c = default(T?[]); T? F; B(T? t) { } static void M<U>(T? t, U? u) { } static B<T?> P { get; set; } event EventHandler<T?> E; public static explicit operator A<T?>(B<T> t) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); // https://github.com/dotnet/roslyn/issues/29995: Report error for `const object c = default(T?[]);`. comp.VerifyDiagnostics( // (5,10): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // delegate T? D<T>(); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 10), // (11,30): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // const object c = default(T?[]); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(11, 30), // (12,5): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? F; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(12, 5), // (13,7): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // B(T? t) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(13, 7), // (14,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void M<U>(T? t, U? u) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(14, 22), // (14,28): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void M<U>(T? t, U? u) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(14, 28), // (15,14): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static B<T?> P { get; set; } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(15, 14), // (16,24): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // event EventHandler<T?> E; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(16, 24), // (17,39): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public static explicit operator A<T?>(B<T> t) => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(17, 39) ); } [Fact] public void NullableT_ReturnType() { var source = @"interface I { } class A { } class B { static T? F1<T>() => throw null!; // error static T? F2<T>() where T : class => throw null!; static T? F3<T>() where T : struct => throw null!; static T? F4<T>() where T : new() => throw null!; // error static T? F5<T>() where T : unmanaged => throw null!; static T? F6<T>() where T : I => throw null!; // error static T? F7<T>() where T : A => throw null!; } class C { static U?[] F1<T, U>() where U : T => throw null!; // error static U?[] F2<T, U>() where T : class where U : T => throw null!; static U?[] F3<T, U>() where T : struct where U : T => throw null!; static U?[] F4<T, U>() where T : new() where U : T => throw null!; // error static U?[] F5<T, U>() where T : unmanaged where U : T => throw null!; static U?[] F6<T, U>() where T : I where U : T => throw null!; // error static U?[] F7<T, U>() where T : A where U : T => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (16,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static U?[] F2<T, U>() where T : class where U : T => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(16, 12), // (8,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static T? F4<T>() where T : new() => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 12), // (18,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static U?[] F4<T, U>() where T : new() where U : T => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(18, 12), // (10,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static T? F6<T>() where T : I => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(10, 12), // (20,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static U?[] F6<T, U>() where T : I where U : T => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(20, 12), // (5,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static T? F1<T>() => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 12), // (15,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static U?[] F1<T, U>() where U : T => throw null!; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(15, 12), // (17,23): error CS0456: Type parameter 'T' has the 'struct' constraint so 'T' cannot be used as a constraint for 'U' // static U?[] F3<T, U>() where T : struct where U : T => throw null!; Diagnostic(ErrorCode.ERR_ConWithValCon, "U").WithArguments("U", "T").WithLocation(17, 23), // (19,23): error CS8379: Type parameter 'T' has the 'unmanaged' constraint so 'T' cannot be used as a constraint for 'U' // static U?[] F5<T, U>() where T : unmanaged where U : T => throw null!; Diagnostic(ErrorCode.ERR_ConWithUnmanagedCon, "U").WithArguments("U", "T").WithLocation(19, 23)); } [Fact] public void NullableT_Parameters() { var source = @"interface I { } abstract class A { internal abstract void F1<T>(T? t); // error internal abstract void F2<T>(T? t) where T : class; internal abstract void F3<T>(T? t) where T : struct; internal abstract void F4<T>(T? t) where T : new(); // error internal abstract void F5<T>(T? t) where T : unmanaged; internal abstract void F6<T>(T? t) where T : I; // error internal abstract void F7<T>(T? t) where T : A; } class B : A { internal override void F1<U>(U? u) { } // error internal override void F2<U>(U? u) { } internal override void F3<U>(U? u) { } internal override void F4<U>(U? u) { } // error internal override void F5<U>(U? u) { } internal override void F6<U>(U? u) { } // error internal override void F7<U>(U? u) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,34): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // internal abstract void F1<T>(T? t); // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 34), // (7,34): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // internal abstract void F4<T>(T? t) where T : new(); // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 34), // (9,34): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // internal abstract void F6<T>(T? t) where T : I; // error Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(9, 34), // (12,7): error CS0534: 'B' does not implement inherited abstract member 'A.F4<T>(T?)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F4<T>(T?)").WithLocation(12, 7), // (12,7): error CS0534: 'B' does not implement inherited abstract member 'A.F1<T>(T?)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F1<T>(T?)").WithLocation(12, 7), // (12,7): error CS0534: 'B' does not implement inherited abstract member 'A.F2<T>(T?)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F2<T>(T?)").WithLocation(12, 7), // (12,7): error CS0534: 'B' does not implement inherited abstract member 'A.F6<T>(T?)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F6<T>(T?)").WithLocation(12, 7), // (12,7): error CS0534: 'B' does not implement inherited abstract member 'A.F7<T>(T?)' // class B : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "A.F7<T>(T?)").WithLocation(12, 7), // (14,28): error CS0115: 'B.F1<U>(U?)': no suitable method found to override // internal override void F1<U>(U? u) { } // error Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B.F1<U>(U?)").WithLocation(14, 28), // (14,37): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // internal override void F1<U>(U? u) { } // error Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(14, 37), // (15,28): error CS0115: 'B.F2<U>(U?)': no suitable method found to override // internal override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B.F2<U>(U?)").WithLocation(15, 28), // (15,37): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // internal override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(15, 37), // (17,28): error CS0115: 'B.F4<U>(U?)': no suitable method found to override // internal override void F4<U>(U? u) { } // error Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F4").WithArguments("B.F4<U>(U?)").WithLocation(17, 28), // (17,37): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // internal override void F4<U>(U? u) { } // error Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(17, 37), // (19,28): error CS0115: 'B.F6<U>(U?)': no suitable method found to override // internal override void F6<U>(U? u) { } // error Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F6").WithArguments("B.F6<U>(U?)").WithLocation(19, 28), // (19,37): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // internal override void F6<U>(U? u) { } // error Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 37), // (20,28): error CS0115: 'B.F7<U>(U?)': no suitable method found to override // internal override void F7<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F7").WithArguments("B.F7<U>(U?)").WithLocation(20, 28), // (20,37): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // internal override void F7<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 37)); } [Fact] public void NullableT_ContainingType() { var source = @"class A<T> { internal interface I { } internal enum E { } } class C { static void F1<T>(A<T?>.I i) { } static void F2<T>(A<T?>.E[] e) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F2<T>(A<T?>.E[] e) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(9, 25), // (8,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F1<T>(A<T?>.I i) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 25) ); } [Fact] public void NullableT_MethodBody() { var source = @"#pragma warning disable 0168 class C<T> { static void M<U>() { T? t; var u = typeof(U?); object? o = default(T?); o = new U?[0]; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? t; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(6, 9), // (7,24): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // var u = typeof(U?); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(7, 24), // (8,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // object? o = default(T?); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 29), // (9,17): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // o = new U?[0]; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(9, 17) ); } [Fact] public void NullableT_Lambda() { var source = @"delegate void D<T>(T t); class C { static void F<T>(D<T> d) { } static void G<T>() { F((T? t) => { }); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // F((T? t) => { }); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 12)); } [Fact] public void NullableT_LocalFunction() { var source = @"#pragma warning disable 8321 class C { static void F1<T>() { T? L1() => throw null!; } static void F2() { void L2<T>(T?[] t) { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (6,9): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? L1() => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(6, 9), // (10,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void L2<T>(T?[] t) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(10, 20)); } [Fact] [WorkItem(29996, "https://github.com/dotnet/roslyn/issues/29996")] public void NullableT_FromMetadata_BaseAndInterfaces() { var source0 = @".class public System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(bool[] b) cil managed { ret } } .class interface public abstract IA`1<T> { } .class interface public abstract IB`1<T> implements class IA`1<!T> { .interfaceimpl type class IA`1<!T> .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) } .class public A`1<T> { } .class public B`1<T> extends class A`1<!T> { .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(bool[]) = ( 01 00 02 00 00 00 00 01 00 00 ) }"; var ref0 = CompileIL(source0); var source1 = @"class C { static void F(IB<object> b) { } static void G(B<object> b) { } }"; var comp = CreateCompilation(source1, new[] { ref0 }); // https://github.com/dotnet/roslyn/issues/29996: Report errors for T? in metadata? comp.VerifyDiagnostics(); } [Fact] [WorkItem(29996, "https://github.com/dotnet/roslyn/issues/29996")] public void NullableT_FromMetadata_Methods() { var source0 = @".class public System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class interface public abstract I { } .class public A { } .class public C { .method public static !!T F1<T>() { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public static !!T F2<class T>() { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public static !!T F3<valuetype .ctor ([mscorlib]System.ValueType) T>() { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public static !!T F4<.ctor T>() { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public static !!T F5<(I) T>() { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } .method public static !!T F6<(A) T>() { .param [0] .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) ldnull throw } }"; var ref0 = CompileIL(source0); var source1 = @"class P { static void Main() { C.F1<int>(); // error C.F1<object>(); C.F2<object>(); C.F3<int>(); C.F4<object>(); // error C.F5<I>(); // error C.F6<A>(); } }"; var comp = CreateCompilation(source1, new[] { ref0 }); // https://github.com/dotnet/roslyn/issues/29996: Report errors for T? in metadata? comp.VerifyDiagnostics(); } [WorkItem(27289, "https://github.com/dotnet/roslyn/issues/27289")] [Fact] public void NullableTInConstraint_01() { var source = @"class A { } class B<T> where T : T? { } class C<T> where T : class, T? { } class D<T> where T : struct, T? { } class E<T> where T : A, T? { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (2,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class B<T> where T : T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(2, 22), // (4,30): error CS0701: 'T?' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // class D<T> where T : struct, T? { } Diagnostic(ErrorCode.ERR_BadBoundType, "T?").WithArguments("T?").WithLocation(4, 30), // (3,9): error CS0454: Circular constraint dependency involving 'T' and 'T' // class C<T> where T : class, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(3, 9), // (2,9): error CS0454: Circular constraint dependency involving 'T' and 'T' // class B<T> where T : T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(2, 9), // (5,9): error CS0454: Circular constraint dependency involving 'T' and 'T' // class E<T> where T : A, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(5, 9)); } [WorkItem(27289, "https://github.com/dotnet/roslyn/issues/27289")] [Fact] public void NullableTInConstraint_02() { var source = @"class A<T, U> where U : T? { } class B<T, U> where T : class where U : T? { } class C<T, U> where T : U? where U : T? { } class D<T, U> where T : class, U? where U : class, T? { } class E<T, U> where T : class, U where U : T? { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (2,15): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // where U : T? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(2, 15), // (11,15): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // where T : U? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(11, 15), // (12,15): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // where U : T? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(12, 15), // (10,9): error CS0454: Circular constraint dependency involving 'T' and 'U' // class C<T, U> Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "U").WithLocation(10, 9), // (15,9): error CS0454: Circular constraint dependency involving 'T' and 'U' // class D<T, U> Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "U").WithLocation(15, 9), // (20,9): error CS0454: Circular constraint dependency involving 'T' and 'U' // class E<T, U> Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "U").WithLocation(20, 9)); } [WorkItem(27289, "https://github.com/dotnet/roslyn/issues/27289")] [Fact] public void NullableTInConstraint_03() { var source = @"class A<T> where T : T, T? { } class B<U> where U : U?, U { } class C<V> where V : V?, V? { } delegate void D1<T1, U1>() where U1 : T1, T1?; delegate void D2<T2, U2>() where U2 : class, T2?, T2; delegate void D3<T3, U3>() where T3 : class where U3 : T3, T3?;"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (1,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class A<T> where T : T, T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(1, 25), // (1,25): error CS0405: Duplicate constraint 'T' for type parameter 'T' // class A<T> where T : T, T? { } Diagnostic(ErrorCode.ERR_DuplicateBound, "T?").WithArguments("T", "T").WithLocation(1, 25), // (1,9): error CS0454: Circular constraint dependency involving 'T' and 'T' // class A<T> where T : T, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(1, 9), // (2,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class B<U> where U : U?, U { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(2, 22), // (2,26): error CS0405: Duplicate constraint 'U' for type parameter 'U' // class B<U> where U : U?, U { } Diagnostic(ErrorCode.ERR_DuplicateBound, "U").WithArguments("U", "U").WithLocation(2, 26), // (2,9): error CS0454: Circular constraint dependency involving 'U' and 'U' // class B<U> where U : U?, U { } Diagnostic(ErrorCode.ERR_CircularConstraint, "U").WithArguments("U", "U").WithLocation(2, 9), // (3,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C<V> where V : V?, V? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "V?").WithArguments("9.0").WithLocation(3, 22), // (3,26): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C<V> where V : V?, V? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "V?").WithArguments("9.0").WithLocation(3, 26), // (3,26): error CS0405: Duplicate constraint 'V' for type parameter 'V' // class C<V> where V : V?, V? { } Diagnostic(ErrorCode.ERR_DuplicateBound, "V?").WithArguments("V", "V").WithLocation(3, 26), // (3,9): error CS0454: Circular constraint dependency involving 'V' and 'V' // class C<V> where V : V?, V? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "V").WithArguments("V", "V").WithLocation(3, 9), // (5,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // where U1 : T1, T1?; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T1?").WithArguments("9.0").WithLocation(5, 20), // (5,20): error CS0405: Duplicate constraint 'T1' for type parameter 'U1' // where U1 : T1, T1?; Diagnostic(ErrorCode.ERR_DuplicateBound, "T1?").WithArguments("T1", "U1").WithLocation(5, 20), // (7,23): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // where U2 : class, T2?, T2; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T2?").WithArguments("9.0").WithLocation(7, 23), // (7,28): error CS0405: Duplicate constraint 'T2' for type parameter 'U2' // where U2 : class, T2?, T2; Diagnostic(ErrorCode.ERR_DuplicateBound, "T2").WithArguments("T2", "U2").WithLocation(7, 28), // (10,20): error CS0405: Duplicate constraint 'T3' for type parameter 'U3' // where U3 : T3, T3?; Diagnostic(ErrorCode.ERR_DuplicateBound, "T3?").WithArguments("T3", "U3").WithLocation(10, 20)); } [Fact] public void NullableTInConstraint_04() { var source = @"class A { } class B { static void F1<T>() where T : T? { } static void F2<T>() where T : class, T? { } static void F3<T>() where T : struct, T? { } static void F4<T>() where T : A, T? { } static void F5<T, U>() where U : T? { } static void F6<T, U>() where T : class where U : T? { } static void F7<T, U>() where T : struct where U : T? { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,20): error CS0454: Circular constraint dependency involving 'T' and 'T' // static void F2<T>() where T : class, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(5, 20), // (6,43): error CS0701: 'T?' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // static void F3<T>() where T : struct, T? { } Diagnostic(ErrorCode.ERR_BadBoundType, "T?").WithArguments("T?").WithLocation(6, 43), // (7,20): error CS0454: Circular constraint dependency involving 'T' and 'T' // static void F4<T>() where T : A, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(7, 20), // (8,38): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F5<T, U>() where U : T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 38), // (10,55): error CS0701: 'T?' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // static void F7<T, U>() where T : struct where U : T? { } Diagnostic(ErrorCode.ERR_BadBoundType, "T?").WithArguments("T?").WithLocation(10, 55), // (4,35): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F1<T>() where T : T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 35), // (4,20): error CS0454: Circular constraint dependency involving 'T' and 'T' // static void F1<T>() where T : T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(4, 20)); } [Fact] public void NullableTInConstraint_05() { var source = @"#pragma warning disable 8321 class A { } class B { static void M() { void F1<T>() where T : T? { } void F2<T>() where T : class, T? { } void F3<T>() where T : struct, T? { } void F4<T>() where T : A, T? { } void F5<T, U>() where U : T? { } void F6<T, U>() where T : class where U : T? { } void F7<T, U>() where T : struct where U : T? { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,32): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F1<T>() where T : T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 32), // (7,17): error CS0454: Circular constraint dependency involving 'T' and 'T' // void F1<T>() where T : T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(7, 17), // (8,17): error CS0454: Circular constraint dependency involving 'T' and 'T' // void F2<T>() where T : class, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(8, 17), // (9,40): error CS0701: 'T?' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void F3<T>() where T : struct, T? { } Diagnostic(ErrorCode.ERR_BadBoundType, "T?").WithArguments("T?").WithLocation(9, 40), // (10,17): error CS0454: Circular constraint dependency involving 'T' and 'T' // void F4<T>() where T : A, T? { } Diagnostic(ErrorCode.ERR_CircularConstraint, "T").WithArguments("T", "T").WithLocation(10, 17), // (11,35): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void F5<T, U>() where U : T? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(11, 35), // (13,52): error CS0701: 'T?' is not a valid constraint. A type used as a constraint must be an interface, a non-sealed class or a type parameter. // void F7<T, U>() where T : struct where U : T? { } Diagnostic(ErrorCode.ERR_BadBoundType, "T?").WithArguments("T?").WithLocation(13, 52)); } [Fact] public void NullableTInConstraint_06() { var source = @"#pragma warning disable 8321 class A<T> where T : class { static void F1<U>() where U : T? { } static void F2() { void F3<U>() where U : T? { } } } class B { static void F4<T>() where T : class { void F5<U>() where U : T? { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableTInConstraint_07() { var source = @"interface I<T, U> where T : class where U : T { } class A<T, U> where T : class where U : T? { } class B1<T> : A<T, T>, I<T, T> where T : class { } class B2<T> : A<T, T?>, I<T, T?> where T : class { } class B3<T> : A<T?, T>, I<T?, T> where T : class { } class B4<T> : A<T?, T?>, I<T?, T?> where T : class { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,7): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'I<T, U>'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // class B2<T> : A<T, T?>, I<T, T?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "B2").WithArguments("I<T, U>", "T", "U", "T?").WithLocation(15, 7), // (19,7): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'A<T, U>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // class B3<T> : A<T?, T>, I<T?, T> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "B3").WithArguments("A<T, U>", "T", "T?").WithLocation(19, 7), // (19,7): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'I<T, U>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // class B3<T> : A<T?, T>, I<T?, T> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "B3").WithArguments("I<T, U>", "T", "T?").WithLocation(19, 7), // (23,7): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'A<T, U>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // class B4<T> : A<T?, T?>, I<T?, T?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "B4").WithArguments("A<T, U>", "T", "T?").WithLocation(23, 7), // (23,7): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'I<T, U>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // class B4<T> : A<T?, T?>, I<T?, T?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "B4").WithArguments("I<T, U>", "T", "T?").WithLocation(23, 7)); } // `class C<T> where T : class, T?` from metadata. [Fact] public void NullableTInConstraint_08() { // https://github.com/dotnet/roslyn/issues/29997: `where T : class, T?` is not valid in C#, // so the class needs to be defined in IL. How and where should the custom // attribute be declared for the constraint type in the following? var source0 = @".class public System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor() = ( 01 00 00 00 ) .class public C<class (!T) T> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } }"; var ref0 = CompileIL(source0); var source1 = @"class Program { static void Main() { object o; o = new C<object?>(); // 1 o = new C<object>(); // 2 } }"; var comp = CreateCompilation(new[] { source1 }, new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,19): error CS0454: Circular constraint dependency involving 'T' and 'T' // o = new C<object?>(); // 1 Diagnostic(ErrorCode.ERR_CircularConstraint, "object?").WithArguments("T", "T").WithLocation(6, 19), // (7,19): error CS0454: Circular constraint dependency involving 'T' and 'T' // o = new C<object>(); // 2 Diagnostic(ErrorCode.ERR_CircularConstraint, "object").WithArguments("T", "T").WithLocation(7, 19)); } // `class C<T, U> where U : T?` from metadata. [Fact] public void NullableTInConstraint_09() { var source0 = @"public class C<T, U> where T : class where U : T? { }"; var source1 = @"class Program { static void Main() { object o; o = new C<object?, object?>(); // 1 o = new C<object?, object>(); // 2 o = new C<object, object?>(); // 3 o = new C<object, object>(); // 4 } }"; var comp = CreateCompilation(source0, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (3,15): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // where U : T? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(3, 15), // (3,16): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // where U : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 16) ); MetadataReference ref0 = comp.ToMetadataReference(); comp = CreateCompilation(new[] { source1 }, new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); ref0 = comp.EmitToImageReference(); comp = CreateCompilation(new[] { source1 }, new[] { ref0 }, options: WithNullableEnable()); var c = comp.GetTypeByMetadataName("C`2"); Assert.IsAssignableFrom<PENamedTypeSymbol>(c); Assert.Equal("C<T, U> where T : class! where U : T?", c.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints)); comp.VerifyDiagnostics( // (6,19): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T, U>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // o = new C<object?, object?>(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T, U>", "T", "object?").WithLocation(6, 19), // (7,19): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C<T, U>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // o = new C<object?, object>(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "object?").WithArguments("C<T, U>", "T", "object?").WithLocation(7, 19) ); } [WorkItem(26294, "https://github.com/dotnet/roslyn/issues/26294")] [Fact] public void NullableTInConstraint_10() { var source = @"interface I<T> { } class C { static void F1<T>() where T : class, I<T?> { } static void F2<T>() where T : I<dynamic?> { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,35): error CS1968: Constraint cannot be a dynamic type 'I<dynamic>' // static void F2<T>() where T : I<dynamic?> { } Diagnostic(ErrorCode.ERR_ConstructedDynamicTypeAsBound, "I<dynamic?>").WithArguments("I<dynamic?>").WithLocation(5, 35)); } [Fact] public void DuplicateConstraints() { var source = @"interface I<T> where T : class { } class C<T> where T : class { static void F1<U>() where U : T, T { } static void F2<U>() where U : T, T? { } static void F3<U>() where U : T?, T { } static void F4<U>() where U : T?, T? { } static void F5<U>() where U : I<T>, I<T> { } static void F6<U>() where U : I<T>, I<T?> { } static void F7<U>() where U : I<T?>, I<T> { } static void F8<U>() where U : I<T?>, I<T?> { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,38): error CS0405: Duplicate constraint 'T' for type parameter 'U' // static void F1<U>() where U : T, T { } Diagnostic(ErrorCode.ERR_DuplicateBound, "T").WithArguments("T", "U").WithLocation(4, 38), // (5,38): error CS0405: Duplicate constraint 'T' for type parameter 'U' // static void F2<U>() where U : T, T? { } Diagnostic(ErrorCode.ERR_DuplicateBound, "T?").WithArguments("T", "U").WithLocation(5, 38), // (6,39): error CS0405: Duplicate constraint 'T' for type parameter 'U' // static void F3<U>() where U : T?, T { } Diagnostic(ErrorCode.ERR_DuplicateBound, "T").WithArguments("T", "U").WithLocation(6, 39), // (7,39): error CS0405: Duplicate constraint 'T' for type parameter 'U' // static void F4<U>() where U : T?, T? { } Diagnostic(ErrorCode.ERR_DuplicateBound, "T?").WithArguments("T", "U").WithLocation(7, 39), // (8,41): error CS0405: Duplicate constraint 'I<T>' for type parameter 'U' // static void F5<U>() where U : I<T>, I<T> { } Diagnostic(ErrorCode.ERR_DuplicateBound, "I<T>").WithArguments("I<T>", "U").WithLocation(8, 41), // (9,41): error CS0405: Duplicate constraint 'I<T>' for type parameter 'U' // static void F6<U>() where U : I<T>, I<T?> { } Diagnostic(ErrorCode.ERR_DuplicateBound, "I<T?>").WithArguments("I<T>", "U").WithLocation(9, 41), // (10,20): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'I<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // static void F7<U>() where U : I<T?>, I<T> { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "U").WithArguments("I<T>", "T", "T?").WithLocation(10, 20), // (10,42): error CS0405: Duplicate constraint 'I<T>' for type parameter 'U' // static void F7<U>() where U : I<T?>, I<T> { } Diagnostic(ErrorCode.ERR_DuplicateBound, "I<T>").WithArguments("I<T>", "U").WithLocation(10, 42), // (11,20): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'I<T>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // static void F8<U>() where U : I<T?>, I<T?> { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "U").WithArguments("I<T>", "T", "T?").WithLocation(11, 20), // (11,42): error CS0405: Duplicate constraint 'I<T>' for type parameter 'U' // static void F8<U>() where U : I<T?>, I<T?> { } Diagnostic(ErrorCode.ERR_DuplicateBound, "I<T?>").WithArguments("I<T>", "U").WithLocation(11, 42)); } [Fact] public void PartialClassConstraints() { var source = @"class A<T, U> where T : A<T, U> where U : B<T, U> { } partial class B<T, U> where T : A<T, U> where U : B<T, U> { } partial class B<T, U> where T : A<T, U> where U : B<T, U> { }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void PartialClassConstraintMismatch() { var source = @"class A { } partial class B<T> where T : A { } partial class B<T> where T : A? { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (2,15): error CS0265: Partial declarations of 'B<T>' have inconsistent constraints for type parameter 'T' // partial class B<T> where T : A { } Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "B").WithArguments("B<T>", "T").WithLocation(2, 15)); } [Fact] public void TypeUnification_01() { var source = @"interface I<T> { } class C1<T, U> : I<T>, I<U> { } class C2<T, U> : I<T>, I<U?> { } class C3<T, U> : I<T?>, I<U> { } class C4<T, U> : I<T?>, I<U?> { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (3,26): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C2<T, U> : I<T>, I<U?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(3, 26), // (4,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C3<T, U> : I<T?>, I<U> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 20), // (5,20): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C4<T, U> : I<T?>, I<U?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 20), // (5,27): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C4<T, U> : I<T?>, I<U?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(5, 27), // (2,7): error CS0695: 'C1<T, U>' cannot implement both 'I<T>' and 'I<U>' because they may unify for some type parameter substitutions // class C1<T, U> : I<T>, I<U> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C1").WithArguments("C1<T, U>", "I<T>", "I<U>").WithLocation(2, 7), // (5,7): error CS0695: 'C4<T, U>' cannot implement both 'I<T?>' and 'I<U?>' because they may unify for some type parameter substitutions // class C4<T, U> : I<T?>, I<U?> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T, U>", "I<T?>", "I<U?>").WithLocation(5, 7), // (3,7): error CS0695: 'C2<T, U>' cannot implement both 'I<T>' and 'I<U?>' because they may unify for some type parameter substitutions // class C2<T, U> : I<T>, I<U?> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C2").WithArguments("C2<T, U>", "I<T>", "I<U?>").WithLocation(3, 7), // (4,7): error CS0695: 'C3<T, U>' cannot implement both 'I<T?>' and 'I<U>' because they may unify for some type parameter substitutions // class C3<T, U> : I<T?>, I<U> { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I<T?>", "I<U>").WithLocation(4, 7) ); } [Fact] public void TypeUnification_02() { var source = @"interface I<T> { } class C1<T, U> : I<T>, I<U> where T : struct { } class C2<T, U> : I<T>, I<U?> where T : struct { } class C3<T, U> : I<T?>, I<U> where T : struct { } class C4<T, U> : I<T?>, I<U?> where T : struct { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (2,7): error CS0695: 'C1<T, U>' cannot implement both 'I<T>' and 'I<U>' because they may unify for some type parameter substitutions // class C1<T, U> : I<T>, I<U> where T : struct { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C1").WithArguments("C1<T, U>", "I<T>", "I<U>").WithLocation(2, 7), // (3,7): error CS0695: 'C2<T, U>' cannot implement both 'I<T>' and 'I<U?>' because they may unify for some type parameter substitutions // class C2<T, U> : I<T>, I<U?> where T : struct { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C2").WithArguments("C2<T, U>", "I<T>", "I<U?>").WithLocation(3, 7), // (3,26): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C2<T, U> : I<T>, I<U?> where T : struct { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(3, 26), // (4,7): error CS0695: 'C3<T, U>' cannot implement both 'I<T?>' and 'I<U>' because they may unify for some type parameter substitutions // class C3<T, U> : I<T?>, I<U> where T : struct { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I<T?>", "I<U>").WithLocation(4, 7), // (5,7): error CS0695: 'C4<T, U>' cannot implement both 'I<T?>' and 'I<U?>' because they may unify for some type parameter substitutions // class C4<T, U> : I<T?>, I<U?> where T : struct { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T, U>", "I<T?>", "I<U?>").WithLocation(5, 7), // (5,27): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C4<T, U> : I<T?>, I<U?> where T : struct { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(5, 27) ); } [Fact] public void TypeUnification_03() { var source = @"interface I<T> { } class C1<T, U> : I<T>, I<U> where T : class { } class C2<T, U> : I<T>, I<U?> where T : class { } class C3<T, U> : I<T?>, I<U> where T : class { } class C4<T, U> : I<T?>, I<U?> where T : class { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (2,7): error CS0695: 'C1<T, U>' cannot implement both 'I<T>' and 'I<U>' because they may unify for some type parameter substitutions // class C1<T, U> : I<T>, I<U> where T : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C1").WithArguments("C1<T, U>", "I<T>", "I<U>").WithLocation(2, 7), // (3,7): error CS0695: 'C2<T, U>' cannot implement both 'I<T>' and 'I<U?>' because they may unify for some type parameter substitutions // class C2<T, U> : I<T>, I<U?> where T : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C2").WithArguments("C2<T, U>", "I<T>", "I<U?>").WithLocation(3, 7), // (3,26): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C2<T, U> : I<T>, I<U?> where T : class { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(3, 26), // (4,7): error CS0695: 'C3<T, U>' cannot implement both 'I<T?>' and 'I<U>' because they may unify for some type parameter substitutions // class C3<T, U> : I<T?>, I<U> where T : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I<T?>", "I<U>").WithLocation(4, 7), // (5,7): error CS0695: 'C4<T, U>' cannot implement both 'I<T?>' and 'I<U?>' because they may unify for some type parameter substitutions // class C4<T, U> : I<T?>, I<U?> where T : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T, U>", "I<T?>", "I<U?>").WithLocation(5, 7), // (5,27): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C4<T, U> : I<T?>, I<U?> where T : class { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(5, 27) ); } [Fact] public void TypeUnification_04() { var source = @"interface I<T> { } class C1<T, U> : I<T>, I<U> where T : struct where U : class { } class C2<T, U> : I<T>, I<U?> where T : struct where U : class { } class C3<T, U> : I<T?>, I<U> where T : struct where U : class { } class C4<T, U> : I<T?>, I<U?> where T : struct where U : class { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // Constraints are ignored when unifying types. comp.VerifyDiagnostics( // (2,7): error CS0695: 'C1<T, U>' cannot implement both 'I<T>' and 'I<U>' because they may unify for some type parameter substitutions // class C1<T, U> : I<T>, I<U> where T : struct where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C1").WithArguments("C1<T, U>", "I<T>", "I<U>").WithLocation(2, 7), // (3,7): error CS0695: 'C2<T, U>' cannot implement both 'I<T>' and 'I<U?>' because they may unify for some type parameter substitutions // class C2<T, U> : I<T>, I<U?> where T : struct where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C2").WithArguments("C2<T, U>", "I<T>", "I<U?>").WithLocation(3, 7), // (4,7): error CS0695: 'C3<T, U>' cannot implement both 'I<T?>' and 'I<U?>' because they may unify for some type parameter substitutions // class C3<T, U> : I<T?>, I<U> where T : struct where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I<T?>", "I<U>").WithLocation(4, 7), // (5,7): error CS0695: 'C4<T, U>' cannot implement both 'I<T?>' and 'I<U?>' because they may unify for some type parameter substitutions // class C4<T, U> : I<T?>, I<U?> where T : struct where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T, U>", "I<T?>", "I<U?>").WithLocation(5, 7)); } [Fact] public void TypeUnification_05() { var source = @"interface I<T> where T : class? { } class C1<T, U> : I<T>, I<U> where T : class where U : class { } class C2<T, U> : I<T>, I<U?> where T : class where U : class { } class C3<T, U> : I<T?>, I<U> where T : class where U : class { } class C4<T, U> : I<T?>, I<U?> where T : class where U : class { }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (2,7): error CS0695: 'C1<T, U>' cannot implement both 'I<T>' and 'I<U>' because they may unify for some type parameter substitutions // class C1<T, U> : I<T>, I<U> where T : class where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C1").WithArguments("C1<T, U>", "I<T>", "I<U>").WithLocation(2, 7), // (3,7): error CS0695: 'C2<T, U>' cannot implement both 'I<T>' and 'I<U?>' because they may unify for some type parameter substitutions // class C2<T, U> : I<T>, I<U?> where T : class where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C2").WithArguments("C2<T, U>", "I<T>", "I<U?>").WithLocation(3, 7), // (4,7): error CS0695: 'C3<T, U>' cannot implement both 'I<T?>' and 'I<U>' because they may unify for some type parameter substitutions // class C3<T, U> : I<T?>, I<U> where T : class where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C3").WithArguments("C3<T, U>", "I<T?>", "I<U>").WithLocation(4, 7), // (5,7): error CS0695: 'C4<T, U>' cannot implement both 'I<T?>' and 'I<U?>' because they may unify for some type parameter substitutions // class C4<T, U> : I<T?>, I<U?> where T : class where U : class { } Diagnostic(ErrorCode.ERR_UnifyingInterfaceInstantiations, "C4").WithArguments("C4<T, U>", "I<T?>", "I<U?>").WithLocation(5, 7)); } [Fact] public void AssignmentNullability() { var source = @"class C { static void F1(string? x1, string y1) { object? z1; (z1 = x1).ToString(); (z1 = y1).ToString(); } static void F2(string? x2, string y2) { object z2; (z2 = x2).ToString(); (z2 = y2).ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (z1 = x1).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1 = x1").WithLocation(6, 10), // (12,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // (z2 = x2).ToString(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(12, 15), // (12,10): warning CS8602: Dereference of a possibly null reference. // (z2 = x2).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2 = x2").WithLocation(12, 10)); } [WorkItem(27008, "https://github.com/dotnet/roslyn/issues/27008")] [Fact] public void OverriddenMethodNullableValueTypeParameter_01() { var source0 = @"public abstract class A { public abstract void F(int? i); }"; var comp0 = CreateCompilation(source0); var ref0 = comp0.EmitToImageReference(); var source = @"class B : A { public override void F(int? i) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); } [Fact] public void OverriddenMethodNullableValueTypeParameter_02() { var source0 = @"public abstract class A<T> where T : struct { public abstract void F(T? t); }"; var comp0 = CreateCompilation(source0); var ref0 = comp0.EmitToImageReference(); var source = @"class B1<T> : A<T> where T : struct { public override void F(T? t) { } } class B2 : A<int> { public override void F(int? t) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); } [WorkItem(27967, "https://github.com/dotnet/roslyn/issues/27967")] [Fact] public void UnannotatedTypeArgument_Interface() { var source0 = @"public interface I<T> { } public class B : I<object[]> { } public class C : I<C> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class Program { static void F(B x) { I<object[]?> a = x; I<object[]> b = x; } static void F(C y) { I<C?> a = y; I<C> b = y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); } [WorkItem(27967, "https://github.com/dotnet/roslyn/issues/27967")] [Fact] public void UnannotatedTypeArgument_BaseType() { var source0 = @"public class A<T> { } public class B : A<object[]> { } public class C : A<C> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class Program { static void F(B x) { A<object[]?> a = x; A<object[]> b = x; } static void F(C y) { A<C?> a = y; A<C> b = y; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); } [Fact] public void UnannotatedTypeArgument_Interface_Lookup() { var source0 = @"public interface I<T> { void F(T t); } public interface I1 : I<object> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"interface I2 : I<object> { } class Program { static void F(I1 i1, I2 i2, object x, object? y) { i1.F(x); i1.F(y); i2.F(x); i2.F(y); // warn } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (11,14): warning CS8604: Possible null reference argument for parameter 't' in 'void I<object>.F(object t)'. // i2.F(y); // warn Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("t", "void I<object>.F(object t)").WithLocation(11, 14)); } [Fact] public void UnannotatedTypeArgument_BaseType_Lookup() { var source0 = @"public class A<T> { public static void F(T t) { } } public class B1 : A<object> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class B2 : A<object> { } class Program { static void F(object x, object? y) { B1.F(x); B1.F(y); B2.F(x); B2.F(y); // warn } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (11,14): warning CS8604: Possible null reference argument for parameter 't' in 'void A<object>.F(object t)'. // B2.F(y); // warn Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("t", "void A<object>.F(object t)").WithLocation(11, 14)); } [Fact] public void UnannotatedConstraint_01() { var source0 = @"public class A1 { } public class A2<T> { } public class B1<T> where T : A1 { } public class B2<T> where T : A2<object> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class Program { static void Main() { new B1<A1?>(); new B1<A1>(); new B2<A2<object?>>(); new B2<A2<object>>(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); var typeParameters = comp.GetMember<NamedTypeSymbol>("B1").TypeParameters; Assert.Equal("A1", typeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); typeParameters = comp.GetMember<NamedTypeSymbol>("B2").TypeParameters; Assert.Equal("A2<System.Object>", typeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); } [Fact] public void UnannotatedConstraint_02() { var source0 = @" public class A1 { } public class A2<T> { } #nullable disable public class B1<T, U> where T : A1 where U : A1? { } #nullable disable public class B2<T, U> where T : A2<object> where U : A2<object?> { }"; var comp0 = CreateCompilation(new[] { source0 }); comp0.VerifyDiagnostics( // (5,48): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public class B1<T, U> where T : A1 where U : A1? { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 48), // (7,63): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public class B2<T, U> where T : A2<object> where U : A2<object?> { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 63) ); var ref0 = comp0.EmitToImageReference(); var source = @"class Program { static void Main() { new B1<A1, A1?>(); new B1<A1?, A1>(); new B2<A2<object>, A2<object?>>(); new B2<A2<object?>, A2<object>>(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (8,29): warning CS8631: The type 'A2<object>' cannot be used as type parameter 'U' in the generic type or method 'B2<T, U>'. Nullability of type argument 'A2<object>' doesn't match constraint type 'A2<object?>'. // new B2<A2<object?>, A2<object>>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A2<object>").WithArguments("B2<T, U>", "A2<object?>", "U", "A2<object>").WithLocation(8, 29)); var typeParameters = comp.GetMember<NamedTypeSymbol>("B1").TypeParameters; Assert.Equal("A1", typeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); Assert.Equal("A1?", typeParameters[1].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); typeParameters = comp.GetMember<NamedTypeSymbol>("B2").TypeParameters; Assert.Equal("A2<System.Object>", typeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); Assert.Equal("A2<System.Object?>", typeParameters[1].ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); } [Fact] public void UnannotatedConstraint_Override() { var source0 = @" public interface I<T> { } public abstract class A<T> where T : class { #nullable disable public abstract void F1<U>() where U : T, I<T>; #nullable disable public abstract void F2<U>() where U : T?, I<T?>; #nullable enable public abstract void F3<U>() where U : T, I<T>; #nullable enable public abstract void F4<U>() where U : T?, I<T?>; }"; var comp0 = CreateCompilation(new[] { source0 }, parseOptions: TestOptions.Regular8); comp0.VerifyDiagnostics( // (8,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public abstract void F2<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 45), // (8,44): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public abstract void F2<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 44), // (8,51): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public abstract void F2<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 51), // (8,50): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public abstract void F2<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 50), // (12,44): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public abstract void F4<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(12, 44), // (12,50): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public abstract void F4<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(12, 50) ); var source = @" #nullable disable class B1 : A<string> { public override void F1<U>() { } public override void F2<U>() { } public override void F3<U>() { } public override void F4<U>() { } } #nullable disable class B2 : A<string?> { public override void F1<U>() { } public override void F2<U>() { } public override void F3<U>() { } public override void F4<U>() { } } #nullable enable class B3 : A<string> { public override void F1<U>() { } public override void F2<U>() { } public override void F3<U>() { } public override void F4<U>() { } } #nullable enable class B4 : A<string?> { public override void F1<U>() { } public override void F2<U>() { } public override void F3<U>() { } public override void F4<U>() { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { new CSharpCompilationReference(comp0) }); comp.VerifyDiagnostics( // (11,20): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // class B2 : A<string?> Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 20) ); verifyAllConstraintTypes(); comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); comp0.VerifyDiagnostics( // (8,45): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public abstract void F2<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 45), // (8,51): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // public abstract void F2<U>() where U : T?, I<T?>; Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 51) ); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { new CSharpCompilationReference(comp0) }); comp.VerifyDiagnostics( // (11,20): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // class B2 : A<string?> Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 20), // (27,7): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // class B4 : A<string?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "B4").WithArguments("A<T>", "T", "string?").WithLocation(27, 7) ); verifyAllConstraintTypes(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { comp0.EmitToImageReference() }); comp.VerifyDiagnostics( // (11,20): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // class B2 : A<string?> Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(11, 20), // (27,7): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // class B4 : A<string?> Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "B4").WithArguments("A<T>", "T", "string?").WithLocation(27, 7) ); verifyAllConstraintTypes(); void verifyAllConstraintTypes() { string bangOrEmpty = comp0.Options.NullableContextOptions == NullableContextOptions.Disable ? "" : "!"; verifyConstraintTypes("B1.F1", "System.String", "I<System.String>"); verifyConstraintTypes("B1.F2", "System.String?", "I<System.String?>"); verifyConstraintTypes("B1.F3", "System.String" + bangOrEmpty, "I<System.String" + bangOrEmpty + ">!"); verifyConstraintTypes("B1.F4", "System.String?", "I<System.String?>!"); verifyConstraintTypes("B2.F1", "System.String?", "I<System.String?>"); verifyConstraintTypes("B2.F2", "System.String?", "I<System.String?>"); verifyConstraintTypes("B2.F3", "System.String?", "I<System.String?>!"); verifyConstraintTypes("B2.F4", "System.String?", "I<System.String?>!"); verifyConstraintTypes("B3.F1", "System.String!", "I<System.String!>"); verifyConstraintTypes("B3.F2", "System.String?", "I<System.String?>"); verifyConstraintTypes("B3.F3", "System.String!", "I<System.String!>!"); verifyConstraintTypes("B3.F4", "System.String?", "I<System.String?>!"); verifyConstraintTypes("B4.F1", "System.String?", "I<System.String?>"); verifyConstraintTypes("B4.F2", "System.String?", "I<System.String?>"); verifyConstraintTypes("B4.F3", "System.String?", "I<System.String?>!"); verifyConstraintTypes("B4.F4", "System.String?", "I<System.String?>!"); } void verifyConstraintTypes(string methodName, params string[] expectedTypes) { var constraintTypes = comp.GetMember<MethodSymbol>(methodName).TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics; AssertEx.Equal(expectedTypes, constraintTypes.SelectAsArray(t => t.ToTestDisplayString(true))); } } [Fact] public void Constraint_LocalFunction_01() { var source = @" class C { #nullable enable void M1() { local(new C(), new C(), new C(), null); void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? { T? x = t; x!.ToString(); } } #nullable disable void M2() { local(new C(), new C(), new C(), null); void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? { T? x = t; // warn 1 x!.ToString(); } } }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (20,14): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? x = t; // warn 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(20, 14), // (20,13): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? x = t; // warn 1 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(20, 13), // (18,56): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 56), // (18,85): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 85), // (18,99): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(18, 99), // (18,98): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(18, 98) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var localSyntaxes = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>(); verifyLocalFunction(localSyntaxes.ElementAt(0), "C.M1.local", new[] { "C!" }); verifyLocalFunction(localSyntaxes.ElementAt(1), "C.M2.local", new[] { "C" }); void verifyLocalFunction(LocalFunctionStatementSyntax localSyntax, string expectedName, string[] expectedConstraintTypes) { var localSymbol = model.GetDeclaredSymbol(localSyntax).GetSymbol<LocalFunctionSymbol>(); var constraintTypes = localSymbol.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics; AssertEx.Equal(expectedConstraintTypes, constraintTypes.SelectAsArray(t => t.ToTestDisplayString(true))); } } [Fact] public void Constraint_LocalFunction_02() { var source = @" class C { void M3() { local(new C(), new C(), new C(), null); void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? { T? x = t; // warn 2 x!.ToString(); // warn 3 } } }"; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,14): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // T? x = t; // warn 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 14), // (9,13): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? x = t; // warn 2 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(9, 13), // (7,56): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 56), // (7,85): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 85), // (7,99): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(7, 99), // (7,98): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void local<T, T2, T3>(T t, T2 t2, T3 t3, string? s) where T : C where T2 : C? where T3 : T? Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(7, 98) ); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var localSyntaxes = tree.GetRoot().DescendantNodes().OfType<LocalFunctionStatementSyntax>(); verifyLocalFunction(localSyntaxes.ElementAt(0), "C.M3.local", new[] { "C" }); void verifyLocalFunction(LocalFunctionStatementSyntax localSyntax, string expectedName, string[] expectedConstraintTypes) { var localSymbol = model.GetDeclaredSymbol(localSyntax).GetSymbol<LocalFunctionSymbol>(); var constraintTypes = localSymbol.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics; AssertEx.Equal(expectedConstraintTypes, constraintTypes.SelectAsArray(t => t.ToTestDisplayString(true))); } } [Fact] public void Constraint_Oblivious_01() { var source0 = @"public interface I<T> { } public class A<T> where T : I<T> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); var ref0 = comp0.EmitToImageReference(); var source = @"using System; class B1 : I<B1> { } class B2 : I<B2?> { } class C { static void Main() { Type t; t = typeof(A<B1>); t = typeof(A<B2>); // 1 t = typeof(A<B1?>); // 2 t = typeof(A<B2?>); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (10,22): warning CS8631: The type 'B2' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. Nullability of type argument 'B2' doesn't match constraint type 'I<B2>'. // t = typeof(A<B2>); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "B2").WithArguments("A<T>", "I<B2>", "T", "B2").WithLocation(10, 22), // (11,22): warning CS8631: The type 'B1?' cannot be used as type parameter 'T' in the generic type or method 'A<T>'. Nullability of type argument 'B1?' doesn't match constraint type 'I<B1?>'. // t = typeof(A<B1?>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "B1?").WithArguments("A<T>", "I<B1?>", "T", "B1?").WithLocation(11, 22) ); var constraintTypes = comp.GetMember<NamedTypeSymbol>("A").TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics; Assert.Equal("I<T>", constraintTypes[0].ToTestDisplayString(true)); } [Fact] public void Constraint_Oblivious_02() { var source0 = @"public class A<T, U, V> where T : A<T, U, V> where V : U { protected interface I { } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); var ref0 = comp0.EmitToImageReference(); var source = @"class B : A<B, object, object> { static void F(I i) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics(); } [Fact] public void Constraint_Oblivious_03() { var source0 = @"public class A { } public class B0<T> where T : A { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"#pragma warning disable 0169 class B1<T> where T : A? { } class B2<T> where T : A { } #nullable enable class B3<T> where T : A? { } #nullable enable class B4<T> where T : A { } #nullable disable class C { B0<A?> F1; // 1 B0<A> F2; B1<A?> F3; // 2 B1<A> F4; B2<A?> F5; // 3 B2<A> F6; B3<A?> F7; // 4 B3<A> F8; B4<A?> F9; // 5 and 6 B4<A> F10; } #nullable enable class D { B0<A?> G1; B0<A> G2; B1<A?> G3; B1<A> G4; B2<A?> G5; B2<A> G6; B3<A?> G7; B3<A> G8; B4<A?> G9; // 7 B4<A> G10; }"; var comp = CreateCompilation(new[] { source }, references: new[] { ref0 }); comp.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_UninitializedNonNullableField).Verify( // (15,9): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B1<A?> F3; // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(15, 9), // (4,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // class B1<T> where T : A? { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 24), // (17,9): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B2<A?> F5; // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 9), // (19,9): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B3<A?> F7; // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(19, 9), // (35,12): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'B4<T>'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // B4<A?> G9; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "G9").WithArguments("B4<T>", "A", "T", "A?").WithLocation(35, 12), // (21,9): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B4<A?> F9; // 5 and 6 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 9), // (13,9): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B0<A?> F1; // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 9) ); } [Fact] public void Constraint_Oblivious_04() { var source0 = @"public class A<T> { } public class B0<T> where T : A<object> { }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"#pragma warning disable 0169 class B1<T> where T : A<object?> { } class B2<T> where T : A<object> { } #nullable enable class B3<T> where T : A<object?> { } #nullable enable class B4<T> where T : A<object> { } #nullable disable class C { B0<A<object?>> F1; // 1 B0<A<object>> F2; B1<A<object?>> F3; // 2 B1<A<object>> F4; B2<A<object?>> F5; // 3 B2<A<object>> F6; B3<A<object?>> F7; // 4 B3<A<object>> F8; B4<A<object?>> F9; // 5 and 6 B4<A<object>> F10; } #nullable enable class D { B0<A<object?>> G1; B0<A<object>> G2; B1<A<object?>> G3; B1<A<object>> G4; // 7 B2<A<object?>> G5; B2<A<object>> G6; B3<A<object?>> G7; B3<A<object>> G8; // 8 B4<A<object?>> G9; // 9 B4<A<object>> G10; }"; var comp = CreateCompilation(new[] { source }, references: new[] { ref0 }); comp.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.WRN_UninitializedNonNullableField).Verify( // (4,31): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // class B1<T> where T : A<object?> { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 31), // (15,16): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B1<A<object?>> F3; // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(15, 16), // (17,16): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B2<A<object?>> F5; // 3 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(17, 16), // (19,16): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B3<A<object?>> F7; // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(19, 16), // (21,16): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B4<A<object?>> F9; // 5 and 6 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 16), // (13,16): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // B0<A<object?>> F1; // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(13, 16), // (30,19): warning CS8631: The type 'A<object>' cannot be used as type parameter 'T' in the generic type or method 'B1<T>'. Nullability of type argument 'A<object>' doesn't match constraint type 'A<object?>'. // B1<A<object>> G4; // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "G4").WithArguments("B1<T>", "A<object?>", "T", "A<object>").WithLocation(30, 19), // (34,19): warning CS8631: The type 'A<object>' cannot be used as type parameter 'T' in the generic type or method 'B3<T>'. Nullability of type argument 'A<object>' doesn't match constraint type 'A<object?>'. // B3<A<object>> G8; // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "G8").WithArguments("B3<T>", "A<object?>", "T", "A<object>").WithLocation(34, 19), // (35,20): warning CS8631: The type 'A<object?>' cannot be used as type parameter 'T' in the generic type or method 'B4<T>'. Nullability of type argument 'A<object?>' doesn't match constraint type 'A<object>'. // B4<A<object?>> G9; // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "G9").WithArguments("B4<T>", "A<object>", "T", "A<object?>").WithLocation(35, 20) ); } [Fact] public void Constraint_TypeParameterConstraint() { var source0 = @"public class A1<T, U> where T : class where U : class, T { } public class A2<T, U> where T : class where U : class, T? { }"; var comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @" class B1<T> where T : A1<T, T?> { } // 1 class B2<T> where T : A2<T?, T> { } // 2 #nullable enable class B3<T> where T : A1<T, T?> { } #nullable enable class B4<T> where T : A2<T?, T> { }"; var comp = CreateCompilation(new[] { source }, references: new[] { ref0 }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (2,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // class B1<T> where T : A1<T, T?> { } // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(2, 30), // (2,29): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class B1<T> where T : A1<T, T?> { } // 1 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(2, 29), // (3,27): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // class B2<T> where T : A2<T?, T> { } // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 27), // (3,26): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class B2<T> where T : A2<T?, T> { } // 2 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(3, 26), // (5,10): warning CS8634: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'A1<T, U>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // class B3<T> where T : A1<T, T?> { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "T").WithArguments("A1<T, U>", "U", "T?").WithLocation(5, 10), // (5,10): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'A1<T, U>'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // class B3<T> where T : A1<T, T?> { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "T").WithArguments("A1<T, U>", "T", "U", "T?").WithLocation(5, 10), // (7,10): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'A2<T, U>'. Nullability of type argument 'T?' doesn't match 'class' constraint. // class B4<T> where T : A2<T?, T> { } Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "T").WithArguments("A2<T, U>", "T", "T?").WithLocation(7, 10)); } // Boxing conversion. [Fact] public void Constraint_BoxingConversion() { var source0 = @"public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } public struct S0 : I<object> { } public struct SIn0 : IIn<object> { } public struct SOut0 : IOut<object> { } public class A { public static void F0<T>() where T : I<object> { } public static void FIn0<T>() where T : IIn<object> { } public static void FOut0<T>() where T : IOut<object> { } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"struct S1 : I<object?> { } struct S2 : I<object> { } struct SIn1 : IIn<object?> { } struct SIn2 : IIn<object> { } struct SOut1 : IOut<object?> { } struct SOut2 : IOut<object> { } class B : A { static void F1<T>() where T : I<object?> { } static void F2<T>() where T : I<object> { } static void FIn1<T>() where T : IIn<object?> { } static void FIn2<T>() where T : IIn<object> { } static void FOut1<T>() where T : IOut<object?> { } static void FOut2<T>() where T : IOut<object> { } static void F() { F0<S0>(); F0<S1>(); F0<S2>(); F1<S0>(); F1<S1>(); F1<S2>(); // 1 F2<S0>(); F2<S1>(); // 2 F2<S2>(); } static void FIn() { FIn0<SIn0>(); FIn0<SIn1>(); FIn0<SIn2>(); FIn1<SIn0>(); FIn1<SIn1>(); FIn1<SIn2>(); // 3 FIn2<SIn0>(); FIn2<SIn1>(); FIn2<SIn2>(); } static void FOut() { FOut0<SOut0>(); FOut0<SOut1>(); FOut0<SOut2>(); FOut1<SOut0>(); FOut1<SOut1>(); FOut1<SOut2>(); FOut2<SOut0>(); FOut2<SOut1>(); // 4 FOut2<SOut2>(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (22,9): warning CS8627: The type 'S2' cannot be used as type parameter 'T' in the generic type or method 'B.F1<T>()'. Nullability of type argument 'S2' doesn't match constraint type 'I<object?>'. // F1<S2>(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F1<S2>").WithArguments("B.F1<T>()", "I<object?>", "T", "S2").WithLocation(22, 9), // (24,9): warning CS8627: The type 'S1' cannot be used as type parameter 'T' in the generic type or method 'B.F2<T>()'. Nullability of type argument 'S1' doesn't match constraint type 'I<object>'. // F2<S1>(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F2<S1>").WithArguments("B.F2<T>()", "I<object>", "T", "S1").WithLocation(24, 9), // (34,9): warning CS8627: The type 'SIn2' cannot be used as type parameter 'T' in the generic type or method 'B.FIn1<T>()'. Nullability of type argument 'SIn2' doesn't match constraint type 'IIn<object?>'. // FIn1<SIn2>(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "FIn1<SIn2>").WithArguments("B.FIn1<T>()", "IIn<object?>", "T", "SIn2").WithLocation(34, 9), // (48,9): warning CS8627: The type 'SOut1' cannot be used as type parameter 'T' in the generic type or method 'B.FOut2<T>()'. Nullability of type argument 'SOut1' doesn't match constraint type 'IOut<object>'. // FOut2<SOut1>(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "FOut2<SOut1>").WithArguments("B.FOut2<T>()", "IOut<object>", "T", "SOut1").WithLocation(48, 9)); } [Fact] public void Constraint_ImplicitTypeParameterConversion() { var source0 = @"public interface I<T> { } public interface IIn<in T> { } public interface IOut<out T> { } public class A { public static void F0<T>() where T : I<object> { } public static void FIn0<T>() where T : IIn<object> { } public static void FOut0<T>() where T : IOut<object> { } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class B : A { static void F1<T>() where T : I<object?> { } static void F2<T>() where T : I<object> { } static void FIn1<T>() where T : IIn<object?> { } static void FIn2<T>() where T : IIn<object> { } static void FOut1<T>() where T : IOut<object?> { } static void FOut2<T>() where T : IOut<object> { } static void F<T, U>() where T : I<object?> where U : I<object> { F0<T>(); F0<U>(); F1<T>(); F1<U>(); // 1 F2<T>(); // 2 F2<U>(); } static void FIn<T, U>() where T : IIn<object?> where U : IIn<object> { FIn0<T>(); FIn0<U>(); FIn1<T>(); FIn1<U>(); // 3 FIn2<T>(); FIn2<U>(); } static void FOut<T, U>() where T : IOut<object?> where U : IOut<object> { FOut0<T>(); FOut0<U>(); FOut1<T>(); FOut1<U>(); FOut2<T>(); // 4 FOut2<U>(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (14,9): warning CS8627: The type 'U' cannot be used as type parameter 'T' in the generic type or method 'B.F1<T>()'. Nullability of type argument 'U' doesn't match constraint type 'I<object?>'. // F1<U>(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F1<U>").WithArguments("B.F1<T>()", "I<object?>", "T", "U").WithLocation(14, 9), // (15,9): warning CS8627: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'B.F2<T>()'. Nullability of type argument 'T' doesn't match constraint type 'I<object>'. // F2<T>(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F2<T>").WithArguments("B.F2<T>()", "I<object>", "T", "T").WithLocation(15, 9), // (23,9): warning CS8627: The type 'U' cannot be used as type parameter 'T' in the generic type or method 'B.FIn1<T>()'. Nullability of type argument 'U' doesn't match constraint type 'IIn<object?>'. // FIn1<U>(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "FIn1<U>").WithArguments("B.FIn1<T>()", "IIn<object?>", "T", "U").WithLocation(23, 9), // (33,9): warning CS8627: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'B.FOut2<T>()'. Nullability of type argument 'T' doesn't match constraint type 'IOut<object>'. // FOut2<T>(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "FOut2<T>").WithArguments("B.FOut2<T>()", "IOut<object>", "T", "T").WithLocation(33, 9)); } [Fact] public void Constraint_MethodTypeInference() { var source0 = @"public class A { } public class B { public static void F0<T>(T t) where T : A { } }"; var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular7); comp0.VerifyDiagnostics(); var ref0 = comp0.EmitToImageReference(); var source = @"class C : B { static void F1<T>(T t) where T : A { } static void G(A x, A? y) { F0(x); F1(x); F0(y); F1(y); // 1 x = y; F0(x); F1(x); // 2 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), references: new[] { ref0 }); comp.VerifyDiagnostics( // (11,9): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C.F1<T>(T)'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // F1(y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F1").WithArguments("C.F1<T>(T)", "A", "T", "A?").WithLocation(11, 9), // (12,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = y; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(12, 13), // (14,9): warning CS8631: The type 'A?' cannot be used as type parameter 'T' in the generic type or method 'C.F1<T>(T)'. Nullability of type argument 'A?' doesn't match constraint type 'A'. // F1(x); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "F1").WithArguments("C.F1<T>(T)", "A", "T", "A?").WithLocation(14, 9)); } [Fact] [WorkItem(29999, "https://github.com/dotnet/roslyn/issues/29999")] public void ThisAndBaseMemberInLambda() { var source = @"delegate void D(); class A { internal string? F; } class B : A { void M() { D d; d = () => { int n = this.F.Length; // 1 this.F = string.Empty; n = this.F.Length; }; d = () => { int n = base.F.Length; // 2 base.F = string.Empty; n = base.F.Length; }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,21): warning CS8602: Dereference of a possibly null reference. // int n = this.F.Length; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.F").WithLocation(13, 21), // (19,21): warning CS8602: Dereference of a possibly null reference. // int n = base.F.Length; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "base.F").WithLocation(19, 21)); } [Fact] [WorkItem(29999, "https://github.com/dotnet/roslyn/issues/29999")] public void ThisAndBaseMemberInLocalFunction() { var source = @"#pragma warning disable 8321 class A { internal string? F; } class B : A { void M() { void f() { int n = this.F.Length; // 1 this.F = string.Empty; n = this.F.Length; } void g() { int n = base.F.Length; // 2 base.F = string.Empty; n = base.F.Length; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,21): warning CS8602: Dereference of a possibly null reference. // int n = this.F.Length; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "this.F").WithLocation(12, 21), // (18,21): warning CS8602: Dereference of a possibly null reference. // int n = base.F.Length; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "base.F").WithLocation(18, 21)); } [WorkItem(31620, "https://github.com/dotnet/roslyn/issues/31620")] [Fact] public void InstanceMemberInLambda() { var source = @"using System; class Program { private object? _f; private object _g = null!; private void F() { Func<bool, object> f = (bool b1) => { Func<bool, object> g = (bool b2) => { if (b2) { _g = null; // 1 return _g; // 2 } return _g; }; if (b1) return _f; // 3 _f = new object(); return _f; }; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,26): warning CS8625: Cannot convert null literal to non-nullable reference type. // _g = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 26), // (15,28): warning CS8603: Possible null reference return. // return _g; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "_g").WithLocation(15, 28), // (19,28): warning CS8603: Possible null reference return. // if (b1) return _f; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "_f").WithLocation(19, 28)); } [WorkItem(31620, "https://github.com/dotnet/roslyn/issues/31620")] [Fact] public void InstanceMemberInLocalFunction() { var source = @"#pragma warning disable 8321 class Program { private object? _f; private object _g = null!; private void F() { object f(bool b1) { if (b1) return _f; // 1 _f = new object(); return _f; object g(bool b2) { if (b2) { _g = null; // 2 return _g; // 3 } return _g; } } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,28): warning CS8603: Possible null reference return. // if (b1) return _f; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "_f").WithLocation(10, 28), // (17,26): warning CS8625: Cannot convert null literal to non-nullable reference type. // _g = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(17, 26), // (18,28): warning CS8603: Possible null reference return. // return _g; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "_g").WithLocation(18, 28)); } [WorkItem(29049, "https://github.com/dotnet/roslyn/issues/29049")] [Fact] public void TypeWithAnnotations_GetHashCode() { var source = @"interface I<T> { } class A : I<A> { } class B<T> where T : I<A?> { } class Program { static void Main() { new B<A>(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (8,15): warning CS8631: The type 'A' cannot be used as type parameter 'T' in the generic type or method 'B<T>'. Nullability of type argument 'A' doesn't match constraint type 'I<A?>'. // new B<A>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A").WithArguments("B<T>", "I<A?>", "T", "A").WithLocation(8, 15)); // Diagnostics must support GetHashCode() and Equals(), to allow removing // duplicates (see CommonCompiler.ReportErrors). foreach (var diagnostic in diagnostics) { diagnostic.GetHashCode(); Assert.True(diagnostic.Equals(diagnostic)); } } [WorkItem(29041, "https://github.com/dotnet/roslyn/issues/29041")] [WorkItem(29048, "https://github.com/dotnet/roslyn/issues/29048")] [WorkItem(30001, "https://github.com/dotnet/roslyn/issues/30001")] [Fact] public void ConstraintCyclesFromMetadata_01() { var source0 = @"using System; public class A0<T> where T : IEquatable<T> { } public class A1<T> where T : class, IEquatable<T> { } public class A3<T> where T : struct, IEquatable<T> { } public class A4<T> where T : struct, IEquatable<T?> { } public class A5<T> where T : IEquatable<string?> { } public class A6<T> where T : IEquatable<int?> { }"; var source = @"class B { static void Main() { new A0<string?>(); // 1 new A0<string>(); new A5<string?>(); // 4 new A5<string>(); // 5 } }"; // No [NullNullTypes] var comp0 = CreateCompilation(source0); var ref0 = comp0.EmitToImageReference(); var comp = CreateCompilation(source, references: new[] { ref0 }); var expectedDiagnostics = new[] { // (5,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A0<string?>(); // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 22), // (9,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A5<string?>(); // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 22) }; comp.VerifyDiagnostics(expectedDiagnostics); verifyTypeParameterConstraint("A0", "System.IEquatable<T>"); verifyTypeParameterConstraint("A1", "System.IEquatable<T>"); verifyTypeParameterConstraint("A3", "System.IEquatable<T>"); verifyTypeParameterConstraint("A4", "System.IEquatable<T?>"); verifyTypeParameterConstraint("A5", "System.IEquatable<System.String?>"); verifyTypeParameterConstraint("A6", "System.IEquatable<System.Int32?>"); // [NullNullTypes(false)] comp0 = CreateCompilation(new[] { source0 }, options: WithNullableDisable()); ref0 = comp0.EmitToImageReference(); comp = CreateCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics(expectedDiagnostics); verifyTypeParameterConstraint("A0", "System.IEquatable<T>"); verifyTypeParameterConstraint("A1", "System.IEquatable<T>"); verifyTypeParameterConstraint("A3", "System.IEquatable<T>"); verifyTypeParameterConstraint("A4", "System.IEquatable<T?>"); verifyTypeParameterConstraint("A5", "System.IEquatable<System.String?>"); verifyTypeParameterConstraint("A6", "System.IEquatable<System.Int32?>"); // [NullNullTypes(true)] comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); ref0 = comp0.EmitToImageReference(); comp = CreateCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A0<string?>(); // 1 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 22), // (9,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A5<string?>(); // 4 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(9, 22) ); verifyTypeParameterConstraint("A0", "System.IEquatable<T>"); verifyTypeParameterConstraint("A1", "System.IEquatable<T>"); verifyTypeParameterConstraint("A3", "System.IEquatable<T>"); verifyTypeParameterConstraint("A4", "System.IEquatable<T?>"); verifyTypeParameterConstraint("A5", "System.IEquatable<System.String?>"); verifyTypeParameterConstraint("A6", "System.IEquatable<System.Int32?>"); comp = CreateCompilation(source, references: new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,16): warning CS8631: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'A0<T>'. Nullability of type argument 'string?' doesn't match constraint type 'System.IEquatable<string?>'. // new A0<string?>(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "string?").WithArguments("A0<T>", "System.IEquatable<string?>", "T", "string?").WithLocation(5, 16), // (9,16): warning CS8631: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'A5<T>'. Nullability of type argument 'string?' doesn't match constraint type 'System.IEquatable<string?>'. // new A5<string?>(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "string?").WithArguments("A5<T>", "System.IEquatable<string?>", "T", "string?").WithLocation(9, 16) ); verifyTypeParameterConstraint("A0", "System.IEquatable<T>"); verifyTypeParameterConstraint("A1", "System.IEquatable<T>"); verifyTypeParameterConstraint("A3", "System.IEquatable<T>"); verifyTypeParameterConstraint("A4", "System.IEquatable<T?>"); verifyTypeParameterConstraint("A5", "System.IEquatable<System.String?>"); verifyTypeParameterConstraint("A6", "System.IEquatable<System.Int32?>"); void verifyTypeParameterConstraint(string typeName, string expected) { var type = comp.GetMember<NamedTypeSymbol>(typeName); var constraintType = type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0]; Assert.Equal(expected, constraintType.ToTestDisplayString()); } } [WorkItem(29041, "https://github.com/dotnet/roslyn/issues/29041")] [WorkItem(29048, "https://github.com/dotnet/roslyn/issues/29048")] [WorkItem(30003, "https://github.com/dotnet/roslyn/issues/30003")] [Fact] public void ConstraintCyclesFromMetadata_02() { var source0 = @"using System; public class A2<T> where T : class, IEquatable<T?> { } "; var source = @"class B { static void Main() { new A2<string?>(); // 2 new A2<string>(); // 3 } }"; // No [NullNullTypes] var comp0 = CreateCompilation(source0, parseOptions: TestOptions.Regular8); comp0.VerifyDiagnostics( // (2,48): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public class A2<T> where T : class, IEquatable<T?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(2, 48), // (2,49): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public class A2<T> where T : class, IEquatable<T?> { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(2, 49) ); MetadataReference ref0 = comp0.ToMetadataReference(); var comp = CreateCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A2<string?>(); // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 22) ); verifyTypeParameterConstraint("A2", "System.IEquatable<T?>"); // [NullNullTypes(false)] comp0 = CreateCompilation(new[] { source0 }, options: WithNullableDisable(), parseOptions: TestOptions.Regular8); comp0.VerifyDiagnostics( // (2,48): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public class A2<T> where T : class, IEquatable<T?> { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(2, 48), // (2,49): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // public class A2<T> where T : class, IEquatable<T?> { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(2, 49) ); ref0 = comp0.ToMetadataReference(); comp = CreateCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A2<string?>(); // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 22) ); verifyTypeParameterConstraint("A2", "System.IEquatable<T?>"); // [NullNullTypes(true)] comp0 = CreateCompilation(new[] { source0 }, options: WithNullableEnable()); ref0 = comp0.EmitToImageReference(); comp = CreateCompilation(source, references: new[] { ref0 }); comp.VerifyDiagnostics( // (5,22): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // new A2<string?>(); // 2 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 22) ); verifyTypeParameterConstraint("A2", "System.IEquatable<T?>"); comp = CreateCompilation(source, references: new[] { ref0 }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,16): warning CS8634: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'A2<T>'. Nullability of type argument 'string?' doesn't match 'class' constraint. // new A2<string?>(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "string?").WithArguments("A2<T>", "T", "string?").WithLocation(5, 16), // (5,16): warning CS8631: The type 'string?' cannot be used as type parameter 'T' in the generic type or method 'A2<T>'. Nullability of type argument 'string?' doesn't match constraint type 'System.IEquatable<string?>'. // new A2<string?>(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "string?").WithArguments("A2<T>", "System.IEquatable<string?>", "T", "string?").WithLocation(5, 16) ); verifyTypeParameterConstraint("A2", "System.IEquatable<T?>"); void verifyTypeParameterConstraint(string typeName, string expected) { var type = comp.GetMember<NamedTypeSymbol>(typeName); var constraintType = type.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics[0]; Assert.Equal(expected, constraintType.ToTestDisplayString()); } } [WorkItem(29186, "https://github.com/dotnet/roslyn/issues/29186")] [Fact] public void AttributeArgumentCycle_OtherAttribute() { var source = @"using System; class AAttribute : Attribute { internal AAttribute(object o) { } } interface IA { } interface IB<T> where T : IA { } [A(typeof(IB<IA>))] class C { }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(30178, "https://github.com/dotnet/roslyn/issues/30178")] public void GenericSubstitution_01() { var source = @" #nullable enable class A<T1, T2> where T1 : class where T2 : class { T1 F; #nullable disable class B : A<T1, T2> { #nullable enable void M1() { F = null; // 1 } } void M2() { F = null; // 2 } #nullable disable class C : A<C, C> { #nullable enable void M3() { F = null; // 3 } } #nullable disable class D : A<T1, D> { #nullable enable void M4() { F = null; // 4 } } #nullable disable class E : A<T2, T2> { #nullable enable void M5() { F = null; // 5 } } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (7,8): warning CS8618: Non-nullable field 'F' is uninitialized. Consider declaring the field as nullable. // T1 F; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "F").WithArguments("field", "F").WithLocation(7, 8), // (7,8): warning CS0414: The field 'A<T1, T2>.F' is assigned but its value is never used // T1 F; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A<T1, T2>.F").WithLocation(7, 8), // (15,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 17), // (21,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(21, 13), // (30,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(30, 17), // (40,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(40, 17), // (50,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(50, 17) ); var b = comp.GetTypeByMetadataName("A`2+B"); Assert.NotNull(b); Assert.True(b.BaseTypeNoUseSiteDiagnostics.IsDefinition); } [Fact] [WorkItem(30177, "https://github.com/dotnet/roslyn/issues/30177")] [WorkItem(30178, "https://github.com/dotnet/roslyn/issues/30178")] public void GenericSubstitution_02() { var source = @" #nullable disable class A<T1, T2> where T1 : class where T2 : class { #nullable enable #pragma warning disable 8618 T1 F; #nullable enable class B : A<T1, T2> { void M1() { F = null; // 1 } } #nullable enable void M2() { F = null; // 2 } #nullable enable class C : A<C, C> { void M3() { F = null; // 3 } } #nullable enable class D : A<T1, D> { void M4() { F = null; // 4 } } #nullable enable class E : A<T2, T2> { void M5() { F = null; // 5 } } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (9,8): warning CS0414: The field 'A<T1, T2>.F' is assigned but its value is never used // T1 F; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A<T1, T2>.F").WithLocation(9, 8), // (16,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 17), // (23,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(23, 13), // (31,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(31, 17), // (40,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(40, 17), // (49,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(49, 17)); var b = comp.GetTypeByMetadataName("A`2+B"); Assert.NotNull(b); Assert.False(b.BaseTypeNoUseSiteDiagnostics.IsDefinition); } [Fact] public void GenericSubstitution_03() { var source = @"#nullable disable class A<T> where T : class { class B : A<T> {} } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); var b = comp.GetTypeByMetadataName("A`1+B"); Assert.NotNull(b); Assert.True(b.BaseTypeNoUseSiteDiagnostics.IsDefinition); } [Fact] [WorkItem(30178, "https://github.com/dotnet/roslyn/issues/30178")] public void GenericSubstitution_04() { var source = @"#nullable enable class A<T> where T : class { class B : A<T> {} } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); var b = comp.GetTypeByMetadataName("A`1+B"); Assert.NotNull(b); Assert.False(b.BaseTypeNoUseSiteDiagnostics.IsDefinition); } [Fact] [WorkItem(30178, "https://github.com/dotnet/roslyn/issues/30178")] public void GenericSubstitution_05() { var source = @" #nullable enable class A<T1, T2> where T1 : class where T2 : class { #nullable disable T1 F; #nullable enable class B : A<T1, T2> { void M1() { F = null; // 1 } } void M2() { F = null; // 2 } class C : A<C, C> { void M3() { F = null; // 3 } } class D : A<T1, D> { void M1() { F = null; // 4 } } class E : A<T2, T2> { void M1() { F = null; // 5 } } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (8,8): warning CS0414: The field 'A<T1, T2>.F' is assigned but its value is never used // T1 F; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A<T1, T2>.F").WithLocation(8, 8), // (14,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 17), // (27,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(27, 17), // (35,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(35, 17), // (43,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(43, 17) ); var b = comp.GetTypeByMetadataName("A`2+B"); Assert.NotNull(b); Assert.False(b.BaseTypeNoUseSiteDiagnostics.IsDefinition); } [Fact] [WorkItem(30177, "https://github.com/dotnet/roslyn/issues/30177")] [WorkItem(30178, "https://github.com/dotnet/roslyn/issues/30178")] public void GenericSubstitution_06() { var source = @" #nullable disable class A<T1, T2> where T1 : class where T2 : class { T1 F; #nullable enable class B : A<T1, T2> { void M1() { F = null; // 1 } } #nullable enable void M2() { F = null; } #nullable enable class C : A<C, C> { void M3() { F = null; // 2 } } #nullable enable class D : A<T1, D> { void M3() { F = null; // 3 } } #nullable enable class E : A<T2, T2> { void M3() { F = null; // 4 } } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (7,8): warning CS0414: The field 'A<T1, T2>.F' is assigned but its value is never used // T1 F; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "F").WithArguments("A<T1, T2>.F").WithLocation(7, 8), // (14,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 17), // (29,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(29, 17), // (38,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(38, 17), // (47,17): warning CS8625: Cannot convert null literal to non-nullable reference type. // F = null; // 4 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(47, 17)); var b = comp.GetTypeByMetadataName("A`2+B"); Assert.NotNull(b); Assert.False(b.BaseTypeNoUseSiteDiagnostics.IsDefinition); } [Fact] [WorkItem(35083, "https://github.com/dotnet/roslyn/issues/35083")] public void GenericSubstitution_07() { var source = @" class A { void M1<T>() { } } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics(); var a = comp.GetTypeByMetadataName("A"); var m1 = a.GetMember<MethodSymbol>("M1"); var m11 = new[] { m1.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(a, NullableAnnotation.Annotated))), m1.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(a, NullableAnnotation.NotAnnotated))), m1.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(a, NullableAnnotation.Oblivious))) }; var m12 = new[] { m1.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(a, NullableAnnotation.Annotated))), m1.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(a, NullableAnnotation.NotAnnotated))), m1.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(a, NullableAnnotation.Oblivious))) }; for (int i = 0; i < m11.Length; i++) { var method1 = m11[i]; Assert.True(method1.Equals(method1)); for (int j = 0; j < m12.Length; j++) { var method2 = m12[j]; // always equal by default Assert.True(method1.Equals(method2)); Assert.True(method2.Equals(method1)); // can differ when considering nullability if (i == j) { Assert.True(method1.Equals(method2, SymbolEqualityComparer.IncludeNullability.CompareKind)); Assert.True(method2.Equals(method1, SymbolEqualityComparer.IncludeNullability.CompareKind)); } else { Assert.False(method1.Equals(method2, SymbolEqualityComparer.IncludeNullability.CompareKind)); Assert.False(method2.Equals(method1, SymbolEqualityComparer.IncludeNullability.CompareKind)); } Assert.Equal(method1.GetHashCode(), method2.GetHashCode()); } } } [Fact] [WorkItem(30171, "https://github.com/dotnet/roslyn/issues/30171")] public void NonNullTypesContext_01() { var source = @" using System.Diagnostics.CodeAnalysis; class A { #nullable disable PLACEHOLDER B[] F1; #nullable enable PLACEHOLDER C[] F2; } class B {} class C {} "; var comp1 = CreateCompilation(new[] { source.Replace("PLACEHOLDER", "") }); verify(comp1); var comp2 = CreateCompilation(new[] { source.Replace("PLACEHOLDER", "annotations") }); verify(comp2); void verify(CSharpCompilation comp) { var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B[]", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); var f2 = comp.GetMember<FieldSymbol>("A.F2"); Assert.Equal("C![]!", f2.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); var tree = comp.SyntaxTrees.First(); var model = comp.GetSemanticModel(tree); var arrays = tree.GetRoot().DescendantNodes().OfType<ArrayTypeSyntax>().ToArray(); Assert.Equal(2, arrays.Length); Assert.Equal("B[]", model.GetTypeInfo(arrays[0]).Type.ToTestDisplayString(includeNonNullable: true)); Assert.Equal("C![]", model.GetTypeInfo(arrays[1]).Type.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_02() { var source0 = @" #pragma warning disable CS0169 class A { #nullable enable PLACEHOLDER B #nullable disable PLACEHOLDER F1; } class B {} "; var source1 = source0.Replace("PLACEHOLDER", ""); var source2 = source0.Replace("PLACEHOLDER", "annotations"); assertNonNullTypesContext(source1, NullableContextOptions.Disable); assertNonNullTypesContext(source1, NullableContextOptions.Warnings); assertNonNullTypesContext(source2, NullableContextOptions.Disable); assertNonNullTypesContext(source2, NullableContextOptions.Warnings); void assertNonNullTypesContext(string source, NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_03() { var source = @" #pragma warning disable CS0169 class A { #nullable disable PLACEHOLDER B #nullable enable PLACEHOLDER F1; } class B {} "; verify(source.Replace("PLACEHOLDER", "")); verify(source.Replace("PLACEHOLDER", "annotations")); void verify(string source) { var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_04() { var source0 = @" #pragma warning disable CS0169 class A { B #nullable enable PLACEHOLDER ? F1; } class B {} "; var source1 = source0.Replace("PLACEHOLDER", ""); var source2 = source0.Replace("PLACEHOLDER", "annotations"); assertNonNullTypesContext(source1, NullableContextOptions.Disable); assertNonNullTypesContext(source1, NullableContextOptions.Warnings); assertNonNullTypesContext(source2, NullableContextOptions.Disable); assertNonNullTypesContext(source2, NullableContextOptions.Warnings); void assertNonNullTypesContext(string source, NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_05() { var source = @" #pragma warning disable CS0169 class A { B #nullable disable PLACEHOLDER ? F1; } class B {} "; verify(source.Replace("PLACEHOLDER", "")); verify(source.Replace("PLACEHOLDER", "annotations")); void verify(string source) { var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics( // (8,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // ? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 6) ); } } [Fact] public void NonNullTypesContext_06() { var source0 = @" #pragma warning disable CS0169 class A { #nullable enable PLACEHOLDER string #nullable disable PLACEHOLDER F1; } "; var source1 = source0.Replace("PLACEHOLDER", ""); var source2 = source0.Replace("PLACEHOLDER", "annotations"); assertNonNullTypesContext(source1, NullableContextOptions.Disable); assertNonNullTypesContext(source1, NullableContextOptions.Warnings); assertNonNullTypesContext(source2, NullableContextOptions.Disable); assertNonNullTypesContext(source2, NullableContextOptions.Warnings); void assertNonNullTypesContext(string source, NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("System.String!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_07() { var source = @" #pragma warning disable CS0169 class A { #nullable disable string #nullable enable F1; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("System.String", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_08() { var source = @" #pragma warning disable CS0169 class A { B[ #nullable enable ] #nullable disable F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B[]!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_09() { var source = @" #pragma warning disable CS0169 class A { B[ #nullable disable ] #nullable enable F1; } class B {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B![]", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_10() { var source = @" #pragma warning disable CS0169 class A { (B, B #nullable enable ) #nullable disable F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal(NullableAnnotation.NotAnnotated, f1.TypeWithAnnotations.NullableAnnotation); } } [Fact] public void NonNullTypesContext_11() { var source = @" #pragma warning disable CS0169 class A { (B, B #nullable disable ) #nullable enable F1; } class B {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal(NullableAnnotation.Oblivious, f1.TypeWithAnnotations.NullableAnnotation); } [Fact] public void NonNullTypesContext_12() { var source = @" #pragma warning disable CS0169 class A { B<A #nullable enable > #nullable disable F1; } class B<T> {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B<A>!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_13() { var source = @" #pragma warning disable CS0169 class A { B<A #nullable disable > #nullable enable F1; } class B<T> {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B<A!>", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_14() { var source = @" class A { void M<T>(out T x){} void Test() { M(out #nullable enable var #nullable disable local); } } class var {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single(); Assert.Equal("var!", model.GetDeclaredSymbol(decl.Designation).GetSymbol<LocalSymbol>().TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_15() { var source = @" class A { void M<T>(out T x){} void Test() { M(out #nullable disable var #nullable enable local); } } class var {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var decl = tree.GetRoot().DescendantNodes().OfType<DeclarationExpressionSyntax>().Single(); Assert.Equal("var", model.GetDeclaredSymbol(decl.Designation).GetSymbol<LocalSymbol>().TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_16() { var source = @" class A<T> where T : #nullable enable class #nullable disable { } "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var a = comp.GetTypeByMetadataName("A`1"); Assert.Equal("A<T> where T : class!", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); } } [Fact] public void NonNullTypesContext_17() { var source = @" class A<T> where T : #nullable disable class #nullable enable { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var a = comp.GetTypeByMetadataName("A`1"); Assert.Equal("A<T> where T : class", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); } [Fact] public void NonNullTypesContext_18() { var source = @" class A<T> where T : class #nullable enable ? #nullable disable { } "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var a = comp.GetTypeByMetadataName("A`1"); Assert.Equal("A<T> where T : class?", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier))); Assert.Equal("A<T> where T : class", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_19() { var source = @" class A<T> where T : class #nullable disable ? #nullable enable { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var a = comp.GetTypeByMetadataName("A`1"); Assert.Equal("A<T> where T : class?", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier))); Assert.Equal("A<T> where T : class", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); comp.VerifyDiagnostics( // (4,5): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // ? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 5) ); } [Fact] public void NonNullTypesContext_20() { var source = @" class A<T> where T : #nullable enable unmanaged #nullable disable { } class unmanaged {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var a = comp.GetTypeByMetadataName("A`1"); Assert.Equal("A<T> where T : unmanaged!", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); } } [Fact] public void NonNullTypesContext_21() { var source = @" class A<T> where T : #nullable disable unmanaged #nullable enable { } class unmanaged {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var a = comp.GetTypeByMetadataName("A`1"); Assert.Equal("A<T> where T : unmanaged", a.ToDisplayString(SymbolDisplayFormat.TestFormatWithConstraints.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier))); } [Fact] public void NonNullTypesContext_22() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Enable, type, "A<System.String!>"); } private static void AssertGetSpeculativeTypeInfo(string source, NullableContextOptions nullableContextOptions, TypeSyntax type, string expected) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var decl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); Assert.Equal(expected, model.GetSpeculativeTypeInfo(decl.Identifier.SpanStart, type, SpeculativeBindingOption.BindAsTypeOrNamespace).Type.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_23() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Disable, type, "A<System.String>"); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Warnings, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_24() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable disable A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Enable, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_25() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable enable A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Disable, type, "A<System.String!>"); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Warnings, type, "A<System.String!>"); } [Fact] public void NonNullTypesContext_26() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable disable b; #nullable enable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Enable, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_27() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable enable b; #nullable disable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Disable, type, "A<System.String!>"); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Warnings, type, "A<System.String!>"); } [Fact] public void NonNullTypesContext_28() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable disable b; #nullable enable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable enable A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Enable, type, "A<System.String!>"); } [Fact] public void NonNullTypesContext_29() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable enable b; #nullable disable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable disable A<string> " ); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Disable, type, "A<System.String>"); AssertGetSpeculativeTypeInfo(source, NullableContextOptions.Warnings, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_30() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Enable, type, "A<System.String!>!"); } private static void AssertTryGetSpeculativeSemanticModel(string source, NullableContextOptions nullableContextOptions, TypeSyntax type, string expected) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var decl = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); Assert.True(model.TryGetSpeculativeSemanticModel(decl.Identifier.SpanStart, type, out model, SpeculativeBindingOption.BindAsTypeOrNamespace)); Assert.Equal(expected, model.GetTypeInfo(type).Type.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_31() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Disable, type, "A<System.String>"); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Warnings, type, "A<System.String>!"); } [Fact] public void NonNullTypesContext_32() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable disable A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Enable, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_33() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string b; } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable enable A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Disable, type, "A<System.String!>!"); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Warnings, type, "A<System.String!>!"); } [Fact] public void NonNullTypesContext_34() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable disable b; #nullable enable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Enable, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_35() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable enable b; #nullable disable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Disable, type, "A<System.String!>!"); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Warnings, type, "A<System.String!>!"); } [Fact] public void NonNullTypesContext_36() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable disable b; #nullable enable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable enable A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Enable, type, "A<System.String!>!"); } [Fact] public void NonNullTypesContext_37() { var source = @" #pragma warning disable CS0169 class A<T> { void Tests() { string #nullable enable b; #nullable disable } } "; TypeSyntax type = SyntaxFactory.ParseTypeName( @" #nullable disable A<string> " ); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Disable, type, "A<System.String>"); AssertTryGetSpeculativeSemanticModel(source, NullableContextOptions.Warnings, type, "A<System.String>"); } [Fact] public void NonNullTypesContext_38() { var source = @" using B = C; #pragma warning disable CS0169 class A { #nullable enable B #nullable disable F1; } class C {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("C!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_39() { var source = @" using B = C; #pragma warning disable CS0169 class A { #nullable disable B #nullable enable F1; } class C {} "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("C", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_40() { var source = @" #pragma warning disable CS0169 class A { C. #nullable enable B #nullable disable F1; } namespace C { class B {} } "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("C.B!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_41() { var source = @" #pragma warning disable CS0169 class A { C. #nullable disable B #nullable enable F1; } namespace C { class B {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("C.B", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_42() { var source = @" #pragma warning disable CS0169 class A { C.B<A #nullable enable > #nullable disable F1; } namespace C { class B<T> {} } "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("C.B<A>!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } } [Fact] public void NonNullTypesContext_43() { var source = @" #pragma warning disable CS0169 class A { C.B<A #nullable disable > #nullable enable F1; } namespace C { class B<T> {} } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("C.B<A!>", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); } [Fact] public void NonNullTypesContext_49() { var source = @" #pragma warning disable CS0169 #nullable enable class A { B #nullable restore ? #nullable enable F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics( // (8,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // ? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 6) ); } } [Fact] public void NonNullTypesContext_51() { var source = @" #pragma warning disable CS0169 class A { B #nullable restore ? F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics( // (8,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // ? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 6) ); } } [Fact] public void NonNullTypesContext_52() { var source = @" #pragma warning disable CS0169 #nullable disable class A { B #nullable restore ? #nullable enable F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics( // (8,6): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // ? Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 6) ); } } [Fact] public void NonNullTypesContext_53() { var source = @" #pragma warning disable CS0169 #nullable enable class A { #nullable restore B #nullable enable F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_55() { var source = @" #pragma warning disable CS0169 class A { #nullable restore B F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_56() { var source = @" #pragma warning disable CS0169 #nullable disable class A { #nullable restore B #nullable enable F1; } class B {} "; assertNonNullTypesContext(NullableContextOptions.Disable); assertNonNullTypesContext(NullableContextOptions.Warnings); void assertNonNullTypesContext(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source }, options: compilationOptions); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_57() { var source = @" #pragma warning disable CS0169 #nullable disable class A { B #nullable restore ? #nullable disable F1; } class B {} "; assertType(NullableContextOptions.Enable); void assertType(NullableContextOptions nullableContextOptions) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_58() { var source = @" #pragma warning disable CS0169 #nullable disable class A { B #nullable restore ? #nullable disable F1; } class B {} "; assertType(NullableContextOptions.Enable); void assertType(NullableContextOptions nullableContextOptions) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_59() { var source = @" #pragma warning disable CS0169 class A { B #nullable restore ? F1; } class B {} "; assertType(NullableContextOptions.Enable); void assertType(NullableContextOptions nullableContextOptions) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_60() { var source = @" #pragma warning disable CS0169 #nullable enable class A { B #nullable restore ? #nullable disable F1; } class B {} "; assertType(NullableContextOptions.Enable); void assertType(NullableContextOptions nullableContextOptions) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B?", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_61() { var source = @" #pragma warning disable CS0169 #nullable disable class A { #nullable restore B #nullable disable F1; } class B {} "; assertType(NullableContextOptions.Enable); void assertType(NullableContextOptions nullableContextOptions) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] public void NonNullTypesContext_62() { var source = @" #pragma warning disable CS0169 class A { #nullable restore #pragma warning disable CS8618 B F1; } class B {} "; assertType(NullableContextOptions.Enable); void assertType(NullableContextOptions nullableContextOptions) { var comp = CreateCompilation(new[] { source }, options: WithNullable(nullableContextOptions)); var f1 = comp.GetMember<FieldSymbol>("A.F1"); Assert.Equal("B!", f1.TypeWithAnnotations.ToTestDisplayString(includeNonNullable: true)); comp.VerifyDiagnostics(); } } [Fact] [WorkItem(34843, "https://github.com/dotnet/roslyn/issues/34843")] [WorkItem(34844, "https://github.com/dotnet/roslyn/issues/34844")] public void ObliviousTypeParameter_01() { var source = $@" #pragma warning disable {(int)ErrorCode.WRN_UninitializedNonNullableField} #pragma warning disable {(int)ErrorCode.WRN_UnreferencedField} #pragma warning disable {(int)ErrorCode.WRN_UnreferencedFieldAssg} #pragma warning disable {(int)ErrorCode.WRN_UnreferencedVarAssg} #pragma warning disable {(int)ErrorCode.WRN_UnassignedInternalField} " + @" #nullable disable class A<T1, T2, T3> where T2 : class where T3 : B { T1 F1; T2 F2; T3 F3; B F4; #nullable enable void M1() { F1.ToString(); F2.ToString(); F3.ToString(); F4.ToString(); } #nullable enable void M2() { T1 x2 = default; T2 y2 = default; T3 z2 = default; } #nullable enable void M3() { C.Test<T1>(); C.Test<T2>(); C.Test<T3>(); } #nullable enable void M4() { D.Test(F1); D.Test(F2); D.Test(F3); D.Test(F4); } } class B {} #nullable enable class C { public static void Test<T>() where T : notnull {} } #nullable enable class D { public static void Test<T>(T x) where T : notnull {} } "; var comp = CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (29,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T1 x2 = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(29, 17), // (30,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T2 y2 = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(30, 17), // (31,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T3 z2 = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(31, 17)); } [Fact] [WorkItem(30220, "https://github.com/dotnet/roslyn/issues/30220")] public void ObliviousTypeParameter_02() { var source = $@" #pragma warning disable {(int)ErrorCode.WRN_UnreferencedVar} " + @" #nullable enable class A<T1> where T1 : class { #nullable disable class B<T2> where T2 : T1 { } #nullable enable void M1() { B<T1> a1; B<T1?> b1; A<T1>.B<T1> c1; A<T1>.B<T1?> d1; A<C>.B<C> e1; A<C>.B<C?> f1; } } class C {} "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( // (20,17): warning CS8631: The type 'T1?' cannot be used as type parameter 'T2' in the generic type or method 'A<T1>.B<T2>'. Nullability of type argument 'T1?' doesn't match constraint type 'T1'. // A<T1>.B<T1?> d1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "T1?").WithArguments("A<T1>.B<T2>", "T1", "T2", "T1?").WithLocation(20, 17), // (22,16): warning CS8631: The type 'C?' cannot be used as type parameter 'T2' in the generic type or method 'A<C>.B<T2>'. Nullability of type argument 'C?' doesn't match constraint type 'C'. // A<C>.B<C?> f1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "C?").WithArguments("A<C>.B<T2>", "C", "T2", "C?").WithLocation(22, 16) ); } [Fact] [WorkItem(34842, "https://github.com/dotnet/roslyn/issues/34842")] public void ObliviousTypeParameter_03() { var source = $@"#pragma warning disable {(int)ErrorCode.WRN_UnreferencedFieldAssg} " + @"#nullable disable class A<T1, T2, T3> where T2 : class where T3 : notnull { T1 F1; T2 F2; T3 F3; B F4; #nullable enable void M1() { F1 = default; F2 = default; F2 = null; F3 = default; F4 = default; } } class B { } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( ); } [Fact] [WorkItem(34842, "https://github.com/dotnet/roslyn/issues/34842")] public void ObliviousTypeParameter_04() { var source = @"#nullable disable class A<T1, T2, T3> where T2 : class where T3 : notnull { void M1(T1 x, T2 y, T3 z, B w) #nullable enable { x = default; y = default; y = null; z = default; w = default; } } class B { } "; var comp = CreateCompilation(new[] { source }); comp.VerifyDiagnostics( ); } [WorkItem(23270, "https://github.com/dotnet/roslyn/issues/23270")] [Fact] public void NotNullAfterDereference_00() { var source = @"class Program { static void M(object? obj) { obj.F(); obj.ToString(); // 1 obj.ToString(); } } static class E { internal static void F(this object? obj) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // obj.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "obj").WithLocation(6, 9)); } [WorkItem(23270, "https://github.com/dotnet/roslyn/issues/23270")] [Fact] public void NotNullAfterDereference_01() { var source = @"class Program { static void F(object? x) { x.ToString(); // 1 object? y; y.ToString(); // 2 y = null; y.ToString(); // 3 x.ToString(); y.ToString(); x = y; if (y != null) { x.ToString(); } x.ToString(); y.ToString(); // 4 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(5, 9), // (7,9): error CS0165: Use of unassigned local variable 'y' // y.ToString(); // 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(7, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(18, 9)); } [Fact] public void NotNullAfterDereference_02() { var source = @"class Program { static void F<T>(T x) { x.ToString(); // 1 T y; y.ToString(); // 2 y = default; y.ToString(); // 4 x.ToString(); y.ToString(); x = y; if (y != null) { x.ToString(); } x.ToString(); y.ToString(); // 5 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(5, 9), // (7,9): error CS0165: Use of unassigned local variable 'y' // y.ToString(); // 2 Diagnostic(ErrorCode.ERR_UseDefViolation, "y").WithArguments("y").WithLocation(7, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(18, 9)); } [Fact] public void NotNullAfterDereference_03() { var source = @"class C { void F1(C x) { } static void G1(C? x) { x?.F1(x); x!.F1(x); x.F1(x); } static void G2(bool b, C? y) { y?.F2(y); if (b) y!.F2(y); // 3 y.F2(y); // 4, 5 } } static class E { internal static void F2(this C x, C y) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,22): warning CS8604: Possible null reference argument for parameter 'y' in 'void E.F2(C x, C y)'. // if (b) y!.F2(y); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("y", "void E.F2(C x, C y)").WithLocation(13, 22), // (14,9): warning CS8604: Possible null reference argument for parameter 'x' in 'void E.F2(C x, C y)'. // y.F2(y); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void E.F2(C x, C y)").WithLocation(14, 9), // (14,14): warning CS8604: Possible null reference argument for parameter 'y' in 'void E.F2(C x, C y)'. // y.F2(y); // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("y", "void E.F2(C x, C y)").WithLocation(14, 14)); } [Fact] public void NotNullAfterDereference_04() { var source = @"class Program { static void F<T>(bool b, string? s) { int n; if (b) { n = s/*T:string?*/.Length; // 1 n = s/*T:string!*/.Length; } n = b ? s/*T:string?*/.Length + // 2 s/*T:string!*/.Length : 0; n = s/*T:string?*/.Length; // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,17): warning CS8602: Dereference of a possibly null reference. // n = s/*T:string?*/.Length; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 17), // (12,17): warning CS8602: Dereference of a possibly null reference. // n = b ? s/*T:string?*/.Length + // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 17), // (14,13): warning CS8602: Dereference of a possibly null reference. // n = s/*T:string?*/.Length; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 13)); comp.VerifyTypes(); } [Fact] public void NotNullAfterDereference_05() { var source = @"class Program { static void F(string? s) { int n; try { n = s/*T:string?*/.Length; // 1 try { n = s/*T:string!*/.Length; } finally { n = s/*T:string!*/.Length; } } catch (System.IO.IOException) { n = s/*T:string?*/.Length; // 2 } catch { n = s/*T:string?*/.Length; // 3 } finally { n = s/*T:string?*/.Length; // 4 } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,17): warning CS8602: Dereference of a possibly null reference. // n = s/*T:string?*/.Length; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(8, 17), // (20,17): warning CS8602: Dereference of a possibly null reference. // n = s/*T:string?*/.Length; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(20, 17), // (24,17): warning CS8602: Dereference of a possibly null reference. // n = s/*T:string?*/.Length; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(24, 17), // (28,17): warning CS8602: Dereference of a possibly null reference. // n = s/*T:string?*/.Length; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(28, 17)); comp.VerifyTypes(); } [Fact] public void NotNullAfterDereference_06() { var source = @"class C { object F = default!; static void G(C? c) { c.F = c; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // One warning only, rather than one warning for dereference of c.F // and another warning for assignment c.F = c. comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // c.F = c; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(6, 9)); } [Fact] public void NotNullAfterDereference_Call() { var source = @"#pragma warning disable 0649 class C { object? y; void F(object? o) { } static void G(C? x) { x.F(x = null); // 1 x.F(x.y); // 2, 3 x.F(x.y); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for x.F(x.y). comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // x.F(x = null); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // x.F(x.y); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 9)); } [Fact] public void NotNullAfterDereference_Array() { var source = @"class Program { static int F(object? o) => 0; static void G(object[]? x, object[] y) { object z; z = x[F(x = null)]; // 1 z = x[x.Length]; // 2, 3 z = x[x.Length]; y[F(y = null)] = 1; y[y.Length] = 2; // 4, 5 y[y.Length] = 3; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for x[x.Length] and y[y.Length]. comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // z = x[F(x = null)]; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 13), // (8,13): warning CS8602: Dereference of a possibly null reference. // z = x[x.Length]; // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13), // (10,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // y[F(y = null)] = 1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(10, 17), // (11,9): warning CS8602: Dereference of a possibly null reference. // y[y.Length] = 2; // 4, 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 9)); } [Fact] public void NotNullAfterDereference_Indexer() { var source = @"#pragma warning disable 0649 class C { object? F; object this[object? o] { get { return 1; } set { } } static void G(C? x, C y) { object z; z = x[x = null]; // 1 z = x[x.F]; // 2 z = x[x.F]; y[y = null] = 1; // 3 y[y.F] = 2; // 4 y[y.F] = 3; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for x[x.F] and y[y.F]. comp.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // z = x[x = null]; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // z = x[x.F]; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(14, 13), // (16,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // y[y = null] = 1; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 15), // (17,9): warning CS8602: Dereference of a possibly null reference. // y[y.F] = 2; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(17, 9) ); } [Fact] public void NotNullAfterDereference_Field() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C { object? F; static object? G(object? o) => o; static void M(C? x, C? y) { object? o; o = x.F; // 1 o = x.F; y.F = G(y = null); // 2 y.F = G(y.F); // 3, 4 y.F = G(y.F); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for y.F = G(y.F). comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // o = x.F; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 13), // (12,9): warning CS8602: Dereference of a possibly null reference. // y.F = G(y = null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.F = G(y.F); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(13, 9)); } [Fact] public void NotNullAfterDereference_Property() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C { object? P { get; set; } static object? F(object? o) => o; static void M(C? x, C? y) { object? o; o = x.P; // 1 o = x.P; y.P = F(y = null); // 2 y.P = F(y.P); // 3, 4 y.P = F(y.P); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for y.P = F(y.P). comp.VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // o = x.F; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 13), // (12,9): warning CS8602: Dereference of a possibly null reference. // y.F = G(y = null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.F = G(y.F); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(13, 9)); } [Fact] public void NotNullAfterDereference_Event() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 delegate void D(); class C { event D E; D F; static D G(C? c) => throw null!; static void M(C? x, C? y, C? z) { x.E(); // 1 x.E(); y.E += G(y = null); // 2 y.E += y.F; // 3, 4 y.E += y.F; y.E(); z.E = null; // 5 z.E(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for y.E += y.F. comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // x.E(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.E += G(y = null); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // y.E += y.F; // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(14, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // z.E = null; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(17, 9), // (17,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // z.E = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(17, 15), // (18,9): warning CS8602: Dereference of a possibly null reference. // z.E(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.E").WithLocation(18, 9)); } [Fact] public void NotNullAfterDereference_Dynamic() { var source = @"class Program { static void F(dynamic? d) { d.ToString(); // 1 d.ToString(); } static void G(dynamic? x, dynamic? y) { object z; z = x[x = null]; // 2 z = x[x.F]; // 3, 4 z = x[x.F]; y[y = null] = 1; y[y.F] = 2; // 5, 6 y[y.F] = 3; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/30598: Should report two warnings for x[x.F] and y[y.F]. comp.VerifyDiagnostics( // (5,9): warning CS8602: Dereference of a possibly null reference. // d.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d").WithLocation(5, 9), // (11,13): warning CS8602: Dereference of a possibly null reference. // z = x[x = null]; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(11, 13), // (12,13): warning CS8602: Dereference of a possibly null reference. // z = x[x.F]; // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(12, 13), // (14,9): warning CS8602: Dereference of a possibly null reference. // y[y = null] = 1; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // y[y.F] = 2; // 5, 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(15, 9)); } [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] [Fact] public void NotNullAfterDereference_MethodGroup_01() { var source = @"delegate void D(); class C { void F1() { } static void F(C? x, C? y) { D d; d = x.F1; // warning d = y.F2; // ok } } static class E { internal static void F2(this C? c) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // d = x.F1; // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 13)); } [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] [Fact] public void NotNullAfterDereference_MethodGroup_02() { var source = @"delegate void D1(int i); delegate void D2(); class C { void F(int i) { } static void F1(D1 d) { } static void F2(D2 d) { } static void G(C? x, C? y) { F1(x.F); // 1 (x.F is a member method group) F1(x.F); F2(y.F); // 2 (y.F is an extension method group) F2(y.F); } } static class E { internal static void F(this C x) { } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,12): warning CS8602: Dereference of a possibly null reference. // F1(x.F); // 1 (x.F is a member method group) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 12), // (12,12): warning CS8604: Possible null reference argument for parameter 'x' in 'void E.F(C x)'. // F2(y.F); // 2 (y.F is an extension method group) Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void E.F(C x)").WithLocation(12, 12)); } [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] [Fact] public void MethodGroupReinferredAfterReceiver() { var source = @"public class C { G<T> CreateG<T>(T t) => new G<T>(); void Main(string? s1, string? s2) { Run(CreateG(s1).M, s2)/*T:(string?, string?)*/; if (s1 == null) return; Run(CreateG(s1).M, s2)/*T:(string!, string?)*/; if (s2 == null) return; Run(CreateG(s1).M, s2)/*T:(string!, string!)*/; } (T, U) Run<T, U>(MyDelegate<T, U> del, U u) => del(u); } public class G<T> { public T t = default(T)!; public (T, U) M<U>(U u) => (t, u); } public delegate (T, U) MyDelegate<T, U>(U u); "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(33638, "https://github.com/dotnet/roslyn/issues/33638")] [Fact] public void TupleFromNestedGenerics() { var source = @"public class G<T> { public (T, U) M<U>(T t, U u) => (t, u); } public class C { public (T, U) M<T, U>(T t, U u) => (t, u); } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [WorkItem(30562, "https://github.com/dotnet/roslyn/issues/30562")] [Fact] public void NotNullAfterDereference_ForEach() { var source = @"class Enumerable { public System.Collections.IEnumerator GetEnumerator() => throw null!; } class Program { static void F1(object[]? x1, object[]? y1) { foreach (var x in x1) { } // 1 foreach (var x in x1) { } } static void F2(object[]? x1, object[]? y1) { foreach (var y in y1) { } // 2 y1.GetEnumerator(); } static void F3(Enumerable? x2, Enumerable? y2) { foreach (var x in x2) { } // 3 foreach (var x in x2) { } } static void F4(Enumerable? x2, Enumerable? y2) { y2.GetEnumerator(); // 4 foreach (var y in y2) { } } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in x1) { } // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(9, 27), // (14,27): warning CS8602: Dereference of a possibly null reference. // foreach (var y in y1) { } // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(14, 27), // (19,27): warning CS8602: Dereference of a possibly null reference. // foreach (var x in x2) { } // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(19, 27), // (24,9): warning CS8602: Dereference of a possibly null reference. // y2.GetEnumerator(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(24, 9)); } [Fact] public void SpecialAndWellKnownMemberLookup() { var source0 = @" namespace System { public class Object { } public abstract class ValueType { } public struct Void { } public struct Int32 { } public class Type { } public struct Boolean { } public struct Enum { } public class Attribute { } public struct Nullable<T> { public static implicit operator Nullable<T>(T x) { throw null!; } public static explicit operator T(Nullable<T> x) { throw null!; } } namespace Collections.Generic { public class EqualityComparer<T> { public static EqualityComparer<T> Default => throw null!; } } } "; var comp = CreateEmptyCompilation(new[] { source0 }, options: WithNullableEnable()); var implicitOp = comp.GetSpecialTypeMember(SpecialMember.System_Nullable_T__op_Implicit_FromT); var explicitOp = comp.GetSpecialTypeMember(SpecialMember.System_Nullable_T__op_Explicit_ToT); var getDefault = comp.GetWellKnownTypeMember(WellKnownMember.System_Collections_Generic_EqualityComparer_T__get_Default); Assert.NotNull(implicitOp); Assert.NotNull(explicitOp); Assert.NotNull(getDefault); Assert.True(implicitOp.IsDefinition); Assert.True(explicitOp.IsDefinition); Assert.True(getDefault.IsDefinition); } [Fact] public void ExpressionTrees_ByRefDynamic() { string source = @" using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Action<dynamic>> e = x => Goo(ref x); } static void Goo<T>(ref T x) { } } "; CompileAndVerify(source, targetFramework: TargetFramework.StandardAndCSharp, options: WithNullableEnable()); } [Fact] [WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")] public void TypeSymbolGetHashCode_Annotated() { var text = @" class C<T> where T : class { C<T?> M() => throw null!; } "; var comp = CreateNullableCompilation(text); var type = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal("C<T>", type.ToTestDisplayString(includeNonNullable: true)); Assert.True(type.IsDefinition); var type2 = comp.GetMember<MethodSymbol>("C.M").ReturnType; Assert.Equal("C<T?>", type2.ToTestDisplayString(includeNonNullable: true)); Assert.False(type2.IsDefinition); AssertHashCodesMatch(type, type2); } [Fact] [WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")] public void TypeSymbolGetHashCode_NotAnnotated() { var text = @" class C<T> where T : class { C<T> M() => throw null!; } "; var comp = CreateNullableCompilation(text); var type = comp.GetMember<NamedTypeSymbol>("C"); Assert.Equal("C<T>", type.ToTestDisplayString(includeNonNullable: true)); Assert.True(type.IsDefinition); var type2 = comp.GetMember<MethodSymbol>("C.M").ReturnType; Assert.Equal("C<T!>", type2.ToTestDisplayString(includeNonNullable: true)); Assert.False(type2.IsDefinition); AssertHashCodesMatch(type, type2); } [Fact] [WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")] public void TypeSymbolGetHashCode_ContainingType() { var text = @" class C<T> where T : class { interface I { } } "; var comp = CreateNullableCompilation(text); var iDefinition = comp.GetMember<NamedTypeSymbol>("C.I"); Assert.Equal("C<T>.I", iDefinition.ToTestDisplayString(includeNonNullable: true)); Assert.True(iDefinition.IsDefinition); var cDefinition = iDefinition.ContainingType; Assert.Equal("C<T>", cDefinition.ToTestDisplayString(includeNonNullable: true)); Assert.True(cDefinition.IsDefinition); var c2 = cDefinition.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(cDefinition.TypeParameters.Single(), NullableAnnotation.NotAnnotated))); Assert.Equal("C<T!>", c2.ToTestDisplayString(includeNonNullable: true)); Assert.False(c2.IsDefinition); AssertHashCodesMatch(cDefinition, c2); var i2 = c2.GetTypeMember("I"); Assert.Equal("C<T!>.I", i2.ToTestDisplayString(includeNonNullable: true)); Assert.False(i2.IsDefinition); AssertHashCodesMatch(iDefinition, i2); var c3 = cDefinition.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(cDefinition.TypeParameters.Single(), NullableAnnotation.Annotated))); Assert.Equal("C<T?>", c3.ToTestDisplayString(includeNonNullable: true)); Assert.False(c3.IsDefinition); AssertHashCodesMatch(cDefinition, c3); var i3 = c3.GetTypeMember("I"); Assert.Equal("C<T?>.I", i3.ToTestDisplayString(includeNonNullable: true)); Assert.False(i3.IsDefinition); AssertHashCodesMatch(iDefinition, i3); } [Fact] [WorkItem(30673, "https://github.com/dotnet/roslyn/issues/30673")] public void TypeSymbolGetHashCode_ContainingType_GenericNestedType() { var text = @" class C<T> where T : class { interface I<U> where U : class { } } "; var comp = CreateNullableCompilation(text); var iDefinition = comp.GetMember<NamedTypeSymbol>("C.I"); Assert.Equal("C<T>.I<U>", iDefinition.ToTestDisplayString(includeNonNullable: true)); Assert.True(iDefinition.IsDefinition); // Construct from iDefinition with annotated U from iDefinition var i1 = iDefinition.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(iDefinition.TypeParameters.Single(), NullableAnnotation.Annotated))); Assert.Equal("C<T>.I<U?>", i1.ToTestDisplayString(includeNonNullable: true)); AssertHashCodesMatch(iDefinition, i1); var cDefinition = iDefinition.ContainingType; Assert.Equal("C<T>", cDefinition.ToTestDisplayString(includeNonNullable: true)); Assert.True(cDefinition.IsDefinition); // Construct from cDefinition with unannotated T from cDefinition var c2 = cDefinition.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(cDefinition.TypeParameters.Single(), NullableAnnotation.NotAnnotated))); var i2 = c2.GetTypeMember("I"); Assert.Equal("C<T!>.I<U>", i2.ToTestDisplayString(includeNonNullable: true)); Assert.Same(i2.OriginalDefinition, iDefinition); AssertHashCodesMatch(i2, iDefinition); // Construct from i2 with U from iDefinition var i2a = i2.Construct(iDefinition.TypeParameters.Single()); Assert.Equal("C<T!>.I<U>", i2a.ToTestDisplayString(includeNonNullable: true)); AssertHashCodesMatch(iDefinition, i2a); // Construct from i2 with annotated U from iDefinition var i2b = i2.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(iDefinition.TypeParameters.Single(), NullableAnnotation.Annotated))); Assert.Equal("C<T!>.I<U?>", i2b.ToTestDisplayString(includeNonNullable: true)); AssertHashCodesMatch(iDefinition, i2b); // Construct from i2 with U from i2 var i2c = i2.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(i2.TypeParameters.Single(), NullableAnnotation.Annotated))); Assert.Equal("C<T!>.I<U?>", i2c.ToTestDisplayString(includeNonNullable: true)); AssertHashCodesMatch(iDefinition, i2c); var c3 = cDefinition.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(cDefinition.TypeParameters.Single(), NullableAnnotation.Annotated))); var i3 = c3.GetTypeMember("I"); Assert.Equal("C<T?>.I<U>", i3.ToTestDisplayString(includeNonNullable: true)); AssertHashCodesMatch(iDefinition, i3); var i3b = i3.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(i3.TypeParameters.Single(), NullableAnnotation.Annotated))); Assert.Equal("C<T?>.I<U?>", i3b.ToTestDisplayString(includeNonNullable: true)); AssertHashCodesMatch(iDefinition, i3b); // Construct from cDefinition with modified T from cDefinition var modifiers = ImmutableArray.Create(CSharpCustomModifier.CreateOptional(comp.GetSpecialType(SpecialType.System_Object))); var c4 = cDefinition.Construct(ImmutableArray.Create(TypeWithAnnotations.Create(cDefinition.TypeParameters.Single(), customModifiers: modifiers))); Assert.Equal("C<T modopt(System.Object)>", c4.ToTestDisplayString()); Assert.False(c4.IsDefinition); Assert.False(cDefinition.Equals(c4, TypeCompareKind.ConsiderEverything)); Assert.False(cDefinition.Equals(c4, TypeCompareKind.CLRSignatureCompareOptions)); Assert.True(cDefinition.Equals(c4, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)); Assert.Equal(cDefinition.GetHashCode(), c4.GetHashCode()); var i4 = c4.GetTypeMember("I"); Assert.Equal("C<T modopt(System.Object)>.I<U>", i4.ToTestDisplayString()); Assert.Same(i4.OriginalDefinition, iDefinition); Assert.False(iDefinition.Equals(i4, TypeCompareKind.ConsiderEverything)); Assert.False(iDefinition.Equals(i4, TypeCompareKind.CLRSignatureCompareOptions)); Assert.True(iDefinition.Equals(i4, TypeCompareKind.IgnoreCustomModifiersAndArraySizesAndLowerBounds)); Assert.Equal(iDefinition.GetHashCode(), i4.GetHashCode()); } private static void AssertHashCodesMatch(TypeSymbol c, TypeSymbol c2) { Assert.True(c.Equals(c2)); Assert.True(c.Equals(c2, SymbolEqualityComparer.Default.CompareKind)); Assert.False(c.Equals(c2, SymbolEqualityComparer.ConsiderEverything.CompareKind)); Assert.True(c.Equals(c2, TypeCompareKind.AllIgnoreOptions)); Assert.Equal(c2.GetHashCode(), c.GetHashCode()); } [Fact] [WorkItem(35619, "https://github.com/dotnet/roslyn/issues/35619")] public void ExplicitInterface_UsingOuterDefinition_Simple() { var text = @" class Outer<T> { protected internal interface Interface { void Method(); } internal class C : Outer<T>.Interface { void Interface.Method() { } } } "; var comp = CreateNullableCompilation(text); comp.VerifyDiagnostics(); } [Fact] [WorkItem(35619, "https://github.com/dotnet/roslyn/issues/35619")] public void ExplicitInterface_UsingOuterDefinition() { var text = @" class Outer<T> where T : class { internal class Inner<U> where U : class { protected internal interface Interface { void Method(); } // The implemented interface is Outer<T!>.Inner<U!>.Interface internal class Derived6 : Outer<T>.Inner<U>.Interface { // The explicit interface is Outer<T>.Inner<U!>.Interface void Inner<U>.Interface.Method() { } } } } "; CreateCompilation(text, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(35619, "https://github.com/dotnet/roslyn/issues/35619")] public void ExplicitInterface_WithExplicitOuter() { var text = @" class Outer<T> where T : class { internal class Inner<U> where U : class { protected internal interface Interface { void Method(); } // The implemented interface is Outer<T!>.Inner<U!>.Interface internal class Derived6 : Outer<T>.Inner<U>.Interface { // The explicit interface is Outer<T!>.Inner<U!>.Interface void Outer<T>.Inner<U>.Interface.Method() { } } } } "; CreateCompilation(text, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] public void ExplicitInterface_WithExplicitOuter_DisabledT() { var text = @" class Outer<T> where T : class { internal class Inner<U> where U : class { protected internal interface Interface { void Method(); } // The implemented interface is Outer<T!>.Inner<U!>.Interface internal class Derived6 : Outer<T>.Inner<U>.Interface { // The explicit interface is Outer<T~>.Inner<U!>.Interface void Outer< #nullable disable T #nullable enable >.Inner<U>.Interface.Method() { } } } } "; CreateCompilation(text, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] public void ExplicitInterface_WithExplicitOuter_DisabledT_ImplementedInterfaceMatches() { var text = @" class Outer<T> where T : class { internal class Inner<U> where U : class { protected internal interface Interface { void Method(); } // The implemented interface is Outer<T~>.Inner<U!>.Interface internal class Derived6 : Inner<U>.Interface { // The explicit interface is Outer<T~>.Inner<U!>.Interface void Outer< #nullable disable T #nullable enable >.Inner<U>.Interface.Method() { } } } } "; CreateCompilation(text, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] public void TestErrorsImplementingGenericNestedInterfaces_Explicit() { var text = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { T Property { set; } void Method<Z>(T a, U[] b, List<V> c, Dictionary<W, Z> d); } internal class Derived4 { internal class Derived5 : Outer<T>.Inner<U>.Interface<U, T> { T Outer<T>.Inner<U>.Interface<U, T>.Property { set { } } void Inner<U>.Interface<U, T>.Method<K>(T a, U[] b, List<U> c, Dictionary<K, T> D) { } } internal class Derived6 : Outer<T>.Inner<U>.Interface<U, T> { T Outer<T>.Inner<U>.Interface<U, T>.Property { set { } } void Inner<U>.Interface<U, T>.Method<K>(T a, U[] b, List<U> c, Dictionary<T, K> D) { } } } } } "; CreateCompilation(text, options: WithNullableEnable()).VerifyDiagnostics( // (14,39): error CS0535: 'Outer<T>.Inner<U>.Derived4.Derived5' does not implement interface member 'Outer<T>.Inner<U>.Interface<U, T>.Method<Z>(T, U[], List<U>, Dictionary<T, Z>)' // internal class Derived5 : Outer<T>.Inner<U>.Interface<U, T> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "Outer<T>.Inner<U>.Interface<U, T>").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5", "Outer<T>.Inner<U>.Interface<U, T>.Method<Z>(T, U[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<T, Z>)").WithLocation(14, 39), // (20,47): error CS0539: 'Outer<T>.Inner<U>.Derived4.Derived5.Method<K>(T, U[], List<U>, Dictionary<K, T>)' in explicit interface declaration is not found among members of the interface that can be implemented // void Inner<U>.Interface<U, T>.Method<K>(T a, U[] b, List<U> c, Dictionary<K, T> D) Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Method").WithArguments("Outer<T>.Inner<U>.Derived4.Derived5.Method<K>(T, U[], System.Collections.Generic.List<U>, System.Collections.Generic.Dictionary<K, T>)").WithLocation(20, 47) ); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] public void TestErrorsImplementingGenericNestedInterfaces_Explicit_IncorrectPartialQualification() { var source = @" using System.Collections.Generic; class Outer<T> { internal class Inner<U> { protected internal interface Interface<V, W> { T Property { set; } void Method<Z>(T a, U[] b, List<V> c, Dictionary<W, Z> d); } internal class Derived3 : Interface<long, string> { T Interface<long, string>.Property { set { } } void Inner<U>.Interface<long, string>.Method<K>(T a, U[] B, List<long> C, Dictionary<string, K> d) { } } } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_01() { var source1 = @" public interface I1<I1T1, I1T2> { void M(); } public interface I2<I2T1, I2T2> : I1<I2T1, I2T2> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2> { void I1<CT1, CT2>.M() { } }"; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_02() { var source1 = @" public interface I1<I1T1> { void M(); } public struct S<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<S<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2> { void I1<S<CT1, CT2>>.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_03() { var source1 = @" public interface I1<I1T1> { void M(); } public class C1<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<C1<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2> { void I1<C1<CT1, CT2>>.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_04() { var source1 = @" public interface I1<I1T1> { void M(); } public class C1<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<C1<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2>, I1<C1<CT1, CT2>> { void I1<C1<CT1, CT2>>.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_05() { var source1 = @" public interface I1<I1T1> { void M(); } public struct S<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<S<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2> { void I1<S<CT1, CT2 #nullable disable > #nullable enable >.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_06() { var source1 = @" public interface I1<I1T1> { void M(); } public class C1<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<C1<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2> { void I1<C1<CT1, CT2 #nullable disable > #nullable enable >.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_07() { var source1 = @" public interface I1<I1T1> { void M(); } public interface I2<I2T1, I2T2> : I1<(I2T1, I2T2)> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2> { void I1<(CT1 a, CT2 b)>.M() { } } "; var expected = new DiagnosticDescription[] { // (4,10): error CS0540: 'C<CT1, CT2>.I1<(CT1 a, CT2 b)>.M()': containing type does not implement interface 'I1<(CT1 a, CT2 b)>' // void I1<(CT1 a, CT2 b)>.M() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<(CT1 a, CT2 b)>").WithArguments("C<CT1, CT2>.I1<(CT1 a, CT2 b)>.M()", "I1<(CT1 a, CT2 b)>").WithLocation(4, 10) }; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(expected); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(expected); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_08() { var source1 = @" public interface I1<I1T1> { void M(); } public interface I2<I2T1, I2T2> : I1<(I2T1, I2T2)> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2>, I1<(CT1 a, CT2 b)> { void I1<(CT1 c, CT2 d)>.M() { } } "; var expected = new DiagnosticDescription[] { // (2,7): error CS8140: 'I1<(CT1 a, CT2 b)>' is already listed in the interface list on type 'C<CT1, CT2>' with different tuple element names, as 'I1<(CT1, CT2)>'. // class C<CT1, CT2> : I2<CT1, CT2>, I1<(CT1 a, CT2 b)> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I1<(CT1 a, CT2 b)>", "I1<(CT1, CT2)>", "C<CT1, CT2>").WithLocation(2, 7), // (4,10): error CS0540: 'C<CT1, CT2>.I1<(CT1 c, CT2 d)>.M()': containing type does not implement interface 'I1<(CT1 c, CT2 d)>' // void I1<(CT1 c, CT2 d)>.M() Diagnostic(ErrorCode.ERR_ClassDoesntImplementInterface, "I1<(CT1 c, CT2 d)>").WithArguments("C<CT1, CT2>.I1<(CT1 c, CT2 d)>.M()", "I1<(CT1 c, CT2 d)>").WithLocation(4, 10) }; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(expected); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(expected); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_09() { var source1 = @" public interface I1<I1T1> { void M(); } public class C1<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<C1<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2>, #nullable disable I1<C1<CT1, CT2>> #nullable enable { void I1<C1<CT1, CT2>>.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] [WorkItem(30677, "https://github.com/dotnet/roslyn/issues/30677")] [WorkItem(31858, "https://github.com/dotnet/roslyn/issues/31858")] public void ExplicitInterfaceImplementation_10() { var source1 = @" public interface I1<I1T1> { void M(); } public class C1<ST1, ST2> { } public interface I2<I2T1, I2T2> : I1<C1<I2T1, I2T2>> { } "; var comp1 = CreateCompilation(source1, options: WithNullableDisable()); comp1.VerifyDiagnostics(); var source2 = @" class C<CT1, CT2> : I2<CT1, CT2>, I1<C1<CT1, CT2 #nullable disable > #nullable enable > { void I1<C1<CT1, CT2>>.M() { } } "; var comp2 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.EmitToImageReference() }); comp2.VerifyDiagnostics(); var comp3 = CreateCompilation(source2, options: WithNullableEnable(), references: new[] { comp1.ToMetadataReference() }); comp3.VerifyDiagnostics(); } [Fact] public void WriteOfReadonlyStaticMemberOfAnotherInstantiation01() { var text = @"public static class Goo<T> { static Goo() { Goo<T>.Y = 3; } public static int Y { get; } }"; CreateCompilation(text, options: WithNullableEnable(TestOptions.ReleaseDll)).VerifyEmitDiagnostics(); CreateCompilation(text, options: WithNullableEnable(TestOptions.ReleaseDll), parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyEmitDiagnostics(); } [Fact] public void TestOverrideGenericMethodWithTypeParamDiffNameWithCustomModifiers() { var text = @" namespace Metadata { using System; public class GD : Outer<string>.Inner<ulong> { public override void Method<X>(string[] x, ulong[] y, X[] z) { Console.Write(""Hello {0}"", z.Length); } static void Main() { new GD().Method<byte>(null, null, new byte[] { 0, 127, 255 }); } } } "; var verifier = CompileAndVerify( text, new[] { TestReferences.SymbolsTests.CustomModifiers.Modifiers.dll }, options: WithNullableEnable(TestOptions.ReleaseExe), expectedOutput: @"Hello 3", expectedSignatures: new[] { // The ILDASM output is following, and Roslyn handles it correctly. // Verifier tool gives different output due to the limitation of Reflection // @".method public hidebysig virtual instance System.Void Method<X>(" + // @"System.String modopt([mscorlib]System.Runtime.CompilerServices.IsConst)[] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) x," + // @"UInt64 modopt([mscorlib]System.Runtime.CompilerServices.IsConst)[] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) y," + // @"!!X modopt([mscorlib]System.Runtime.CompilerServices.IsConst)[] modopt([mscorlib]System.Runtime.CompilerServices.IsConst) z) cil managed") Signature("Metadata.GD", "Method", @".method public hidebysig virtual instance System.Void Method<X>(" + @"modopt(System.Runtime.CompilerServices.IsConst) System.String[] x, " + @"modopt(System.Runtime.CompilerServices.IsConst) System.UInt64[] y, "+ @"modopt(System.Runtime.CompilerServices.IsConst) X[] z) cil managed"), }, symbolValidator: module => { var expected = @"[NullableContext(1)] [Nullable({ 0, 1 })] Metadata.GD void Method<X>(System.String![]! x, System.UInt64[]! y, X[]! z) [Nullable(0)] X System.String![]! x System.UInt64[]! y X[]! z GD() "; var actual = NullableAttributesVisitor.GetString((PEModuleSymbol)module); AssertEx.AssertEqualToleratingWhitespaceDifferences(expected, actual); }); } [Fact] [WorkItem(30747, "https://github.com/dotnet/roslyn/issues/30747")] public void MissingTypeKindBasisTypes() { var source1 = @" public struct A {} public enum B {} public class C {} public delegate void D(); public interface I1 {} "; var compilation1 = CreateEmptyCompilation(source1, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { MinCorlibRef }); compilation1.VerifyEmitDiagnostics(); Assert.Equal(TypeKind.Struct, compilation1.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation1.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation1.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation1.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation1.GetTypeByMetadataName("I1").TypeKind); var source2 = @" interface I2 { I1 M(A a, B b, C c, D d); } "; var compilation2 = CreateEmptyCompilation(source2, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { compilation1.EmitToImageReference(), MinCorlibRef }); compilation2.VerifyEmitDiagnostics(); // Verification against a corlib not named exactly mscorlib is expected to fail. CompileAndVerify(compilation2, verify: Verification.Fails); Assert.Equal(TypeKind.Struct, compilation2.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation2.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation2.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation2.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation2.GetTypeByMetadataName("I1").TypeKind); var compilation3 = CreateEmptyCompilation(source2, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { compilation1.ToMetadataReference(), MinCorlibRef }); compilation3.VerifyEmitDiagnostics(); CompileAndVerify(compilation3, verify: Verification.Fails); Assert.Equal(TypeKind.Struct, compilation3.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation3.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation3.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation3.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation3.GetTypeByMetadataName("I1").TypeKind); var compilation4 = CreateEmptyCompilation(source2, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { compilation1.EmitToImageReference() }); compilation4.VerifyDiagnostics( // (4,10): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "A").WithArguments("System.ValueType", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 10), // (4,15): error CS0012: The type 'Enum' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("System.Enum", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 15), // (4,25): error CS0012: The type 'MulticastDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.MulticastDelegate", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 25) ); var a = compilation4.GetTypeByMetadataName("A"); var b = compilation4.GetTypeByMetadataName("B"); var c = compilation4.GetTypeByMetadataName("C"); var d = compilation4.GetTypeByMetadataName("D"); var i1 = compilation4.GetTypeByMetadataName("I1"); Assert.Equal(TypeKind.Class, a.TypeKind); Assert.NotNull(a.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, b.TypeKind); Assert.NotNull(b.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, c.TypeKind); Assert.Null(c.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, d.TypeKind); Assert.NotNull(d.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Interface, i1.TypeKind); Assert.Null(i1.GetUseSiteDiagnostic()); var compilation5 = CreateEmptyCompilation(source2, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { compilation1.ToMetadataReference() }); compilation5.VerifyEmitDiagnostics( // 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), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1), // error CS0518: Predefined type 'System.Attribute' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Attribute").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute..ctor' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", ".ctor").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.AllowMultiple' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "AllowMultiple").WithLocation(1, 1), // error CS0656: Missing compiler required member 'System.AttributeUsageAttribute.Inherited' Diagnostic(ErrorCode.ERR_MissingPredefinedMember).WithArguments("System.AttributeUsageAttribute", "Inherited").WithLocation(1, 1), // error CS0518: Predefined type 'System.Byte' is not defined or imported Diagnostic(ErrorCode.ERR_PredefinedTypeNotFound).WithArguments("System.Byte").WithLocation(1, 1)); var compilation6 = CreateEmptyCompilation(source2, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { compilation1.EmitToImageReference(), MscorlibRef }); compilation6.VerifyDiagnostics( // (4,10): error CS0012: The type 'ValueType' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "A").WithArguments("System.ValueType", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 10), // (4,15): error CS0012: The type 'Enum' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "B").WithArguments("System.Enum", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 15), // (4,25): error CS0012: The type 'MulticastDelegate' is defined in an assembly that is not referenced. You must add a reference to assembly 'mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2'. // I1 M(A a, B b, C c, D d); Diagnostic(ErrorCode.ERR_NoTypeDef, "D").WithArguments("System.MulticastDelegate", "mincorlib, Version=0.0.0.0, Culture=neutral, PublicKeyToken=ce65828c82a341f2").WithLocation(4, 25) ); a = compilation6.GetTypeByMetadataName("A"); b = compilation6.GetTypeByMetadataName("B"); c = compilation6.GetTypeByMetadataName("C"); d = compilation6.GetTypeByMetadataName("D"); i1 = compilation6.GetTypeByMetadataName("I1"); Assert.Equal(TypeKind.Class, a.TypeKind); Assert.NotNull(a.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, b.TypeKind); Assert.NotNull(b.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, c.TypeKind); Assert.Null(c.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Class, d.TypeKind); Assert.NotNull(d.GetUseSiteDiagnostic()); Assert.Equal(TypeKind.Interface, i1.TypeKind); Assert.Null(i1.GetUseSiteDiagnostic()); var compilation7 = CreateEmptyCompilation(source2, options: WithNullableEnable(TestOptions.ReleaseDll), references: new[] { compilation1.ToMetadataReference(), MscorlibRef }); compilation7.VerifyEmitDiagnostics(); CompileAndVerify(compilation7); Assert.Equal(TypeKind.Struct, compilation7.GetTypeByMetadataName("A").TypeKind); Assert.Equal(TypeKind.Enum, compilation7.GetTypeByMetadataName("B").TypeKind); Assert.Equal(TypeKind.Class, compilation7.GetTypeByMetadataName("C").TypeKind); Assert.Equal(TypeKind.Delegate, compilation7.GetTypeByMetadataName("D").TypeKind); Assert.Equal(TypeKind.Interface, compilation7.GetTypeByMetadataName("I1").TypeKind); } [Fact, WorkItem(718176, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/718176")] public void AccessPropertyWithoutArguments() { var source1 = @"Imports System Imports System.Runtime.InteropServices <Assembly: PrimaryInteropAssembly(0, 0)> <Assembly: Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E210"")> <ComImport()> <Guid(""165F752D-E9C4-4F7E-B0D0-CDFD7A36E211"")> Public Interface I Property Value(Optional index As Object = Nothing) As Object End Interface"; var ref1 = BasicCompilationUtils.CompileToMetadata(source1); var source2 = @"class C : I { public dynamic get_Value(object index = null) => ""Test""; public void set_Value(object index = null, object value = null) { } } class Test { static void Main() { I x = new C(); System.Console.WriteLine(x.Value.Length); } }"; var comp = CreateCompilation(source2, new[] { ref1.WithEmbedInteropTypes(true), CSharpRef }, options: WithNullableEnable(TestOptions.ReleaseExe)); CompileAndVerify(comp, expectedOutput: "4"); } [Fact] public void NullabilityOfTypeParameters_001() { var source = @" class Outer { void M<T>(T x) { object y; y = x; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(7, 13) ); } [Fact] public void NullabilityOfTypeParameters_002() { var source = @" class Outer { void M<T>(T x) { dynamic y; y = x; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(7, 13) ); } [Fact] public void NullabilityOfTypeParameters_003() { var source = @" class Outer { void M<T>(T x) where T : I1 { object y; y = x; dynamic z; z = x; } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_004() { var source = @" class Outer { void M<T, U>(U x) where U : T { T y; y = x; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_005() { var source = @" class Outer { void M<T>(T x) { if (x == null) return; object y; y = x; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_006() { var source = @" class Outer { void M<T>(T x) { if (x == null) return; dynamic y; y = x; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_007() { var source = @" class Outer { T M0<T>(T x0, T y0) { if (x0 == null) throw null!; M2(x0) = x0; M2<T>(x0) = y0; M2(x0).ToString(); M2<T>(x0).ToString(); throw null!; } void M1(object? x1, object? y1) { if (x1 == null) return; M2(x1) = x1; M2(x1) = y1; } ref U M2<U>(U a) where U : notnull => throw null!; } "; // Note: you cannot pass a `T` to a `U : object` even if the `T` was null-tested CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2(x0) = x0; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2").WithArguments("Outer.M2<U>(U)", "U", "T").WithLocation(7, 9), // (8,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2<T>(x0) = y0; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2<T>").WithArguments("Outer.M2<U>(U)", "U", "T").WithLocation(8, 9), // (10,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2(x0).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2").WithArguments("Outer.M2<U>(U)", "U", "T").WithLocation(10, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // M2(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0)").WithLocation(10, 9), // (11,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2<T>(x0).ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2<T>").WithArguments("Outer.M2<U>(U)", "U", "T").WithLocation(11, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // M2<T>(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2<T>(x0)").WithLocation(11, 9), // (19,18): warning CS8601: Possible null reference assignment. // M2(x1) = y1; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y1").WithLocation(19, 18) ); } [Fact] public void NullabilityOfTypeParameters_008() { var source = @" class Outer { void M0<T, U>(T x0, U y0, U z0) where U : T { if (x0 == null) return; if (y0 == null) return; M2(x0) = y0; M2(x0) = z0; M2<T>(x0) = y0; M2<T>(x0) = z0; M2(x0).ToString(); M2<T>(x0).ToString(); } ref U M2<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // M2(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // M2<T>(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2<T>(x0)").WithLocation(13, 9) ); } [Fact] public void NullabilityOfTypeParameters_009() { var source = @" class Outer { void M0<T>(T x0, T y0) { x0 = y0; } void M1<T>(T y1) { T x1 = y1; x1 = y1; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_010() { var source = @" class Outer { void M0<T>(Outer x0, T y0) where T : Outer? { x0 = y0; } void M1<T>(T y1) where T : Outer? { Outer x1 = y1; x1 = y1; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x0 = y0; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y0").WithLocation(6, 14), // (11,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer x1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(11, 20), // (12,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // x1 = y1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y1").WithLocation(12, 14) ); } [Fact] public void NullabilityOfTypeParameters_011() { var source = @" class Outer { void M0<T>(Outer x0, T y0) where T : Outer? { if (y0 == null) return; x0 = y0; } void M1<T>(T y1) where T : Outer? { if (y1 == null) return; Outer x1 = y1; x1 = y1; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(30938, "https://github.com/dotnet/roslyn/issues/30938")] public void NullabilityOfTypeParameters_012() { var source = @" class Outer { void M<T>(object? x, object y) { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // z = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "T").WithLocation(7, 13), // (8,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // z = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("object", "T").WithLocation(8, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9)); } [Fact] [WorkItem(30938, "https://github.com/dotnet/roslyn/issues/30938")] public void NullabilityOfTypeParameters_013() { var source = @" class Outer { void M<T>(dynamic? x, dynamic y) { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_014() { var source = @" class Outer { void M<T>(object? x, object y) where T : I1 { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // z = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "T").WithLocation(7, 13), // (8,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // z = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("object", "T").WithLocation(8, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9)); } [Fact] public void NullabilityOfTypeParameters_015() { var source = @" class Outer { void M<T>(dynamic? x, dynamic y) where T : I1 { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_016() { var source = @" class Outer { void M<T>(object? x, object y) where T : I1? { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // z = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "T").WithLocation(7, 13), // (8,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // z = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("object", "T").WithLocation(8, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9)); } [Fact] public void NullabilityOfTypeParameters_017() { var source = @" class Outer { void M<T>(dynamic? x, dynamic y) where T : I1? { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_018() { var source = @" class Outer { void M<T, U>(T x) where U : T { U y; y = x; y = (U)x; y.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'T' to 'U'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("T", "U").WithLocation(7, 13), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_019() { var source = @" class Outer { void M<T, U>(T x) where U : T, I1 { U y; y = x; y = (U)x; y.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'T' to 'U'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("T", "U").WithLocation(7, 13), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_020() { var source = @" class Outer { void M<T, U>(T x) where U : T, I1? { U y; y = x; y = (U)x; y.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'T' to 'U'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("T", "U").WithLocation(7, 13), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_021() { var source = @" class Outer { void M<T, U>(T x) where U : T where T : I1 { U y; y = x; y = (U)x; y.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'T' to 'U'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("T", "U").WithLocation(7, 13) ); } [Fact] public void NullabilityOfTypeParameters_022() { var source = @" class Outer { void M<T>(object? x) { if (x == null) return; T y; y = x; y = (T)x; y.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,13): error CS0266: Cannot implicitly convert type 'object' to 'T'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("object", "T").WithLocation(8, 13) ); } [Fact] [WorkItem(30939, "https://github.com/dotnet/roslyn/issues/30939")] public void NullabilityOfTypeParameters_023() { var source = @" class Outer { void M1<T>(dynamic? x) { if (x == null) return; T y; y = x; y = (T)x; y.ToString(); } void M2<T>(dynamic? x) { if (x != null) return; T y; y = x; y = (T)x; y.ToString(); // 1 } void M3<T>(dynamic? x) { if (x != null) { T y; y = x; y = (T)x; y.ToString(); } else { T y; y = x; y = (T)x; y.ToString(); // 2 } } void M4<T>(dynamic? x) { if (x == null) { T y; y = x; y = (T)x; y.ToString(); // 3 } else { T y; y = x; y = (T)x; y.ToString(); } } void M5<T>(dynamic? x) { // Since `||` here could be a user-defined `operator |` invocation, // no reasonable inferences can be made. if (x == null || false) { T y; y = x; y = (T)x; y.ToString(); // 4 } else { T y; y = x; y = (T)x; y.ToString(); // 5 } } void M6<T>(dynamic? x) { // Since `&&` here could be a user-defined `operator &` invocation, // no reasonable inferences can be made. if (x == null && true) { T y; y = x; y = (T)x; y.ToString(); // 6 } else { T y; y = x; y = (T)x; y.ToString(); // 7 } } void M7<T>(dynamic? x) { if (!(x == null)) { T y; y = x; y = (T)x; y.ToString(); } else { T y; y = x; y = (T)x; y.ToString(); // 8 } } void M8<T>(dynamic? x) { if (!(x != null)) { T y; y = x; y = (T)x; y.ToString(); // 9 } else { T y; y = x; y = (T)x; y.ToString(); } } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(18, 9), // (34,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(34, 13), // (44,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(44, 13), // (63,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(63, 13), // (70,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(70, 13), // (82,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(82, 13), // (89,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(89, 13), // (106,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(106, 13), // (116,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(116, 13)); } [Fact] [WorkItem(30939, "https://github.com/dotnet/roslyn/issues/30939")] public void DynamicControlTest() { var source = @" class Outer { void M1(dynamic? x) { if (x == null) return; string y; y = x; y = (string)x; y.ToString(); } void M2(dynamic? x) { if (x != null) return; string y; y = x; // 1 y = (string)x; // 2 y.ToString(); // 3 } void M3(dynamic? x) { if (x != null) { string y; y = x; y = (string)x; y.ToString(); } else { string y; y = x; // 4 y = (string)x; // 5 y.ToString(); // 6 } } void M4(dynamic? x) { if (x == null) { string y; y = x; // 7 y = (string)x; // 8 y.ToString(); // 9 } else { string y; y = x; y = (string)x; y.ToString(); } } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (16,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(16, 13), // (17,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = (string)x; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)x").WithLocation(17, 13), // (18,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(18, 9), // (32,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(32, 17), // (33,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = (string)x; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)x").WithLocation(33, 17), // (34,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(34, 13), // (42,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = x; // 7 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(42, 17), // (43,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = (string)x; // 8 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(string)x").WithLocation(43, 17), // (44,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(44, 13)); } [Fact] [WorkItem(30940, "https://github.com/dotnet/roslyn/issues/30940")] [WorkItem(30941, "https://github.com/dotnet/roslyn/issues/30941")] public void NullabilityOfTypeParameters_024() { var source = @" class Outer { void M<T>(Outer? x, Outer y) where T : Outer? { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'Outer' to 'T'. An explicit conversion exists (are you missing a cast?) // z = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("Outer", "T").WithLocation(7, 13), // (8,13): error CS0266: Cannot implicitly convert type 'Outer' to 'T'. An explicit conversion exists (are you missing a cast?) // z = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("Outer", "T").WithLocation(8, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9) ); } [Fact] [WorkItem(30940, "https://github.com/dotnet/roslyn/issues/30940")] public void NullabilityOfTypeParameters_025() { var source = @" class Outer { void M<T>(Outer? x) where T : Outer? { if (x == null) return; T y; y = x; y = (T)x; y.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,13): error CS0266: Cannot implicitly convert type 'Outer' to 'T'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("Outer", "T").WithLocation(8, 13) ); } [Fact] [WorkItem(30940, "https://github.com/dotnet/roslyn/issues/30940")] [WorkItem(30941, "https://github.com/dotnet/roslyn/issues/30941")] public void NullabilityOfTypeParameters_026() { var source = @" class Outer { void M<T>(Outer? x, Outer y) where T : Outer { T z; z = x; z = y; z = (T)x; z.ToString(); // 1 z = (T)y; z.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,13): error CS0266: Cannot implicitly convert type 'Outer' to 'T'. An explicit conversion exists (are you missing a cast?) // z = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("Outer", "T").WithLocation(7, 13), // (7,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // z = x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(7, 13), // (8,13): error CS0266: Cannot implicitly convert type 'Outer' to 'T'. An explicit conversion exists (are you missing a cast?) // z = y; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "y").WithArguments("Outer", "T").WithLocation(8, 13), // (9,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // z = (T)x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)x").WithLocation(9, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(10, 9) ); } [Fact] [WorkItem(30940, "https://github.com/dotnet/roslyn/issues/30940")] public void NullabilityOfTypeParameters_027() { var source = @" class Outer { void M<T>(Outer? x) where T : Outer { if (x == null) return; T y; y = x; y = (T)x; y.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,13): error CS0266: Cannot implicitly convert type 'Outer' to 'T'. An explicit conversion exists (are you missing a cast?) // y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("Outer", "T").WithLocation(8, 13) ); } [Fact] public void NullabilityOfTypeParameters_028() { var source = @" class Outer { void M0<T>(Outer x0, T y0) where T : Outer { x0 = y0; } void M1<T>(T y1) where T : Outer { Outer x1 = y1; x1 = y1; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_029() { var source = @" class Outer { void M0<T>(T x) { x = default; x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_030() { var source = @" class Outer { void M0<T>(T x) { x = default(T); x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_031() { var source = @" class Outer { void M0<T>(T x) where T : I1? { x = default; x.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_032() { var source = @" class Outer { void M0<T>(T x) where T : I1? { x = default(T); x.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_033() { var source = @" class Outer { void M0<T>(T x) where T : Outer { x = default; x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_034() { var source = @" class Outer { void M0<T>(T x) where T : Outer { x = default(T); x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(T)").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_035() { var source = @" class Outer { void M0<T>(T x) where T : I1 { x = default; x.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_036() { var source = @" class Outer { void M0<T>(T x) where T : I1 { x = default(T); x.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_037() { var source = @" class Outer { void M0<T>(T x) { x.ToString(); x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9) ); } [Fact] public void NullabilityOfTypeParameters_038() { var source = @" class Outer { void M0<T>(T x) where T : I1? { x.ToString(); x.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9) ); } [Fact] public void NullabilityOfTypeParameters_039() { var source = @" class Outer { void M0<T>(T x) where T : I1 { x.ToString(); x.ToString(); } } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_040() { var source = @" class Outer { void M0<T>(T x) where T : Outer? { x.ToString(); x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9) ); } [Fact] public void NullabilityOfTypeParameters_041() { var source = @" class Outer { void M0<T>(T x) where T : Outer { x.ToString(); x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_042() { var source = @" class Outer { void M0<T>(T x) { M1(x); M1<T>(x); } void M1<T>(T x) where T : notnull {} } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8714: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M1(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(6, 9), // (7,9): warning CS8714: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M1<T>(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<T>").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_043() { var source = @" class Outer { void M0<T>(T x) { if (x == null) return; M1(x); M1<T>(x); } void M1<T>(T x) where T : notnull {} } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8714: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M1(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(7, 9), // (8,9): warning CS8714: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M1<T>(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M1<T>").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_044() { var source = @" class Outer { void M0<T>(T x) where T : class? { M1(x); M1<T>(x); } void M1<T>(T x) where T : class {} } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8634: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'class' constraint. // M1(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(6, 9), // (7,9): warning CS8634: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'class' constraint. // M1<T>(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<T>").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_045() { var source = @" class Outer { void M0<T>(T x) where T : class? { if (x == null) return; M1(x); M1<T>(x); } void M1<T>(T x) where T : class {} } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8634: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'class' constraint. // M1(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(7, 9), // (8,9): warning CS8634: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'Outer.M1<T>(T)'. Nullability of type argument 'T' doesn't match 'class' constraint. // M1<T>(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "M1<T>").WithArguments("Outer.M1<T>(T)", "T", "T").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_046() { var source = @" class Outer { void M0<T>(T x) where T : class? { x = null; x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9)); } [Fact] public void NullabilityOfTypeParameters_047() { var source = @" class Outer { void M0<T>(T x) where T : class { x = null; x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_048() { var source = @" class Outer { void M0<T>(T x) where T : Outer? { x = null; x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9)); } [Fact] public void NullabilityOfTypeParameters_049() { var source = @" class Outer { void M0<T>(T x) where T : Outer { x = null; x.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_050() { var source = @" class Outer { void M0<T>(T x) { M1(x, x).ToString(); } T M1<T>(T x, T y) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // M1(x, x).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x, x)").WithLocation(6, 9) ); } [Fact] public void NullabilityOfTypeParameters_051() { var source = @" class Outer { void M0<T>(T x, T y) { if (x == null) return; M1(x, y).ToString(); } T M1<T>(T x, T y) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // M1(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x, y)").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_052() { var source = @" class Outer { void M0<T>(T x, T y) { if (y == null) return; M1(x, y).ToString(); } T M1<T>(T x, T y) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // M1(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x, y)").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_053() { var source = @" class Outer { void M0<T>(T x, T y) { if (x == null) return; if (y == null) return; M1(x, y).ToString(); M1<T>(x, y).ToString(); } T M1<T>(T x, T y) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M1(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x, y)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // M1<T>(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1<T>(x, y)").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_054() { var source = @" class Outer { void M0<T>(T x, object y) { M1(x, y).ToString(); } T M1<T>(T x, T y) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,12): warning CS8604: Possible null reference argument for parameter 'x' in 'object Outer.M1<object>(object x, object y)'. // M1(x, y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("x", "object Outer.M1<object>(object x, object y)").WithLocation(6, 12) ); } [Fact] public void NullabilityOfTypeParameters_055() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { M2(x0, y0) = z0; } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_056() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; M2(x0, y0) = z0; M2(x0, y0).ToString(); } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M2(x0, y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0, y0)").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_057() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (y0 == null) return; M2(x0, y0) = z0; } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_058() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; if (y0 == null) return; M2(x0, y0) = z0; M2<T>(x0, y0) = z0; M2(x0, y0).ToString(); } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M2(x0, y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0, y0)").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_059() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T, I1 { if (x0 == null) return; if (y0 == null) return; M2(x0, y0) = z0; } ref U M2<U>(U a, U b) => throw null!; } interface I1 {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_060() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : class, T { if (x0 == null) return; if (y0 == null) return; M2(x0, y0) = z0; } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_061() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; if (y0 == null) return; if (z0 == null) return; M2(x0, y0) = z0; } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_062() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { M2(out x0, out y0) = z0; } ref U M2<U>(out U a, out U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_063() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; M2(out M3(x0), out y0) = z0; M2(out M3<T>(x0), out y0); M2<T>(out M3(x0), out y0); M2<T>(out M3<T>(x0), out y0); M2(out M3(x0), out y0).ToString(); M2<T>(out M3(x0), out y0).ToString(); } ref U M2<U>(out U a, out U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // M2(out M3(x0), out y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(out M3(x0), out y0)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // M2<T>(out M3(x0), out y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2<T>(out M3(x0), out y0)").WithLocation(13, 9) ); } [Fact] public void NullabilityOfTypeParameters_064() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (y0 == null) return; M2(out x0, out M3(y0)) = z0; M2(out x0, out M3<T>(y0)); M2<T>(out x0, out M3(y0)); M2<T>(out x0, out M3<T>(y0)); M2(out x0, out M3(y0)).ToString(); // warn M2<T>(out x0, out M3(y0)).ToString(); // warn } ref U M2<U>(out U a, out U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // M2(out x0, out M3(y0)).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(out x0, out M3(y0))").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // M2<T>(out x0, out M3(y0)).ToString(); // warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2<T>(out x0, out M3(y0))").WithLocation(13, 9) ); } [Fact] public void NullabilityOfTypeParameters_065() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; if (y0 == null) return; M2(out M3(x0), out M3(y0)) = z0; M2<T>(out M3(x0), out M3(y0)) = z0; M2(out M3<T>(x0), out M3(y0)) = z0; M2(out M3(x0), out M3<T>(y0)) = z0; M2(out M3(x0), out M3(y0)).ToString(); } ref U M2<U>(out U a, out U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // M2(out M3(x0), out M3(y0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(out M3(x0), out M3(y0))").WithLocation(12, 9) ); } [Fact] public void NullabilityOfTypeParameters_066() { var source = @" class Outer { void M0<T>(T x0, object? y0) { object? z0 = new object(); z0 = x0; M2(out y0, out M3(z0)).ToString(); } ref U M2<U>(out U a, out U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M2(out y0, out M3(z0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(out y0, out M3(z0))").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_067() { var source = @" class Outer { void M0<T>(T x0, object? y0) { object? z0 = new object(); z0 = x0; M2(y0, z0).ToString(); } ref U M2<U>(U a, U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M2(y0, z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(y0, z0)").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_068() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T where T : class? { M2(M3(x0), M3(y0)) = z0; } ref U M2<U>(I1<U> a, I1<U> b) => throw null!; I1<U> M3<U>(U a) => throw null!; } interface I1<in T> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_069() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T where T : class? { if (x0 == null) return; M2(M3(x0), M3(y0)) = z0; M2<T>(M3<T>(x0), M3<T>(y0)) = z0; M2(M3(x0), M3(y0)).ToString(); } ref U M2<U>(I1<U> a, I1<U> b) => throw null!; I1<U> M3<U>(U a) => throw null!; } interface I1<in T> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M2(M3(x0), M3(y0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(M3(x0), M3(y0))").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_070() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T where T : class? { if (y0 == null) return; M2(M3(x0), M3(y0)) = z0; M2<T>(M3(x0), M3(y0)) = z0; M2(M3(x0), M3(y0)).ToString(); } ref U M2<U>(I1<U> a, I1<U> b) => throw null!; I1<U> M3<U>(U a) => throw null!; } interface I1<in T> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M2(M3(x0), M3(y0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(M3(x0), M3(y0))").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_071() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T where T : class? { if (x0 == null) return; if (y0 == null) return; M2(M3(x0), M3(y0)) = z0; M2<T>(M3(x0), M3(y0)) = z0; M2(M3<T>(x0), M3(y0)) = z0; M2(M3(x0), M3(y0)).ToString(); } ref U M2<U>(I1<U> a, I1<U> b) => throw null!; I1<U> M3<U>(U a) => throw null!; } interface I1<in T> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // M2(M3(x0), M3(y0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(M3(x0), M3(y0))").WithLocation(12, 9) ); } [Fact] public void NullabilityOfTypeParameters_072() { var source = @" class Outer { void M0<T>(T x0, I1<object?> y0) { object? z0 = new object(); z0 = x0; M2(y0, M3(z0)).ToString(); } ref U M2<U>(I1<U> a, I1<U> b) => throw null!; I1<U> M3<U>(U a) => throw null!; } interface I1<in T> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M2(y0, M3(z0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(y0, M3(z0))").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_073() { var source = @" class Outer { void M0<T>(object x0, T y0) { if (y0 == null) return; object? z0 = new object(); z0 = y0; M2(out x0, out M3(z0)).ToString(); } ref U M2<U>(out U a, out U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_074() { var source = @" class Outer { void M0<T>(object x0, T y0) { if (y0 == null) return; object? z0 = new object(); z0 = y0; M2(out M3(z0), out x0).ToString(); } ref U M2<U>(out U a, out U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_075() { var source = @" class Outer { void M0<T>() where T : new() { T x0; x0 = new T(); x0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_076() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { M2(ref x0, ref y0) = z0; } ref U M2<U>(ref U a, ref U b) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_077() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; M2(ref M3(x0), ref y0) = z0; M2<T>(ref M3(x0), ref y0); M2(ref M3(x0), ref y0).ToString(); } ref U M2<U>(ref U a, ref U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M2(ref M3(x0), ref y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(ref M3(x0), ref y0)").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_078() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (y0 == null) return; M2(ref x0, ref M3(y0)) = z0; M2<T>(ref x0, ref M3(y0)); M2(ref x0, ref M3(y0)).ToString(); } ref U M2<U>(ref U a, ref U b) => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M2(ref x0, ref M3(y0)).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(ref x0, ref M3(y0))").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_079() { var source = @" class Outer { void M0<T, U>(T x0, T y0, U z0) where U : T { if (x0 == null) return; if (y0 == null) return; M2(ref M3(x0), ref M3(y0)) = z0; M2<T>(ref M3(x0), ref M3(y0)) = z0; } ref U M2<U>(ref U a, ref U b) where U : notnull => throw null!; ref U M3<U>(U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(ref U, ref U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2(ref M3(x0), ref M3(y0)) = z0; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2").WithArguments("Outer.M2<U>(ref U, ref U)", "U", "T").WithLocation(8, 9), // (9,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(ref U, ref U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2<T>(ref M3(x0), ref M3(y0)) = z0; Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2<T>").WithArguments("Outer.M2<U>(ref U, ref U)", "U", "T").WithLocation(9, 9) ); } [Fact] [WorkItem(30946, "https://github.com/dotnet/roslyn/issues/30946")] public void NullabilityOfTypeParameters_080() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (x0 == null) return; M2(x0).M3(ref y0); M2<T>(x0).M3(ref y0); } Other<U> M2<U>(U a) where U : notnull => throw null!; } class Other<U> where U : notnull { public void M3(ref U a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2(x0).M3(ref y0); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2").WithArguments("Outer.M2<U>(U)", "U", "T").WithLocation(7, 9), // (8,9): warning CS8714: The type 'T' cannot be used as type parameter 'U' in the generic type or method 'Outer.M2<U>(U)'. Nullability of type argument 'T' doesn't match 'notnull' constraint. // M2<T>(x0).M3(ref y0); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "M2<T>").WithArguments("Outer.M2<U>(U)", "U", "T").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_081() { var source = @" class Outer { void M0<T>(T x0) { M2(x0); } void M2(object a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,12): warning CS8604: Possible null reference argument for parameter 'a' in 'void Outer.M2(object a)'. // M2(x0); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x0").WithArguments("a", "void Outer.M2(object a)").WithLocation(6, 12) ); } [Fact] public void NullabilityOfTypeParameters_082() { var source = @" class Outer { void M0<T>(T x0) { M2(x0); } void M2(in object a) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,12): warning CS8604: Possible null reference argument for parameter 'a' in 'void Outer.M2(in object a)'. // M2(x0); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x0").WithArguments("a", "void Outer.M2(in object a)").WithLocation(6, 12) ); } [Fact] public void NullabilityOfTypeParameters_083() { var source = @" class Outer { void M0<T>(T x0, I1<T> y0, I1<string?> z0) where T : class? { M3(M2(x0)); M3<I1<T>>(y0); M3<I1<string?>>(z0); } I1<U> M2<U>(U a) => throw null!; void M3<U>(U a) where U : I1<object> => throw null!; } interface I1<out U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U>(U)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<object>'. // M3(M2(x0)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3").WithArguments("Outer.M3<U>(U)", "I1<object>", "U", "I1<T>").WithLocation(6, 9), // (7,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U>(U)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<object>'. // M3<I1<T>>(y0); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<T>>").WithArguments("Outer.M3<U>(U)", "I1<object>", "U", "I1<T>").WithLocation(7, 9), // (8,9): warning CS8631: The type 'I1<string?>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U>(U)'. Nullability of type argument 'I1<string?>' doesn't match constraint type 'I1<object>'. // M3<I1<string?>>(z0); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<string?>>").WithArguments("Outer.M3<U>(U)", "I1<object>", "U", "I1<string?>").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_084() { var source = @" class Outer { void M0<T, U>(T x0, I1<T> y0, I1<object> z0, U? a0) where T : class? where U : class, T { M3(M2(x0), a0); if (x0 == null) return; M3(M2(x0), a0); M3<I1<T>, U>(y0, null); M3<I1<object>, string>(z0, null); } I1<U> M2<U>(U a) => throw null!; void M3<U, W>(U a, W? b) where U : I1<W?> where W : class => throw null!; } interface I1<in U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U, W>(U, W?)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<U?>'. // M3(M2(x0), a0); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3").WithArguments("Outer.M3<U, W>(U, W?)", "I1<U?>", "U", "I1<T>").WithLocation(6, 9), // (9,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U, W>(U, W?)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<U?>'. // M3(M2(x0), a0); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3").WithArguments("Outer.M3<U, W>(U, W?)", "I1<U?>", "U", "I1<T>").WithLocation(9, 9), // (11,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U, W>(U, W?)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<U?>'. // M3<I1<T>, U>(y0, null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<T>, U>").WithArguments("Outer.M3<U, W>(U, W?)", "I1<U?>", "U", "I1<T>").WithLocation(11, 9), // (12,9): warning CS8631: The type 'I1<object>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U, W>(U, W?)'. Nullability of type argument 'I1<object>' doesn't match constraint type 'I1<string?>'. // M3<I1<object>, string>(z0, null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<object>, string>").WithArguments("Outer.M3<U, W>(U, W?)", "I1<string?>", "U", "I1<object>").WithLocation(12, 9) ); } [Fact] public void NullabilityOfTypeParameters_085() { var source = @" class Outer { void M0<T>(T x0, I1<T> y0, I1<object> z0, T a0) { if (x0 == null) return; M3(M2(x0), a0); M3(M2(a0), x0); M3<I1<object>, object?>(z0, null); } I1<U> M2<U>(U a) => throw null!; void M3<U, W>(U a, W b) where U : I1<W> => throw null!; } interface I1<U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8631: The type 'I1<object>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U, W>(U, W)'. Nullability of type argument 'I1<object>' doesn't match constraint type 'I1<object?>'. // M3<I1<object>, object?>(z0, null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<object>, object?>").WithArguments("Outer.M3<U, W>(U, W)", "I1<object?>", "U", "I1<object>").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_086() { var source = @" class Outer { void M0<T>(T x0, I1<string> z0) where T : class? { if (x0 == null) return; M3(M2(x0)); M3(M2<T>(x0)); M3<I1<T>>(M2(x0)); M3<I1<string>>(z0); } I1<U> M2<U>(U a) => throw null!; void M3<U>(U a) where U : I1<object> => throw null!; } interface I1<out U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U>(U)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<object>'. // M3(M2(x0)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3").WithArguments("Outer.M3<U>(U)", "I1<object>", "U", "I1<T>").WithLocation(7, 9), // (8,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U>(U)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<object>'. // M3(M2<T>(x0)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3").WithArguments("Outer.M3<U>(U)", "I1<object>", "U", "I1<T>").WithLocation(8, 9), // (9,9): warning CS8631: The type 'I1<T>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U>(U)'. Nullability of type argument 'I1<T>' doesn't match constraint type 'I1<object>'. // M3<I1<T>>(M2(x0)); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<T>>").WithArguments("Outer.M3<U>(U)", "I1<object>", "U", "I1<T>").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_087() { var source = @" class Outer { void M0<T, U>(T x0, I1<T> y0, I1<object> z0, U? a0) where T : class? where U : class, T { M3(M2(x0), a0); if (x0 == null) return; M3(M2(x0), a0); M3<I1<T>, U>(y0, null); M3<I1<object>, string>(z0, null); } I1<U> M2<U>(U a) => throw null!; void M3<U, W>(U a, W? b) where U : I1<W> where W : class => throw null!; } interface I1<in U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_088() { var source = @" class Outer { void M0<T, U>(T x0, I1<T> y0, I1<object> z0, U a0) where T : class? where U : class?, T { M3(M2(x0), a0); if (x0 == null) return; M3(M2(x0), a0); // 1 M3<I1<T>, U>(y0, a0); M3<I1<object>, string?>(z0, null); } I1<U> M2<U>(U a) => throw null!; void M3<U, W>(U a, W b) where U : I1<W> => throw null!; } interface I1<in U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (12,9): warning CS8631: The type 'I1<object>' cannot be used as type parameter 'U' in the generic type or method 'Outer.M3<U, W>(U, W)'. Nullability of type argument 'I1<object>' doesn't match constraint type 'I1<string?>'. // M3<I1<object>, string?>(z0, null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "M3<I1<object>, string?>").WithArguments("Outer.M3<U, W>(U, W)", "I1<string?>", "U", "I1<object>").WithLocation(12, 9) ); } [Fact] public void NullabilityOfTypeParameters_089() { var source = @" class Outer { void M0<T>(T x0, I1<T> y0, I1<object> z0, T a0) { if (x0 == null) return; if (a0 == null) return; M3(M2(x0), a0); M3(M2(a0), x0); M3<I1<object>, object>(z0, new object()); } I1<U> M2<U>(U a) => throw null!; void M3<U, W>(U a, W b) where U : I1<W> => throw null!; } interface I1<U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_090() { var source = @" class Outer { void M0<T>(T x0, I1<T> y0, I1<object> z0, T a0) { M3(M2(x0), a0); M3<I1<T>,T>(y0, a0); } I1<U> M2<U>(U a) => throw null!; void M3<U, W>(U a, W b) where U : I1<W> => throw null!; } interface I1<U> {} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_091() { var source = @" class Outer { void M0<T>(T x0) where T : I1? { x0?.ToString(); x0?.M1(x0); x0.ToString(); } } interface I1 { void M1(object x); } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_092() { var source = @" class Outer { void M0<T>(T x0) { if (x0 is null) return; x0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_093() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (y0 == null) return; T z0 = x0 ?? y0; M1(z0) = x0; M1(z0).ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_094() { var source = @" class Outer { void M0<T>(T x0, T y0) { (x0 ?? y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (x0 ?? y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0 ?? y0").WithLocation(6, 10) ); } [Fact] [WorkItem(30952, "https://github.com/dotnet/roslyn/issues/30952")] public void NullabilityOfTypeParameters_095() { var source = @" class Outer { void M0<T>(object? x0, T z0) { if (x0 is T y0) { M2(y0) = z0; x0.ToString(); y0.ToString(); } } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(30952, "https://github.com/dotnet/roslyn/issues/30952")] public void NullabilityOfTypeParameters_096() { var source = @" class Outer { void M0<T>(T x0, object? z0) { if (x0 is object y0) { M2(y0) = z0; x0.ToString(); y0.ToString(); } } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,22): warning CS8601: Possible null reference assignment. // M2(y0) = z0; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "z0").WithLocation(8, 22) ); } [Fact] public void NullabilityOfTypeParameters_097() { var source = @" class Outer { void M0<T>(T x0, T z0) { if (x0 is var y0) { M2(y0) = z0; x0.ToString(); y0.ToString(); } } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(9, 13), // (10,13): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(10, 13) ); } [Fact] public void NullabilityOfTypeParameters_098() { var source = @" class Outer { void M0<T>(T x0) { if (x0 is default) return; x0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,19): error CS8505: A default literal 'default' is not valid as a pattern. Use another literal (e.g. '0' or 'null') as appropriate. To match everything, use a discard pattern '_'. // if (x0 is default) return; Diagnostic(ErrorCode.ERR_DefaultPattern, "default").WithLocation(6, 19), // (7,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_099() { var source = @" class Outer { void M0<T>(T x0) { if (x0 is default(T)) return; x0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,19): error CS0150: A constant value is expected // if (x0 is default(T)) return; Diagnostic(ErrorCode.ERR_ConstantExpected, "default(T)").WithLocation(6, 19), // (7,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(7, 9) ); } [Fact] public void NullabilityOfTypeParameters_100() { var source = @" class Outer { void M0<T>(T x0, T y0) where T : class? { if (x0 is null) return; M2(x0) = y0; M2(x0).ToString(); x0.ToString(); } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // M2(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0)").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_101() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (y0 == null) return; (x0 ?? y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_102() { var source = @" class Outer { void M0<T>(T x0, T y0) where T : class? { if (x0 == null) return; M2(x0) = y0; M2(x0).ToString(); x0.ToString(); } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // M2(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0)").WithLocation(9, 9) ); } [Fact] [WorkItem(30952, "https://github.com/dotnet/roslyn/issues/30952")] public void NullabilityOfTypeParameters_103() { var source = @" class Outer { void M0<T>(T x0, T z0) { if (x0 is T y0) { M2(x0) = z0; M2(y0) = z0; M2(x0).ToString(); M2(y0).ToString(); x0.ToString(); y0.ToString(); } } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,13): warning CS8602: Dereference of a possibly null reference. // M2(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(x0)").WithLocation(10, 13), // (11,13): warning CS8602: Dereference of a possibly null reference. // M2(y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(y0)").WithLocation(11, 13) ); } [Fact] public void NullabilityOfTypeParameters_104() { var source = @" class Outer<T> { void M0(bool b, T x0) { T y0; if (b) { y0 = M2(); } else { y0 = x0; } y0.ToString(); } #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (17,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(17, 9) ); } [Fact] public void NullabilityOfTypeParameters_105() { var source = @" class Outer<T> { void M0(bool b, T x0) { T y0; if (b) { y0 = x0; } else { y0 = M2(); } y0.ToString(); } #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (17,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(17, 9) ); } [Fact] public void NullabilityOfTypeParameters_106() { var source = @" class Outer<T> { void M0(bool b, T x0) { T y0; if (b || x0 == null) { y0 = M3(); } else { y0 = x0; } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_107() { var source = @" class Outer<T> { void M0(bool b, T x0) { T y0; if (b && x0 != null) { y0 = x0; } else { y0 = M3(); } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_108() { var source = @" class Outer<T> { void M0(T x0) { x0!.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_109() { var source = @" class Outer { void M0<T>(T x0) where T : I1<T?> { x0 = default; } void M1<T>(T x1) where T : I1<T> { x1 = default; } } interface I1<T> {} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (4,35): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void M0<T>(T x0) where T : I1<T?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 35) ); } [Fact] public void NullabilityOfTypeParameters_110() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (x0 == null) return; T z0 = x0 ?? y0; M1(z0).ToString(); M1(z0) = y0; z0.ToString(); z0?.ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(10, 9)); } [Fact] public void NullabilityOfTypeParameters_111() { var source = @" class Outer { void M0<T>(T x0, T y0, T a0) { if (x0 == null) return; if (y0 == null) return; T z0 = x0 ?? y0; M1(z0) = a0; z0?.ToString(); M1(z0).ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_112() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (x0 == null) return; var z0 = x0; z0 = y0; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_113() { var source = @" class Outer { void M0<T>(T x0, T y0, T u0, T v0) { var a0 = new[] {x0, y0}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; M2(v0).ToString(); } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M2(v0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(v0)").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_114() { var source = @" class Outer { void M0<T>(T x0, T y0, T u0, T v0) { if (x0 == null) return; var a0 = new[] {x0, y0}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; M2<T>(v0) = a0[1]; M2(v0).ToString(); } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // M2(v0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(v0)").WithLocation(13, 9) ); } [Fact] public void NullabilityOfTypeParameters_115() { var source = @" class Outer { void M0<T>(T x0, T y0, T u0, T v0) { if (y0 == null) return; var a0 = new[] {x0, y0}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; M2<T>(v0) = a0[1]; M2(v0).ToString(); } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // M2(v0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(v0)").WithLocation(13, 9) ); } [Fact] public void NullabilityOfTypeParameters_116() { var source = @" class Outer { void M0<T>(T x0, T y0, T u0, T v0) { if (x0 == null) return; if (y0 == null) return; var a0 = new[] {x0, y0}; a0[0] = u0; a0[0].ToString(); if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; } ref T M2<T>(T x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // a0[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a0[0]").WithLocation(10, 9) ); } [Fact] public void NullabilityOfTypeParameters_117() { var source = @" class Outer<T> { void M0(T x0, T u0, T v0) { var a0 = new[] {x0, M3()}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_118() { var source = @" class Outer<T> { void M0(T x0, T u0, T v0) { var a0 = new[] {M3(), x0}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_119() { var source = @" class Outer<T> { void M0(T x0, T u0, T v0) { if (x0 == null) return; var a0 = new[] {x0, M3()}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_120() { var source = @" class Outer<T> { void M0(T x0, T u0, T v0) { if (x0 == null) return; var a0 = new[] {M3(), x0}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_121() { var source = @" class Outer<T> { void M0(T u0, T v0) { var a0 = new[] {M3(), M3()}; a0[0] = u0; if (v0 == null) return; a0[0] = v0; M2(v0) = a0[1]; } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_122() { var source = @" class Outer<T> { void M0(bool b, T x0) { T y0; if (b) { y0 = M3(); } else { y0 = M3(); } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; #nullable disable T M3() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_123() { var source = @" class Outer<T> { void M0(bool b, T x0, T a0, T b0) { if (a0 == null) return; if (b0 == null) return; T y0; if (b) { y0 = a0; } else { y0 = b0; } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_124() { var source = @" class Outer<T> { void M0(bool b, T x0, T a0, T b0) { T y0; if (b) { y0 = a0; } else { y0 = b0; } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(18, 9) ); } [Fact] public void NullabilityOfTypeParameters_125() { var source = @" class Outer<T> { void M0(bool b, T x0, T a0, T b0) { if (a0 == null) return; T y0; if (b) { y0 = a0; } else { y0 = b0; } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (20,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(20, 9) ); } [Fact] public void NullabilityOfTypeParameters_126() { var source = @" class Outer<T> { void M0(bool b, T x0, T a0, T b0) { if (b0 == null) return; T y0; if (b) { y0 = a0; } else { y0 = b0; } M2(y0) = x0; y0.ToString(); } ref T M2<U>(U x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (20,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(20, 9) ); } [Fact] public void NullabilityOfTypeParameters_127() { var source = @" class C<T> { public C<object> X = null!; public C<object?> Y = null!; void F(object? y0) { if (y0 == null) return; object? x0; x0 = null; _ = new C<int>() { Y = M(x0), X = M(y0) }; } ref C<S> M<S>(S x) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_128() { var source = @" class C<T> { void F(object? y0) { if (y0 == null) return; object? x0; x0 = null; M2( out M1(x0), out M1(y0) ); } ref C<S> M1<S>(S x) => throw null!; void M2(out C<object?> x, out C<object> y) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_129() { var source = @" class C<T> { void F(object? y0) { if (y0 == null) return; object? x0; x0 = null; M2( ref M1(x0), ref M1(y0) ); } ref C<S> M1<S>(S x) => throw null!; void M2(ref C<object?> x, ref C<object> y) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_130() { var source = @" class C<T> { void F(object? y0) { if (y0 == null) return; object? x0; x0 = null; M2(M1(x0), M1(y0)) = (C<object?> a, C<object> b) => throw null!; } C<S> M1<S>(S x) => throw null!; ref System.Action<U, V> M2<U, V>(U x, V y) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_131() { var source = @" class C<T> where T : class? { void F(T y0) { if (y0 == null) return; T x0; x0 = null; M2(M1(x0), M1(y0)) = (C<T> a, C<T> b) => throw null!; } C<S> M1<S>(S x) where S : class? => throw null!; ref System.Action<U, V> M2<U, V>(U x, V y) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,13): warning CS8622: Nullability of reference types in type of parameter 'a' of 'lambda expression' doesn't match the target delegate 'Action<C<T?>, C<T>>'. // (C<T> a, C<T> b) => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "(C<T> a, C<T> b) => throw null!").WithArguments("a", "lambda expression", "System.Action<C<T?>, C<T>>").WithLocation(11, 13)); } [Fact] public void NullabilityOfTypeParameters_132() { var source = @" class C<T> where T : class? { void F(T x0, T y0) { M2(M1(x0), M1(y0)) = (C<T> a, C<T> b) => throw null!; } C<S> M1<S>(S x) where S : class? => throw null!; ref System.Action<U, V> M2<U, V>(U x, V y) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_133() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; T z0 = M2() ?? y0; M1(z0) = x0; M1<T>(z0) = x0; M1(z0).ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_134() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; T z0 = y0 ?? M2(); M1(z0) = x0; M1<T>(z0) = x0; M1(z0).ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_135() { var source = @" class Outer<T> { void M0(T x0) { T z0 = M2() ?? M2(); M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_136() { var source = @" class Outer<T> { void M0(T x0, T y0) { T z0 = M2() ?? y0; M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9)); } [Fact] public void NullabilityOfTypeParameters_137() { var source = @" class Outer<T> { void M0(T x0, T y0) { T z0 = y0 ?? M2(); M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_138() { var source = @" class C<T> where T : class? { void F(T x0, T y0) { T z0 = x0 ?? y0; M2(M1(z0)) = (C<T> a) => throw null!; } C<S> M1<S>(S x) where S : class? => throw null!; ref System.Action<U> M2<U>(U x) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_139() { var source = @" class C<T> where T : class? { void F(T x0, T y0) { T z0 = x0 ?? y0; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_140() { var source = @" class C<T> where T : class? { void F(T x0, T y0) { T z0 = new [] {x0, y0}[0]; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_141() { var source = @" struct C<T> where T : class? { void F(T x0, object? y0) { F1 = x0; F2 = y0; x0 = F1; y0 = F2; } #nullable disable T F1; object F2; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_142() { var source = @" class Outer { void M0<T>(bool b, T x0, T y0) { (b ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (b ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x0 : y0").WithLocation(6, 10) ); } [Fact] public void NullabilityOfTypeParameters_143() { var source = @" class Outer { void M0<T>(bool b, T x0, T y0) { if (y0 == null) return; (b ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,10): warning CS8602: Dereference of a possibly null reference. // (b ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x0 : y0").WithLocation(7, 10) ); } [Fact] public void NullabilityOfTypeParameters_144() { var source = @" class Outer { void M0<T>(bool b, T x0, T y0) { if (x0 == null) return; (b ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,10): warning CS8602: Dereference of a possibly null reference. // (b ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b ? x0 : y0").WithLocation(7, 10) ); } [Fact] public void NullabilityOfTypeParameters_145() { var source = @" class Outer { void M0<T>(bool b, T x0, T y0, T a0) { if (x0 == null) return; if (y0 == null) return; T z0 = b ? x0 : y0; M1(z0) = a0; z0?.ToString(); M1(z0).ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(11, 9) ); } [Fact, WorkItem(33924, "https://github.com/dotnet/roslyn/issues/33924")] public void NullabilityOfTypeParameters_146() { var source = @" class Outer<T> { void M0(bool b, T x0, T y0) { if (y0 == null) return; T z0 = b ? M2() : y0; M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact, WorkItem(33924, "https://github.com/dotnet/roslyn/issues/33924")] public void NullabilityOfTypeParameters_147() { var source = @" class Outer<T> { void M0(bool b, T x0, T y0) { if (y0 == null) return; T z0 = b ? y0 : M2(); M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact, WorkItem(33924, "https://github.com/dotnet/roslyn/issues/33924")] public void NullabilityOfTypeParameters_148() { var source = @" class Outer<T> { void M0(bool b, T x0) { T z0 = b ? M2() : M2(); M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_149() { var source = @" class Outer<T> { void M0(bool b, T x0, T y0) { T z0 = b ? M2() : y0; M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_150() { var source = @" class Outer<T> { void M0(bool b, T x0, T y0) { T z0 = b ? y0 : M2(); M1(z0) = x0; z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_151() { var source = @" class C<T> where T : class? { void F(bool b, T x0, T y0) { T z0 = b ? x0 : y0; M2(M1(z0)) = (C<T> a) => throw null!; } C<S> M1<S>(S x) where S : class? => throw null!; ref System.Action<U> M2<U>(U x) => throw null!; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_153() { var source = @" class Outer { void M0<T>(T x0, T y0) { (true ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (true ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "true ? x0 : y0").WithLocation(6, 10) ); } [Fact] public void NullabilityOfTypeParameters_154() { var source = @" class Outer { void M0<T>(bool b, T x0, T y0) { if (y0 == null) return; (true ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,10): warning CS8602: Dereference of a possibly null reference. // (true ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "true ? x0 : y0").WithLocation(7, 10) ); } [Fact, WorkItem(33924, "https://github.com/dotnet/roslyn/issues/33924")] public void NullabilityOfTypeParameters_155() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (x0 == null) return; (true ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_156() { var source = @" class Outer { void M0<T>(T x0, T y0, T a0) { if (x0 == null) return; if (y0 == null) return; T z0 = true ? x0 : y0; M1(z0) = a0; M1(z0).ToString(); z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(12, 9)); } [Fact] public void NullabilityOfTypeParameters_157() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; T z0 = true ? M2() : y0; M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(10, 9)); } [Fact] public void NullabilityOfTypeParameters_158() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; T z0 = true ? y0 : M2(); M1(z0) = x0; M1(z0).ToString(); z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9)); } [Fact] public void NullabilityOfTypeParameters_159() { var source = @" class Outer<T> { void M0(T x0) { T z0 = true ? M2() : M2(); M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_160() { var source = @" class Outer<T> { void M0(T x0, T y0) { T z0 = true ? M2() : y0; M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_161() { var source = @" class Outer<T> { void M0(T x0, T y0) { T z0 = true ? y0 : M2(); M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_162() { var source = @" class Outer { void M0<T>(T x0, T y0) { (false ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (false ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "false ? x0 : y0").WithLocation(6, 10) ); } [Fact, WorkItem(33924, "https://github.com/dotnet/roslyn/issues/33924")] public void NullabilityOfTypeParameters_163() { var source = @" class Outer { void M0<T>(bool b, T x0, T y0) { if (y0 == null) return; (false ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_164() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (x0 == null) return; (false ? x0 : y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,10): warning CS8602: Dereference of a possibly null reference. // (false ? x0 : y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "false ? x0 : y0").WithLocation(7, 10) ); } [Fact] public void NullabilityOfTypeParameters_165() { var source = @" class Outer { void M0<T>(T x0, T y0, T a0) { if (x0 == null) return; if (y0 == null) return; T z0 = false ? x0 : y0; M1(z0) = a0; M1(z0).ToString(); z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(12, 9)); } [Fact] public void NullabilityOfTypeParameters_166() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; T z0 = false ? M2() : y0; M1(z0) = x0; M1(z0).ToString(); z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9)); } [Fact] public void NullabilityOfTypeParameters_167() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; T z0 = false ? y0 : M2(); M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(10, 9)); } [Fact] public void NullabilityOfTypeParameters_168() { var source = @" class Outer<T> { void M0(T x0) { T z0 = false ? M2() : M2(); M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_169() { var source = @" class Outer<T> { void M0(T x0, T y0) { T z0 = false ? M2() : y0; M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_170() { var source = @" class Outer<T> { void M0(T x0, T y0) { T z0 = false ? y0 : M2(); M1(z0) = x0; z0?.ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9)); } [Fact] public void NullabilityOfTypeParameters_171() { var source = @" class Outer<T, U> where T : Outer<T, U>? where U : T { void M0(T x0) { U y0 = (U)x0; U z0 = y0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_172() { var source = @" class Outer<T, U> where T : class? where U : T { void M0(T x0) { U y0 = (U)x0; U z0 = y0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9)); } [Fact] public void NullableClassConditionalAccess() { var source = @" class Program<T> where T : Program<T>? { T field = default!; static void M(T t) { T t1 = t?.field; // 1 T? t2 = t?.field; } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t1 = t?.field; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t?.field").WithLocation(8, 16) ); } [Fact] public void NullabilityOfTypeParameters_173() { var source = @" class Outer<T, U> where T : Outer<T, U>?, U { void M0(T x0) { T? z0 = x0?.M1(); U? y0 = z0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_174() { var source = @" class Outer<T, U> where T : Outer<T, U>? where U : T { void M0(T x0) { T? z0 = x0?.M1(); U? y0 = (U?)z0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_175() { var source = @" class Outer<T, U> where T : Outer<T, U>?, U { void M0(T x0) { if (x0 == null) return; T? z0 = x0?.M1(); U? y0 = z0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(12, 9) ); } [Fact] public void NullabilityOfTypeParameters_176() { var source = @" class Outer<T, U> where T : Outer<T, U>?, U { void M0(Outer<T, U>? x0) { T? z0 = x0?.M1(); U? y0 = z0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_177() { var source = @" class Outer<T, U> where T : Outer<T, U>?, U { void M0(Outer<T, U> x0) { T? z0 = x0?.M1(); U? y0 = z0; y0?.ToString(); y0.ToString(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(11, 9) ); } [Fact] public void NullabilityOfTypeParameters_178() { var source = @" class Outer<T> where T : Outer<T>? { void M0(T x0) { Outer<T> z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } Outer<T> M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> z0 = x0?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0?.M1()").WithLocation(6, 23), // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_179() { var source = @" class Outer<T> where T : Outer<T>? { void M0(T x0) { if (x0 == null) return; Outer<T> z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } Outer<T> M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> z0 = x0?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0?.M1()").WithLocation(7, 23), // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_180() { var source = @" class Outer<T> where T : Outer<T>? { void M0(T x0) { Outer<T> z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } Outer<T>? M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> z0 = x0?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0?.M1()").WithLocation(6, 23), // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_181() { var source = @" class Outer<T> where T : Outer<T>? { void M0(T x0) { if (x0 == null) return; Outer<T> z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } Outer<T>? M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> z0 = x0?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0?.M1()").WithLocation(7, 23), // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_182() { var source = @" class Outer<T, U> where T : Outer<T, U>?, U where U : class? { void M0(T x0) { U? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } U M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_183() { var source = @" class Outer<T, U> where T : Outer<T, U>?, U where U : class? { void M0(T x0) { if (x0 == null) return; U? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } U M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_184() { var source = @" class Outer<T, U> where T : U where U : Outer<T, U>? { void M0(U x0) { U? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_185() { var source = @" class Outer<T, U> where T : U where U : Outer<T, U>? { void M0(U x0) { T? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_186() { var source = @" class Outer<T, U> where T : U where U : Outer<T, U>? { void M0(U x0) { if (x0 == null) return; U? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_187() { var source = @" class Outer<T, U> where T : U where U : Outer<T, U>? { void M0(U x0) { if (x0 == null) return; T? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } T M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_188() { var source = @" class Outer<T, U> where T : Outer<T, U>? where U : class? { void M0(T x0) { U? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } U M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_189() { var source = @" class Outer<T, U> where T : Outer<T, U>? where U : class? { void M0(T x0) { if (x0 == null) return; U? z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } U M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_190() { var source = @" class Outer<T, U> where T : Outer<T, U>? where U : class { void M0(T x0) { U z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } U M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // U z0 = x0?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0?.M1()").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_191() { var source = @" class Outer<T, U> where T : Outer<T, U>? where U : class { void M0(T x0) { if (x0 == null) return; U z0 = x0?.M1(); z0?.ToString(); z0.ToString(); } U M1() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // U z0 = x0?.M1(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0?.M1()").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // z0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_192() { var source = @" class Outer<T> { void M0(T x0) { object y0 = x0 as object; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y0 = x0 as object; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as object").WithLocation(6, 21), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_193() { var source = @" class Outer<T> { void M0(T x0) { if (x0 == null) return; object y0 = x0 as object; y0?.ToString(); y0.ToString(); // 1 } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_194() { var source = @" class Outer<T> { void M0(T x0) { dynamic y0 = x0 as dynamic; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // dynamic y0 = x0 as dynamic; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as dynamic").WithLocation(6, 22), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_195() { var source = @" class Outer<T> { void M0(T x0) { if (x0 == null) return; dynamic y0 = x0 as dynamic; y0?.ToString(); y0.ToString(); // 1 } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_196() { var source = @" class Outer<T> where T : class? { void M0(object x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_197() { var source = @" class Outer<T> where T : class? { void M0(object? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_198() { var source = @" class Outer<T> where T : class? { void M0(object? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_199() { var source = @" class Outer<T> where T : class? { void M0(dynamic x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_200() { var source = @" class Outer<T> where T : class? { void M0(dynamic? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_201() { var source = @" class Outer<T> where T : class? { void M0(dynamic? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_202() { var source = @" class Outer<T> where T : notnull { void M0(T x0) { object y0 = x0 as object; y0?.ToString(); y0.ToString(); // 1 } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_203() { var source = @" class Outer<T> where T : notnull { void M0(T x0) { dynamic y0 = x0 as dynamic; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_204() { var source = @" class Outer<T> where T : class { void M0(object x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_205() { var source = @" class Outer<T> where T : class { void M0(object? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_206() { var source = @" class Outer<T> where T : class { void M0(object? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_207() { var source = @" class Outer<T> where T : class { void M0(dynamic x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_208() { var source = @" class Outer<T> where T : class { void M0(dynamic? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_209() { var source = @" class Outer<T> where T : class { void M0(dynamic? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_210() { var source = @" class Outer<T> { void M0(T x0) { Outer<T> y0 = x0 as Outer<T>; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> y0 = x0 as Outer<T>; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as Outer<T>").WithLocation(6, 23), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_211() { var source = @" class Outer<T> { void M0(T x0) { if (x0 == null) return; Outer<T> y0 = x0 as Outer<T>; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> y0 = x0 as Outer<T>; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as Outer<T>").WithLocation(7, 23), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_212() { var source = @" class Outer<T> where T : class? { void M0(Outer<T>? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_213() { var source = @" class Outer<T> where T : class? { void M0(Outer<T>? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_214() { var source = @" class Outer<T> where T : class? { void M0(Outer<T> x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_215() { var source = @" class Outer<T> where T : class { void M0(T x0) { Outer<T> y0 = x0 as Outer<T>; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> y0 = x0 as Outer<T>; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as Outer<T>").WithLocation(6, 23), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_216() { var source = @" class Outer<T> where T : class { void M0(Outer<T>? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_217() { var source = @" class Outer<T> where T : class { void M0(Outer<T>? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_218() { var source = @" class Outer<T> where T : class { void M0(Outer<T> x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_219() { var source = @" class Outer<T> where T : Outer<T>? { void M0(T x0) { Outer<T> y0 = x0 as Outer<T>; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Outer<T> y0 = x0 as Outer<T>; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as Outer<T>").WithLocation(6, 23), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_220() { var source = @" class Outer<T> where T : Outer<T>? { void M0(T x0) { if (x0 == null) return; Outer<T> y0 = x0 as Outer<T>; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_221() { var source = @" class Outer<T> where T : Outer<T>? { void M0(Outer<T> x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_222() { var source = @" class Outer<T> where T : Outer<T> { void M0(T x0) { Outer<T> y0 = x0 as Outer<T>; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_223() { var source = @" class Outer<T> where T : Outer<T> { void M0(Outer<T>? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_224() { var source = @" class Outer<T> where T : Outer<T> { void M0(Outer<T>? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_225() { var source = @" class Outer<T> where T : Outer<T> { void M0(Outer<T> x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_226() { var source = @" class Outer<T> where T : I1? { void M0(T x0) { I1 y0 = x0 as I1; y0?.ToString(); y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // I1 y0 = x0 as I1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as I1").WithLocation(6, 17), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_227() { var source = @" class Outer<T> where T : I1? { void M0(T x0) { if (x0 == null) return; I1 y0 = x0 as I1; y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_228() { var source = @" class Outer<T> where T : class?, I1? { void M0(I1 x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_229() { var source = @" class Outer<T> where T : I1 { void M0(T x0) { I1 y0 = x0 as I1; y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_230() { var source = @" class Outer<T> where T : class?, I1 { void M0(I1? x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_231() { var source = @" class Outer<T> where T : class?, I1 { void M0(I1? x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_232() { var source = @" class Outer<T> where T : class?, I1 { void M0(I1 x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } interface I1{} "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_233() { var source = @" class Outer<T> where T : class? { void M0(T x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_234() { var source = @" class Outer<T> where T : class? { void M0(T x0) { if (x0 == null) return; T y0 = x0 as T; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_235() { var source = @" class Outer<T> where T : class { void M0(T x0) { T y0 = x0 as T; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_237() { var source = @" class Outer<T, U> where T : U where U : class? { void M0(T x0) { U y0 = x0 as U; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_238() { var source = @" class Outer<T, U> where T : U where U : class? { void M0(T x0) { if (x0 == null) return; U y0 = x0 as U; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_239() { var source = @" class Outer<T, U> where T : U where U : class { void M0(T x0) { U y0 = x0 as U; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_240() { var source = @" class Outer<T, U> where T : class, U where U : class? { void M0(T x0) { U y0 = x0 as U; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_241() { var source = @" class Outer<T, U> where T : class?, U where U : class? { void M0(T x0) { U y0 = x0 as U; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_242() { var source = @" class Outer<T, U> where T : class?, U where U : class? { void M0(T x0) { if (x0 == null) return; U y0 = x0 as U; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_243() { var source = @" class Outer<T, U> where T : class?, U where U : class { void M0(T x0) { U y0 = x0 as U; y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_244() { var source = @" class Outer<T, U> where T : class, U where U : class? { void M0(U x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_245() { var source = @" class Outer<T, U> where T : class, U where U : class? { void M0(U x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_246() { var source = @" class Outer<T, U> where T : class, U where U : class { void M0(U x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_248() { var source = @" class Outer<T, U> where T : class?, U where U : class? { void M0(U x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_249() { var source = @" class Outer<T, U> where T : class?, U where U : class? { void M0(U x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_250() { var source = @" class Outer<T, U> where T : class?, U where U : class { void M0(U x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_251() { var source = @" class Outer<T, U> where T : class?, U { void M0(U x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_252() { var source = @" class Outer<T, U> where T : class?, U { void M0(U x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_253() { var source = @" class Outer<T, U> where T : class, U { void M0(U x0) { T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(6, 16), // (8,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(8, 9) ); } [Fact] public void NullabilityOfTypeParameters_254() { var source = @" class Outer<T, U> where T : class, U { void M0(U x0) { if (x0 == null) return; T y0 = x0 as T; y0?.ToString(); y0.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y0 = x0 as T; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x0 as T").WithLocation(7, 16), // (9,9): warning CS8602: Dereference of a possibly null reference. // y0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(9, 9) ); } [Fact] public void NullabilityOfTypeParameters_255() { var source = @" class Outer { void M0<T>(T x0, T y0, T z0) { if (y0 == null) return; z0 ??= y0; M1(z0) = x0; M1(z0).ToString(); z0.ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // M1(z0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(z0)").WithLocation(10, 9)); } [Fact] public void NullabilityOfTypeParameters_256() { var source = @" class Outer { void M0<T>(T x0, T y0) { (x0 ??= y0).ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // (x0 ??= y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0 ??= y0").WithLocation(6, 10)); } [Fact] public void NullabilityOfTypeParameters_257() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (y0 == null) return; (x0 ??= y0)?.ToString(); } } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( ); } [Fact] public void NullabilityOfTypeParameters_258() { var source = @" class Outer { void M0<T>(T x0, T y0) { if (x0 == null) return; x0 ??= y0; M1(x0).ToString(); M1(x0) = y0; x0?.ToString(); x0.ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // M1(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x0)").WithLocation(8, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(11, 9)); } [Fact] public void NullabilityOfTypeParameters_259() { var source = @" class Outer { void M0<T>(T x0, T y0, T a0) { if (x0 == null) return; if (y0 == null) return; x0 ??= y0; M1(x0) = a0; x0?.ToString(); M1(x0).ToString(); } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M1(x0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(x0)").WithLocation(11, 9)); } [Fact] public void NullabilityOfTypeParameters_260() { var source = @" class Outer<T> { void M0(T x0, T y0) { if (y0 == null) return; y0 ??= M2(); M1(y0) = x0; M1<T>(y0) = x0; M1(y0).ToString(); y0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // M1(y0).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M1(y0)").WithLocation(11, 9)); } [Fact] public void NullabilityOfTypeParameters_261() { var source = @" class Outer<T> { void M0(T x0, T y0) { y0 ??= M2(); M1(y0) = x0; y0.ToString(); } ref S M1<S>(S x) => throw null!; #nullable disable T M2() => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] public void NullabilityOfTypeParameters_262() { var source = @" class Outer<T1, T2> where T1 : class, T2 { void M0(T1 t1, T2 t2) { t1 ??= t2 as T1; M1(t1) ??= t2 as T1; } ref S M1<S>(S x) => throw null!; } "; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (6,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // t1 ??= t2 as T1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t2 as T1").WithLocation(6, 16)); } [Fact] [WorkItem(33295, "https://github.com/dotnet/roslyn/issues/33295")] public void NullabilityOfTypeParameters_263() { var source = @" #nullable enable class C<T> { public T FieldWithInferredAnnotation; } class C { static void Main() { Test(null); } static void Test(string? s) { s = """"; hello: var c = GetC(s); c.FieldWithInferredAnnotation.ToString(); s = null; goto hello; } public static C<T> GetC<T>(T t) => new C<T> { FieldWithInferredAnnotation = t }; public static T GetT<T>(T t) => t; }"; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics( // (5,12): warning CS8618: Non-nullable field 'FieldWithInferredAnnotation' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public T FieldWithInferredAnnotation; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "FieldWithInferredAnnotation").WithArguments("field", "FieldWithInferredAnnotation").WithLocation(5, 12), // (19,5): warning CS8602: Dereference of a possibly null reference. // c.FieldWithInferredAnnotation.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.FieldWithInferredAnnotation").WithLocation(19, 5)); } [Fact] public void UpdateFieldFromReceiverType() { var source = @"class A<T> { } class B<T> { internal T F = default!; } class Program { internal static B<T> Create<T>(T t) => throw null!; static void M1(object x, object? y) { var b1 = Create(x); b1.F = x; b1.F = y; // 1 } static void M2(A<object?> x, A<object> y, A<object?> z) { var b2 = Create(x); b2.F = y; // 2 b2.F = z; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,16): warning CS8601: Possible null reference assignment. // b1.F = y; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(13, 16), // (18,16): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'A<object?>'. // b2.F = y; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object>", "A<object?>").WithLocation(18, 16)); } [Fact] public void UpdatePropertyFromReceiverType() { var source = @"class A<T> { } class B<T> { internal T P { get; set; } = default!; } class Program { internal static B<T> Create<T>(T t) => throw null!; static void M1(object x, object? y) { var b1 = Create(x); b1.P = x; b1.P = y; // 1 } static void M2(A<object?> x, A<object> y, A<object?> z) { var b2 = Create(x); b2.P = y; // 2 b2.P = z; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,16): warning CS8601: Possible null reference assignment. // b1.P = y; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(13, 16), // (18,16): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'A<object?>'. // b2.P = y; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("A<object>", "A<object?>").WithLocation(18, 16)); } [WorkItem(31018, "https://github.com/dotnet/roslyn/issues/31018")] [Fact] public void UpdateEventFromReceiverType() { var source = @"#pragma warning disable 0067 delegate void D<T>(T t); class C<T> { internal event D<T> E; } class Program { internal static C<T> Create<T>(T t) => throw null!; static void M1(object x, D<object> y, D<object?> z) { var c1 = Create(x); c1.E += y; c1.E += z; // 1 } static void M2(object? x, D<object> y, D<object?> z) { var c2 = Create(x); c2.E += y; // 2 c2.E += z; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/31018: Report warnings. comp.VerifyDiagnostics( // (5,25): warning CS8618: Non-nullable event 'E' is uninitialized. Consider declaring the event as nullable. // internal event D<T> E; Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "E").WithArguments("event", "E").WithLocation(5, 25) ); } [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] [Fact] public void UpdateMethodFromReceiverType_01() { var source = @"class C<T> { internal void F(T t) { } } class Program { internal static C<T> Create<T>(T t) => throw null!; static void M(object x, object? y, string? z) { var c = Create(x); c.F(x); c.F(y); // 1 c.F(z); // 2 c.F(null); // 3 } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,13): warning CS8604: Possible null reference argument for parameter 't' in 'void C<object>.F(object t)'. // c.F(y); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("t", "void C<object>.F(object t)").WithLocation(12, 13), // (13,13): warning CS8604: Possible null reference argument for parameter 't' in 'void C<object>.F(object t)'. // c.F(z); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "z").WithArguments("t", "void C<object>.F(object t)").WithLocation(13, 13), // (14,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.F(null); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 13)); } [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] [Fact] public void UpdateMethodFromReceiverType_02() { var source = @"class A<T> { } class B<T> { internal void F<U>(U u) where U : A<T> { } } class Program { internal static B<T> Create<T>(T t) => throw null!; static void M1(object x, A<object> y, A<object?> z) { var b1 = Create(x); b1.F(y); b1.F(z); // 1 } static void M2(object? x, A<object> y, A<object?> z) { var b2 = Create(x); b2.F(y); // 2 b2.F(z); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8631: The type 'A<object?>' cannot be used as type parameter 'U' in the generic type or method 'B<object>.F<U>(U)'. Nullability of type argument 'A<object?>' doesn't match constraint type 'A<object>'. // b1.F(z); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "b1.F").WithArguments("B<object>.F<U>(U)", "A<object>", "U", "A<object?>").WithLocation(13, 9), // (18,9): warning CS8631: The type 'A<object>' cannot be used as type parameter 'U' in the generic type or method 'B<object?>.F<U>(U)'. Nullability of type argument 'A<object>' doesn't match constraint type 'A<object?>'. // b2.F(y); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "b2.F").WithArguments("B<object?>.F<U>(U)", "A<object?>", "U", "A<object>").WithLocation(18, 9)); } [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] [Fact] public void UpdateMethodFromReceiverType_03() { var source = @"class C<T> { internal static T F() => throw null!; } class Program { internal static C<T> Create<T>(T t) => throw null!; static void M(object x) { var c1 = Create(x); c1.F().ToString(); x = null; var c2 = Create(x); c2.F().ToString(); } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): error CS0176: Member 'C<object>.F()' cannot be accessed with an instance reference; qualify it with a type name instead // c1.F().ToString(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "c1.F").WithArguments("C<object>.F()").WithLocation(11, 9), // (12,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 13), // (14,9): error CS0176: Member 'C<object>.F()' cannot be accessed with an instance reference; qualify it with a type name instead // c2.F().ToString(); Diagnostic(ErrorCode.ERR_ObjectProhibited, "c2.F").WithArguments("C<object>.F()").WithLocation(14, 9)); } [Fact] public void AnnotationsInMetadata_01() { var source = @" using System.Collections.Generic; class B { public int F01; public int? F02; public string F03; public string? F04; public KeyValuePair<int, long> F05; public KeyValuePair<string, object> F06; public KeyValuePair<string?, object> F07; public KeyValuePair<string, object?> F08; public KeyValuePair<string?, object?> F09; public KeyValuePair<int, object> F10; public KeyValuePair<int, object?> F11; public KeyValuePair<object, int> F12; public KeyValuePair<object?, int> F13; public Dictionary<int, long> F14; public Dictionary<int, long>? F15; public Dictionary<string, object> F16; public Dictionary<string, object>? F17; public Dictionary<string?, object> F18; public Dictionary<string?, object>? F19; public Dictionary<string, object?> F20; public Dictionary<string, object?>? F21; public Dictionary<string?, object?> F22; public Dictionary<string?, object?>? F23; public Dictionary<int, object> F24; public Dictionary<int, object>? F25; public Dictionary<int, object?> F26; public Dictionary<int, object?>? F27; public Dictionary<object, int> F28; public Dictionary<object, int>? F29; public Dictionary<object?, int> F30; public Dictionary<object?, int>? F31; } "; var comp = CreateCompilation(new[] { source }); CompileAndVerify(comp, symbolValidator: validateAnnotationsContextFalse); comp = CreateCompilation(new[] { source }, options: WithNullable(NullableContextOptions.Warnings)); CompileAndVerify(comp, symbolValidator: validateAnnotationsContextFalse); comp = CreateCompilation(new[] { @"#nullable enable warnings " + source }); CompileAndVerify(comp, symbolValidator: validateAnnotationsContextFalse); comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); CompileAndVerify(comp, symbolValidator: validateAnnotationsContextTrue); comp = CreateCompilation(new[] { source }, options: WithNullable(NullableContextOptions.Annotations)); CompileAndVerify(comp, symbolValidator: validateAnnotationsContextTrue); comp = CreateCompilation(new[] { @"#nullable enable annotations " + source }); CompileAndVerify(comp, symbolValidator: validateAnnotationsContextTrue); static void validateAnnotationsContextFalse(ModuleSymbol m) { (string type, string attribute)[] baseline = new[] { ("System.Int32", null), ("System.Int32?", null), ("System.String", null), ("System.String?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.KeyValuePair<System.Int32, System.Int64>", null), ("System.Collections.Generic.KeyValuePair<System.String, System.Object>", null), ("System.Collections.Generic.KeyValuePair<System.String?, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({0, 2, 0})"), ("System.Collections.Generic.KeyValuePair<System.String, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 0, 2})"), ("System.Collections.Generic.KeyValuePair<System.String?, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 2, 2})"), ("System.Collections.Generic.KeyValuePair<System.Int32, System.Object>", null), ("System.Collections.Generic.KeyValuePair<System.Int32, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 2})"), ("System.Collections.Generic.KeyValuePair<System.Object, System.Int32>", null), ("System.Collections.Generic.KeyValuePair<System.Object?, System.Int32>", "System.Runtime.CompilerServices.NullableAttribute({0, 2})"), ("System.Collections.Generic.Dictionary<System.Int32, System.Int64>", null), ("System.Collections.Generic.Dictionary<System.Int32, System.Int64>?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", null), ("System.Collections.Generic.Dictionary<System.String, System.Object>?", "System.Runtime.CompilerServices.NullableAttribute({2, 0, 0})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({0, 2, 0})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object>?", "System.Runtime.CompilerServices.NullableAttribute({2, 2, 0})"), ("System.Collections.Generic.Dictionary<System.String, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 0, 2})"), ("System.Collections.Generic.Dictionary<System.String, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute({2, 0, 2})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 2, 2})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object>", null), ("System.Collections.Generic.Dictionary<System.Int32, System.Object>?", "System.Runtime.CompilerServices.NullableAttribute({2, 0})"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 2})"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.Dictionary<System.Object, System.Int32>", null), ("System.Collections.Generic.Dictionary<System.Object, System.Int32>?", "System.Runtime.CompilerServices.NullableAttribute({2, 0})"), ("System.Collections.Generic.Dictionary<System.Object?, System.Int32>", "System.Runtime.CompilerServices.NullableAttribute({0, 2})"), ("System.Collections.Generic.Dictionary<System.Object?, System.Int32>?", "System.Runtime.CompilerServices.NullableAttribute(2)") }; Assert.Equal(31, baseline.Length); AnnotationsInMetadataFieldSymbolValidator(m, baseline); } static void validateAnnotationsContextTrue(ModuleSymbol m) { (string type, string attribute)[] baseline = new[] { ("System.Int32", null), ("System.Int32?", null), ("System.String!", "System.Runtime.CompilerServices.NullableAttribute(1)"), ("System.String?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.KeyValuePair<System.Int32, System.Int64>", null), ("System.Collections.Generic.KeyValuePair<System.String!, System.Object!>", "System.Runtime.CompilerServices.NullableAttribute({0, 1, 1})"), ("System.Collections.Generic.KeyValuePair<System.String?, System.Object!>", "System.Runtime.CompilerServices.NullableAttribute({0, 2, 1})"), ("System.Collections.Generic.KeyValuePair<System.String!, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 1, 2})"), ("System.Collections.Generic.KeyValuePair<System.String?, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 2, 2})"), ("System.Collections.Generic.KeyValuePair<System.Int32, System.Object!>", "System.Runtime.CompilerServices.NullableAttribute({0, 1})"), ("System.Collections.Generic.KeyValuePair<System.Int32, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 2})"), ("System.Collections.Generic.KeyValuePair<System.Object!, System.Int32>", "System.Runtime.CompilerServices.NullableAttribute({0, 1})"), ("System.Collections.Generic.KeyValuePair<System.Object?, System.Int32>", "System.Runtime.CompilerServices.NullableAttribute({0, 2})"), ("System.Collections.Generic.Dictionary<System.Int32, System.Int64>!", "System.Runtime.CompilerServices.NullableAttribute(1)"), ("System.Collections.Generic.Dictionary<System.Int32, System.Int64>?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.Dictionary<System.String!, System.Object!>!", "System.Runtime.CompilerServices.NullableAttribute(1)"), ("System.Collections.Generic.Dictionary<System.String!, System.Object!>?", "System.Runtime.CompilerServices.NullableAttribute({2, 1, 1})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object!>!", "System.Runtime.CompilerServices.NullableAttribute({1, 2, 1})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object!>?", "System.Runtime.CompilerServices.NullableAttribute({2, 2, 1})"), ("System.Collections.Generic.Dictionary<System.String!, System.Object?>!", "System.Runtime.CompilerServices.NullableAttribute({1, 1, 2})"), ("System.Collections.Generic.Dictionary<System.String!, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute({2, 1, 2})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object?>!", "System.Runtime.CompilerServices.NullableAttribute({1, 2, 2})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object!>!", "System.Runtime.CompilerServices.NullableAttribute(1)"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object!>?", "System.Runtime.CompilerServices.NullableAttribute({2, 1})"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object?>!", "System.Runtime.CompilerServices.NullableAttribute({1, 2})"), ("System.Collections.Generic.Dictionary<System.Int32, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Collections.Generic.Dictionary<System.Object!, System.Int32>!", "System.Runtime.CompilerServices.NullableAttribute(1)"), ("System.Collections.Generic.Dictionary<System.Object!, System.Int32>?", "System.Runtime.CompilerServices.NullableAttribute({2, 1})"), ("System.Collections.Generic.Dictionary<System.Object?, System.Int32>!", "System.Runtime.CompilerServices.NullableAttribute({1, 2})"), ("System.Collections.Generic.Dictionary<System.Object?, System.Int32>?", "System.Runtime.CompilerServices.NullableAttribute(2)") }; } } private static void AnnotationsInMetadataFieldSymbolValidator(ModuleSymbol m, (string type, string attribute)[] baseline) { var b = m.GlobalNamespace.GetMember<NamedTypeSymbol>("B"); for (int i = 0; i < baseline.Length; i++) { var name = "F" + (i + 1).ToString("00"); var f = b.GetMember<FieldSymbol>(name); Assert.Equal(baseline[i].type, f.TypeWithAnnotations.ToTestDisplayString(true)); if (baseline[i].attribute == null) { Assert.Empty(f.GetAttributes()); } else { Assert.Equal(baseline[i].attribute, f.GetAttributes().Single().ToString()); } } } [Fact] public void AnnotationsInMetadata_02() { var ilSource = @" // =============== CLASS MEMBERS DECLARATION =================== .class private auto ansi beforefieldinit B`12<class T01,class T02,class T03,class T04, class T05,class T06,class T07,class T08, class T09,class T10,class T11,class T12> extends [mscorlib]System.Object { .param type T01 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 00 00 00 ) .param type T02 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 01 00 00 ) .param type T03 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 02 00 00 ) .param type T04 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 03 00 00 ) .param type T05 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 04 00 00 ) .param type T06 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 05 00 00 ) .param type T07 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 00 00 00 ) .param type T08 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 01 00 00 ) .param type T09 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 02 00 00 ) .param type T10 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 02 00 00 00 01 01 00 00 ) .param type T11 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 00 00 00 00 00 00 ) .param type T12 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 FF FF FF FF 00 00 ) .field public int32 F01 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 00 00 00 ) .field public int32 F02 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 01 00 00 ) .field public int32 F03 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 02 00 00 ) .field public int32 F04 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 03 00 00 ) .field public int32 F05 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 00 00 00 ) .field public int32 F06 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 01 00 00 ) .field public int32 F07 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 02 00 00 ) .field public int32 F08 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 04 00 00 ) .field public int32 F09 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 FF FF FF FF 00 00 ) .field public valuetype [mscorlib]System.Nullable`1<int32> F10 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 00 00 00 ) .field public valuetype [mscorlib]System.Nullable`1<int32> F11 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 02 00 00 00 00 00 00 00 ) .field public valuetype [mscorlib]System.Nullable`1<int32> F12 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 FF FF FF FF 00 00 ) .field public string F13 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 00 00 00 ) .field public string F14 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 03 00 00 ) .field public string F15 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 00 00 00 ) .field public string F16 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 01 00 00 ) .field public string F17 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 02 00 00 ) .field public string F18 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 01 00 00 00 04 00 00 ) .field public string F19 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 FF FF FF FF 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F20 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 00 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F21 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8) = ( 01 00 03 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F22 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 FF FF FF FF 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F23 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 00 00 00 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F24 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 01 01 01 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F25 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 02 02 02 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F26 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 01 04 05 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F27 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 00 01 02 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F28 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 01 02 00 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F29 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 03 00 00 00 02 00 01 00 00 ) .field public string F30 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 02 00 00 00 01 01 00 00 ) .field public string F31 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 00 00 00 00 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F32 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 04 00 00 00 01 01 01 01 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F33 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 02 00 00 00 01 01 00 00 ) .field public class [mscorlib]System.Collections.Generic.Dictionary`2<string,object> F34 .custom instance void System.Runtime.CompilerServices.NullableAttribute::.ctor(uint8[]) = ( 01 00 00 00 00 00 00 00 ) .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 8 (0x8) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: nop IL_0007: ret } // end of method B`12::.ctor } // end of class B`12 .class public auto ansi beforefieldinit System.Runtime.CompilerServices.NullableAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(uint8 x) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method NullableAttribute::.ctor .method public hidebysig specialname rtspecialname instance void .ctor(uint8[] x) cil managed { // Code size 9 (0x9) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Attribute::.ctor() IL_0006: nop IL_0007: nop IL_0008: ret } // end of method NullableAttribute::.ctor } // end of class System.Runtime.CompilerServices.NullableAttribute // ============================================================= // *********** DISASSEMBLY COMPLETE *********************** /* class B<[Nullable(0)]T01, [Nullable(1)]T02, [Nullable(2)]T03, [Nullable(3)]T04, [Nullable(4)]T05, [Nullable(5)]T06, [Nullable(new byte[] { 0 })]T07, [Nullable(new byte[] { 1 })]T08, [Nullable(new byte[] { 2 })]T09, [Nullable(new byte[] { 1, 1 })]T10, [Nullable(new byte[] { })]T11, [Nullable(null)]T12> where T01 : class where T02 : class where T03 : class where T04 : class where T05 : class where T06 : class where T07 : class where T08 : class where T09 : class where T10 : class where T11 : class where T12 : class { [Nullable(0)] public int F01; [Nullable(1)] public int F02; [Nullable(2)] public int F03; [Nullable(3)] public int F04; [Nullable(new byte[] { 0 })] public int F05; [Nullable(new byte[] { 1 })] public int F06; [Nullable(new byte[] { 2 })] public int F07; [Nullable(new byte[] { 4 })] public int F08; [Nullable(null)] public int F09; [Nullable(0)] public int? F10; [Nullable(new byte[] { 0, 0 })] public int? F11; [Nullable(null)] public int? F12; [Nullable(0)] public string F13; [Nullable(3)] public string F14; [Nullable(new byte[] { 0 })] public string F15; [Nullable(new byte[] { 1 })] public string F16; [Nullable(new byte[] { 2 })] public string F17; [Nullable(new byte[] { 4 })] public string F18; [Nullable(null)] public string F19; [Nullable(0)] public System.Collections.Generic.Dictionary<string, object> F20; [Nullable(3)] public System.Collections.Generic.Dictionary<string, object> F21; [Nullable(null)] public System.Collections.Generic.Dictionary<string, object> F22; [Nullable(new byte[] { 0, 0, 0 })] public System.Collections.Generic.Dictionary<string, object> F23; [Nullable(new byte[] { 1, 1, 1 })] public System.Collections.Generic.Dictionary<string, object> F24; [Nullable(new byte[] { 2, 2, 2 })] public System.Collections.Generic.Dictionary<string, object> F25; [Nullable(new byte[] { 1, 4, 5 })] public System.Collections.Generic.Dictionary<string, object> F26; [Nullable(new byte[] { 0, 1, 2 })] public System.Collections.Generic.Dictionary<string, object> F27; [Nullable(new byte[] { 1, 2, 0 })] public System.Collections.Generic.Dictionary<string, object> F28; [Nullable(new byte[] { 2, 0, 1 })] public System.Collections.Generic.Dictionary<string, object> F29; [Nullable(new byte[] { 1, 1 })] public string F30; [Nullable(new byte[] { })] public string F31; [Nullable(new byte[] { 1, 1, 1, 1 })] public System.Collections.Generic.Dictionary<string, object> F32; [Nullable(new byte[] { 1, 1 })] public System.Collections.Generic.Dictionary<string, object> F33; [Nullable(new byte[] { })] public System.Collections.Generic.Dictionary<string, object> F34; }*/ "; var source = @""; var compilation = CreateCompilation(new[] { source }, new[] { CompileIL(ilSource) }); NamedTypeSymbol b = compilation.GetTypeByMetadataName("B`12"); (string type, string attribute)[] fieldsBaseline = new[] { ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute(0)"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute(1)"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute(2)"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute(3)"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute({0})"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute({1})"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute({2})"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute({4})"), ("System.Int32", "System.Runtime.CompilerServices.NullableAttribute(null)"), ("System.Int32?", "System.Runtime.CompilerServices.NullableAttribute(0)"), ("System.Int32?", "System.Runtime.CompilerServices.NullableAttribute({0, 0})"), ("System.Int32?", "System.Runtime.CompilerServices.NullableAttribute(null)"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute(0)"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute(3)"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute({0})"), ("System.String!", "System.Runtime.CompilerServices.NullableAttribute({1})"), ("System.String?", "System.Runtime.CompilerServices.NullableAttribute({2})"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute({4})"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute(null)"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute(0)"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute(3)"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute(null)"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({0, 0, 0})"), ("System.Collections.Generic.Dictionary<System.String!, System.Object!>!", "System.Runtime.CompilerServices.NullableAttribute({1, 1, 1})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object?>?", "System.Runtime.CompilerServices.NullableAttribute({2, 2, 2})"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({1, 4, 5})"), ("System.Collections.Generic.Dictionary<System.String!, System.Object?>", "System.Runtime.CompilerServices.NullableAttribute({0, 1, 2})"), ("System.Collections.Generic.Dictionary<System.String?, System.Object>!", "System.Runtime.CompilerServices.NullableAttribute({1, 2, 0})"), ("System.Collections.Generic.Dictionary<System.String, System.Object!>?", "System.Runtime.CompilerServices.NullableAttribute({2, 0, 1})"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute({1, 1})"), ("System.String", "System.Runtime.CompilerServices.NullableAttribute({})"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({1, 1, 1, 1})"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({1, 1})"), ("System.Collections.Generic.Dictionary<System.String, System.Object>", "System.Runtime.CompilerServices.NullableAttribute({})"), }; Assert.Equal(34, fieldsBaseline.Length); AnnotationsInMetadataFieldSymbolValidator(b.ContainingModule, fieldsBaseline); (bool? constraintIsNullable, string attribute)[] typeParametersBaseline = new[] { ((bool?)null, "System.Runtime.CompilerServices.NullableAttribute(0)"), (false, "System.Runtime.CompilerServices.NullableAttribute(1)"), (true, "System.Runtime.CompilerServices.NullableAttribute(2)"), (null, "System.Runtime.CompilerServices.NullableAttribute(3)"), (null, "System.Runtime.CompilerServices.NullableAttribute(4)"), (null, "System.Runtime.CompilerServices.NullableAttribute(5)"), (null, "System.Runtime.CompilerServices.NullableAttribute({0})"), (null, "System.Runtime.CompilerServices.NullableAttribute({1})"), (null, "System.Runtime.CompilerServices.NullableAttribute({2})"), (null, "System.Runtime.CompilerServices.NullableAttribute({1, 1})"), (null, "System.Runtime.CompilerServices.NullableAttribute({})"), (null, "System.Runtime.CompilerServices.NullableAttribute(null)"), }; Assert.Equal(12, typeParametersBaseline.Length); for (int i = 0; i < typeParametersBaseline.Length; i++) { var t = b.TypeParameters[i]; Assert.Equal(typeParametersBaseline[i].constraintIsNullable, t.ReferenceTypeConstraintIsNullable); Assert.Equal(typeParametersBaseline[i].attribute, t.GetAttributes().Single().ToString()); } } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInFinally_01() { var source = @"public static class Program { public static void Main() { string? s = string.Empty; try { } finally { s = null; } _ = s.Length; // warning } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 13) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_02() { var source = @"public static class Program { public static int Main() { string? s = string.Empty; try { s = null; MayThrow(); s = string.Empty; } catch (System.Exception) { } return s.Length; // warning: possibly null } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,16): warning CS8602: Dereference of a possibly null reference. // return s.Length; // warning: possibly null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(16, 16) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_03() { var source = @"public static class Program { public static int Main() { string? s = string.Empty; try { s = null; MayThrow(); s = string.Empty; } catch (System.Exception) { return s.Length; // warning: possibly null } return s.Length; } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,20): warning CS8602: Dereference of a possibly null reference. // return s.Length; // warning: possibly null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 20) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_04() { var source = @"public static class Program { public static int Main() { string? s = string.Empty; try { s = null; MayThrow(); s = string.Empty; } catch (System.Exception) { _ = s.Length; // warning 1 } finally { _ = s.Length; // warning 2 } return s.Length; // ok (previously dereferenced) } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17), // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_05() { var source = @"public static class Program { public static int Main() { string? s = null; try { MayThrow(); s = string.Empty; _ = s.Length; // ok } catch (System.Exception) { _ = s.Length; // warning 1 } finally { _ = s.Length; // warning 2 } return s.Length; // ok (previously dereferenced) } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17), // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_06() { var source = @"public static class Program { public static int Main() { string? s = null; try { MayThrow(); s = string.Empty; _ = s.Length; // ok } catch (System.NullReferenceException) { _ = s.Length; // warning 1 } catch (System.Exception) { _ = s.Length; // warning 2 } finally { _ = s.Length; // warning 3 } return s.Length; // ok (previously dereferenced) } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17), // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17), // (22,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(22, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_07() { var source = @"public static class Program { public static int Main() { string? s = null; try { MayThrow(); s = string.Empty; _ = s.Length; // ok } catch (System.NullReferenceException) { _ = s.Length; // warning 1 } catch (System.Exception) { _ = s.Length; // warning 2 } return s.Length; // ok } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17), // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateBeforeTry_08() { var source = @"public static class Program { public static int Main() { string? s = null; try { MayThrow(); _ = s.Length; // warning 1 } catch (System.NullReferenceException) { _ = s.Length; // warning 2 } catch (System.Exception) { _ = s.Length; // warning 3 } return s.Length; // ok (previously dereferenced) } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17), // (13,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 17), // (17,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInTry_09() { var source = @"public static class Program { public static int Main() { string? s = string.Empty; try { s = null; MayThrow(); s = string.Empty; } finally { _ = s.Length; // warning } return s.Length; // ok } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInCatch_10() { var source = @"public static class Program { public static int Main() { string? s = string.Empty; try { MayThrow(); } catch (System.Exception) { s = null; MayThrow(); s = string.Empty; } finally { _ = s.Length; // warning } return s.Length; // ok } static void MayThrow() { throw null!; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17) ); } [Fact, WorkItem(30561, "https://github.com/dotnet/roslyn/issues/30561")] public void SetNullableStateInNestedTry_01() { var source = @"public static class Program { public static void Main() { { string? s = string.Empty; try { try { s = null; } catch (System.Exception) { } finally { } } catch (System.Exception) { } finally { } _ = s.Length; // warning 1a } { string? s = string.Empty; try { try { } catch (System.Exception) { s = null; } finally { } } catch (System.Exception) { } finally { } _ = s.Length; // warning 1b } { string? s = string.Empty; try { try { } catch (System.Exception) { } finally { s = null; } } catch (System.Exception) { } finally { } _ = s.Length; // warning 1c } { string? s = string.Empty; try { } catch (System.Exception) { try { s = null; } catch (System.Exception) { } finally { } } finally { _ = s.Length; // warning 2a } } { string? s = string.Empty; try { } catch (System.Exception) { try { } catch (System.Exception) { s = null; } finally { } } finally { _ = s.Length; // warning 2b } } { string? s = string.Empty; try { } catch (System.Exception) { try { } catch (System.Exception) { } finally { s = null; } } finally { _ = s.Length; // warning 2c } } { string? s = string.Empty; try { } catch (System.Exception) { } finally { try { s = null; } catch (System.Exception) { } finally { } } _ = s.Length; // warning 3a } { string? s = string.Empty; try { } catch (System.Exception) { } finally { try { } catch (System.Exception) { s = null; } finally { } } _ = s.Length; // warning 3b } { string? s = string.Empty; try { } catch (System.Exception) { } finally { try { } catch (System.Exception) { } finally { s = null; } } _ = s.Length; // warning 3c } } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (27,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1a Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(27, 17), // (52,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1b Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(52, 17), // (77,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 1c Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(77, 17), // (100,21): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2a Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(100, 21), // (124,21): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2b Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(124, 21), // (148,21): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 2c Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(148, 21), // (174,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 3a Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(174, 17), // (199,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 3b Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(199, 17), // (224,17): warning CS8602: Dereference of a possibly null reference. // _ = s.Length; // warning 3c Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(224, 17) ); } [WorkItem(30938, "https://github.com/dotnet/roslyn/issues/30938")] [Fact] public void ExplicitCastAndInferredTargetType() { var source = @"class Program { static void F(object? x) { if (x == null) return; var y = x; x = null; y = (object)x; } }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = (object)x; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)x").WithLocation(8, 13)); } [Fact] [WorkItem(31395, "https://github.com/dotnet/roslyn/issues/31395")] public void InheritNullabilityOfNonNullableClassMember() { var source = @"#pragma warning disable 8618 class C<T> { internal T F; } class Program { static bool b = false; static void F1(string? s) { var a1 = new C<string>() { F = s }; // 0 if (b) F(a1.F/*T:string?*/); // 1 var b1 = a1; if (b) F(b1.F/*T:string?*/); // 2 } static void F2<T>(T? t) where T : class { var a2 = new C<T>() { F = t }; // 3 if (b) F(a2.F/*T:T?*/); // 4 var b2 = a2; if (b) F(b2.F/*T:T?*/); // 5 } static void F(object o) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,40): warning CS8601: Possible null reference assignment. // var a1 = new C<string>() { F = s }; // 0 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(11, 40), // (12,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(a1.F/*T:string?*/); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a1.F").WithArguments("o", "void Program.F(object o)").WithLocation(12, 18), // (14,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(b1.F/*T:string?*/); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b1.F").WithArguments("o", "void Program.F(object o)").WithLocation(14, 18), // (18,35): warning CS8601: Possible null reference assignment. // var a2 = new C<T>() { F = t }; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(18, 35), // (19,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(a2.F/*T:T?*/); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a2.F").WithArguments("o", "void Program.F(object o)").WithLocation(19, 18), // (21,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(b2.F/*T:T?*/); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b2.F").WithArguments("o", "void Program.F(object o)").WithLocation(21, 18)); comp.VerifyTypes(); } [Fact] public void InheritNullabilityOfNonNullableStructMember() { var source = @"#pragma warning disable 8618 struct S<T> { internal T F; } class Program { static bool b = false; static void F1(string? s) { var a1 = new S<string>() { F = s }; // 0 if (b) F(a1.F/*T:string?*/); // 1 var b1 = a1; if (b) F(b1.F/*T:string?*/); // 2 } static void F2<T>(T? t) where T : class { var a2 = new S<T>() { F = t }; // 3 if (b) F(a2.F/*T:T?*/); // 4 var b2 = a2; if (b) F(b2.F/*T:T?*/); // 5 } static void F(object o) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,40): warning CS8601: Possible null reference assignment. // var a1 = new S<string>() { F = s }; // 0 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "s").WithLocation(11, 40), // (12,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(a1.F/*T:string?*/); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a1.F").WithArguments("o", "void Program.F(object o)").WithLocation(12, 18), // (14,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(b1.F/*T:string?*/); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b1.F").WithArguments("o", "void Program.F(object o)").WithLocation(14, 18), // (18,35): warning CS8601: Possible null reference assignment. // var a2 = new S<T>() { F = t }; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(18, 35), // (19,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(a2.F/*T:T?*/); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "a2.F").WithArguments("o", "void Program.F(object o)").WithLocation(19, 18), // (21,18): warning CS8604: Possible null reference argument for parameter 'o' in 'void Program.F(object o)'. // if (b) F(b2.F/*T:T?*/); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "b2.F").WithArguments("o", "void Program.F(object o)").WithLocation(21, 18)); comp.VerifyTypes(); } /// <summary> /// Nullability of variable members is tracked up to a fixed depth. /// </summary> [Fact] [WorkItem(31395, "https://github.com/dotnet/roslyn/issues/31395")] public void InheritNullabilityMaxDepth_01() { var source = @"#pragma warning disable 8618 class A { internal B? B; } class B { internal A? A; } class Program { static void F() { var a1 = new A() { B = new B() }; var a2 = new A() { B = new B() { A = a1 } }; var a3 = new A() { B = new B() { A = a2 } }; a1.B.ToString(); a2.B.A.B.ToString(); a3.B.A.B.A.B.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // a3.B.A.B.A.B.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a3.B.A.B.A.B").WithLocation(19, 9)); } /// <summary> /// Nullability of variable members is tracked up to a fixed depth. /// </summary> [Fact] [WorkItem(31395, "https://github.com/dotnet/roslyn/issues/31395")] public void InheritNullabilityMaxDepth_02() { var source = @"class Program { static void F(string x, object y) { (((((string? x5, object? y5) x4, string? y4) x3, object? y3) x2, string? y2) x1, object? y1) t = (((((x, y), x), y), x), y); t.y1.ToString(); t.x1.y2.ToString(); t.x1.x2.y3.ToString(); t.x1.x2.x3.y4.ToString(); t.x1.x2.x3.x4.y5.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // t.x1.x2.x3.x4.y5.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.x1.x2.x3.x4.y5").WithLocation(10, 9)); } /// <summary> /// Nullability of variable members is tracked up to a fixed depth. /// </summary> [Fact] [WorkItem(31395, "https://github.com/dotnet/roslyn/issues/31395")] [WorkItem(35773, "https://github.com/dotnet/roslyn/issues/35773")] public void InheritNullabilityMaxDepth_03() { var source = @"class Program { static void Main() { (((((string x5, string y5) x4, string y4) x3, string y3) x2, string y2) x1, string y1) t = default; t.x1.x2.x3.x4.x5.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void DiagnosticOptions_01() { var source = @" partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } private static void AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(string source) { string id = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable); var source2 = @" partial class Program { #nullable enable static void F(object o) { } }"; var comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable()); comp.VerifyDiagnostics(); foreach (ReportDiagnostic option in Enum.GetValues(typeof(ReportDiagnostic))) { comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable().WithSpecificDiagnosticOptions(id, option)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable().WithGeneralDiagnosticOption(option)); comp.VerifyDiagnostics(); } assertDiagnosticOptions(NullableContextOptions.Enable); assertDiagnosticOptions(NullableContextOptions.Warnings); void assertDiagnosticOptions(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions); var diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): error CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithWarningAsError(true) ); Assert.Equal(DiagnosticSeverity.Error, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error). WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): error CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithWarningAsError(true) ); Assert.Equal(DiagnosticSeverity.Error, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): error CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithWarningAsError(true) ); Assert.Equal(DiagnosticSeverity.Error, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): hidden CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Hidden, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): hidden CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Hidden, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); } } [Fact] public void DiagnosticOptions_02() { var source = @" #pragma warning disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } private static void AssertDiagnosticOptions_NullableWarningsNeverGiven(string source) { string id1 = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable); string id2 = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable); var source2 = @" partial class Program { #nullable enable static void F(object o) { } static object M() { return new object(); } }"; var comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable()); comp.VerifyDiagnostics(); foreach (ReportDiagnostic option in Enum.GetValues(typeof(ReportDiagnostic))) { comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable().WithSpecificDiagnosticOptions(id1, id2, option)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable().WithGeneralDiagnosticOption(option)); comp.VerifyDiagnostics(); } assertDiagnosticOptions(NullableContextOptions.Disable); assertDiagnosticOptions(NullableContextOptions.Enable); assertDiagnosticOptions(NullableContextOptions.Warnings); assertDiagnosticOptions(NullableContextOptions.Annotations); void assertDiagnosticOptions(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Default)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithGeneralDiagnosticOption(ReportDiagnostic.Default)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Error)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Error). WithGeneralDiagnosticOption(ReportDiagnostic.Default)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Error)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Suppress)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Suppress). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Hidden)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Hidden). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id1, id2, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); comp.VerifyDiagnostics(); } } [Fact] public void DiagnosticOptions_03() { var source = @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_04() { var source = @" #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_05() { var source = @" #nullable disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_06() { var source = @" #nullable enable partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(source); } private static void AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(string source) { var source2 = @" partial class Program { #nullable enable static void F(object o) { } }"; assertDiagnosticOptions(NullableContextOptions.Disable); assertDiagnosticOptions(NullableContextOptions.Enable); assertDiagnosticOptions(NullableContextOptions.Warnings); assertDiagnosticOptions(NullableContextOptions.Annotations); void assertDiagnosticOptions(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions options = WithNullable(nullableContextOptions); string id = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable); var comp = CreateCompilation(new[] { source, source2 }, options: options); var diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (8,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 11) ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options.WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): error CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithWarningAsError(true) ); Assert.Equal(DiagnosticSeverity.Error, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error). WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): error CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithWarningAsError(true) ); Assert.Equal(DiagnosticSeverity.Error, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): error CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithWarningAsError(true) ); Assert.Equal(DiagnosticSeverity.Error, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): hidden CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Hidden, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): hidden CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Hidden, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify( // (6,11): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null") ); Assert.Equal(DiagnosticSeverity.Warning, diagnostics.Single().Severity); } } [Fact] public void DiagnosticOptions_07() { var source = @" #pragma warning disable #nullable disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_08() { var source = @" #pragma warning disable #nullable enable partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_09() { var source = @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" #nullable disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_10() { var source = @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" #nullable enable partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_11() { var source = @" #nullable disable #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_12() { var source = @" #nullable disable #pragma warning disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_13() { var source = @" #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" #nullable disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_14() { var source = @" #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" #nullable enable partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_15() { var source = @" #nullable disable #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_16() { var source = @" #pragma warning restore partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_17() { var source = @" #nullable disable #pragma warning restore partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_18() { var source = @" #pragma warning restore #nullable disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_19() { var source = @" #nullable enable #pragma warning restore partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_20() { var source = @" #pragma warning restore #nullable enable partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_21() { var source = @" #nullable enable #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_NullAsNonNullable) + @" partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_22() { var source = @" #nullable restore partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_23() { var source = @" #nullable safeonly "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (2,11): error CS8637: Expected 'enable', 'disable', or 'restore' // #nullable safeonly Diagnostic(ErrorCode.ERR_NullableDirectiveQualifierExpected, "safeonly").WithLocation(2, 11) ); } [Fact] public void DiagnosticOptions_26() { var source = @" #nullable restore #nullable disable partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_27() { var source = @" #nullable restore #nullable enable partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_30() { var source = @" #nullable disable #nullable restore partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_32() { var source = @" #nullable enable #nullable restore partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_36() { var source = @" partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } private static void AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(string source) { var source2 = @" partial class Program { #nullable enable static object M() { return new object(); } }"; string id = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable); assertDiagnosticOptions1(NullableContextOptions.Enable); assertDiagnosticOptions1(NullableContextOptions.Warnings); assertDiagnosticOptions2(NullableContextOptions.Disable); assertDiagnosticOptions2(NullableContextOptions.Annotations); void assertDiagnosticOptions1(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions); var diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error). WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); } void assertDiagnosticOptions2(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions compilationOptions = WithNullable(nullableContextOptions); var comp = CreateCompilation(new[] { source, source2 }, options: compilationOptions); comp.VerifyDiagnostics(); foreach (ReportDiagnostic option in Enum.GetValues(typeof(ReportDiagnostic))) { comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable().WithSpecificDiagnosticOptions(id, option)); comp.VerifyDiagnostics(); comp = CreateCompilation(new[] { source, source2 }, options: WithNullableDisable().WithGeneralDiagnosticOption(option)); comp.VerifyDiagnostics(); } } } [Fact] public void DiagnosticOptions_37() { var source = @" #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_38() { var source = @" #nullable enable partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } private static void AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(string source) { var source2 = @" partial class Program { #nullable enable static object M() { return new object(); } }"; assertDiagnosticOptions(NullableContextOptions.Disable); assertDiagnosticOptions(NullableContextOptions.Enable); assertDiagnosticOptions(NullableContextOptions.Warnings); assertDiagnosticOptions(NullableContextOptions.Annotations); void assertDiagnosticOptions(NullableContextOptions nullableContextOptions) { CSharpCompilationOptions options = WithNullable(nullableContextOptions); string id = MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable); var comp = CreateCompilation(new[] { source, source2 }, options: options); var diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options.WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Error). WithGeneralDiagnosticOption(ReportDiagnostic.Default)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Suppress). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithGeneralDiagnosticOption(ReportDiagnostic.Suppress)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options.WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Hidden). WithGeneralDiagnosticOption(ReportDiagnostic.Error)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); comp = CreateCompilation(new[] { source, source2 }, options: options. WithSpecificDiagnosticOptions(id, ReportDiagnostic.Default). WithGeneralDiagnosticOption(ReportDiagnostic.Hidden)); diagnostics = comp.GetDiagnostics(); diagnostics.Verify(); } } [Fact] public void DiagnosticOptions_39() { var source = @" #pragma warning disable #nullable enable partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_40() { var source = @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" #nullable enable partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_41() { var source = @" #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" #nullable enable partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_42() { var source = @" #nullable disable #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_43() { var source = @" #pragma warning restore partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_44() { var source = @" #nullable disable #pragma warning restore partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_45() { var source = @" #nullable enable #pragma warning restore partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_46() { var source = @" #pragma warning restore #nullable enable partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_48() { var source = @" #nullable enable #pragma warning restore " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_49() { var source = @" #nullable restore partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_53() { var source = @" #nullable restore #nullable enable partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_56() { var source = @" #nullable disable #nullable restore partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_58() { var source = @" #nullable enable #nullable restore partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_62() { var source = @" #nullable disable warnings partial class Program { static void Test() { F(null); var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_63() { var source = @" #nullable enable warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_64() { var source = @" #pragma warning disable #nullable enable warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_65() { var source = @" #pragma warning disable " + MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ConvertingNullableToNonNullable) + @" #nullable enable warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableWarningsNeverGiven(source); } [Fact] public void DiagnosticOptions_66() { var source = @" #pragma warning restore #nullable enable warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_67() { var source = @" #nullable restore #nullable enable warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_UnlessDisabledByDiagnosticOptions(source); } [Fact] public void DiagnosticOptions_68() { var source = @" #nullable restore warnings partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_69() { var source = @" #nullable disable #nullable restore warnings partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_70() { var source = @" #nullable enable #nullable restore warnings partial class Program { static void Test() { F(null); } }"; AssertDiagnosticOptions_NullableWarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_72() { var source = @" #nullable restore warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_73() { var source = @" #nullable disable #nullable restore warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] public void DiagnosticOptions_74() { var source = @" #nullable enable #nullable restore warnings partial class Program { static void Test() { var x = M(); x = null; } }"; AssertDiagnosticOptions_NullableW_WarningsGiven_OnlyWhenEnabledInProject(source); } [Fact] [WorkItem(31394, "https://github.com/dotnet/roslyn/issues/31394")] public void InheritMemberNullability_Class() { var source = @"#pragma warning disable 8618 class C<T> { internal T F; } class Program { static void F() { C<object> x = new C<object?>() { F = null }; x.F/*T:object?*/.ToString(); // 1 C<object?> y = new C<object>() { F = new object() }; y.F/*T:object!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,23): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // C<object> x = new C<object?>() { F = null }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C<object?>() { F = null }").WithArguments("C<object?>", "C<object>").WithLocation(10, 23), // (11,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(11, 9), // (12,24): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // C<object?> y = new C<object>() { F = new object() }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C<object>() { F = new object() }").WithArguments("C<object>", "C<object?>").WithLocation(12, 24)); comp.VerifyTypes(); } [Fact] [WorkItem(31394, "https://github.com/dotnet/roslyn/issues/31394")] public void InheritMemberNullability_Struct() { var source = @"#pragma warning disable 8618 struct S<T> { internal T F; } class Program { static void F() { S<object> x = new S<object?>(); x.F/*T:object?*/.ToString(); // 1 S<object?> y = new S<object>() { F = new object() }; y.F/*T:object!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,23): warning CS8619: Nullability of reference types in value of type 'S<object?>' doesn't match target type 'S<object>'. // S<object> x = new S<object?>(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new S<object?>()").WithArguments("S<object?>", "S<object>").WithLocation(10, 23), // (11,9): warning CS8602: Dereference of a possibly null reference. // x.F/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(11, 9), // (12,24): warning CS8619: Nullability of reference types in value of type 'S<object>' doesn't match target type 'S<object?>'. // S<object?> y = new S<object>() { F = new object() }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new S<object>() { F = new object() }").WithArguments("S<object>", "S<object?>").WithLocation(12, 24)); comp.VerifyTypes(); } [Fact] [WorkItem(31394, "https://github.com/dotnet/roslyn/issues/31394")] public void InheritMemberNullability_AnonymousTypeField() { var source = @"class C<T> { } class Program { static void F1(C<object> x1, C<object?>? y1) { var a1 = new { F = x1 }; a1.F/*T:C<object!>!*/.ToString(); a1 = new { F = y1 }; a1.F/*T:C<object!>?*/.ToString(); // 1 } static void F2(C<object>? x2, C<object?> y2) { var a2 = new { F = x2 }; a2.F/*T:C<object!>?*/.ToString(); // 2 a2 = new { F = y2 }; a2.F/*T:C<object!>!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: C<object?>? F>' doesn't match target type '<anonymous type: C<object> F>'. // a1 = new { F = y1 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new { F = y1 }").WithArguments("<anonymous type: C<object?>? F>", "<anonymous type: C<object> F>").WithLocation(8, 14), // (9,9): warning CS8602: Dereference of a possibly null reference. // a1.F/*T:C<object!>?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a1.F").WithLocation(9, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // a2.F/*T:C<object!>?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2.F").WithLocation(14, 9), // (15,14): warning CS8619: Nullability of reference types in value of type '<anonymous type: C<object?> F>' doesn't match target type '<anonymous type: C<object>? F>'. // a2 = new { F = y2 }; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new { F = y2 }").WithArguments("<anonymous type: C<object?> F>", "<anonymous type: C<object>? F>").WithLocation(15, 14)); comp.VerifyTypes(); } [Fact] [WorkItem(31394, "https://github.com/dotnet/roslyn/issues/31394")] public void InheritMemberNullability_TupleElement_01() { var source = @"class C<T> { } class Program { static void F1(C<object> x1, C<object?>? y1) { var t1 = (x1, y1); t1.Item1/*T:C<object!>!*/.ToString(); t1 = (y1, y1); t1.Item1/*T:C<object!>?*/.ToString(); // 1 } static void F2(C<object>? x2, C<object?> y2) { var t2 = (x2, y2); t2.Item1/*T:C<object!>?*/.ToString(); // 2 t2 = (y2, y2); t2.Item1/*T:C<object!>!*/.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,14): warning CS8619: Nullability of reference types in value of type '(C<object?>?, C<object?>?)' doesn't match target type '(C<object> x1, C<object?>? y1)'. // t1 = (y1, y1); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(y1, y1)").WithArguments("(C<object?>?, C<object?>?)", "(C<object> x1, C<object?>? y1)").WithLocation(8, 14), // (9,9): warning CS8602: Dereference of a possibly null reference. // t1.Item1/*T:C<object!>?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1.Item1").WithLocation(9, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // t2.Item1/*T:C<object!>?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2.Item1").WithLocation(14, 9), // (15,14): warning CS8619: Nullability of reference types in value of type '(C<object?>, C<object?>)' doesn't match target type '(C<object>? x2, C<object?> y2)'. // t2 = (y2, y2); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(y2, y2)").WithArguments("(C<object?>, C<object?>)", "(C<object>? x2, C<object?> y2)").WithLocation(15, 14)); comp.VerifyTypes(); } [Fact] [WorkItem(31394, "https://github.com/dotnet/roslyn/issues/31394")] public void InheritMemberNullability_TupleElement_02() { var source = @"class C<T> { } class Program { static void F(C<object> x, C<object?>? y) { (C<object?>? a, C<object> b) t = (x, y); t.a/*T:C<object?>!*/.ToString(); t.b/*T:C<object!>?*/.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,42): warning CS8619: Nullability of reference types in value of type '(C<object> x, C<object?>? y)' doesn't match target type '(C<object?>? a, C<object> b)'. // (C<object?>? a, C<object> b) t = (x, y); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, y)").WithArguments("(C<object> x, C<object?>? y)", "(C<object?>? a, C<object> b)").WithLocation(6, 42), // (8,9): warning CS8602: Dereference of a possibly null reference. // t.b/*T:C<object!>?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.b").WithLocation(8, 9)); comp.VerifyTypes(); } private static readonly NullableAnnotation[] s_AllNullableAnnotations = ((NullableAnnotation[])Enum.GetValues(typeof(NullableAnnotation))).Where(n => n != NullableAnnotation.Ignored).ToArray(); private static readonly NullableFlowState[] s_AllNullableFlowStates = (NullableFlowState[])Enum.GetValues(typeof(NullableFlowState)); [Fact] public void TestJoinForNullableAnnotations() { var inputs = new[] { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }; Func<int, int, NullableAnnotation> getResult = (i, j) => NullableAnnotationExtensions.Join(inputs[i], inputs[j]); var expected = new NullableAnnotation[3, 3] { { NullableAnnotation.Annotated, NullableAnnotation.Annotated, NullableAnnotation.Annotated }, { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.Oblivious }, { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }, }; AssertEqual(expected, getResult, inputs.Length); } [Fact] public void TestJoinForNullableFlowStates() { var inputs = new[] { NullableFlowState.NotNull, NullableFlowState.MaybeNull }; Func<int, int, NullableFlowState> getResult = (i, j) => inputs[i].Join(inputs[j]); var expected = new NullableFlowState[2, 2] { { NullableFlowState.NotNull, NullableFlowState.MaybeNull }, { NullableFlowState.MaybeNull, NullableFlowState.MaybeNull }, }; AssertEqual(expected, getResult, inputs.Length); } [Fact] public void TestMeetForNullableAnnotations() { var inputs = new[] { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }; Func<int, int, NullableAnnotation> getResult = (i, j) => NullableAnnotationExtensions.Meet(inputs[i], inputs[j]); var expected = new NullableAnnotation[3, 3] { { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }, { NullableAnnotation.Oblivious, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }, { NullableAnnotation.NotAnnotated, NullableAnnotation.NotAnnotated, NullableAnnotation.NotAnnotated }, }; AssertEqual(expected, getResult, inputs.Length); } [Fact] public void TestMeetForNullableFlowStates() { var inputs = new[] { NullableFlowState.NotNull, NullableFlowState.MaybeNull }; Func<int, int, NullableFlowState> getResult = (i, j) => inputs[i].Meet(inputs[j]); var expected = new NullableFlowState[2, 2] { { NullableFlowState.NotNull, NullableFlowState.NotNull }, { NullableFlowState.NotNull, NullableFlowState.MaybeNull }, }; AssertEqual(expected, getResult, inputs.Length); } [Fact] public void TestEnsureCompatible() { var inputs = new[] { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }; Func<int, int, NullableAnnotation> getResult = (i, j) => NullableAnnotationExtensions.EnsureCompatible(inputs[i], inputs[j]); var expected = new NullableAnnotation[3, 3] { { NullableAnnotation.Annotated, NullableAnnotation.Annotated, NullableAnnotation.NotAnnotated }, { NullableAnnotation.Annotated, NullableAnnotation.Oblivious, NullableAnnotation.NotAnnotated }, { NullableAnnotation.NotAnnotated, NullableAnnotation.NotAnnotated, NullableAnnotation.NotAnnotated }, }; AssertEqual(expected, getResult, inputs.Length); } private static void AssertEqual(NullableAnnotation[,] expected, Func<int, int, NullableAnnotation> getResult, int size) { AssertEx.Equal<NullableAnnotation>(expected, getResult, (na1, na2) => na1 == na2, na => $"NullableAnnotation.{na}", "{0,-32:G}", size); } private static void AssertEqual(NullableFlowState[,] expected, Func<int, int, NullableFlowState> getResult, int size) { AssertEx.Equal<NullableFlowState>(expected, getResult, (na1, na2) => na1 == na2, na => $"NullableFlowState.{na}", "{0,-32:G}", size); } [Fact] public void TestAbsorptionForNullableAnnotations() { foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { Assert.Equal(a, a.Meet(a.Join(b))); Assert.Equal(a, a.Join(a.Meet(b))); } } } [Fact] public void TestAbsorptionForNullableFlowStates() { foreach (var a in s_AllNullableFlowStates) { foreach (var b in s_AllNullableFlowStates) { Assert.Equal(a, a.Meet(a.Join(b))); Assert.Equal(a, a.Join(a.Meet(b))); } } } [Fact] public void TestJoinForNullableAnnotationsIsAssociative() { foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { foreach (var c in s_AllNullableAnnotations) { var leftFirst = a.Join(b).Join(c); var rightFirst = a.Join(b.Join(c)); Assert.Equal(leftFirst, rightFirst); } } } } [Fact] public void TestJoinForNullableFlowStatesIsAssociative() { foreach (var a in s_AllNullableFlowStates) { foreach (var b in s_AllNullableFlowStates) { foreach (var c in s_AllNullableFlowStates) { var leftFirst = a.Join(b).Join(c); var rightFirst = a.Join(b.Join(c)); Assert.Equal(leftFirst, rightFirst); } } } } [Fact] public void TestMeetForNullableAnnotationsIsAssociative() { foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { foreach (var c in s_AllNullableAnnotations) { var leftFirst = a.Meet(b).Meet(c); var rightFirst = a.Meet(b.Meet(c)); Assert.Equal(leftFirst, rightFirst); } } } } [Fact] public void TestMeetForNullableFlowStatesIsAssociative() { foreach (var a in s_AllNullableFlowStates) { foreach (var b in s_AllNullableFlowStates) { foreach (var c in s_AllNullableFlowStates) { var leftFirst = a.Meet(b).Meet(c); var rightFirst = a.Meet(b.Meet(c)); Assert.Equal(leftFirst, rightFirst); } } } } [Fact] public void TestEnsureCompatibleIsAssociative() { Func<bool, bool> identity = x => x; foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { foreach (var c in s_AllNullableAnnotations) { foreach (bool isPossiblyNullableReferenceTypeTypeParameter in new[] { true, false }) { var leftFirst = a.EnsureCompatible(b).EnsureCompatible(c); var rightFirst = a.EnsureCompatible(b.EnsureCompatible(c)); Assert.Equal(leftFirst, rightFirst); } } } } } [Fact] public void TestJoinForNullableAnnotationsIsCommutative() { foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { var leftFirst = a.Join(b); var rightFirst = b.Join(a); Assert.Equal(leftFirst, rightFirst); } } } [Fact] public void TestJoinForNullableFlowStatesIsCommutative() { Func<bool, bool> identity = x => x; foreach (var a in s_AllNullableFlowStates) { foreach (var b in s_AllNullableFlowStates) { var leftFirst = a.Join(b); var rightFirst = b.Join(a); Assert.Equal(leftFirst, rightFirst); } } } [Fact] public void TestMeetForNullableAnnotationsIsCommutative() { foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { var leftFirst = a.Meet(b); var rightFirst = b.Meet(a); Assert.Equal(leftFirst, rightFirst); } } } [Fact] public void TestMeetForNullableFlowStatesIsCommutative() { foreach (var a in s_AllNullableFlowStates) { foreach (var b in s_AllNullableFlowStates) { var leftFirst = a.Meet(b); var rightFirst = b.Meet(a); Assert.Equal(leftFirst, rightFirst); } } } [Fact] public void TestEnsureCompatibleIsCommutative() { foreach (var a in s_AllNullableAnnotations) { foreach (var b in s_AllNullableAnnotations) { var leftFirst = a.EnsureCompatible(b); var rightFirst = b.EnsureCompatible(a); Assert.Equal(leftFirst, rightFirst); } } } [Fact] public void NullableT_CSharp7() { var source = @"class Program { static void F<T>(T? x) where T : struct { _ = x.Value; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular7, options: WithNullableEnable()); comp.VerifyDiagnostics( // error CS8630: Invalid 'NullableContextOptions' value: 'Enable' for C# 7.0. Please use language version '8.0' or greater. Diagnostic(ErrorCode.ERR_NullableOptionNotAvailable).WithArguments("NullableContextOptions", "Enable", "7.0", "8.0").WithLocation(1, 1) ); } [Fact] public void NullableT_WarningDisabled() { var source = @"#nullable disable //#nullable disable warnings class Program { static void F<T>(T? x) where T : struct { _ = x.Value; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void NullableT_01() { var source = @"class Program { static void F<T>(T? x) where T : struct { _ = x.Value; // 1 _ = x.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,13): warning CS8629: Nullable value type may be null. // _ = x.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(5, 13) ); } [Fact] public void NullableT_02() { var source = @"class Program { static void F<T>(T x) where T : struct { T? y = x; _ = y.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_03() { var source = @"class Program { static void F<T>(T? x) where T : struct { T y = x; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,15): error CS0266: Cannot implicitly convert type 'T?' to 'T'. An explicit conversion exists (are you missing a cast?) // T y = x; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "x").WithArguments("T?", "T").WithLocation(5, 15), // (5,15): warning CS8629: Nullable value type may be null. // T y = x; Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(5, 15)); } [Fact] public void NullableT_04() { var source = @"class Program { static T F1<T>(T? x) where T : struct { return (T)x; // 1 } static T F2<T>() where T : struct { return (T)default(T?); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,16): warning CS8629: Nullable value type may be null. // return (T)x; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)x").WithLocation(5, 16), // (9,16): warning CS8629: Nullable value type may be null. // return (T)default(T?); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)default(T?)").WithLocation(9, 16)); } [Fact] public void NullableT_05() { var source = @"using System; class Program { static void F<T>() where T : struct { _ = nameof(Nullable<T>.HasValue); _ = nameof(Nullable<T>.Value); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_06() { var source = @"class Program { static void F<T>(T? x, T? y) where T : struct { _ = (T)x; // 1 _ = (T)x; x = y; _ = (T)x; // 2 _ = (T)x; _ = (T)y; // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,13): warning CS8629: Nullable value type may be null. // _ = (T)x; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)x").WithLocation(5, 13), // (8,13): warning CS8629: Nullable value type may be null. // _ = (T)x; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)x").WithLocation(8, 13), // (10,13): warning CS8629: Nullable value type may be null. // _ = (T)y; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)y").WithLocation(10, 13)); } [Fact] public void NullableT_07() { var source = @"class Program { static void F1((int, int) x) { (int, int)? y = x; _ = y.Value; var z = ((int, int))y; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_08() { var source = @"class Program { static void F1((int, int)? x) { var y = ((int, int))x; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,17): warning CS8629: Nullable value type may be null. // var y = ((int, int))x; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "((int, int))x").WithLocation(5, 17)); } [Fact] public void NullableT_09() { var source = @"class Program { static void F<T>(T t) where T : struct { T? x = null; _ = x.Value; // 1 T? y = default; _ = y.Value; // 2 T? z = default(T); _ = z.Value; T? w = t; _ = w.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8629: Nullable value type may be null. // _ = x.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(6, 13), // (8,13): warning CS8629: Nullable value type may be null. // _ = y.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(8, 13) ); } [WorkItem(31502, "https://github.com/dotnet/roslyn/issues/31502")] [Fact] public void NullableT_10() { var source = @"class Program { static void F<T>(T t) where T : struct { T? x = new System.Nullable<T>(); _ = x.Value; // 1 T? y = new System.Nullable<T>(t); _ = y.Value; T? z = new T?(); _ = z.Value; // 2 T? w = new T?(t); _ = w.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8629: Nullable value type may be null. // _ = x.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(6, 13), // (10,13): warning CS8629: Nullable value type may be null. // _ = z.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "z").WithLocation(10, 13) ); } [Fact] public void NullableT_11() { var source = @"class C<T> where T : struct { static void F1(T? t1) { if (t1.HasValue) _ = t1.Value; else _ = t1.Value; // 1 } static void F2(T? t2) { if (!t2.HasValue) _ = t2.Value; // 2 else _ = t2.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,17): warning CS8629: Nullable value type may be null. // _ = t1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t1").WithLocation(8, 17), // (13,17): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(13, 17) ); } [Fact] public void NullableT_12() { var source = @"class C<T> where T : struct { static void F1(T? t1) { if (t1 != null) _ = t1.Value; else _ = t1.Value; // 1 } static void F2(T? t2) { if (t2 == null) _ = t2.Value; // 2 else _ = t2.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,17): warning CS8629: Nullable value type may be null. // _ = t1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t1").WithLocation(8, 17), // (13,17): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(13, 17) ); } [Fact] public void NullableT_13() { var source = @"class C<T> where T : struct { static void F1(T? t1) { if (null != t1) _ = (T)t1; else _ = (T)t1; // 1 } static void F2(T? t2) { if (null == t2) { var o2 = (object)t2; // 2 o2.ToString(); // 3 } else { var o2 = (object)t2; o2.ToString(); } } static void F3(T? t3) { if (null == t3) { var d3 = (dynamic)t3; // 4 d3.ToString(); // 5 } else { var d3 = (dynamic)t3; d3.ToString(); } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,17): warning CS8629: Nullable value type may be null. // _ = (T)t1; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)t1").WithLocation(8, 17), // (14,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var o2 = (object)t2; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t2").WithLocation(14, 22), // (15,13): warning CS8602: Dereference of a possibly null reference. // o2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o2").WithLocation(15, 13), // (27,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var d3 = (dynamic)t3; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(dynamic)t3").WithLocation(27, 22), // (28,13): warning CS8602: Dereference of a possibly null reference. // d3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "d3").WithLocation(28, 13)); } [Fact] public void NullableT_14() { var source = @"class C<T> where T : struct { static void F1(T? t1) { if (t1.HasValue) { if (t1.HasValue) _ = t1.Value; else _ = t1.Value; } } static void F2(T? t2) { if (t2 != null) { if (!t2.HasValue) _ = t2.Value; else _ = t2.Value; } } static void F3(T? t3) { if (!t3.HasValue) { if (t3 != null) _ = t3.Value; else _ = t3.Value; // 1 } } static void F4(T? t4) { if (t4 == null) { if (t4 == null) _ = t4.Value; // 2 else _ = t4.Value; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (24,22): warning CS8629: Nullable value type may be null. // else _ = t3.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t3").WithLocation(24, 22), // (31,33): warning CS8629: Nullable value type may be null. // if (t4 == null) _ = t4.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4").WithLocation(31, 33) ); } [Fact] public void NullableT_15() { var source = @"class C<T> where T : struct { static void F1(T? x1, T? y1) { _ = x1.HasValue ? x1.Value : y1.Value; // 1 } static void F2(T? x2, T? y2) { _ = !x2.HasValue ? y2.Value : // 2 x2.Value; } static void F3(T? x3, T? y3) { _ = x3.HasValue || y3.HasValue ? x3.Value : // 3 y3.Value; // 4 } static void F4(T? x4, T? y4) { _ = x4.HasValue && y4.HasValue ? (T)x4 : (T)y4; // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8629: Nullable value type may be null. // y1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y1").WithLocation(7, 13), // (12,13): warning CS8629: Nullable value type may be null. // y2.Value : // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y2").WithLocation(12, 13), // (18,13): warning CS8629: Nullable value type may be null. // x3.Value : // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x3").WithLocation(18, 13), // (19,13): warning CS8629: Nullable value type may be null. // y3.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y3").WithLocation(19, 13), // (25,13): warning CS8629: Nullable value type may be null. // (T)y4; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)y4").WithLocation(25, 13) ); } [Fact] public void NullableT_16() { var source = @"class C<T> where T : struct { static void F1(T? x1, T? y1) { _ = x1 != null ? x1.Value : y1.Value; // 1 } static void F2(T? x2, T? y2) { _ = x2 == null ? y2.Value : // 2 x2.Value; } static void F3(T? x3, T? y3) { _ = x3 != null || y3 != null ? x3.Value : // 3 y3.Value; // 4 } static void F4(T? x4, T? y4) { _ = x4 != null && y4 != null ? (T)x4 : (T)y4; // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8629: Nullable value type may be null. // y1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y1").WithLocation(7, 13), // (12,13): warning CS8629: Nullable value type may be null. // y2.Value : // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y2").WithLocation(12, 13), // (18,13): warning CS8629: Nullable value type may be null. // x3.Value : // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x3").WithLocation(18, 13), // (19,13): warning CS8629: Nullable value type may be null. // y3.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y3").WithLocation(19, 13), // (25,13): warning CS8629: Nullable value type may be null. // (T)y4; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)y4").WithLocation(25, 13) ); } [Fact, WorkItem(33924, "https://github.com/dotnet/roslyn/issues/33924")] public void NullableT_17() { var source = @"class C<T> where T : struct { static void F1(T? x1, T? y1) { _ = (T)(x1 != null ? x1 : y1); // 1 } static void F2(T? x2, T? y2) { if (y2 == null) return; _ = (T)(x2 != null ? x2 : y2); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,13): warning CS8629: Nullable value type may be null. // _ = (T)(x1 != null ? x1 : y1); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)(x1 != null ? x1 : y1)").WithLocation(5, 13)); } [Fact] public void NullableT_18() { var source = @"class C<T> where T : struct { static void F1(T? x1, T? y1) { object? z1 = x1 != null ? (object?)x1 : y1; _ = z1/*T:object?*/.ToString(); // 1 dynamic? w1 = x1 != null ? (dynamic?)x1 : y1; _ = w1/*T:dynamic?*/.ToString(); // 2 } static void F2(T? x2, T? y2) { if (y2 == null) return; object? z2 = x2 != null ? (object?)x2 : y2; _ = z2/*T:object?*/.ToString(); // 3 dynamic? w2 = x2 != null ? (dynamic?)x2 : y2; _ = w2/*T:dynamic?*/.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8602: Dereference of a possibly null reference. // _ = z1/*T:object?*/.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1").WithLocation(6, 13), // (8,13): warning CS8602: Dereference of a possibly null reference. // _ = w1/*T:dynamic?*/.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w1").WithLocation(8, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = z2/*T:object!*/.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2").WithLocation(14, 13), // (16,13): warning CS8602: Dereference of a possibly null reference. // _ = w2/*T:dynamic!*/.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w2").WithLocation(16, 13) ); comp.VerifyTypes(); } [Fact] public void NullableT_19() { var source = @"#pragma warning disable 0649 struct A { internal B? B; } struct B { internal C? C; } struct C { } class Program { static void F1(A? na1) { if (na1?.B?.C != null) { _ = na1.Value.B.Value.C.Value; } else { A a1 = na1.Value; // 1 B b1 = a1.B.Value; // 2 C c1 = b1.C.Value; // 3 } } static void F2(A? na2) { if (na2?.B?.C != null) { _ = (C)((B)((A)na2).B).C; } else { A a2 = (A)na2; // 4 B b2 = (B)a2.B; // 5 C c2 = (C)b2.C; // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,20): warning CS8629: Nullable value type may be null. // A a1 = na1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "na1").WithLocation(23, 20), // (24,20): warning CS8629: Nullable value type may be null. // B b1 = a1.B.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "a1.B").WithLocation(24, 20), // (25,20): warning CS8629: Nullable value type may be null. // C c1 = b1.C.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "b1.C").WithLocation(25, 20), // (36,20): warning CS8629: Nullable value type may be null. // A a2 = (A)na2; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(A)na2").WithLocation(36, 20), // (37,20): warning CS8629: Nullable value type may be null. // B b2 = (B)a2.B; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(B)a2.B").WithLocation(37, 20), // (38,20): warning CS8629: Nullable value type may be null. // C c2 = (C)b2.C; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(C)b2.C").WithLocation(38, 20) ); } [Fact] public void NullableT_20() { var source = @"#pragma warning disable 0649 struct A { internal B? B; } struct B { } class Program { static void F1(A? na1) { if (na1?.B != null) { var a1 = (object)na1; a1.ToString(); } else { var a1 = (object)na1; // 1 a1.ToString(); // 2 } } static void F2(A? na2) { if (na2?.B != null) { var a2 = (System.ValueType)na2; a2.ToString(); } else { var a2 = (System.ValueType)na2; // 3 a2.ToString(); // 4 } } static void F3(A? na3) { if (na3?.B != null) { var a3 = (A)na3; var b3 = (object)a3.B; b3.ToString(); } else { var a3 = (A)na3; // 5 var b3 = (object)a3.B; // 6 b3.ToString(); // 7 } } static void F4(A? na4) { if (na4?.B != null) { var a4 = (A)na4; var b4 = (System.ValueType)a4.B; b4.ToString(); } else { var a4 = (A)na4; // 8 var b4 = (System.ValueType)a4.B; // 9 b4.ToString(); // 10 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var a1 = (object)na1; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)na1").WithLocation(20, 22), // (21,13): warning CS8602: Dereference of a possibly null reference. // a1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a1").WithLocation(21, 13), // (33,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var a2 = (System.ValueType)na2; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(System.ValueType)na2").WithLocation(33, 22), // (34,13): warning CS8602: Dereference of a possibly null reference. // a2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a2").WithLocation(34, 13), // (47,22): warning CS8629: Nullable value type may be null. // var a3 = (A)na3; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(A)na3").WithLocation(47, 22), // (48,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var b3 = (object)a3.B; // 6 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)a3.B").WithLocation(48, 22), // (49,13): warning CS8602: Dereference of a possibly null reference. // b3.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b3").WithLocation(49, 13), // (62,22): warning CS8629: Nullable value type may be null. // var a4 = (A)na4; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(A)na4").WithLocation(62, 22), // (63,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var b4 = (System.ValueType)a4.B; // 9 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(System.ValueType)a4.B").WithLocation(63, 22), // (64,13): warning CS8602: Dereference of a possibly null reference. // b4.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b4").WithLocation(64, 13)); } [Fact] public void NullableT_21() { var source = @"#pragma warning disable 0649 struct A { internal B? B; public static implicit operator C(A a) => new C(); } struct B { public static implicit operator C(B b) => new C(); } class C { } class Program { static void F1(A? na1) { if (na1?.B != null) { var c1 = (C)na1; c1.ToString(); } else { var c1 = (C)na1; // 1 c1.ToString(); // 2 } } static void F2(A? na2) { if (na2?.B != null) { var a2 = (A)na2; var c2 = (C)a2.B; c2.ToString(); } else { var a2 = (A)na2; // 3 var c2 = (C)a2.B; // 4 c2.ToString(); // 5 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (25,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var c1 = (C)na1; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)na1").WithLocation(25, 22), // (26,13): warning CS8602: Dereference of a possibly null reference. // c1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(26, 13), // (39,22): warning CS8629: Nullable value type may be null. // var a2 = (A)na2; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(A)na2").WithLocation(39, 22), // (40,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // var c2 = (C)a2.B; // 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(C)a2.B").WithLocation(40, 22), // (41,13): warning CS8602: Dereference of a possibly null reference. // c2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(41, 13)); } [Fact] public void NullableT_22() { var source = @"#pragma warning disable 0649 struct S { internal C? C; } class C { internal S? S; } class Program { static void F1(S? ns) { if (ns?.C != null) { _ = ns.Value.C.ToString(); } else { var s = ns.Value; // 1 var c = s.C; c.ToString(); // 2 } } static void F2(C? nc) { if (nc?.S != null) { _ = nc.S.Value; } else { var ns = nc.S; // 3 _ = ns.Value; // 4 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (20,21): warning CS8629: Nullable value type may be null. // var s = ns.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ns").WithLocation(20, 21), // (22,13): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(22, 13), // (34,22): warning CS8602: Dereference of a possibly null reference. // var ns = nc.S; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "nc").WithLocation(34, 22), // (35,17): warning CS8629: Nullable value type may be null. // _ = ns.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ns").WithLocation(35, 17) ); } [Fact] public void NullableT_IntToLong() { var source = @"class Program { // int -> long? static void F1(int i) { var nl1 = (long?)i; _ = nl1.Value; long? nl2 = i; _ = nl2.Value; int? ni = i; long? nl3 = ni; _ = nl3.Value; } // int? -> long? static void F2(int? ni) { if (ni.HasValue) { long? nl1 = ni; _ = nl1.Value; var nl2 = (long?)ni; _ = nl2.Value; } else { long? nl3 = ni; _ = nl3.Value; // 1 var nl4 = (long?)ni; _ = nl4.Value; // 2 } } // int? -> long static void F3(int? ni) { if (ni.HasValue) { _ = (long)ni; } else { _ = (long)ni; // 3 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (27,17): warning CS8629: Nullable value type may be null. // _ = nl3.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl3").WithLocation(27, 17), // (29,17): warning CS8629: Nullable value type may be null. // _ = nl4.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl4").WithLocation(29, 17), // (41,17): warning CS8629: Nullable value type may be null. // _ = (long)ni; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(long)ni").WithLocation(41, 17) ); } [Fact] public void NullableT_LongToStruct() { var source = @"struct S { public static implicit operator S(long l) => new S(); } class Program { // int -> long -> S -> S? static void F1(int i) { var s1 = (S?)i; _ = s1.Value; S? s2 = i; _ = s2.Value; int? ni = i; S? s3 = ni; _ = s3.Value; } // int? -> long? -> S? static void F2(int? ni) { if (ni.HasValue) { var s1 = (S?)ni; _ = s1.Value; S? s2 = ni; _ = s2.Value; } else { var s3 = (S?)ni; _ = s3.Value; // 1 S? s4 = ni; _ = s4.Value; // 2 } } // int? -> long? -> S? -> S static void F3(int? ni) { if (ni.HasValue) { _ = (S)ni; } else { _ = (S)ni; // 3 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (31,17): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(31, 17), // (33,17): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(33, 17), // (45,20): warning CS8629: Nullable value type may be null. // _ = (S)ni; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ni").WithLocation(45, 20) ); } [Fact] public void NullableT_LongToNullableStruct() { var source = @"struct S { public static implicit operator S?(long l) => new S(); } class Program { // int -> long -> S? static void F1(int i) { var s1 = (S?)i; _ = s1.Value; // 1 S? s2 = i; _ = s2.Value; // 2 int? ni = i; S? s3 = ni; _ = s3.Value; // 3 } // int? -> long? -> S? static void F2(int? ni) { if (ni.HasValue) { var s1 = (S?)ni; _ = s1.Value; // 4 S? s2 = ni; _ = s2.Value; // 5 } else { var s3 = (S?)ni; _ = s3.Value; // 6 S? s4 = ni; _ = s4.Value; // 7 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(13, 13), // (16,13): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(16, 13), // (24,17): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(24, 17), // (26,17): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(26, 17), // (31,17): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(31, 17), // (33,17): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(33, 17) ); } [Fact] public void NullableT_NullableLongToStruct() { var source = @"struct S { public static implicit operator S(long? l) => new S(); } class Program { // int -> int? -> long? -> S static void F1(int i) { _ = (S)i; S s = i; } // int? -> long? -> S static void F2(int? ni) { _ = (S)ni; S s = ni; } // int? -> long? -> S -> S? static void F3(int? ni) { var ns1 = (S?)ni; _ = ns1.Value; S? ns2 = ni; _ = ns1.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_NullableLongToNullableStruct() { var source = @"struct S { public static implicit operator S?(long? l) => new S(); } class Program { // int -> int? -> long? -> S static void F1(int i) { _ = (S)i; // 1 } // int? -> long? -> S? static void F2(int? ni) { if (ni.HasValue) { var ns1 = (S?)ni; _ = ns1.Value; // 2 S? ns2 = ni; _ = ns2.Value; // 3 } else { var ns3 = (S?)ni; _ = ns3.Value; // 4 S? ns4 = ni; _ = ns4.Value; // 5 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8629: Nullable value type may be null. // _ = (S)i; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(S)i").WithLocation(10, 13), // (18,17): warning CS8629: Nullable value type may be null. // _ = ns1.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ns1").WithLocation(18, 17), // (20,17): warning CS8629: Nullable value type may be null. // _ = ns2.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ns2").WithLocation(20, 17), // (25,17): warning CS8629: Nullable value type may be null. // _ = ns3.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ns3").WithLocation(25, 17), // (27,17): warning CS8629: Nullable value type may be null. // _ = ns4.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ns4").WithLocation(27, 17) ); } [Fact] public void NullableT_StructToInt() { var source = @"struct S { public static implicit operator int(S s) => 0; } class Program { // S -> int -> long? static void F1(S s) { var nl1 = (long?)s; _ = nl1.Value; long? nl2 = s; _ = nl2.Value; } // S? -> int? -> long? static void F2(S? ns) { if (ns.HasValue) { var nl1 = (long?)ns; _ = nl1.Value; long? nl2 = ns; _ = nl2.Value; } else { var nl1 = (long?)ns; _ = nl1.Value; // 1 long? nl2 = ns; _ = nl2.Value; // 2 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (28,17): warning CS8629: Nullable value type may be null. // _ = nl1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl1").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = nl2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl2").WithLocation(30, 17) ); } [Fact] public void NullableT_StructToNullableInt() { var source = @"struct S { public static implicit operator int?(S s) => 0; } class Program { // S -> int? -> long? static void F1(S s) { var nl1 = (long?)s; _ = nl1.Value; // 1 long? nl2 = s; _ = nl2.Value; // 2 } // S? -> int? -> long? static void F2(S? ns) { if (ns.HasValue) { var nl1 = (long?)ns; _ = nl1.Value; // 3 long? nl2 = ns; _ = nl2.Value; // 4 } else { var nl1 = (long?)ns; _ = nl1.Value; // 5 long? nl2 = ns; _ = nl2.Value; // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = nl1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = nl2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = nl1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = nl2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl2").WithLocation(23, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = nl1.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl1").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = nl2.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl2").WithLocation(30, 17) ); } [Fact] public void NullableT_NullableStructToInt() { var source = @"struct S { public static implicit operator int(S? s) => 0; } class Program { // S -> S? -> int -> long static void F1(S s) { _ = (long)s; long l2 = s; } // S? -> int -> long static void F2(S? ns) { if (ns.HasValue) { _ = (long)ns; long l2 = ns; } else { _ = (long)ns; long l2 = ns; } } // S? -> int -> long -> long? static void F3(S? ns) { if (ns.HasValue) { var nl1 = (long?)ns; _ = nl1.Value; long? nl2 = ns; _ = nl2.Value; } else { var nl1 = (long?)ns; _ = nl1.Value; long? nl2 = ns; _ = nl2.Value; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_NullableStructToNullableInt() { var source = @"struct S { public static implicit operator int?(S? s) => 0; } class Program { // S -> S? -> int? -> long? static void F1(S s) { var nl1 = (long?)s; _ = nl1.Value; // 1 long? nl2 = s; _ = nl2.Value; // 2 } // S? -> int? -> long? static void F2(S? ns) { if (ns.HasValue) { var nl1 = (long?)ns; _ = nl1.Value; // 3 long? nl2 = ns; _ = nl2.Value; // 4 } else { var nl3 = (long?)ns; _ = nl3.Value; // 5 long? nl4 = ns; _ = nl4.Value; // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = nl1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = nl2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = nl1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = nl2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl2").WithLocation(23, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = nl3.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl3").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = nl4.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "nl4").WithLocation(30, 17) ); } [Fact] [WorkItem(35334, "https://github.com/dotnet/roslyn/issues/35334")] public void NullableT_StructToClass() { var source = @"struct S { public static implicit operator C(S s) => new C(); } class C { } class Program { // S -> C static void F1(S s) { var c1 = (C)s; _ = c1.ToString(); C c2 = s; _ = c2.ToString(); } // S? -> C? static void F2(S? ns) { if (ns.HasValue) { var c1 = (C?)ns; _ = c1.ToString(); // 1 C? c2 = ns; _ = c2.ToString(); } else { var c3 = (C?)ns; _ = c3.ToString(); // 2 C? c4 = ns; _ = c4.ToString(); // 3 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(24, 17), // (31,17): warning CS8602: Dereference of a possibly null reference. // _ = c3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c3").WithLocation(31, 17), // (33,17): warning CS8602: Dereference of a possibly null reference. // _ = c4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c4").WithLocation(33, 17)); } [Fact] public void NullableT_StructToNullableClass() { var source = @"struct S { public static implicit operator C?(S s) => new C(); } class C { } class Program { // S -> C? static void F1(S s) { var c1 = (C?)s; _ = c1.ToString(); // 1 C? c2 = s; _ = c2.ToString(); // 2 } // S? -> C? static void F2(S? ns) { if (ns.HasValue) { var c1 = (C?)ns; _ = c1.ToString(); // 3 C? c2 = ns; _ = c2.ToString(); // 4 } else { var c3 = (C?)ns; _ = c3.ToString(); // 5 C? c4 = ns; _ = c4.ToString(); // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(14, 13), // (16,13): warning CS8602: Dereference of a possibly null reference. // _ = c2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(16, 13), // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(24, 17), // (26,17): warning CS8602: Dereference of a possibly null reference. // _ = c2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(26, 17), // (31,17): warning CS8602: Dereference of a possibly null reference. // _ = c3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c3").WithLocation(31, 17), // (33,17): warning CS8602: Dereference of a possibly null reference. // _ = c4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c4").WithLocation(33, 17)); } [Fact] [WorkItem(35334, "https://github.com/dotnet/roslyn/issues/35334")] public void NullableT_NullableStructToClass() { var source = @"struct S { public static implicit operator C(S? s) => new C(); } class C { } class Program { // S -> C static void F1(S s) { var c1 = (C)s; _ = c1.ToString(); C c2 = s; _ = c2.ToString(); } // S? -> C? static void F2(S? ns) { if (ns.HasValue) { var c1 = (C?)ns; _ = c1.ToString(); // 1 C? c2 = ns; _ = c2.ToString(); } else { var c3 = (C?)ns; _ = c3.ToString(); // 2 C? c4 = ns; _ = c4.ToString(); } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(24, 17), // (31,17): warning CS8602: Dereference of a possibly null reference. // _ = c3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c3").WithLocation(31, 17)); } [Fact] public void NullableT_NullableStructToNullableClass() { var source = @"struct S { public static implicit operator C?(S? s) => new C(); } class C { } class Program { // S -> C? static void F1(S s) { var c1 = (C?)s; _ = c1.ToString(); // 1 C? c2 = s; _ = c2.ToString(); // 2 } // S? -> C? static void F2(S? ns) { if (ns.HasValue) { var c1 = (C?)ns; _ = c1.ToString(); // 3 C? c2 = ns; _ = c2.ToString(); // 4 } else { var c3 = (C?)ns; _ = c3.ToString(); // 5 C? c4 = ns; _ = c4.ToString(); // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(14, 13), // (16,13): warning CS8602: Dereference of a possibly null reference. // _ = c2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(16, 13), // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(24, 17), // (26,17): warning CS8602: Dereference of a possibly null reference. // _ = c2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(26, 17), // (31,17): warning CS8602: Dereference of a possibly null reference. // _ = c3.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c3").WithLocation(31, 17), // (33,17): warning CS8602: Dereference of a possibly null reference. // _ = c4.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c4").WithLocation(33, 17)); } [Fact] public void NullableT_ClassToStruct() { var source = @"struct S { public static implicit operator S(C c) => new S(); } class C { } class Program { // C -> S static void F1(C c) { _ = (S)c; S s2 = c; } // C? -> S? static void F2(bool b, C? nc) { if (nc != null) { var s1 = (S?)nc; _ = s1.Value; S? s2 = nc; _ = s2.Value; } else { if (b) { var s3 = (S?)nc; // 1 _ = s3.Value; } if (b) { S? s4 = nc; // 2 _ = s4.Value; } } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (30,30): warning CS8604: Possible null reference argument for parameter 'c' in 'S.implicit operator S(C c)'. // var s3 = (S?)nc; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nc").WithArguments("c", "S.implicit operator S(C c)").WithLocation(30, 30), // (35,25): warning CS8604: Possible null reference argument for parameter 'c' in 'S.implicit operator S(C c)'. // S? s4 = nc; // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nc").WithArguments("c", "S.implicit operator S(C c)").WithLocation(35, 25)); } [Fact] public void NullableT_ClassToNullableStruct() { var source = @"struct S { public static implicit operator S?(C c) => new S(); } class C { } class Program { // C -> S? static void F1(C c) { var s1 = (S?)c; _ = s1.Value; // 1 S? s2 = c; _ = s2.Value; // 2 } // C? -> S? static void F2(bool b, C? nc) { if (nc != null) { var s1 = (S?)nc; _ = s1.Value; // 3 S? s2 = nc; _ = s2.Value; // 4 } else { if (b) { var s3 = (S?)nc; // 5 _ = s3.Value; // 6 } if (b) { S? s4 = nc; // 7 _ = s4.Value; // 8 } } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(14, 13), // (16,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(16, 13), // (24,17): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(24, 17), // (26,17): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(26, 17), // (32,30): warning CS8604: Possible null reference argument for parameter 'c' in 'S.implicit operator S?(C c)'. // var s3 = (S?)nc; // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nc").WithArguments("c", "S.implicit operator S?(C c)").WithLocation(32, 30), // (33,21): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(33, 21), // (37,25): warning CS8604: Possible null reference argument for parameter 'c' in 'S.implicit operator S?(C c)'. // S? s4 = nc; // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nc").WithArguments("c", "S.implicit operator S?(C c)").WithLocation(37, 25), // (38,21): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(38, 21) ); } [Fact] public void NullableT_NullableClassToStruct() { var source = @"struct S { public static implicit operator S(C? c) => new S(); } class C { } class Program { // C -> S static void F1(C c) { _ = (S)c; S s2 = c; } // C? -> S? static void F2(C? nc) { if (nc != null) { var s1 = (S?)nc; _ = s1.Value; S? s2 = nc; _ = s2.Value; } else { var s3 = (S?)nc; _ = s3.Value; S? s4 = nc; _ = s4.Value; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_NullableClassToNullableStruct() { var source = @"struct S { public static implicit operator S?(C? c) => new S(); } class C { } class Program { // C -> S? static void F1(C c) { var s1 = (S?)c; _ = s1.Value; // 1 S? s2 = c; _ = s2.Value; // 2 } // C? -> S? static void F2(C? nc) { if (nc != null) { var s1 = (S?)nc; _ = s1.Value; // 3 S? s2 = nc; _ = s2.Value; // 4 } else { var s3 = (S?)nc; _ = s3.Value; // 5 S? s4 = nc; _ = s4.Value; // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(14, 13), // (16,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(16, 13), // (24,17): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(24, 17), // (26,17): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(26, 17), // (31,17): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(31, 17), // (33,17): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(33, 17) ); } // https://github.com/dotnet/roslyn/issues/31675: Add similar tests for // type parameters with `class?` constraint and Nullable<T> constraint. [Fact] public void NullableT_StructToTypeParameterUnconstrained() { var source = @"struct S<T> { public static implicit operator T(S<T> s) => throw null!; } class C<T> { // S<T> -> T static void F1(S<T> s) { var t1 = (T)s; _ = t1.ToString(); // 1 T t2 = s; _ = t2.ToString(); // 2 } // S<T>? -> T static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T)ns; _ = t1.ToString(); // 3 } else { var t2 = (T)ns; _ = t2.ToString(); // 4 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(11, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = t2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(13, 13), // (21,17): warning CS8602: Dereference of a possibly null reference. // _ = t1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(21, 17), // (26,17): warning CS8602: Dereference of a possibly null reference. // _ = t2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(26, 17)); } [Fact] public void NullableT_NullableStructToTypeParameterUnconstrained() { var source = @"struct S<T> { public static implicit operator T(S<T>? s) => throw null!; } class C<T> { // S<T> -> T static void F1(S<T> s) { var t1 = (T)s; _ = t1.ToString(); // 1 T t2 = s; _ = t2.ToString(); // 2 } // S<T>? -> T static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T)ns; _ = t1.ToString(); // 3 } else { var t2 = (T)ns; _ = t2.ToString(); // 4 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8602: Dereference of a possibly null reference. // _ = t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(11, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // _ = t2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(13, 13), // (21,17): warning CS8602: Dereference of a possibly null reference. // _ = t1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(21, 17), // (26,17): warning CS8602: Dereference of a possibly null reference. // _ = t2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t2").WithLocation(26, 17)); } [Fact] [WorkItem(35334, "https://github.com/dotnet/roslyn/issues/35334")] public void NullableT_StructToTypeParameterClassConstraint() { var source = @"struct S<T> { public static implicit operator T(S<T> s) => throw null!; } class C<T> where T : class { // S<T> -> T static void F1(S<T> s) { var t1 = (T)s; _ = t1.ToString(); T t2 = s; _ = t2.ToString(); } // S<T>? -> T? static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T?)ns; _ = t1.ToString(); // 1 T? t2 = ns; _ = t2.ToString(); } else { var t3 = (T?)ns; _ = t3.ToString(); // 2 T? t4 = ns; _ = t4.ToString(); // 3 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (21,17): warning CS8602: Dereference of a possibly null reference. // _ = t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(21, 17), // (28,17): warning CS8602: Dereference of a possibly null reference. // _ = t3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3").WithLocation(28, 17), // (30,17): warning CS8602: Dereference of a possibly null reference. // _ = t4.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t4").WithLocation(30, 17)); } [Fact] [WorkItem(35334, "https://github.com/dotnet/roslyn/issues/35334")] public void NullableT_NullableStructToTypeParameterClassConstraint() { var source = @"struct S<T> { public static implicit operator T(S<T>? s) => throw null!; } class C<T> where T : class { // S<T> -> T static void F1(S<T> s) { var t1 = (T)s; _ = t1.ToString(); T t2 = s; _ = t2.ToString(); } // S<T>? -> T? static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T?)ns; _ = t1.ToString(); // 1 T? t2 = ns; _ = t2.ToString(); } else { var t3 = (T?)ns; _ = t3.ToString(); // 2 T? t4 = ns; _ = t4.ToString(); } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (21,17): warning CS8602: Dereference of a possibly null reference. // _ = t1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1").WithLocation(21, 17), // (28,17): warning CS8602: Dereference of a possibly null reference. // _ = t3.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3").WithLocation(28, 17)); } [Fact] public void NullableT_StructToTypeParameterStructConstraint() { var source = @"struct S<T> { public static implicit operator T(S<T> s) => throw null!; } class C<T> where T : struct { // S<T> -> T static void F1(S<T> s) { var t1 = (T)s; _ = t1.ToString(); T t2 = s; _ = t2.ToString(); } // S<T>? -> T? static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T?)ns; _ = t1.Value; T? t2 = ns; _ = t2.Value; } else { var t3 = (T?)ns; _ = t3.Value; // 1 T? t4 = ns; _ = t4.Value; // 2 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (28,17): warning CS8629: Nullable value type may be null. // _ = t3.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t3").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = t4.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4").WithLocation(30, 17) ); } [Fact] public void NullableT_NullableStructToTypeParameterStructConstraint() { var source = @"struct S<T> { public static implicit operator T(S<T>? s) => throw null!; } class C<T> where T : struct { // S<T> -> T static void F1(S<T> s) { var t1 = (T)s; _ = t1.ToString(); T t2 = s; _ = t2.ToString(); } // S<T>? -> T? static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T?)ns; _ = t1.Value; T? t2 = ns; _ = t2.Value; } else { var t3 = (T?)ns; _ = t3.Value; T? t4 = ns; _ = t4.Value; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_StructToNullableTypeParameterStructConstraint() { var source = @"struct S<T> where T : struct { public static implicit operator T?(S<T> s) => throw null!; } class C<T> where T : struct { // S<T> -> T? static void F1(S<T> s) { var t1 = (T?)s; _ = t1.Value; // 1 T? t2 = s; _ = t2.Value; // 2 } // S<T>? -> T? static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T?)ns; _ = t1.Value; // 3 T? t2 = ns; _ = t2.Value; // 4 } else { var t3 = (T?)ns; // 5 _ = t3.Value; // 6 T? t4 = ns; // 7 _ = t4.Value; // 8 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = t1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = t1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(23, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = t3.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t3").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = t4.Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4").WithLocation(30, 17) ); } [Fact] public void NullableT_NullableStructToNullableTypeParameterStructConstraint() { var source = @"struct S<T> where T : struct { public static implicit operator T?(S<T>? s) => throw null!; } class C<T> where T : struct { // S<T> -> T? static void F1(S<T> s) { var t1 = (T?)s; _ = t1.Value; // 1 T? t2 = s; _ = t2.Value; // 2 } // S<T>? -> T? static void F2(S<T>? ns) { if (ns.HasValue) { var t1 = (T?)ns; _ = t1.Value; // 3 T? t2 = ns; _ = t2.Value; // 4 } else { var t3 = (T?)ns; _ = t3.Value; // 5 T? t4 = ns; _ = t4.Value; // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = t1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = t1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(23, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = t3.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t3").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = t4.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4").WithLocation(30, 17) ); } [Fact] public void NullableT_TypeParameterUnconstrainedToStruct() { var source = @"struct S<T> { public static implicit operator S<T>(T t) => throw null!; } class C<T> { // T -> S<T> static void F1(T t) { _ = (S<T>)t; S<T> s2 = t; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_TypeParameterUnconstrainedToNullableStruct() { var source = @"struct S<T> { public static implicit operator S<T>?(T t) => throw null!; } class C<T> { // T -> S<T>? static void F1(T t) { var s1 = (S<T>?)t; _ = s1.Value; // 1 S<T>? s2 = t; _ = s2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(13, 13) ); } [Fact] public void NullableT_TypeParameterClassConstraintToStruct() { var source = @"struct S<T> { public static implicit operator S<T>(T t) => throw null!; } class C<T> where T : class { // T -> S<T> static void F1(T t) { _ = (S<T>)t; S<T> s2 = t; } // T? -> S<T>? static void F2(bool b, T? nt) { if (nt != null) { var s1 = (S<T>?)nt; _ = s1.Value; S<T>? s2 = nt; _ = s2.Value; } else { if (b) { var s3 = (S<T>?)nt; // 1 _ = s3.Value; } if (b) { S<T>? s4 = nt; // 2 _ = s4.Value; } } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (27,33): warning CS8604: Possible null reference argument for parameter 't' in 'S<T>.implicit operator S<T>(T t)'. // var s3 = (S<T>?)nt; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nt").WithArguments("t", "S<T>.implicit operator S<T>(T t)").WithLocation(27, 33), // (32,28): warning CS8604: Possible null reference argument for parameter 't' in 'S<T>.implicit operator S<T>(T t)'. // S<T>? s4 = nt; // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nt").WithArguments("t", "S<T>.implicit operator S<T>(T t)").WithLocation(32, 28)); } [Fact] public void NullableT_TypeParameterClassConstraintToNullableStruct() { var source = @"struct S<T> { public static implicit operator S<T>?(T t) => throw null!; } class C<T> where T : class { // T -> S<T>? static void F1(T t) { var s1 = (S<T>?)t; _ = s1.Value; // 1 S<T>? s2 = t; _ = s2.Value; // 2 } // T? -> S<T>? static void F2(bool b, T? nt) { if (nt != null) { var s1 = (S<T>?)nt; _ = s1.Value; // 3 S<T>? s2 = nt; _ = s2.Value; // 4 } else { if (b) { var s3 = (S<T>?)nt; // 5 _ = s3.Value; // 6 } if (b) { S<T>? s4 = nt; // 7 _ = s4.Value; // 8 } } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(23, 17), // (29,33): warning CS8604: Possible null reference argument for parameter 't' in 'S<T>.implicit operator S<T>?(T t)'. // var s3 = (S<T>?)nt; // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nt").WithArguments("t", "S<T>.implicit operator S<T>?(T t)").WithLocation(29, 33), // (30,21): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(30, 21), // (34,28): warning CS8604: Possible null reference argument for parameter 't' in 'S<T>.implicit operator S<T>?(T t)'. // S<T>? s4 = nt; // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "nt").WithArguments("t", "S<T>.implicit operator S<T>?(T t)").WithLocation(34, 28), // (35,21): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(35, 21) ); } [Fact] public void NullableT_TypeParameterStructConstraintToStruct() { var source = @"struct S<T> { public static implicit operator S<T>(T t) => throw null!; } class C<T> where T : struct { // T -> S<T> static void F1(T t) { _ = (S<T>)t; S<T> s2 = t; } // T? -> S<T>? static void F2(T? nt) { if (nt != null) { var s1 = (S<T>?)nt; _ = s1.Value; S<T>? s2 = nt; _ = s2.Value; } else { var s3 = (S<T>?)nt; _ = s3.Value; // 1 S<T>? s4 = nt; _ = s4.Value; // 2 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (26,17): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(26, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(28, 17) ); } [Fact] public void NullableT_TypeParameterStructConstraintToNullableStruct() { var source = @"struct S<T> { public static implicit operator S<T>?(T t) => throw null!; } class C<T> where T : struct { // T -> S<T>? static void F1(T t) { var s1 = (S<T>?)t; _ = s1.Value; // 1 S<T>? s2 = t; _ = s2.Value; // 2 } // T? -> S<T>? static void F2(T? nt) { if (nt != null) { var s1 = (S<T>?)nt; _ = s1.Value; // 3 S<T>? s2 = nt; _ = s2.Value; // 4 } else { var s3 = (S<T>?)nt; // 5 _ = s3.Value; // 6 S<T>? s4 = nt; // 7 _ = s4.Value; // 8 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(23, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(30, 17) ); } [Fact] public void NullableT_NullableTypeParameterStructConstraintToStruct() { var source = @"struct S<T> where T : struct { public static implicit operator S<T>(T? t) => throw null!; } class C<T> where T : struct { // T -> S<T> static void F1(T t) { _ = (S<T>)t; S<T> s2 = t; } // T? -> S<T>? static void F2(T? nt) { if (nt != null) { var s1 = (S<T>?)nt; _ = s1.Value; S<T>? s2 = nt; _ = s2.Value; } else { var s3 = (S<T>?)nt; _ = s3.Value; S<T>? s4 = nt; _ = s4.Value; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_NullableTypeParameterStructConstraintToNullableStruct() { var source = @"struct S<T> where T : struct { public static implicit operator S<T>?(T? t) => throw null!; } class C<T> where T : struct { // T -> S<T>? static void F1(T t) { var s1 = (S<T>?)t; _ = s1.Value; // 1 S<T>? s2 = t; _ = s2.Value; // 2 } // T? -> S<T>? static void F2(T? nt) { if (nt != null) { var s1 = (S<T>?)nt; _ = s1.Value; // 3 S<T>? s2 = nt; _ = s2.Value; // 4 } else { var s3 = (S<T>?)nt; _ = s3.Value; // 5 S<T>? s4 = nt; _ = s4.Value; // 6 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(11, 13), // (13,13): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(13, 13), // (21,17): warning CS8629: Nullable value type may be null. // _ = s1.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1").WithLocation(21, 17), // (23,17): warning CS8629: Nullable value type may be null. // _ = s2.Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2").WithLocation(23, 17), // (28,17): warning CS8629: Nullable value type may be null. // _ = s3.Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s3").WithLocation(28, 17), // (30,17): warning CS8629: Nullable value type may be null. // _ = s4.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s4").WithLocation(30, 17) ); } [Fact] public void NullableT_ValueTypeConstraint_01() { var source = @"abstract class A<T> { internal abstract void F<U>(U x) where U : T; } class B1 : A<int> { internal override void F<U>(U x) { int? y = x; _ = y.Value; _ = ((int?)x).Value; } } class B2 : A<int?> { internal override void F<U>(U x) { int? y = x; _ = y.Value; // 1 _ = ((int?)x).Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // Conversions are not allowed from U to int in B1.F or from U to int? in B2.F, // so those conversions are not handled in NullableWalker either. comp.VerifyDiagnostics( // (9,18): error CS0029: Cannot implicitly convert type 'U' to 'int?' // int? y = x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("U", "int?").WithLocation(9, 18), // (11,14): error CS0030: Cannot convert type 'U' to 'int?' // _ = ((int?)x).Value; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)x").WithArguments("U", "int?").WithLocation(11, 14), // (18,18): error CS0029: Cannot implicitly convert type 'U' to 'int?' // int? y = x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "x").WithArguments("U", "int?").WithLocation(18, 18), // (19,13): warning CS8629: Nullable value type may be null. // _ = y.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(19, 13), // (20,14): error CS0030: Cannot convert type 'U' to 'int?' // _ = ((int?)x).Value; // 2 Diagnostic(ErrorCode.ERR_NoExplicitConv, "(int?)x").WithArguments("U", "int?").WithLocation(20, 14)); } [Fact] public void NullableT_ValueTypeConstraint_02() { var source = @"abstract class A<T> { internal abstract void F<U>(T t) where U : T; } class B1 : A<int?> { internal override void F<U>(int? t) { U u = t; object? o = u; o.ToString(); // 1 } } class B2 : A<int?> { internal override void F<U>(int? t) { if (t == null) return; U u = t; object? o = u; o.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,15): error CS0029: Cannot implicitly convert type 'int?' to 'U' // U u = t; Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("int?", "U").WithLocation(9, 15), // (11,9): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(11, 9), // (19,15): error CS0029: Cannot implicitly convert type 'int?' to 'U' // U u = t; Diagnostic(ErrorCode.ERR_NoImplicitConv, "t").WithArguments("int?", "U").WithLocation(19, 15)); } [Fact] public void NullableT_ValueTypeConstraint_03() { var source = @"abstract class A<T> { internal abstract void F<U>(T t) where U : T; } class B1 : A<int?> { internal override void F<U>(int? t) { U u = (U)(object?)t; object? o = u; o.ToString(); // 1 } } class B2 : A<int?> { internal override void F<U>(int? t) { if (t == null) return; U u = (U)(object?)t; object? o = u; o.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(11, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // o.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(21, 9)); } [Fact] public void NullableT_Box() { var source = @"class Program { static void F1<T>(T? x1, T? y1) where T : struct { if (x1 == null) return; ((object?)x1).ToString(); // 1 ((object?)y1).ToString(); // 2 } static void F2<T>(T? x2, T? y2) where T : struct { if (x2 == null) return; object? z2 = x2; z2.ToString(); object? w2 = y2; w2.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,10): warning CS8602: Dereference of a possibly null reference. // ((object?)x1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object?)x1").WithLocation(6, 10), // (7,10): warning CS8602: Dereference of a possibly null reference. // ((object?)y1).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object?)y1").WithLocation(7, 10), // (15,9): warning CS8602: Dereference of a possibly null reference. // w2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w2").WithLocation(15, 9) ); } [Fact] public void NullableT_Box_ValueTypeConstraint() { var source = @"abstract class A<T> { internal abstract void F<U>(U x) where U : T; } class B1 : A<int> { internal override void F<U>(U x) { ((object?)x).ToString(); // 1 object y = x; y.ToString(); } } class B2 : A<int?> { internal override void F<U>(U x) { ((object?)x).ToString(); // 2 object? y = x; y.ToString(); } void F(int? x) { ((object?)x).ToString(); // 3 object? y = x; y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,10): warning CS8602: Dereference of a possibly null reference. // ((object?)x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object?)x").WithLocation(9, 10), // (18,10): warning CS8602: Dereference of a possibly null reference. // ((object?)x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object?)x").WithLocation(18, 10), // (25,10): warning CS8602: Dereference of a possibly null reference. // ((object?)x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object?)x").WithLocation(25, 10) ); } [Fact] public void NullableT_Unbox() { var source = @"class Program { static void F1<T>(object x1, object? y1) where T : struct { _ = ((T?)x1).Value; _ = ((T?)y1).Value; // 1 } static void F2<T>(object x2, object? y2) where T : struct { var z2 = (T?)x2; _ = z2.Value; var w2 = (T?)y2; _ = w2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,14): warning CS8629: Nullable value type may be null. // _ = ((T?)y1).Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T?)y1").WithLocation(6, 14), // (13,13): warning CS8629: Nullable value type may be null. // _ = w2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "w2").WithLocation(13, 13) ); } [Fact] public void NullableT_Unbox_ValueTypeConstraint() { var source = @"abstract class A<T> { internal abstract void F<U>(object? x) where U : T; } class B1 : A<int> { internal override void F<U>(object? x) { int y = (U)x; } } class B2 : A<int?> { internal override void F<U>(object? x) { _ = ((U)x).Value; _ = ((int?)(object)(U)x).Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // Conversions are not allowed from U to int in B1.F or from U to int? in B2.F, // so those conversions are not handled in NullableWalker either. comp.VerifyDiagnostics( // (9,17): error CS0029: Cannot implicitly convert type 'U' to 'int' // int y = (U)x; Diagnostic(ErrorCode.ERR_NoImplicitConv, "(U)x").WithArguments("U", "int").WithLocation(9, 17), // (9,17): warning CS8605: Unboxing a possibly null value. // int y = (U)x; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)x").WithLocation(9, 17), // (16,20): error CS1061: 'U' does not contain a definition for 'Value' and no accessible extension method 'Value' accepting a first argument of type 'U' could be found (are you missing a using directive or an assembly reference?) // _ = ((U)x).Value; Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Value").WithArguments("U", "Value").WithLocation(16, 20), // (17,14): warning CS8629: Nullable value type may be null. // _ = ((int?)(object)(U)x).Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int?)(object)(U)x").WithLocation(17, 14), // (17,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // _ = ((int?)(object)(U)x).Value; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)(U)x").WithLocation(17, 20)); } [Fact] public void NullableT_Dynamic() { var source = @"class Program { static void F1<T>(dynamic x1, dynamic? y1) where T : struct { T? z1 = x1; _ = z1.Value; T? w1 = y1; _ = w1.Value; // 1 } static void F2<T>(dynamic x2, dynamic? y2) where T : struct { var z2 = (T?)x2; _ = z2.Value; var w2 = (T?)y2; _ = w2.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8629: Nullable value type may be null. // _ = w1.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "w1").WithLocation(8, 13), // (15,13): warning CS8629: Nullable value type may be null. // _ = w2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "w2").WithLocation(15, 13) ); } [Fact] public void NullableT_23() { var source = @"#pragma warning disable 649 struct S { internal int F; } class Program { static void F(S? x, S? y) { if (y == null) return; int? ni; ni = x?.F; _ = ni.Value; // 1 ni = y?.F; _ = ni.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8629: Nullable value type may be null. // _ = ni.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ni").WithLocation(13, 13), // (15,13): warning CS8629: Nullable value type may be null. // _ = ni.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "ni").WithLocation(15, 13) ); } [Fact] public void NullableT_24() { var source = @"class Program { static void F(bool b, int? x, int? y) { if ((b ? x : y).HasValue) { _ = x.Value; // 1 _ = y.Value; // 2 } if ((b ? x : x).HasValue) { _ = x.Value; // 3 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,17): warning CS8629: Nullable value type may be null. // _ = x.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(7, 17), // (8,17): warning CS8629: Nullable value type may be null. // _ = y.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(8, 17), // (12,17): warning CS8629: Nullable value type may be null. // _ = x.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(12, 17) ); } [Fact] public void NullableT_25() { var source = @"class Program { static void F1(int? x) { var y = ~x; _ = y.Value; // 1 } static void F2(int x, int? y) { var z = x + y; _ = z.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8629: Nullable value type may be null. // _ = y.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(6, 13), // (11,13): warning CS8629: Nullable value type may be null. // _ = z.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "z").WithLocation(11, 13) ); } [WorkItem(31500, "https://github.com/dotnet/roslyn/issues/31500")] [Fact] public void NullableT_26() { var source = @"class Program { static void F1(int? x) { if (x == null) return; var y = ~x; _ = y.Value; } static void F2(int x, int? y) { if (y == null) return; var z = x + y; _ = z.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [WorkItem(31500, "https://github.com/dotnet/roslyn/issues/31500")] [Fact] public void NullableT_27() { var source = @"struct A { public static implicit operator B(A a) => new B(); } struct B { } class Program { static void F1(A? a) { B? b = a; _ = b.Value; // 1 } static void F2(A? a) { if (a != null) { B? b1 = a; _ = b1.Value; } else { B? b2 = a; _ = b2.Value; // 2 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8629: Nullable value type may be null. // _ = b.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "b").WithLocation(13, 13), // (25,17): warning CS8629: Nullable value type may be null. // _ = b2.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "b2").WithLocation(25, 17) ); } [Fact] public void NullableT_28() { var source = @"class Program { static void F<T>(T? x, T? y) where T : struct { object z = x ?? y; object? w = x ?? y; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object z = x ?? y; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x ?? y").WithLocation(5, 20)); } [Fact] public void NullableT_29() { var source = @"class Program { static void F<T>(T? t) where T : struct { if (!t.HasValue) return; _ = t ?? default(T); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( ); } [Fact] public void NullableT_30() { var source = @"class Program { static void F<T>(T? t) where T : struct { t.HasValue = true; t.Value = default(T); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS0200: Property or indexer 'T?.HasValue' cannot be assigned to -- it is read only // t.HasValue = true; Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "t.HasValue").WithArguments("T?.HasValue").WithLocation(5, 9), // (6,9): error CS0200: Property or indexer 'T?.Value' cannot be assigned to -- it is read only // t.Value = default(T); Diagnostic(ErrorCode.ERR_AssgReadonlyProp, "t.Value").WithArguments("T?.Value").WithLocation(6, 9), // (6,9): warning CS8629: Nullable value type may be null. // t.Value = default(T); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(6, 9) ); } [Fact] public void NullableT_31() { var source = @"struct S { } class Program { static void F() { var s = (S?)F; _ = s.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,18): error CS0030: Cannot convert type 'method' to 'S?' // var s = (S?)F; Diagnostic(ErrorCode.ERR_NoExplicitConv, "(S?)F").WithArguments("method", "S?").WithLocation(6, 18)); } [WorkItem(33330, "https://github.com/dotnet/roslyn/issues/33330")] [Fact] public void NullableT_32() { var source = @"#nullable enable class Program { static void F(int? i, int j) { _ = (int)(i & j); // 1 _ = (int)(i | j); // 2 _ = (int)(i ^ j); // 3 _ = (int)(~i); // 4 if (i.HasValue) { _ = (int)(i & j); _ = (int)(i | j); _ = (int)(i ^ j); _ = (int)(~i); } } static void F(bool? i, bool b) { _ = (bool)(i & b); // 5 _ = (bool)(i | b); // 6 _ = (bool)(i ^ b); // 7 _ = (bool)(!i); // 8 if (i.HasValue) { _ = (bool)(i & b); _ = (bool)(i | b); _ = (bool)(i ^ b); _ = (bool)(!i); } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8629: Nullable value type may be null. // _ = (int)(i & j); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int)(i & j)").WithLocation(6, 13), // (7,13): warning CS8629: Nullable value type may be null. // _ = (int)(i | j); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int)(i | j)").WithLocation(7, 13), // (8,13): warning CS8629: Nullable value type may be null. // _ = (int)(i ^ j); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int)(i ^ j)").WithLocation(8, 13), // (9,13): warning CS8629: Nullable value type may be null. // _ = (int)(~i); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(int)(~i)").WithLocation(9, 13), // (20,13): warning CS8629: Nullable value type may be null. // _ = (bool)(i & b); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(bool)(i & b)").WithLocation(20, 13), // (21,13): warning CS8629: Nullable value type may be null. // _ = (bool)(i | b); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(bool)(i | b)").WithLocation(21, 13), // (22,13): warning CS8629: Nullable value type may be null. // _ = (bool)(i ^ b); // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(bool)(i ^ b)").WithLocation(22, 13), // (23,13): warning CS8629: Nullable value type may be null. // _ = (bool)(!i); // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(bool)(!i)").WithLocation(23, 13)); } [WorkItem(32626, "https://github.com/dotnet/roslyn/issues/32626")] [Fact] public void NullableCtor() { var source = @" using System; struct S { internal object? F; } class Program { static void Baseline() { S? x = new S(); x.Value.F.ToString(); // warning baseline S? y = new S() { F = 2 }; y.Value.F.ToString(); // ok baseline } static void F() { S? x = new Nullable<S>(new S()); x.Value.F.ToString(); // warning S? y = new Nullable<S>(new S() { F = 2 }); y.Value.F.ToString(); // ok } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // x.Value.F.ToString(); // warning baseline Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.F").WithLocation(14, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // x.Value.F.ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.F").WithLocation(23, 9) ); } [WorkItem(32626, "https://github.com/dotnet/roslyn/issues/32626")] [Fact] public void NullableCtorErr() { var source = @" using System; struct S { internal object? F; } class Program { static void F() { S? x = new S() { F = 2 }; x.Value.F.ToString(); // ok baseline S? y = new Nullable<S>(1); y.Value.F.ToString(); // warning 1 S? z = new Nullable<S>(null); z.Value.F.ToString(); // warning 2 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,32): error CS1503: Argument 1: cannot convert from 'int' to 'S' // S? y = new Nullable<S>(1); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "S").WithLocation(16, 32), // (17,9): warning CS8602: Dereference of a possibly null reference. // y.Value.F.ToString(); // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.F").WithLocation(17, 9), // (19,32): error CS1503: Argument 1: cannot convert from '<null>' to 'S' // S? z = new Nullable<S>(null); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "S").WithLocation(19, 32), // (20,9): warning CS8602: Dereference of a possibly null reference. // z.Value.F.ToString(); // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.Value.F").WithLocation(20, 9) ); } [WorkItem(32626, "https://github.com/dotnet/roslyn/issues/32626")] [Fact] public void NullableCtor1() { var source = @" using System; struct S { internal object? F; } class Program { static void F() { S? x = new Nullable<S>(new S() { F = 2 }); x.Value.F.ToString(); // ok S? y = new Nullable<S>(); y.Value.F.ToString(); // warning 1 S? z = new Nullable<S>(default); z.Value.F.ToString(); // warning 2 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,9): warning CS8629: Nullable value type may be null. // y.Value.F.ToString(); // warning 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(17, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // y.Value.F.ToString(); // warning 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.F").WithLocation(17, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // z.Value.F.ToString(); // warning 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z.Value.F").WithLocation(20, 9)); } [Fact, WorkItem(38575, "https://github.com/dotnet/roslyn/issues/38575")] public void NullableCtor_Dynamic() { var source = @" using System; class C { void M() { var value = GetValue((dynamic)""""); _ = new DateTime?(value); } DateTime GetValue(object o) => default; } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_AlwaysTrueOrFalse() { var source = @"class Program { static void F1<T>(T? t1) where T : struct { if (!t1.HasValue) return; if (t1.HasValue) { } // always false if (!t1.HasValue) { } // always true if (t1 != null) { } // always false if (t1 == null) { } // always true } static void F2<T>(T? t2) where T : struct { if (!t2.HasValue) return; if (t2 == null) { } // always false if (t2 != null) { } // always true if (!t2.HasValue) { } // always false if (t2.HasValue) { } // always true } static void F3<T>(T? t3) where T : struct { if (t3 == null) return; if (!t3.HasValue) { } // always true if (t3.HasValue) { } // always false if (t3 == null) { } // always true if (t3 != null) { } // always false } static void F4<T>(T? t4) where T : struct { if (t4 == null) return; if (t4 != null) { } // always true if (t4 == null) { } // always false if (t4.HasValue) { } // always true if (!t4.HasValue) { } // always false } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_As_01() { var source = @"class Program { static void F1<T>(object x1, object? y1) where T : struct { _ = (x1 as T?).Value; // 1 _ = (y1 as T?).Value; // 2 } static void F2<T>(T x2, T? y2) where T : struct { _ = (x2 as T?).Value; _ = (y2 as T?).Value; // 3 } static void F3<T, U>(U x3) where T : struct { _ = (x3 as T?).Value; // 4 } static void F4<T, U>(U x4, U? y4) where T : struct where U : class { _ = (x4 as T?).Value; // 5 _ = (y4 as T?).Value; // 6 } static void F5<T, U>(U x5, U? y5) where T : struct where U : struct { _ = (x5 as T?).Value; // 7 _ = (y5 as T?).Value; // 8 } static void F6<T, U>(U x6) where T : struct, U { _ = (x6 as T?).Value; // 9 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,14): warning CS8629: Nullable value type may be null. // _ = (x1 as T?).Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x1 as T?").WithLocation(5, 14), // (6,14): warning CS8629: Nullable value type may be null. // _ = (y1 as T?).Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y1 as T?").WithLocation(6, 14), // (11,14): warning CS8629: Nullable value type may be null. // _ = (y2 as T?).Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y2 as T?").WithLocation(11, 14), // (15,14): warning CS8629: Nullable value type may be null. // _ = (x3 as T?).Value; // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x3 as T?").WithLocation(15, 14), // (19,14): warning CS8629: Nullable value type may be null. // _ = (x4 as T?).Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x4 as T?").WithLocation(19, 14), // (20,14): warning CS8629: Nullable value type may be null. // _ = (y4 as T?).Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y4 as T?").WithLocation(20, 14), // (24,14): warning CS8629: Nullable value type may be null. // _ = (x5 as T?).Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x5 as T?").WithLocation(24, 14), // (25,14): warning CS8629: Nullable value type may be null. // _ = (y5 as T?).Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y5 as T?").WithLocation(25, 14), // (29,14): warning CS8629: Nullable value type may be null. // _ = (x6 as T?).Value; // 9 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x6 as T?").WithLocation(29, 14) ); } [Fact] public void NullableT_As_02() { var source = @"class Program { static void F1<T>(T? t1) where T : struct { _ = (t1 as object).ToString(); // 1 if (t1.HasValue) _ = (t1 as object).ToString(); else _ = (t1 as object).ToString(); } static void F2<T>(T? t2) where T : struct { _ = (t2 as T?).Value; // 2 if (t2.HasValue) _ = (t2 as T?).Value; else _ = (t2 as T?).Value; } static void F3<T, U>(T? t3) where T : struct where U : class { _ = (t3 as U).ToString(); // 3 if (t3.HasValue) _ = (t3 as U).ToString(); // 4 else _ = (t3 as U).ToString(); // 5 } static void F4<T, U>(T? t4) where T : struct where U : struct { _ = (t4 as U?).Value; // 6 if (t4.HasValue) _ = (t4 as U?).Value; // 7 else _ = (t4 as U?).Value; // 8 } static void F5<T>(T? t5) where T : struct { _ = (t5 as dynamic).ToString(); // 9 if (t5.HasValue) _ = (t5 as dynamic).ToString(); else _ = (t5 as dynamic).ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,14): warning CS8602: Dereference of a possibly null reference. // _ = (t1 as object).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t1 as object").WithLocation(5, 14), // (13,14): warning CS8629: Nullable value type may be null. // _ = (t2 as T?).Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2 as T?").WithLocation(13, 14), // (21,14): warning CS8602: Dereference of a possibly null reference. // _ = (t3 as U).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3 as U").WithLocation(21, 14), // (23,18): warning CS8602: Dereference of a possibly null reference. // _ = (t3 as U).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3 as U").WithLocation(23, 18), // (25,18): warning CS8602: Dereference of a possibly null reference. // _ = (t3 as U).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t3 as U").WithLocation(25, 18), // (29,14): warning CS8629: Nullable value type may be null. // _ = (t4 as U?).Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4 as U?").WithLocation(29, 14), // (31,18): warning CS8629: Nullable value type may be null. // _ = (t4 as U?).Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4 as U?").WithLocation(31, 18), // (33,18): warning CS8629: Nullable value type may be null. // _ = (t4 as U?).Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t4 as U?").WithLocation(33, 18), // (37,14): warning CS8602: Dereference of a possibly null reference. // _ = (t5 as dynamic).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t5 as dynamic").WithLocation(37, 14) ); } [Fact] public void NullableT_As_ValueTypeConstraint_01() { var source = @"abstract class A<T> { internal abstract void F<U>(U u) where U : T; } class B1 : A<int> { internal override void F<U>(U u) { _ = (u as U?).Value; _ = (u as int?).Value; // 1 } } class B2 : A<int?> { internal override void F<U>(U u) { _ = (u as int?).Value; // 2 } }"; // Implicit conversions are not allowed from U to int in B1.F or from U to int? in B2.F, // so those conversions are not handled in NullableWalker either. var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,14): warning CS8629: Nullable value type may be null. // _ = (u as int?).Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "u as int?").WithLocation(10, 14), // (17,14): warning CS8629: Nullable value type may be null. // _ = (u as int?).Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "u as int?").WithLocation(17, 14) ); } [Fact] public void NullableT_As_ValueTypeConstraint_02() { var source = @"abstract class A<T> { internal abstract void F<U>(T t) where U : T; } class B1 : A<int> { internal override void F<U>(int t) { _ = (t as U?).Value; // 1 } } class B2 : A<int?> { internal override void F<U>(int? t) { _ = (t as U).Value; // 2 _ = (t as U?).Value; // 3 } }"; // Implicit conversions are not allowed from int to U in B1.F or from int? to U in B2.F, // so those conversions are not handled in NullableWalker either. var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,14): warning CS8629: Nullable value type may be null. // _ = (t as U?).Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t as U?").WithLocation(9, 14), // (16,14): error CS0413: The type parameter 'U' cannot be used with the 'as' operator because it does not have a class type constraint nor a 'class' constraint // _ = (t as U).Value; // 2 Diagnostic(ErrorCode.ERR_AsWithTypeVar, "t as U").WithArguments("U").WithLocation(16, 14), // (17,14): warning CS8629: Nullable value type may be null. // _ = (t as U?).Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t as U?").WithLocation(17, 14), // (17,19): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // _ = (t as U?).Value; // 3 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "U?").WithArguments("System.Nullable<T>", "T", "U").WithLocation(17, 19) ); } [Fact] [WorkItem(38213, "https://github.com/dotnet/roslyn/issues/38213")] public void NullableT_IsOperator_01() { var source = @"class C { void M() { int? i = null; _ = i is object ? i.Value : i.Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,15): warning CS8629: Nullable value type may be null. // : i.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(8, 15)); } [Fact] [WorkItem(38213, "https://github.com/dotnet/roslyn/issues/38213")] public void NullableT_IsOperator_02() { var source = @"public class C { public int? i = null; static void M(C? c) { _ = c?.i is object ? c.i.Value : c.i.Value; // 1, 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,15): warning CS8602: Dereference of a possibly null reference. // : c.i.Value; // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(9, 15), // (9,15): warning CS8629: Nullable value type may be null. // : c.i.Value; // 1, 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.i").WithLocation(9, 15)); } [Fact] [WorkItem(38213, "https://github.com/dotnet/roslyn/issues/38213")] public void NullableT_IsOperator_03() { var source = @"class C { void M1() { int? i = null; _ = i is int ? i.Value : i.Value; // 1 } void M2() { int? i = null; _ = i is int? ? i.Value : i.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,15): warning CS8629: Nullable value type may be null. // : i.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(9, 15), // (18,15): warning CS8629: Nullable value type may be null. // : i.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(18, 15)); } [Fact] [WorkItem(38213, "https://github.com/dotnet/roslyn/issues/38213")] public void NullableT_IsOperator_NotAPureNullTest() { var source = @"class C { static void M1() { int? i = 42; _ = i is object ? i.Value : i.Value; // 1 } static void M2() { int? i = 42; _ = i is int ? i.Value : i.Value; } static void M3() { int? i = 42; _ = i is int? ? i.Value : i.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,15): warning CS8629: Nullable value type may be null. // : i.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(8, 15)); } [WorkItem(31501, "https://github.com/dotnet/roslyn/issues/31501")] [Fact] public void NullableT_Suppress_01() { var source = @"class Program { static void F<T>(T x, T? y, T? z) where T : struct { _ = (T)((T?)null)!; _ = (T)((T?)default)!; _ = (T)default(T?)!; _ = (T)((T?)x)!; _ = (T)y!; _ = ((T)z)!; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,14): warning CS8629: Nullable value type may be null. // _ = ((T)z)!; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "(T)z").WithLocation(10, 14)); } [WorkItem(31501, "https://github.com/dotnet/roslyn/issues/31501")] [Fact] public void NullableT_Suppress_02() { var source = @"class Program { static void F<T>(T x, T? y, T? z) where T : struct { _ = ((T?)null)!.Value; _ = ((T?)default)!.Value; _ = default(T?)!.Value; _ = ((T?)x)!.Value; _ = y!.Value; _ = z.Value!; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8629: Nullable value type may be null. // _ = z.Value!; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "z").WithLocation(10, 13) ); } [Fact] public void NullableT_NotNullWhenTrue() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static bool F<T>([NotNullWhen(true)]T? t) where T : struct { return true; } static void G<T>(T? t) where T : struct { if (F(t)) _ = t.Value; else _ = t.Value; // 1 } }"; var comp = CreateCompilation(new[] { source, NotNullWhenAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,17): warning CS8629: Nullable value type may be null. // _ = t.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(13, 17) ); } [Fact] public void NullableT_NotNullWhenTrue_DifferentRefKinds() { var source = @"using System.Diagnostics.CodeAnalysis; class C { bool F2([NotNullWhen(true)] string? s) { s = null; return true; } bool F2([NotNullWhen(true)] ref string? s) { s = null; return true; // 1 } bool F3([NotNullWhen(true)] in string? s) { s = null; // 2 return true; } bool F4([NotNullWhen(true)] out string? s) { s = null; return true; // 3 } }"; var comp = CreateNullableCompilation(new[] { source, NotNullWhenAttributeDefinition }); comp.VerifyDiagnostics( // (13,9): error CS8762: Parameter 's' must have a non-null value when exiting with 'true'. // return true; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return true;").WithArguments("s", "true").WithLocation(13, 9), // (18,9): error CS8331: Cannot assign to variable 'in string?' because it is a readonly variable // s = null; // 2 Diagnostic(ErrorCode.ERR_AssignReadonlyNotField, "s").WithArguments("variable", "in string?").WithLocation(18, 9), // (25,9): error CS8762: Parameter 's' must have a non-null value when exiting with 'true'. // return true; // 3 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return true;").WithArguments("s", "true").WithLocation(25, 9) ); } [Fact] public void NullableT_DoesNotReturnIfFalse() { var source = @"using System.Diagnostics.CodeAnalysis; class Program { static void F([DoesNotReturnIf(false)] bool b) { } static void G<T>(T? x, T? y) where T : struct { F(x != null); _ = x.Value; F(y.HasValue); _ = y.Value; } }"; var comp = CreateCompilation(new[] { source, DoesNotReturnIfAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void NullableT_AllMembers() { var source = @"class C<T> where T : struct { static void F1(T? t1) { _ = t1.HasValue; } static void F2(T? t2) { _ = t2.Value; // 1 } static void F3(T? t3) { _ = t3.GetValueOrDefault(); } static void F4(T? t4) { _ = t4.GetHashCode(); } static void F5(T? t5) { _ = t5.ToString(); } static void F6(T? t6) { _ = t6.Equals(t6); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): warning CS8629: Nullable value type may be null. // _ = t2.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t2").WithLocation(9, 13) ); } [WorkItem(33174, "https://github.com/dotnet/roslyn/issues/33174")] [Fact] public void NullableBaseMembers() { var source = @" static class Program { static void Main() { int? x = null; x.GetHashCode(); // ok x.Extension(); // ok x.GetType(); // warning1 int? y = null; y.MemberwiseClone(); // warning2 y.Lalala(); // does not exist } static void Extension(this int? self) { } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8629: Nullable value type may be null. // x.GetType(); // warning1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "x").WithLocation(12, 9), // (15,9): warning CS8629: Nullable value type may be null. // y.MemberwiseClone(); // warning2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(15, 9), // (15,11): error CS1540: Cannot access protected member 'object.MemberwiseClone()' via a qualifier of type 'int?'; the qualifier must be of type 'Program' (or derived from it) // y.MemberwiseClone(); // warning2 Diagnostic(ErrorCode.ERR_BadProtectedAccess, "MemberwiseClone").WithArguments("object.MemberwiseClone()", "int?", "Program").WithLocation(15, 11), // (17,11): error CS1061: 'int?' does not contain a definition for 'Lalala' and no accessible extension method 'Lalala' accepting a first argument of type 'int?' could be found (are you missing a using directive or an assembly reference?) // y.Lalala(); // does not exist Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Lalala").WithArguments("int?", "Lalala").WithLocation(17, 11) ); } [Fact] public void NullableT_Using() { var source = @"using System; struct S : IDisposable { void IDisposable.Dispose() { } } class Program { static void F1(S? s) { using (s) { } _ = s.Value; // 1 } static void F2<T>(T? t) where T : struct, IDisposable { using (t) { } _ = t.Value; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,13): warning CS8629: Nullable value type may be null. // _ = s.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s").WithLocation(11, 13), // (16,13): warning CS8629: Nullable value type may be null. // _ = t.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(16, 13) ); } [WorkItem(31503, "https://github.com/dotnet/roslyn/issues/31503")] [Fact] public void NullableT_ForEach() { var source = @"using System.Collections; using System.Collections.Generic; struct S : IEnumerable { public IEnumerator GetEnumerator() => throw null!; } class Program { static void F1(S? s) { foreach (var i in s) // 1 ; foreach (var i in s) ; } static void F2<T, U>(T? t) where T : struct, IEnumerable<U> { foreach (var i in t) // 2 ; foreach (var i in t) ; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,27): warning CS8629: Nullable value type may be null. // foreach (var i in s) // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s").WithLocation(11, 27), // (18,27): warning CS8629: Nullable value type may be null. // foreach (var i in t) // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t").WithLocation(18, 27) ); } [Fact] public void NullableT_IndexAndRange() { var source = @"class Program { static void F1(int? x) { _ = ^x; } static void F2(int? y) { _ = ..y; _ = ^y..; } static void F3(int? z, int? w) { _ = z..^w; } }"; var comp = CreateCompilationWithIndexAndRange(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void PatternIndexer() { var src = @" #nullable enable class C { static void M1(string? s) { _ = s[^1]; } static void M2(string? s) { _ = s[1..10]; } }"; var comp = CreateCompilationWithIndexAndRange(src, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // _ = s[^1]; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(7, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // _ = s[1..10]; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 9)); } [WorkItem(31770, "https://github.com/dotnet/roslyn/issues/31770")] [Fact] public void UserDefinedConversion_NestedNullability_01() { var source = @"class A<T> { } class B { public static implicit operator B(A<object> a) => throw null!; } class Program { static void F(B b) { } static void Main() { A<object?> a = new A<object?>(); B b = a; // 1 F(a); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/31798: Consider improving warning to reference user-defined operator. comp.VerifyDiagnostics( // (12,15): warning CS8619: Nullability of reference types in value of type 'A<object?>' doesn't match target type 'A<object>'. // B b = a; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "a").WithArguments("A<object?>", "A<object>").WithLocation(12, 15), // (13,11): warning CS8620: Argument of type 'A<object?>' cannot be used for parameter 'b' of type 'B' in 'void Program.F(B b)' due to differences in the nullability of reference types. // F(a); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "a").WithArguments("A<object?>", "B", "b", "void Program.F(B b)").WithLocation(13, 11)); } [Fact] public void UserDefinedConversion_NestedNullability_02() { var source = @"class A<T> { } class B { public static implicit operator A<object>(B b) => throw null!; } class Program { static void F(A<object?> a) { } static void Main() { B b = new B(); A<object?> a = b; // 1 F(b); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/31798: Consider improving warning to reference user-defined operator. comp.VerifyDiagnostics( // (12,24): warning CS8619: Nullability of reference types in value of type 'A<object>' doesn't match target type 'A<object?>'. // A<object?> a = b; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b").WithArguments("A<object>", "A<object?>").WithLocation(12, 24), // (13,11): warning CS8620: Argument of type 'B' cannot be used for parameter 'a' of type 'A<object?>' in 'void Program.F(A<object?> a)' due to differences in the nullability of reference types. // F(b); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b").WithArguments("B", "A<object?>", "a", "void Program.F(A<object?> a)").WithLocation(13, 11)); } [WorkItem(31864, "https://github.com/dotnet/roslyn/issues/31864")] [Fact] public void BestType_DifferentTupleNullability_01() { var source = @"using System; class Program { static void F(bool b) { DateTime? x = DateTime.MaxValue; string? y = null; _ = (b ? (x, y) : (null, null))/*T:(System.DateTime?, string?)*/; _ = (b ? (null, null) : (x, y))/*T:(System.DateTime?, string?)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(31864, "https://github.com/dotnet/roslyn/issues/31864")] [Fact] public void BestType_DifferentTupleNullability_02() { var source = @"class Program { static void F<T, U>(bool b) where T : class, new() where U : struct { T? t1 = null; T? t2 = new T(); U? u1 = null; U? u2 = new U(); _ = (b ? (t1, t2) : (null, null))/*T:(T?, T?)*/; _ = (b ? (null, null) : (u1, u2))/*T:(U?, U?)*/; _ = (b ? (t1, u2) : (null, null))/*T:(T?, U?)*/; _ = (b ? (null, null) : (t2, u1))/*T:(T?, U?)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(31864, "https://github.com/dotnet/roslyn/issues/31864")] [Fact] public void BestType_DifferentTupleNullability_03() { var source = @"class Program { static void F<T, U>() where T : class, new() where U : struct { T? t1 = null; T? t2 = new T(); U? u1 = null; U? u2 = new U(); _ = new[] { (t1, t2), (null, null) }[0]/*T:(T?, T?)*/; _ = new[] { (null, null), (u1, u2) }[0]/*T:(U?, U?)*/; _ = new[] { (t1, u2), (null, null) }[0]/*T:(T?, U?)*/; _ = new[] { (null, null), (t2, u1) }[0]/*T:(T?, U?)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_04() { var source = @"class Program { static void F<T>(bool b) where T : class, new() { _ = (b ? (new T(), new T()) : (null, null))/*T:(T?, T?)*/; _ = (b ? (null, new T()) : (new T(), new T()))/*T:(T?, T!)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_05() { var source = @"class Program { static void F<T>() where T : class, new() { _ = new[] { (new T(), new T()), (null, null) }[0]/*T:(T?, T?)*/; _ = new[] { (null, new T()), (new T(), new T()) }[0]/*T:(T?, T!)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_06() { var source = @"class Program { static void F<T>(bool b, T x, T? y) where T : class { _ = (b ? (x, y) : (y, x))/*T:(T?, T?)*/; _ = (b ? (x, x) : (y, default))/*T:(T?, T?)*/; _ = (b ? (null, x) : (x, y))/*T:(T?, T?)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_07() { var source = @"class Program { static void F<T>(T x, T? y) where T : class { _ = new[] { (x, y), (y, x) }[0]/*T:(T?, T?)*/; _ = new[] { (x, x), (y, default) }[0]/*T:(T?, T?)*/; _ = new[] { (null, x), (x, y) }[0]/*T:(T?, T?)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_08() { var source = @"class Program { static void F<T>(bool b, T? x, object y) where T : class { var t = (b ? (x: y, y: y) : (x, null))/*T:(object? x, object?)*/; var u = (b ? (x: default, y: x) : (x, y))/*T:(T? x, object? y)*/; t.x.ToString(); // 1 t.y.ToString(); // 2 u.x.ToString(); // 3 u.y.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.x").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.y").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.x").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.y").WithLocation(11, 9)); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_09() { var source = @"class Program { static void F<T>(T? x, object y) where T : class { var t = new[] { (x: y, y: y), (x, null) }[0]/*T:(object? x, object?)*/; var u = new[] { (x: default, y: x), (x, y) }[0]/*T:(T? x, object? y)*/; t.x.ToString(); // 1 t.y.ToString(); // 2 u.x.ToString(); // 3 u.y.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // t.x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.x").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // t.y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.y").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // u.x.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.x").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u.y").WithLocation(11, 9)); comp.VerifyTypes(); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33344")] [WorkItem(32575, "https://github.com/dotnet/roslyn/issues/32575")] public void BestType_DifferentTupleNullability_10() { var source = @"class Program { static void F<T, U>(bool b, T t, U u) where U : class { var x = (b ? (t, u) : default)/*T:(T t, U? u)*/; x.Item1.ToString(); // 1 x.Item2.ToString(); // 2 var y = (b ? default : (t, u))/*T:(T t, U? u)*/; y.Item1.ToString(); // 3 y.Item2.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32575: Not handling default for U. comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Item1").WithLocation(7, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.Item2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Item2").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // y.Item1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Item1").WithLocation(10, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // y.Item2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Item2").WithLocation(11, 9) ); comp.VerifyTypes(); } [Fact] [WorkItem(32575, "https://github.com/dotnet/roslyn/issues/32575")] [WorkItem(33344, "https://github.com/dotnet/roslyn/issues/33344")] public void BestType_DifferentTupleNullability_11() { var source = @"class Program { static void F<T, U>(T t, U u) where U : class { var x = new[] { (t, u), default }[0]/*T:(T t, U u)*/; // should be (T t, U? u) x.Item1.ToString(); // 1 x.Item2.ToString(); // 2 var y = new[] { default, (t, u) }[0]/*T:(T t, U u)*/; // should be (T t, U? u) y.Item1.ToString(); // 3 y.Item2.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // https://github.com/dotnet/roslyn/issues/32575: Not handling default for U. // SHOULD BE 4 diagnostics. ); comp.VerifyTypes(); } [Fact] public void BestType_DifferentTupleNullability_12() { var source = @"class Program { static void F<U>(bool b, U? u) where U : struct { var t = b ? (1, u) : default; t.Item1.ToString(); _ = t.Item2.Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8629: Nullable value type may be null. // _ = t.Item2.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t.Item2").WithLocation(8, 13) ); } [Fact] public void BestType_DifferentTupleNullability_13() { var source = @"class Program { static void F<U>(U? u) where U : struct { var t = new[] { (1, u), default }[0]; t.Item1.ToString(); _ = t.Item2.Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8629: Nullable value type may be null. // _ = t.Item2.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "t.Item2").WithLocation(8, 13) ); } [WorkItem(32006, "https://github.com/dotnet/roslyn/issues/32006")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void LambdaReturnType_DifferentTupleNullability_01() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @"using System; class Program { static T F<T>(Func<bool, T> f) { return f(true); } static void G<T, U>() where T : class, new() where U : struct { F(b => { if (b) { T? t1 = null; U? u2 = new U(); return (t1, u2); } return (null, null); })/*T:(T? t1, U? u2)*/; F(b => { if (b) return (null, null); T? t2 = new T(); U? u1 = null; return (t2, u1); })/*T:(T! t2, U? u1)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32006: Warning inferring return type. comp.VerifyDiagnostics( // (20,24): warning CS8619: Nullability of reference types in value of type '(T?, U?)' doesn't match target type '(T? t1, U? u2)'. // return (null, null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, null)").WithArguments("(T?, U?)", "(T? t1, U? u2)").WithLocation(20, 24), // (24,31): warning CS8619: Nullability of reference types in value of type '(T?, U?)' doesn't match target type '(T t2, U? u1)'. // if (b) return (null, null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, null)").WithArguments("(T?, U?)", "(T t2, U? u1)").WithLocation(24, 31)); comp.VerifyTypes(); } [WorkItem(32006, "https://github.com/dotnet/roslyn/issues/32006")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void LambdaReturnType_DifferentTupleNullability_02() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @"using System; class Program { static T F<T>(Func<bool, T> f) { return f(true); } static void G<T>() where T : class, new() { F(b => { if (b) return (new T(), new T()); return (null, null); })/*T:(T!, T!)*/; F(b => { if (b) return (null, new T()); return (new T(), new T()); })/*T:(T!, T!)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32006: Warning inferring return type. comp.VerifyDiagnostics( // (11,59): warning CS8619: Nullability of reference types in value of type '(T?, T?)' doesn't match target type '(T, T)'. // F(b => { if (b) return (new T(), new T()); return (null, null); })/*T:(T!, T!)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, null)").WithArguments("(T?, T?)", "(T, T)").WithLocation(11, 59), // (12,32): warning CS8619: Nullability of reference types in value of type '(T?, T)' doesn't match target type '(T, T)'. // F(b => { if (b) return (null, new T()); return (new T(), new T()); })/*T:(T!, T!)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, new T())").WithArguments("(T?, T)", "(T, T)").WithLocation(12, 32)); comp.VerifyTypes(); } [WorkItem(32006, "https://github.com/dotnet/roslyn/issues/32006")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void LambdaReturnType_DifferentTupleNullability_03() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @"using System; class Program { static T F<T>(Func<bool, T> f) { return f(true); } static void G<T>(T x, T? y) where T : class { F(b => { if (b) return (x, y); return (y, x); })/*T:(T?, T?)*/; F(b => { if (b) return (x, x); return (y, default); })/*T:(T!, T!)*/; F(b => { if (b) return (null, x); return (x, y); })/*T:(T! x, T? y)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32006: Warning inferring return type. comp.VerifyDiagnostics( // (12,47): warning CS8619: Nullability of reference types in value of type '(T? y, T?)' doesn't match target type '(T, T)'. // F(b => { if (b) return (x, x); return (y, default); })/*T:(T?, T?)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(y, default)").WithArguments("(T? y, T?)", "(T, T)").WithLocation(12, 47), // (13,32): warning CS8619: Nullability of reference types in value of type '(T?, T x)' doesn't match target type '(T x, T? y)'. // F(b => { if (b) return (null, x); return (x, y); })/*T:(T?, T?)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(null, x)").WithArguments("(T?, T x)", "(T x, T? y)").WithLocation(13, 32)); comp.VerifyTypes(); } [WorkItem(32006, "https://github.com/dotnet/roslyn/issues/32006")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/32006")] public void LambdaReturnType_DifferentTupleNullability_04() { // See https://github.com/dotnet/roslyn/issues/32006 // need to relax assertion in GetImplicitTupleLiteralConversion var source = @"using System; class Program { static T F<T>(Func<bool, T> f) { return f(true); } static void G<T>(T? x, object y) where T : class { F(b => { if (b) return (y, y); return (x, null); })/*T:(object!, object!)*/; F(b => { if (b) return (default, x); return (x, y); })/*T:(T? x, object! y)*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/32006: Warning inferring return type. comp.VerifyDiagnostics( // (11,47): warning CS8619: Nullability of reference types in value of type '(object? x, object?)' doesn't match target type '(object, object)'. // F(b => { if (b) return (y, y); return (x, null); })/*T:(object?, object?)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, null)").WithArguments("(object? x, object?)", "(object, object)").WithLocation(11, 47), // (12,32): warning CS8619: Nullability of reference types in value of type '(T?, object? x)' doesn't match target type '(T? x, object y)'. // F(b => { if (b) return (default, x); return (x, y); })/*T:(T?, object?)*/; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default, x)").WithArguments("(T?, object? x)", "(T? x, object y)").WithLocation(12, 32)); comp.VerifyTypes(); } [Fact] public void DisplayMultidimensionalArray() { var source = @" class C { void M(A<object> o, A<string[][][,]?> s) { o = s; } } interface A<out T> {} "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8619: Nullability of reference types in value of type 'A<string[]?[][*,*]>' doesn't match target type 'A<object>'. // o = s; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "s").WithArguments("A<string[][][*,*]?>", "A<object>").WithLocation(6, 13) ); comp.VerifyTypes(); } [Fact] [WorkItem(31862, "https://github.com/dotnet/roslyn/issues/31862")] public void Issue31862_01() { var source = @" using System; using System.Collections; using System.Collections.Generic; public class Working<T> : IEnumerable<IEquatable<T>> { public IEnumerator<IEquatable<T>> GetEnumerator() => null; IEnumerator IEnumerable.GetEnumerator() => throw null!; } public class Broken<T> : IEnumerable<IEquatable<T>> { IEnumerator<IEquatable<T>> IEnumerable<IEquatable<T>>.GetEnumerator() => null; IEnumerator IEnumerable.GetEnumerator() => throw null!; } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,58): warning CS8603: Possible null reference return. // public IEnumerator<IEquatable<T>> GetEnumerator() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(8, 58), // (15,78): warning CS8603: Possible null reference return. // IEnumerator<IEquatable<T>> IEnumerable<IEquatable<T>>.GetEnumerator() => null; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(15, 78) ); } [Fact] [WorkItem(31862, "https://github.com/dotnet/roslyn/issues/31862")] public void Issue31862_02() { var source = @" using System; using System.Collections; using System.Collections.Generic; public class Working<T> : IEnumerable<IEquatable<T>> { public IEnumerator<IEquatable<T>?> GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } public class Broken<T> : IEnumerable<IEquatable<T>> { IEnumerator<IEquatable<T>?> IEnumerable<IEquatable<T>>.GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,40): warning CS8613: Nullability of reference types in return type of 'IEnumerator<IEquatable<T>?> Working<T>.GetEnumerator()' doesn't match implicitly implemented member 'IEnumerator<IEquatable<T>> IEnumerable<IEquatable<T>>.GetEnumerator()'. // public IEnumerator<IEquatable<T>?> GetEnumerator() => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnImplicitImplementation, "GetEnumerator").WithArguments("IEnumerator<IEquatable<T>?> Working<T>.GetEnumerator()", "IEnumerator<IEquatable<T>> IEnumerable<IEquatable<T>>.GetEnumerator()").WithLocation(8, 40), // (15,60): warning CS8616: Nullability of reference types in return type doesn't match implemented member 'IEnumerator<IEquatable<T>> IEnumerable<IEquatable<T>>.GetEnumerator()'. // IEnumerator<IEquatable<T>?> IEnumerable<IEquatable<T>>.GetEnumerator() => throw null!; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnExplicitImplementation, "GetEnumerator").WithArguments("IEnumerator<IEquatable<T>> IEnumerable<IEquatable<T>>.GetEnumerator()").WithLocation(15, 60) ); } [Fact] [WorkItem(31862, "https://github.com/dotnet/roslyn/issues/31862")] public void Issue31862_03() { var source = @" using System; using System.Collections; using System.Collections.Generic; public class Working<T> : IEnumerable<IEquatable<T>> { public IEnumerator<IEquatable<T?>> GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } public class Broken<T> : IEnumerable<IEquatable<T>> { IEnumerator<IEquatable<T?>> IEnumerable<IEquatable<T>>.GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } "; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (8,35): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public IEnumerator<IEquatable<T?>> GetEnumerator() => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(8, 35), // (15,28): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // IEnumerator<IEquatable<T?>> IEnumerable<IEquatable<T>>.GetEnumerator() => throw null!; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(15, 28) ); } [Fact] [WorkItem(31862, "https://github.com/dotnet/roslyn/issues/31862")] public void Issue31862_04() { var source = @" using System; using System.Collections; using System.Collections.Generic; public class Working<T> : IEnumerable<IEquatable<T>> { public IEnumerator<IEquatable<T>>? GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } public class Broken<T> : IEnumerable<IEquatable<T>> { IEnumerator<IEquatable<T>>? IEnumerable<IEquatable<T>>.GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(31862, "https://github.com/dotnet/roslyn/issues/31862")] public void Issue31862_05() { var source = @" using System; using System.Collections; using System.Collections.Generic; public class Working<T> : IEnumerable<IEquatable<T>> where T : class { public IEnumerator<IEquatable<T?>> GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } public class Broken<T> : IEnumerable<IEquatable<T>> where T : class { IEnumerator<IEquatable<T?>> IEnumerable<IEquatable<T>>.GetEnumerator() => throw null!; IEnumerator IEnumerable.GetEnumerator() => throw null!; } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(37868, "https://github.com/dotnet/roslyn/issues/37868")] public void IsPatternVariableDeclaration_LeftOfAssignmentOperator() { var source = @" using System; class C { void Test1() { if (unknown is string b = ) { Console.WriteLine(b); } } void Test2(bool a) { if (a is bool (b = a)) { Console.WriteLine(b); } } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,13): error CS0103: The name 'unknown' does not exist in the current context // if (unknown is string b = ) Diagnostic(ErrorCode.ERR_NameNotInContext, "unknown").WithArguments("unknown").WithLocation(8, 13), // (8,35): error CS1525: Invalid expression term ')' // if (unknown is string b = ) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(8, 35), // (10,31): error CS0165: Use of unassigned local variable 'b' // Console.WriteLine(b); Diagnostic(ErrorCode.ERR_UseDefViolation, "b").WithArguments("b").WithLocation(10, 31), // (16,23): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'bool', with 1 out parameters and a void return type. // if (a is bool (b = a)) Diagnostic(ErrorCode.ERR_MissingDeconstruct, "(b ").WithArguments("bool", "1").WithLocation(16, 23), // (16,24): error CS0103: The name 'b' does not exist in the current context // if (a is bool (b = a)) Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(16, 24), // (16,26): error CS1026: ) expected // if (a is bool (b = a)) Diagnostic(ErrorCode.ERR_CloseParenExpected, "=").WithLocation(16, 26), // (16,30): error CS1525: Invalid expression term ')' // if (a is bool (b = a)) Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(16, 30), // (16,30): error CS1002: ; expected // if (a is bool (b = a)) Diagnostic(ErrorCode.ERR_SemicolonExpected, ")").WithLocation(16, 30), // (16,30): error CS1513: } expected // if (a is bool (b = a)) Diagnostic(ErrorCode.ERR_RbraceExpected, ")").WithLocation(16, 30), // (18,31): error CS0103: The name 'b' does not exist in the current context // Console.WriteLine(b); Diagnostic(ErrorCode.ERR_NameNotInContext, "b").WithArguments("b").WithLocation(18, 31)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_UseInExpression() { var source = @" class C { void M(string? s1, string s2) { string s3 = (s1 ??= s2); string? s4 = null, s5 = null; string s6 = (s4 ??= s5); // Warn 1 s4.ToString(); // Warn 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // string s6 = (s4 ??= s5); // Warn 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "s4 ??= s5").WithLocation(8, 22), // (9,9): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // Warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(9, 9)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_AssignsState() { var source = @" class C { object? F = null; void M(C? c1, C c2, C c3) { c1 ??= c2; c1.ToString(); if (c3.F == null) return; c1 = null; c1 ??= c3; c1.F.ToString(); // Warn 1 c1 = null; c1 ??= c3; c1.ToString(); c1.F.ToString(); // Warn 2 if (c1.F == null) return; c1 ??= c2; c1.F.ToString(); // Warn 3 // We could support this in the future if MakeSlot is made smarter to understand // that the slot of a ??= is the slot of the left-hand side. https://github.com/dotnet/roslyn/issues/32501 (c1 ??= c3).F.ToString(); // Warn 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,9): warning CS8602: Dereference of a possibly null reference. // c1.F.ToString(); // Warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.F").WithLocation(14, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // c1.F.ToString(); // Warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.F").WithLocation(19, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // c1.F.ToString(); // Warn 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1.F").WithLocation(23, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // (c1 ??= c3).F.ToString(); // Warn 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(c1 ??= c3).F").WithLocation(27, 9)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_RightStateValidInRightOnly() { var source = @" class C { C GetC(C c) => c; void M(C? c1, C? c2, C c3) { c1 ??= (c2 = c3); c1.ToString(); c2.ToString(); // Warn 1 c1 = null; c2 = null; c1 ??= (c2 = c3).GetC(c2); c1.ToString(); c2.ToString(); // Warn 2 c1 = null; c2 = null; c1 ??= (c2 = c3).GetC(c1); // Warn 3 c1.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // c2.ToString(); // Warn 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(9, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // c2.ToString(); // Warn 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(15, 9), // (19,31): warning CS8604: Possible null reference argument for parameter 'c' in 'C C.GetC(C c)'. // c1 ??= (c2 = c3).GetC(c1); // Warn 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c1").WithArguments("c", "C C.GetC(C c)").WithLocation(19, 31)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_Contravariant() { var source = @" class C { #nullable disable C GetC() => null; #nullable enable void M(C? c1, C c2) { // nullable + non-null = non-null #nullable disable C c3 #nullable enable = (c1 ??= GetC()); _ = c1/*T:C!*/; _ = c3/*T:C!*/; // oblivious + nullable = nullable // Since c3 is non-nullable, the result is non-nullable. c1 = null; var c4 = (c3 ??= c1); _ = c3/*T:C?*/; _ = c4/*T:C?*/; // oblivious + not nullable = not nullable c3 = GetC(); var c5 = (c3 ??= c2); _ = c3/*T:C!*/; _ = c5/*T:C!*/; // not nullable + oblivious = not nullable var c6 = (c2 ??= GetC()); _ = c2/*T:C!*/; _ = c6/*T:C!*/; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_LeftNotTracked() { var source = @" class C { void M(C?[] c1, C c2) { c1[0] ??= c2; c1[0].ToString(); // Warn } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // c1[0].ToString(); // Warn Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1[0]").WithLocation(7, 9)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_RefReturn() { var source = @" class C { void M1(C c1, C? c2) { M2(c1) ??= c2; // Warn 1, 2 M2(c1).ToString(); M2(c2) ??= c1; M2(c2).ToString(); // Warn 3 } ref T M2<T>(T t) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,20): warning CS8601: Possible null reference assignment. // M2(c1) ??= c2; // Warn 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "c2").WithLocation(6, 20), // (10,9): warning CS8602: Dereference of a possibly null reference. // M2(c2).ToString(); // Warn 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "M2(c2)").WithLocation(10, 9)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_NestedLHS() { var source = @" class C { object? F = null; void M1(C c1, object f) { c1.F ??= f; c1.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_Conversions() { var source = @" class C<T> { void M1(C<object>? c1, C<object?> c2, C<object?> c3, C<object>? c4) { c1 ??= c2; c3 ??= c4; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,16): warning CS8619: Nullability of reference types in value of type 'C<object?>' doesn't match target type 'C<object>'. // c1 ??= c2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c2").WithArguments("C<object?>", "C<object>").WithLocation(6, 16), // (7,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // c3 ??= c4; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "c4").WithLocation(7, 16), // (7,16): warning CS8619: Nullability of reference types in value of type 'C<object>' doesn't match target type 'C<object?>'. // c3 ??= c4; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "c4").WithArguments("C<object>", "C<object?>").WithLocation(7, 16)); } [WorkItem(30140, "https://github.com/dotnet/roslyn/issues/30140")] [Fact] public void NullCoalescingAssignment_LeftStillNullableOnRight() { var source = @" class C { void M1(C? c1) { c1 ??= M2(c1); c1.ToString(); } C M2(C c1) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,19): warning CS8604: Possible null reference argument for parameter 'c1' in 'C C.M2(C c1)'. // c1 ??= M2(c1); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "c1").WithArguments("c1", "C C.M2(C c1)").WithLocation(6, 19)); } [Fact] public void NullCoalescingAssignment_DefaultConvertedToNullableUnderlyingType() { var source = @" class C { void M1(int? i) { (i ??= default).ToString(); // default is converted to int, so there's no warning. } }"; CreateCompilation(source, options: WithNullableEnable()).VerifyDiagnostics(); } [Fact] [WorkItem(41273, "https://github.com/dotnet/roslyn/issues/41273")] public void NullCoalescingAssignment_InTryCatchFinally01() { var source = @" using System; public class C { string x; public C() { try { x = """"; } catch (Exception) { x ??= """"; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(41273, "https://github.com/dotnet/roslyn/issues/41273")] public void NullCoalescingAssignment_InTryCatchFinally02() { var source = @" using System; public class C { string x; public C() { try { } catch (Exception) { x ??= """"; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,12): warning CS8618: Non-nullable field 'x' is uninitialized. Consider declaring the field as nullable. // public C() Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "x").WithLocation(7, 12) ); } [Fact] [WorkItem(41273, "https://github.com/dotnet/roslyn/issues/41273")] public void NullCoalescingAssignment_InTryCatchFinally03() { var source = @" public class C { string x; public C() { try { } finally { x ??= """"; } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(41273, "https://github.com/dotnet/roslyn/issues/41273")] public void NullCoalescingAssignment_InTryCatchFinally04() { var source = @" public class C { string x; public C() // 1 { try { x = """"; } finally { x ??= null; // 2 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,12): warning CS8618: Non-nullable field 'x' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "x").WithLocation(6, 12), // (14,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // x ??= null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(14, 19) ); } [Fact] [WorkItem(41273, "https://github.com/dotnet/roslyn/issues/41273")] public void NullCoalescingAssignment_InTryCatchFinally05() { var source = @" using System; public class C { string x; public C() // 1 { try { x = """"; } catch (Exception) { x ??= null; // 2 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,12): warning CS8618: Non-nullable field 'x' must contain a non-null value when exiting constructor. Consider declaring the field as nullable. // public C() // 1 Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "C").WithArguments("field", "x").WithLocation(7, 12), // (15,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // x ??= null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 19) ); } [Fact] public void Deconstruction_01() { var source = @"class Program { static void F<T, U>() where U : class { (T x, U y) = default((T, U)); // 1 x.ToString(); // 2 y.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T x, U y) = default((T, U)); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default((T, U))").WithLocation(5, 22), // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9)); } [Fact] public void Deconstruction_02() { var source = @"class Program { static void F<T, U>() where U : class { (T x, U y) = (default, default); // 1 x.ToString(); // 2 y.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,32): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T x, U y) = (default, default); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(5, 32), // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9)); } [Fact] public void Deconstruction_03() { var source = @"class Program { static void F<T>() where T : class, new() { (T x, T? y) = (null, new T()); // 1 x.ToString(); // 2 y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T x, T? y) = (null, new T()); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 24), // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9)); } [Fact] public void Deconstruction_04() { var source = @"class Program { static void F<T>(T x, T? y) where T : class { (T a, T? b) = (x, y); a.ToString(); b.ToString(); // 1 (a, b) = (y, x); // 2 a.ToString(); // 3 b.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 9), // (8,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // (a, b) = (y, x); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "y").WithLocation(8, 19), // (9,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(9, 9)); } [Fact] public void Deconstruction_05() { var source = @"class Program { static void F<T>((T, T?) t) where T : class { (T a, T? b) = t; a.ToString(); b.ToString(); // 1 (b, a) = t; // 2 a.ToString(); // 3 b.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 9), // (8,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // (b, a) = t; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(8, 18), // (9,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(9, 9)); } [Fact] public void Deconstruction_06() { var source = @"class Program { static void F<T>() where T : class, new() { (T, T?) t = (default, new T()); // 1 (T a, T? b) = t; // 2 a.ToString(); // 3 b.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,21): warning CS8619: Nullability of reference types in value of type '(T?, T)' doesn't match target type '(T, T?)'. // (T, T?) t = (default, new T()); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default, new T())").WithArguments("(T?, T)", "(T, T?)").WithLocation(5, 21), // (6,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T a, T? b) = t; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(6, 23), // (7,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(7, 9)); } [Fact] public void Deconstruction_07() { var source = @"class Program { static void F<T, U>() where U : class { var (x, y) = default((T, U)); x.ToString(); // 1 y.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(7, 9)); } [Fact] public void Deconstruction_08() { var source = @"class Program { static void F<T>() where T : class, new() { T x = default; // 1 T? y = new T(); var (a, b) = (x, y); a.ToString(); // 2 b.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = default; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(5, 15), // (8,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(8, 9)); } [Fact] public void Deconstruction_09() { var source = @"class Program { static void F<T>() where T : class, new() { (T, T?) t = (default, new T()); // 1 var (a, b) = t; a.ToString(); // 2 b.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,21): warning CS8619: Nullability of reference types in value of type '(T?, T)' doesn't match target type '(T, T?)'. // (T, T?) t = (default, new T()); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(default, new T())").WithArguments("(T?, T)", "(T, T?)").WithLocation(5, 21), // (7,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(7, 9)); } [Fact] public void Deconstruction_10() { var source = @"class Program { static void F<T>((T, T?) t) where T : class { if (t.Item2 == null) return; t.Item1 = null; // 1 var (a, b) = t; a.ToString(); // 2 b.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // t.Item1 = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 19), // (8,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(8, 9)); } [Fact] public void Deconstruction_11() { var source = @"class Program { static void F(object? x, object y, string? z) { ((object? a, object? b), string? c) = ((x, y), z); a.ToString(); // 1 b.ToString(); c.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9)); } [Fact] public void Deconstruction_12() { var source = @"class Program { static void F((object?, object) x, string? y) { ((object? a, object? b), string? c) = (x, y); a.ToString(); // 1 b.ToString(); c.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9)); } [Fact] public void Deconstruction_13() { var source = @"class Program { static void F(((object?, object), string?) t) { ((object? a, object? b), string? c) = t; a.ToString(); // 1 b.ToString(); c.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(6, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9)); } [Fact] public void Deconstruction_14() { var source = @"class Program { static void F(object? x, string y, (object, string?) z) { ((object?, object?) a, (object? b, object? c)) = ((x, y), z); a.Item1.ToString(); // 1 a.Item2.ToString(); b.ToString(); c.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): warning CS8602: Dereference of a possibly null reference. // a.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.Item1").WithLocation(6, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(9, 9)); } [Fact] public void Deconstruction_15() { var source = @"class Program { static void F((object?, string) x, object y, string? z) { ((object a, object b), (object x, object y) c) = (x, (y, z)); // 1, 2 a.ToString(); // 3 b.ToString(); c.x.ToString(); c.y.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,59): warning CS8600: Converting null literal or possible null value to non-nullable type. // ((object a, object b), (object x, object y) c) = (x, (y, z)); // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(5, 59), // (5,62): warning CS8619: Nullability of reference types in value of type '(object y, object? z)' doesn't match target type '(object x, object y)'. // ((object a, object b), (object x, object y) c) = (x, (y, z)); // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(y, z)").WithArguments("(object y, object? z)", "(object x, object y)").WithLocation(5, 62), // (6,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(6, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // c.y.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.y").WithLocation(9, 9)); } [Fact] public void Deconstruction_16() { var source = @"class Program { static void F<T, U>(T t, U? u) where U : class { T x; U y; (x, _) = (t, u); (_, y) = (t, u); // 1 (x, _, (_, y)) = (t, t, (u, u)); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,22): warning CS8600: Converting null literal or possible null value to non-nullable type. // (_, y) = (t, u); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(8, 22), // (9,37): warning CS8600: Converting null literal or possible null value to non-nullable type. // (x, _, (_, y)) = (t, t, (u, u)); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(9, 37)); } [Fact] public void Deconstruction_17() { var source = @"class Pair<T, U> where U : class { internal void Deconstruct(out T t, out U? u) => throw null!; } class Program { static void F<T, U>() where U : class { var (t, u) = new Pair<T, U>(); t.ToString(); // 1 u.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // u.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "u").WithLocation(11, 9)); } [Fact] public void Deconstruction_18() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F<T>() where T : class { (T x1, T y1) = new Pair<T, T?>(); // 1 x1.ToString(); y1.ToString(); // 2 (T? x2, T? y2) = new Pair<T, T?>(); x2.ToString(); y2.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T x1, T y1) = new Pair<T, T?>(); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T y1").WithLocation(9, 16), // (11,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(11, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(14, 9)); } [Fact] public void Deconstruction_19() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F<T, U>() where U : class { (T, U?) t = new Pair<T, U?>(); t.Item1.ToString(); // 1 t.Item2.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,21): error CS0029: Cannot implicitly convert type 'Pair<T, U?>' to '(T, U?)' // (T, U?) t = new Pair<T, U?>(); Diagnostic(ErrorCode.ERR_NoImplicitConv, "new Pair<T, U?>()").WithArguments("Pair<T, U?>", "(T, U?)").WithLocation(9, 21), // (10,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // t.Item2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item2").WithLocation(11, 9)); } [Fact] public void Deconstruction_TupleAndDeconstruct() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F<T>(T? x, Pair<T, T?> y) where T : class { (T a, (T? b, T? c)) = (x, y); // 1 a.ToString(); // 2 b.ToString(); c.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,32): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T a, (T? b, T? c)) = (x, y); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(9, 32), // (10,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(12, 9)); } [Fact] [WorkItem(33005, "https://github.com/dotnet/roslyn/issues/33005")] public void Deconstruction_DeconstructAndTuple() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F<T>(Pair<T?, (T, T?)> p) where T : class { (T a, (T? b, T? c)) = p; // 1 a.ToString(); // 2 b.ToString(); c.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T a, (T? b, T? c)) = p; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T a").WithLocation(9, 10), // (10,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(12, 9) ); } [Fact] [WorkItem(33005, "https://github.com/dotnet/roslyn/issues/33005")] public void Deconstruction_DeconstructAndDeconstruct() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F<T>(Pair<T?, Pair<T, T?>> p) where T : class { (T a, (T? b, T? c)) = p; // 1 a.ToString(); // 2 b.ToString(); c.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,10): warning CS8600: Converting null literal or possible null value to non-nullable type. // (T a, (T? b, T? c)) = p; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T a").WithLocation(9, 10), // (10,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(12, 9) ); } [Fact] public void Deconstruction_20() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F1(Pair<object, object>? p1) { var (x, y) = p1; // 1 (x, y) = p1; } static void F2(Pair<object, object>? p2) { if (p2 == null) return; var (x, y) = p2; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,22): warning CS8602: Dereference of a possibly null reference. // var (x, y) = p1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p1").WithLocation(9, 22)); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_21() { var source = @"class Program { static void F<T, U>((T, U) t) where U : struct { object? x; object? y; var u = ((x, y) = t); u.x.ToString(); // 1 u.y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/33011: Should warn for `u.x`. comp.VerifyDiagnostics(); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_22() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F(Pair<object, object?> p) { object? x; object? y; var t = ((x, y) = p); t.x.ToString(); t.y.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/33011: Should warn for `t.y`. comp.VerifyDiagnostics(); } // As above, but with struct type. [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_23() { var source = @"struct Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F(Pair<object, object?> p) { object? x; object? y; var t = ((x, y) = p); t.x.ToString(); t.y.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // https://github.com/dotnet/roslyn/issues/33011: Should warn for `t.y` only. comp.VerifyDiagnostics(); } [Fact] public void Deconstruction_24() { var source = @"class Program { static void F(bool b, object x, object? y) { (object?, object, object?, object, object?, (object, object?), object, object, object?, object) t = (x, x, x, y, y, (y, x), x, x, y, y); // 1 var (_1, _2, _3, _4, _5, (_6a, _6b), _7, _8, _9, _10) = t; _1.ToString(); _2.ToString(); _3.ToString(); _4.ToString(); // 2 _5.ToString(); // 3 _6a.ToString(); // 4 _6b.ToString(); _7.ToString(); _8.ToString(); _9.ToString(); // 5 _10.ToString(); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,109): warning CS8619: Nullability of reference types in value of type '(object, object, object, object?, object?, (object? y, object x), object, object, object?, object?)' doesn't match target type '(object?, object, object?, object, object?, (object, object?), object, object, object?, object)'. // (object?, object, object?, object, object?, (object, object?), object, object, object?, object) t = (x, x, x, y, y, (y, x), x, x, y, y); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "(x, x, x, y, y, (y, x), x, x, y, y)").WithArguments("(object, object, object, object?, object?, (object? y, object x), object, object, object?, object?)", "(object?, object, object?, object, object?, (object, object?), object, object, object?, object)").WithLocation(5, 109), // (10,9): warning CS8602: Dereference of a possibly null reference. // _4.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "_4").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // _5.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "_5").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // _6a.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "_6a").WithLocation(12, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // _9.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "_9").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // _10.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "_10").WithLocation(17, 9)); } [Fact] [WorkItem(33017, "https://github.com/dotnet/roslyn/issues/33017")] public void Deconstruction_25() { var source = @"using System.Collections.Generic; class Program { static void F1<T>(IEnumerable<(T, T)> e1) { foreach (var (x1, y1) in e1) { x1.ToString(); // 1 y1.ToString(); // 2 } foreach ((object? z1, object? w1) in e1) { z1.ToString(); // 3 w1.ToString(); // 4 } } static void F2<T>(IEnumerable<(T, T?)> e2) where T : class { foreach (var (x2, y2) in e2) { x2.ToString(); y2.ToString(); // 5 } foreach ((object? z2, object? w2) in e2) { z2.ToString(); w2.ToString(); // 6 } } static void F3<T>(IEnumerable<(T, T?)> e3) where T : struct { foreach (var (x3, y3) in e3) { x3.ToString(); _ = y3.Value; // 7 } foreach ((object? z3, object? w3) in e3) { z3.ToString(); w3.ToString(); // 8 } } static void F4((object?, object?)[] arr) { foreach ((object, object) el in arr) // 9 { el.Item1.ToString(); el.Item2.ToString(); } foreach ((object i1, object i2) in arr) // 10, 11 { i1.ToString(); // 12 i2.ToString(); // 13 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(8, 13), // (9,13): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(9, 13), // (13,13): warning CS8602: Dereference of a possibly null reference. // z1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1").WithLocation(13, 13), // (14,13): warning CS8602: Dereference of a possibly null reference. // w1.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w1").WithLocation(14, 13), // (22,13): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(22, 13), // (27,13): warning CS8602: Dereference of a possibly null reference. // w2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w2").WithLocation(27, 13), // (35,17): warning CS8629: Nullable value type may be null. // _ = y3.Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y3").WithLocation(35, 17), // (40,13): warning CS8602: Dereference of a possibly null reference. // w3.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "w3").WithLocation(40, 13), // (45,35): warning CS8619: Nullability of reference types in value of type '(object?, object?)' doesn't match target type '(object, object)'. // foreach ((object, object) el in arr) // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "el").WithArguments("(object?, object?)", "(object, object)").WithLocation(45, 35), // (51,44): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach ((object i1, object i2) in arr) // 10, 11 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "arr").WithLocation(51, 44), // (51,44): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach ((object i1, object i2) in arr) // 10, 11 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "arr").WithLocation(51, 44), // (53,13): warning CS8602: Dereference of a possibly null reference. // i1.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "i1").WithLocation(53, 13), // (54,13): warning CS8602: Dereference of a possibly null reference. // i2.ToString(); // 13 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "i2").WithLocation(54, 13) ); } [Fact] public void Deconstruction_26() { var source = @"class Program { static void F(bool c, object? a, object? b) { if (b == null) return; var (x, y, z, w) = c ? (a, b, a, b) : (a, a, b, b); x.ToString(); // 1 y.ToString(); // 2 z.ToString(); // 3 w.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(9, 9)); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] public void Deconstruction_27() { var source = @"class Program { static void F(object? x, object y) { if (x == null) return; y = null; // 1 var t = (new[] { x }, new[] { y }); var (ax, ay) = t; ax[0].ToString(); ay[0].ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // ay[0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ay[0]").WithLocation(10, 9) ); } [Fact] public void Deconstruction_28() { var source = @"class Program { public void Deconstruct(out int x, out int y) => throw null!; static void F(Program? p) { var (x, y) = p; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,22): warning CS8602: Dereference of a possibly null reference. // var (x, y) = p; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p").WithLocation(7, 22) ); } [Fact] public void Deconstruction_29() { var source = @"class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; } class Program { static void F(Pair<object?, Pair<object, object?>?> p) { (object? x, (object y, object? z)) = p; // 1 x.ToString(); // 2 y.ToString(); z.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // (object? x, (object y, object? z)) = p; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(object? x, (object y, object? z)) = p").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(12, 9) ); } [Fact] public void Deconstruction_30() { var source = @" class Pair<T, U> { public void Deconstruct(out T t, out U u) => throw null!; } class Program { static Pair<T, U> CreatePair<T, U>(T t, U u) => new Pair<T, U>(); static void F(string? x, object? y) { if (x == null) return; var p = CreatePair(x, y); (x, y) = p; x.ToString(); // ok y.ToString(); // warning } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(17, 9) ); } [Fact] public void Deconstruction_31() { var source = @" class Pair<T, U> { public void Deconstruct(out T t, out U u) => throw null!; } class Program { static Pair<T, U> CreatePair<T, U>(T t, U u) => new Pair<T, U>(); static void F(string? x, object? y) { if (x == null) return; var p = CreatePair(x, CreatePair(x, y)); object? z; (z, (x, y)) = p; x.ToString(); // ok y.ToString(); // warning } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(18, 9) ); } [Fact] [WorkItem(35131, "https://github.com/dotnet/roslyn/issues/35131")] [WorkItem(33017, "https://github.com/dotnet/roslyn/issues/33017")] public void Deconstruction_32() { var source = @" using System.Collections.Generic; class Pair<T, U> { public void Deconstruct(out T t, out U u) => throw null!; } class Program { static List<Pair<T, U>> CreatePairList<T, U>(T t, U u) => new List<Pair<T, U>>(); static void F(string x, object? y) { foreach((var x2, var y2) in CreatePairList(x, y)) { x2.ToString(); y2.ToString(); // 1 } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,13): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(17, 13) ); } [Fact] [WorkItem(35131, "https://github.com/dotnet/roslyn/issues/35131")] [WorkItem(33017, "https://github.com/dotnet/roslyn/issues/33017")] public void Deconstruction_33() { var source = @" using System.Collections.Generic; class Pair<T, U> { public void Deconstruct(out T t, out U u) => throw null!; } class Program { static List<Pair<T, U>> CreatePairList<T, U>(T t, U u) => new List<Pair<T, U>>(); static void F<T>(T x, T? y) where T : class { x = null; // 1 if (y == null) return; foreach((T x2, T? y2) in CreatePairList(x, y)) // 2 { x2.ToString(); // 3 y2.ToString(); } } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(15, 13), // (17,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // foreach((T x2, T? y2) in CreatePairList(x, y)) // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T x2").WithLocation(17, 18), // (19,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(19, 13) ); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] public void Deconstruction_34() { var source = @"class Program { static void F(object? x, object y) { if (x == null) return; y = null; // 1 var t = (new[] { x }, y); var (ax, ay) = t; ax[0].ToString(); ay.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(6, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // ay.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ay").WithLocation(10, 9) ); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] public void Deconstruction_35() { var source = @" using System.Collections.Generic; class Program { static List<T> MakeList<T>(T a) { throw null!; } static void F(object? x, object y) { if (x == null) return; y = null; // 1 var t = (new[] { x }, MakeList(y)); var (ax, ay) = t; ax[0].ToString(); ay[0].ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 13), // (18,9): warning CS8602: Dereference of a possibly null reference. // ay[0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ay[0]").WithLocation(18, 9) ); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] public void Deconstruction_36() { var source = @" using System.Collections.Generic; class Program { static List<T> MakeList<T>(T a) where T : notnull { throw null!; } static void F(object? x, object y) { if (x == null) return; y = null; // 1 var t = (new[] { x }, MakeList(y)); // 2 var (ax, ay) = t; ax[0].ToString(); ay[0].ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 13), // (14,31): warning CS8714: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'Program.MakeList<T>(T)'. Nullability of type argument 'object?' doesn't match 'notnull' constraint. // var t = (new[] { x }, MakeList(y)); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterNotNullConstraint, "MakeList").WithArguments("Program.MakeList<T>(T)", "T", "object?").WithLocation(14, 31), // (17,9): warning CS8602: Dereference of a possibly null reference. // ay[0].ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ay[0]").WithLocation(17, 9) ); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] public void Deconstruction_37() { var source = @" using System.Collections.Generic; class Program { static List<T> MakeList<T>(T a) { throw null!; } static void F(object? x, object y) { if (x == null) return; y = null; // 1 var ylist = MakeList(y); var ylist2 = MakeList(ylist); var ylist3 = MakeList(ylist2); ylist3 = null; var t = (new[] { x }, MakeList(ylist3)); var (ax, ay) = t; ax[0].ToString(); ay[0].ToString(); // 2 var ay0 = ay[0]; if (ay0 == null) return; ay0[0].ToString(); ay0[0][0].ToString(); ay0[0][0][0].ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8600: Converting null literal or possible null value to non-nullable type. // y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 13), // (21,9): warning CS8602: Dereference of a possibly null reference. // ay[0].ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ay[0]").WithLocation(21, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // ay0[0][0][0].ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ay0[0][0][0]").WithLocation(26, 9) ); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void Deconstruction_38() { var source = @" class Program { static void F(object? x1, object y1) { var t = (x1, y1); var (x2, y2) = t; if (x1 == null) return; y1 = null; // 1 var u = (x1, y1); (x2, y2) = u; x2 = null; y2 = null; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y1 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(9, 14) ); } [Fact] [WorkItem(33019, "https://github.com/dotnet/roslyn/issues/33019")] [WorkItem(40477, "https://github.com/dotnet/roslyn/issues/40477")] public void Deconstruction_39() { var source = @" class Program { static void F(object? x1, object y1) { if (x1 == null) return; y1 = null; // 1 var t = (x1, y1); var (x2, y2) = (t.Item1, t.Item2); x2 = null; y2 = null; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,14): warning CS8600: Converting null literal or possible null value to non-nullable type. // y1 = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(7, 14) ); } [Fact] public void Deconstruction_ExtensionMethod_01() { var source = @"class Pair<T, U> { } static class E { internal static void Deconstruct(this Pair<object?, object>? p, out object x, out object? y) => throw null!; } class Program { static void F(Pair<object, object?>? p) { (object? x, object? y) = p; x.ToString(); y.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,34): warning CS8620: Argument of type 'Pair<object, object?>' cannot be used for parameter 'p' of type 'Pair<object?, object>' in 'void E.Deconstruct(Pair<object?, object>? p, out object x, out object? y)' due to differences in the nullability of reference types. // (object? x, object? y) = p; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "p").WithArguments("Pair<object, object?>", "Pair<object?, object>", "p", "void E.Deconstruct(Pair<object?, object>? p, out object x, out object? y)").WithLocation(12, 34), // (14,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(14, 9)); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_02() { var source = @"struct Pair<T, U> { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U> p, out T t, out U u) => throw null!; } class Program { static void F<T, U>(Pair<T, U> p) where U : class { var (x, y) = p; x.ToString(); // 1 y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 9) ); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_03() { var source = @"class Pair<T, U> { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U> p, out T t, out U u) => throw null!; } class Program { static void F(Pair<object?, object>? p) { (object? x, object? y) = p; // 1 x.ToString(); // 2 y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,34): warning CS8604: Possible null reference argument for parameter 'p' in 'void E.Deconstruct<object?, object>(Pair<object?, object> p, out object? t, out object u)'. // (object? x, object? y) = p; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "p").WithArguments("p", "void E.Deconstruct<object?, object>(Pair<object?, object> p, out object? t, out object u)").WithLocation(12, 34), // (13,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 9) ); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_04() { var source = @"class Pair<T, U> { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U> p, out T t, out U u) => throw null!; } class Program { static void F(Pair<object?, Pair<object, object?>?> p) { (object? x, (object y, object? z)) = p; // 1 x.ToString(); // 2 y.ToString(); z.ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,9): warning CS8604: Possible null reference argument for parameter 'p' in 'void E.Deconstruct<object, object?>(Pair<object, object?> p, out object t, out object? u)'. // (object? x, (object y, object? z)) = p; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(object? x, (object y, object? z)) = p").WithArguments("p", "void E.Deconstruct<object, object?>(Pair<object, object?> p, out object t, out object? u)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(15, 9) ); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_05() { var source = @"class Pair<T, U> { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U>? p, out T t, out U u) => throw null!; } class Program { static void F(Pair<object?, Pair<object, object?>> p) { (object? x, (object y, object? z)) = p; x.ToString(); // 1 y.ToString(); z.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(15, 9) ); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_06() { var source = @"class Pair<T, U> { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U>? p, out T t, out U u) => throw null!; } class Program { static Pair<T, U> CreatePair<T, U>(T t, U u) => new Pair<T, U>(); static void F(string? x, object? y) { if (x == null) return; var p = CreatePair(x, CreatePair(x, y)); object? z; (z, (x, y)) = p; x.ToString(); // ok y.ToString(); // warning } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(19, 9) ); } [Fact] public void Deconstruction_ExtensionMethod_07() { var source = @"class A<T, U> { } class B : A<object, object?> { } static class E { internal static void Deconstruct(this A<object?, object> a, out object? x, out object y) => throw null!; } class Program { static void F(B b) { (object? x, object? y) = b; // 1 x.ToString(); // 2 y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,34): warning CS8620: Argument of type 'B' cannot be used for parameter 'a' of type 'A<object?, object>' in 'void E.Deconstruct(A<object?, object> a, out object? x, out object y)' due to differences in the nullability of reference types. // (object? x, object? y) = b; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b").WithArguments("B", "A<object?, object>", "a", "void E.Deconstruct(A<object?, object> a, out object? x, out object y)").WithLocation(15, 34), // (16,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(16, 9)); } [Fact] public void Deconstruction_ExtensionMethod_08() { var source = @"#nullable enable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; class Enumerable<T> : IAsyncEnumerable<T> { IAsyncEnumerator<T> IAsyncEnumerable<T>.GetAsyncEnumerator(CancellationToken token) => throw null!; } class Pair<T, U> { } static class E { internal static void Deconstruct(this Pair<object?, object> p, out object? x, out object y) => throw null!; } static class Program { static async Task Main() { var e = new Enumerable<Pair<object, object?>>(); await foreach (var (x1, y1) in e) // 1 { x1.ToString(); // 2 y1.ToString(); } await foreach ((object x2, object? y2) in e) // 3, 4 { x2.ToString(); // 5 y2.ToString(); } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { s_IAsyncEnumerable, source }); comp.VerifyDiagnostics( // (21,40): warning CS8620: Argument of type 'Pair<object, object?>' cannot be used for parameter 'p' of type 'Pair<object?, object>' in 'void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)' due to differences in the nullability of reference types. // await foreach (var (x1, y1) in e) // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "e").WithArguments("Pair<object, object?>", "Pair<object?, object>", "p", "void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)").WithLocation(21, 40), // (23,13): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(23, 13), // (26,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // await foreach ((object x2, object? y2) in e) // 3, 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "object x2").WithLocation(26, 25), // (26,51): warning CS8620: Argument of type 'Pair<object, object?>' cannot be used for parameter 'p' of type 'Pair<object?, object>' in 'void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)' due to differences in the nullability of reference types. // await foreach ((object x2, object? y2) in e) // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "e").WithArguments("Pair<object, object?>", "Pair<object?, object>", "p", "void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)").WithLocation(26, 51), // (28,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(28, 13)); } [Fact] public void Deconstruction_ExtensionMethod_09() { var source = @"#nullable enable using System.Threading.Tasks; class Enumerable<T> { public Enumerator<T> GetAsyncEnumerator() => new Enumerator<T>(); } class Enumerator<T> { public T Current => default!; public ValueTask<bool> MoveNextAsync() => default; public ValueTask DisposeAsync() => default; } class Pair<T, U> { } static class E { internal static void Deconstruct(this Pair<object?, object> p, out object? x, out object y) => throw null!; } static class Program { static async Task Main() { var e = new Enumerable<Pair<object, object?>>(); await foreach (var (x1, y1) in e) // 1 { x1.ToString(); // 2 y1.ToString(); } await foreach ((object x2, object? y2) in e) // 3, 4 { x2.ToString(); // 5 y2.ToString(); } } }"; var comp = CreateCompilationWithTasksExtensions(source); comp.VerifyDiagnostics( // (25,40): warning CS8620: Argument of type 'Pair<object, object?>' cannot be used for parameter 'p' of type 'Pair<object?, object>' in 'void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)' due to differences in the nullability of reference types. // await foreach (var (x1, y1) in e) // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "e").WithArguments("Pair<object, object?>", "Pair<object?, object>", "p", "void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)").WithLocation(25, 40), // (27,13): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(27, 13), // (30,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // await foreach ((object x2, object? y2) in e) // 3, 4 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "object x2").WithLocation(30, 25), // (30,51): warning CS8620: Argument of type 'Pair<object, object?>' cannot be used for parameter 'p' of type 'Pair<object?, object>' in 'void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)' due to differences in the nullability of reference types. // await foreach ((object x2, object? y2) in e) // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "e").WithArguments("Pair<object, object?>", "Pair<object?, object>", "p", "void E.Deconstruct(Pair<object?, object> p, out object? x, out object y)").WithLocation(30, 51), // (32,13): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(32, 13)); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_ConstraintWarning() { var source = @"class Pair<T, U> where T : class? { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U> p, out T t, out U u) where T : class => throw null!; } class Program { static void F(Pair<object?, object> p) { var (x, y) = p; // 1 x.ToString(); // 2 y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,22): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'E.Deconstruct<T, U>(Pair<T, U>, out T, out U)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // var (x, y) = p; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "p").WithArguments("E.Deconstruct<T, U>(Pair<T, U>, out T, out U)", "T", "object?").WithLocation(14, 22), // (15,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 9) ); } [Fact] [WorkItem(33006, "https://github.com/dotnet/roslyn/issues/33006")] public void Deconstruction_ExtensionMethod_ConstraintWarning_Nested() { var source = @"class Pair<T, U> where T : class? { } class Pair2<T, U> where U : class? { } static class E { internal static void Deconstruct<T, U>(this Pair<T, U> p, out T t, out U u) where T : class => throw null!; internal static void Deconstruct<T, U>(this Pair2<T, U> p, out T t, out U u) where U : class => throw null!; } class Program { static void F(Pair<object?, Pair2<object, object?>?> p) { var (x, (y, z)) = p; // 1, 2, 3 x.ToString(); // 4 y.ToString(); z.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (21,9): warning CS8604: Possible null reference argument for parameter 'p' in 'void E.Deconstruct<object, object?>(Pair2<object, object?> p, out object t, out object? u)'. // var (x, (y, z)) = p; // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "var (x, (y, z)) = p").WithArguments("p", "void E.Deconstruct<object, object?>(Pair2<object, object?> p, out object t, out object? u)").WithLocation(21, 9), // (21,27): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'E.Deconstruct<T, U>(Pair<T, U>, out T, out U)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // var (x, (y, z)) = p; // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "p").WithArguments("E.Deconstruct<T, U>(Pair<T, U>, out T, out U)", "T", "object?").WithLocation(21, 27), // (21,27): warning CS8634: The type 'object?' cannot be used as type parameter 'U' in the generic type or method 'E.Deconstruct<T, U>(Pair2<T, U>, out T, out U)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // var (x, (y, z)) = p; // 1, 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "p").WithArguments("E.Deconstruct<T, U>(Pair2<T, U>, out T, out U)", "U", "object?").WithLocation(21, 27), // (22,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(22, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(24, 9) ); } [Fact] public void Deconstruction_EvaluationOrder_01() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C { internal object F; } class Program { static void F0(C? x0, C? y0) { (x0.F, // 1 x0.F) = (y0.F, // 2 y0.F); } static void F1(C? x1, C? y1) { (x1.F, // 3 _) = (y1.F, // 4 x1.F); } static void F2(C? x2, C? y2) { (_, y2.F) = // 5 (y2.F, x2.F); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,10): warning CS8602: Dereference of a possibly null reference. // (x0.F, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(11, 10), // (13,18): warning CS8602: Dereference of a possibly null reference. // (y0.F, // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(13, 18), // (18,10): warning CS8602: Dereference of a possibly null reference. // (x1.F, // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(18, 10), // (20,18): warning CS8602: Dereference of a possibly null reference. // (y1.F, // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(20, 18), // (26,13): warning CS8602: Dereference of a possibly null reference. // y2.F) = // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(26, 13), // (28,21): warning CS8602: Dereference of a possibly null reference. // x2.F); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(28, 21)); } [Fact] public void Deconstruction_EvaluationOrder_02() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class C { internal object F; } class Program { static void F0(C? x0, C? y0, C? z0) { ((x0.F, // 1 y0.F), // 2 z0.F) = // 3 ((y0.F, z0.F), x0.F); } static void F1(C? x1, C? y1, C? z1) { ((x1.F, // 4 _), x1.F) = ((y1.F, // 5 z1.F), // 6 z1.F); } static void F2(C? x2, C? y2, C? z2) { ((_, _), x2.F) = // 7 ((x2.F, y2.F), // 8 z2.F); // 9 } static void F3(C? x3, C? y3, C? z3) { (x3.F, // 10 (x3.F, y3.F)) = // 11 (y3.F, (z3.F, // 12 x3.F)); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,11): warning CS8602: Dereference of a possibly null reference. // ((x0.F, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(11, 11), // (12,13): warning CS8602: Dereference of a possibly null reference. // y0.F), // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(12, 13), // (13,17): warning CS8602: Dereference of a possibly null reference. // z0.F) = // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z0").WithLocation(13, 17), // (20,11): warning CS8602: Dereference of a possibly null reference. // ((x1.F, // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(20, 11), // (23,23): warning CS8602: Dereference of a possibly null reference. // ((y1.F, // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(23, 23), // (24,25): warning CS8602: Dereference of a possibly null reference. // z1.F), // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z1").WithLocation(24, 25), // (31,17): warning CS8602: Dereference of a possibly null reference. // x2.F) = // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(31, 17), // (33,25): warning CS8602: Dereference of a possibly null reference. // y2.F), // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(33, 25), // (34,29): warning CS8602: Dereference of a possibly null reference. // z2.F); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z2").WithLocation(34, 29), // (38,10): warning CS8602: Dereference of a possibly null reference. // (x3.F, // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(38, 10), // (40,17): warning CS8602: Dereference of a possibly null reference. // y3.F)) = // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y3").WithLocation(40, 17), // (42,26): warning CS8602: Dereference of a possibly null reference. // (z3.F, // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z3").WithLocation(42, 26)); } [Fact] public void Deconstruction_EvaluationOrder_03() { var source = @"#pragma warning disable 8618 class Pair<T, U> { internal void Deconstruct(out T t, out U u) => throw null!; internal T First; internal U Second; } class Program { static void F0(Pair<object, object>? p0) { (_, _) = p0; // 1 } static void F1(Pair<object, object>? p1) { (_, p1.Second) = // 2 p1; } static void F2(Pair<object, object>? p2) { (p2.First, // 3 _) = p2; } static void F3(Pair<object, object>? p3) { (p3.First, // 4 p3.Second) = p3; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // p0; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p0").WithLocation(14, 17), // (19,13): warning CS8602: Dereference of a possibly null reference. // p1.Second) = // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p1").WithLocation(19, 13), // (24,10): warning CS8602: Dereference of a possibly null reference. // (p2.First, // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p2").WithLocation(24, 10), // (30,10): warning CS8602: Dereference of a possibly null reference. // (p3.First, // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "p3").WithLocation(30, 10)); } [Fact] public void Deconstruction_EvaluationOrder_04() { var source = @"#pragma warning disable 0649 #pragma warning disable 8618 class Pair { internal void Deconstruct(out object x, out object y) => throw null!; internal object First; internal object Second; } class Program { static void F0(Pair? x0, Pair? y0) { ((x0.First, // 1 _), y0.First) = // 2 (x0, y0.Second); } static void F1(Pair? x1, Pair? y1) { ((_, y1.First), // 3 _) = (x1, // 4 y1.Second); } static void F2(Pair? x2, Pair? y2) { ((_, _), x2.First) = // 5 (x2, y2.Second); // 6 } static void F3(Pair? x3, Pair? y3) { (x3.First, // 7 (_, y3.First)) = // 8 (y3.Second, x3); } static void F4(Pair? x4, Pair? y4) { (_, (x4.First, // 9 _)) = (x4.Second, y4); // 10 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,11): warning CS8602: Dereference of a possibly null reference. // ((x0.First, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(13, 11), // (15,17): warning CS8602: Dereference of a possibly null reference. // y0.First) = // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y0").WithLocation(15, 17), // (22,13): warning CS8602: Dereference of a possibly null reference. // y1.First), // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(22, 13), // (24,22): warning CS8602: Dereference of a possibly null reference. // (x1, // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(24, 22), // (31,17): warning CS8602: Dereference of a possibly null reference. // x2.First) = // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(31, 17), // (33,25): warning CS8602: Dereference of a possibly null reference. // y2.Second); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(33, 25), // (37,10): warning CS8602: Dereference of a possibly null reference. // (x3.First, // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(37, 10), // (39,17): warning CS8602: Dereference of a possibly null reference. // y3.First)) = // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y3").WithLocation(39, 17), // (46,14): warning CS8602: Dereference of a possibly null reference. // (x4.First, // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(46, 14), // (49,25): warning CS8602: Dereference of a possibly null reference. // y4); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y4").WithLocation(49, 25)); } [Fact] public void Deconstruction_ImplicitBoxingConversion_01() { var source = @"class Program { static void F<T, U, V>((T, U, V?) t) where U : struct where V : struct { (object a, object b, object c) = t; // 1, 2 a.ToString(); // 3 b.ToString(); c.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,42): warning CS8600: Converting null literal or possible null value to non-nullable type. // (object a, object b, object c) = t; // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(7, 42), // (7,42): warning CS8600: Converting null literal or possible null value to non-nullable type. // (object a, object b, object c) = t; // 1, 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "t").WithLocation(7, 42), // (8,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(10, 9)); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_ImplicitBoxingConversion_02() { var source = @"class Program { static void F<T>(T x, T? y) where T : struct { (T?, T?) t = (x, y); (object? a, object? b) = t; a.ToString(); b.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(8, 9)); } [Fact] public void Deconstruction_ImplicitNullableConversion_01() { var source = @"struct S { internal object F; } class Program { static void F(S s) { (S? x, S? y, S? z) = (s, new S(), default); _ = x.Value; x.Value.F.ToString(); _ = y.Value; y.Value.F.ToString(); // 1 _ = z.Value; // 2 z.Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,21): warning CS0649: Field 'S.F' is never assigned to, and will always have its default value null // internal object F; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "F").WithArguments("S.F", "null").WithLocation(3, 21), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.Value.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.F").WithLocation(13, 9), // (14,13): warning CS8629: Nullable value type may be null. // _ = z.Value; // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "z").WithLocation(14, 13)); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_ImplicitNullableConversion_02() { var source = @"#pragma warning disable 0649 struct S { internal object F; } class Program { static void F(S s) { (S, S) t = (s, new S()); (S? x, S? y) = t; _ = x.Value; x.Value.F.ToString(); _ = y.Value; y.Value.F.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // y.Value.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.Value.F").WithLocation(15, 9)); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_ImplicitNullableConversion_03() { var source = @"#pragma warning disable 0649 struct S<T> { internal T F; } class Program { static void F<T>((S<T?>, S<T>) t) where T : class, new() { (S<T>? x, S<T?>? y) = t; // 1, 2 x.Value.F.ToString(); // 3 y.Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,31): warning CS8619: Nullability of reference types in value of type 'S<T?>' doesn't match target type 'S<T>?'. // (S<T>? x, S<T?>? y) = t; // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("S<T?>", "S<T>?").WithLocation(10, 31), // (10,31): warning CS8619: Nullability of reference types in value of type 'S<T>' doesn't match target type 'S<T?>?'. // (S<T>? x, S<T?>? y) = t; // 1, 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("S<T>", "S<T?>?").WithLocation(10, 31), // (11,9): warning CS8602: Dereference of a possibly null reference. // x.Value.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.Value.F").WithLocation(11, 9)); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_ImplicitNullableConversion_04() { var source = @"#pragma warning disable 0649 struct S<T> { internal T F; } class Program { static void F<T>((object, (S<T?>, S<T>)) t) where T : class, new() { (object a, (S<T>? x, S<T?>? y) b) = t; // 1 b.x.Value.F.ToString(); // 2 b.y.Value.F.ToString(); // 3, 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,45): warning CS8619: Nullability of reference types in value of type '(S<T?>, S<T>)' doesn't match target type '(S<T>? x, S<T?>? y)'. // (object a, (S<T>? x, S<T?>? y) b) = t; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "t").WithArguments("(S<T?>, S<T>)", "(S<T>? x, S<T?>? y)").WithLocation(10, 45), // (11,9): warning CS8629: Nullable value type may be null. // b.x.Value.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "b.x").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // b.y.Value.F.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "b.y").WithLocation(12, 9), // (12,9): warning CS8602: Possible dereference of a null reference. // b.y.Value.F.ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.y.Value.F").WithLocation(12, 9)); } [Fact] [WorkItem(33011, "https://github.com/dotnet/roslyn/issues/33011")] public void Deconstruction_ImplicitUserDefinedConversion_01() { var source = @"class A { } class B { public static implicit operator B?(A a) => new B(); } class Program { static void F((object, (A?, A)) t) { (object x, (B?, B) y) = t; } }"; // https://github.com/dotnet/roslyn/issues/33011 Should have warnings about conversions from B? to B and from A? to A var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] public void Deconstruction_TooFewVariables() { var source = @"class Program { static void F(object x, object y, object? z) { (object? a, object? b) = (x, y, z = 3); a.ToString(); b.ToString(); z.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS8132: Cannot deconstruct a tuple of '3' elements into '2' variables. // (object? a, object? b) = (x, y, z = 3); Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(object? a, object? b) = (x, y, z = 3)").WithArguments("3", "2").WithLocation(5, 9), // (6,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 9)); } [Fact] public void Deconstruction_TooManyVariables() { var source = @"class Program { static void F(object x, object y) { (object? a, object? b, object? c) = (x, y = null); // 1 a.ToString(); // 2 b.ToString(); // 3 c.ToString(); // 4 y.ToString(); // 5 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS8132: Cannot deconstruct a tuple of '2' elements into '3' variables. // (object? a, object? b, object? c) = (x, y = null); // 1 Diagnostic(ErrorCode.ERR_DeconstructWrongCardinality, "(object? a, object? b, object? c) = (x, y = null)").WithArguments("2", "3").WithLocation(5, 9), // (5,53): warning CS8600: Converting null literal or possible null value to non-nullable type. // (object? a, object? b, object? c) = (x, y = null); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(5, 53), // (6,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(6, 9), // (7,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // c.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9)); } [Fact] public void Deconstruction_NoDeconstruct_01() { var source = @"class C { C(object o) { } static void F() { object? z = null; var (x, y) = new C(z = 1); x.ToString(); y.ToString(); z.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,14): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'x'. // var (x, y) = new C(z = 1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "x").WithArguments("x").WithLocation(7, 14), // (7,17): error CS8130: Cannot infer the type of implicitly-typed deconstruction variable 'y'. // var (x, y) = new C(z = 1); Diagnostic(ErrorCode.ERR_TypeInferenceFailedForImplicitlyTypedDeconstructionVariable, "y").WithArguments("y").WithLocation(7, 17), // (7,22): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // var (x, y) = new C(z = 1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C(z = 1)").WithArguments("C", "Deconstruct").WithLocation(7, 22), // (7,22): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. // var (x, y) = new C(z = 1); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C(z = 1)").WithArguments("C", "2").WithLocation(7, 22)); } [Fact] public void Deconstruction_NoDeconstruct_02() { var source = @"class C { C(object o) { } static void F() { object? z = null; (object? x, object? y) = new C(z = 1); x.ToString(); y.ToString(); z.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,34): error CS1061: 'C' does not contain a definition for 'Deconstruct' and no accessible extension method 'Deconstruct' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // (object? x, object? y) = new C(z = 1); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "new C(z = 1)").WithArguments("C", "Deconstruct").WithLocation(7, 34), // (7,34): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. // (object? x, object? y) = new C(z = 1); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C(z = 1)").WithArguments("C", "2").WithLocation(7, 34), // (8,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 9)); } [Fact] public void Deconstruction_TooFewDeconstructArguments() { var source = @"class C { internal void Deconstruct(out object x, out object y, out object z) => throw null!; } class Program { static void F() { (object? x, object? y) = new C(); x.ToString(); y.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,34): error CS7036: There is no argument given that corresponds to the required formal parameter 'z' of 'C.Deconstruct(out object, out object, out object)' // (object? x, object? y) = new C(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "new C()").WithArguments("z", "C.Deconstruct(out object, out object, out object)").WithLocation(9, 34), // (9,34): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 2 out parameters and a void return type. // (object? x, object? y) = new C(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "2").WithLocation(9, 34), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 9)); } [Fact] public void Deconstruction_TooManyDeconstructArguments() { var source = @"class C { internal void Deconstruct(out object x, out object y) => throw null!; } class Program { static void F() { (object? x, object? y, object? z) = new C(); x.ToString(); y.ToString(); z.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,45): error CS1501: No overload for method 'Deconstruct' takes 3 arguments // (object? x, object? y, object? z) = new C(); Diagnostic(ErrorCode.ERR_BadArgCount, "new C()").WithArguments("Deconstruct", "3").WithLocation(9, 45), // (9,45): error CS8129: No suitable 'Deconstruct' instance or extension method was found for type 'C', with 3 out parameters and a void return type. // (object? x, object? y, object? z) = new C(); Diagnostic(ErrorCode.ERR_MissingDeconstruct, "new C()").WithArguments("C", "3").WithLocation(9, 45), // (10,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // z.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "z").WithLocation(12, 9)); } [Fact] [WorkItem(26628, "https://github.com/dotnet/roslyn/issues/26628")] public void ImplicitConstructor_01() { var source = @"#pragma warning disable 414 class Program { object F = null; // warning }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,16): warning CS8625: Cannot convert null literal to non-nullable reference type. // object F = null; // warning Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 16)); } [Fact] [WorkItem(26628, "https://github.com/dotnet/roslyn/issues/26628")] public void ImplicitStaticConstructor_01() { var source = @"#pragma warning disable 414 class Program { static object F = null; // warning }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,23): warning CS8625: Cannot convert null literal to non-nullable reference type. // static object F = null; // warning Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 23)); } [Fact] [WorkItem(26628, "https://github.com/dotnet/roslyn/issues/26628")] [WorkItem(33394, "https://github.com/dotnet/roslyn/issues/33394")] public void ImplicitStaticConstructor_02() { var source = @"class C { C(string s) { } static C Empty = new C(null); // warning }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (4,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // static C Empty = new C(null); // warning Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(4, 28)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_01() { var source = @"class Program { static void F(ref object? x, ref object y) { x = 1; y = null; // 1 x.ToString(); y.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // y = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(6, 13), // (8,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(8, 9)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_02() { var source = @"class Program { static void F(object? px, object py) { ref object? x = ref px; ref object y = ref py; x = 1; y = null; // 1 x.ToString(); y.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8625: Cannot convert null literal to non-nullable reference type. // y = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(8, 13), // (10,9): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(10, 9)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_03() { var source = @"class Program { static void F(ref int? x, ref int? y) { x = 1; y = null; _ = x.Value; _ = y.Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,13): warning CS8629: Nullable value type may be null. // _ = y.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(8, 13)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_04() { var source = @"class Program { static void F(int? px, int? py) { ref int? x = ref px; ref int? y = ref py; x = 1; y = null; _ = x.Value; _ = y.Value; // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,13): warning CS8629: Nullable value type may be null. // _ = y.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y").WithLocation(10, 13)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_05() { var source = @"#pragma warning disable 8618 class C { internal object F; } class Program { static void F(ref C x, ref C y) { x = new C() { F = 1 }; y = new C() { F = null }; // 1 x.F.ToString(); y.F.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,27): warning CS8625: Cannot convert null literal to non-nullable reference type. // y = new C() { F = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(11, 27), // (13,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(13, 9)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_06() { var source = @"#pragma warning disable 8618 class C { internal object? F; } class Program { static void F(ref C x, ref C y) { x = new C() { F = 1 }; y = new C() { F = null }; x.F.ToString(); y.F.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(13, 9)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_07() { var source = @"#pragma warning disable 8618 class C { internal object F; } class Program { static void F(C px, C py) { ref C x = ref px; ref C y = ref py; x = new C() { F = 1 }; y = new C() { F = null }; // 1 x.F.ToString(); y.F.ToString(); // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,27): warning CS8625: Cannot convert null literal to non-nullable reference type. // y = new C() { F = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 27), // (15,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(15, 9)); } [Fact] [WorkItem(25868, "https://github.com/dotnet/roslyn/issues/25868")] public void ByRefTarget_08() { var source = @"#pragma warning disable 8618 class C { internal object? F; } class Program { static void F(C px, C py) { ref C x = ref px; ref C y = ref py; x = new C() { F = 1 }; y = new C() { F = null }; x.F.ToString(); y.F.ToString(); // 1 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(15, 9)); } [Fact] [WorkItem(33095, "https://github.com/dotnet/roslyn/issues/33095")] public void ByRefTarget_09() { var source = @"class Program { static void F(ref string x) { ref string? y = ref x; // 1 y = null; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,29): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // ref string? y = ref x; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("string", "string?").WithLocation(5, 29) ); } [Fact] [WorkItem(33095, "https://github.com/dotnet/roslyn/issues/33095")] public void ByRefTarget_10() { var source = @"class Program { static ref string F1(ref string? x) { return ref x; // 1 } static ref string? F2(ref string y) { return ref y; // 2 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,20): warning CS8619: Nullability of reference types in value of type 'string?' doesn't match target type 'string'. // return ref x; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "x").WithArguments("string?", "string").WithLocation(5, 20), // (9,20): warning CS8619: Nullability of reference types in value of type 'string' doesn't match target type 'string?'. // return ref y; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "y").WithArguments("string", "string?").WithLocation(9, 20) ); } [Fact] public void AssignmentToSameVariable_01() { var source = @"#pragma warning disable 8618 class C { internal C F; } class Program { static void F() { C a = new C() { F = null }; // 1 a = a; a.F.ToString(); // 2 C b = new C() { F = new C() { F = null } }; // 3 b.F = b.F; b.F.F.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // C a = new C() { F = null }; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(10, 29), // (11,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // a = a; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "a = a").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // a.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a.F").WithLocation(12, 9), // (13,43): warning CS8625: Cannot convert null literal to non-nullable reference type. // C b = new C() { F = new C() { F = null } }; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 43), // (14,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // b.F = b.F; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "b.F = b.F").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // b.F.F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b.F.F").WithLocation(15, 9)); } [Fact] public void AssignmentToSameVariable_02() { var source = @"#pragma warning disable 8618 struct A { internal int? F; } struct B { internal A A; } class Program { static void F() { A a = new A() { F = 1 }; a = a; _ = a.F.Value; B b = new B() { A = new A() { F = 2 } }; b.A = b.A; _ = b.A.F.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // a = a; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "a = a").WithLocation(15, 9), // (18,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // b.A = b.A; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "b.A = b.A").WithLocation(18, 9)); } [Fact] public void AssignmentToSameVariable_03() { var source = @"#pragma warning disable 8618 class C { internal object F; } class Program { static void F(C? c) { c.F = c.F; // 1 c.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS1717: Assignment made to same variable; did you mean to assign something else? // c.F = c.F; // 1 Diagnostic(ErrorCode.WRN_AssignmentToSelf, "c.F = c.F").WithLocation(10, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // c.F = c.F; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(10, 9)); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_01() { var source = @"class Program { static readonly string? F = null; static readonly int? G = null; static void Main() { if (F != null) F.ToString(); if (G != null) _ = G.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_02() { var source = @"#pragma warning disable 0649, 8618 class C<T> { static T F; static void M() { if (F == null) return; F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_03() { var source = @"#pragma warning disable 0649, 8618 class C<T> { internal static T F; } class Program { static void F1<T1>() { C<T1>.F.ToString(); // 1 C<T1>.F.ToString(); } static void F2<T2>() where T2 : class { C<T2?>.F.ToString(); // 2 C<T2>.F.ToString(); } static void F3<T3>() where T3 : class { C<T3>.F.ToString(); C<T3?>.F.ToString(); } static void F4<T4>() where T4 : struct { _ = C<T4?>.F.Value; // 3 _ = C<T4?>.F.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // C<T1>.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T1>.F").WithLocation(10, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // C<T2?>.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T2?>.F").WithLocation(15, 9), // (25,13): warning CS8629: Nullable value type may be null. // _ = C<T4?>.F.Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "C<T4?>.F").WithLocation(25, 13)); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_04() { var source = @"#pragma warning disable 0649, 8618 class C<T> { internal static T F; } class Program { static void F1<T1>() { C<T1>.F = default; // 1 C<T1>.F.ToString(); // 2 } static void F2<T2>() where T2 : class, new() { C<T2?>.F = new T2(); C<T2?>.F.ToString(); } static void F3<T3>() where T3 : class, new() { C<T3>.F = new T3(); C<T3>.F.ToString(); } static void F4<T4>() where T4 : class { C<T4>.F = null; // 3 C<T4>.F.ToString(); // 4 } static void F5<T5>() where T5 : struct { C<T5?>.F = default(T5); _ = C<T5?>.F.Value; } static void F6<T6>() where T6 : new() { C<T6>.F = new T6(); C<T6>.F.ToString(); } static void F7() { C<string>.F = null; // 5 _ = C<string>.F.Length; // 6 } static void F8() { C<int?>.F = 3; _ = C<int?>.F.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,19): warning CS8601: Possible null reference assignment. // C<T1>.F = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(10, 19), // (11,9): warning CS8602: Dereference of a possibly null reference. // C<T1>.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T1>.F").WithLocation(11, 9), // (25,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // C<T4>.F = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(25, 19), // (26,9): warning CS8602: Dereference of a possibly null reference. // C<T4>.F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T4>.F").WithLocation(26, 9), // (40,23): warning CS8625: Cannot convert null literal to non-nullable reference type. // C<string>.F = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(40, 23), // (41,13): warning CS8602: Dereference of a possibly null reference. // _ = C<string>.F.Length; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<string>.F").WithLocation(41, 13)); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_05() { var source = @"class C<T> { internal static T P { get => throw null!; set { } } } class Program { static void F1<T1>() { C<T1>.P = default; // 1 C<T1>.P.ToString(); // 2 } static void F2<T2>() where T2 : class, new() { C<T2?>.P = new T2(); C<T2?>.P.ToString(); } static void F3<T3>() where T3 : class, new() { C<T3>.P = new T3(); C<T3>.P.ToString(); } static void F4<T4>() where T4 : class { C<T4>.P = null; // 3 C<T4>.P.ToString(); // 4 } static void F5<T5>() where T5 : struct { C<T5?>.P = default(T5); _ = C<T5?>.P.Value; } static void F6<T6>() where T6 : new() { C<T6>.P = new T6(); C<T6>.P.ToString(); } static void F7() { C<string>.P = null; // 5 _ = C<string>.P.Length; // 6 } static void F8() { C<int?>.P = 3; _ = C<int?>.P.Value; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,19): warning CS8601: Possible null reference assignment. // C<T1>.P = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(13, 19), // (14,9): warning CS8602: Dereference of a possibly null reference. // C<T1>.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T1>.P").WithLocation(14, 9), // (28,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // C<T4>.P = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(28, 19), // (29,9): warning CS8602: Dereference of a possibly null reference. // C<T4>.P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<T4>.P").WithLocation(29, 9), // (43,23): warning CS8625: Cannot convert null literal to non-nullable reference type. // C<string>.P = null; // 5 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(43, 23), // (44,13): warning CS8602: Dereference of a possibly null reference. // _ = C<string>.P.Length; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "C<string>.P").WithLocation(44, 13)); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_06() { var source = @"#pragma warning disable 0649, 8618 struct S<T> { internal static T F; } class Program { static void F1<T1>() { S<T1>.F = default; // 1 S<T1>.F.ToString(); // 2 } static void F2<T2>() where T2 : class, new() { S<T2?>.F = new T2(); S<T2?>.F.ToString(); } static void F3<T3>() where T3 : class { S<T3>.F = null; // 3 S<T3>.F.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,19): warning CS8601: Possible null reference assignment. // S<T1>.F = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(10, 19), // (11,9): warning CS8602: Dereference of a possibly null reference. // S<T1>.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "S<T1>.F").WithLocation(11, 9), // (20,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // S<T3>.F = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(20, 19), // (21,9): warning CS8602: Dereference of a possibly null reference. // S<T3>.F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "S<T3>.F").WithLocation(21, 9)); } [Fact] [WorkItem(26651, "https://github.com/dotnet/roslyn/issues/26651")] public void StaticMember_07() { var source = @"struct S<T> { internal static T P { get; set; } } class Program { static void F1<T1>() { S<T1>.P = default; // 1 S<T1>.P.ToString(); // 2 } static void F2<T2>() where T2 : class, new() { S<T2?>.P = new T2(); S<T2?>.P.ToString(); } static void F3<T3>() where T3 : class { S<T3>.P = null; // 3 S<T3>.P.ToString(); // 4 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (3,23): warning CS8618: Non-nullable property 'P' is uninitialized. Consider declaring the property as nullable. // internal static T P { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "P").WithArguments("property", "P").WithLocation(3, 23), // (9,19): warning CS8601: Possible null reference assignment. // S<T1>.P = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(9, 19), // (10,9): warning CS8602: Dereference of a possibly null reference. // S<T1>.P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "S<T1>.P").WithLocation(10, 9), // (19,19): warning CS8625: Cannot convert null literal to non-nullable reference type. // S<T3>.P = null; // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(19, 19), // (20,9): warning CS8602: Dereference of a possibly null reference. // S<T3>.P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "S<T3>.P").WithLocation(20, 9)); } [Fact] public void Expression_VoidReturn() { var source = @"class Program { static object F(object x) => x; static void G(object? y) { return F(y); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,9): error CS0127: Since 'Program.G(object?)' returns void, a return keyword must not be followed by an object expression // return F(y); Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("Program.G(object?)").WithLocation(6, 9), // (6,18): warning CS8604: Possible null reference argument for parameter 'x' in 'object Program.F(object x)'. // return F(y); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "object Program.F(object x)").WithLocation(6, 18)); } [Fact] public void Expression_AsyncTaskReturn() { var source = @"using System.Threading.Tasks; class Program { static object F(object x) => x; static async Task G(object? y) { await Task.Delay(0); return F(y); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): error CS1997: Since 'Program.G(object?)' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'? // return F(y); Diagnostic(ErrorCode.ERR_TaskRetNoObjectRequired, "return").WithArguments("Program.G(object?)").WithLocation(8, 9), // (8,18): warning CS8604: Possible null reference argument for parameter 'x' in 'object Program.F(object x)'. // return F(y); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "object Program.F(object x)").WithLocation(8, 18)); } [Fact] [WorkItem(33481, "https://github.com/dotnet/roslyn/issues/33481")] public void TypelessTuple_VoidReturn() { var source = @"class Program { static void F() { return (null, string.Empty); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,9): error CS0127: Since 'Program.F()' returns void, a return keyword must not be followed by an object expression // return (null, string.Empty); Diagnostic(ErrorCode.ERR_RetNoObjectRequired, "return").WithArguments("Program.F()").WithLocation(5, 9)); } [Fact] [WorkItem(33481, "https://github.com/dotnet/roslyn/issues/33481")] public void TypelessTuple_AsyncTaskReturn() { var source = @"using System.Threading.Tasks; class Program { static async Task F() { await Task.Delay(0); return (null, string.Empty); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,9): error CS1997: Since 'Program.F()' is an async method that returns 'Task', a return keyword must not be followed by an object expression. Did you intend to return 'Task<T>'? // return (null, string.Empty); Diagnostic(ErrorCode.ERR_TaskRetNoObjectRequired, "return").WithArguments("Program.F()").WithLocation(7, 9)); } [Fact] public void TypelessTuple_VoidLambdaReturn() { var source = @"class Program { static void F() { _ = new System.Action(() => { return (null, string.Empty); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // return (null, string.Empty); Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(7, 13)); } [Fact] public void TypelessTuple_AsyncTaskLambdaReturn() { var source = @"using System.Threading.Tasks; class Program { static void F() { _ = new System.Func<Task>(async () => { await Task.Delay(0); return (null, string.Empty); }); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,13): error CS8031: Async lambda expression converted to a 'Task' returning delegate cannot return a value. Did you intend to return 'Task<T>'? // return (null, string.Empty); Diagnostic(ErrorCode.ERR_TaskRetNoObjectRequiredLambda, "return").WithLocation(9, 13)); } [Fact] [WorkItem(29967, "https://github.com/dotnet/roslyn/issues/29967")] public void InterfaceProperties_01() { var source = @"interface IA<T> { T A { get; } } interface IB<T> : IA<T> { T B { get; } } class Program { static IB<T> CreateB<T>(T t) { throw null!; } static void F1<T>(T x1) { if (x1 == null) return; var y1 = CreateB(x1); y1.A.ToString(); // 1 y1.B.ToString(); // 2 } static void F2<T>() where T : class { T x2 = null; // 3 var y2 = CreateB(x2); y2.ToString(); y2.A.ToString(); // 4 y2.B.ToString(); // 5 } static void F3<T>() where T : class, new() { T? x3 = new T(); var y3 = CreateB(x3); y3.A.ToString(); y3.B.ToString(); } static void F4<T>() where T : struct { T? x4 = null; var y4 = CreateB(x4); _ = y4.A.Value; // 6 _ = y4.B.Value; // 7 } static void F5<T>() where T : struct { T? x5 = new T(); var y5 = CreateB(x5); _ = y5.A.Value; // 8 _ = y5.B.Value; // 9 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,9): warning CS8602: Dereference of a possibly null reference. // y1.A.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1.A").WithLocation(19, 9), // (20,9): warning CS8602: Dereference of a possibly null reference. // y1.B.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1.B").WithLocation(20, 9), // (24,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x2 = null; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(24, 16), // (27,9): warning CS8602: Dereference of a possibly null reference. // y2.A.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2.A").WithLocation(27, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // y2.B.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2.B").WithLocation(28, 9), // (41,13): warning CS8629: Nullable value type may be null. // _ = y4.A.Value; // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y4.A").WithLocation(41, 13), // (42,13): warning CS8629: Nullable value type may be null. // _ = y4.B.Value; // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y4.B").WithLocation(42, 13), // (48,13): warning CS8629: Nullable value type may be null. // _ = y5.A.Value; // 8 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y5.A").WithLocation(48, 13), // (49,13): warning CS8629: Nullable value type may be null. // _ = y5.B.Value; // 9 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "y5.B").WithLocation(49, 13)); } [Fact] [WorkItem(29967, "https://github.com/dotnet/roslyn/issues/29967")] public void InterfaceProperties_02() { var source = @"interface IA<T> { T A { get; } } interface IB<T> { T B { get; } } interface IC<T, U> : IA<T>, IB<U> { } class Program { static IC<T, U> CreateC<T, U>(T t, U u) { throw null!; } static void F<T, U>() where T : class, new() where U : class { T? x = new T(); T y = null; // 1 var xy = CreateC(x, y); xy.A.ToString(); xy.B.ToString(); // 2 var yx = CreateC(y, x); yx.A.ToString(); // 3 yx.B.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(23, 15), // (26,9): warning CS8602: Dereference of a possibly null reference. // xy.B.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "xy.B").WithLocation(26, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // yx.A.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "yx.A").WithLocation(28, 9)); } [Fact] [WorkItem(29967, "https://github.com/dotnet/roslyn/issues/29967")] public void InterfaceMethods_01() { var source = @"interface IA<T> { void A(T t); } interface IB<T> : IA<T> { void B(T t); } class Program { static bool b = false; static IB<T> CreateB<T>(T t) { throw null!; } static void F1<T>(T x1) { if (x1 == null) return; T y1 = default; var ix1 = CreateB(x1); var iy1 = b ? CreateB(y1) : null!; if (b) ix1.A(y1); // 1 if (b) ix1.B(y1); // 2 iy1.A(x1); iy1.B(x1); } static void F2<T>() where T : class, new() { T x2 = null; // 3 T? y2 = new T(); var ix2 = CreateB(x2); var iy2 = CreateB(y2); if (b) ix2.A(y2); if (b) ix2.B(y2); if (b) iy2.A(x2); // 4 if (b) iy2.B(x2); // 5 } static void F3<T>() where T : struct { T? x3 = null; T? y3 = new T(); var ix3 = CreateB(x3); var iy3 = CreateB(y3); ix3.A(y3); ix3.B(y3); iy3.A(x3); iy3.B(x3); } }"; var comp = CreateCompilation(source, options: WithNullableEnable(), parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (22,22): warning CS8604: Possible null reference argument for parameter 't' in 'void IA<T>.A(T t)'. // if (b) ix1.A(y1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y1").WithArguments("t", "void IA<T>.A(T t)").WithLocation(22, 22), // (23,22): warning CS8604: Possible null reference argument for parameter 't' in 'void IB<T>.B(T t)'. // if (b) ix1.B(y1); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y1").WithArguments("t", "void IB<T>.B(T t)").WithLocation(23, 22), // (29,16): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x2 = null; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(29, 16), // (35,22): warning CS8604: Possible null reference argument for parameter 't' in 'void IA<T>.A(T t)'. // if (b) iy2.A(x2); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("t", "void IA<T>.A(T t)").WithLocation(35, 22), // (36,22): warning CS8604: Possible null reference argument for parameter 't' in 'void IB<T>.B(T t)'. // if (b) iy2.B(x2); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x2").WithArguments("t", "void IB<T>.B(T t)").WithLocation(36, 22)); } [Fact] [WorkItem(29967, "https://github.com/dotnet/roslyn/issues/29967")] public void InterfaceMethods_02() { var source = @"interface IA { T A<T>(T u); } interface IB<T> { T B<U>(U u); } interface IC<T> : IA, IB<T> { } class Program { static IC<T> CreateC<T>(T t) { throw null!; } static void F<T, U>() where T : class, new() where U : class { T? x = new T(); U y = null; // 1 var ix = CreateC(x); var iy = CreateC(y); ix.A(y).ToString(); // 2 ix.B(y).ToString(); iy.A(x).ToString(); iy.B(x).ToString(); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (23,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // U y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(23, 15), // (26,9): warning CS8602: Dereference of a possibly null reference. // ix.A(y).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ix.A(y)").WithLocation(26, 9), // (29,9): warning CS8602: Dereference of a possibly null reference. // iy.B(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "iy.B(x)").WithLocation(29, 9)); } [Fact] [WorkItem(36018, "https://github.com/dotnet/roslyn/issues/36018")] public void InterfaceMethods_03() { var source = @" #nullable enable interface IEquatable<T> { bool Equals(T other); } interface I1 : IEquatable<I1?>, IEquatable<string?> { } class C1 : I1 { public bool Equals(string? other) { return true; } public bool Equals(I1? other) { return true; } } class C2 { void M(I1 x, string y) { x.Equals(y); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(36018, "https://github.com/dotnet/roslyn/issues/36018")] public void InterfaceMethods_04() { var source = @" #nullable enable interface IEquatable<T> { bool Equals(T other); } interface I1 : IEquatable<I1>, IEquatable<string> { } class C1 : I1 { public bool Equals(string other) { return true; } public bool Equals(I1 other) { return true; } } class C2 { void M(I1 x, string? y) { x.Equals(y); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (28,18): warning CS8604: Possible null reference argument for parameter 'other' in 'bool IEquatable<string>.Equals(string other)'. // x.Equals(y); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("other", "bool IEquatable<string>.Equals(string other)").WithLocation(28, 18) ); } [Fact] [WorkItem(36018, "https://github.com/dotnet/roslyn/issues/36018")] public void InterfaceMethods_05() { var source = @" #nullable enable interface IEquatable<T> { bool Equals(T other); } interface I1<T> : IEquatable<I1<T>>, IEquatable<T> { } class C2 { void M(string? y, string z) { GetI1(y).Equals(y); GetI1(z).Equals(y); } I1<T> GetI1<T>(T x) => throw null!; } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (16,25): warning CS8604: Possible null reference argument for parameter 'other' in 'bool IEquatable<string>.Equals(string other)'. // GetI1(z).Equals(y); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("other", "bool IEquatable<string>.Equals(string other)").WithLocation(16, 25) ); } [Fact, WorkItem(33347, "https://github.com/dotnet/roslyn/issues/33347")] public void NestedNullConditionalAccess() { var source = @" class Node { public Node? Next = null; void M(Node node) { } private static void Test(Node? node) { node?.Next?.Next?.M(node.Next); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31909, "https://github.com/dotnet/roslyn/issues/31909")] public void NestedNullConditionalAccess2() { var source = @" public class C { public C? f; void Test1(C? c) => c?.f.M(c.f.ToString()); // nested use of `c.f` is safe void Test2(C? c) => c.f.M(c.f.ToString()); void M(string s) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,27): warning CS8602: Dereference of a possibly null reference. // void Test1(C? c) => c?.f.M(c.f.ToString()); // nested use of `c.f` is safe Diagnostic(ErrorCode.WRN_NullReferenceReceiver, ".f").WithLocation(5, 27), // (6,25): warning CS8602: Dereference of a possibly null reference. // void Test2(C? c) => c.f.M(c.f.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(6, 25), // (6,25): warning CS8602: Dereference of a possibly null reference. // void Test2(C? c) => c.f.M(c.f.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.f").WithLocation(6, 25) ); } [Fact, WorkItem(33347, "https://github.com/dotnet/roslyn/issues/33347")] public void NestedNullConditionalAccess3() { var source = @" class Node { public Node? Next = null; static Node M2(Node a, Node b) => a; Node M1() => null!; private static void Test(Node notNull, Node? possiblyNull) { _ = possiblyNull?.Next?.M1() ?? M2(possiblyNull = notNull, possiblyNull.Next = notNull); possiblyNull.Next.M1(); // incorrect warning } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(31905, "https://github.com/dotnet/roslyn/issues/31905")] public void NestedNullConditionalAccess4() { var source = @" public class C { public C? Nested; void Test1(C? c) => c?.Nested?.M(c.Nested.ToString()); void Test2(C? c) => c.Nested?.M(c.Nested.ToString()); void Test3(C c) => c?.Nested?.M(c.Nested.ToString()); void M(string s) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,25): warning CS8602: Dereference of a possibly null reference. // void Test2(C? c) => c.Nested?.M(c.Nested.ToString()); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(7, 25) ); } [Fact] public void ConditionalAccess() { var source = @"class C { void M1(C c, C[] a) { _ = (c?.S).Length; _ = (a?[0]).P; } void M2<T>(T t) where T : I { if (t == null) return; _ = (t?.S).Length; _ = (t?[0]).P; } int P { get => 0; } string S => throw null!; } interface I { string S { get; } C this[int i] { get; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,14): warning CS8602: Dereference of a possibly null reference. // _ = (c?.S).Length; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c?.S").WithLocation(5, 14), // (6,14): warning CS8602: Dereference of a possibly null reference. // _ = (a?[0]).P; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a?[0]").WithLocation(6, 14), // (11,14): warning CS8602: Dereference of a possibly null reference. // _ = (t?.S).Length; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t?.S").WithLocation(11, 14), // (12,14): warning CS8602: Dereference of a possibly null reference. // _ = (t?[0]).P; Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t?[0]").WithLocation(12, 14) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33615")] public void TestSubstituteMemberOfTuple() { var source = @"using System; class C { static void Main() { Console.WriteLine(Test(42)); } public static Test(object? a) { if (a == null) return; var x = (f1: a, f2: a); Func<object> f = () => x.Test(a); f(); } } namespace System { public struct ValueTuple<T1, T2> { public T1 Item1; public T2 Item2; public ValueTuple(T1 item1, T2 item2) { this.Item1 = item1; this.Item2 = item2; } public override string ToString() { return '{' + Item1?.ToString() + "", "" + Item2?.ToString() + '}'; } public U Test<U>(U val) { return val; } } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(33905, "https://github.com/dotnet/roslyn/issues/33905")] public void TestDiagnosticsInUnreachableCode() { var source = @"#pragma warning disable 0162 // suppress unreachable statement warning #pragma warning disable 0219 // suppress unused local warning class G<T> { public static void Test(bool b, object? o, G<string?> g) { if (b) M1(o); // 1 M2(g); // 2 if (false) M1(o); if (false) M2(g); if (false && M1(o)) M2(g); if (false && M2(g)) M1(o); if (true || M1(o)) M2(g); // 3 if (true || M2(g)) M1(o); // 4 G<string> g1 = g; // 5 if (false) { G<string> g2 = g; } if (false) { object o1 = null; } } public static bool M1(object o) => true; public static bool M2(G<string> o) => true; }"; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,19): warning CS8604: Possible null reference argument for parameter 'o' in 'bool G<T>.M1(object o)'. // if (b) M1(o); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "bool G<T>.M1(object o)").WithLocation(7, 19), // (8,12): warning CS8620: Argument of type 'G<string?>' cannot be used for parameter 'o' of type 'G<string>' in 'bool G<T>.M2(G<string> o)' due to differences in the nullability of reference types. // M2(g); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "g").WithArguments("G<string?>", "G<string>", "o", "bool G<T>.M2(G<string> o)").WithLocation(8, 12), // (14,16): warning CS8620: Argument of type 'G<string?>' cannot be used for parameter 'o' of type 'G<string>' in 'bool G<T>.M2(G<string> o)' due to differences in the nullability of reference types. // M2(g); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "g").WithArguments("G<string?>", "G<string>", "o", "bool G<T>.M2(G<string> o)").WithLocation(14, 16), // (16,16): warning CS8604: Possible null reference argument for parameter 'o' in 'bool G<T>.M1(object o)'. // M1(o); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("o", "bool G<T>.M1(object o)").WithLocation(16, 16), // (17,24): warning CS8619: Nullability of reference types in value of type 'G<string?>' doesn't match target type 'G<string>'. // G<string> g1 = g; // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "g").WithArguments("G<string?>", "G<string>").WithLocation(17, 24)); } [Fact] [WorkItem(33446, "https://github.com/dotnet/roslyn/issues/33446")] [WorkItem(34018, "https://github.com/dotnet/roslyn/issues/34018")] public void NullInferencesInFinallyClause() { var source = @"class Node { public Node? Next = null!; static void M1(Node node) { try { Mout(out node.Next); } finally { Mout(out node); // might set node to one in which node.Next == null } node.Next.ToString(); // 1 } static void M2() { Node? node = null; try { Mout(out node); } finally { if (node is null) {} else {} } node.ToString(); } static void M3() { Node? node = null; try { Mout(out node); } finally { node ??= node; } node.ToString(); } static void M4() { Node? node = null; try { Mout(out node); } finally { try { } finally { if (node is null) {} else {} } } node.ToString(); } static void M5() { Node? node = null; try { Mout(out node); } finally { try { if (node is null) {} else {} } finally { } } node.ToString(); } static void M6() { Node? node = null; try { Mout(out node); } finally { (node, _) = (null, node); } node.ToString(); // 2 } static void MN1() { Node? node = null; Mout(out node); if (node == null) {} else {} node.ToString(); // 3 } static void MN2() { Node? node = null; try { Mout(out node); } finally { if (node == null) {} else {} } node.ToString(); } static void Mout(out Node node) => node = null!; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,9): warning CS8602: Dereference of a possibly null reference. // node.Next.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "node.Next").WithLocation(15, 9), // (97,9): warning CS8602: Dereference of a possibly null reference. // node.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "node").WithLocation(97, 9), // (104,9): warning CS8602: Dereference of a possibly null reference. // node.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "node").WithLocation(104, 9)); } [Fact, WorkItem(32934, "https://github.com/dotnet/roslyn/issues/32934")] public void NoCycleInStructLayout() { var source = @" #nullable enable public struct Goo<T> { public static Goo<T> Bar; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(32446, "https://github.com/dotnet/roslyn/issues/32446")] public void RefValueOfNullableType() { var source = @" using System; public class C { public void M(TypedReference r) { _ = __refvalue(r, string?).Length; // 1 _ = __refvalue(r, string).Length; } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = __refvalue(r, string?).Length; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "__refvalue(r, string?)").WithLocation(7, 13) ); } [Fact, WorkItem(25375, "https://github.com/dotnet/roslyn/issues/25375")] public void ParamsNullable_SingleNullParam() { var source = @" class C { static void F(object x, params object?[] y) { } static void G(object x, params object[]? y) { } static void Main() { // Both calls here are invoked in normal form, not expanded F(string.Empty, null); // 1 G(string.Empty, null); // These are called with expanded form F(string.Empty, null, string.Empty); G(string.Empty, null, string.Empty); // 2 // Explicitly called with array F(string.Empty, new object?[] { null }); G(string.Empty, new object[] { null }); // 3 } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (16,25): warning CS8625: Cannot convert null literal to non-nullable reference type. // F(string.Empty, null); // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 25), // (22,25): warning CS8625: Cannot convert null literal to non-nullable reference type. // G(string.Empty, null, string.Empty); // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(22, 25), // (27,40): warning CS8625: Cannot convert null literal to non-nullable reference type. // G(string.Empty, new object[] { null }); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(27, 40) ); } [Fact, WorkItem(32172, "https://github.com/dotnet/roslyn/issues/32172")] public void NullableIgnored_InDisabledCode() { var source = @" #if UNDEF #nullable disable #endif #define DEF #if DEF #nullable disable // 1 #endif #if UNDEF #nullable enable #endif public class C { public void F(object o) { F(null); // no warning. '#nullable enable' in a disabled code region } } "; CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (9,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // #nullable disable // 1 Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(9, 2) ); CreateCompilation(new[] { source }, options: WithNullableEnable()) .VerifyDiagnostics(); } [Fact, WorkItem(32172, "https://github.com/dotnet/roslyn/issues/32172")] public void DirectiveIgnored_InDisabledCode() { var source = @" #nullable disable warnings #if UNDEF #nullable restore warnings #endif public class C { public void F(object o) { F(null); // no warning. '#nullable restore warnings' in a disabled code region } } "; CreateCompilation(new[] { source }, parseOptions: TestOptions.Regular7_3) .VerifyDiagnostics( // (2,2): error CS8652: The feature 'nullable reference types' is not available in C# 7.3. Please use language version 8.0 or greater. // #nullable disable warnings Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "nullable").WithArguments("nullable reference types", "8.0").WithLocation(2, 2)); CreateCompilation(new[] { source }, options: WithNullableEnable()) .VerifyDiagnostics(); } [WorkItem(30987, "https://github.com/dotnet/roslyn/issues/30987")] [Fact] public void TypeInference_LowerBounds_TopLevelNullability_03() { var source = @"using System; class C { static T F<T>(T x, T y) => x; static void G1(A x, B? y) { F(x, x)/*T:A!*/; F(x, y)/*T:A?*/; F(y, x)/*T:A?*/; F(y, y)/*T:B?*/; } static void G2(A x, B? y) { _ = new [] { x, x }[0]/*T:A!*/; _ = new [] { x, y }[0]/*T:A?*/; _ = new [] { y, x }[0]/*T:A?*/; _ = new [] { y, y }[0]/*T:B?*/; } static T M<T>(Func<T> func) => func(); static void G3(bool b, A x, B? y) { M(() => { if (b) return x; return x; })/*T:A!*/; M(() => { if (b) return x; return y; })/*T:A?*/; M(() => { if (b) return y; return x; })/*T:A?*/; M(() => { if (b) return y; return y; })/*T:B?*/; } static void G4(bool b, A x, B? y) { _ = (b ? x : x)/*T:A!*/; _ = (b ? x : y)/*T:A?*/; _ = (b ? y : x)/*T:A?*/; _ = (b ? y : y)/*T:B?*/; } } class A { } class B : A { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(30987, "https://github.com/dotnet/roslyn/issues/30987")] [Fact] public void TypeInference_LowerBounds_TopLevelNullability_04() { var source = @"class D { static T F<T>(T x, T y, T z) => x; static void G1(A x, B? y, C z) { F(x, y, z)/*T:A?*/; F(y, z, x)/*T:A?*/; F(z, x, y)/*T:A?*/; F(x, z, y)/*T:A?*/; F(z, y, x)/*T:A?*/; F(y, x, z)/*T:A?*/; } } class A { } class B : A { } class C : A { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); comp.VerifyTypes(); } [WorkItem(30987, "https://github.com/dotnet/roslyn/issues/30987")] [Fact] public void TypeInference_LowerBounds_TopLevelNullability_05() { var source = @"class D { #nullable disable static T F<T>(T x, T y, T z) => x; static void G1(A x, B? y, C z) #nullable enable { F(x, y, z)/*T:A?*/; F(y, z, x)/*T:A?*/; F(z, x, y)/*T:A?*/; F(x, z, y)/*T:A?*/; F(z, y, x)/*T:A?*/; F(y, x, z)/*T:A?*/; } } class A { } class B : A { } class C : A { } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (5,26): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' context. // static void G1(A x, B? y, C z) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 26)); comp.VerifyTypes(); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_01() { var source = @"using System; class C { static T F<T>(Func<T> f) => throw null!; static void G(object? o) { F(() => o).ToString(); // warning: maybe null if (o == null) return; F(() => o).ToString(); // no warning } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F(() => o).ToString(); // warning: maybe null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => o)").WithLocation(8, 9)); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_02() { var source = @"using System; class C { static bool M(object? o) => throw null!; static T F<T>(Func<T> f, bool ignored) => throw null!; static void G(object? o) { F(() => o, M(1)).ToString(); // warning: maybe null if (o == null) return; F(() => o, M(o = null)).ToString(); // no warning } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F(() => o, M(1)).ToString(); // warning: maybe null Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => o, M(1))").WithLocation(9, 9)); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_03() { var source = @"using System; class C { static bool M(object? o) => throw null!; static Func<T> F<T>(Func<T> f, bool ignored = false) => throw null!; static void G(object? o) { var fa1 = new[] { F(() => o), F(() => o, M(o = null)) }; fa1[0]().ToString(); // warning if (o == null) return; var fa2 = new[] { F(() => o), F(() => o, M(o = null)) }; fa2[0]().ToString(); if (o == null) return; var fa3 = new[] { F(() => o, M(o = null)), F(() => o) }; fa3[0]().ToString(); // warning } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // fa1[0]().ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "fa1[0]()").WithLocation(10, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // fa3[0]().ToString(); // warning Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "fa3[0]()").WithLocation(18, 9)); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_04() { var source = @"using System; class C { static T F<T>(Func<T> f) => throw null!; static void G(object? o) { F((Func<object>)(() => o)).ToString(); // 1 if (o == null) return; F((Func<object>)(() => o)).ToString(); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,32): warning CS8603: Possible null reference return. // F((Func<object>)(() => o)).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(8, 32)); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_05() { var source = @"using System; class C { static T F<T>(Func<T> f) => throw null!; static void G(Action a) => throw null!; static void M(object? o) { F(() => o).ToString(); // 1 if (o == null) return; F(() => o).ToString(); G(() => o = null); // does not affect state in caller F(() => o).ToString(); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F(() => o).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F(() => o)").WithLocation(9, 9)); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_06() { var source = @"using System; class C { static T F<T>(object? o, params Func<T>[] a) => throw null!; static void M(string? x) { F(x = """", () => x = null, () => x.ToString()); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(29617, "https://github.com/dotnet/roslyn/issues/29617")] public void CaptureVariablesWhereLambdaAppears_07() { var source = @"using System; class C { static T F<T>([System.Diagnostics.CodeAnalysis.NotNull] object? o, params Func<T>[] a) => throw null!; static void M(string? x) { F(x = """", () => x = null, () => x.ToString()); } } "; var comp = CreateCompilation(new[] { source, NotNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(34841, "https://github.com/dotnet/roslyn/issues/34841")] public void PartialClassWithConstraints_01() { var source1 = @"#nullable enable using System; partial class C<T> where T : IEquatable<T>, new() { }"; var source2 = @"using System; partial class C<T> where T : IEquatable<T>, new() { }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source2, source1 }); comp.VerifyDiagnostics(); validate(); void validate() { var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.Equal("System.IEquatable<T>!", t.ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } } [Fact] [WorkItem(34841, "https://github.com/dotnet/roslyn/issues/34841")] public void PartialClassWithConstraints_02() { var source1 = @"#nullable enable using System; partial class C<T> where T : class?, IEquatable<T?>, new() { }"; var source2 = @"using System; partial class C<T> where T : class, IEquatable<T>, new() { }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source2, source1 }); comp.VerifyDiagnostics(); validate(); void validate() { var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.True(t.ReferenceTypeConstraintIsNullable); Assert.Equal("System.IEquatable<T?>!", t.ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } } [Fact] [WorkItem(34841, "https://github.com/dotnet/roslyn/issues/34841")] public void PartialClassWithConstraints_03() { var source1 = @"#nullable enable using System; class C<T> where T : IEquatable<T> { }"; var source2 = @"using System; class C<T> where T : IEquatable<T> { }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics( // (2,7): error CS0101: The namespace '<global namespace>' already contains a definition for 'C' // class C<T> where T : IEquatable<T> Diagnostic(ErrorCode.ERR_DuplicateNameInNS, "C").WithArguments("C", "<global namespace>").WithLocation(2, 7) ); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("System.IEquatable<T>!", t.ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } [Fact] public void PartialClassWithConstraints_04() { var source1 = @" using System; partial class C<T> where T : IEquatable< #nullable enable string? #nullable disable > { }"; var source2 = @"using System; partial class C<T> where T : IEquatable<string #nullable enable >? #nullable disable { }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source2, source1 }); comp.VerifyDiagnostics(); validate(); void validate() { var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("System.IEquatable<System.String?>?", t.ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } } [Fact] public void PartialClassWithConstraints_05() { var source1 = @"#nullable enable partial class C<T> where T : class, new() { }"; var source2 = @" partial class C<T> where T : class, new() { }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source2, source1 }); comp.VerifyDiagnostics(); validate(); void validate() { var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.False(t.ReferenceTypeConstraintIsNullable); } } [Fact] public void PartialClassWithConstraints_06() { var source1 = @"#nullable enable partial class C<T> where T : class, new() { } partial class C<T> where T : class, new() { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.False(t.ReferenceTypeConstraintIsNullable); } [Fact] public void PartialClassWithConstraints_07() { var source1 = @"#nullable enable partial class C<T> where T : class?, new() { } partial class C<T> where T : class?, new() { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.True(t.ReferenceTypeConstraintIsNullable); } [Fact] public void PartialClassWithConstraints_08() { var source1 = @"#nullable disable partial class C<T> where T : class, new() { } partial class C<T> where T : class, new() { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics(); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.Null(t.ReferenceTypeConstraintIsNullable); } [Fact] public void PartialClassWithConstraints_09() { var source1 = @"#nullable enable partial class C<T> where T : class?, new() { } partial class C<T> where T : class, new() { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics( // (2,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : class?, new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(2, 15) ); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.True(t.ReferenceTypeConstraintIsNullable); } [Fact] public void PartialClassWithConstraints_10() { var source1 = @"#nullable enable partial class C<T> where T : class, new() { } partial class C<T> where T : class?, new() { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics( // (2,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : class, new() Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(2, 15) ); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.True(t.HasConstructorConstraint); Assert.True(t.HasReferenceTypeConstraint); Assert.False(t.ReferenceTypeConstraintIsNullable); } [Fact] public void PartialClassWithConstraints_11() { var source1 = @"#nullable enable using System; partial class C<T> where T : IEquatable<T>? { } partial class C<T> where T : IEquatable<T> { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics( // (3,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : IEquatable<T>? Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(3, 15) ); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("System.IEquatable<T>?", t.ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } [Fact] public void PartialClassWithConstraints_12() { var source1 = @"#nullable enable using System; partial class C<T> where T : IEquatable<T> { } partial class C<T> where T : IEquatable<T>? { }"; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics( // (3,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : IEquatable<T> Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(3, 15) ); var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("System.IEquatable<T>!", t.ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } [Fact] public void PartialClassWithConstraints_13() { var source1 = @"#nullable enable using System; partial class C<T> where T : class, IEquatable<T>?, IEquatable<string?> { } "; var source2 = @"using System; partial class C<T> where T : class, IEquatable<string>, IEquatable<T> { }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); validate(0, 1); comp = CreateCompilation(new[] { source2, source1 }); comp.VerifyDiagnostics(); validate(1, 0); void validate(int i, int j) { var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("System.IEquatable<T!>?", t.ConstraintTypesNoUseSiteDiagnostics[i].ToTestDisplayString(true)); Assert.Equal("System.IEquatable<System.String?>!", t.ConstraintTypesNoUseSiteDiagnostics[j].ToTestDisplayString(true)); } } [Fact] public void PartialClassWithConstraints_14() { var source0 = @" interface I1<T, S> { } "; var source1 = @" partial class C<T> where T : I1< #nullable enable string?, #nullable disable string> { } "; var source2 = @" partial class C<T> where T : I1<string, #nullable enable string? #nullable disable > { } "; var source3 = @" partial class C<T> where T : I1<string, string #nullable enable >? #nullable disable { } "; var comp1 = CreateCompilation(new[] { source0, source1 }); comp1.VerifyDiagnostics(); var c = comp1.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("I1<System.String?, System.String>", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); var comp2 = CreateCompilation(new[] { source0, source2 }); comp2.VerifyDiagnostics(); c = comp2.GlobalNamespace.GetTypeMember("C"); t = c.TypeParameters[0]; Assert.Equal("I1<System.String, System.String?>", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); var comp3 = CreateCompilation(new[] { source0, source3 }); comp3.VerifyDiagnostics(); c = comp3.GlobalNamespace.GetTypeMember("C"); t = c.TypeParameters[0]; Assert.Equal("I1<System.String, System.String>?", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); var comp = CreateCompilation(new[] { source0, source1, source2, source3 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source0, source1, source3, source2 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source0, source2, source1, source3 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source0, source2, source3, source1 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source0, source3, source1, source2 }); comp.VerifyDiagnostics(); validate(); comp = CreateCompilation(new[] { source0, source3, source2, source1 }); comp.VerifyDiagnostics(); validate(); void validate() { var c = comp.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("I1<System.String?, System.String?>?", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); } } [Fact] public void PartialClassWithConstraints_15() { var source = @" interface I1 { } interface I2 { } #nullable enable partial class C<T> where T : I1?, #nullable disable I2 { } #nullable enable partial class C<T> where T : I1, I2? { } "; var comp1 = CreateCompilation(new[] { source }); comp1.VerifyDiagnostics( // (12,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : I1?, Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(12, 15) ); var c = comp1.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("I1?", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); Assert.Equal("I2?", t.ConstraintTypesNoUseSiteDiagnostics[1].ToTestDisplayString(true)); } [Fact] public void PartialClassWithConstraints_16() { var source = @" interface I1 { } interface I2 { } #nullable enable partial class C<T> where T : I1, #nullable disable I2 { } #nullable enable partial class C<T> where T : I1?, I2 { } "; var comp1 = CreateCompilation(new[] { source }); comp1.VerifyDiagnostics( // (12,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : I1, Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(12, 15) ); var c = comp1.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("I1!", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); Assert.Equal("I2!", t.ConstraintTypesNoUseSiteDiagnostics[1].ToTestDisplayString(true)); } [Fact] public void PartialClassWithConstraints_17() { var source = @" interface I1 { } interface I2 { } #nullable disable partial class C<T> where T : I1, #nullable enable I2? { } partial class C<T> where T : I1?, I2 { } "; var comp1 = CreateCompilation(new[] { source }); comp1.VerifyDiagnostics( // (12,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : I1, Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(12, 15) ); var c = comp1.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("I1?", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); Assert.Equal("I2?", t.ConstraintTypesNoUseSiteDiagnostics[1].ToTestDisplayString(true)); } [Fact] public void PartialClassWithConstraints_18() { var source = @" interface I1 { } interface I2 { } #nullable disable partial class C<T> where T : I1, #nullable enable I2 { } partial class C<T> where T : I1, I2? { } "; var comp1 = CreateCompilation(new[] { source }); comp1.VerifyDiagnostics( // (12,15): error CS0265: Partial declarations of 'C<T>' have inconsistent constraints for type parameter 'T' // partial class C<T> where T : I1, Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "C").WithArguments("C<T>", "T").WithLocation(12, 15) ); var c = comp1.GlobalNamespace.GetTypeMember("C"); TypeParameterSymbol t = c.TypeParameters[0]; Assert.Equal("I1!", t.ConstraintTypesNoUseSiteDiagnostics[0].ToTestDisplayString(true)); Assert.Equal("I2!", t.ConstraintTypesNoUseSiteDiagnostics[1].ToTestDisplayString(true)); } [Fact] public void PartialInterfacesWithConstraints_01() { var source = @" #nullable enable interface I1 { } partial interface I1<in T> where T : I1 {} partial interface I1<in T> where T : I1? {} partial interface I2<in T> where T : I1? {} partial interface I2<in T> where T : I1 {} partial interface I3<out T> where T : I1 {} partial interface I3<out T> where T : I1? {} partial interface I4<out T> where T : I1? {} partial interface I4<out T> where T : I1 {} "; var comp1 = CreateCompilation(new[] { source }); comp1.VerifyDiagnostics( // (8,19): error CS0265: Partial declarations of 'I1<T>' have inconsistent constraints for type parameter 'T' // partial interface I1<in T> where T : I1 Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I1").WithArguments("I1<T>", "T").WithLocation(8, 19), // (14,19): error CS0265: Partial declarations of 'I2<T>' have inconsistent constraints for type parameter 'T' // partial interface I2<in T> where T : I1? Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I2").WithArguments("I2<T>", "T").WithLocation(14, 19), // (20,19): error CS0265: Partial declarations of 'I3<T>' have inconsistent constraints for type parameter 'T' // partial interface I3<out T> where T : I1 Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I3").WithArguments("I3<T>", "T").WithLocation(20, 19), // (26,19): error CS0265: Partial declarations of 'I4<T>' have inconsistent constraints for type parameter 'T' // partial interface I4<out T> where T : I1? Diagnostic(ErrorCode.ERR_PartialWrongConstraints, "I4").WithArguments("I4<T>", "T").WithLocation(26, 19) ); } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_01() { var source0 = @" #nullable enable Base<string> base1 = new C(); Base<string?> base2 = new C(); // 1 class Base<T> { } "; var source1 = @" #nullable enable partial class C : Base<string> { } "; var source2 = @" #nullable disable partial class C : Base<string> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,23): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string?>'. // Base<string?> base2 = new C(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string?>").WithLocation(5, 23) ); var cClass = comp.GetMember<NamedTypeSymbol>("C"); var @base = cClass.BaseTypeNoUseSiteDiagnostics; // note: the symbol model doesn't include a nullable annotation for base types or implemented interfaces. Assert.Equal("Base<System.String!>", @base.ToTestDisplayString(includeNonNullable: true)); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_02() { var source0 = @" #nullable enable Base<string> base1 = new C(); // 1 Base<string?> base2 = new C(); class Base<T> { } "; var source1 = @" #nullable enable partial class C : Base<string?> { } "; var source2 = @" #nullable disable partial class C : Base<string> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (4,22): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string>'. // Base<string> base1 = new C(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string>").WithLocation(4, 22) ); var cClass = comp.GetMember<NamedTypeSymbol>("C"); var @base = cClass.BaseTypeNoUseSiteDiagnostics; // note: the symbol model doesn't include a nullable annotation for base types or implemented interfaces. Assert.Equal("Base<System.String?>", @base.ToTestDisplayString(includeNonNullable: true)); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_03() { var source0 = @" #nullable enable Base<string> base1 = new C(); Base<string?> base2 = new C(); // 1 class Base<T> { } "; var source1 = @" #nullable enable partial class C : Base<string> { } "; var source2 = @" #nullable enable partial class C : Base< #nullable disable string #nullable enable > { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,23): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string?>'. // Base<string?> base2 = new C(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string?>").WithLocation(5, 23) ); var cClass = comp.GetMember<NamedTypeSymbol>("C"); var @base = cClass.BaseTypeNoUseSiteDiagnostics; Assert.Equal("Base<System.String!>", @base.ToTestDisplayString(includeNonNullable: true)); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_04() { var source0 = @" #nullable enable Base<string> base1 = new C(); // 1 Base<string?> base2 = new C(); class Base<T> { } "; var source1 = @" #nullable enable partial class C : Base<string?> { } "; var source2 = @" #nullable enable partial class C : Base< #nullable disable string #nullable enable > { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (4,22): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string>'. // Base<string> base1 = new C(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string>").WithLocation(4, 22) ); var cClass = comp.GetMember<NamedTypeSymbol>("C"); var @base = cClass.BaseTypeNoUseSiteDiagnostics; Assert.Equal("Base<System.String?>", @base.ToTestDisplayString(includeNonNullable: true)); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_05() { var source0 = @" #nullable enable Base<string> base1 = new C(); Base<string?> base2 = new C(); // 1 class Base<T> { } "; var source1 = @" #nullable enable partial class C : Base<string> { } "; var source2 = @" #nullable enable partial class C : Base< #nullable disable string > { } // Note: the top-level nullability is oblivious here. "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,23): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string?>'. // Base<string?> base2 = new C(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string?>").WithLocation(5, 23) ); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_06() { var source0 = @" #nullable enable Base<string, object?> base1 = new C(); Base<string, object> base2 = new C(); // 1 Base<string?, object?> base3 = new C(); // 2 class Base<T, U> { } "; var source1 = @" #nullable enable partial class C : Base<string, object?> { } "; var source2 = @" #nullable disable partial class C : Base<string, object> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,30): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string, object>'. // Base<string, object> base2 = new C(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string, object>").WithLocation(5, 30), // (6,32): warning CS8619: Nullability of reference types in value of type 'C' doesn't match target type 'Base<string?, object?>'. // Base<string?, object?> base3 = new C(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C()").WithArguments("C", "Base<string?, object?>").WithLocation(6, 32) ); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_07() { var source0 = @" #nullable enable Base<string, object?> base1 = new C(); // 1 Base<string, object> base2 = new C(); // 2 Base<string?, object?> base3 = new C(); // 3 class Base<T, U> { } "; var source1 = @" #nullable enable partial class C : Base<string, object?> { } // 4 "; var source2 = @" #nullable disable partial class C : Base<string, object> { } "; var source3 = @" #nullable enable partial class C : Base<string?, object> { } "; var comp = CreateCompilation(new[] { source0, source1, source2, source3 }); verify(); comp = CreateCompilation(new[] { source0, source3, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (3,15): error CS0263: Partial declarations of 'C' must not specify different base classes // partial class C : Base<string, object?> { } // 4 Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C").WithArguments("C").WithLocation(3, 15), // (4,31): error CS0029: Cannot implicitly convert type 'C' to 'Base<string, object?>' // Base<string, object?> base1 = new C(); // 1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C()").WithArguments("C", "Base<string, object?>").WithLocation(4, 31), // (5,30): error CS0029: Cannot implicitly convert type 'C' to 'Base<string, object>' // Base<string, object> base2 = new C(); // 2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C()").WithArguments("C", "Base<string, object>").WithLocation(5, 30), // (6,32): error CS0029: Cannot implicitly convert type 'C' to 'Base<string?, object?>' // Base<string?, object?> base3 = new C(); // 3 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C()").WithArguments("C", "Base<string?, object?>").WithLocation(6, 32) ); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_08() { var source0 = @" #nullable enable Base<S, object?> base1 = new C1(); Base<S, object> base2 = new C1(); // 1 Base<object?, S> base3 = new C2(); // 2 Base<object, S> base4 = new C2(); class Base<T, U> { } struct S { } "; var source1 = @" #nullable enable partial class C1 : Base<S, object?> { } partial class C2 : Base<object, S> { } "; var source2 = @" #nullable disable partial class C1 : Base<S, object> { } partial class C2 : Base<object, S> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,25): warning CS8619: Nullability of reference types in value of type 'C1' doesn't match target type 'Base<S, object>'. // Base<S, object> base2 = new C1(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C1()").WithArguments("C1", "Base<S, object>").WithLocation(5, 25), // (7,26): warning CS8619: Nullability of reference types in value of type 'C2' doesn't match target type 'Base<object?, S>'. // Base<object?, S> base3 = new C2(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C2()").WithArguments("C2", "Base<object?, S>").WithLocation(7, 26) ); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_09() { var source0 = @" #nullable enable Base<S?, object?> base1 = new C1(); Base<S?, object> base2 = new C1(); // 1 Base<object?, S?> base3 = new C2(); // 2 Base<object, S?> base4 = new C2(); class Base<T, U> { } struct S { } "; var source1 = @" #nullable enable partial class C1 : Base<S?, object?> { } partial class C2 : Base<object, S?> { } "; var source2 = @" #nullable disable partial class C1 : Base<S?, object> { } partial class C2 : Base<object, S?> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,26): warning CS8619: Nullability of reference types in value of type 'C1' doesn't match target type 'Base<S?, object>'. // Base<S?, object> base2 = new C1(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C1()").WithArguments("C1", "Base<S?, object>").WithLocation(5, 26), // (7,27): warning CS8619: Nullability of reference types in value of type 'C2' doesn't match target type 'Base<object?, S?>'. // Base<object?, S?> base3 = new C2(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C2()").WithArguments("C2", "Base<object?, S?>").WithLocation(7, 27) ); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_10() { var source0 = @" #nullable enable Base<S, object?> base1 = new C1(); Base<S, object> base2 = new C1(); // 1 Base<object?, S> base3 = new C2(); // 2 Base<object, S> base4 = new C2(); class Base<T, U> { } struct S { } "; var source1 = @" #nullable enable partial class C1 : Base<S, object?> { } partial class C2 : Base<object, S> { } "; var source2 = @" #nullable enable partial class C1 : Base< S, #nullable disable object> { } #nullable enable partial class C2 : Base< object, #nullable disable S> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,25): warning CS8619: Nullability of reference types in value of type 'C1' doesn't match target type 'Base<S, object>'. // Base<S, object> base2 = new C1(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C1()").WithArguments("C1", "Base<S, object>").WithLocation(5, 25), // (7,26): warning CS8619: Nullability of reference types in value of type 'C2' doesn't match target type 'Base<object?, S>'. // Base<object?, S> base3 = new C2(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C2()").WithArguments("C2", "Base<object?, S>").WithLocation(7, 26) ); } } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_11() { var source0 = @" #nullable enable Base<S?, object?> base1 = new C1(); Base<S?, object> base2 = new C1(); // 1 Base<object?, S?> base3 = new C2(); // 2 Base<object, S?> base4 = new C2(); class Base<T, U> { } struct S { } "; var source1 = @" #nullable enable partial class C1 : Base<S?, object?> { } partial class C2 : Base<object, S?> { } "; var source2 = @" #nullable enable partial class C1 : Base< S?, #nullable disable object> { } #nullable enable partial class C2 : Base< object, #nullable disable S?> { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); comp.VerifyDiagnostics( // (5,26): warning CS8619: Nullability of reference types in value of type 'C1' doesn't match target type 'Base<S?, object>'. // Base<S?, object> base2 = new C1(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C1()").WithArguments("C1", "Base<S?, object>").WithLocation(5, 26), // (7,27): warning CS8619: Nullability of reference types in value of type 'C2' doesn't match target type 'Base<object?, S?>'. // Base<object?, S?> base3 = new C2(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C2()").WithArguments("C2", "Base<object?, S?>").WithLocation(7, 27) ); } [Fact, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] public void PartialBaseTypeDifference_12() { var source0 = @" #nullable enable Base<S, object?> base1 = new C1<S>(); Base<S, object> base2 = new C1<S>(); // 1 Base<object?, S> base3 = new C2<S>(); // 2 Base<object, S> base4 = new C2<S>(); class Base<T, U> { } struct S { } "; var source1 = @" #nullable enable partial class C1<TStruct> : Base<TStruct, object?> where TStruct : struct { } partial class C2<TStruct> : Base<object, TStruct> where TStruct : struct { } "; var source2 = @" #nullable enable partial class C1<TStruct> : Base< TStruct, #nullable disable object> where TStruct : struct { } #nullable enable partial class C2<TStruct> : Base< object, #nullable disable TStruct> where TStruct : struct { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); verify(); comp = CreateCompilation(new[] { source0, source2, source1 }); verify(); void verify() { comp.VerifyDiagnostics( // (5,25): warning CS8619: Nullability of reference types in value of type 'C1<S>' doesn't match target type 'Base<S, object>'. // Base<S, object> base2 = new C1<S>(); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C1<S>()").WithArguments("C1<S>", "Base<S, object>").WithLocation(5, 25), // (7,26): warning CS8619: Nullability of reference types in value of type 'C2<S>' doesn't match target type 'Base<object?, S>'. // Base<object?, S> base3 = new C2<S>(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "new C2<S>()").WithArguments("C2<S>", "Base<object?, S>").WithLocation(7, 26) ); } } [Theory, WorkItem(45960, "https://github.com/dotnet/roslyn/issues/45960")] [InlineData("")] [InlineData("where T : class")] public void PartialBaseTypeDifference_13(string constraints) { var source0 = @" #nullable enable Base<C, object?> base1 = new C1<C>(); // 1 Base<C, object> base2 = new C1<C>(); // 2 Base<object?, C> base3 = new C2<C>(); // 3 Base<object, C> base4 = new C2<C>(); // 4 class Base<T, U> { } class C { } "; var source1 = @" #nullable enable partial class C1<T> : Base<T, object?> " + constraints + @" { } // 5 partial class C2<T> : Base<object, T> " + constraints + @" { } // 6 "; var source2 = @" #nullable enable partial class C1<T> : Base< T, #nullable disable object> " + constraints + @" { } #nullable enable partial class C2<T> : Base< object, #nullable disable T> " + constraints + @" { } "; var comp = CreateCompilation(new[] { source0, source1, source2 }); comp.VerifyDiagnostics( // (3,15): error CS0263: Partial declarations of 'C1<T>' must not specify different base classes // partial class C1<T> : Base<T, object?> { } // 5 Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C1").WithArguments("C1<T>").WithLocation(3, 15), // (4,15): error CS0263: Partial declarations of 'C2<T>' must not specify different base classes // partial class C2<T> : Base<object, T> { } // 6 Diagnostic(ErrorCode.ERR_PartialMultipleBases, "C2").WithArguments("C2<T>").WithLocation(4, 15), // (4,26): error CS0029: Cannot implicitly convert type 'C1<C>' to 'Base<C, object?>' // Base<C, object?> base1 = new C1<C>(); // 1 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C1<C>()").WithArguments("C1<C>", "Base<C, object?>").WithLocation(4, 26), // (5,25): error CS0029: Cannot implicitly convert type 'C1<C>' to 'Base<C, object>' // Base<C, object> base2 = new C1<C>(); // 2 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C1<C>()").WithArguments("C1<C>", "Base<C, object>").WithLocation(5, 25), // (7,26): error CS0029: Cannot implicitly convert type 'C2<C>' to 'Base<object?, C>' // Base<object?, C> base3 = new C2<C>(); // 3 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C2<C>()").WithArguments("C2<C>", "Base<object?, C>").WithLocation(7, 26), // (8,25): error CS0029: Cannot implicitly convert type 'C2<C>' to 'Base<object, C>' // Base<object, C> base4 = new C2<C>(); // 4 Diagnostic(ErrorCode.ERR_NoImplicitConv, "new C2<C>()").WithArguments("C2<C>", "Base<object, C>").WithLocation(8, 25) ); } [Fact] public void PartialMethodsWithConstraints_01() { var source1 = @"#nullable enable using System; partial class C { static partial void F<T>() where T : IEquatable<T>; }"; var source2 = @"using System; partial class C { static partial void F<T>() where T : IEquatable<T> { } }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); var f = comp.GlobalNamespace.GetMember<MethodSymbol>("C.F"); Assert.Equal("System.IEquatable<T>!", f.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); Assert.Equal("System.IEquatable<T>", f.PartialImplementationPart.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } [Fact] public void PartialMethodsWithConstraints_02() { var source1 = @"#nullable enable using System; partial class C { static partial void F<T>() where T : class?, IEquatable<T?>; }"; var source2 = @"using System; partial class C { static partial void F<T>() where T : class, IEquatable<T> { } }"; var comp = CreateCompilation(new[] { source1, source2 }); comp.VerifyDiagnostics(); var f = comp.GlobalNamespace.GetMember<MethodSymbol>("C.F"); Assert.True(f.TypeParameters[0].ReferenceTypeConstraintIsNullable); Assert.Equal("System.IEquatable<T?>!", f.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); Assert.Null(f.PartialImplementationPart.TypeParameters[0].ReferenceTypeConstraintIsNullable); Assert.Equal("System.IEquatable<T>", f.PartialImplementationPart.TypeParameters[0].ConstraintTypesNoUseSiteDiagnostics.Single().ToTestDisplayString(true)); } [Fact] [WorkItem(35227, "https://github.com/dotnet/roslyn/issues/35227")] public void PartialMethodsWithConstraints_03() { var source1 = @" partial class C { #nullable enable static partial void F<T>(I<T> x) where T : class; #nullable disable static partial void F<T>(I<T> x) where T : class #nullable enable { Test2(x); } void Test1<U>() where U : class? { F<U>(null); } static void Test2<S>(I<S?> x) where S : class { } } interface I<in S> { } "; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics( // (16,9): warning CS8634: The type 'U' cannot be used as type parameter 'T' in the generic type or method 'C.F<T>(I<T>)'. Nullability of type argument 'U' doesn't match 'class' constraint. // F<U>(null); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "F<U>").WithArguments("C.F<T>(I<T>)", "T", "U").WithLocation(16, 9), // (16,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // F<U>(null); Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(16, 14) ); } [Fact] [WorkItem(35227, "https://github.com/dotnet/roslyn/issues/35227")] public void PartialMethodsWithConstraints_04() { var source1 = @" partial class C { #nullable disable static partial void F<T>(I<T> x) where T : class; #nullable enable static partial void F<T>(I<T> x) where T : class { Test2(x); } void Test1<U>() where U : class? { F<U>(null); } static void Test2<S>(I<S?> x) where S : class { } } interface I<in S> { } "; var comp = CreateCompilation(new[] { source1 }); comp.VerifyDiagnostics( // (10,15): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 'x' of type 'I<T?>' in 'void C.Test2<T>(I<T?> x)' due to differences in the nullability of reference types. // Test2(x); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "x", "void C.Test2<T>(I<T?> x)").WithLocation(10, 15) ); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceMethod_DifferingNullabilityAnnotations1() { var text = @" #nullable enable public interface Interface<T> where T : class { void Method(string i); void Method(T? i); } public class Class : Interface<string> { void Interface<string>.Method(string i) { } //this explicitly implements both methods in Interface<string> public void Method(string i) { } //this is here to avoid CS0535 - not implementing interface method } "; CreateCompilation(text).VerifyDiagnostics( // (11,28): warning CS0473: Explicit interface implementation 'Class.Interface<string>.Method(string)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void Interface<string>.Method(string i) { } //this explicitly implements both methods in Interface<string> Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Class.Interface<string>.Method(string)").WithLocation(11, 28), // (12,17): warning CS8767: Nullability of reference types in type of parameter 'i' of 'void Class.Method(string i)' doesn't match implicitly implemented member 'void Interface<string>.Method(string? i)' (possibly because of nullability attributes). // public void Method(string i) { } //this is here to avoid CS0535 - not implementing interface method Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "Method").WithArguments("i", "void Class.Method(string i)", "void Interface<string>.Method(string? i)").WithLocation(12, 17)); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceMethod_DifferingNullabilityAnnotations2() { var text = @" #nullable enable public interface Interface<T> where T : class { void Method(string i); void Method(T? i); } public class Class : Interface<string> { void Interface<string>.Method(string? i) { } //this explicitly implements both methods in Interface<string> public void Method(string i) { } //this is here to avoid CS0535 - not implementing interface method } "; CreateCompilation(text).VerifyDiagnostics( // (11,28): warning CS0473: Explicit interface implementation 'Class.Interface<string>.Method(string?)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void Interface<string>.Method(string? i) { } //this explicitly implements both methods in Interface<string> Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Class.Interface<string>.Method(string?)").WithLocation(11, 28), // (12,17): warning CS8767: Nullability of reference types in type of parameter 'i' of 'void Class.Method(string i)' doesn't match implicitly implemented member 'void Interface<string>.Method(string? i)' (possibly because of nullability attributes). // public void Method(string i) { } //this is here to avoid CS0535 - not implementing interface method Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "Method").WithArguments("i", "void Class.Method(string i)", "void Interface<string>.Method(string? i)").WithLocation(12, 17)); } [Fact] public void TestExplicitImplementationAmbiguousInterfaceMethod_DifferingNullabilityAnnotations3() { var text = @" #nullable enable public interface Interface<T> where T : class { void Method(string? i); void Method(T i); } public class Class : Interface<string> { void Interface<string>.Method(string i) { } //this explicitly implements both methods in Interface<string> public void Method(string? i) { } //this is here to avoid CS0535 - not implementing interface method } "; CreateCompilation(text).VerifyDiagnostics( // (11,28): warning CS0473: Explicit interface implementation 'Class.Interface<string>.Method(string)' matches more than one interface member. Which interface member is actually chosen is implementation-dependent. Consider using a non-explicit implementation instead. // void Interface<string>.Method(string i) { } //this explicitly implements both methods in Interface<string> Diagnostic(ErrorCode.WRN_ExplicitImplCollision, "Method").WithArguments("Class.Interface<string>.Method(string)").WithLocation(11, 28), // (11,28): warning CS8769: Nullability of reference types in type of parameter 'i' doesn't match implemented member 'void Interface<string>.Method(string? i)' (possibly because of nullability attributes). // void Interface<string>.Method(string i) { } //this explicitly implements both methods in Interface<string> Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "Method").WithArguments("i", "void Interface<string>.Method(string? i)").WithLocation(11, 28) ); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : class; } class C1 : I { public void Goo<T>(T? value) where T : class { } } class C2 : I { void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (13,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(13, 12), // (15,12): error CS0539: 'C2.Goo<T>(T?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I.Goo<T>(T? value) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Goo").WithArguments("C2.Goo<T>(T?)").WithLocation(15, 12), // (15,22): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I.Goo<T>(T? value) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "value").WithArguments("System.Nullable<T>", "T", "T").WithLocation(15, 22)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodTakingNonNullableClassParameter_WithMethodTakingNullableClassParameter() { var source = @" #nullable enable interface I { void Goo<T>(T value) where T : class; } class C1 : I { public void Goo<T>(T? value) where T : class { } } class C2 : I { void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (13,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T)").WithLocation(13, 12), // (15,12): error CS0539: 'C2.Goo<T>(T?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I.Goo<T>(T? value) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Goo").WithArguments("C2.Goo<T>(T?)").WithLocation(15, 12), // (15,22): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I.Goo<T>(T? value) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "value").WithArguments("System.Nullable<T>", "T", "T").WithLocation(15, 22)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ImplementMethodTakingNullableClassParameter_WithMethodTakingNonNullableClassParameter() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : class; } class C1 : I { public void Goo<T>(T value) where T : class { } } class C2 : I { void I.Goo<T>(T value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (10,17): warning CS8767: Nullability of reference types in type of parameter 'value' of 'void C1.Goo<T>(T value)' doesn't match implicitly implemented member 'void I.Goo<T>(T? value)' (possibly because of nullability attributes). // public void Goo<T>(T value) where T : class { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnImplicitImplementation, "Goo").WithArguments("value", "void C1.Goo<T>(T value)", "void I.Goo<T>(T? value)").WithLocation(10, 17), // (15,12): warning CS8769: Nullability of reference types in type of parameter 'value' doesn't match implemented member 'void I.Goo<T>(T? value)' (possibly because of nullability attributes). // void I.Goo<T>(T value) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "Goo").WithArguments("value", "void I.Goo<T>(T? value)").WithLocation(15, 12)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ExplicitImplementationOverloadAcceptingNullableT() { var source = @" interface I { void Goo<T>(T value); void Goo<T>(T? value) where T : struct; } class C1 : I { public void Goo<T>(T value) { } public void Goo<T>(T? value) where T : struct { } } class C2 : I { void I.Goo<T>(T value) { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ExplicitImplementationOverloadAcceptingNullableT_OppositeDeclarationOrder() { var source = @" interface I { void Goo<T>(T? value) where T : struct; void Goo<T>(T value); } class C1 : I { public void Goo<T>(T value) { } public void Goo<T>(T? value) where T : struct { } } class C2 : I { void I.Goo<T>(T value) { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ExplicitImplementationOverloadAcceptingNullableT_WithClassConstraint() { var source = @" #nullable enable interface I { void Goo<T>(T value) where T : class; void Goo<T>(T? value) where T : struct; } class C1 : I { public void Goo<T>(T value) where T : class { } public void Goo<T>(T? value) where T : struct { } } class C2 : I { void I.Goo<T>(T value) { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ExplicitImplementationOverloadAcceptingNullableT_ReturnTypesDoNotMatchNullabilityModifiers() { var source = @" #nullable enable interface I<U> where U : class { U Goo<T>(T value); U Goo<T>(T? value) where T : struct; } class C1<U> : I<U> where U : class { public U? Goo<T>(T value) => default; public U? Goo<T>(T? value) where T : struct => default; } class C2<U> : I<U> where U : class { U? I<U>.Goo<T>(T value) => default; U? I<U>.Goo<T>(T? value) => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (11,15): warning CS8766: Nullability of reference types in return type of 'U? C1<U>.Goo<T>(T value)' doesn't match implicitly implemented member 'U I<U>.Goo<T>(T value)' (possibly because of nullability attributes). // public U? Goo<T>(T value) => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "Goo").WithArguments("U? C1<U>.Goo<T>(T value)", "U I<U>.Goo<T>(T value)").WithLocation(11, 15), // (12,15): warning CS8766: Nullability of reference types in return type of 'U? C1<U>.Goo<T>(T? value)' doesn't match implicitly implemented member 'U I<U>.Goo<T>(T? value)' (possibly because of nullability attributes). // public U? Goo<T>(T? value) where T : struct => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "Goo").WithArguments("U? C1<U>.Goo<T>(T? value)", "U I<U>.Goo<T>(T? value)").WithLocation(12, 15), // (17,13): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'U I<U>.Goo<T>(T value)' (possibly because of nullability attributes). // U? I<U>.Goo<T>(T value) => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "Goo").WithArguments("U I<U>.Goo<T>(T value)").WithLocation(17, 13), // (18,13): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'U I<U>.Goo<T>(T? value)' (possibly because of nullability attributes). // U? I<U>.Goo<T>(T? value) => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "Goo").WithArguments("U I<U>.Goo<T>(T? value)").WithLocation(18, 13)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void ExplicitImplementationOverloadAcceptingNullableT_ReturnTypesDoNotMatchNullabilityModifiers_OppositeDeclarationOrder() { var source = @" #nullable enable interface I<U> where U : class { U Goo<T>(T? value) where T : struct; U Goo<T>(T value); } class C1<U> : I<U> where U : class { public U? Goo<T>(T value) => default; public U? Goo<T>(T? value) where T : struct => default; } class C2<U> : I<U> where U : class { U? I<U>.Goo<T>(T value) => default; U? I<U>.Goo<T>(T? value) => default; } "; //As a result of https://github.com/dotnet/roslyn/issues/34583 these don't test anything useful at the moment var comp = CreateCompilation(source).VerifyDiagnostics( // (11,15): warning CS8766: Nullability of reference types in return type of 'U? C1<U>.Goo<T>(T value)' doesn't match implicitly implemented member 'U I<U>.Goo<T>(T value)' (possibly because of nullability attributes). // public U? Goo<T>(T value) => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "Goo").WithArguments("U? C1<U>.Goo<T>(T value)", "U I<U>.Goo<T>(T value)").WithLocation(11, 15), // (12,15): warning CS8766: Nullability of reference types in return type of 'U? C1<U>.Goo<T>(T? value)' doesn't match implicitly implemented member 'U I<U>.Goo<T>(T? value)' (possibly because of nullability attributes). // public U? Goo<T>(T? value) where T : struct => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "Goo").WithArguments("U? C1<U>.Goo<T>(T? value)", "U I<U>.Goo<T>(T? value)").WithLocation(12, 15), // (17,13): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'U I<U>.Goo<T>(T value)' (possibly because of nullability attributes). // U? I<U>.Goo<T>(T value) => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "Goo").WithArguments("U I<U>.Goo<T>(T value)").WithLocation(17, 13), // (18,13): warning CS8768: Nullability of reference types in return type doesn't match implemented member 'U I<U>.Goo<T>(T? value)' (possibly because of nullability attributes). // U? I<U>.Goo<T>(T? value) => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnExplicitImplementation, "Goo").WithArguments("U I<U>.Goo<T>(T? value)").WithLocation(18, 13)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : class; void Goo<T>(T? value) where T : struct; } class C2 : I { void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(9, 12)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_WithImplicitOverrideOfStructMember() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : class; void Goo<T>(T? value) where T : struct; } class C2 : I { public void Goo<T>(T? value) where T : struct { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(9, 12)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_WithImplicitOverrideOfClassMember() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : class; void Goo<T>(T? value) where T : struct; } class C2 : I { public void Goo<T>(T? value) where T : class { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_WithImplicitOverrideOfStructMember_OppositeDeclarationOrder() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : struct; void Goo<T>(T? value) where T : class; } class C2 : I { public void Goo<T>(T? value) where T : struct { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(9, 12)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_WithImplicitOverrideOfClassMember_OppositeDeclarationOrder() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : struct; void Goo<T>(T? value) where T : class; } class C2 : I { public void Goo<T>(T? value) where T : class { } void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_OppositeDeclarationOrder() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : struct; void Goo<T>(T? value) where T : class; } class C2 : I { void I.Goo<T>(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(9, 12)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_DifferingReturnType() { var source = @" #nullable enable interface I { string Goo<T>(T? value) where T : class; int Goo<T>(T? value) where T : struct; } class C2 : I { int I.Goo<T>(T? value) => 42; string I.Goo<T>(T? value) => ""42""; } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(9, 12), // (12,14): error CS0539: 'C2.Goo<T>(T?)' in explicit interface declaration is not found among members of the interface that can be implemented // string I.Goo<T>(T? value) => "42"; Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "Goo").WithArguments("C2.Goo<T>(T?)").WithLocation(12, 14), // (12,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // string I.Goo<T>(T? value) => "42"; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "value").WithArguments("System.Nullable<T>", "T", "T").WithLocation(12, 24)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void AmbiguousExplicitInterfaceImplementation_ReturnTypeDifferingInNullabilityAnotation() { var source = @" #nullable enable interface I { object Goo<T>(T? value) where T : class; object? Goo<T>(T? value) where T : struct; } class C2 : I { object I.Goo<T>(T? value) => 42; object? I.Goo<T>(T? value) => 42; } "; var comp = CreateCompilation(source).VerifyDiagnostics( // (9,7): error CS8646: 'I.Goo<T>(T?)' is explicitly implemented more than once. // class C2 : I Diagnostic(ErrorCode.ERR_DuplicateExplicitImpl, "C2").WithArguments("I.Goo<T>(T?)").WithLocation(9, 7), // (9,12): error CS0535: 'C2' does not implement interface member 'I.Goo<T>(T?)' // class C2 : I Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I").WithArguments("C2", "I.Goo<T>(T?)").WithLocation(9, 12), // (12,15): error CS0111: Type 'C2' already defines a member called 'I.Goo' with the same parameter types // object? I.Goo<T>(T? value) => 42; Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "Goo").WithArguments("I.Goo", "C2").WithLocation(12, 15)); } [Fact] [WorkItem(34508, "https://github.com/dotnet/roslyn/issues/34508")] public void OverrideMethodTakingNullableClassTypeParameterDefinedByClass_WithMethodTakingNullableClassParameter() { var source = @" #nullable enable abstract class Base<T> where T : class { public abstract void Goo(T? value); } class Derived<T> : Base<T> where T : class { public override void Goo(T? value) { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.False(dGoo.Parameters[0].Type.IsNullableType()); Assert.True(dGoo.Parameters[0].TypeWithAnnotations.NullableAnnotation == NullableAnnotation.Annotated); } [Fact] public void ImplementMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter1() { var source = @" #nullable enable interface I { void Goo<T>(T? value) where T : class; } class C1 : I { public void Goo<T>(T? value) where T : class { } } class C2 : I { void I.Goo<T>(T? value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.Parameters[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, c2Goo.Parameters[0].TypeWithAnnotations.NullableAnnotation); } [Fact] public void ImplementMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter2() { var source = @" #nullable enable interface I { void Goo<T>(T?[] value) where T : class; } class C1 : I { public void Goo<T>(T?[] value) where T : class { } } class C2 : I { void I.Goo<T>(T?[] value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(((ArrayTypeSymbol)c2Goo.Parameters[0].Type).ElementType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, ((ArrayTypeSymbol)c2Goo.Parameters[0].Type).ElementTypeWithAnnotations.NullableAnnotation); } [Fact] public void ImplementMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter3() { var source = @" #nullable enable interface I { void Goo<T>((T a, T? b)? value) where T : class; } class C1 : I { public void Goo<T>((T a, T? b)? value) where T : class { } } class C2 : I { void I.Goo<T>((T a, T? b)? value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.Parameters[0].Type.IsNullableType()); var tuple = c2Goo.Parameters[0].Type.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.True(tuple.TupleElements[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.NotAnnotated, tuple.TupleElements[0].TypeWithAnnotations.NullableAnnotation); Assert.True(tuple.TupleElements[1].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, tuple.TupleElements[1].TypeWithAnnotations.NullableAnnotation); } [Fact] public void ImplementMethodReturningNullableClassParameter_WithMethodReturningNullableClass1() { var source = @" #nullable enable interface I { T? Goo<T>() where T : class; } class C1 : I { public T? Goo<T>() where T : class => default; } class C2 : I { T? I.Goo<T>() where T : class => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.ReturnType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, c2Goo.ReturnTypeWithAnnotations.NullableAnnotation); } [Fact] public void ImplementMethodReturningNullableClassParameter_WithMethodReturningNullableClass2() { var source = @" #nullable enable interface I { T?[] Goo<T>() where T : class; } class C1 : I { public T?[] Goo<T>() where T : class => default!; } class C2 : I { T?[] I.Goo<T>() where T : class => default!; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(((ArrayTypeSymbol)c2Goo.ReturnType).ElementType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, ((ArrayTypeSymbol)c2Goo.ReturnType).ElementTypeWithAnnotations.NullableAnnotation); } [Fact] public void ImplementMethodReturningNullableClassParameter_WithMethodReturningNullableClass3() { var source = @" #nullable enable interface I { (T a, T? b)? Goo<T>() where T : class; } class C1 : I { public (T a, T? b)? Goo<T>() where T : class => default; } class C2 : I { (T a, T? b)? I.Goo<T>() where T : class => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var c2Goo = (MethodSymbol)comp.GetMember("C2.I.Goo"); Assert.True(c2Goo.ReturnType.IsNullableType()); var tuple = c2Goo.ReturnType.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.True(tuple.TupleElements[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.NotAnnotated, tuple.TupleElements[0].TypeWithAnnotations.NullableAnnotation); Assert.True(tuple.TupleElements[1].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, tuple.TupleElements[1].TypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter1() { var source = @" #nullable enable abstract class Base { public abstract void Goo<T>(T? value) where T : class; } class Derived : Base { public override void Goo<T>(T? value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.Parameters[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, dGoo.Parameters[0].TypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter2() { var source = @" #nullable enable abstract class Base { public abstract void Goo<T>(T?[] value) where T : class; } class Derived : Base { public override void Goo<T>(T?[] value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(((ArrayTypeSymbol)dGoo.Parameters[0].Type).ElementType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, ((ArrayTypeSymbol)dGoo.Parameters[0].Type).ElementTypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethodTakingNullableClassParameter_WithMethodTakingNullableClassParameter3() { var source = @" #nullable enable abstract class Base { public abstract void Goo<T>((T a, T? b)? value) where T : class; } class Derived : Base { public override void Goo<T>((T a, T? b)? value) where T : class { } } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.Parameters[0].Type.IsNullableType()); var tuple = dGoo.Parameters[0].Type.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.True(tuple.TupleElements[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.NotAnnotated, tuple.TupleElements[0].TypeWithAnnotations.NullableAnnotation); Assert.True(tuple.TupleElements[1].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, tuple.TupleElements[1].TypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethodReturningNullableClassParameter_WithMethodReturningNullableClass1() { var source = @" #nullable enable abstract class Base { public abstract T? Goo<T>() where T : class; } class Derived : Base { public override T? Goo<T>() where T : class => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.ReturnType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, dGoo.ReturnTypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethodReturningNullableClassParameter_WithMethodReturningNullableClass2() { var source = @" #nullable enable abstract class Base { public abstract T?[] Goo<T>() where T : class; } class Derived : Base { public override T?[] Goo<T>() where T : class => default!; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(((ArrayTypeSymbol)dGoo.ReturnType).ElementType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, ((ArrayTypeSymbol)dGoo.ReturnType).ElementTypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethodReturningNullableClassParameter_WithMethodReturningNullableClass3() { var source = @" #nullable enable abstract class Base { public abstract (T a, T? b)? Goo<T>() where T : class; } class Derived : Base { public override (T a, T? b)? Goo<T>() where T : class => default; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.ReturnType.IsNullableType()); var tuple = dGoo.ReturnType.GetMemberTypeArgumentsNoUseSiteDiagnostics()[0]; Assert.True(tuple.TupleElements[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.NotAnnotated, tuple.TupleElements[0].TypeWithAnnotations.NullableAnnotation); Assert.True(tuple.TupleElements[1].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, tuple.TupleElements[1].TypeWithAnnotations.NullableAnnotation); } [Fact] public void OverrideMethod_WithMultipleClassAndStructConstraints() { var source = @" using System.IO; #nullable enable abstract class Base { public abstract T? Goo<T, U, V>(U? u, (V?, U?) vu) where T : Stream where U : struct where V : class; } class Derived : Base { public override T? Goo<T, U, V>(U? u, (V?, U?) vu) where T : class where U : struct where V : class => default!; } "; var comp = CreateCompilation(source).VerifyDiagnostics(); var dGoo = (MethodSymbol)comp.GetMember("Derived.Goo"); Assert.True(dGoo.ReturnType.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, dGoo.ReturnTypeWithAnnotations.NullableAnnotation); Assert.True(dGoo.Parameters[0].Type.IsNullableType()); var tuple = dGoo.Parameters[1].Type; Assert.True(tuple.TupleElements[0].Type.IsReferenceType); Assert.Equal(NullableAnnotation.Annotated, tuple.TupleElements[0].TypeWithAnnotations.NullableAnnotation); Assert.True(tuple.TupleElements[1].Type.IsNullableType()); } [Fact] [WorkItem(29894, "https://github.com/dotnet/roslyn/issues/29894")] public void TypeOf_03() { var source = @" #nullable enable class K<T> { } class C1 { object o1 = typeof(int); object o2 = typeof(string); object o3 = typeof(int?); object o4 = typeof(string?); // 1 object o5 = typeof(K<int?>); object o6 = typeof(K<string?>); object o7 = typeof(K<int?>?); // 2 object o8 = typeof(K<string?>?);// 3 } #nullable disable class C2 { object o1 = typeof(int); object o2 = typeof(string); object o3 = typeof(int?); object o4 = typeof(string?); // 4, 5 object o5 = typeof(K<int?>); object o6 = typeof(K<string?>); // 6 object o7 = typeof(K<int?>?); // 7, 8 object o8 = typeof(K<string?>?);// 9, 10, 11 } #nullable enable class C3<T, TClass, TStruct> where TClass : class where TStruct : struct { object o1 = typeof(T?); // 12 object o2 = typeof(TClass?); // 13 object o3 = typeof(TStruct?); } "; CreateCompilation(source, parseOptions: TestOptions.Regular8).VerifyDiagnostics( // (9,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o4 = typeof(string?); // 1 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(string?)").WithLocation(9, 17), // (12,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o7 = typeof(K<int?>?); // 2 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(K<int?>?)").WithLocation(12, 17), // (13,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o8 = typeof(K<string?>?);// 3 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(K<string?>?)").WithLocation(13, 17), // (21,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o4 = typeof(string?); // 4, 5 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(string?)").WithLocation(21, 17), // (21,30): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // object o4 = typeof(string?); // 4, 5 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(21, 30), // (23,32): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // object o6 = typeof(K<string?>); // 6 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(23, 32), // (24,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o7 = typeof(K<int?>?); // 7, 8 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(K<int?>?)").WithLocation(24, 17), // (24,31): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // object o7 = typeof(K<int?>?); // 7, 8 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(24, 31), // (25,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o8 = typeof(K<string?>?);// 9, 10, 11 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(K<string?>?)").WithLocation(25, 17), // (25,32): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // object o8 = typeof(K<string?>?);// 9, 10, 11 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(25, 32), // (25,34): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // object o8 = typeof(K<string?>?);// 9, 10, 11 Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(25, 34), // (32,24): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // object o1 = typeof(T?); // 12 Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(32, 24), // (33,17): error CS8639: The typeof operator cannot be used on a nullable reference type // object o2 = typeof(TClass?); // 13 Diagnostic(ErrorCode.ERR_BadNullableTypeof, "typeof(TClass?)").WithLocation(33, 17)); } [Fact, WorkItem(34299, "https://github.com/dotnet/roslyn/issues/34299")] public void CheckLambdaInArrayInitializer_01() { var source = @"using System; class C { static void G(object? o, string s) { Func<object> f = () => o; // 1 _ = f /*T:System.Func<object!>!*/; var fa3 = new[] { f, () => o, // 2 () => { s = null; // 3 return null; // 4 }, }; _ = fa3 /*T:System.Func<object!>![]!*/; fa3[0]().ToString(); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (7,32): warning CS8603: Possible null reference return. // Func<object> f = () => o; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(7, 32), // (11,19): warning CS8603: Possible null reference return. // () => o, // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(11, 19), // (13,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 25), // (14,28): warning CS8603: Possible null reference return. // return null; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(14, 28)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/35302"), WorkItem(35302, "https://github.com/dotnet/roslyn/issues/35302")] public void CheckLambdaInArrayInitializer_02() { var source = @"using System; class C { static void G(object? o, string s) { if (o == null) return; var f = M(o); _ = f /*T:System.Func<object!>!*/; var fa3 = new[] { f, () => null, // 1 () => { s = null; // 2 return null; // 3 }, }; _ = fa3 /*T:System.Func<object!>![]!*/; fa3[0]().ToString(); } static Func<T> M<T>(T t) => () => t; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (12,19): warning CS8603: Possible null reference return. // () => null, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(12, 19), // (14,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 25), // (15,28): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(15, 28)); } [Fact, WorkItem(34299, "https://github.com/dotnet/roslyn/issues/34299")] public void CheckLambdaInSwitchExpression_01() { var source = @"using System; class C { static void G(int i, object? o, string s) { Func<object> f = () => i; _ = f /*T:System.Func<object!>!*/; var f2 = i switch { 1 => f, 2 => () => o, // 1 _ => () => { s = null; // 2 return null; // 3 }, }; _ = f2 /*T:System.Func<object!>!*/; f2().ToString(); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyTypes(); comp.VerifyDiagnostics( // (11,24): warning CS8603: Possible null reference return. // 2 => () => o, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(11, 24), // (13,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 25), // (14,28): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(14, 28)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/35302"), WorkItem(34299, "https://github.com/dotnet/roslyn/issues/34299")] public void CheckLambdaInSwitchExpression_02() { var source = @"using System; class C { static void G(int i, object? o, string s) { if (o == null) return; var f = M(o); _ = f /*T:System.Func<object!>!*/; var f2 = i switch { 1 => f, 2 => () => o, // 1 _ => () => { s = null; // 2 return null; // 3 }, }; _ = f2 /*T:System.Func<object!>!*/; f2().ToString(); } static Func<T> M<T>(T t) => () => t; } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); //comp.VerifyTypes(); comp.VerifyDiagnostics( // (12,24): warning CS8603: Possible null reference return. // 2 => () => o, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(12, 24), // (12,24): warning CS8603: Possible null reference return. // 2 => () => o, // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "o").WithLocation(12, 24), // (14,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 25), // (14,25): warning CS8600: Converting null literal or possible null value to non-nullable type. // s = null; // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 25), // (15,28): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(15, 28), // (15,28): warning CS8603: Possible null reference return. // return null; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "null").WithLocation(15, 28)); } [Fact, WorkItem(34299, "https://github.com/dotnet/roslyn/issues/34299")] public void CheckLambdaInLambdaInference() { var source = @"using System; class C { static Func<T> M<T>(Func<T> f) => f; static void G(int i, object? o, string? s) { if (o == null) return; var f = M(() => o); var f2 = M(() => { if (i == 1) return f; if (i == 2) return () => s; // 1 return () => { return s; // 2 }; }); f2().ToString(); } } "; var comp = CreateCompilation(new[] { source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,42): warning CS8603: Possible null reference return. // if (i == 2) return () => s; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(12, 42), // (14,32): warning CS8603: Possible null reference return. // return s; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s").WithLocation(14, 32)); } [Fact, WorkItem(29956, "https://github.com/dotnet/roslyn/issues/29956")] public void ConditionalExpression_InferredResultType() { CSharpCompilation c = CreateNullableCompilation(@" class C { void Test1(object? x) { M(x)?.Self()/*T:Box<object?>?*/; M(x)?.Value()/*T:object?*/; if (x == null) return; M(x)?.Self()/*T:Box<object!>?*/; M(x)?.Value()/*T:object?*/; } void Test2<T>(T x) { M(x)?.Self()/*T:Box<T>?*/; M(x)?.Value()/*T:void*/; if (x == null) return; M(x)?.Self()/*T:Box<T>?*/; M(x)?.Value()/*T:void*/; } void Test3(int x) { M(x)?.Self()/*T:Box<int>?*/; M(x)?.Value()/*T:int?*/; if (x == null) return; // 1 M(x)?.Self()/*T:Box<int>?*/; M(x)?.Value()/*T:int?*/; } void Test4(int? x) { M(x)?.Self()/*T:Box<int?>?*/; M(x)?.Value()/*T:int?*/; if (x == null) return; M(x)?.Self()/*T:Box<int?>?*/; M(x)?.Value()/*T:int?*/; } void Test5<T>(T? x) where T : class { M(x)?.Self()/*T:Box<T?>?*/; M(x)?.Value()/*T:T?*/; if (x == null) return; M(x)?.Self()/*T:Box<T!>?*/; M(x)?.Value()/*T:T?*/; } void Test6<T>(T x) where T : struct { M(x)?.Self()/*T:Box<T>?*/; M(x)?.Value()/*T:T?*/; if (x == null) return; // 2 M(x)?.Self()/*T:Box<T>?*/; M(x)?.Value()/*T:T?*/; } void Test7<T>(T? x) where T : struct { M(x)?.Self()/*T:Box<T?>?*/; M(x)?.Value()/*T:T?*/; if (x == null) return; M(x)?.Self()/*T:Box<T?>?*/; M(x)?.Value()/*T:T?*/; } void Test8<T>(T x) where T : class { M(x)?.Self()/*T:Box<T!>?*/; M(x)?.Value()/*T:T?*/; if (x == null) return; M(x)?.Self()/*T:Box<T!>?*/; M(x)?.Value()/*T:T?*/; } void Test9<T>(T x) where T : class { M(x)?.Self()/*T:Box<T!>?*/; M(x)?.Value()/*T:T?*/; if (x != null) return; M(x)?.Self()/*T:Box<T?>?*/; M(x)?.Value()/*T:T?*/; } static Box<T> M<T>(T t) => new Box<T>(t); } class Box<T> { public Box<T> Self() => this; public T Value() => throw null!; public Box(T value) { } } "); c.VerifyTypes(); c.VerifyDiagnostics( // (26,13): warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equal to 'null' of type 'int?' // if (x == null) return; // 1 Diagnostic(ErrorCode.WRN_NubExprIsConstBool, "x == null").WithArguments("false", "int", "int?").WithLocation(26, 13), // (53,13): error CS0019: Operator '==' cannot be applied to operands of type 'T' and '<null>' // if (x == null) return; // 2 Diagnostic(ErrorCode.ERR_BadBinaryOps, "x == null").WithArguments("==", "T", "<null>").WithLocation(53, 13)); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_01() { var source = @"#nullable enable using System; public class Program { static void Main(string? value) { int count = 84; if (value?.Length == count) { Console.WriteLine(value.Length); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_02() { var source = @"#nullable enable using System; public class Program { static void Main(string? value) { if (value?.Length == (int?) null) { Console.WriteLine(value.Length); // 1 } else { Console.WriteLine(value.Length); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(value.Length); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(10, 31)); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_03() { var source = @"#nullable enable using System; public class Program { static void Main(string? value) { int? i = null; if (value?.Length == i) { Console.WriteLine(value.Length); // 1 } else { Console.WriteLine(value.Length); // 2 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(value.Length); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(11, 31), // (15,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(value.Length); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(15, 31)); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_04() { var source = @"#nullable enable using System; public class C { public string? s; } public class Program { static void Main(C? value) { const object? i = null; if (value?.s == i) { Console.WriteLine(value.s); // 1 } else { Console.WriteLine(value.s); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (16,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(value.s); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "value").WithLocation(16, 31)); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_05() { var source = @"#nullable enable using System; public class Program { static void Main(string? x, string? y) { if (x?.Length == 2 && y?.Length == 2) { Console.WriteLine(x.Length); Console.WriteLine(y.Length); } else { Console.WriteLine(x.Length); // 1 Console.WriteLine(y.Length); // 2 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(x.Length); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 31), // (16,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(y.Length); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(16, 31)); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_06() { var source = @"#nullable enable using System; public class Program { static void Main(string? x, string? y) { if (x?.Length != 2 || y?.Length != 2) { Console.WriteLine(x.Length); // 1 Console.WriteLine(y.Length); // 2 } else { Console.WriteLine(x.Length); Console.WriteLine(y.Length); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(x.Length); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 31), // (11,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(y.Length); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 31)); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_07() { var source = @"#nullable enable using System; public class Program { static void Main(string? x, string? y) { if (x?.Length == 2 ? y?.Length == 2 : y?.Length == 3) { Console.WriteLine(x.Length); // 1 Console.WriteLine(y.Length); } else { Console.WriteLine(x.Length); // 2 Console.WriteLine(y.Length); // 3 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(x.Length); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(10, 31), // (15,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(x.Length); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(15, 31), // (16,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(y.Length); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(16, 31) ); } [Fact, WorkItem(34942, "https://github.com/dotnet/roslyn/issues/34942")] public void ConditionalAccess_08() { var source = @"#nullable enable using System; public class A { public static explicit operator B(A? a) => new B(); } public class B { } public class Program { static void Main(A? a) { B b = new B(); if ((B)a == b) { Console.WriteLine(a.ToString()); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,31): warning CS8602: Dereference of a possibly null reference. // Console.WriteLine(a.ToString()); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(19, 31)); } [Fact, WorkItem(35075, "https://github.com/dotnet/roslyn/issues/35075")] public void ConditionalExpression_TypeParameterConstrainedToNullableValueType() { CSharpCompilation c = CreateNullableCompilation(@" class C<T> { public virtual void M<U>(B x, U y) where U : T { } } class B : C<int?> { public override void M<U>(B x, U y) { var z = x?.Test(y)/*T:U?*/; z = null; } T Test<T>(T x) => throw null!; }"); c.VerifyTypes(); // Per https://github.com/dotnet/roslyn/issues/35075 errors should be expected c.VerifyDiagnostics(); } [Fact] public void AttributeAnnotation_DoesNotReturnIfFalse() { var source = @"#pragma warning disable 169 using System.Diagnostics.CodeAnalysis; class A : System.Attribute { internal A(object x, object y) { } } [A(Assert(F != null), F)] class Program { static object? F; static object Assert([DoesNotReturnIf(false)]bool b) => throw null!; }"; var comp = CreateCompilation(new[] { DoesNotReturnIfAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(Assert(F != null), F)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "Assert(F != null)").WithLocation(7, 4), // (7,23): warning CS8604: Possible null reference argument for parameter 'y' in 'A.A(object x, object y)'. // [A(Assert(F != null), F)] Diagnostic(ErrorCode.WRN_NullReferenceArgument, "F").WithArguments("y", "A.A(object x, object y)").WithLocation(7, 23), // (7,23): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(Assert(F != null), F)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F").WithLocation(7, 23)); } [Fact] public void AttributeAnnotation_NotNull() { var source = @"#pragma warning disable 169 using System.Diagnostics.CodeAnalysis; class A : System.Attribute { internal A(object x, object y) { } } [A(NotNull(F), F)] class Program { static object? F; static object NotNull([NotNull]object? o) => throw null!; }"; var comp = CreateCompilation(new[] { NotNullAttributeDefinition, source }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (7,4): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(NotNull(F), F)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "NotNull(F)").WithLocation(7, 4), // (7,16): warning CS8604: Possible null reference argument for parameter 'y' in 'A.A(object x, object y)'. // [A(NotNull(F), F)] Diagnostic(ErrorCode.WRN_NullReferenceArgument, "F").WithArguments("y", "A.A(object x, object y)").WithLocation(7, 16), // (7,16): error CS0182: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type // [A(NotNull(F), F)] Diagnostic(ErrorCode.ERR_BadAttributeArgument, "F").WithLocation(7, 16)); } [Fact] [WorkItem(35056, "https://github.com/dotnet/roslyn/issues/35056")] public void CircularAttribute() { var source = @"class A : System.Attribute { A([A(1)]int x) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact, WorkItem(34827, "https://github.com/dotnet/roslyn/issues/34827")] public void ArrayConversionToInterface() { string source = @" using System.Collections.Generic; class C { void M() { IEnumerable<object> x1 = new[] { ""string"", null }; // 1 IEnumerable<object?> x2 = new[] { ""string"", null }; IEnumerable<object?> x3 = new[] { ""string"" }; IList<string> x4 = new[] { ""string"", null }; // 2 ICollection<string?> x5 = new[] { ""string"", null }; ICollection<string?> x6 = new[] { ""string"" }; IReadOnlyList<string?> x7 = new[] { ""string"" }; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,34): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'IEnumerable<object>'. // IEnumerable<object> x1 = new[] { "string", null }; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new[] { ""string"", null }").WithArguments("string?[]", "System.Collections.Generic.IEnumerable<object>").WithLocation(7, 34), // (10,28): warning CS8619: Nullability of reference types in value of type 'string?[]' doesn't match target type 'IList<string>'. // IList<string> x4 = new[] { "string", null }; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new[] { ""string"", null }").WithArguments("string?[]", "System.Collections.Generic.IList<string>").WithLocation(10, 28) ); } [Fact, WorkItem(34827, "https://github.com/dotnet/roslyn/issues/34827")] public void ArrayConversionToInterface_Nested() { string source = @" using System.Collections.Generic; class C { void M() { IEnumerable<object[]> x1 = new[] { new[] { ""string"", null } }; // 1 IEnumerable<object[]?> x2 = new[] { new[] { ""string"", null } }; // 2 IEnumerable<object?[]> x3 = new[] { new[] { ""string"", null } }; IEnumerable<object?[]?> x4 = new[] { new[] { ""string"" } }; IEnumerable<IEnumerable<string>> x5 = new[] { new[] { ""string"" , null } }; // 3 IEnumerable<IEnumerable<string?>> x6 = new[] { new[] { ""string"" , null } }; IEnumerable<IEnumerable<string?>> x7 = new[] { new[] { ""string"" } }; } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (7,36): warning CS8619: Nullability of reference types in value of type 'string?[][]' doesn't match target type 'IEnumerable<object[]>'. // IEnumerable<object[]> x1 = new[] { new[] { "string", null } }; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new[] { new[] { ""string"", null } }").WithArguments("string?[][]", "System.Collections.Generic.IEnumerable<object[]>").WithLocation(7, 36), // (8,37): warning CS8619: Nullability of reference types in value of type 'string?[][]' doesn't match target type 'IEnumerable<object[]?>'. // IEnumerable<object[]?> x2 = new[] { new[] { "string", null } }; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new[] { new[] { ""string"", null } }").WithArguments("string?[][]", "System.Collections.Generic.IEnumerable<object[]?>").WithLocation(8, 37), // (11,47): warning CS8619: Nullability of reference types in value of type 'string?[][]' doesn't match target type 'IEnumerable<IEnumerable<string>>'. // IEnumerable<IEnumerable<string>> x5 = new[] { new[] { "string" , null } }; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, @"new[] { new[] { ""string"" , null } }").WithArguments("string?[][]", "System.Collections.Generic.IEnumerable<System.Collections.Generic.IEnumerable<string>>").WithLocation(11, 47) ); } [Fact] [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] public void ExtensionMethodDelegate_01() { var source = @"delegate void D0(); delegate void D1<T>(T t); static class E { internal static void F<T>(this T t) { } } class Program { static void M0(string? x, string y) { D0 d; d = x.F; d = x.F<string?>; d = x.F<string>; // 1 d = y.F; d = y.F<string?>; d = y.F<string>; } static void M1() { D1<string?> d; D1<string> e; d = E.F<string?>; d = E.F<string>; // 2 e = E.F<string?>; e = E.F<string>; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,13): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string>(string t)'. // d = x.F<string>; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string>(string t)").WithLocation(14, 13), // (24,13): warning CS8622: Nullability of reference types in type of parameter 't' of 'void E.F<string>(string t)' doesn't match the target delegate 'D1<string?>'. // d = E.F<string>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "E.F<string>").WithArguments("t", "void E.F<string>(string t)", "D1<string?>").WithLocation(24, 13)); } [Fact] public void ExtensionMethodDelegate_02() { var source = @"delegate void D0(); delegate void D1<T>(T t); static class E { internal static void F<T>(this T t) { } } class Program { static void M0(string? x, string y) { _ = new D0(x.F); _ = new D0(x.F<string?>); _ = new D0(x.F<string>); // 1 _ = new D0(y.F); _ = new D0(y.F<string?>); _ = new D0(y.F<string>); } static void M1() { _ = new D1<string?>(E.F<string?>); _ = new D1<string?>(E.F<string>); // 2 _ = new D1<string>(E.F<string?>); _ = new D1<string>(E.F<string>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,20): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string>(string t)'. // _ = new D0(x.F<string>); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string>(string t)").WithLocation(13, 20), // (21,29): warning CS8622: Nullability of reference types in type of parameter 't' of 'void E.F<string>(string t)' doesn't match the target delegate 'D1<string?>'. // _ = new D1<string?>(E.F<string>); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "E.F<string>").WithArguments("t", "void E.F<string>(string t)", "D1<string?>").WithLocation(21, 29)); } [Fact] [WorkItem(30287, "https://github.com/dotnet/roslyn/issues/30287")] [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] public void ExtensionMethodDelegate_03() { var source = @"delegate void D<in T>(T t); static class E { internal static void F<T>(this T t, int i) { } } class Program { static void M(string? x, string y) { D<int> d; d = x.F; d = x.F<string?>; d = x.F<string>; // 1 d = y.F; d = y.F<string?>; d = y.F<string>; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string>(string t, int i)'. // d = x.F<string>; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string>(string t, int i)").WithLocation(13, 13)); } [Fact] [WorkItem(30287, "https://github.com/dotnet/roslyn/issues/30287")] public void ExtensionMethodDelegate_04() { var source = @"delegate void D<in T>(T t); static class E { internal static void F<T>(this T t, int i) { } } class Program { static void M(string? x, string y) { _ = new D<int>(x.F); _ = new D<int>(x.F<string?>); _ = new D<int>(x.F<string>); // 1 _ = new D<int>(y.F); _ = new D<int>(y.F<string?>); _ = new D<int>(y.F<string>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,24): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string>(string t, int i)'. // _ = new D<int>(x.F<string>); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string>(string t, int i)").WithLocation(12, 24)); } [Fact] [WorkItem(30287, "https://github.com/dotnet/roslyn/issues/30287")] [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] public void ExtensionMethodDelegate_05() { var source = @"delegate void D<in T>(T t); static class E { internal static void F<T, U>(this T t, U u) { } } class Program { static void M(bool b, string? x, string y) { D<string?> d; D<string> e; if (b) d = x.F<string?, string?>; if (b) e = x.F<string?, string>; if (b) d = x.F<string, string?>; // 1 if (b) e = x.F<string, string>; // 2 if (b) d = y.F<string?, string?>; if (b) e = y.F<string?, string>; if (b) d = y.F<string, string?>; if (b) e = y.F<string, string>; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,20): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string, string?>(string t, string? u)'. // if (b) d = x.F<string, string?>; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string, string?>(string t, string? u)").WithLocation(14, 20), // (15,20): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string, string>(string t, string u)'. // if (b) e = x.F<string, string>; // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string, string>(string t, string u)").WithLocation(15, 20)); } [Fact] [WorkItem(30287, "https://github.com/dotnet/roslyn/issues/30287")] public void ExtensionMethodDelegate_06() { var source = @"delegate void D<in T>(T t); static class E { internal static void F<T, U>(this T t, U u) { } } class Program { static void M(bool b, string? x, string y) { if (b) _ = new D<string?>(x.F<string?, string?>); if (b) _ = new D<string>(x.F<string?, string>); if (b) _ = new D<string?>(x.F<string, string?>); // 1 if (b) _ = new D<string>(x.F<string, string>); // 2 if (b) _ = new D<string?>(y.F<string?, string?>); if (b) _ = new D<string>(y.F<string?, string>); if (b) _ = new D<string?>(y.F<string, string?>); if (b) _ = new D<string>(y.F<string, string>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,35): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string, string?>(string t, string? u)'. // if (b) _ = new D<string?>(x.F<string, string?>); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string, string?>(string t, string? u)").WithLocation(12, 35), // (13,34): warning CS8604: Possible null reference argument for parameter 't' in 'void E.F<string, string>(string t, string u)'. // if (b) _ = new D<string>(x.F<string, string>); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "x").WithArguments("t", "void E.F<string, string>(string t, string u)").WithLocation(13, 34)); } [Fact] [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] public void ExtensionMethodDelegate_07() { var source = @"delegate void D(); static class E { internal static void F<T>(this T t) { } } class Program { static void M<T, U, V>() where U : class where V : struct { D d; d = default(T).F; d = default(U).F; d = default(V).F; d = default(V?).F; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,13): error CS1113: Extension method 'E.F<T>(T)' defined on value type 'T' cannot be used to create delegates // d = default(T).F; Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "default(T).F").WithArguments("E.F<T>(T)", "T").WithLocation(13, 13), // (15,13): error CS1113: Extension method 'E.F<V>(V)' defined on value type 'V' cannot be used to create delegates // d = default(V).F; Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "default(V).F").WithArguments("E.F<V>(V)", "V").WithLocation(15, 13), // (16,13): error CS1113: Extension method 'E.F<V?>(V?)' defined on value type 'V?' cannot be used to create delegates // d = default(V?).F; Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "default(V?).F").WithArguments("E.F<V?>(V?)", "V?").WithLocation(16, 13)); } [Fact] [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] public void ExtensionMethodDelegate_08() { var source = @"delegate void D(); static class E { internal static void F<T>(this T t) { } } class Program { static void M<T, U, V>() where U : class where V : struct { _ = new D(default(T).F); _ = new D(default(U).F); _ = new D(default(V).F); _ = new D(default(V?).F); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,19): error CS1113: Extension method 'E.F<T>(T)' defined on value type 'T' cannot be used to create delegates // _ = new D(default(T).F); Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "default(T).F").WithArguments("E.F<T>(T)", "T").WithLocation(12, 19), // (14,19): error CS1113: Extension method 'E.F<V>(V)' defined on value type 'V' cannot be used to create delegates // _ = new D(default(V).F); Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "default(V).F").WithArguments("E.F<V>(V)", "V").WithLocation(14, 19), // (15,19): error CS1113: Extension method 'E.F<V?>(V?)' defined on value type 'V?' cannot be used to create delegates // _ = new D(default(V?).F); Diagnostic(ErrorCode.ERR_ValueTypeExtDelegate, "default(V?).F").WithArguments("E.F<V?>(V?)", "V?").WithLocation(15, 19)); } [Fact] [WorkItem(30563, "https://github.com/dotnet/roslyn/issues/30563")] public void ExtensionMethodDelegate_09() { var source = @"delegate T D<T>(); static class E { internal static T F<T>(this T t) => t; } class Program { static void M<T>() where T : class { T? t = default; D<T> d; d = t.F; // 1 d = t.F!; d = t.F<T?>; // 2 d = t.F<T?>!; _ = new D<T>(t.F); // 3 _ = new D<T>(t.F!); _ = new D<T>(t.F<T?>); // 4 _ = new D<T>(t.F<T?>!); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,13): warning CS8621: Nullability of reference types in return type of 'T? E.F<T?>(T? t)' doesn't match the target delegate 'D<T>'. // d = t.F; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "t.F").WithArguments("T? E.F<T?>(T? t)", "D<T>").WithLocation(12, 13), // (14,13): warning CS8621: Nullability of reference types in return type of 'T? E.F<T?>(T? t)' doesn't match the target delegate 'D<T>'. // d = t.F<T?>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "t.F<T?>").WithArguments("T? E.F<T?>(T? t)", "D<T>").WithLocation(14, 13), // (16,22): warning CS8621: Nullability of reference types in return type of 'T? E.F<T?>(T? t)' doesn't match the target delegate 'D<T>'. // _ = new D<T>(t.F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "t.F").WithArguments("T? E.F<T?>(T? t)", "D<T>").WithLocation(16, 22), // (18,22): warning CS8621: Nullability of reference types in return type of 'T? E.F<T?>(T? t)' doesn't match the target delegate 'D<T>'. // _ = new D<T>(t.F<T?>); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "t.F<T?>").WithArguments("T? E.F<T?>(T? t)", "D<T>").WithLocation(18, 22)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void DelegateInferredNullability_01() { var source = @"delegate T D<T>(); class C<T> { internal T F() => throw null!; } class Program { static C<T> Create<T>(T t) => new C<T>(); static void M() { object? x = new object(); object y = null; // 1 D<object?> d1; D<object> d2; d1 = Create(x).F; d2 = Create(x).F; d1 = Create(y).F; d2 = Create(y).F; // 2 _ = new D<object?>(Create(x).F); _ = new D<object>(Create(x).F); _ = new D<object?>(Create(y).F); _ = new D<object>(Create(y).F); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 20), // (18,14): warning CS8621: Nullability of reference types in return type of 'object? C<object?>.F()' doesn't match the target delegate 'D<object>'. // d2 = Create(y).F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Create(y).F").WithArguments("object? C<object?>.F()", "D<object>").WithLocation(18, 14), // (22,27): warning CS8621: Nullability of reference types in return type of 'object? C<object?>.F()' doesn't match the target delegate 'D<object>'. // _ = new D<object>(Create(y).F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Create(y).F").WithArguments("object? C<object?>.F()", "D<object>").WithLocation(22, 27)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void DelegateInferredNullability_02() { var source = @"delegate void D<T>(T t); class C<T> { internal void F(T t) { } } class Program { static C<T> Create<T>(T t) => new C<T>(); static void M() { object? x = new object(); object y = null; // 1 D<object?> d1; D<object> d2; d1 = Create(x).F; // 2 d2 = Create(x).F; d1 = Create(y).F; d2 = Create(y).F; _ = new D<object?>(Create(x).F); // 3 _ = new D<object>(Create(x).F); _ = new D<object?>(Create(y).F); _ = new D<object>(Create(y).F); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 20), // (15,14): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C<object>.F(object t)' doesn't match the target delegate 'D<object?>'. // d1 = Create(x).F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Create(x).F").WithArguments("t", "void C<object>.F(object t)", "D<object?>").WithLocation(15, 14), // (19,28): warning CS8622: Nullability of reference types in type of parameter 't' of 'void C<object>.F(object t)' doesn't match the target delegate 'D<object?>'. // _ = new D<object?>(Create(x).F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInParameterTypeOfTargetDelegate, "Create(x).F").WithArguments("t", "void C<object>.F(object t)", "D<object?>").WithLocation(19, 28)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void DelegateInferredNullability_03() { var source = @"delegate T D<T>(); class C<T> { internal U F<U>() where U : T => throw null!; } class Program { static C<T> Create<T>(T t) => new C<T>(); static void M<T>() where T : class, new() { T? x = new T(); T y = null; // 1 D<T?> d1; D<T> d2; d1 = Create(x).F<T?>; // 2 d2 = Create(x).F<T>; d1 = Create(y).F<T?>; d2 = Create(y).F<T>; _ = new D<T?>(Create(x).F<T?>); // 3 _ = new D<T>(Create(x).F<T>); _ = new D<T?>(Create(y).F<T?>); _ = new D<T>(Create(y).F<T>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 15), // (15,14): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'C<T>.F<U>()'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // d1 = Create(x).F<T?>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "Create(x).F<T?>").WithArguments("C<T>.F<U>()", "T", "U", "T?").WithLocation(15, 14), // (19,23): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'C<T>.F<U>()'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // _ = new D<T?>(Create(x).F<T?>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "Create(x).F<T?>").WithArguments("C<T>.F<U>()", "T", "U", "T?").WithLocation(19, 23)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void DelegateInferredNullability_04() { var source = @"delegate void D<T>(T t); class C<T> { internal void F<U>(U u) where U : T { } } class Program { static C<T> Create<T>(T t) => new C<T>(); static void M<T>() where T : class, new() { T? x = new T(); T y = null; // 1 D<T?> d1; D<T> d2; d1 = Create(x).F; // 2 d2 = Create(x).F; d1 = Create(y).F; d2 = Create(y).F; _ = new D<T?>(Create(x).F); // 3 _ = new D<T>(Create(x).F); _ = new D<T?>(Create(y).F); _ = new D<T>(Create(y).F); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 15), // (15,14): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'C<T>.F<U>(U)'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // d1 = Create(x).F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "Create(x).F").WithArguments("C<T>.F<U>(U)", "T", "U", "T?").WithLocation(15, 14), // (19,23): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'C<T>.F<U>(U)'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // _ = new D<T?>(Create(x).F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "Create(x).F").WithArguments("C<T>.F<U>(U)", "T", "U", "T?").WithLocation(19, 23)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void DelegateInferredNullability_05() { var source = @"delegate void D<T>(T t); class C<T> { internal void F<U>(U u) where U : T { } } class Program { static C<T> Create<T>(T t) => new C<T>(); static void M<T>() where T : class, new() { T? x = new T(); T y = null; // 1 D<T?> d1; D<T> d2; d1 = Create(x).F<T?>; // 2 d2 = Create(x).F<T>; d1 = Create(y).F<T?>; d2 = Create(y).F<T>; _ = new D<T?>(Create(x).F<T?>); // 3 _ = new D<T>(Create(x).F<T>); _ = new D<T?>(Create(y).F<T?>); _ = new D<T>(Create(y).F<T>); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (12,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 15), // (15,14): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'C<T>.F<U>(U)'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // d1 = Create(x).F<T?>; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "Create(x).F<T?>").WithArguments("C<T>.F<U>(U)", "T", "U", "T?").WithLocation(15, 14), // (19,23): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'C<T>.F<U>(U)'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // _ = new D<T?>(Create(x).F<T?>); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "Create(x).F<T?>").WithArguments("C<T>.F<U>(U)", "T", "U", "T?").WithLocation(19, 23)); } [Fact] [WorkItem(35274, "https://github.com/dotnet/roslyn/issues/35274")] public void DelegateInferredNullability_06() { var source = @"delegate T D<T>(); class C<T> { internal T F() => throw null!; } class Program { static C<T> Create<T>(T t) => new C<T>(); static void Main() { string? s = null; var x = Create(s); C<string?> y = Create(s); D<string> d; d = Create(s).F; // 1 d = x.F; // 2 d = y.F; // 3 _ = new D<string>(Create(s).F); // 4 _ = new D<string>(x.F); // 5 _ = new D<string>(y.F); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,13): warning CS8621: Nullability of reference types in return type of 'string? C<string?>.F()' doesn't match the target delegate 'D<string>'. // d = Create(s).F; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Create(s).F").WithArguments("string? C<string?>.F()", "D<string>").WithLocation(15, 13), // (16,13): warning CS8621: Nullability of reference types in return type of 'string? C<string?>.F()' doesn't match the target delegate 'D<string>'. // d = x.F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.F").WithArguments("string? C<string?>.F()", "D<string>").WithLocation(16, 13), // (17,13): warning CS8621: Nullability of reference types in return type of 'string? C<string?>.F()' doesn't match the target delegate 'D<string>'. // d = y.F; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "y.F").WithArguments("string? C<string?>.F()", "D<string>").WithLocation(17, 13), // (18,27): warning CS8621: Nullability of reference types in return type of 'string? C<string?>.F()' doesn't match the target delegate 'D<string>'. // _ = new D<string>(Create(s).F); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Create(s).F").WithArguments("string? C<string?>.F()", "D<string>").WithLocation(18, 27), // (19,27): warning CS8621: Nullability of reference types in return type of 'string? C<string?>.F()' doesn't match the target delegate 'D<string>'. // _ = new D<string>(x.F); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.F").WithArguments("string? C<string?>.F()", "D<string>").WithLocation(19, 27), // (20,27): warning CS8621: Nullability of reference types in return type of 'string? C<string?>.F()' doesn't match the target delegate 'D<string>'. // _ = new D<string>(y.F); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "y.F").WithArguments("string? C<string?>.F()", "D<string>").WithLocation(20, 27)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_01() { var source = @"delegate T D<T>(); static class E { internal static T F<T>(this T t) => t; } class Program { static void M() { object? x = new object(); object y = null; // 1 D<object?> d1; D<object> d2; d1 = x.F; d2 = x.F; d1 = y.F; d2 = y.F; // 2 _ = new D<object?>(x.F); _ = new D<object>(x.F); _ = new D<object?>(y.F); _ = new D<object>(y.F); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 20), // (17,14): warning CS8621: Nullability of reference types in return type of 'object? E.F<object?>(object? t)' doesn't match the target delegate 'D<object>'. // d2 = y.F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "y.F").WithArguments("object? E.F<object?>(object? t)", "D<object>").WithLocation(17, 14), // (21,27): warning CS8621: Nullability of reference types in return type of 'object? E.F<object?>(object? t)' doesn't match the target delegate 'D<object>'. // _ = new D<object>(y.F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "y.F").WithArguments("object? E.F<object?>(object? t)", "D<object>").WithLocation(21, 27)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_02() { var source = @"delegate void D<T>(T t); static class E { internal static void F<T>(this T x, T y) { } } class Program { static void M() { object? x = new object(); object y = null; // 1 D<object?> d1; D<object> d2; d1 = x.F; d2 = x.F; d1 = y.F; d2 = y.F; _ = new D<object?>(x.F); _ = new D<object>(x.F); _ = new D<object?>(y.F); _ = new D<object>(y.F); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 20)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_03() { var source = @"delegate void D<T>(T t); static class E { internal static void F<T>(this T x, T y) { } } class Program { static void M(bool b) { object? x = new object(); object y = null; // 1 D<object?> d1; D<object> d2; if (b) d1 = x.F<object?>; if (b) d2 = x.F<object>; if (b) d1 = y.F<object?>; if (b) d2 = y.F<object>; // 2 if (b) _ = new D<object?>(x.F<object?>); if (b) _ = new D<object>(x.F<object>); if (b) _ = new D<object?>(y.F<object?>); if (b) _ = new D<object>(y.F<object>); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 20), // (17,21): warning CS8604: Possible null reference argument for parameter 'x' in 'void E.F<object>(object x, object y)'. // if (b) d2 = y.F<object>; // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void E.F<object>(object x, object y)").WithLocation(17, 21), // (21,34): warning CS8604: Possible null reference argument for parameter 'x' in 'void E.F<object>(object x, object y)'. // if (b) _ = new D<object>(y.F<object>); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("x", "void E.F<object>(object x, object y)").WithLocation(21, 34)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_04() { var source = @"delegate T D<T>(); static class E { internal static T F<T>(this T t) => t; } class Program { static void M<T>(bool b) where T : class, new() { T? x = new T(); T y = null; // 1 D<T?> d1; D<T> d2; if (b) d1 = x.F<T?>; if (b) d2 = x.F<T>; if (b) d1 = y.F<T?>; if (b) d2 = y.F<T>; // 2 if (b) _ = new D<T?>(x.F<T?>); if (b) _ = new D<T>(x.F<T>); if (b) _ = new D<T?>(y.F<T?>); if (b) _ = new D<T>(y.F<T>); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 15), // (17,21): warning CS8604: Possible null reference argument for parameter 't' in 'T E.F<T>(T t)'. // if (b) d2 = y.F<T>; // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("t", "T E.F<T>(T t)").WithLocation(17, 21), // (21,29): warning CS8604: Possible null reference argument for parameter 't' in 'T E.F<T>(T t)'. // if (b) _ = new D<T>(y.F<T>); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("t", "T E.F<T>(T t)").WithLocation(21, 29)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_05() { var source = @"delegate void D<T>(T t); static class E { internal static void F<T, U>(this T t, U u) where U : T { } } class Program { static void M<T>() where T : class, new() { T? x = new T(); T y = null; // 1 D<T?> d1; D<T> d2; d1 = x.F; // 2 d2 = x.F; d1 = y.F; d2 = y.F; _ = new D<T?>(x.F); // 3 _ = new D<T>(x.F); _ = new D<T?>(y.F); _ = new D<T>(y.F); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 15), // (14,14): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'E.F<T, U>(T, U)'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // d1 = x.F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "x.F").WithArguments("E.F<T, U>(T, U)", "T", "U", "T?").WithLocation(14, 14), // (18,23): warning CS8631: The type 'T?' cannot be used as type parameter 'U' in the generic type or method 'E.F<T, U>(T, U)'. Nullability of type argument 'T?' doesn't match constraint type 'T'. // _ = new D<T?>(x.F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "x.F").WithArguments("E.F<T, U>(T, U)", "T", "U", "T?").WithLocation(18, 23)); } [Fact] [WorkItem(35274, "https://github.com/dotnet/roslyn/issues/35274")] public void ExtensionMethodDelegateInferredNullability_06() { var source = @"delegate T D<T>(); class C<T> { } static class E { internal static T F<T>(this C<T> c) => throw null!; } class Program { static C<T> Create<T>(T t) => new C<T>(); static void Main() { string? s = null; var x = Create(s); C<string?> y = Create(s); D<string> d; d = Create(s).F; // 1 d = x.F; // 2 d = y.F; // 3 _ = new D<string>(Create(s).F); // 4 _ = new D<string>(x.F); // 5 _ = new D<string>(y.F); // 6 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,13): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(C<string?> c)' doesn't match the target delegate 'D<string>'. // d = Create(s).F; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Create(s).F").WithArguments("string? E.F<string?>(C<string?> c)", "D<string>").WithLocation(18, 13), // (19,13): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(C<string?> c)' doesn't match the target delegate 'D<string>'. // d = x.F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.F").WithArguments("string? E.F<string?>(C<string?> c)", "D<string>").WithLocation(19, 13), // (20,13): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(C<string?> c)' doesn't match the target delegate 'D<string>'. // d = y.F; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "y.F").WithArguments("string? E.F<string?>(C<string?> c)", "D<string>").WithLocation(20, 13), // (21,27): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(C<string?> c)' doesn't match the target delegate 'D<string>'. // _ = new D<string>(Create(s).F); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "Create(s).F").WithArguments("string? E.F<string?>(C<string?> c)", "D<string>").WithLocation(21, 27), // (22,27): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(C<string?> c)' doesn't match the target delegate 'D<string>'. // _ = new D<string>(x.F); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.F").WithArguments("string? E.F<string?>(C<string?> c)", "D<string>").WithLocation(22, 27), // (23,27): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(C<string?> c)' doesn't match the target delegate 'D<string>'. // _ = new D<string>(y.F); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "y.F").WithArguments("string? E.F<string?>(C<string?> c)", "D<string>").WithLocation(23, 27)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_07() { var source = @"delegate T D<T>(); static class E { internal static T F<T>(this T t) where T : class => t; } class Program { static void M<T>() where T : class, new() { T? x = new T(); T y = null; // 1 D<T?> d; d = x.F; d = y.F; // 2 _ = new D<T?>(x.F); _ = new D<T?>(y.F); // 3 } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (11,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 15), // (14,13): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'E.F<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // d = y.F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "y.F").WithArguments("E.F<T>(T)", "T", "T?").WithLocation(14, 13), // (16,23): warning CS8634: The type 'T?' cannot be used as type parameter 'T' in the generic type or method 'E.F<T>(T)'. Nullability of type argument 'T?' doesn't match 'class' constraint. // _ = new D<T?>(y.F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "y.F").WithArguments("E.F<T>(T)", "T", "T?").WithLocation(16, 23)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_08() { var source = @"delegate T D<T>(); static class E { internal static T F<T>(this T t) => t; } class Program { static void M<T>() where T : class, new() { T x; N(() => { x = null; // 1 D<T> d = x.F; // 2 _ = new D<T>(x.F); // 3 }); } static void N(System.Action a) { } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (13,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(13, 17), // (14,22): warning CS8621: Nullability of reference types in return type of 'T? E.F<T?>(T? t)' doesn't match the target delegate 'D<T>'. // D<T> d = x.F; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.F").WithArguments("T? E.F<T?>(T? t)", "D<T>").WithLocation(14, 22), // (15,26): warning CS8621: Nullability of reference types in return type of 'T? E.F<T?>(T? t)' doesn't match the target delegate 'D<T>'. // _ = new D<T>(x.F); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "x.F").WithArguments("T? E.F<T?>(T? t)", "D<T>").WithLocation(15, 26)); } [Fact] [WorkItem(33637, "https://github.com/dotnet/roslyn/issues/33637")] public void ExtensionMethodDelegateInferredNullability_09() { var source = @"delegate T D<T>(); static class E { internal static T F<T>(this T t) => t; } class A : System.Attribute { internal A(D<string> d) { } } [A(default(string).F)] class Program { }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,2): error CS0181: Attribute constructor parameter 'd' has type 'D<string>', which is not a valid attribute parameter type // [A(default(string).F)] Diagnostic(ErrorCode.ERR_BadAttributeParamType, "A").WithArguments("d", "D<string>").WithLocation(10, 2), // (10,4): warning CS8621: Nullability of reference types in return type of 'string? E.F<string?>(string? t)' doesn't match the target delegate 'D<string>'. // [A(default(string).F)] Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOfTargetDelegate, "default(string).F").WithArguments("string? E.F<string?>(string? t)", "D<string>").WithLocation(10, 4)); } [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_01() { var source = @"class C<T> { public static C<T> operator &(C<T> a, C<T> b) => a; } class Program { static void M(C<string> a, string s) { var b = Create(s); _ = a & b; } static C<T> Create<T>(T t) => new C<T>(); }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } // C<T~> operator op(C<T~>, C<T~>) [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_02() { var source = @"#nullable disable class C<T> { public static C<T> operator +(C<T> a, C<T> b) => a; } class Program { static void M1<T>( #nullable disable C<T> a, #nullable enable C<T> b) { _ = a + a; _ = a + b; _ = b + a; _ = b + b; } static void M2<T>( #nullable disable C<T> c, #nullable enable C<T> d) where T : class? { _ = c + c; _ = c + d; _ = d + c; _ = d + d; } static void M3<T>( #nullable disable C<T> x, #nullable enable C<T> y, C<T?> z) where T : class { _ = x + x; _ = x + y; _ = x + z; _ = y + x; _ = y + y; _ = y + z; _ = z + x; _ = z + y; _ = z + z; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (44,17): warning CS8620: Argument of type 'C<T?>' cannot be used for parameter 'b' of type 'C<T>' in 'C<T> C<T>.operator +(C<T> a, C<T> b)' due to differences in the nullability of reference types. // _ = y + z; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C<T?>", "C<T>", "b", "C<T> C<T>.operator +(C<T> a, C<T> b)").WithLocation(44, 17), // (46,17): warning CS8620: Argument of type 'C<T>' cannot be used for parameter 'b' of type 'C<T?>' in 'C<T?> C<T?>.operator +(C<T?> a, C<T?> b)' due to differences in the nullability of reference types. // _ = z + y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<T>", "C<T?>", "b", "C<T?> C<T?>.operator +(C<T?> a, C<T?> b)").WithLocation(46, 17)); } // C<T> operator op(C<T>, C<T>) [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_03() { var source = @"#nullable enable class C<T> { public static C<T> operator -(C<T> a, C<T> b) => a; } class Program { static void M1<T>( #nullable disable C<T> a, #nullable enable C<T> b) { _ = a - a; _ = a - b; _ = b - a; _ = b - b; } static void M2<T>( #nullable disable C<T> c, #nullable enable C<T> d) where T : class? { _ = c - c; _ = c - d; _ = d - c; _ = d - d; } static void M3<T>( #nullable disable C<T> x, #nullable enable C<T> y, C<T?> z) where T : class { _ = x - x; _ = x - y; _ = x - z; _ = y - x; _ = y - y; _ = y - z; _ = z - x; _ = z - y; _ = z - z; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (44,17): warning CS8620: Argument of type 'C<T?>' cannot be used for parameter 'b' of type 'C<T>' in 'C<T> C<T>.operator -(C<T> a, C<T> b)' due to differences in the nullability of reference types. // _ = y - z; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C<T?>", "C<T>", "b", "C<T> C<T>.operator -(C<T> a, C<T> b)").WithLocation(44, 17), // (46,17): warning CS8620: Argument of type 'C<T>' cannot be used for parameter 'b' of type 'C<T?>' in 'C<T?> C<T?>.operator -(C<T?> a, C<T?> b)' due to differences in the nullability of reference types. // _ = z - y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<T>", "C<T?>", "b", "C<T?> C<T?>.operator -(C<T?> a, C<T?> b)").WithLocation(46, 17)); } // C<T~> operator op(C<T~>, C<T>) [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_04() { var source = @"class C<T> { #nullable disable public static C<T> operator *( C<T> a, #nullable enable C<T> b) => a; } class Program { static void M1<T>( #nullable disable C<T> a, #nullable enable C<T> b) { _ = a * a; _ = a * b; _ = b * a; _ = b * b; } static void M2<T>( #nullable disable C<T> c, #nullable enable C<T> d) where T : class? { _ = c * c; _ = c * d; _ = d * c; _ = d * d; } static void M3<T>( #nullable disable C<T> x, #nullable enable C<T> y, C<T?> z) where T : class { _ = x * x; _ = x * y; _ = x * z; _ = y * x; _ = y * y; _ = y * z; _ = z * x; _ = z * y; _ = z * z; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (47,17): warning CS8620: Argument of type 'C<T?>' cannot be used for parameter 'b' of type 'C<T>' in 'C<T> C<T>.operator *(C<T> a, C<T> b)' due to differences in the nullability of reference types. // _ = y * z; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C<T?>", "C<T>", "b", "C<T> C<T>.operator *(C<T> a, C<T> b)").WithLocation(47, 17), // (49,17): warning CS8620: Argument of type 'C<T>' cannot be used for parameter 'b' of type 'C<T?>' in 'C<T?> C<T?>.operator *(C<T?> a, C<T?> b)' due to differences in the nullability of reference types. // _ = z * y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<T>", "C<T?>", "b", "C<T?> C<T?>.operator *(C<T?> a, C<T?> b)").WithLocation(49, 17)); } // C<T~> operator op(C<T~>, C<T~>) where T : class? [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_05() { var source = @"#nullable enable class C<T> where T : class? { #nullable disable public static C<T> operator +(C<T> a, C<T> b) => a; } class Program { static void M1<T>( #nullable disable C<T> a, #nullable enable C<T> b) where T : class? { _ = a + a; _ = a + b; _ = b + a; _ = b + b; } static void M2<T>( #nullable disable C<T> x, #nullable enable C<T> y, C<T?> z) where T : class { _ = x + x; _ = x + y; _ = x + z; _ = y + x; _ = y + y; _ = y + z; _ = z + x; _ = z + y; _ = z + z; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (34,17): warning CS8620: Argument of type 'C<T?>' cannot be used for parameter 'b' of type 'C<T>' in 'C<T> C<T>.operator +(C<T> a, C<T> b)' due to differences in the nullability of reference types. // _ = y + z; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C<T?>", "C<T>", "b", "C<T> C<T>.operator +(C<T> a, C<T> b)").WithLocation(34, 17), // (36,17): warning CS8620: Argument of type 'C<T>' cannot be used for parameter 'b' of type 'C<T?>' in 'C<T?> C<T?>.operator +(C<T?> a, C<T?> b)' due to differences in the nullability of reference types. // _ = z + y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<T>", "C<T?>", "b", "C<T?> C<T?>.operator +(C<T?> a, C<T?> b)").WithLocation(36, 17)); } // C<T!> operator op(C<T!>, C<T!>) where T : class? [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_06() { var source = @"#nullable enable class C<T> where T : class? { public static C<T> operator -(C<T> a, C<T> b) => a; } class Program { static void M1<T>( #nullable disable C<T> a, #nullable enable C<T> b) where T : class? { _ = a - a; _ = a - b; _ = b - a; _ = b - b; } static void M2<T>( #nullable disable C<T> x, #nullable enable C<T> y, C<T?> z) where T : class { _ = x - x; _ = x - y; _ = x - z; _ = y - x; _ = y - y; _ = y - z; _ = z - x; _ = z - y; _ = z - z; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (33,17): warning CS8620: Argument of type 'C<T?>' cannot be used for parameter 'b' of type 'C<T>' in 'C<T> C<T>.operator -(C<T> a, C<T> b)' due to differences in the nullability of reference types. // _ = y - z; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C<T?>", "C<T>", "b", "C<T> C<T>.operator -(C<T> a, C<T> b)").WithLocation(33, 17), // (35,17): warning CS8620: Argument of type 'C<T>' cannot be used for parameter 'b' of type 'C<T?>' in 'C<T?> C<T?>.operator -(C<T?> a, C<T?> b)' due to differences in the nullability of reference types. // _ = z - y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<T>", "C<T?>", "b", "C<T?> C<T?>.operator -(C<T?> a, C<T?> b)").WithLocation(35, 17)); } // C<T~> operator op(C<T!>, C<T~>) where T : class? [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_07() { var source = @"#nullable enable class C<T> where T : class? { #nullable disable public static C<T> operator *( #nullable enable C<T> a, #nullable disable C<T> b) => a; } class Program { static void M1<T>( #nullable disable C<T> a, #nullable enable C<T> b) where T : class? { _ = a * a; _ = a * b; _ = b * a; _ = b * b; } static void M2<T>( #nullable disable C<T> x, #nullable enable C<T> y, C<T?> z) where T : class { _ = x * x; _ = x * y; _ = x * z; _ = y * x; _ = y * y; _ = y * z; _ = z * x; _ = z * y; _ = z * z; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (38,17): warning CS8620: Argument of type 'C<T?>' cannot be used for parameter 'b' of type 'C<T>' in 'C<T> C<T>.operator *(C<T> a, C<T> b)' due to differences in the nullability of reference types. // _ = y * z; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "z").WithArguments("C<T?>", "C<T>", "b", "C<T> C<T>.operator *(C<T> a, C<T> b)").WithLocation(38, 17), // (40,17): warning CS8620: Argument of type 'C<T>' cannot be used for parameter 'b' of type 'C<T?>' in 'C<T?> C<T?>.operator *(C<T?> a, C<T?> b)' due to differences in the nullability of reference types. // _ = z * y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("C<T>", "C<T?>", "b", "C<T?> C<T?>.operator *(C<T?> a, C<T?> b)").WithLocation(40, 17)); } // C<T~> operator op(C<T~>, C<T~>) where T : class [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_08() { var source = @"#nullable enable class C<T> where T : class { #nullable disable public static C<T> operator /(C<T> a, C<T> b) => a; } class Program { static void M<T>( #nullable disable C<T> x, #nullable enable C<T> y) where T : class { _ = x / x; _ = x / y; _ = y / x; _ = y / y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } // C<T!> operator op(C<T!>, C<T!>) where T : class [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_09() { var source = @"#nullable enable class C<T> where T : class { public static C<T> operator &(C<T> a, C<T> b) => a; } class Program { static void M<T>( #nullable disable C<T> x, #nullable enable C<T> y) where T : class { _ = x & x; _ = x & y; _ = y & x; _ = y & y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } // C<T~> operator op(C<T!>, C<T~>) where T : class [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/35057")] public void Operator_10() { var source = @"#nullable enable class C<T> where T : class { #nullable disable public static C<T> operator |( #nullable enable C<T> a, #nullable disable C<T> b) => a; } class Program { static void M<T>( #nullable disable C<T> x, #nullable enable C<T> y) where T : class { _ = x | x; _ = x | y; _ = y | x; _ = y | y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/39361")] public void Operator_11() { var source = @" #nullable enable using System; struct S { public static implicit operator DateTime?(S? value) => default; bool M1(S? x1, DateTime y1) { return x1 == y1; } bool M2(DateTime? x2, DateTime y2) { return x2 == y2; } bool M3(DateTime x3, DateTime? y3) { return x3 == y3; } bool M4(DateTime x4, S? y4) { return x4 == y4; } bool M5(DateTime? x5, DateTime? y5) { return x5 == y5; } bool M6(S? x6, DateTime? y6) { return x6 == y6; } bool M7(DateTime? x7, S? y7) { return x7 == y7; } bool M8(DateTime x8, S y8) { return x8 == y8; } bool M9(S x9, DateTime y9) { return x9 == y9; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(35057, "https://github.com/dotnet/roslyn/issues/39361")] public void Operator_12() { var source = @" #nullable enable struct S { public static bool operator-(S value) => default; bool? M1(S? x1) { return -x1; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_NonNullExpr_LiteralNull_WarnsWhenTrue(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M(string s) {{ if ({equalsMethodName}(s, null)) {{ _ = s.ToString(); // 1 }} else {{ _ = s.ToString(); }} }} static void M2(string s) {{ if ({equalsMethodName}(null, s)) {{ _ = s.ToString(); // 2 }} else {{ _ = s.ToString(); }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17), // (21,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(21, 17)); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_NonNullExpr_NonNullExpr_NoWarning(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M(string s1, string s2) {{ if ({equalsMethodName}(s1, s2)) {{ _ = s1.ToString(); _ = s2.ToString(); }} else {{ _ = s1.ToString(); _ = s2.ToString(); }} }} static void M2(string s1, string s2) {{ if ({equalsMethodName}(s2, s1)) {{ _ = s1.ToString(); _ = s2.ToString(); }} else {{ _ = s1.ToString(); _ = s2.ToString(); }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38010, "https://github.com/dotnet/roslyn/issues/38010")] public void ReferenceEquals_IncompleteCall() { var source = @" #nullable enable class C { static void M() { ReferenceEquals( } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'objA' of 'object.ReferenceEquals(object, object)' // ReferenceEquals( Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "ReferenceEquals").WithArguments("objA", "object.ReferenceEquals(object, object)").WithLocation(7, 9), // (7,25): error CS1026: ) expected // ReferenceEquals( Diagnostic(ErrorCode.ERR_CloseParenExpected, "").WithLocation(7, 25), // (7,25): error CS1002: ; expected // ReferenceEquals( Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(7, 25)); } [Fact] [WorkItem(38010, "https://github.com/dotnet/roslyn/issues/38010")] public void EqualsMethod_BadArgCount() { var source = @" #nullable enable class C { void M(System.IEquatable<string> eq1) { object.Equals(); object.Equals(0); object.Equals(null, null, null); object.ReferenceEquals(); object.ReferenceEquals(1); object.ReferenceEquals(null, null, null); eq1.Equals(); eq1.Equals(true, false); this.Equals(); this.Equals(null, null); } public override bool Equals(object other) { return base.Equals(other); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,7): warning CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class C Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "C").WithArguments("C").WithLocation(3, 7), // (7,16): error CS1501: No overload for method 'Equals' takes 0 arguments // object.Equals(); Diagnostic(ErrorCode.ERR_BadArgCount, "Equals").WithArguments("Equals", "0").WithLocation(7, 16), // (8,9): error CS0120: An object reference is required for the non-static field, method, or property 'object.Equals(object)' // object.Equals(0); Diagnostic(ErrorCode.ERR_ObjectRequired, "object.Equals").WithArguments("object.Equals(object)").WithLocation(8, 9), // (9,16): error CS1501: No overload for method 'Equals' takes 3 arguments // object.Equals(null, null, null); Diagnostic(ErrorCode.ERR_BadArgCount, "Equals").WithArguments("Equals", "3").WithLocation(9, 16), // (11,16): error CS7036: There is no argument given that corresponds to the required formal parameter 'objA' of 'object.ReferenceEquals(object, object)' // object.ReferenceEquals(); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "ReferenceEquals").WithArguments("objA", "object.ReferenceEquals(object, object)").WithLocation(11, 16), // (12,16): error CS7036: There is no argument given that corresponds to the required formal parameter 'objB' of 'object.ReferenceEquals(object, object)' // object.ReferenceEquals(1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "ReferenceEquals").WithArguments("objB", "object.ReferenceEquals(object, object)").WithLocation(12, 16), // (13,16): error CS1501: No overload for method 'ReferenceEquals' takes 3 arguments // object.ReferenceEquals(null, null, null); Diagnostic(ErrorCode.ERR_BadArgCount, "ReferenceEquals").WithArguments("ReferenceEquals", "3").WithLocation(13, 16), // (15,13): error CS1501: No overload for method 'Equals' takes 0 arguments // eq1.Equals(); Diagnostic(ErrorCode.ERR_BadArgCount, "Equals").WithArguments("Equals", "0").WithLocation(15, 13), // (16,9): error CS0176: Member 'object.Equals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead // eq1.Equals(true, false); Diagnostic(ErrorCode.ERR_ObjectProhibited, "eq1.Equals").WithArguments("object.Equals(object, object)").WithLocation(16, 9), // (18,14): error CS1501: No overload for method 'Equals' takes 0 arguments // this.Equals(); Diagnostic(ErrorCode.ERR_BadArgCount, "Equals").WithArguments("Equals", "0").WithLocation(18, 14), // (19,9): error CS0176: Member 'object.Equals(object, object)' cannot be accessed with an instance reference; qualify it with a type name instead // this.Equals(null, null); Diagnostic(ErrorCode.ERR_ObjectProhibited, "this.Equals").WithArguments("object.Equals(object, object)").WithLocation(19, 9)); } [Fact] [WorkItem(38010, "https://github.com/dotnet/roslyn/issues/38010")] public void EqualsMethod_DefaultArgument_01() { var source = @" #nullable enable class C // 1 { static void M(C c1) { if (c1.Equals()) { _ = c1.ToString(); // 2 } if (c1.Equals(null)) { _ = c1.ToString(); // 3 } } public override bool Equals(object? other = null) => false; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,7): warning CS0659: 'C' overrides Object.Equals(object o) but does not override Object.GetHashCode() // class C // 1 Diagnostic(ErrorCode.WRN_EqualsWithoutGetHashCode, "C").WithArguments("C").WithLocation(3, 7), // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(9, 17), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(14, 17)); } [Fact] [WorkItem(38010, "https://github.com/dotnet/roslyn/issues/38010")] public void EqualsMethod_DefaultArgument_02() { var source = @" #nullable enable class C : System.IEquatable<C> { static void M(C c1) { if (c1.Equals()) { _ = c1.ToString(); // 1 } if (c1.Equals(null)) { _ = c1.ToString(); // 2 } } public bool Equals(C? other = null) => false; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(9, 17), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(14, 17)); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_MaybeNullExpr_MaybeNullExpr_Warns(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M(string? s1, string? s2) {{ if ({equalsMethodName}(s1, s2)) {{ _ = s1.ToString(); // 1 _ = s2.ToString(); // 2 }} else {{ _ = s1.ToString(); // 3 _ = s2.ToString(); // 4 }} }} static void M2(string? s1, string? s2) {{ if ({equalsMethodName}(s2, s1)) {{ _ = s1.ToString(); // 5 _ = s2.ToString(); // 6 }} else {{ _ = s1.ToString(); // 7 _ = s2.ToString(); // 8 }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(9, 17), // (10,17): warning CS8602: Dereference of a possibly null reference. // _ = s2.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(10, 17), // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(14, 17), // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = s2.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(15, 17), // (23,17): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(23, 17), // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = s2.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(24, 17), // (28,17): warning CS8602: Dereference of a possibly null reference. // _ = s1.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(28, 17), // (29,17): warning CS8602: Dereference of a possibly null reference. // _ = s2.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2").WithLocation(29, 17)); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_NonNullExpr_ConstantNull_WarnsWhenTrue(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M1(string s) {{ const string? s2 = null; if ({equalsMethodName}(s, s2)) {{ _ = s.ToString(); // 1 }} else {{ _ = s.ToString(); }} }} static void M2(string s) {{ const string? s2 = null; if ({equalsMethodName}(s2, s)) {{ _ = s.ToString(); // 2 }} else {{ _ = s.ToString(); }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 17), // (23,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(23, 17)); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_MaybeNullExpr_ConstantNull_NoWarningWhenFalse(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M1(string? s) {{ const string? s2 = null; if ({equalsMethodName}(s, s2)) {{ _ = s.ToString(); // 1 }} else {{ _ = s.ToString(); }} }} static void M2(string? s) {{ const string? s2 = null; if ({equalsMethodName}(s2, s)) {{ _ = s.ToString(); // 2 }} else {{ _ = s.ToString(); }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (10,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 17), // (23,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(23, 17)); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_NonNullExpr_MaybeNullExpr_NoWarning(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M1(string s) {{ string? s2 = null; if ({equalsMethodName}(s, s2)) {{ _ = s.ToString(); }} else {{ _ = s.ToString(); }} }} static void M2(string s) {{ string? s2 = null; if ({equalsMethodName}(s2, s)) {{ _ = s.ToString(); }} else {{ _ = s.ToString(); }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue(string equalsMethodName) { var source = $@" #nullable enable class C {{ static void M1(string? s) {{ if ({equalsMethodName}(s, """")) {{ _ = s.ToString(); }} else {{ _ = s.ToString(); // 1 }} }} static void M2(string? s) {{ if ({equalsMethodName}("""", s)) {{ _ = s.ToString(); }} else {{ _ = s.ToString(); // 2 }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 17), // (25,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(25, 17)); } [Theory] [InlineData("object.Equals")] [InlineData("object.ReferenceEquals")] [WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void StaticEqualsMethod__NullableValueTypeExpr_ValueTypeExpr_NoWarningWhenTrue(string equalsMethodName) { var source = $@" #nullable enable class C {{ int? i = 42; static void M1(C? c) {{ if ({equalsMethodName}(c?.i, 42)) {{ _ = c.i.Value.ToString(); }} else {{ _ = c.i.Value.ToString(); // 1 }} }} static void M2(C? c) {{ if ({equalsMethodName}(42, c?.i)) {{ _ = c.i.Value.ToString(); }} else {{ _ = c.i.Value.ToString(); // 2 }} }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,17): warning CS8602: Dereference of a possibly null reference. // _ = c.i.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(14, 17), // (14,17): warning CS8629: Nullable value type may be null. // _ = c.i.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.i").WithLocation(14, 17), // (26,17): warning CS8602: Dereference of a possibly null reference. // _ = c.i.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(26, 17), // (26,17): warning CS8629: Nullable value type may be null. // _ = c.i.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "c.i").WithLocation(26, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" #nullable enable class C { static void M1(string? s) { if ("""".Equals(s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceEqualsMethod_NonNullExpr_LiteralNull_NoWarningWhenTrue() { var source = @" #nullable enable class C { static void M1(string s) { if (s.Equals(null)) { _ = s.ToString(); // 1 } else { _ = s.ToString(); } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceEqualsMethod_IEquatableMissing_MaybeNullExpr_NonNullExpr_Warns() { var source = @" #nullable enable class C { static void M1(string? s) { if ("""".Equals(s)) { _ = s.ToString(); // 1 } else { _ = s.ToString(); // 2 } } }"; var expected = new[] { // (9,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(9, 17), // (13,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 17) }; var comp = CreateCompilation(source); comp.MakeTypeMissing(WellKnownType.System_IEquatable_T); comp.VerifyDiagnostics(expected); comp = CreateCompilation(source); comp.MakeMemberMissing(WellKnownMember.System_IEquatable_T__Equals); comp.VerifyDiagnostics(expected); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceEqualsMethod_IEquatableEqualsOverloaded_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" #pragma warning disable CS0436 namespace System { interface IEquatable<in T> { bool Equals(T t, int compareFlags); bool Equals(T t); } } #nullable enable class C : System.IEquatable<C?> { public bool Equals(C? other) => throw null!; public bool Equals(C? other, int compareFlags) => throw null!; static void M1(C? c) { C c1 = new C(); if (c1.Equals(c)) { _ = c.ToString(); } else { _ = c.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (27,17): warning CS8602: Dereference of a possibly null reference. // _ = c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(27, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceEqualsMethod_IEquatableEqualsBadSignature_MaybeNullExpr_NonNullExpr_Warns() { var source = @" #pragma warning disable CS0436 namespace System { interface IEquatable<in T> { bool Equals(T t, int compareFlags); } } #nullable enable class C : System.IEquatable<C?> { public bool Equals(C? c) => throw null!; public bool Equals(C? c, int compareFlags) => throw null!; static void M1(C? c) { C c1 = new C(); if (c1.Equals(c)) { _ = c.ToString(); // 1 } else { _ = c.ToString(); // 2 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (22,17): warning CS8602: Dereference of a possibly null reference. // _ = c.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(22, 17), // (26,17): warning CS8602: Dereference of a possibly null reference. // _ = c.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(26, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void IEquatableEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" using System; #nullable enable class C { static void M1(IEquatable<string?> equatable, string? s) { if (equatable.Equals(s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void IEquatableEqualsMethod_ClassConstrainedGeneric() { var source = @" using System; #nullable enable class C { static void M1<T>(IEquatable<T?> equatable, T? t) where T : class { if (equatable.Equals(t)) { _ = t.ToString(); } else { _ = t.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(15, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_UnconstrainedGeneric() { var source = @" using System; #nullable enable class C { static void M1<T>(IEquatable<T?> equatable, T? t) where T : class { if (equatable.Equals(t)) { _ = t.ToString(); } else { _ = t.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(15, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void IEquatableEqualsMethod_NullableVariance() { var source = @" using System; #nullable enable class C : IEquatable<string> { public bool Equals(string? s) => throw null!; static void M1(C c, string? s) { if (c.Equals(s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ImplInBaseType() { var source = @" using System; #nullable enable class B : IEquatable<string> { public bool Equals(string? s) => throw null!; } class C : B { static void M1(C c, string? s) { if (c.Equals(s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (20,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(20, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ExplicitImpl() { var source = @" using System; #nullable enable class C : IEquatable<string> { public bool Equals(string? s) => throw null!; bool IEquatable<string>.Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() // 1 : s.ToString(); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 15), // (14,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ImplicitImplInBaseType_ExplicitImplInDerivedType() { var source = @" using System; #nullable enable class B : IEquatable<string> { public bool Equals(string? s) => throw null!; } class C : B, IEquatable<string> { bool IEquatable<string>.Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ImplicitImplInBaseType_ExplicitImplInDerivedType_02() { var source = @" using System; #nullable enable class B : IEquatable<string> { public virtual bool Equals(string? s) => throw null!; } class C : B, IEquatable<string> { bool IEquatable<string>.Equals(string? s) => throw null!; public override bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(19, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ExplicitImplInDerivedType() { var source = @" using System; #nullable enable class B { public bool Equals(string? s) => throw null!; } class C : B, IEquatable<string> { bool IEquatable<string>.Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() // 1 : s.ToString(); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_Override() { var source = @" using System; #nullable enable class B : IEquatable<string> { public virtual bool Equals(string? s) => throw null!; } class C : B { public override bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ExplicitImplAboveNonImplementing() { var source = @" using System; #nullable enable class A : IEquatable<string> { bool IEquatable<string>.Equals(string? s) => throw null!; } class B : A { } class C : B { public bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() // 1 : s.ToString(); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 15), // (19,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(19, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_Complex() { var source = @" using System; #nullable enable class A { } class B { public virtual bool Equals(string? s) => throw null!; } class C : B, IEquatable<string> { } class D : C, IEquatable<string> { bool IEquatable<string>.Equals(string? s) => throw null!; public override bool Equals(string? s) => throw null!; } class E : D { static void M1(A a, string? s) { _ = a.Equals(s) ? s.ToString() : s.ToString(); // 1 } static void M2(B b, string? s) { _ = b.Equals(s) ? s.ToString() // 2 : s.ToString(); // 3 } static void M3(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 4 } static void M4(D d, string? s) { _ = d.Equals(s) ? s.ToString() : s.ToString(); // 5 } static void M5(E e, string? s) { _ = e.Equals(s) ? s.ToString() : s.ToString(); // 6 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (31,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(31, 15), // (37,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(37, 15), // (38,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(38, 15), // (45,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(45, 15), // (52,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(52, 15), // (59,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(59, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_VirtualImpl_ExplicitImpl_Override() { var source = @" using System; #nullable enable class A : IEquatable<string> { public virtual bool Equals(string? s) => throw null!; } class B : A, IEquatable<string> { bool IEquatable<string>.Equals(string? s) => throw null!; } class C : B { public override bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (24,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(24, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_DefaultImplementation_01() { var source = @" using System; #nullable enable interface I1 : IEquatable<string?> { bool IEquatable<string?>.Equals(string? s) => throw null!; void M1(string? s) { _ = this.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (14,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(14, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_DefaultImplementation_02() { var source = @" using System; #nullable enable interface I1 : IEquatable<string?> { bool IEquatable<string?>.Equals(string? s) => throw null!; } class C : I1 { void M1(string? s) { _ = this.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_DefaultImplementation_03() { var source = @" #nullable enable using System; interface I1 : IEquatable<string?> { bool IEquatable<string?>.Equals(string? s) => throw null!; } class C : I1 { bool Equals(string? s) => throw null!; void M1(string? s) { _ = this.Equals(s) ? s.ToString() // 1 : s.ToString(); // 2 } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_SkipIntermediateBasesAndOverrides() { var source = @" using System; #nullable enable class A : IEquatable<string?> { public virtual bool Equals(string? s) => throw null!; } class B : A, IEquatable<string?> { bool IEquatable<string?>.Equals(string? s) => throw null!; } class C : B { public override bool Equals(string? s) => throw null!; } class D : C { } class E : D { static void M1(E e, string? s) { _ = e.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (29,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(29, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_CallableExplicitImplementation() { var vbSource = @" Imports System Public Class C Implements IEquatable(Of String) Public Function Equals(str As String) As Boolean Implements IEquatable(Of String).Equals Return False End Function End Class "; var source = @" #nullable enable class Program { void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var vbComp = CreateVisualBasicCompilation(vbSource); var comp = CreateCompilation(source, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_CallableExplicitImplementation_MismatchedName() { var vbSource = @" Imports System Public Class C Implements IEquatable(Of String) Public Function MyEquals(str As String) As Boolean Implements IEquatable(Of String).Equals Return False End Function End Class "; var source = @" #nullable enable class Program { void M1(C c, string? s) { _ = c.MyEquals(s) ? s.ToString() : s.ToString(); // 1 } }"; var vbComp = CreateVisualBasicCompilation(vbSource); var comp = CreateCompilation(source, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (10,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(10, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_CallableExplicitImplementation_Override() { var vbSource = @" Imports System Public Class B Implements IEquatable(Of String) Public Overridable Function MyEquals(str As String) As Boolean Implements IEquatable(Of String).Equals Return False End Function End Class "; var source = @" #nullable enable class C : B { public override bool MyEquals(string? str) => false; void M1(C c, string? s) { _ = c.MyEquals(s) ? s.ToString() : s.ToString(); // 1 } }"; var vbComp = CreateVisualBasicCompilation(vbSource); var comp = CreateCompilation(source, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (12,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(12, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_CallableExplicitImplementation_ImplementsViaDerivedClass() { var vbSource = @" Imports System Interface IMyEquatable Function Equals(str As String) As Boolean End Interface Public Class B Implements IMyEquatable Public Shadows Function Equals(str As String) As Boolean Implements IMyEquatable.Equals Return False End Function End Class "; var source = @" #nullable enable using System; class C : B, IEquatable<string> { } class Program { void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var vbComp = CreateVisualBasicCompilation(vbSource); var comp = CreateCompilation(source, references: new[] { vbComp.EmitToImageReference() }); comp.VerifyDiagnostics( // (13,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEquatableEqualsMethod_ImplInNonImplementingBase() { var source = @" using System; #nullable enable class B { public bool Equals(string? s) => throw null!; } class C : B, IEquatable<string?> { static void M1(C c, string? s) { if (c.Equals(s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (21,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(21, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceEqualsMethod_NullableVariance_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" using System; #nullable enable class C : IEquatable<C> { public bool Equals(C? other) => throw null!; static void M1(C? c2) { C c1 = new C(); if (c1.Equals(c2)) { _ = c2.ToString(); } else { _ = c2.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = c2.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c2").WithLocation(18, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceObjectEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" #nullable enable class C { static void M1(object? o) { if ("""".Equals(o)) { _ = o.ToString(); } else { _ = o.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,17): warning CS8602: Dereference of a possibly null reference. // _ = o.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(13, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceObjectEqualsMethod_MaybeNullExprReferenceConversion_NonNullExpr_NoWarningWhenTrue() { var source = @" #nullable enable class C { static void M1(string? s) { if ("""".Equals((object?)s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(13, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void InstanceObjectEqualsMethod_ConditionalAccessExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" #nullable enable class C { object? F = default; static void M1(C? c) { C c1 = new C(); if (c1.Equals(c?.F)) { _ = c.F.ToString(); } else { _ = c.F.ToString(); // 1, 2 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (16,17): warning CS8602: Dereference of a possibly null reference. // _ = c.F.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c").WithLocation(16, 17), // (16,17): warning CS8602: Dereference of a possibly null reference. // _ = c.F.ToString(); // 1, 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c.F").WithLocation(16, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void IEqualityComparerEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" using System.Collections.Generic; #nullable enable class C { static void M1(IEqualityComparer<string?> comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEqualityComparerEqualsMethod_Impl() { var source = @" using System.Collections.Generic; #nullable enable public class Comparer : IEqualityComparer<string> { public bool Equals(string? s1, string? s2) => false; public int GetHashCode(string s) => s.GetHashCode(); } class C { static void M(Comparer comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (22,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(22, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEqualityComparerEqualsMethod_ImplInBaseType() { var source = @" using System.Collections.Generic; #nullable enable public class Comparer : IEqualityComparer<string> { public bool Equals(string? s1, string? s2) => false; public int GetHashCode(string s) => s.GetHashCode(); } public class Comparer2 : Comparer { } class C { static void M(Comparer2 comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(24, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void IEqualityComparerEqualsMethod_ImplInNonImplementingClass() { var source = @" using System.Collections.Generic; #nullable enable public class Comparer { public bool Equals(string? s1, string? s2) => false; public int GetHashCode(string s) => s.GetHashCode(); } public class Comparer2 : Comparer, IEqualityComparer<string> { } class C { static void M(Comparer2 comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (24,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(24, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void EqualityComparerEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" using System.Collections.Generic; #nullable enable class C { static void M1(EqualityComparer<string?> comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void EqualityComparerEqualsMethod_IEqualityComparerMissing_MaybeNullExpr_NonNullExpr_Warns() { var source = @" using System.Collections.Generic; #nullable enable class C { static void M1(EqualityComparer<string?> comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); // 1 } else { _ = s.ToString(); // 2 } } }"; var comp = CreateCompilation(source); comp.MakeTypeMissing(WellKnownType.System_Collections_Generic_IEqualityComparer_T); comp.VerifyDiagnostics( // (11,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(11, 17), // (15,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(15, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void IEqualityComparer_SubInterfaceEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" using System.Collections.Generic; #nullable enable interface MyEqualityComparer : IEqualityComparer<string?> { } class C { static void M1(MyEqualityComparer comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void IEqualityComparer_SubSubInterfaceEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" using System.Collections.Generic; #nullable enable interface MyEqualityComparer : IEqualityComparer<string?> { } interface MySubEqualityComparer : MyEqualityComparer { } class C { static void M1(MySubEqualityComparer comparer, string? s) { if (comparer.Equals("""", s)) { _ = s.ToString(); } else { _ = s.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,17): warning CS8602: Dereference of a possibly null reference. // _ = s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(19, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void OverrideEqualsMethod_MaybeNullExpr_NonNullExpr_NoWarningWhenTrue() { var source = @" #nullable enable class C { public override bool Equals(object? other) => throw null!; public override int GetHashCode() => throw null!; static void M1(C? c1) { C c2 = new C(); if (c2.Equals(c1)) { _ = c1.ToString(); } else { _ = c1.ToString(); // 1 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(17, 17)); } [Fact, WorkItem(35816, "https://github.com/dotnet/roslyn/issues/35816")] public void NotImplementingEqualsMethod_MaybeNullExpr_NonNullExpr_Warns() { var source = @" #nullable enable class C { public bool Equals(C? other) => throw null!; static void M1(C? c1) { C c2 = new C(); if (c2.Equals(c1)) { _ = c1.ToString(); // 1 } else { _ = c1.ToString(); // 2 } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(12, 17), // (16,17): warning CS8602: Dereference of a possibly null reference. // _ = c1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(16, 17)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void NotImplementingEqualsMethod_Virtual() { var source = @" #nullable enable class C { public virtual bool Equals(C? other) => throw null!; static void M1(C? c1) { C c2 = new C(); _ = c2.Equals(c1) ? c1.ToString() // 1 : c1.ToString(); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,15): warning CS8602: Dereference of a possibly null reference. // ? c1.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(11, 15), // (12,15): warning CS8602: Dereference of a possibly null reference. // : c1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "c1").WithLocation(12, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void EqualsMethod_ImplInNonImplementingClass_Override() { var source = @" using System; #nullable enable class B { public virtual bool Equals(string? s) => throw null!; } class C : B, IEquatable<string> { public override bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void EqualsMethod_OverrideImplementsInterfaceMethod_MultipleOverride() { var source = @" #nullable enable using System; class A { public virtual bool Equals(string? s) => throw null!; } class B : A, IEquatable<string> { public override bool Equals(string? s) => throw null!; } class C : B { public override bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = c.Equals(s) ? s.ToString() : s.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (23,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(23, 15)); } [Fact, WorkItem(40577, "https://github.com/dotnet/roslyn/issues/40577")] public void EqualsMethod_OverrideImplementsInterfaceMethod_CastToBaseType() { var source = @" #nullable enable using System; class B { public virtual bool Equals(string? s) => throw null!; } class C : B, IEquatable<string> { public override bool Equals(string? s) => throw null!; static void M1(C c, string? s) { _ = ((B)c).Equals(s) ? s.ToString() // 1 : s.ToString(); // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (17,15): warning CS8602: Dereference of a possibly null reference. // ? s.ToString() // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(17, 15), // (18,15): warning CS8602: Dereference of a possibly null reference. // : s.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s").WithLocation(18, 15)); } [Fact, WorkItem(42960, "https://github.com/dotnet/roslyn/issues/42960")] public void EqualsMethod_IncompleteBaseClause() { var source = @" class C : { void M(C? other) { if (Equals(other)) { other.ToString(); } if (this.Equals(other)) { other.ToString(); } } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (2,10): error CS1031: Type expected // class C : Diagnostic(ErrorCode.ERR_TypeExpected, "").WithLocation(2, 10), // (6,13): error CS0120: An object reference is required for the non-static field, method, or property 'object.Equals(object)' // if (Equals(other)) { other.ToString(); } Diagnostic(ErrorCode.ERR_ObjectRequired, "Equals").WithArguments("object.Equals(object)").WithLocation(6, 13), // (6,30): warning CS8602: Dereference of a possibly null reference. // if (Equals(other)) { other.ToString(); } Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "other").WithLocation(6, 30)); } [Fact, WorkItem(42960, "https://github.com/dotnet/roslyn/issues/42960")] public void EqualsMethod_ErrorBaseClause() { var source = @" class C : ERROR { void M(C? other) { if (Equals(other)) { other.ToString(); } if (this.Equals(other)) { other.ToString(); } } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (2,11): error CS0246: The type or namespace name 'ERROR' could not be found (are you missing a using directive or an assembly reference?) // class C : ERROR Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "ERROR").WithArguments("ERROR").WithLocation(2, 11), // (6,13): error CS0120: An object reference is required for the non-static field, method, or property 'object.Equals(object)' // if (Equals(other)) { other.ToString(); } Diagnostic(ErrorCode.ERR_ObjectRequired, "Equals").WithArguments("object.Equals(object)").WithLocation(6, 13), // (6,30): warning CS8602: Dereference of a possibly null reference. // if (Equals(other)) { other.ToString(); } Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "other").WithLocation(6, 30)); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirective() { var source = @" class C { void M(object? o1) { object o2 = o1; } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (6,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object o2 = o1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "o1").WithLocation(6, 21)); Assert.True(IsNullableAnalysisEnabled(comp, "C.M")); } [Theory] [InlineData("")] [InlineData("annotations")] [InlineData("warnings")] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirective_WithNullDisables(string directive) { var source = $@" #nullable disable {directive} class C {{ void M(object? o1) {{ object o2 = o1; }} }}"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(directive == "warnings" ? DiagnosticDescription.None : new[] { // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18) }); Assert.Equal(directive == "annotations", IsNullableAnalysisEnabled(comp, "C.M")); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableEnable() { ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableDirective("", // (7,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object o2 = o1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "o1").WithLocation(7, 21)); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableEnableAnnotations() { ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableDirective("annotations"); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableEnableWarnings() { ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableDirective("warnings", // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18)); } private static void ShouldRunNullableWalker_GlobalDirectiveOff_WithNullableDirective(string directive, params DiagnosticDescription[] expectedDiagnostics) { var source = $@" #nullable enable {directive} class C {{ void M(object? o1) {{ object o2 = o1; }} }}"; var comp = CreateCompilation(source, options: WithNullableDisable()); comp.VerifyDiagnostics(expectedDiagnostics); Assert.Equal(directive != "annotations", IsNullableAnalysisEnabled(comp, "C.M")); } [Theory] [InlineData("disable")] [InlineData("disable annotations")] [InlineData("disable warnings")] [InlineData("restore")] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_WithNonInfluencingNullableDirectives(string directive) { var source = $@" #nullable {directive} class C {{ void M(object? o1) {{ object o2 = o1; }} }}"; var comp = CreateCompilation(source, options: WithNullableDisable()); comp.VerifyDiagnostics( // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18)); Assert.False(IsNullableAnalysisEnabled(comp, "C.M")); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles_NullableEnable() { ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles("", // (4,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 18), // (7,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object o4 = o3; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "o3").WithLocation(7, 21)); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles_NullableEnableAnnotations() { ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles("annotations", // (4,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 18)); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles_NullableEnableWarnings() { ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles("warnings", // (4,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 18), // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o3) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18)); } private static void ShouldRunNullableWalker_GlobalDirectiveOff_MultipleFiles(string directive, params DiagnosticDescription[] expectedDiagnostics) { var source1 = @" class C { void M(object? o1) { object o2 = o1; } }"; var source2 = $@" #nullable enable {directive} class D {{ void M(object? o3) {{ object o4 = o3; }} }}"; var comp = CreateCompilation(new[] { source1, source2 }, options: WithNullableDisable()); comp.VerifyDiagnostics(expectedDiagnostics); Assert.NotEqual(directive == "annotations", IsNullableAnalysisEnabled(comp, "D.M")); } [Fact] [WorkItem(36131, "https://github.com/dotnet/roslyn/issues/36131")] public void ShouldRunNullableWalker_GlobalDirectiveOff_MultipleDirectivesSingleFile() { var source = @" #nullable disable class C { void M(object? o1) { #nullable enable object o2 = o1; #nullable restore } }"; var comp = CreateCompilation(source, options: WithNullableDisable()); comp.VerifyDiagnostics( // (5,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // void M(object? o1) Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 18), // (8,21): warning CS8600: Converting null literal or possible null value to non-nullable type. // object o2 = o1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "o1").WithLocation(8, 21)); Assert.True(IsNullableAnalysisEnabled(comp, "C.M")); } [Theory] // 2 states * 3 states * 3 states = 18 combinations [InlineData("locationNonNull", "valueNonNull", "comparandNonNull", true)] [InlineData("locationNonNull", "valueNonNull", "comparandMaybeNull", true)] [InlineData("locationNonNull", "valueNonNull", "null", true)] [InlineData("locationNonNull", "valueMaybeNull", "comparandNonNull", false)] [InlineData("locationNonNull", "valueMaybeNull", "comparandMaybeNull", false)] [InlineData("locationNonNull", "valueMaybeNull", "null", false)] [InlineData("locationNonNull", "null", "comparandMaybeNull", false)] [InlineData("locationNonNull", "null", "comparandNonNull", false)] [InlineData("locationNonNull", "null", "null", false)] [InlineData("locationMaybeNull", "valueNonNull", "comparandNonNull", false)] [InlineData("locationMaybeNull", "valueNonNull", "comparandMaybeNull", false)] [InlineData("locationMaybeNull", "valueNonNull", "null", true)] [InlineData("locationMaybeNull", "valueMaybeNull", "comparandNonNull", false)] [InlineData("locationMaybeNull", "valueMaybeNull", "comparandMaybeNull", false)] [InlineData("locationMaybeNull", "valueMaybeNull", "null", false)] [InlineData("locationMaybeNull", "null", "comparandNonNull", false)] [InlineData("locationMaybeNull", "null", "comparandMaybeNull", false)] [InlineData("locationMaybeNull", "null", "null", false)] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchange_LocationNullState(string location, string value, string comparand, bool isLocationNonNullAfterCall) { var source = $@" #pragma warning disable 0436 using System.Threading; using System.Diagnostics.CodeAnalysis; namespace System.Threading {{ public static class Interlocked {{ public static object? CompareExchange([NotNullIfNotNull(""value"")] ref object? location, object? value, object? comparand) {{ return location; }} }} }} class C {{ // locationNonNull is annotated, but its flow state is non-null void M(object? locationNonNull, object? locationMaybeNull, object comparandNonNull, object? comparandMaybeNull, object valueNonNull, object? valueMaybeNull) {{ locationNonNull = new object(); Interlocked.CompareExchange(ref {location}, {value}, {comparand}); _ = {location}.ToString(); }} }} "; var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (19,13): warning CS8602: Dereference of a possibly null reference. // _ = {location}.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, location).WithLocation(19, 13) }); source = $@" #pragma warning disable 0436 using System.Threading; namespace System.Threading {{ public static class Interlocked {{ public static T CompareExchange<T>(ref T location, T value, T comparand) where T : class? {{ return location; }} }} }} class C {{ // locationNonNull is annotated, but its flow state is non-null void M<T>(T? locationNonNull, T? locationMaybeNull, T comparandNonNull, T? comparandMaybeNull, T valueNonNull, T? valueMaybeNull) where T : class, new() {{ locationNonNull = new T(); Interlocked.CompareExchange(ref {location}, {value}, {comparand}); _ = {location}.ToString(); }} }} "; comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (19,13): warning CS8602: Dereference of a possibly null reference. // _ = {location}.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, location).WithLocation(19, 13) }); source = $@" class C {{ // locationNonNull is annotated, but its flow state is non-null void M(object? locationNonNull, object? locationMaybeNull, object comparandNonNull, object? comparandMaybeNull, object valueNonNull, object? valueMaybeNull) {{ locationNonNull = new object(); if ({location} == {comparand}) {{ {location} = {value}; }} _ = {location}.ToString(); }} }} "; comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(isLocationNonNullAfterCall ? Array.Empty<DiagnosticDescription>() : new[] { // (12,13): warning CS8602: Dereference of a possibly null reference. // _ = {location}.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, location).WithLocation(12, 13) }); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchange_NoLocationSlot() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static object? CompareExchange(ref object? location, object? value, object? comparand) { return location; } } } class C { void M() { var arr = new object?[1]; Interlocked.CompareExchange(ref arr[0], new object(), null); _ = arr[0].ToString(); // 1 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (18,13): warning CS8602: Dereference of a possibly null reference. // _ = arr[0].ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "arr[0]").WithLocation(18, 13)); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchangeT_NotAnnotatedLocation_MaybeNullComparand() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static T CompareExchange<T>(ref T location, T value, T comparand) where T : class? { return location; } } } class C { void M<T>(T location, T value, T? comparand) where T : class { Interlocked.CompareExchange(ref location, value, comparand); // no warning because `location` will be assigned a not-null from `value` _ = location.ToString(); } void M2<T>(T location, T? value, T? comparand) where T : class { Interlocked.CompareExchange(ref location, value, comparand); // 1 _ = location.ToString(); // 2 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (21,41): warning CS8600: Converting null literal or possible null value to non-nullable type. // Interlocked.CompareExchange(ref location, value, comparand); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "location").WithLocation(21, 41), // (22,13): warning CS8602: Dereference of a possibly null reference. // _ = location.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "location").WithLocation(22, 13)); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchangeT_NotAnnotatedLocation_NonNullComparand() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static T CompareExchange<T>(ref T location, T value, T comparand) where T : class? { return location; } } } class C { void M<T>(T location, T value, T comparand) where T : class { Interlocked.CompareExchange(ref location, value, comparand); _ = location.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchangeT_NotAnnotatedLocation_NonNullReturnValue() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static T CompareExchange<T>(ref T location, T value, T comparand) where T : class? { return location; } } } class C { void M<T>(T location, T value, T comparand) where T : class { var result = Interlocked.CompareExchange(ref location, value, comparand); _ = location.ToString(); _ = result.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics(); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchangeT_NonNullLocation_MaybeNullReturnValue() { var source = @" #pragma warning disable 0436 using System.Threading; using System.Diagnostics.CodeAnalysis; namespace System.Threading { public static class Interlocked { public static T CompareExchange<T>([NotNullIfNotNull(""value"")] ref T location, T value, T comparand) where T : class? { return location; } } } class C { // location is annotated, but its flow state is non-null void M<T>(T? location, T value, T comparand) where T : class, new() { location = new T(); var result = Interlocked.CompareExchange(ref location, value, comparand); _ = location.ToString(); _ = result.ToString(); location = null; result = Interlocked.CompareExchange(ref location, value, null); _ = location.ToString(); _ = result.ToString(); // 1 } } "; // Note: the return value of CompareExchange is the value in `location` before the call. // Therefore it might make sense to give the return value a flow state equal to the flow state of `location` before the call. // Tracked by https://github.com/dotnet/roslyn/issues/36911 var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( // (25,13): warning CS8602: Dereference of a possibly null reference. // _ = result.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result").WithLocation(25, 13)); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchangeT_MaybeNullLocation_MaybeNullReturnValue() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static T CompareExchange<T>(ref T location, T value, T comparand) where T : class? { return location; } } } class C { void M<T>(T? location, T value, T comparand) where T : class { var result = Interlocked.CompareExchange(ref location, value, comparand); _ = location.ToString(); // 1 _ = result.ToString(); // 2 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,13): warning CS8602: Dereference of a possibly null reference. // _ = location.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "location").WithLocation(17, 13), // (18,13): warning CS8602: Dereference of a possibly null reference. // _ = result.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "result").WithLocation(18, 13)); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchange_UnrecognizedOverload() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static object? CompareExchange(ref object? location, object? value) { return location; } public static object? CompareExchange(ref object? location, object? value, object? comparand) { return location; } } } class C { void M() { object? location = null; Interlocked.CompareExchange(ref location, new object()); _ = location.ToString(); // 1 Interlocked.CompareExchange(ref location, new object(), null); _ = location.ToString(); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (19,13): warning CS8602: Dereference of a possibly null reference. // _ = location.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "location").WithLocation(19, 13)); } [Fact] [WorkItem(36911, "https://github.com/dotnet/roslyn/issues/36911")] public void CompareExchangeT_UnrecognizedOverload() { var source = @" #pragma warning disable 0436 using System.Threading; using System.Diagnostics.CodeAnalysis; namespace System.Threading { public static class Interlocked { public static T CompareExchange<T>([NotNullIfNotNull(""value"")] ref T location, T value) where T : class? { return location; } public static T CompareExchange<T>([NotNullIfNotNull(""value"")] ref T location, T value, T comparand) where T : class? { return location; } } } class C { void M() { string? location = null; Interlocked.CompareExchange(ref location, ""hello""); _ = location.ToString(); location = null; Interlocked.CompareExchange(ref location, ""hello"", null); _ = location.ToString(); location = string.Empty; Interlocked.CompareExchange(ref location, ""hello"", null); _ = location.ToString(); } } "; var comp = CreateCompilation(new[] { source, NotNullIfNotNullAttributeDefinition }, options: WithNullableEnable()); comp.VerifyDiagnostics( ); } [Fact] [WorkItem(38010, "https://github.com/dotnet/roslyn/issues/38010")] public void CompareExchange_BadArgCount() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static object? CompareExchange(ref object? location, object? value, object? comparand) { return location; } } } class C { void M() { string? location = null; Interlocked.CompareExchange(ref location, new object()); // 1 _ = location.ToString(); // 2 } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,21): error CS7036: There is no argument given that corresponds to the required formal parameter 'comparand' of 'Interlocked.CompareExchange(ref object?, object?, object?)' // Interlocked.CompareExchange(ref location, new object()); // 1 Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "CompareExchange").WithArguments("comparand", "System.Threading.Interlocked.CompareExchange(ref object?, object?, object?)").WithLocation(17, 21), // (18,13): warning CS8602: Dereference of a possibly null reference. // _ = location.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "location").WithLocation(18, 13)); } [Fact] [WorkItem(46673, "https://github.com/dotnet/roslyn/issues/46673")] public void CompareExchange_NamedArguments() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { public static class Interlocked { public static object? CompareExchange(ref object? location, object? value, object? comparand) { return location; } } } class C { void M() { object location1 = """"; Interlocked.CompareExchange(ref location1, comparand: """", value: null); // 1 object location2 = """"; Interlocked.CompareExchange(ref location2, comparand: null, value: """"); object location3 = """"; Interlocked.CompareExchange(comparand: """", value: null, location: ref location3); // 2 object location4 = """"; Interlocked.CompareExchange(comparand: null, value: """", location: ref location4); } } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (17,41): warning CS8600: Converting null literal or possible null value to non-nullable type. // Interlocked.CompareExchange(ref location1, comparand: "", value: null); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "location1").WithLocation(17, 41), // (23,79): warning CS8600: Converting null literal or possible null value to non-nullable type. // Interlocked.CompareExchange(comparand: "", value: null, location: ref location3); // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "location3").WithLocation(23, 79)); } [Fact] [WorkItem(46673, "https://github.com/dotnet/roslyn/issues/46673")] public void CompareExchange_NamedArgumentsWithOptionalParameters() { var source = @" #pragma warning disable 0436 using System.Threading; namespace System.Threading { class Interlocked { public static T CompareExchange<T>(ref T location1, T value, T comparand = default) where T : class => value; } } class C { static void F(object target, object value) { Interlocked.CompareExchange(value: value, location1: ref target); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (8,84): warning CS8625: Cannot convert null literal to non-nullable reference type. // public static T CompareExchange<T>(ref T location1, T value, T comparand = default) where T : class => value; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(8, 84), // (15,9): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'Interlocked.CompareExchange<T>(ref T, T, T)'. Nullability of type argument 'object?' doesn't match 'class' constraint. // Interlocked.CompareExchange(value: value, location1: ref target); Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "Interlocked.CompareExchange").WithArguments("System.Threading.Interlocked.CompareExchange<T>(ref T, T, T)", "T", "object?").WithLocation(15, 9)); } [Fact] [WorkItem(37187, "https://github.com/dotnet/roslyn/issues/37187")] public void IEquatableContravariantNullability() { var def = @" using System; namespace System { public interface IEquatable<T> { bool Equals(T other); } } public class A : IEquatable<A?> { public bool Equals(A? a) => false; public static void M<T>(Span<T> s) where T : IEquatable<T>? { s[0]?.Equals(null); s[0]?.Equals(s[1]); } } public class B : IEquatable<(B?, B?)> { public bool Equals((B?, B?) l) => false; } "; var spanRef = CreateCompilation(SpanSource, options: TestOptions.UnsafeReleaseDll) .EmitToImageReference(); var comp = CreateCompilation(def + @" class C { static void Main() { var x = new Span<A?>(); var y = new Span<A>(); A.M(x); A.M(y); IEquatable<A?> i1 = new A(); IEquatable<A> i2 = i1; IEquatable<A> i3 = new A(); IEquatable<A?> i4 = i3; // warn _ = i4; IEquatable<(B?, B?)> i5 = new B(); IEquatable<(B, B)> i6 = i5; IEquatable<(B, B)> i7 = new B(); IEquatable<(B?, B?)> i8 = i7; // warn _ = i8; } }", new[] { spanRef }, options: WithNullableEnable().WithSpecificDiagnosticOptions("CS0436", ReportDiagnostic.Suppress)); comp.VerifyDiagnostics( // (34,29): warning CS8619: Nullability of reference types in value of type 'IEquatable<A>' doesn't match target type 'IEquatable<A?>'. // IEquatable<A?> i4 = i3; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i3").WithArguments("System.IEquatable<A>", "System.IEquatable<A?>").WithLocation(41, 29), // (40,35): warning CS8619: Nullability of reference types in value of type 'IEquatable<(B, B)>' doesn't match target type 'IEquatable<(B?, B?)>'. // IEquatable<(B?, B?)> i8 = i7; // warn Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i7").WithArguments("System.IEquatable<(B, B)>", "System.IEquatable<(B?, B?)>").WithLocation(47, 35) ); // Test with non-wellknown type var defComp = CreateCompilation(def, references: new[] { spanRef }, options: WithNullableEnable().WithSpecificDiagnosticOptions("CS0436", ReportDiagnostic.Suppress)); defComp.VerifyDiagnostics(); var useComp = CreateCompilation(@" using System; public interface IEquatable<T> { bool Equals(T other); } class C { static void Main() { var x = new Span<A?>(); var y = new Span<A>(); A.M(x); A.M(y); } }", references: new[] { spanRef, defComp.ToMetadataReference() }, options: WithNullableEnable()); useComp.VerifyDiagnostics(); } [Fact] public void IEquatableNotContravariantExceptNullability() { var src = @" using System; class A : IEquatable<A?> { public bool Equals(A? a) => false; } class B : A {} class C { static void Main() { var x = new Span<B?>(); var y = new Span<B>(); M(x); M(y); } static void M<T>(Span<T> s) where T : IEquatable<T>? { } }"; var comp = CreateCompilationWithSpan(src + @" namespace System { public interface IEquatable<T> { bool Equals(T other); } } ", options: WithNullableEnable().WithSpecificDiagnosticOptions("CS0436", ReportDiagnostic.Suppress)); comp.VerifyDiagnostics( // (25,9): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(Span<T>)'. There is no implicit reference conversion from 'B' to 'System.IEquatable<B>'. // M(x); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(System.Span<T>)", "System.IEquatable<B>", "T", "B").WithLocation(18, 9), // (26,9): error CS0311: The type 'B' cannot be used as type parameter 'T' in the generic type or method 'C.M<T>(Span<T>)'. There is no implicit reference conversion from 'B' to 'System.IEquatable<B>'. // M(y); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedRefType, "M").WithArguments("C.M<T>(System.Span<T>)", "System.IEquatable<B>", "T", "B").WithLocation(19, 9)); // If IEquatable is actually marked contravariant this is fine comp = CreateCompilationWithSpan(src + @" namespace System { public interface IEquatable<in T> { bool Equals(T other); } } ", options: WithNullableEnable().WithSpecificDiagnosticOptions("CS0436", ReportDiagnostic.Suppress)); comp.VerifyDiagnostics(); } [Fact] public void IEquatableInWrongNamespace() { var comp = CreateCompilation(@" public interface IEquatable<T> { bool Equals(T other); } public class A : IEquatable<A?> { public bool Equals(A? a) => false; public static void Main() { IEquatable<A?> i1 = new A(); IEquatable<A> i2 = i1; IEquatable<A?> i3 = i2; _ = i3; } } ", options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,28): warning CS8619: Nullability of reference types in value of type 'IEquatable<A?>' doesn't match target type 'IEquatable<A>'. // IEquatable<A> i2 = i1; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i1").WithArguments("IEquatable<A?>", "IEquatable<A>").WithLocation(14, 28), // (15,29): warning CS8619: Nullability of reference types in value of type 'IEquatable<A>' doesn't match target type 'IEquatable<A?>'. // IEquatable<A?> i3 = i2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "i2").WithArguments("IEquatable<A>", "IEquatable<A?>").WithLocation(15, 29)); } [Fact] public void IEquatableNullableVarianceOutParameters() { var comp = CreateCompilation(@" using System; class C { void M<T>(IEquatable<T?> input, out IEquatable<T> output) where T: class { output = input; } } namespace System { public interface IEquatable<T> { bool Equals(T other); } } ", options: WithNullableEnable().WithSpecificDiagnosticOptions("CS0436", ReportDiagnostic.Suppress)); comp.VerifyDiagnostics(); } [Fact] [WorkItem(37269, "https://github.com/dotnet/roslyn/issues/37269")] public void TypeParameterReturnType_01() { var source = @"using System; using System.Threading.Tasks; static class ResultExtensions { static async Task<Result<TResult, B>> MapAsync<A, B, TResult>( this Result<A, B> result, Func<A, Task<TResult>> map) { return await result.Match( async a => FromA<TResult>(await map(a)), b => Task.FromResult(FromB<TResult, B>(b))); } static Result<A, B> FromA<A, B>(A value) => throw null!; static Result<A, B> FromB<A, B>(B value) => throw null!; } class Result<A, B> { public TResult Match<TResult>(Func<A, TResult> a, Func<B, TResult> b) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (10,24): error CS0305: Using the generic method 'ResultExtensions.FromA<A, B>(A)' requires 2 type arguments // async a => FromA<TResult>(await map(a)), Diagnostic(ErrorCode.ERR_BadArity, "FromA<TResult>").WithArguments("ResultExtensions.FromA<A, B>(A)", "method", "2").WithLocation(10, 24)); } [Fact] public void TypeParameterReturnType_02() { var source = @"using System; using System.Threading.Tasks; static class ResultExtensions { static async Task<Result<TResult, B>> MapAsync<A, B, TResult>( this Result<A, B> result, Func<A, Task<TResult>> map) { return await result.Match( async a => FromA<TResult, B>(await map(a)), b => Task.FromResult(FromB<TResult, B>(b))); } static Result<A, B> FromA<A, B>(A value) => throw null!; static Result<A, B> FromB<A, B>(B value) => throw null!; } class Result<A, B> { public TResult Match<TResult>(Func<A, TResult> a, Func<B, TResult> b) => throw null!; }"; var comp = CreateCompilation(source, options: WithNullableEnable()); // Use VerifyEmitDiagnostics() to test assertions in CodeGenerator.EmitCallExpression. comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(36052, "https://github.com/dotnet/roslyn/issues/36052")] public void UnassignedLocal() { var source = @" class Program : Base { void M0() { string? x0a; x0a/*T:string?*/.ToString(); // 1 string x0b; x0b/*T:string!*/.ToString(); } void M1<T>() { T x1; x1/*T:T*/.ToString(); // 2 } void M2(object? o) { if (o is string x2a) {} x2a/*T:string!*/.ToString(); if (T() && o is var x2b) {} x2b/*T:object?*/.ToString(); // 3 } void M3() { do { } while (T() && M<string?>(out string? s3) && s3/*T:string?*/.Length > 1); // 4 do { } while (T() && M<string>(out string s3) && s3/*T:string!*/.Length > 1); } void M4() { while (T() || M<string?>(out string? s4)) { s4/*T:string?*/.ToString(); // 5 } while (T() || M<string>(out string s4)) { s4/*T:string!*/.ToString(); } } void M5() { for (string? s1; T(); ) s1/*T:string?*/.ToString(); // 6 for (string s1; T(); ) s1/*T:string!*/.ToString(); } Program(int x) : base((T() || M<string?>(out string? s6)) && s6/*T:string?*/.Length > 1) {} // 7 Program(long x) : base((T() || M<string>(out string s7)) && s7/*T:string!*/.Length > 1) {} static bool T() => true; static bool M<T>(out T x) { x = default(T)!; return true; } } class Base { public Base(bool b) {} } "; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyTypes(); comp.GetDiagnostics().Where(d => d.Code != (int)ErrorCode.ERR_UseDefViolation).Verify( // (7,9): warning CS8602: Dereference of a possibly null reference. // x0a.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0a").WithLocation(7, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(14, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // x2b.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2b").WithLocation(21, 9), // (27,55): warning CS8602: Dereference of a possibly null reference. // } while (T() && M<string?>(out string? s3) && s3.Length > 1); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3").WithLocation(27, 55), // (36,13): warning CS8602: Dereference of a possibly null reference. // s4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4").WithLocation(36, 13), // (45,33): warning CS8602: Dereference of a possibly null reference. // for (string? s1; T(); ) s1.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1").WithLocation(45, 33), // (48,66): warning CS8602: Dereference of a possibly null reference. // Program(int x) : base((T() || M<string?>(out string? s6)) && s6.Length > 1) {} // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s6").WithLocation(48, 66)); } [Fact] [WorkItem(38183, "https://github.com/dotnet/roslyn/issues/38183")] public void UnboundGenericTypeReference_StructConstraint() { var source = @"class Program { static void Main(string[] args) { F<Boxed<int>>(); } static void F<T>() { if (typeof(T).GetGenericTypeDefinition() == typeof(Boxed<>)) { } } } class Boxed<T> where T : struct { public bool Equals(Boxed<T>? other) => false; public override bool Equals(object? obj) => Equals(obj as Boxed<T>); public override int GetHashCode() => 0; }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); CompileAndVerify(comp, expectedOutput: ""); } [Fact] [WorkItem(38183, "https://github.com/dotnet/roslyn/issues/38183")] public void UnboundGenericTypeReference_ClassConstraint() { var source = @"class Program { static void Main(string[] args) { F<Boxed<object>>(); } static void F<T>() { if (typeof(T).GetGenericTypeDefinition() == typeof(Boxed<>)) { } } } class Boxed<T> where T : class { public bool Equals(Boxed<T>? other) => false; public override bool Equals(object? obj) => Equals(obj as Boxed<T>); public override int GetHashCode() => 0; }"; var comp = CreateCompilation(source, options: WithNullableEnable(TestOptions.ReleaseExe)); CompileAndVerify(comp, expectedOutput: ""); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_Invariant_ObliviousVersusUnannotated() { var source = @" #nullable enable warnings static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I<T> source) => throw null!; } class C : I<object>, I2 {} interface I<T> {} #nullable enable annotations interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("c.Extension()", invocation.ToString()); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_Invariant_ObliviousVersusAnnotated() { var source = @" #nullable enable static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I<T> source) => throw null!; } class C : I<object?>, I2 {} interface I<T> {} #nullable disable interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 9) ); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object?>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_Invariant_ObliviousVersusAnnotated_ReverseOrder() { var source = @" #nullable enable static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I<T> source) => throw null!; } class C : I2, I<object?> {} interface I<T> {} #nullable disable interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x").WithLocation(8, 9) ); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object?>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_Invariant_AnnotatedVersusUnannotated() { var source = @" #nullable enable static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I<T> source) => throw null!; } class C : I<object?>, I2 {} interface I<T> {} interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,7): warning CS8645: 'I<object>' is already listed in the interface list on type 'C' with different nullability of reference types. // class C : I<object?>, I2 {} Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C").WithArguments("I<object>", "C").WithLocation(13, 7) ); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("c.Extension()", invocation.ToString()); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_Invariant_UnannotatedVersusAnnotated() { var source = @" #nullable enable static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I<T> source) => throw null!; } class C : I<object>, I2 {} interface I<T> {} interface I2 : I<object?> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,7): warning CS8645: 'I<object?>' is already listed in the interface list on type 'C' with different nullability of reference types. // class C : I<object>, I2 {} Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C").WithArguments("I<object?>", "C").WithLocation(13, 7) ); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("c.Extension()", invocation.ToString()); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_LowerBound_Contravariant() { var source = @" #nullable enable warnings static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I3<I<T>> source) => throw null!; } class C : I3<I<object>>, I2 {} interface I<T> {} interface I3<in T> {} #nullable enable annotations interface I2 : I3<I<object>> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("c.Extension()", invocation.ToString()); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_LowerBound_Variant() { var source = @" #nullable enable warnings static class P { static void M(C c) { var x = c.Extension(); x.ToString(); } public static T Extension<T>(this I3<I<T>> source) => throw null!; } class C : I3<I<object>>, I2 {} interface I<T> {} interface I3<out T> {} #nullable enable annotations interface I2 : I3<I<object>> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("c.Extension()", invocation.ToString()); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_UpperBound_ObliviousVersusUnannotated() { var source = @" #nullable enable warnings static class P { static void M(ICon<I<object>> c) { var x = c.Extension(""""); x.ToString(); } public static T Extension<T>(this ICon<I3<T>> source, T other) where T : class => throw null!; } interface ICon<in T> where T : class {} interface I<T> where T : class {} interface I3<T> : I<T>, I2<T> where T : class {} #nullable enable annotations interface I2<T> : I<T> where T : class {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_UpperBound_AnnotatedVersusUnannotated() { var source = @" #nullable enable static class P { static void M(ICon<I<object>> c) { var x = c.Extension(""""); x.ToString(); } public static T Extension<T>(this ICon<I3<T>> source, T other) where T : class => throw null!; } interface ICon<in T> where T : class {} interface I<T> where T : class? {} interface I3<T> : I<T?>, I2<T> where T : class {} interface I2<T> : I<T> where T : class {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,11): warning CS8645: 'I<T>' is already listed in the interface list on type 'I3<T>' with different nullability of reference types. // interface I3<T> : I<T?>, I2<T> where T : class {} Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I3").WithArguments("I<T>", "I3<T>").WithLocation(15, 11) ); var tree = comp.SyntaxTrees.Single(); var declaration = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration); Assert.Equal("System.Object?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.NullableAnnotation); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38427, "https://github.com/dotnet/roslyn/issues/38427")] public void MethodTypeInference_ImplementedInterfaces_Indirect_TupleDifferences() { var source = @" static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<(int a, int b)>, I2 {} interface I<T> {} interface I2 : I<(int c, int d)> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,11): error CS1061: 'C' does not contain a definition for 'Extension' and no accessible extension method 'Extension' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // c.Extension(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Extension").WithArguments("C", "Extension").WithLocation(6, 11), // (12,7): error CS8140: 'I<(int c, int d)>' is already listed in the interface list on type 'C' with different tuple element names, as 'I<(int a, int b)>'. // class C : I<(int a, int b)>, I2 {} Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I<(int c, int d)>", "I<(int a, int b)>", "C").WithLocation(12, 7) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Indirect_Object() { var source = @" static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<object>, I2 {} interface I<T> {} interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Direct() { var source = @" #nullable enable warnings static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<object>, #nullable enable annotations I<object> { } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,5): warning CS8645: 'I<object>' is already listed in the interface list on type 'C' with different nullability of reference types. // I<object> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I<object>").WithArguments("I<object>", "C").WithLocation(15, 5) ); var interfaces = comp.GetTypeByMetadataName("C").InterfacesNoUseSiteDiagnostics(); Assert.Equal(new[] { "I<object>", "I<object!>" }, interfaces.Select(i => i.ToDisplayString(TypeWithAnnotations.TestDisplayFormat))); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void ImplementedInterfaces_Partials_ObliviousVersusUnannotated() { var source = @" partial class C : I<object> { } #nullable enable partial class C : I<object> { } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void ImplementedInterfaces_Partials_AnnotatedVersusUnannotated() { var source = @" #nullable enable partial class C : I<object?> { } partial class C : I<object> { } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (3,15): warning CS8645: 'I<object>' is already listed in the interface list on type 'C' with different nullability of reference types. // partial class C : I<object?> { } Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C").WithArguments("I<object>", "C").WithLocation(3, 15) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Direct_AnnotatedVersusUnannotated() { var source = @" #nullable enable static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<object>, I<object?> { } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (13,7): warning CS8645: 'I<object?>' is already listed in the interface list on type 'C' with different nullability of reference types. // class C : I<object>, I<object?> Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C").WithArguments("I<object?>", "C").WithLocation(13, 7) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Direct_NullabilityAndTupleNameDifferences() { var source = @" #nullable enable static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<(object a, object b)>, I<(object? c, object? d)> { } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,11): error CS1061: 'C' does not contain a definition for 'Extension' and no accessible extension method 'Extension' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // c.Extension(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Extension").WithArguments("C", "Extension").WithLocation(7, 11), // (13,7): error CS8140: 'I<(object? c, object? d)>' is already listed in the interface list on type 'C' with different tuple element names, as 'I<(object a, object b)>'. // class C : I<(object a, object b)>, I<(object? c, object? d)> Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I<(object? c, object? d)>", "I<(object a, object b)>", "C").WithLocation(13, 7) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Direct_Object() { var source = @" static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null; } class C : I<object>, I<object> {} interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,22): error CS0528: 'I<object>' is already listed in interface list // class C : I<object>, I<object> {} Diagnostic(ErrorCode.ERR_DuplicateInterfaceInBaseList, "I<object>").WithArguments("I<object>").WithLocation(12, 22) ); } [Fact, WorkItem(38427, "https://github.com/dotnet/roslyn/issues/38427")] public void MethodTypeInference_ImplementedInterfaces_Direct_TupleDifferences() { var source = @" #nullable enable warnings static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<(int a, int b)>, I<(int c, int d)> {} interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,11): error CS1061: 'C' does not contain a definition for 'Extension' and no accessible extension method 'Extension' accepting a first argument of type 'C' could be found (are you missing a using directive or an assembly reference?) // c.Extension(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Extension").WithArguments("C", "Extension").WithLocation(7, 11), // (13,7): error CS8140: 'I<(int c, int d)>' is already listed in the interface list on type 'C' with different tuple element names, as 'I<(int a, int b)>'. // class C : I<(int a, int b)>, I<(int c, int d)> {} Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "C").WithArguments("I<(int c, int d)>", "I<(int a, int b)>", "C").WithLocation(13, 7) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Partial_ObliviousVsAnnotated() { var source = @" #nullable enable static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} partial class C : I<object?> { } #nullable disable partial class C : I<object> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object?>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Partial_ObliviousVsUnannotated() { var source = @" #nullable enable static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} partial class C : I<object> { } #nullable disable partial class C : I<object> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_ImplementedInterfaces_Partial_AnnotatedVsUnannotated() { var source = @" #nullable enable static class P { static void M(C c) { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} partial class C : I<object?> { } partial class C : I<object> { } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (15,15): warning CS8645: 'I<object>' is already listed in the interface list on type 'C' with different nullability of reference types. // partial class C : I<object?> { } Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "C").WithArguments("I<object>", "C").WithLocation(15, 15) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocation = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("Extension<object!>", model.GetSymbolInfo(invocation).Symbol.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Indirect() { var source = @" #nullable enable warnings static class P { static void M<T>(T c) where T : I<object>, I2 { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} #nullable enable annotations interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Indirect_UsingBaseClass() { var source = @" #nullable enable warnings static class P { static void M<T>(T c) where T : C { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<object>, I2 {} interface I<T> {} #nullable enable annotations interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Indirect_UsingBaseClass_AnnotatedVersusUnannotated() { var source = @" #nullable enable annotations static class P { static void M<T>(T c) where T : C { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } class C : I<object?>, I2 {} interface I<T> {} interface I2 : I<object> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38427, "https://github.com/dotnet/roslyn/issues/38427")] public void MethodTypeInference_TypeParameter_Indirect_TupleDifferences() { var source = @" static class P { static void M<T>(T c) where T : I<(int a, int b)>, I2 { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} interface I2 : I<(int c, int d)> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,11): error CS1061: 'T' does not contain a definition for 'Extension' and no accessible extension method 'Extension' accepting a first argument of type 'T' could be found (are you missing a using directive or an assembly reference?) // c.Extension(); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "Extension").WithArguments("T", "Extension").WithLocation(6, 11) ); } [Fact, WorkItem(38427, "https://github.com/dotnet/roslyn/issues/38427")] public void MethodTypeInference_TypeParameter_Indirect_MatchingTuples() { var source = @" static class P { static void M<T>(T c) where T : I<(int a, int b)>, I2 { var t = c.Extension(); _ = t.a; } public static T Extension<T>(this I<T> source) => throw null!; } interface I<T> {} interface I2 : I<(int a, int b)> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Direct() { var source = @" #nullable enable warnings static class P { static void M<T>(T c) where T : I<object>, #nullable enable annotations I<object> { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): error CS0405: Duplicate constraint 'I<object>' for type parameter 'T' // I<object> Diagnostic(ErrorCode.ERR_DuplicateBound, "I<object>").WithArguments("I<object>", "T").WithLocation(7, 9) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Direct_NullabilityAndTupleNameDifferences() { var source = @" #nullable enable static class P { static void M<T>(T c) where T : I<(object a, object b)>, I<(object? c, object? d)> { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,62): error CS0405: Duplicate constraint 'I<(object c, object d)>' for type parameter 'T' // static void M<T>(T c) where T : I<(object a, object b)>, I<(object? c, object? d)> Diagnostic(ErrorCode.ERR_DuplicateBound, "I<(object? c, object? d)>").WithArguments("I<(object c, object d)>", "T").WithLocation(5, 62) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Direct_NullabilityAndTupleNameDifferences_Oblivious() { var source = @" #nullable enable static class P { static void M<T>(T c) where T : I<(object a, object b)>, #nullable disable I<(object c, object d)> { } } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): error CS0405: Duplicate constraint 'I<(object c, object d)>' for type parameter 'T' // I<(object c, object d)> Diagnostic(ErrorCode.ERR_DuplicateBound, "I<(object c, object d)>").WithArguments("I<(object c, object d)>", "T").WithLocation(7, 9) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_TypeParameter_Direct_NullabilityDifferences_Oblivious() { var source = @" #nullable enable static class P { static void M<T>(T c) where T : I<(object a, object b)>, #nullable disable I<(object a, object b)> { } } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): error CS0405: Duplicate constraint 'I<(object a, object b)>' for type parameter 'T' // I<(object a, object b)> Diagnostic(ErrorCode.ERR_DuplicateBound, "I<(object a, object b)>").WithArguments("I<(object a, object b)>", "T").WithLocation(7, 9) ); } [Fact, WorkItem(38427, "https://github.com/dotnet/roslyn/issues/38427")] public void MethodTypeInference_TypeParameter_Direct_TupleDifferences() { var source = @" static class P { static void M<T>(T c) where T : I<(int a, int b)>, I<(int c, int d)> { c.Extension(); } public static void Extension<T>(this I<T> source) => throw null!; } interface I<T> {} "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,56): error CS0405: Duplicate constraint 'I<(int c, int d)>' for type parameter 'T' // static void M<T>(T c) where T : I<(int a, int b)>, I<(int c, int d)> Diagnostic(ErrorCode.ERR_DuplicateBound, "I<(int c, int d)>").WithArguments("I<(int c, int d)>", "T").WithLocation(4, 56) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MultipleIEnumerableT_UnannotatedObjectVersusAnnotatedObject() { var text = @" using System.Collections; using System.Collections.Generic; #nullable enable warnings class C<T> { void M(Enumerable e) { foreach (var x in e) { } } } #nullable enable interface I : IEnumerable<C<object?>> { } class Enumerable : IEnumerable<C<object>>, I #nullable disable { IEnumerator<C<object>> IEnumerable<C<object>>.GetEnumerator() { throw null!; } IEnumerator IEnumerable.GetEnumerator() { throw null!; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (17,7): warning CS8645: 'IEnumerable<C<object?>>' is already listed in the interface list on type 'Enumerable' with different nullability of reference types. // class Enumerable : IEnumerable<C<object>>, I Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Enumerable").WithArguments("System.Collections.Generic.IEnumerable<C<object?>>", "Enumerable").WithLocation(17, 7) ); var tree = comp.SyntaxTrees.Single(); var @foreach = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal("C<System.Object>", model.GetForEachStatementInfo(@foreach).ElementType.ToTestDisplayString()); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MultipleIEnumerableT_AnnotatedObjectVersusUnannotatedObject() { var text = @" using System.Collections; using System.Collections.Generic; #nullable enable warnings class C<T> { void M(Enumerable e) { foreach (var x in e) { } } } #nullable enable interface I : IEnumerable<C<object>> { } class Enumerable : IEnumerable<C<object?>>, I #nullable disable { IEnumerator<C<object>> IEnumerable<C<object>>.GetEnumerator() { throw null!; } IEnumerator IEnumerable.GetEnumerator() { throw null!; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (17,7): warning CS8645: 'IEnumerable<C<object>>' is already listed in the interface list on type 'Enumerable' with different nullability of reference types. // class Enumerable : IEnumerable<C<object?>>, I Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "Enumerable").WithArguments("System.Collections.Generic.IEnumerable<C<object>>", "Enumerable").WithLocation(17, 7) ); var tree = comp.SyntaxTrees.Single(); var @foreach = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); // Note: we get the same element type regardless of the order in which interfaces are listed Assert.Equal("C<System.Object>", model.GetForEachStatementInfo(@foreach).ElementType.ToTestDisplayString()); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MultipleIEnumerableT_TupleAVersusTupleC() { var text = @" using System.Collections; using System.Collections.Generic; #nullable enable warnings class C<T> { void M(Enumerable e) { foreach (var x in e) { } } } #nullable enable interface I : IEnumerable<C<(int a, int b)>> { } class Enumerable : IEnumerable<C<(int c, int d)>>, I #nullable disable { IEnumerator<C<(int c, int d)>> IEnumerable<C<(int c, int d)>>.GetEnumerator() { throw null!; } IEnumerator IEnumerable.GetEnumerator() { throw null!; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (17,7): error CS8140: 'IEnumerable<C<(int a, int b)>>' is already listed in the interface list on type 'Enumerable' with different tuple element names, as 'IEnumerable<C<(int c, int d)>>'. // class Enumerable : IEnumerable<C<(int c, int d)>>, I Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "Enumerable").WithArguments("System.Collections.Generic.IEnumerable<C<(int a, int b)>>", "System.Collections.Generic.IEnumerable<C<(int c, int d)>>", "Enumerable").WithLocation(17, 7) ); var tree = comp.SyntaxTrees.Single(); var @foreach = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal("C<(System.Int32 a, System.Int32 b)>", model.GetForEachStatementInfo(@foreach).ElementType.ToTestDisplayString()); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MultipleIEnumerableT_TupleCVersusTupleA() { var text = @" using System.Collections; using System.Collections.Generic; #nullable enable warnings class C<T> { void M(Enumerable e) { foreach (var x in e) { } } } #nullable enable interface I : IEnumerable<C<(int c, int d)>> { } class Enumerable : IEnumerable<C<(int a, int b)>>, I #nullable disable { IEnumerator<C<(int a, int b)>> IEnumerable<C<(int a, int b)>>.GetEnumerator() { throw null!; } IEnumerator IEnumerable.GetEnumerator() { throw null!; } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (17,7): error CS8140: 'IEnumerable<C<(int c, int d)>>' is already listed in the interface list on type 'Enumerable' with different tuple element names, as 'IEnumerable<C<(int a, int b)>>'. // class Enumerable : IEnumerable<C<(int a, int b)>>, I Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "Enumerable").WithArguments("System.Collections.Generic.IEnumerable<C<(int c, int d)>>", "System.Collections.Generic.IEnumerable<C<(int a, int b)>>", "Enumerable").WithLocation(17, 7) ); var tree = comp.SyntaxTrees.Single(); var @foreach = tree.GetRoot().DescendantNodes().OfType<ForEachStatementSyntax>().Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); Assert.Equal("C<(System.Int32 c, System.Int32 d)>", model.GetForEachStatementInfo(@foreach).ElementType.ToTestDisplayString()); } [Fact, WorkItem(42837, "https://github.com/dotnet/roslyn/issues/42837")] public void NullableDirectivesInSpeculativeModel() { var source = @" #nullable enable public class C<TSymbol> where TSymbol : class, ISymbolInternal { public object? _uniqueSymbolOrArities; private bool HasUniqueSymbol => false; public void GetUniqueSymbolOrArities(out IArityEnumerable? arities, out TSymbol? uniqueSymbol) { if (this.HasUniqueSymbol) { arities = null; #nullable disable // Can '_uniqueSymbolOrArities' be null? https://github.com/dotnet/roslyn/issues/39166 uniqueSymbol = (TSymbol)_uniqueSymbolOrArities; #nullable enable } } } interface IArityEnumerable { } interface ISymbolInternal { } "; var comp = CreateNullableCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var root = tree.GetRoot(); var ifStatement = root.DescendantNodes().OfType<IfStatementSyntax>().Single(); var cast = ifStatement.DescendantNodes().OfType<CastExpressionSyntax>().Single(); var replaceWith = cast.Expression; var newIfStatement = ifStatement.ReplaceNode(cast, replaceWith); Assert.True(model.TryGetSpeculativeSemanticModel( ifStatement.SpanStart, newIfStatement, out var speculativeModel)); var assignment = newIfStatement.DescendantNodes() .OfType<AssignmentExpressionSyntax>() .ElementAt(1); var info = speculativeModel.GetSymbolInfo(assignment); Assert.Null(info.Symbol); var typeInfo = speculativeModel.GetTypeInfo(assignment); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, typeInfo.Nullability.Annotation); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_Operator() { var source = @" #nullable enable public interface I<T> where T : class? { public static T operator +(I<T> x, I<T> y) => throw null!; } class C { static void Main(I<object> x, I<object?> y) { var z = x + y; z = y + x; } } "; var compilation1 = CreateCompilation(source, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (12,21): warning CS8620: Argument of type 'I<object?>' cannot be used for parameter 'y' of type 'I<object>' in 'object I<object>.operator +(I<object> x, I<object> y)' due to differences in the nullability of reference types. // var z = x + y; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y").WithArguments("I<object?>", "I<object>", "y", "object I<object>.operator +(I<object> x, I<object> y)").WithLocation(12, 21), // (13,17): warning CS8620: Argument of type 'I<object>' cannot be used for parameter 'y' of type 'I<object?>' in 'object? I<object?>.operator +(I<object?> x, I<object?> y)' due to differences in the nullability of reference types. // z = y + x; Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<object>", "I<object?>", "y", "object? I<object?>.operator +(I<object?> x, I<object?> y)").WithLocation(13, 17) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_Operator_NoDirectlyImplementedOperator() { var source = @" #nullable enable public interface I2 : I<object>, I3 { } public interface I3 : I<object?> { } public interface I<T> where T : class? { public static T operator +(I<T> x, I<T> y) => throw null!; } class C { static void Main(I2 x, I2 y) { var z = x + y; z = y + x; } } "; var compilation1 = CreateCompilation(source, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (3,18): warning CS8645: 'I<object?>' is already listed in the interface list on type 'I2' with different nullability of reference types. // public interface I2 : I<object>, I3 { } Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I2").WithArguments("I<object?>", "I2").WithLocation(3, 18) ); } [Fact, WorkItem(38168, "https://github.com/dotnet/roslyn/issues/38168")] public void MethodTypeInference_Operator_TupleDifferences() { var source = @" #nullable enable public interface I2 : I<(int c, int d)> { } public interface I<T> { public static T operator +(I<T> x, I<T> y) => throw null!; } class C { static void M<T>(T x, T y) where T : I<(int a, int b)>, I2 { var z = x + y; z = y + x; } } "; var compilation1 = CreateCompilation(source, parseOptions: TestOptions.Regular, targetFramework: TargetFramework.NetCoreApp); compilation1.VerifyDiagnostics( // (13,17): error CS0034: Operator '+' is ambiguous on operands of type 'T' and 'T' // var z = x + y; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "x + y").WithArguments("+", "T", "T").WithLocation(13, 17), // (14,13): error CS0034: Operator '+' is ambiguous on operands of type 'T' and 'T' // z = y + x; Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "y + x").WithArguments("+", "T", "T").WithLocation(14, 13) ); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_UnaryOperator_01() { var source = @"#pragma warning disable 649 #nullable enable class A<T> { public static A<T> operator~(A<T> a) => a; internal T F = default!; } class B<T> : A<T> { } class Program { static B<T> Create<T>(T t) { return new B<T>(); } static void F<T>() where T : class, new() { T x = null; // 1 (~Create(x)).F.ToString(); // 2 T? y = new T(); (~Create(y)).F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (19,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(19, 15), // (20,9): warning CS8602: Dereference of a possibly null reference. // (~Create(x)).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(~Create(x)).F").WithLocation(20, 9)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_UnaryOperator_02() { var source = @"#nullable enable interface IA<T> { T P { get; } public static IA<T> operator~(IA<T> a) => a; } interface IB<T> : IA<T> { } class Program { static IB<T> Create<T>(T t) { throw null!; } static void F<T>() where T : class, new() { T x = null; // 1 (~Create(x)).P.ToString(); // 2 T? y = new T(); (~Create(y)).P.ToString(); } }"; var comp = CreateCompilation(source, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics( // (18,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 15), // (19,9): warning CS8602: Dereference of a possibly null reference. // (~Create(x)).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(~Create(x)).P").WithLocation(19, 9)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_UnaryOperator_03() { var source = @"#pragma warning disable 649 #nullable enable struct S<T> { public static S<T> operator~(S<T> s) => s; internal T F; } class Program { static S<T> Create1<T>(T t) => new S<T>(); static S<T>? Create2<T>(T t) => null; static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var s1x = ~Create1(x); s1x.F.ToString(); // 2 var s2x = (~Create2(x)).Value; // 3 s2x.F.ToString(); // 4 var s1y = ~Create1(y); s1y.F.ToString(); var s2y = (~Create2(y)).Value; // 5 s2y.F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 15), // (17,9): warning CS8602: Dereference of a possibly null reference. // s1x.F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1x.F").WithLocation(17, 9), // (18,20): warning CS8629: Nullable value type may be null. // var s2x = (~Create2(x)).Value; // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "~Create2(x)").WithLocation(18, 20), // (19,9): warning CS8602: Dereference of a possibly null reference. // s2x.F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2x.F").WithLocation(19, 9), // (22,20): warning CS8629: Nullable value type may be null. // var s2y = (~Create2(y)).Value; // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "~Create2(y)").WithLocation(22, 20)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_UnaryOperator_04() { var source = @"#pragma warning disable 649 #pragma warning disable 8629 struct S<T> { public static S<T>? operator~(S<T>? s) => s; internal T F; } class Program { static S<T> Create1<T>(T t) => new S<T>(); static S<T>? Create2<T>(T t) => null; static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var s1x = (~Create1(x)).Value; s1x.F.ToString(); // 2 var s2x = (~Create2(x)).Value; s2x.F.ToString(); // 3 var s1y = (~Create1(y)).Value; s1y.F.ToString(); var s2y = (~Create2(y)).Value; s2y.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (14,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 15), // (17,9): warning CS8602: Dereference of a possibly null reference. // s1x.F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s1x.F").WithLocation(17, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // s2x.F.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2x.F").WithLocation(19, 9)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_BinaryOperator_01() { var source = @"#pragma warning disable 649 #nullable enable class A<T> { public static A<T> operator+(A<T> a, B<T> b) => a; internal T F = default!; } class B<T> { public static A<T> operator*(A<T> a, B<T> b) => a; } class Program { static A<T> CreateA<T>(T t) => new A<T>(); static B<T> CreateB<T>(T t) => new B<T>(); static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var ax = CreateA(x); var bx = CreateB(x); var ay = CreateA(y); var by = CreateB(y); (ax + bx).F.ToString(); // 2 (ax + by).F.ToString(); // 3 (ay + bx).F.ToString(); // 4 (ay + by).F.ToString(); (ax * bx).F.ToString(); // 5 (ax * by).F.ToString(); // 6 (ay * bx).F.ToString(); // 7 (ay * by).F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(18, 15), // (24,9): warning CS8602: Dereference of a possibly null reference. // (ax + bx).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(ax + bx).F").WithLocation(24, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // (ax + by).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(ax + by).F").WithLocation(25, 9), // (25,15): warning CS8620: Argument of type 'B<T>' cannot be used for parameter 'b' of type 'B<T?>' in 'A<T?> A<T?>.operator +(A<T?> a, B<T?> b)' due to differences in the nullability of reference types. // (ax + by).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "by").WithArguments("B<T>", "B<T?>", "b", "A<T?> A<T?>.operator +(A<T?> a, B<T?> b)").WithLocation(25, 15), // (26,15): warning CS8620: Argument of type 'B<T?>' cannot be used for parameter 'b' of type 'B<T>' in 'A<T> A<T>.operator +(A<T> a, B<T> b)' due to differences in the nullability of reference types. // (ay + bx).F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "bx").WithArguments("B<T?>", "B<T>", "b", "A<T> A<T>.operator +(A<T> a, B<T> b)").WithLocation(26, 15), // (28,9): warning CS8602: Dereference of a possibly null reference. // (ax * bx).F.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(ax * bx).F").WithLocation(28, 9), // (29,10): warning CS8620: Argument of type 'A<T?>' cannot be used for parameter 'a' of type 'A<T>' in 'A<T> B<T>.operator *(A<T> a, B<T> b)' due to differences in the nullability of reference types. // (ax * by).F.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "ax").WithArguments("A<T?>", "A<T>", "a", "A<T> B<T>.operator *(A<T> a, B<T> b)").WithLocation(29, 10), // (30,9): warning CS8602: Dereference of a possibly null reference. // (ay * bx).F.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(ay * bx).F").WithLocation(30, 9), // (30,10): warning CS8620: Argument of type 'A<T>' cannot be used for parameter 'a' of type 'A<T?>' in 'A<T?> B<T?>.operator *(A<T?> a, B<T?> b)' due to differences in the nullability of reference types. // (ay * bx).F.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "ay").WithArguments("A<T>", "A<T?>", "a", "A<T?> B<T?>.operator *(A<T?> a, B<T?> b)").WithLocation(30, 10)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_BinaryOperator_02() { var source = @"#pragma warning disable 649 #nullable enable class A1<T> { public static A1<T> operator+(A1<T> a, B1<T> b) => a; internal T F = default!; } class B1<T> : A1<T> { } class A2<T> { public static A2<T> operator*(A2<T> a, B2<T> b) => a; internal T F = default!; } class B2<T> : A2<T> { } class Program { static B1<T> Create1<T>(T t) => new B1<T>(); static B2<T> Create2<T>(T t) => new B2<T>(); static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var b1x = Create1(x); var b2x = Create2(x); var b1y = Create1(y); var b2y = Create2(y); (b1x + b1x).F.ToString(); // 2 (b1x + b1y).F.ToString(); // 3 (b1y + b1x).F.ToString(); // 4 (b1y + b1y).F.ToString(); (b2x * b2x).F.ToString(); // 5 (b2x * b2y).F.ToString(); // 6 (b2y * b2x).F.ToString(); // 7 (b2y * b2y).F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (25,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(25, 15), // (31,9): warning CS8602: Dereference of a possibly null reference. // (b1x + b1x).F.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b1x + b1x).F").WithLocation(31, 9), // (32,9): warning CS8602: Dereference of a possibly null reference. // (b1x + b1y).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b1x + b1y).F").WithLocation(32, 9), // (32,16): warning CS8620: Argument of type 'B1<T>' cannot be used for parameter 'b' of type 'B1<T?>' in 'A1<T?> A1<T?>.operator +(A1<T?> a, B1<T?> b)' due to differences in the nullability of reference types. // (b1x + b1y).F.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b1y").WithArguments("B1<T>", "B1<T?>", "b", "A1<T?> A1<T?>.operator +(A1<T?> a, B1<T?> b)").WithLocation(32, 16), // (33,16): warning CS8620: Argument of type 'B1<T?>' cannot be used for parameter 'b' of type 'B1<T>' in 'A1<T> A1<T>.operator +(A1<T> a, B1<T> b)' due to differences in the nullability of reference types. // (b1y + b1x).F.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b1x").WithArguments("B1<T?>", "B1<T>", "b", "A1<T> A1<T>.operator +(A1<T> a, B1<T> b)").WithLocation(33, 16), // (35,9): warning CS8602: Dereference of a possibly null reference. // (b2x * b2x).F.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b2x * b2x).F").WithLocation(35, 9), // (36,9): warning CS8602: Dereference of a possibly null reference. // (b2x * b2y).F.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(b2x * b2y).F").WithLocation(36, 9), // (36,16): warning CS8620: Argument of type 'B2<T>' cannot be used for parameter 'b' of type 'B2<T?>' in 'A2<T?> A2<T?>.operator *(A2<T?> a, B2<T?> b)' due to differences in the nullability of reference types. // (b2x * b2y).F.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b2y").WithArguments("B2<T>", "B2<T?>", "b", "A2<T?> A2<T?>.operator *(A2<T?> a, B2<T?> b)").WithLocation(36, 16), // (37,16): warning CS8620: Argument of type 'B2<T?>' cannot be used for parameter 'b' of type 'B2<T>' in 'A2<T> A2<T>.operator *(A2<T> a, B2<T> b)' due to differences in the nullability of reference types. // (b2y * b2x).F.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "b2x").WithArguments("B2<T?>", "B2<T>", "b", "A2<T> A2<T>.operator *(A2<T> a, B2<T> b)").WithLocation(37, 16)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_BinaryOperator_03() { var source = @"#pragma warning disable 649 #nullable enable struct S<T> { public static S<T> operator+(S<T> x, S<T> y) => x; internal T F; } class Program { static S<T> Create1<T>(T t) => new S<T>(); static S<T>? Create2<T>(T t) => null; static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var s1x = Create1(x); var s2x = Create2(x); var s1y = Create1(y); var s2y = Create2(y); (s1x + s1y).F.ToString(); (s1y + s1x).F.ToString(); (s1x + s2y).Value.F.ToString(); (s1y + s2x).Value.F.ToString(); (s2x + s1y).Value.F.ToString(); (s2y + s1x).Value.F.ToString(); (s2x + s2y).Value.F.ToString(); (s2y + s2x).Value.F.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (14,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(14, 15), // (20,9): warning CS8602: Dereference of a possibly null reference. // (s1x + s1y).F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s1x + s1y).F").WithLocation(20, 9), // (20,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>' in 'S<T?> S<T?>.operator +(S<T?> x, S<T?> y)' due to differences in the nullability of reference types. // (s1x + s1y).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1y").WithArguments("S<T>", "S<T?>", "y", "S<T?> S<T?>.operator +(S<T?> x, S<T?> y)").WithLocation(20, 16), // (21,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>' in 'S<T> S<T>.operator +(S<T> x, S<T> y)' due to differences in the nullability of reference types. // (s1y + s1x).F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1x").WithArguments("S<T?>", "S<T>", "y", "S<T> S<T>.operator +(S<T> x, S<T> y)").WithLocation(21, 16), // (22,9): warning CS8602: Dereference of a possibly null reference. // (s1x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s1x + s2y).Value.F").WithLocation(22, 9), // (22,10): warning CS8629: Nullable value type may be null. // (s1x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1x + s2y").WithLocation(22, 10), // (22,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>' in 'S<T?> S<T?>.operator +(S<T?> x, S<T?> y)' due to differences in the nullability of reference types. // (s1x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2y").WithArguments("S<T>", "S<T?>", "y", "S<T?> S<T?>.operator +(S<T?> x, S<T?> y)").WithLocation(22, 16), // (23,10): warning CS8629: Nullable value type may be null. // (s1y + s2x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s1y + s2x").WithLocation(23, 10), // (23,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>' in 'S<T> S<T>.operator +(S<T> x, S<T> y)' due to differences in the nullability of reference types. // (s1y + s2x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2x").WithArguments("S<T?>", "S<T>", "y", "S<T> S<T>.operator +(S<T> x, S<T> y)").WithLocation(23, 16), // (24,9): warning CS8602: Dereference of a possibly null reference. // (s2x + s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s2x + s1y).Value.F").WithLocation(24, 9), // (24,10): warning CS8629: Nullable value type may be null. // (s2x + s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2x + s1y").WithLocation(24, 10), // (24,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>' in 'S<T?> S<T?>.operator +(S<T?> x, S<T?> y)' due to differences in the nullability of reference types. // (s2x + s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1y").WithArguments("S<T>", "S<T?>", "y", "S<T?> S<T?>.operator +(S<T?> x, S<T?> y)").WithLocation(24, 16), // (25,10): warning CS8629: Nullable value type may be null. // (s2y + s1x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2y + s1x").WithLocation(25, 10), // (25,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>' in 'S<T> S<T>.operator +(S<T> x, S<T> y)' due to differences in the nullability of reference types. // (s2y + s1x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1x").WithArguments("S<T?>", "S<T>", "y", "S<T> S<T>.operator +(S<T> x, S<T> y)").WithLocation(25, 16), // (26,9): warning CS8602: Dereference of a possibly null reference. // (s2x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s2x + s2y).Value.F").WithLocation(26, 9), // (26,10): warning CS8629: Nullable value type may be null. // (s2x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2x + s2y").WithLocation(26, 10), // (26,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>' in 'S<T?> S<T?>.operator +(S<T?> x, S<T?> y)' due to differences in the nullability of reference types. // (s2x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2y").WithArguments("S<T>", "S<T?>", "y", "S<T?> S<T?>.operator +(S<T?> x, S<T?> y)").WithLocation(26, 16), // (27,10): warning CS8629: Nullable value type may be null. // (s2y + s2x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "s2y + s2x").WithLocation(27, 10), // (27,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>' in 'S<T> S<T>.operator +(S<T> x, S<T> y)' due to differences in the nullability of reference types. // (s2y + s2x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2x").WithArguments("S<T?>", "S<T>", "y", "S<T> S<T>.operator +(S<T> x, S<T> y)").WithLocation(27, 16)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_BinaryOperator_04() { var source = @"#pragma warning disable 649 #pragma warning disable 8629 struct S<T> { public static S<T>? operator+(S<T> x, S<T>? y) => x; public static S<T>? operator*(S<T>? x, S<T> y) => x; internal T F; } class Program { static S<T> Create1<T>(T t) => new S<T>(); static S<T>? Create2<T>(T t) => null; static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var s1x = Create1(x); var s2x = Create2(x); var s1y = Create1(y); var s2y = Create2(y); (s1x + s1y).Value.F.ToString(); (s1x + s2x).Value.F.ToString(); (s1x + s2y).Value.F.ToString(); (s1y + s1x).Value.F.ToString(); (s1y + s2x).Value.F.ToString(); (s1y + s2y).Value.F.ToString(); (s1x * s1y).Value.F.ToString(); (s1y * s1x).Value.F.ToString(); (s2x * s1x).Value.F.ToString(); (s2x * s1y).Value.F.ToString(); (s2y * s1x).Value.F.ToString(); (s2y * s1y).Value.F.ToString(); } }"; var comp = CreateCompilation(source, options: WithNullableEnable()); comp.VerifyDiagnostics( // (15,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(15, 15), // (21,9): warning CS8602: Dereference of a possibly null reference. // (s1x + s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s1x + s1y).Value.F").WithLocation(21, 9), // (21,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>?' in 'S<T?>? S<T?>.operator +(S<T?> x, S<T?>? y)' due to differences in the nullability of reference types. // (s1x + s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1y").WithArguments("S<T>", "S<T?>?", "y", "S<T?>? S<T?>.operator +(S<T?> x, S<T?>? y)").WithLocation(21, 16), // (22,9): warning CS8602: Dereference of a possibly null reference. // (s1x + s2x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s1x + s2x).Value.F").WithLocation(22, 9), // (23,9): warning CS8602: Dereference of a possibly null reference. // (s1x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s1x + s2y).Value.F").WithLocation(23, 9), // (23,16): warning CS8620: Argument of type 'S<T>?' cannot be used for parameter 'y' of type 'S<T?>?' in 'S<T?>? S<T?>.operator +(S<T?> x, S<T?>? y)' due to differences in the nullability of reference types. // (s1x + s2y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2y").WithArguments("S<T>?", "S<T?>?", "y", "S<T?>? S<T?>.operator +(S<T?> x, S<T?>? y)").WithLocation(23, 16), // (24,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>?' in 'S<T>? S<T>.operator +(S<T> x, S<T>? y)' due to differences in the nullability of reference types. // (s1y + s1x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1x").WithArguments("S<T?>", "S<T>?", "y", "S<T>? S<T>.operator +(S<T> x, S<T>? y)").WithLocation(24, 16), // (25,16): warning CS8620: Argument of type 'S<T?>?' cannot be used for parameter 'y' of type 'S<T>?' in 'S<T>? S<T>.operator +(S<T> x, S<T>? y)' due to differences in the nullability of reference types. // (s1y + s2x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s2x").WithArguments("S<T?>?", "S<T>?", "y", "S<T>? S<T>.operator +(S<T> x, S<T>? y)").WithLocation(25, 16), // (27,9): warning CS8602: Dereference of a possibly null reference. // (s1x * s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s1x * s1y).Value.F").WithLocation(27, 9), // (27,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>' in 'S<T?>? S<T?>.operator *(S<T?>? x, S<T?> y)' due to differences in the nullability of reference types. // (s1x * s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1y").WithArguments("S<T>", "S<T?>", "y", "S<T?>? S<T?>.operator *(S<T?>? x, S<T?> y)").WithLocation(27, 16), // (28,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>' in 'S<T>? S<T>.operator *(S<T>? x, S<T> y)' due to differences in the nullability of reference types. // (s1y * s1x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1x").WithArguments("S<T?>", "S<T>", "y", "S<T>? S<T>.operator *(S<T>? x, S<T> y)").WithLocation(28, 16), // (29,9): warning CS8602: Dereference of a possibly null reference. // (s2x * s1x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s2x * s1x).Value.F").WithLocation(29, 9), // (30,9): warning CS8602: Dereference of a possibly null reference. // (s2x * s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "(s2x * s1y).Value.F").WithLocation(30, 9), // (30,16): warning CS8620: Argument of type 'S<T>' cannot be used for parameter 'y' of type 'S<T?>' in 'S<T?>? S<T?>.operator *(S<T?>? x, S<T?> y)' due to differences in the nullability of reference types. // (s2x * s1y).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1y").WithArguments("S<T>", "S<T?>", "y", "S<T?>? S<T?>.operator *(S<T?>? x, S<T?> y)").WithLocation(30, 16), // (31,16): warning CS8620: Argument of type 'S<T?>' cannot be used for parameter 'y' of type 'S<T>' in 'S<T>? S<T>.operator *(S<T>? x, S<T> y)' due to differences in the nullability of reference types. // (s2y * s1x).Value.F.ToString(); Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "s1x").WithArguments("S<T?>", "S<T>", "y", "S<T>? S<T>.operator *(S<T>? x, S<T> y)").WithLocation(31, 16)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_BinaryLogicalOperator_01() { var source = @"#pragma warning disable 660 #pragma warning disable 661 #nullable enable class A<T> { public static A<T> operator&(A<T> x, A<T> y) => x; public static A<T> operator|(A<T> x, A<T> y) => y; public static bool operator true(A<T> a) => true; public static bool operator false(A<T> a) => false; } class B<T> : A<T> { } class Program { static A<T> CreateA<T>(T t) => new A<T>(); static B<T> CreateB<T>(T t) => new B<T>(); static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var ax = CreateA(x); var bx = CreateB(x); var ay = CreateA(y); var by = CreateB(y); _ = (ax && ay); // 2 _ = (ax && bx); _ = (ax || by); // 3 _ = (by && ax); // 4 _ = (by || ay); _ = (by || bx); // 5 } }"; var comp = CreateCompilation(source); // https://github.com/dotnet/roslyn/issues/29605: Missing warnings. comp.VerifyDiagnostics( // (20,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(20, 15)); } [Fact] [WorkItem(29605, "https://github.com/dotnet/roslyn/issues/29605")] public void ReinferMethod_BinaryLogicalOperator_02() { var source = @"#pragma warning disable 660 #pragma warning disable 661 #nullable enable struct S<T> { public static S<T> operator&(S<T> x, S<T> y) => x; public static S<T> operator|(S<T> x, S<T> y) => y; public static bool operator true(S<T>? s) => true; public static bool operator false(S<T>? s) => false; } class Program { static S<T> Create1<T>(T t) => new S<T>(); static S<T>? Create2<T>(T t) => null; static void F<T>() where T : class, new() { T x = null; // 1 T? y = new T(); var s1x = Create1(x); var s2x = Create2(x); var s1y = Create1(y); var s2y = Create2(y); _ = (s1x && s1y); // 2 _ = (s1x && s2x); _ = (s1x || s2y); // 3 _ = (s2y && s1x); // 4 _ = (s2y || s1y); _ = (s2y || s2x); // 5 } }"; var comp = CreateCompilation(source); // https://github.com/dotnet/roslyn/issues/29605: Missing warnings. comp.VerifyDiagnostics( // (17,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T x = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(17, 15)); } [Fact] [WorkItem(38726, "https://github.com/dotnet/roslyn/issues/38726")] public void CollectionInitializerBoxingConversion() { var source = @"#nullable enable using System.Collections; struct S : IEnumerable { IEnumerator IEnumerable.GetEnumerator() => null!; } static class Program { static void Add(this object x, object y) { } static T F<T>() where T : IEnumerable, new() { return new T() { 1, 2 }; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void GetAwaiterExtensionMethod() { var source = @"#nullable enable using System.Runtime.CompilerServices; using System.Threading.Tasks; class Awaitable { } static class Program { static TaskAwaiter GetAwaiter(this Awaitable? a) => default; static async Task Main() { Awaitable? x = new Awaitable(); Awaitable y = null; // 1 await x; await y; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,23): warning CS8600: Converting null literal or possible null value to non-nullable type. // Awaitable y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(11, 23)); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterExtensionMethod_Await() { var source = @"#nullable enable using System.Runtime.CompilerServices; using System.Threading.Tasks; struct StructAwaitable<T> { } static class Program { static TaskAwaiter GetAwaiter(this StructAwaitable<object?> s) => default; static StructAwaitable<T> Create<T>(T t) => new StructAwaitable<T>(); static async Task Main() { object? x = new object(); object y = null; // 1 await Create(x); // 2 await Create(y); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(12, 20), // (13,15): warning CS8620: Argument of type 'StructAwaitable<object>' cannot be used for parameter 's' of type 'StructAwaitable<object?>' in 'TaskAwaiter Program.GetAwaiter(StructAwaitable<object?> s)' due to differences in the nullability of reference types. // await Create(x); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(x)").WithArguments("StructAwaitable<object>", "StructAwaitable<object?>", "s", "TaskAwaiter Program.GetAwaiter(StructAwaitable<object?> s)").WithLocation(13, 15)); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterExtensionMethod_AwaitUsing() { var source = @"#nullable enable using System.Runtime.CompilerServices; using System.Threading.Tasks; struct StructAwaitable<T> { } class Disposable<T> { public StructAwaitable<T> DisposeAsync() => new StructAwaitable<T>(); } static class Program { static TaskAwaiter GetAwaiter(this StructAwaitable<object> s) => default; static Disposable<T> Create<T>(T t) => new Disposable<T>(); static async Task Main() { object? x = new object(); object y = null; // 1 await using (Create(x)) { } await using (Create(y)) // 2 { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { IAsyncDisposableDefinition, source }); // Should report warning for GetAwaiter(). comp.VerifyDiagnostics( // (16,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 20)); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterExtensionMethod_AwaitUsingLocal() { var source = @"#nullable enable using System.Runtime.CompilerServices; using System.Threading.Tasks; struct StructAwaitable<T> { } class Disposable<T> { public StructAwaitable<T> DisposeAsync() => new StructAwaitable<T>(); } static class Program { static TaskAwaiter GetAwaiter(this StructAwaitable<object> s) => default; static Disposable<T> Create<T>(T t) => new Disposable<T>(); static async Task Main() { object? x = new object(); object y = null; // 1 await using var dx = Create(x); await using var dy = Create(y); // 2 } }"; var comp = CreateCompilationWithTasksExtensions(new[] { IAsyncDisposableDefinition, source }); // Should report warning for GetAwaiter(). comp.VerifyDiagnostics( // (16,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(16, 20)); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterExtensionMethod_AwaitForEach() { var source = @"#nullable enable using System.Runtime.CompilerServices; using System.Threading.Tasks; struct StructAwaitable1<T> { } struct StructAwaitable2<T> { } class Enumerable<T> { public Enumerator<T> GetAsyncEnumerator() => new Enumerator<T>(); } class Enumerator<T> { public object Current => null!; public StructAwaitable1<T> MoveNextAsync() => new StructAwaitable1<T>(); public StructAwaitable2<T> DisposeAsync() => new StructAwaitable2<T>(); } static class Program { static TaskAwaiter<bool> GetAwaiter(this StructAwaitable1<object?> s) => default; static TaskAwaiter GetAwaiter(this StructAwaitable2<object> s) => default; static Enumerable<T> Create<T>(T t) => new Enumerable<T>(); static async Task Main() { object? x = new object(); object y = null; // 1 await foreach (var o in Create(x)) // 2 { } await foreach (var o in Create(y)) // 3 { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { s_IAsyncEnumerable, source }); comp.VerifyDiagnostics( // (24,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(24, 20), // (25,33): warning CS8620: Argument of type 'StructAwaitable1<object>' cannot be used for parameter 's' of type 'StructAwaitable1<object?>' in 'TaskAwaiter<bool> Program.GetAwaiter(StructAwaitable1<object?> s)' due to differences in the nullability of reference types. // await foreach (var o in Create(x)) // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(x)").WithArguments("StructAwaitable1<object>", "StructAwaitable1<object?>", "s", "TaskAwaiter<bool> Program.GetAwaiter(StructAwaitable1<object?> s)").WithLocation(25, 33), // (28,33): warning CS8620: Argument of type 'StructAwaitable2<object?>' cannot be used for parameter 's' of type 'StructAwaitable2<object>' in 'TaskAwaiter Program.GetAwaiter(StructAwaitable2<object> s)' due to differences in the nullability of reference types. // await foreach (var o in Create(y)) // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(y)").WithArguments("StructAwaitable2<object?>", "StructAwaitable2<object>", "s", "TaskAwaiter Program.GetAwaiter(StructAwaitable2<object> s)").WithLocation(28, 33) ); } [Fact] [WorkItem(30956, "https://github.com/dotnet/roslyn/issues/30956")] public void GetAwaiterExtensionMethod_AwaitForEach_InverseAnnotations() { var source = @"#nullable enable using System.Runtime.CompilerServices; using System.Threading.Tasks; struct StructAwaitable1<T> { } struct StructAwaitable2<T> { } class Enumerable<T> { public Enumerator<T> GetAsyncEnumerator() => new Enumerator<T>(); } class Enumerator<T> { public object Current => null!; public StructAwaitable1<T> MoveNextAsync() => new StructAwaitable1<T>(); public StructAwaitable2<T> DisposeAsync() => new StructAwaitable2<T>(); } static class Program { static TaskAwaiter<bool> GetAwaiter(this StructAwaitable1<object> s) => default; static TaskAwaiter GetAwaiter(this StructAwaitable2<object?> s) => default; static Enumerable<T> Create<T>(T t) => new Enumerable<T>(); static async Task Main() { object? x = new object(); object y = null; // 1 await foreach (var o in Create(x)) // 2 { } await foreach (var o in Create(y)) // 3 { } } }"; var comp = CreateCompilationWithTasksExtensions(new[] { s_IAsyncEnumerable, source }); comp.VerifyDiagnostics( // (24,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // object y = null; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "null").WithLocation(24, 20), // (25,33): warning CS8620: Argument of type 'StructAwaitable2<object>' cannot be used for parameter 's' of type 'StructAwaitable2<object?>' in 'TaskAwaiter Program.GetAwaiter(StructAwaitable2<object?> s)' due to differences in the nullability of reference types. // await foreach (var o in Create(x)) // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(x)").WithArguments("StructAwaitable2<object>", "StructAwaitable2<object?>", "s", "TaskAwaiter Program.GetAwaiter(StructAwaitable2<object?> s)").WithLocation(25, 33), // (28,33): warning CS8620: Argument of type 'StructAwaitable1<object?>' cannot be used for parameter 's' of type 'StructAwaitable1<object>' in 'TaskAwaiter<bool> Program.GetAwaiter(StructAwaitable1<object> s)' due to differences in the nullability of reference types. // await foreach (var o in Create(y)) // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "Create(y)").WithArguments("StructAwaitable1<object?>", "StructAwaitable1<object>", "s", "TaskAwaiter<bool> Program.GetAwaiter(StructAwaitable1<object> s)").WithLocation(28, 33) ); } [Fact] [WorkItem(34921, "https://github.com/dotnet/roslyn/issues/34921")] public void NullableStructMembersOfClassesAndInterfaces() { var source = @"#nullable enable interface I<T> { T P { get; } } class C<T> { internal T F = default!; } class Program { static void F1<T>(I<(T, T)> i) where T : class? { var t = i.P; t.Item1.ToString(); // 1 } static void F2<T>(C<(T, T)> c) where T : class? { var t = c.F; t.Item1.ToString();// 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (18,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(18, 9), // (24,9): warning CS8602: Dereference of a possibly null reference. // t.Item1.ToString();// 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t.Item1").WithLocation(24, 9) ); } [Fact] [WorkItem(38339, "https://github.com/dotnet/roslyn/issues/38339")] public void AllowNull_Default() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class C<T> { internal T _f1 = default(T); internal T _f2 = default; [AllowNull] internal T _f3 = default(T); [AllowNull] internal T _f4 = default; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,34): warning CS8601: Possible null reference assignment. // internal T _f1 = default(T); Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default(T)").WithLocation(5, 34), // (6,34): warning CS8601: Possible null reference assignment. // internal T _f2 = default; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(6, 34)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Join() { var source = @"#nullable enable class C<T> where T : new() { static T F1(bool b) { T t1; if (b) t1 = default(T); else t1 = default(T); return t1; // 1 } static T F2(bool b, T t) { T t2; if (b) t2 = default(T); else t2 = t; return t2; // 2 } static T F3(bool b) { T t3; if (b) t3 = default(T); else t3 = new T(); return t3; // 3 } static T F4(bool b, T t) { T t4; if (b) t4 = t; else t4 = default(T); return t4; // 4 } static T F5(bool b, T t) { T t5; if (b) t5 = t; else t5 = t; return t5; } static T F6(bool b, T t) { T t6; if (b) t6 = t; else t6 = new T(); return t6; } static T F7(bool b) { T t7; if (b) t7 = new T(); else t7 = default(T); return t7; // 5 } static T F8(bool b, T t) { T t8; if (b) t8 = new T(); else t8 = t; return t8; } static T F9(bool b) { T t9; if (b) t9 = new T(); else t9 = new T(); return t9; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,16): warning CS8603: Possible null reference return. // return t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(9, 16), // (16,16): warning CS8603: Possible null reference return. // return t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(16, 16), // (23,16): warning CS8603: Possible null reference return. // return t3; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t3").WithLocation(23, 16), // (30,16): warning CS8603: Possible null reference return. // return t4; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t4").WithLocation(30, 16), // (51,16): warning CS8603: Possible null reference return. // return t7; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t7").WithLocation(51, 16)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Meet_01() { var source = @"#nullable enable class C<T> where T : new() { static T F1() { T t1; try { t1 = default(T); } finally { t1 = default(T); } return t1; // 1 } static T F2(T t) { T t2; try { t2 = default(T); } finally { t2 = t; } return t2; } static T F3() { T t3; try { t3 = default(T); } finally { t3 = new T(); } return t3; } static T F4(T t) { T t4; try { t4 = t; } finally { t4 = default(T); } return t4; // 2 } static T F5(T t) { T t5; try { t5 = t; } finally { t5 = t; } return t5; } static T F6(T t) { T t6; try { t6 = t; } finally { t6 = new T(); } return t6; } static T F7() { T t7; try { t7 = new T(); } finally { t7 = default(T); } return t7; // 3 } static T F8(T t) { T t8; try { t8 = new T(); } finally { t8 = t; } return t8; } static T F9() { T t9; try { t9 = new T(); } finally { t9 = new T(); } return t9; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (9,16): warning CS8603: Possible null reference return. // return t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(9, 16), // (30,16): warning CS8603: Possible null reference return. // return t4; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t4").WithLocation(30, 16), // (51,16): warning CS8603: Possible null reference return. // return t7; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t7").WithLocation(51, 16)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Meet_02() { var source = @"#nullable enable class C<T> where T : new() { static bool b = false; static void F0(T t) { } static T F2(T t) { T t2 = t; T r2; try { t2 = default(T); t2 = t; } finally { if (b) F0(t2); // 1 r2 = t2; } return r2; // 2 } static T F3(T t) { T t3 = t; T r3; try { t3 = default(T); t3 = new T(); } finally { if (b) F0(t3); // 3 r3 = t3; } return r3; // 4 } static T F4(T t) { T t4 = t; T r4; try { t4 = t; t4 = default(T); } finally { if (b) F0(t4); // 5 r4 = t4; } return r4; // 6 } static T F6(T t) { T t6 = t; T r6; try { t6 = t; t6 = new T(); } finally { F0(t6); r6 = t6; } return r6; } static T F7(T t) { T t7 = t; T r7; try { t7 = new T(); t7 = default(T); } finally { if (b) F0(t7); // 7 r7 = t7; } return r7; // 8 } static T F8(T t) { T t8 = t; T r8; try { t8 = new T(); t8 = t; } finally { F0(t8); r8 = t8; } return r8; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); // Ideally, there should not be a warning for 2 or 4 because the return // statements are only executed when no exceptions are thrown. comp.VerifyDiagnostics( // (19,23): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F0(T t)'. // if (b) F0(t2); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t2").WithArguments("t", "void C<T>.F0(T t)").WithLocation(19, 23), // (22,16): warning CS8603: Possible null reference return. // return r2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "r2").WithLocation(22, 16), // (35,23): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F0(T t)'. // if (b) F0(t3); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t3").WithArguments("t", "void C<T>.F0(T t)").WithLocation(35, 23), // (38,16): warning CS8603: Possible null reference return. // return r3; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "r3").WithLocation(38, 16), // (51,23): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F0(T t)'. // if (b) F0(t4); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t4").WithArguments("t", "void C<T>.F0(T t)").WithLocation(51, 23), // (54,16): warning CS8603: Possible null reference return. // return r4; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "r4").WithLocation(54, 16), // (83,23): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F0(T t)'. // if (b) F0(t7); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t7").WithArguments("t", "void C<T>.F0(T t)").WithLocation(83, 23), // (86,16): warning CS8603: Possible null reference return. // return r7; // 8 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "r7").WithLocation(86, 16)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_01() { var source = @"#nullable enable class Program { static T F01<T>() => default(T); static T F02<T>() where T : class => default(T); static T F03<T>() where T : struct => default(T); static T F04<T>() where T : notnull => default(T); static T F05<T, U>() where U : T => default(U); static T F06<T, U>() where U : class, T => default(U); static T F07<T, U>() where U : struct, T => default(U); static T F08<T, U>() where U : notnull, T => default(U); static T F09<T>() => (T)default(T); static T F10<T>() where T : class => (T)default(T); static T F11<T>() where T : struct => (T)default(T); static T F12<T>() where T : notnull => (T)default(T); static T F13<T, U>() where U : T => (T)default(U); static T F14<T, U>() where U : class, T => (T)default(U); static T F15<T, U>() where U : struct, T => (T)default(U); static T F16<T, U>() where U : notnull, T => (T)default(U); static U F17<T, U>() where U : T => (U)default(T); static U F18<T, U>() where U : class, T => (U)default(T); static U F19<T, U>() where U : struct, T => (U)default(T); static U F20<T, U>() where U : notnull, T => (U)default(T); static U F21<T, U>() => (U)(object)default(T); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,26): warning CS8603: Possible null reference return. // static T F01<T>() => default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(4, 26), // (5,42): warning CS8603: Possible null reference return. // static T F02<T>() where T : class => default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(5, 42), // (7,44): warning CS8603: Possible null reference return. // static T F04<T>() where T : notnull => default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(7, 44), // (8,41): warning CS8603: Possible null reference return. // static T F05<T, U>() where U : T => default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(U)").WithLocation(8, 41), // (9,48): warning CS8603: Possible null reference return. // static T F06<T, U>() where U : class, T => default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(U)").WithLocation(9, 48), // (11,50): warning CS8603: Possible null reference return. // static T F08<T, U>() where U : notnull, T => default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(U)").WithLocation(11, 50), // (12,26): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F09<T>() => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(12, 26), // (12,26): warning CS8603: Possible null reference return. // static T F09<T>() => (T)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)default(T)").WithLocation(12, 26), // (13,42): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>() where T : class => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(13, 42), // (13,42): warning CS8603: Possible null reference return. // static T F10<T>() where T : class => (T)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)default(T)").WithLocation(13, 42), // (15,44): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F12<T>() where T : notnull => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(15, 44), // (15,44): warning CS8603: Possible null reference return. // static T F12<T>() where T : notnull => (T)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)default(T)").WithLocation(15, 44), // (16,41): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F13<T, U>() where U : T => (T)default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(U)").WithLocation(16, 41), // (16,41): warning CS8603: Possible null reference return. // static T F13<T, U>() where U : T => (T)default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)default(U)").WithLocation(16, 41), // (17,48): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F14<T, U>() where U : class, T => (T)default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(U)").WithLocation(17, 48), // (17,48): warning CS8603: Possible null reference return. // static T F14<T, U>() where U : class, T => (T)default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)default(U)").WithLocation(17, 48), // (19,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F16<T, U>() where U : notnull, T => (T)default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(U)").WithLocation(19, 50), // (19,50): warning CS8603: Possible null reference return. // static T F16<T, U>() where U : notnull, T => (T)default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)default(U)").WithLocation(19, 50), // (20,41): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F17<T, U>() where U : T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(20, 41), // (20,41): warning CS8603: Possible null reference return. // static U F17<T, U>() where U : T => (U)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)default(T)").WithLocation(20, 41), // (21,48): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F18<T, U>() where U : class, T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(21, 48), // (21,48): warning CS8603: Possible null reference return. // static U F18<T, U>() where U : class, T => (U)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)default(T)").WithLocation(21, 48), // (22,49): warning CS8605: Unboxing a possibly null value. // static U F19<T, U>() where U : struct, T => (U)default(T); Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)default(T)").WithLocation(22, 49), // (23,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F20<T, U>() where U : notnull, T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(23, 50), // (23,50): warning CS8603: Possible null reference return. // static U F20<T, U>() where U : notnull, T => (U)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)default(T)").WithLocation(23, 50), // (24,29): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>() => (U)(object)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)default(T)").WithLocation(24, 29), // (24,29): warning CS8603: Possible null reference return. // static U F21<T, U>() => (U)(object)default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)(object)default(T)").WithLocation(24, 29), // (24,32): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>() => (U)(object)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)default(T)").WithLocation(24, 32)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_02() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F01<T>() => default(T); [return: MaybeNull]static T F02<T>() where T : class => default(T); [return: MaybeNull]static T F03<T>() where T : struct => default(T); [return: MaybeNull]static T F04<T>() where T : notnull => default(T); [return: MaybeNull]static T F05<T, U>() where U : T => default(U); [return: MaybeNull]static T F06<T, U>() where U : class, T => default(U); [return: MaybeNull]static T F07<T, U>() where U : struct, T => default(U); [return: MaybeNull]static T F08<T, U>() where U : notnull, T => default(U); [return: MaybeNull]static T F09<T>() => (T)default(T); [return: MaybeNull]static T F10<T>() where T : class => (T)default(T); [return: MaybeNull]static T F11<T>() where T : struct => (T)default(T); [return: MaybeNull]static T F12<T>() where T : notnull => (T)default(T); [return: MaybeNull]static T F13<T, U>() where U : T => (T)default(U); [return: MaybeNull]static T F14<T, U>() where U : class, T => (T)default(U); [return: MaybeNull]static T F15<T, U>() where U : struct, T => (T)default(U); [return: MaybeNull]static T F16<T, U>() where U : notnull, T => (T)default(U); [return: MaybeNull]static U F17<T, U>() where U : T => (U)default(T); [return: MaybeNull]static U F18<T, U>() where U : class, T => (U)default(T); [return: MaybeNull]static U F19<T, U>() where U : struct, T => (U)default(T); [return: MaybeNull]static U F20<T, U>() where U : notnull, T => (U)default(T); [return: MaybeNull]static U F21<T, U>() => (U)(object)default(T); }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (14,61): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F10<T>() where T : class => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(14, 61), // (22,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F18<T, U>() where U : class, T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(22, 67), // (23,68): warning CS8605: Unboxing a possibly null value. // [return: MaybeNull]static U F19<T, U>() where U : struct, T => (U)default(T); Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)default(T)").WithLocation(23, 68), // (25,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>() => (U)(object)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)default(T)").WithLocation(25, 51)); comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,45): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F09<T>() => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(13, 45), // (14,61): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F10<T>() where T : class => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(14, 61), // (16,63): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F12<T>() where T : notnull => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(16, 63), // (17,60): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F13<T, U>() where U : T => (T)default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(U)").WithLocation(17, 60), // (18,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F14<T, U>() where U : class, T => (T)default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(U)").WithLocation(18, 67), // (20,69): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F16<T, U>() where U : notnull, T => (T)default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(U)").WithLocation(20, 69), // (21,60): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F17<T, U>() where U : T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(21, 60), // (22,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F18<T, U>() where U : class, T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(22, 67), // (23,68): warning CS8605: Unboxing a possibly null value. // [return: MaybeNull]static U F19<T, U>() where U : struct, T => (U)default(T); Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)default(T)").WithLocation(23, 68), // (24,69): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F20<T, U>() where U : notnull, T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(24, 69), // (25,48): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>() => (U)(object)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)default(T)").WithLocation(25, 48), // (25,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>() => (U)(object)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)default(T)").WithLocation(25, 51)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_02A() { var source = @"#nullable enable class Program { static T? F02<T>() where T : class => default(T); static T? F10<T>() where T : class => (T)default(T); static U? F18<T, U>() where U : class, T => (U)default(T); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,43): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T? F10<T>() where T : class => (T)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)default(T)").WithLocation(5, 43), // (6,49): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U? F18<T, U>() where U : class, T => (U)default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)default(T)").WithLocation(6, 49)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_03() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static T F01<T>([AllowNull]T t) => t; static T F02<T>([AllowNull]T t) where T : class => t; static T F03<T>([AllowNull]T t) where T : struct => t; static T F04<T>([AllowNull]T t) where T : notnull => t; static T F05<T, U>([AllowNull]U u) where U : T => u; static T F06<T, U>([AllowNull]U u) where U : class, T => u; static T F07<T, U>([AllowNull]U u) where U : struct, T => u; static T F08<T, U>([AllowNull]U u) where U : notnull, T => u; static T F09<T>([AllowNull]T t) => (T)t; static T F10<T>([AllowNull]T t) where T : class => (T)t; static T F11<T>([AllowNull]T t) where T : struct => (T)t; static T F12<T>([AllowNull]T t) where T : notnull => (T)t; static T F13<T, U>([AllowNull]U u) where U : T => (T)u; static T F14<T, U>([AllowNull]U u) where U : class, T => (T)u; static T F15<T, U>([AllowNull]U u) where U : struct, T => (T)u; static T F16<T, U>([AllowNull]U u) where U : notnull, T => (T)u; static U F17<T, U>([AllowNull]T t) where U : T => (U)t; static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; static U F19<T, U>([AllowNull]T t) where U : struct, T => (U)t; static U F20<T, U>([AllowNull]T t) where U : notnull, T => (U)t; static U F21<T, U>([AllowNull]T t) => (U)(object)t; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,40): warning CS8603: Possible null reference return. // static T F01<T>([AllowNull]T t) => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(5, 40), // (6,56): warning CS8603: Possible null reference return. // static T F02<T>([AllowNull]T t) where T : class => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 56), // (8,58): warning CS8603: Possible null reference return. // static T F04<T>([AllowNull]T t) where T : notnull => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(8, 58), // (9,55): warning CS8603: Possible null reference return. // static T F05<T, U>([AllowNull]U u) where U : T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 55), // (10,62): warning CS8603: Possible null reference return. // static T F06<T, U>([AllowNull]U u) where U : class, T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 62), // (12,64): warning CS8603: Possible null reference return. // static T F08<T, U>([AllowNull]U u) where U : notnull, T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(12, 64), // (13,40): warning CS8603: Possible null reference return. // static T F09<T>([AllowNull]T t) => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(13, 40), // (14,56): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>([AllowNull]T t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(14, 56), // (14,56): warning CS8603: Possible null reference return. // static T F10<T>([AllowNull]T t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(14, 56), // (16,58): warning CS8603: Possible null reference return. // static T F12<T>([AllowNull]T t) where T : notnull => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(16, 58), // (17,55): warning CS8603: Possible null reference return. // static T F13<T, U>([AllowNull]U u) where U : T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(17, 55), // (18,62): warning CS8603: Possible null reference return. // static T F14<T, U>([AllowNull]U u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(18, 62), // (20,64): warning CS8603: Possible null reference return. // static T F16<T, U>([AllowNull]U u) where U : notnull, T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(20, 64), // (21,55): warning CS8603: Possible null reference return. // static U F17<T, U>([AllowNull]T t) where U : T => (U)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(21, 55), // (22,62): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 62), // (22,62): warning CS8603: Possible null reference return. // static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(22, 62), // (23,63): warning CS8605: Unboxing a possibly null value. // static U F19<T, U>([AllowNull]T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(23, 63), // (24,64): warning CS8603: Possible null reference return. // static U F20<T, U>([AllowNull]T t) where U : notnull, T => (U)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(24, 64), // (25,43): warning CS8603: Possible null reference return. // static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)(object)t").WithLocation(25, 43), // (25,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(25, 46)); comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,40): warning CS8603: Possible null reference return. // static T F01<T>([AllowNull]T t) => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(5, 40), // (6,56): warning CS8603: Possible null reference return. // static T F02<T>([AllowNull]T t) where T : class => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 56), // (8,58): warning CS8603: Possible null reference return. // static T F04<T>([AllowNull]T t) where T : notnull => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(8, 58), // (9,55): warning CS8603: Possible null reference return. // static T F05<T, U>([AllowNull]U u) where U : T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 55), // (10,62): warning CS8603: Possible null reference return. // static T F06<T, U>([AllowNull]U u) where U : class, T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 62), // (12,64): warning CS8603: Possible null reference return. // static T F08<T, U>([AllowNull]U u) where U : notnull, T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(12, 64), // (13,40): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F09<T>([AllowNull]T t) => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(13, 40), // (13,40): warning CS8603: Possible null reference return. // static T F09<T>([AllowNull]T t) => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(13, 40), // (14,56): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>([AllowNull]T t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(14, 56), // (14,56): warning CS8603: Possible null reference return. // static T F10<T>([AllowNull]T t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(14, 56), // (16,58): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F12<T>([AllowNull]T t) where T : notnull => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(16, 58), // (16,58): warning CS8603: Possible null reference return. // static T F12<T>([AllowNull]T t) where T : notnull => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(16, 58), // (17,55): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F13<T, U>([AllowNull]U u) where U : T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(17, 55), // (17,55): warning CS8603: Possible null reference return. // static T F13<T, U>([AllowNull]U u) where U : T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(17, 55), // (18,62): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F14<T, U>([AllowNull]U u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(18, 62), // (18,62): warning CS8603: Possible null reference return. // static T F14<T, U>([AllowNull]U u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(18, 62), // (20,64): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F16<T, U>([AllowNull]U u) where U : notnull, T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(20, 64), // (20,64): warning CS8603: Possible null reference return. // static T F16<T, U>([AllowNull]U u) where U : notnull, T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(20, 64), // (21,55): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F17<T, U>([AllowNull]T t) where U : T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(21, 55), // (21,55): warning CS8603: Possible null reference return. // static U F17<T, U>([AllowNull]T t) where U : T => (U)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(21, 55), // (22,62): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 62), // (22,62): warning CS8603: Possible null reference return. // static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(22, 62), // (23,63): warning CS8605: Unboxing a possibly null value. // static U F19<T, U>([AllowNull]T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(23, 63), // (24,64): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F20<T, U>([AllowNull]T t) where U : notnull, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(24, 64), // (24,64): warning CS8603: Possible null reference return. // static U F20<T, U>([AllowNull]T t) where U : notnull, T => (U)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)t").WithLocation(24, 64), // (25,43): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)t").WithLocation(25, 43), // (25,43): warning CS8603: Possible null reference return. // static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(U)(object)t").WithLocation(25, 43), // (25,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(25, 46)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_03A() { var source = @"#nullable enable class Program { static T F02<T>(T? t) where T : class => t; static T F06<T, U>(U? u) where U : class, T => u; static T F10<T>(T? t) where T : class => (T)t; static T F14<T, U>(U? u) where U : class, T => (T)u; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,46): warning CS8603: Possible null reference return. // static T F02<T>(T? t) where T : class => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(4, 46), // (5,52): warning CS8603: Possible null reference return. // static T F06<T, U>(U? u) where U : class, T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 52), // (6,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>(T? t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(6, 46), // (6,46): warning CS8603: Possible null reference return. // static T F10<T>(T? t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(6, 46), // (7,52): warning CS8603: Possible null reference return. // static T F14<T, U>(U? u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(7, 52)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,46): warning CS8603: Possible null reference return. // static T F02<T>(T? t) where T : class => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(4, 46), // (5,52): warning CS8603: Possible null reference return. // static T F06<T, U>(U? u) where U : class, T => u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 52), // (6,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>(T? t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(6, 46), // (6,46): warning CS8603: Possible null reference return. // static T F10<T>(T? t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)t").WithLocation(6, 46), // (7,52): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F14<T, U>(U? u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(7, 52), // (7,52): warning CS8603: Possible null reference return. // static T F14<T, U>(U? u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)u").WithLocation(7, 52)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_04() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F01<T>(T t) => t; [return: MaybeNull]static T F02<T>(T t) where T : class => t; [return: MaybeNull]static T F03<T>(T t) where T : struct => t; [return: MaybeNull]static T F04<T>(T t) where T : notnull => t; [return: MaybeNull]static T F05<T, U>(U u) where U : T => u; [return: MaybeNull]static T F06<T, U>(U u) where U : class, T => u; [return: MaybeNull]static T F07<T, U>(U u) where U : struct, T => u; [return: MaybeNull]static T F08<T, U>(U u) where U : notnull, T => u; [return: MaybeNull]static T F09<T>(T t) => (T)t; [return: MaybeNull]static T F10<T>(T t) where T : class => (T)t; [return: MaybeNull]static T F11<T>(T t) where T : struct => (T)t; [return: MaybeNull]static T F12<T>(T t) where T : notnull => (T)t; [return: MaybeNull]static T F13<T, U>(U u) where U : T => (T)u; [return: MaybeNull]static T F14<T, U>(U u) where U : class, T => (T)u; [return: MaybeNull]static T F15<T, U>(U u) where U : struct, T => (T)u; [return: MaybeNull]static T F16<T, U>(U u) where U : notnull, T => (T)u; [return: MaybeNull]static U F17<T, U>(T t) where U : T => (U)t; [return: MaybeNull]static U F18<T, U>(T t) where U : class, T => (U)t; [return: MaybeNull]static U F19<T, U>(T t) where U : struct, T => (U)t; [return: MaybeNull]static U F20<T, U>(T t) where U : notnull, T => (U)t; [return: MaybeNull]static U F21<T, U>(T t) => (U)(object)t; }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (22,70): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F18<T, U>(T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 70), // (23,71): warning CS8605: Unboxing a possibly null value. // [return: MaybeNull]static U F19<T, U>(T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(23, 71), // (25,54): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>(T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(25, 54)); comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (21,63): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F17<T, U>(T t) where U : T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(21, 63), // (22,70): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F18<T, U>(T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 70), // (23,71): warning CS8605: Unboxing a possibly null value. // [return: MaybeNull]static U F19<T, U>(T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(23, 71), // (24,72): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F20<T, U>(T t) where U : notnull, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(24, 72), // (25,51): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>(T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)t").WithLocation(25, 51), // (25,54): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>(T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(25, 54)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_04A() { var source = @"#nullable enable class Program { static T? F02<T>(T t) where T : class => t; static T? F10<T>(T t) where T : class => (T)t; static U? F18<T, U>(T t) where U : class, T => (U)t; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,52): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U? F18<T, U>(T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(6, 52)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_05() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F01<T>([AllowNull]T t) => t; [return: MaybeNull]static T F02<T>([AllowNull]T t) where T : class => t; [return: MaybeNull]static T F03<T>([AllowNull]T t) where T : struct => t; [return: MaybeNull]static T F04<T>([AllowNull]T t) where T : notnull => t; [return: MaybeNull]static T F05<T, U>([AllowNull]U u) where U : T => u; [return: MaybeNull]static T F06<T, U>([AllowNull]U u) where U : class, T => u; [return: MaybeNull]static T F07<T, U>([AllowNull]U u) where U : struct, T => u; [return: MaybeNull]static T F08<T, U>([AllowNull]U u) where U : notnull, T => u; [return: MaybeNull]static T F09<T>([AllowNull]T t) => (T)t; [return: MaybeNull]static T F10<T>([AllowNull]T t) where T : class => (T)t; [return: MaybeNull]static T F11<T>([AllowNull]T t) where T : struct => (T)t; [return: MaybeNull]static T F12<T>([AllowNull]T t) where T : notnull => (T)t; [return: MaybeNull]static T F13<T, U>([AllowNull]U u) where U : T => (T)u; [return: MaybeNull]static T F14<T, U>([AllowNull]U u) where U : class, T => (T)u; [return: MaybeNull]static T F15<T, U>([AllowNull]U u) where U : struct, T => (T)u; [return: MaybeNull]static T F16<T, U>([AllowNull]U u) where U : notnull, T => (T)u; [return: MaybeNull]static U F17<T, U>([AllowNull]T t) where U : T => (U)t; [return: MaybeNull]static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; [return: MaybeNull]static U F19<T, U>([AllowNull]T t) where U : struct, T => (U)t; [return: MaybeNull]static U F20<T, U>([AllowNull]T t) where U : notnull, T => (U)t; [return: MaybeNull]static U F21<T, U>([AllowNull]T t) => (U)(object)t; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (14,75): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F10<T>([AllowNull]T t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(14, 75), // (22,81): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 81), // (23,82): warning CS8605: Unboxing a possibly null value. // [return: MaybeNull]static U F19<T, U>([AllowNull]T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(23, 82), // (25,65): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(25, 65)); comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,59): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F09<T>([AllowNull]T t) => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(13, 59), // (14,75): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F10<T>([AllowNull]T t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(14, 75), // (16,77): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F12<T>([AllowNull]T t) where T : notnull => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(16, 77), // (17,74): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F13<T, U>([AllowNull]U u) where U : T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(17, 74), // (18,81): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F14<T, U>([AllowNull]U u) where U : class, T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(18, 81), // (20,83): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F16<T, U>([AllowNull]U u) where U : notnull, T => (T)u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)u").WithLocation(20, 83), // (21,74): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F17<T, U>([AllowNull]T t) where U : T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(21, 74), // (22,81): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(22, 81), // (23,82): warning CS8605: Unboxing a possibly null value. // [return: MaybeNull]static U F19<T, U>([AllowNull]T t) where U : struct, T => (U)t; Diagnostic(ErrorCode.WRN_UnboxPossibleNull, "(U)t").WithLocation(23, 82), // (24,83): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F20<T, U>([AllowNull]T t) where U : notnull, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(24, 83), // (25,62): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)(object)t").WithLocation(25, 62), // (25,65): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static U F21<T, U>([AllowNull]T t) => (U)(object)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(object)t").WithLocation(25, 65)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_05A() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static T? F02<T>(T? t) where T : class => t; static T? F10<T>(T? t) where T : class => (T)t; static U? F18<T, U>([AllowNull]T t) where U : class, T => (U)t; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (6,47): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T? F10<T>(T? t) where T : class => (T)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)t").WithLocation(6, 47), // (7,63): warning CS8600: Converting null literal or possible null value to non-nullable type. // static U? F18<T, U>([AllowNull]T t) where U : class, T => (U)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(7, 63)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_06() { var source = @"#nullable enable class Program { static T F01<T>(dynamic? d) => d; static T F02<T>(dynamic? d) where T : class => d; static T F03<T>(dynamic? d) where T : struct => d; static T F04<T>(dynamic? d) where T : notnull => d; static T F09<T>(dynamic? d) => (T)d; static T F10<T>(dynamic? d) where T : class => (T)d; static T F11<T>(dynamic? d) where T : struct => (T)d; static T F12<T>(dynamic? d) where T : notnull => (T)d; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,36): warning CS8603: Possible null reference return. // static T F01<T>(dynamic? d) => d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "d").WithLocation(4, 36), // (5,52): warning CS8603: Possible null reference return. // static T F02<T>(dynamic? d) where T : class => d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "d").WithLocation(5, 52), // (7,54): warning CS8603: Possible null reference return. // static T F04<T>(dynamic? d) where T : notnull => d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "d").WithLocation(7, 54), // (8,36): warning CS8603: Possible null reference return. // static T F09<T>(dynamic? d) => (T)d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)d").WithLocation(8, 36), // (9,52): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>(dynamic? d) where T : class => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(9, 52), // (9,52): warning CS8603: Possible null reference return. // static T F10<T>(dynamic? d) where T : class => (T)d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)d").WithLocation(9, 52), // (11,54): warning CS8603: Possible null reference return. // static T F12<T>(dynamic? d) where T : notnull => (T)d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)d").WithLocation(11, 54)); comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,36): warning CS8603: Possible null reference return. // static T F01<T>(dynamic? d) => d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "d").WithLocation(4, 36), // (5,52): warning CS8603: Possible null reference return. // static T F02<T>(dynamic? d) where T : class => d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "d").WithLocation(5, 52), // (7,54): warning CS8603: Possible null reference return. // static T F04<T>(dynamic? d) where T : notnull => d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "d").WithLocation(7, 54), // (8,36): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F09<T>(dynamic? d) => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(8, 36), // (8,36): warning CS8603: Possible null reference return. // static T F09<T>(dynamic? d) => (T)d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)d").WithLocation(8, 36), // (9,52): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F10<T>(dynamic? d) where T : class => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(9, 52), // (9,52): warning CS8603: Possible null reference return. // static T F10<T>(dynamic? d) where T : class => (T)d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)d").WithLocation(9, 52), // (11,54): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F12<T>(dynamic? d) where T : notnull => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(11, 54), // (11,54): warning CS8603: Possible null reference return. // static T F12<T>(dynamic? d) where T : notnull => (T)d; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T)d").WithLocation(11, 54)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_07() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F01<T>(dynamic? d) => d; [return: MaybeNull]static T F02<T>(dynamic? d) where T : class => d; [return: MaybeNull]static T F03<T>(dynamic? d) where T : struct => d; [return: MaybeNull]static T F04<T>(dynamic? d) where T : notnull => d; [return: MaybeNull]static T F09<T>(dynamic? d) => (T)d; [return: MaybeNull]static T F10<T>(dynamic? d) where T : class => (T)d; [return: MaybeNull]static T F11<T>(dynamic? d) where T : struct => (T)d; [return: MaybeNull]static T F12<T>(dynamic? d) where T : notnull => (T)d; }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (10,71): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F10<T>(dynamic? d) where T : class => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(10, 71)); comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,55): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F09<T>(dynamic? d) => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(9, 55), // (10,71): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F10<T>(dynamic? d) where T : class => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(10, 71), // (12,73): warning CS8600: Converting null literal or possible null value to non-nullable type. // [return: MaybeNull]static T F12<T>(dynamic? d) where T : notnull => (T)d; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)d").WithLocation(12, 73)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_08() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static dynamic F01<T>([AllowNull]T t) => t; static dynamic F02<T>([AllowNull]T t) where T : class => t; static dynamic F03<T>([AllowNull]T t) where T : struct => t; static dynamic F04<T>([AllowNull]T t) where T : notnull => t; static dynamic F09<T>([AllowNull]T t) => (dynamic)t; static dynamic F10<T>([AllowNull]T t) where T : class => (dynamic)t; static dynamic F11<T>([AllowNull]T t) where T : struct => (dynamic)t; static dynamic F12<T>([AllowNull]T t) where T : notnull => (dynamic)t; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,46): warning CS8603: Possible null reference return. // static dynamic F01<T>([AllowNull]T t) => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(5, 46), // (6,62): warning CS8603: Possible null reference return. // static dynamic F02<T>([AllowNull]T t) where T : class => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 62), // (8,64): warning CS8603: Possible null reference return. // static dynamic F04<T>([AllowNull]T t) where T : notnull => t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(8, 64), // (9,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // static dynamic F09<T>([AllowNull]T t) => (dynamic)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(dynamic)t").WithLocation(9, 46), // (9,46): warning CS8603: Possible null reference return. // static dynamic F09<T>([AllowNull]T t) => (dynamic)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(dynamic)t").WithLocation(9, 46), // (10,62): warning CS8600: Converting null literal or possible null value to non-nullable type. // static dynamic F10<T>([AllowNull]T t) where T : class => (dynamic)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(dynamic)t").WithLocation(10, 62), // (10,62): warning CS8603: Possible null reference return. // static dynamic F10<T>([AllowNull]T t) where T : class => (dynamic)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(dynamic)t").WithLocation(10, 62), // (12,64): warning CS8600: Converting null literal or possible null value to non-nullable type. // static dynamic F12<T>([AllowNull]T t) where T : notnull => (dynamic)t; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(dynamic)t").WithLocation(12, 64), // (12,64): warning CS8603: Possible null reference return. // static dynamic F12<T>([AllowNull]T t) where T : notnull => (dynamic)t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(dynamic)t").WithLocation(12, 64)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_Conversions_09() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static dynamic? F01<T>([AllowNull]T t) => t; static dynamic? F02<T>([AllowNull]T t) where T : class => t; static dynamic? F03<T>([AllowNull]T t) where T : struct => t; static dynamic? F04<T>([AllowNull]T t) where T : notnull => t; static dynamic? F09<T>([AllowNull]T t) => (dynamic?)t; static dynamic? F10<T>([AllowNull]T t) where T : class => (dynamic?)t; static dynamic? F11<T>([AllowNull]T t) where T : struct => (dynamic?)t; static dynamic? F12<T>([AllowNull]T t) where T : notnull => (dynamic?)t; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_01() { var source = @"#nullable enable using System; using System.Diagnostics.CodeAnalysis; class C<T> where T : class? { public C(T x) => f = x; T f; T P1 { get => f; set => f = value; } [AllowNull] T P2 { get => f; set => f = value ?? throw new ArgumentNullException(); } [MaybeNull] T P3 { get => default!; set => f = value; } void M1() { P1 = null; // 1 P2 = null; P3 = null; // 2 } void M2() { f = P1; f = P2; f = P3; // 3 } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // P1 = null; // 1 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(13, 14), // (15,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // P3 = null; // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 14), // (21,13): warning CS8601: Possible null reference assignment. // f = P3; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "P3").WithLocation(21, 13)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_02() { var source = @"#nullable enable class C<T> { internal T F = default!; static C<T> F0() => throw null!; static T F1() { T t = default(T); return t; // 1 } static void F2() { var t = default(T); F0().F = t; // 2 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t = default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(T)").WithLocation(8, 15), // (9,16): warning CS8603: Possible null reference return. // return t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(9, 16), // (14,18): warning CS8601: Possible null reference assignment. // F0().F = t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(14, 18)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_03() { var source = @"#nullable enable class Program { static void M<T>() where T : notnull { if (default(T) == null) { } } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_04() { var source = @"#nullable enable #pragma warning disable 649 using System.Diagnostics.CodeAnalysis; class C<T> { [MaybeNull]T F = default!; static void M(C<T> x, C<T> y) { if (x.F == null) return; x.F.ToString(); y.F.ToString(); // 1 } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // y.F.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y.F").WithLocation(11, 9)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_05() { var source = @"#nullable enable class Program { static void M<T>() where T : notnull { var t = default(T); t.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(7, 9)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_06() { var source = @"#nullable enable class Program { static void M<T>() where T : notnull { T t = default; t.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(6, 15), // (7,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(7, 9)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_07() { var source = @"#nullable enable class Program { static void M<T>(T t) where T : notnull { if (t == null) { } t.ToString(); // 1 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // t.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "t").WithLocation(7, 9)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_08() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F<T>() => throw null!; static T1 F1<T1>() { return F<T1>(); // 1 } static T2 F2<T2>() where T2 : notnull { return F<T2>(); // 2 } static T3 F3<T3>() where T3 : class { return F<T3>(); // 3 } static T4 F4<T4>() where T4 : class? { return F<T4>(); // 4 } static T5 F5<T5>() where T5 : struct { return F<T5>(); } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (8,16): warning CS8603: Possible null reference return. // return F<T1>(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "F<T1>()").WithLocation(8, 16), // (12,16): warning CS8603: Possible null reference return. // return F<T2>(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "F<T2>()").WithLocation(12, 16), // (16,16): warning CS8603: Possible null reference return. // return F<T3>(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "F<T3>()").WithLocation(16, 16), // (20,16): warning CS8603: Possible null reference return. // return F<T4>(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "F<T4>()").WithLocation(20, 16)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_09() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F<T>() => throw null!; [return: MaybeNull]static T1 F1<T1>() { return F<T1>(); } [return: MaybeNull]static T2 F2<T2>() where T2 : notnull { return F<T2>(); } [return: MaybeNull]static T3 F3<T3>() where T3 : class { return F<T3>(); } [return: MaybeNull]static T4 F4<T4>() where T4 : class? { return F<T4>(); } [return: MaybeNull]static T5 F5<T5>() where T5 : struct { return F<T5>(); } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_10() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F<T>() => throw null!; static T1 F1<T1>() { T1 t1 = F<T1>(); return t1; } static T2 F2<T2>() where T2 : notnull { T2 t2 = F<T2>(); return t2; } static T3 F3<T3>() where T3 : class { T3 t3 = F<T3>(); return t3; } static T4 F4<T4>() where T4 : class? { T4 t4 = F<T4>(); return t4; } static T5 F5<T5>() where T5 : struct { T5 t5 = F<T5>(); return t5; } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (8,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T1 t1 = F<T1>(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F<T1>()").WithLocation(8, 17), // (9,16): warning CS8603: Possible null reference return. // return t1; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(9, 16), // (13,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T2 t2 = F<T2>(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F<T2>()").WithLocation(13, 17), // (14,16): warning CS8603: Possible null reference return. // return t2; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(14, 16), // (18,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T3 t3 = F<T3>(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F<T3>()").WithLocation(18, 17), // (19,16): warning CS8603: Possible null reference return. // return t3; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t3").WithLocation(19, 16), // (23,17): warning CS8600: Converting null literal or possible null value to non-nullable type. // T4 t4 = F<T4>(); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "F<T4>()").WithLocation(23, 17), // (24,16): warning CS8603: Possible null reference return. // return t4; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t4").WithLocation(24, 16)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_11() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F<T>() => throw null!; static T M<T>() where T : notnull { var t = F<T>(); return t; // 1 } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (9,16): warning CS8603: Possible null reference return. // return t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(9, 16)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_12() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static T Identity<T>(T t) => t; [return: MaybeNull]static T F<T>() => throw null!; static T F1<T>() => Identity(F<T>()); // 1 static T F2<T>() where T : notnull => Identity(F<T>()); // 2 static T F3<T>() where T : class => Identity(F<T>()); // 3 static T F4<T>() where T : class? => Identity(F<T>()); // 4 static T F5<T>() where T : struct => Identity(F<T>()); }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (7,25): warning CS8603: Possible null reference return. // static T F1<T>() => Identity(F<T>()); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Identity(F<T>())").WithLocation(7, 25), // (8,43): warning CS8603: Possible null reference return. // static T F2<T>() where T : notnull => Identity(F<T>()); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Identity(F<T>())").WithLocation(8, 43), // (9,41): warning CS8603: Possible null reference return. // static T F3<T>() where T : class => Identity(F<T>()); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Identity(F<T>())").WithLocation(9, 41), // (10,42): warning CS8603: Possible null reference return. // static T F4<T>() where T : class? => Identity(F<T>()); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "Identity(F<T>())").WithLocation(10, 42)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_13() { var source = @"#nullable enable class Program { static void F1<T>(object? x1) { var y1 = (T)x1; _ = y1.ToString(); // 1 } static void F2<T>(object? x2) { var y2 = (T)x2!; _ = y2.ToString(); } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,18): warning CS8600: Converting null literal or possible null value to non-nullable type. // var y1 = (T)x1; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)x1").WithLocation(6, 18), // (7,13): warning CS8602: Dereference of a possibly null reference. // _ = y1.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(7, 13)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_14() { var source = @"#nullable enable #pragma warning disable 414 using System.Diagnostics.CodeAnalysis; class C<T> { T F1 = default; [AllowNull]T F2 = default; [MaybeNull]T F3 = default; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (6,12): warning CS8601: Possible null reference assignment. // T F1 = default; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(6, 12), // (8,23): warning CS8601: Possible null reference assignment. // [MaybeNull]T F3 = default; Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(8, 23)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_15() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class C<T> { T F1 = default!; [AllowNull]T F2 = default!; [MaybeNull]T F3 = default!; void M1(T x, [AllowNull]T y) { F1 = x; F2 = x; F3 = x; F1 = y; // 1 F2 = y; F3 = y; // 2 } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (13,14): warning CS8601: Possible null reference assignment. // F1 = y; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(13, 14), // (15,14): warning CS8601: Possible null reference assignment. // F3 = y; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y").WithLocation(15, 14)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_16() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static T F1<T, U>(bool b, T t, U u) where U : T => b ? t : u; static T F2<T, U>(bool b, T t, [AllowNull]U u) where U : T => b ? t : u; static T F3<T, U>(bool b, [AllowNull]T t, U u) where U : T => b ? t : u; static T F4<T, U>(bool b, [AllowNull]T t, [AllowNull]U u) where U : T => b ? t : u; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (6,67): warning CS8603: Possible null reference return. // static T F2<T, U>(bool b, T t, [AllowNull]U u) where U : T => b ? t : u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? t : u").WithLocation(6, 67), // (7,67): warning CS8603: Possible null reference return. // static T F3<T, U>(bool b, [AllowNull]T t, U u) where U : T => b ? t : u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? t : u").WithLocation(7, 67), // (8,78): warning CS8603: Possible null reference return. // static T F4<T, U>(bool b, [AllowNull]T t, [AllowNull]U u) where U : T => b ? t : u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? t : u").WithLocation(8, 78)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_17() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static T F0<T>(T t) => t ?? default; static T F1<T>(T t) => t ?? default(T); static T F2<T, U>(T t) where U : T => t ?? default(U); static T F3<T, U>(T t, U u) where U : T => t ?? u; static T F4<T, U>(T t, [AllowNull]U u) where U : T => t ?? u; static T F5<T, U>([AllowNull]T t, U u) where U : T => t ?? u; static T F6<T, U>([AllowNull]T t, [AllowNull]U u) where U : T => t ?? u; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,28): warning CS8603: Possible null reference return. // static T F0<T>(T t) => t ?? default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ?? default").WithLocation(5, 28), // (6,28): warning CS8603: Possible null reference return. // static T F1<T>(T t) => t ?? default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ?? default(T)").WithLocation(6, 28), // (7,43): warning CS8603: Possible null reference return. // static T F2<T, U>(T t) where U : T => t ?? default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ?? default(U)").WithLocation(7, 43), // (9,59): warning CS8603: Possible null reference return. // static T F4<T, U>(T t, [AllowNull]U u) where U : T => t ?? u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ?? u").WithLocation(9, 59), // (11,70): warning CS8603: Possible null reference return. // static T F6<T, U>([AllowNull]T t, [AllowNull]U u) where U : T => t ?? u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ?? u").WithLocation(11, 70)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_18() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static T F0<T>(T t) => t ??= default; static T F1<T>(T t) => t ??= default(T); static T F2<T, U>(T t) where U : T => t ??= default(U); static T F3<T, U>(T t, U u) where U : T => t ??= u; static T F4<T, U>(T t, [AllowNull]U u) where U : T => t ??= u; static T F5<T, U>([AllowNull]T t, U u) where U : T => t ??= u; static T F6<T, U>([AllowNull]T t, [AllowNull]U u) where U : T => t ??= u; }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,28): warning CS8603: Possible null reference return. // static T F0<T>(T t) => t ??= default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ??= default").WithLocation(5, 28), // (5,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F0<T>(T t) => t ??= default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(5, 34), // (6,28): warning CS8603: Possible null reference return. // static T F1<T>(T t) => t ??= default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ??= default(T)").WithLocation(6, 28), // (6,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F1<T>(T t) => t ??= default(T); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(T)").WithLocation(6, 34), // (7,43): warning CS8603: Possible null reference return. // static T F2<T, U>(T t) where U : T => t ??= default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ??= default(U)").WithLocation(7, 43), // (7,49): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F2<T, U>(T t) where U : T => t ??= default(U); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(U)").WithLocation(7, 49), // (9,59): warning CS8603: Possible null reference return. // static T F4<T, U>(T t, [AllowNull]U u) where U : T => t ??= u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ??= u").WithLocation(9, 59), // (9,65): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F4<T, U>(T t, [AllowNull]U u) where U : T => t ??= u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(9, 65), // (11,70): warning CS8603: Possible null reference return. // static T F6<T, U>([AllowNull]T t, [AllowNull]U u) where U : T => t ??= u; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t ??= u").WithLocation(11, 70), // (11,76): warning CS8600: Converting null literal or possible null value to non-nullable type. // static T F6<T, U>([AllowNull]T t, [AllowNull]U u) where U : T => t ??= u; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(11, 76)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_19() { var source = @"#nullable enable using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; class Program { static IEnumerable<T> F<T>(T t1, [AllowNull]T t2) { yield return default(T); yield return t1; yield return t2; } static IEnumerator<T> F<T, U>(U u1, [AllowNull]U u2) where U : T { yield return default(U); yield return u1; yield return u2; } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (8,22): warning CS8603: Possible null reference return. // yield return default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(8, 22), // (10,22): warning CS8603: Possible null reference return. // yield return t2; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(10, 22), // (14,22): warning CS8603: Possible null reference return. // yield return default(U); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(U)").WithLocation(14, 22), // (16,22): warning CS8603: Possible null reference return. // yield return u2; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u2").WithLocation(16, 22)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_20() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull] static T F<T>() => default; static void F1<T>() { _ = F<T>(); } static void F2<T>() where T : class { _ = F<T>(); } static void F3<T>() where T : struct { _ = F<T>(); } static void F4<T>() where T : notnull { _ = F<T>(); } }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] [WorkItem(39888, "https://github.com/dotnet/roslyn/issues/39888")] public void MaybeNullT_21() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { [return: MaybeNull]static T F1<T>(bool b, T t) => b switch { false => t, _ => default }; [return: MaybeNull]static T F2<T>(bool b, T t) => b switch { false => default, _ => t }; [return: MaybeNull]static T F3<T>(bool b, T t) where T : class => b switch { false => t, _ => default }; [return: MaybeNull]static T F4<T>(bool b, T t) where T : class => b switch { false => default, _ => t }; [return: MaybeNull]static T F5<T>(bool b, T t) where T : struct => b switch { false => t, _ => default }; [return: MaybeNull]static T F6<T>(bool b, T t) where T : struct => b switch { false => default, _ => t }; [return: MaybeNull]static T F7<T>(bool b, T t) where T : notnull => b switch { false => t, _ => default }; [return: MaybeNull]static T F8<T>(bool b, T t) where T : notnull => b switch { false => default, _ => t }; }"; var comp = CreateCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] [WorkItem(39888, "https://github.com/dotnet/roslyn/issues/39888")] public void MaybeNullT_21A() { var source = @"#nullable enable class Program { static T F1<T>(bool b, T t) => b switch { false => t, _ => default }; static T F2<T>(bool b, T t) => b switch { false => default, _ => t }; static T F3<T>(bool b, T t) where T : class => b switch { false => t, _ => default }; static T F4<T>(bool b, T t) where T : class => b switch { false => default, _ => t }; static T F5<T>(bool b, T t) where T : struct => b switch { false => t, _ => default }; static T F6<T>(bool b, T t) where T : struct => b switch { false => default, _ => t }; static T F7<T>(bool b, T t) where T : notnull => b switch { false => t, _ => default }; static T F8<T>(bool b, T t) where T : notnull => b switch { false => default, _ => t }; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,36): warning CS8603: Possible null reference return. // static T F1<T>(bool b, T t) => b switch { false => t, _ => default }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { false => t, _ => default }").WithLocation(4, 36), // (5,36): warning CS8603: Possible null reference return. // static T F2<T>(bool b, T t) => b switch { false => default, _ => t }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { false => default, _ => t }").WithLocation(5, 36), // (6,52): warning CS8603: Possible null reference return. // static T F3<T>(bool b, T t) where T : class => b switch { false => t, _ => default }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { false => t, _ => default }").WithLocation(6, 52), // (7,52): warning CS8603: Possible null reference return. // static T F4<T>(bool b, T t) where T : class => b switch { false => default, _ => t }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { false => default, _ => t }").WithLocation(7, 52), // (10,54): warning CS8603: Possible null reference return. // static T F7<T>(bool b, T t) where T : notnull => b switch { false => t, _ => default }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { false => t, _ => default }").WithLocation(10, 54), // (11,54): warning CS8603: Possible null reference return. // static T F8<T>(bool b, T t) where T : notnull => b switch { false => default, _ => t }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b switch { false => default, _ => t }").WithLocation(11, 54)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_21B() { var source = @"#nullable enable class Program { static T F1<T>(T t) => new[] { t, default }[0]; static T F2<T>(T t) => new[] { default, t }[0]; static T F3<T>(T t) where T : class => new[] { t, default }[0]; static T F4<T>(T t) where T : class => new[] { default, t }[0]; static T F5<T>(T t) where T : struct => new[] { t, default }[0]; static T F6<T>(T t) where T : struct => new[] { default, t }[0]; static T F7<T>(T t) where T : notnull => new[] { t, default }[0]; static T F8<T>(T t) where T : notnull => new[] { default, t }[0]; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,28): warning CS8603: Possible null reference return. // static T F1<T>(T t) => new[] { t, default }[0]; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { t, default }[0]").WithLocation(4, 28), // (5,28): warning CS8603: Possible null reference return. // static T F2<T>(T t) => new[] { default, t }[0]; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { default, t }[0]").WithLocation(5, 28), // (6,44): warning CS8603: Possible null reference return. // static T F3<T>(T t) where T : class => new[] { t, default }[0]; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { t, default }[0]").WithLocation(6, 44), // (7,44): warning CS8603: Possible null reference return. // static T F4<T>(T t) where T : class => new[] { default, t }[0]; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { default, t }[0]").WithLocation(7, 44), // (10,46): warning CS8603: Possible null reference return. // static T F7<T>(T t) where T : notnull => new[] { t, default }[0]; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { t, default }[0]").WithLocation(10, 46), // (11,46): warning CS8603: Possible null reference return. // static T F8<T>(T t) where T : notnull => new[] { default, t }[0]; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { default, t }[0]").WithLocation(11, 46)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_21C() { var source = @"#nullable enable class Program { static T F1<T>(bool b, T t) => b ? t : default; static T F2<T>(bool b, T t) => b ? default : t; static T F3<T>(bool b, T t) where T : class => b ? t : default; static T F4<T>(bool b, T t) where T : class => b ? default : t; static T F5<T>(bool b, T t) where T : struct => b ? t : default; static T F6<T>(bool b, T t) where T : struct => b ? default : t; static T F7<T>(bool b, T t) where T : notnull => b ? t : default; static T F8<T>(bool b, T t) where T : notnull => b ? default : t; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,36): warning CS8603: Possible null reference return. // static T F1<T>(bool b, T t) => b ? t : default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? t : default").WithLocation(4, 36), // (5,36): warning CS8603: Possible null reference return. // static T F2<T>(bool b, T t) => b ? default : t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? default : t").WithLocation(5, 36), // (6,52): warning CS8603: Possible null reference return. // static T F3<T>(bool b, T t) where T : class => b ? t : default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? t : default").WithLocation(6, 52), // (7,52): warning CS8603: Possible null reference return. // static T F4<T>(bool b, T t) where T : class => b ? default : t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? default : t").WithLocation(7, 52), // (10,54): warning CS8603: Possible null reference return. // static T F7<T>(bool b, T t) where T : notnull => b ? t : default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? t : default").WithLocation(10, 54), // (11,54): warning CS8603: Possible null reference return. // static T F8<T>(bool b, T t) where T : notnull => b ? default : t; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? default : t").WithLocation(11, 54)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_21D() { var source = @"#nullable enable using System; class Program { static Func<T> F1<T>(bool b, T t) => () => { if (b) return t; return default; }; static Func<T> F2<T>(bool b, T t) => () => { if (b) return default; return t; }; static Func<T> F3<T>(bool b, T t) where T : class => () => { if (b) return t; return default; }; static Func<T> F4<T>(bool b, T t) where T : class => () => { if (b) return default; return t; }; static Func<T> F5<T>(bool b, T t) where T : struct => () => { if (b) return t; return default; }; static Func<T> F6<T>(bool b, T t) where T : struct => () => { if (b) return default; return t; }; static Func<T> F7<T>(bool b, T t) where T : notnull => () => { if (b) return t; return default; }; static Func<T> F8<T>(bool b, T t) where T : notnull => () => { if (b) return default; return t; }; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (5,74): warning CS8603: Possible null reference return. // static Func<T> F1<T>(bool b, T t) => () => { if (b) return t; return default; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(5, 74), // (6,64): warning CS8603: Possible null reference return. // static Func<T> F2<T>(bool b, T t) => () => { if (b) return default; return t; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(6, 64), // (7,90): warning CS8603: Possible null reference return. // static Func<T> F3<T>(bool b, T t) where T : class => () => { if (b) return t; return default; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(7, 90), // (8,80): warning CS8603: Possible null reference return. // static Func<T> F4<T>(bool b, T t) where T : class => () => { if (b) return default; return t; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(8, 80), // (11,92): warning CS8603: Possible null reference return. // static Func<T> F7<T>(bool b, T t) where T : notnull => () => { if (b) return t; return default; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(11, 92), // (12,82): warning CS8603: Possible null reference return. // static Func<T> F8<T>(bool b, T t) where T : notnull => () => { if (b) return default; return t; }; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(12, 82)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_22() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; class Program { static async Task<T> F<T>(int i, T x, [AllowNull]T y) { await Task.Delay(0); switch (i) { case 0: return default(T); case 1: return x; default: return y; } } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition }); comp.VerifyDiagnostics( // (11,24): warning CS8603: Possible null reference return. // case 0: return default(T); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T)").WithLocation(11, 24), // (13,25): warning CS8603: Possible null reference return. // default: return y; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y").WithLocation(13, 25)); } [Fact] [WorkItem(37362, "https://github.com/dotnet/roslyn/issues/37362")] public void MaybeNullT_23() { var source = @"#nullable enable class Program { static T Get<T>() { throw new System.NotImplementedException(); } static T F1<T>(bool b) => b ? Get<T>() : default; static T F2<T>(bool b) => b ? default : Get<T>(); static T F3<T>() => false ? Get<T>() : default; static T F4<T>() => true ? Get<T>() : default; static T F5<T>() => false ? default : Get<T>(); static T F6<T>() => true ? default : Get<T>(); }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,31): warning CS8603: Possible null reference return. // static T F1<T>(bool b) => b ? Get<T>() : default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? Get<T>() : default").WithLocation(8, 31), // (9,31): warning CS8603: Possible null reference return. // static T F2<T>(bool b) => b ? default : Get<T>(); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "b ? default : Get<T>()").WithLocation(9, 31), // (10,25): warning CS8603: Possible null reference return. // static T F3<T>() => false ? Get<T>() : default; Diagnostic(ErrorCode.WRN_NullReferenceReturn, "false ? Get<T>() : default").WithLocation(10, 25), // (13,25): warning CS8603: Possible null reference return. // static T F6<T>() => true ? default : Get<T>(); Diagnostic(ErrorCode.WRN_NullReferenceReturn, "true ? default : Get<T>()").WithLocation(13, 25)); } [Fact] [WorkItem(39926, "https://github.com/dotnet/roslyn/issues/39926")] public void MaybeNullT_24() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class C<T> { [MaybeNull]T P1 { get; } = default; // 1 [AllowNull]T P2 { get; } = default; [MaybeNull, AllowNull]T P3 { get; } = default; [MaybeNull]T P4 { get; set; } = default; // 2 [AllowNull]T P5 { get; set; } = default; [MaybeNull, AllowNull]T P6 { get; set; } = default; C([AllowNull]T t) { P1 = t; // 3 P2 = t; P3 = t; P4 = t; // 4 P5 = t; P6 = t; } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,32): warning CS8601: Possible null reference assignment. // [MaybeNull]T P1 { get; } = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(5, 32), // (8,37): warning CS8601: Possible null reference assignment. // [MaybeNull]T P4 { get; set; } = default; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(8, 37), // (13,14): warning CS8601: Possible null reference assignment. // P1 = t; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(13, 14), // (16,14): warning CS8601: Possible null reference assignment. // P4 = t; // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(16, 14)); } [Fact] public void MaybeNullT_25() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class C<T> { [NotNull]T P1 { get; } = default; // 1 [DisallowNull]T P2 { get; } = default; // 2 [NotNull, DisallowNull]T P3 { get; } = default; // 3 [NotNull]T P4 { get; set; } = default; // 4 [DisallowNull]T P5 { get; set; } = default; // 5 [NotNull, DisallowNull]T P6 { get; set; } = default; // 6 C([AllowNull]T t) { P1 = t; // 7 P2 = t; // 8 P3 = t; // 9 P4 = t; // 10 P5 = t; // 11 P6 = t; // 12 } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,30): warning CS8601: Possible null reference assignment. // [NotNull]T P1 { get; } = default; // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(5, 30), // (6,35): warning CS8601: Possible null reference assignment. // [DisallowNull]T P2 { get; } = default; // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(6, 35), // (7,44): warning CS8601: Possible null reference assignment. // [NotNull, DisallowNull]T P3 { get; } = default; // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(7, 44), // (8,35): warning CS8601: Possible null reference assignment. // [NotNull]T P4 { get; set; } = default; // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(8, 35), // (9,40): warning CS8601: Possible null reference assignment. // [DisallowNull]T P5 { get; set; } = default; // 5 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(9, 40), // (10,49): warning CS8601: Possible null reference assignment. // [NotNull, DisallowNull]T P6 { get; set; } = default; // 6 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "default").WithLocation(10, 49), // (13,14): warning CS8601: Possible null reference assignment. // P1 = t; // 7 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(13, 14), // (14,14): warning CS8601: Possible null reference assignment. // P2 = t; // 8 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(14, 14), // (15,14): warning CS8601: Possible null reference assignment. // P3 = t; // 9 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(15, 14), // (16,14): warning CS8601: Possible null reference assignment. // P4 = t; // 10 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(16, 14), // (17,14): warning CS8601: Possible null reference assignment. // P5 = t; // 11 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(17, 14), // (18,14): warning CS8601: Possible null reference assignment. // P6 = t; // 12 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "t").WithLocation(18, 14)); } [Fact] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void MaybeNullT_26() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>( [AllowNull]T x, T y) { y = x; } static void F2<T>( [AllowNull]T x, [AllowNull]T y) { y = x; } static void F3<T>( [AllowNull]T x, [DisallowNull]T y) { y = x; } static void F4<T>( [AllowNull]T x, [MaybeNull]T y) { y = x; } static void F5<T>( [AllowNull]T x, [NotNull]T y) { y = x; } // 1 static void F6<T>( T x, T y) { y = x; } static void F7<T>( T x, [AllowNull]T y) { y = x; } static void F8<T>( T x, [DisallowNull]T y) { y = x; } static void F9<T>( T x, [MaybeNull]T y) { y = x; } static void FA<T>( T x, [NotNull]T y) { y = x; } // 2 static void FB<T>([DisallowNull]T x, T y) { y = x; } static void FC<T>([DisallowNull]T x, [AllowNull]T y) { y = x; } static void FD<T>([DisallowNull]T x, [DisallowNull]T y) { y = x; } static void FE<T>([DisallowNull]T x, [MaybeNull]T y) { y = x; } static void FF<T>([DisallowNull]T x, [NotNull]T y) { y = x; } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }); // DisallowNull on a parameter also means null is disallowed in that parameter on the inside of the method comp.VerifyDiagnostics( // (5,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F1<T>( [AllowNull]T x, T y) { y = x; } Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(5, 67), // (6,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F2<T>( [AllowNull]T x, [AllowNull]T y) { y = x; } Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(6, 67), // (7,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F3<T>( [AllowNull]T x, [DisallowNull]T y) { y = x; } Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(7, 67), // (9,67): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F5<T>( [AllowNull]T x, [NotNull]T y) { y = x; } // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(9, 67), // (9,70): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F5<T>( [AllowNull]T x, [NotNull]T y) { y = x; } // 1 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(9, 70), // (14,70): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void FA<T>( T x, [NotNull]T y) { y = x; } // 2 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(14, 70)); } [Fact] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void MaybeNullT_27() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>( [AllowNull]T x, out T y) { y = x; } // 1 static void F2<T>( [AllowNull]T x, [AllowNull]out T y) { y = x; } // 2 static void F3<T>( [AllowNull]T x, [DisallowNull]out T y) { y = x; } // 3 static void F4<T>( [AllowNull]T x, [MaybeNull]out T y) { y = x; } static void F5<T>( [AllowNull]T x, [NotNull]out T y) { y = x; } // 4 static void F6<T>( T x, out T y) { y = x; } static void F7<T>( T x, [AllowNull]out T y) { y = x; } static void F8<T>( T x, [DisallowNull]out T y) { y = x; } static void F9<T>( T x, [MaybeNull]out T y) { y = x; } static void FA<T>( T x, [NotNull]out T y) { y = x; } // 5 static void FB<T>([DisallowNull]T x, out T y) { y = x; } static void FC<T>([DisallowNull]T x, [AllowNull]out T y) { y = x; } static void FD<T>([DisallowNull]T x, [DisallowNull]out T y) { y = x; } static void FE<T>([DisallowNull]T x, [MaybeNull]out T y) { y = x; } static void FF<T>([DisallowNull]T x, [NotNull]out T y) { y = x; } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,71): warning CS8601: Possible null reference assignment. // static void F1<T>( [AllowNull]T x, out T y) { y = x; } // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(5, 71), // (6,71): warning CS8601: Possible null reference assignment. // static void F2<T>( [AllowNull]T x, [AllowNull]out T y) { y = x; } // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(6, 71), // (7,71): warning CS8601: Possible null reference assignment. // static void F3<T>( [AllowNull]T x, [DisallowNull]out T y) { y = x; } // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(7, 71), // (9,71): warning CS8601: Possible null reference assignment. // static void F5<T>( [AllowNull]T x, [NotNull]out T y) { y = x; } // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(9, 71), // (9,74): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F5<T>( [AllowNull]T x, [NotNull]out T y) { y = x; } // 4 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(9, 74), // (14,74): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void FA<T>( T x, [NotNull]out T y) { y = x; } // 5 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(14, 74)); } [Fact] [WorkItem(36039, "https://github.com/dotnet/roslyn/issues/36039")] public void NotNullOutParameterWithVariousTypes() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static void F1(string? x, [NotNull]out string? y) { y = x; } // 1 static void F2(string? x, [NotNull]out string y) { y = x; } // 2, 3 static void F3<T>(T x, [NotNull]out T y) { y = x; } // 4 static void F4<T>([DisallowNull]T x, [NotNull]out T y) { y = x; } static void F5(int? x, [NotNull]out int? y) { y = x; } // 5 }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,64): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F1(string? x, [NotNull]out string? y) { y = x; } // 1 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(5, 64), // (6,60): warning CS8601: Possible null reference assignment. // static void F2(string? x, [NotNull]out string y) { y = x; } // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(6, 60), // (6,63): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F2(string? x, [NotNull]out string y) { y = x; } // 2, 3 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(6, 63), // (7,55): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F3<T>(T x, [NotNull]out T y) { y = x; } // 4 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(7, 55), // (9,58): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F5(int? x, [NotNull]out int? y) { y = x; } // 5 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(9, 58) ); } [Fact] [WorkItem(39922, "https://github.com/dotnet/roslyn/issues/39922")] public void MaybeNullT_28() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Program { static void F1<T>( [AllowNull]T x, ref T y) { y = x; } // 1 static void F2<T>( [AllowNull]T x, [AllowNull]ref T y) { y = x; } // 2 static void F3<T>( [AllowNull]T x, [DisallowNull]ref T y) { y = x; } // 3 static void F4<T>( [AllowNull]T x, [MaybeNull]ref T y) { y = x; } static void F5<T>( [AllowNull]T x, [NotNull]ref T y) { y = x; } // 4 static void F6<T>( T x, ref T y) { y = x; } static void F7<T>( T x, [AllowNull]ref T y) { y = x; } static void F8<T>( T x, [DisallowNull]ref T y) { y = x; } static void F9<T>( T x, [MaybeNull]ref T y) { y = x; } static void FA<T>( T x, [NotNull]ref T y) { y = x; } // 5 static void FB<T>([DisallowNull]T x, ref T y) { y = x; } static void FC<T>([DisallowNull]T x, [AllowNull]ref T y) { y = x; } static void FD<T>([DisallowNull]T x, [DisallowNull]ref T y) { y = x; } static void FE<T>([DisallowNull]T x, [MaybeNull]ref T y) { y = x; } static void FF<T>([DisallowNull]T x, [NotNull]ref T y) { y = x; } }"; var comp = CreateCompilation(new[] { source, AllowNullAttributeDefinition, DisallowNullAttributeDefinition, MaybeNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics( // (5,71): warning CS8601: Possible null reference assignment. // static void F1<T>( [AllowNull]T x, ref T y) { y = x; } // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(5, 71), // (6,71): warning CS8601: Possible null reference assignment. // static void F2<T>( [AllowNull]T x, [AllowNull]ref T y) { y = x; } // 2 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(6, 71), // (7,71): warning CS8601: Possible null reference assignment. // static void F3<T>( [AllowNull]T x, [DisallowNull]ref T y) { y = x; } // 3 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(7, 71), // (9,71): warning CS8601: Possible null reference assignment. // static void F5<T>( [AllowNull]T x, [NotNull]ref T y) { y = x; } // 4 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "x").WithLocation(9, 71), // (9,74): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void F5<T>( [AllowNull]T x, [NotNull]ref T y) { y = x; } // 4 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(9, 74), // (14,74): warning CS8777: Parameter 'y' must have a non-null value when exiting. // static void FA<T>( T x, [NotNull]ref T y) { y = x; } // 5 Diagnostic(ErrorCode.WRN_ParameterDisallowsNull, "}").WithArguments("y").WithLocation(14, 74)); } [Fact] [WorkItem(38638, "https://github.com/dotnet/roslyn/issues/38638")] public void MaybeNullT_29() { var source = @"#nullable enable class Program { static T F1<T>() { (T t1, T t2) = (default, default); return t1; // 1 } static T F2<T>() { T t2; (_, t2) = (default(T), default(T)); return t2; // 2 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,16): warning CS8603: Possible null reference return. // return t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(7, 16), // (13,16): warning CS8603: Possible null reference return. // return t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(13, 16)); } [Fact] public void UnconstrainedTypeParameter_01() { var source = @"#nullable enable class Program { static void F<T, U>(U? u) where U : T { T? t = u; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,25): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F<T, U>(U? u) where U : T Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(4, 25), // (6,9): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // T? t = u; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(6, 9)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_02(bool useCompilationReference) { var sourceA = @"#nullable enable public abstract class A { public abstract void F<T>(T? t); }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,31): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public abstract void F<T>(T? t); Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 31)); comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable enable abstract class B : A { public abstract override void F<T>(T? t) where T : default; }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,40): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public abstract override void F<T>(T? t) where T : default; Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 40), // (4,56): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // public abstract override void F<T>(T? t) where T : default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(4, 56)); verifyMethod(comp); comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); verifyMethod(comp); static void verifyMethod(CSharpCompilation comp) { var method = comp.GetMember<MethodSymbol>("B.F"); Assert.Equal("void B.F<T>(T? t)", method.ToTestDisplayString(includeNonNullable: true)); var parameterType = method.Parameters[0].TypeWithAnnotations; Assert.Equal(NullableAnnotation.Annotated, parameterType.NullableAnnotation); } } [Fact] public void UnconstrainedTypeParameter_03() { var source = @"interface I { } abstract class A { internal abstract void F1<T>() where T : default; internal abstract void F2<T>() where T : default, default; internal abstract void F3<T>() where T : struct, default; static void F4<T>() where T : default, class, new() { } static void F5<T, U>() where U : T, default { } static void F6<T>() where T : default, A { } static void F6<T>() where T : default, notnull { } static void F6<T>() where T : unmanaged, default { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (4,46): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // internal abstract void F1<T>() where T : default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(4, 46), // (4,46): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F1<T>() where T : default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(4, 46), // (5,46): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(5, 46), // (5,46): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(5, 46), // (5,55): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(5, 55), // (5,55): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(5, 55), // (5,55): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(5, 55), // (6,54): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // internal abstract void F3<T>() where T : struct, default; Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(6, 54), // (6,54): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F3<T>() where T : struct, default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(6, 54), // (6,54): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal abstract void F3<T>() where T : struct, default; Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(6, 54), // (7,35): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F4<T>() where T : default, class, new() { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(7, 35), // (7,35): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F4<T>() where T : default, class, new() { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(7, 35), // (7,44): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F4<T>() where T : default, class, new() { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(7, 44), // (8,41): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F5<T, U>() where U : T, default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(8, 41), // (8,41): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F5<T, U>() where U : T, default { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(8, 41), // (8,41): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F5<T, U>() where U : T, default { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(8, 41), // (9,35): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F6<T>() where T : default, A { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(9, 35), // (9,35): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F6<T>() where T : default, A { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(9, 35), // (10,17): error CS0111: Type 'A' already defines a member called 'F6' with the same parameter types // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "F6").WithArguments("F6", "A").WithLocation(10, 17), // (10,35): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(10, 35), // (10,35): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(10, 35), // (10,44): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(10, 44), // (11,17): error CS0111: Type 'A' already defines a member called 'F6' with the same parameter types // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "F6").WithArguments("F6", "A").WithLocation(11, 17), // (11,46): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(11, 46), // (11,46): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(11, 46), // (11,46): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(11, 46)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,46): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F1<T>() where T : default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(4, 46), // (5,46): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(5, 46), // (5,55): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(5, 55), // (5,55): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal abstract void F2<T>() where T : default, default; Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(5, 55), // (6,54): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // internal abstract void F3<T>() where T : struct, default; Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(6, 54), // (6,54): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal abstract void F3<T>() where T : struct, default; Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(6, 54), // (7,35): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F4<T>() where T : default, class, new() { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(7, 35), // (7,44): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F4<T>() where T : default, class, new() { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(7, 44), // (8,41): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F5<T, U>() where U : T, default { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(8, 41), // (8,41): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F5<T, U>() where U : T, default { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(8, 41), // (9,35): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F6<T>() where T : default, A { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(9, 35), // (10,17): error CS0111: Type 'A' already defines a member called 'F6' with the same parameter types // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "F6").WithArguments("F6", "A").WithLocation(10, 17), // (10,35): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(10, 35), // (10,44): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F6<T>() where T : default, notnull { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "notnull").WithLocation(10, 44), // (11,17): error CS0111: Type 'A' already defines a member called 'F6' with the same parameter types // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "F6").WithArguments("F6", "A").WithLocation(11, 17), // (11,46): error CS8823: The 'default' constraint is valid on override and explicit interface implementation methods only. // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_DefaultConstraintOverrideOnly, "default").WithLocation(11, 46), // (11,46): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // static void F6<T>() where T : unmanaged, default { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(11, 46)); } [Fact] public void UnconstrainedTypeParameter_04() { var source = @"#nullable enable abstract class A { internal abstract void F1<T>(T? t) where T : struct; internal abstract void F2<T>(T? t) where T : class; } class B0 : A { internal override void F1<T>(T? t) { } internal override void F2<T>(T? t) { } } class B1 : A { internal override void F1<T>(T? t) where T : default { } internal override void F2<T>(T? t) where T : default { } } class B2 : A { internal override void F1<T>(T? t) where T : struct, default { } internal override void F2<T>(T? t) where T : class, default { } } class B3 : A { internal override void F1<T>(T? t) where T : default, struct { } internal override void F2<T>(T? t) where T : default, class { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,7): error CS0534: 'B0' does not implement inherited abstract member 'A.F2<T>(T?)' // class B0 : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B0").WithArguments("B0", "A.F2<T>(T?)").WithLocation(7, 7), // (10,28): error CS0115: 'B0.F2<T>(T?)': no suitable method found to override // internal override void F2<T>(T? t) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B0.F2<T>(T?)").WithLocation(10, 28), // (10,37): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // internal override void F2<T>(T? t) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(10, 37), // (12,7): error CS0534: 'B1' does not implement inherited abstract member 'A.F1<T>(T?)' // class B1 : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B1").WithArguments("B1", "A.F1<T>(T?)").WithLocation(12, 7), // (14,28): error CS0115: 'B1.F1<T>(T?)': no suitable method found to override // internal override void F1<T>(T? t) where T : default { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B1.F1<T>(T?)").WithLocation(14, 28), // (15,31): error CS8822: Method 'B1.F2<T>(T?)' specifies a 'default' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F2<T>(T?)' is constrained to a reference type or a value type. // internal override void F2<T>(T? t) where T : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "T").WithArguments("B1.F2<T>(T?)", "T", "T", "A.F2<T>(T?)").WithLocation(15, 31), // (19,58): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal override void F1<T>(T? t) where T : struct, default { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(19, 58), // (20,57): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal override void F2<T>(T? t) where T : class, default { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "default").WithLocation(20, 57), // (22,7): error CS0534: 'B3' does not implement inherited abstract member 'A.F1<T>(T?)' // class B3 : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B3").WithArguments("B3", "A.F1<T>(T?)").WithLocation(22, 7), // (24,28): error CS0115: 'B3.F1<T>(T?)': no suitable method found to override // internal override void F1<T>(T? t) where T : default, struct { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B3.F1<T>(T?)").WithLocation(24, 28), // (24,59): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal override void F1<T>(T? t) where T : default, struct { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "struct").WithLocation(24, 59), // (25,59): error CS0449: The 'class', 'struct', 'unmanaged', 'notnull', and 'default' constraints cannot be combined or duplicated, and must be specified first in the constraints list. // internal override void F2<T>(T? t) where T : default, class { } Diagnostic(ErrorCode.ERR_TypeConstraintsMustBeUniqueAndFirst, "class").WithLocation(25, 59)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_05(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I { } public abstract class A { public abstract T? F1<T>(); public abstract T? F2<T>() where T : class; public abstract T? F3<T>() where T : class?; public abstract T? F4<T>() where T : struct; public abstract T? F5<T>() where T : notnull; public abstract T? F6<T>() where T : unmanaged; public abstract T? F7<T>() where T : I; public abstract T? F8<T>() where T : I?; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB0 = @"#nullable enable class B : A { public override T? F1<T>() where T : default => default; public override T? F2<T>() where T : class => default; public override T? F3<T>() where T : class => default; public override T? F4<T>() => default; public override T? F5<T>() where T : default => default; public override T? F6<T>() => default; public override T? F7<T>() where T : default => default; public override T? F8<T>() where T : default => default; }"; comp = CreateCompilation(sourceB0, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var sourceB1 = @"#nullable enable class B : A { public override T? F1<T>() => default; public override T? F2<T>() => default; public override T? F3<T>() => default; public override T? F4<T>() => default; public override T? F5<T>() => default; public override T? F6<T>() => default; public override T? F7<T>() => default; public override T? F8<T>() => default; }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,24): error CS0508: 'B.F1<T>()': return type must be 'T' to match overridden member 'A.F1<T>()' // public override T? F1<T>() => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F1").WithArguments("B.F1<T>()", "A.F1<T>()", "T").WithLocation(4, 24), // (4,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F1<T>() => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F1").WithArguments("System.Nullable<T>", "T", "T").WithLocation(4, 24), // (5,24): error CS0508: 'B.F2<T>()': return type must be 'T' to match overridden member 'A.F2<T>()' // public override T? F2<T>() => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F2").WithArguments("B.F2<T>()", "A.F2<T>()", "T").WithLocation(5, 24), // (5,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F2<T>() => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F2").WithArguments("System.Nullable<T>", "T", "T").WithLocation(5, 24), // (6,24): error CS0508: 'B.F3<T>()': return type must be 'T' to match overridden member 'A.F3<T>()' // public override T? F3<T>() => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F3").WithArguments("B.F3<T>()", "A.F3<T>()", "T").WithLocation(6, 24), // (6,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F3<T>() => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F3").WithArguments("System.Nullable<T>", "T", "T").WithLocation(6, 24), // (8,24): error CS0508: 'B.F5<T>()': return type must be 'T' to match overridden member 'A.F5<T>()' // public override T? F5<T>() => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F5").WithArguments("B.F5<T>()", "A.F5<T>()", "T").WithLocation(8, 24), // (8,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F5<T>() => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F5").WithArguments("System.Nullable<T>", "T", "T").WithLocation(8, 24), // (10,24): error CS0508: 'B.F7<T>()': return type must be 'T' to match overridden member 'A.F7<T>()' // public override T? F7<T>() => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F7").WithArguments("B.F7<T>()", "A.F7<T>()", "T").WithLocation(10, 24), // (10,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F7<T>() => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F7").WithArguments("System.Nullable<T>", "T", "T").WithLocation(10, 24), // (11,24): error CS0508: 'B.F8<T>()': return type must be 'T' to match overridden member 'A.F8<T>()' // public override T? F8<T>() => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F8").WithArguments("B.F8<T>()", "A.F8<T>()", "T").WithLocation(11, 24), // (11,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F8<T>() => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F8").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 24)); var sourceB2 = @"#nullable enable class B : A { public override T? F1<T>() where T : default => default; public override T? F2<T>() where T : default => default; public override T? F3<T>() where T : default => default; public override T? F4<T>() where T : default => default; public override T? F5<T>() where T : default => default; public override T? F6<T>() where T : default => default; public override T? F7<T>() where T : default => default; public override T? F8<T>() where T : default => default; }"; comp = CreateCompilation(sourceB2, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,27): error CS8822: Method 'B.F2<T>()' specifies a 'default' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F2<T>()' is constrained to a reference type or a value type. // public override T? F2<T>() where T : default => default; Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "T").WithArguments("B.F2<T>()", "T", "T", "A.F2<T>()").WithLocation(5, 27), // (6,27): error CS8822: Method 'B.F3<T>()' specifies a 'default' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F3<T>()' is constrained to a reference type or a value type. // public override T? F3<T>() where T : default => default; Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "T").WithArguments("B.F3<T>()", "T", "T", "A.F3<T>()").WithLocation(6, 27), // (7,24): error CS0508: 'B.F4<T>()': return type must be 'T?' to match overridden member 'A.F4<T>()' // public override T? F4<T>() where T : default => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F4").WithArguments("B.F4<T>()", "A.F4<T>()", "T?").WithLocation(7, 24), // (7,27): error CS8822: Method 'B.F4<T>()' specifies a 'default' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F4<T>()' is constrained to a reference type or a value type. // public override T? F4<T>() where T : default => default; Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "T").WithArguments("B.F4<T>()", "T", "T", "A.F4<T>()").WithLocation(7, 27), // (9,24): error CS0508: 'B.F6<T>()': return type must be 'T?' to match overridden member 'A.F6<T>()' // public override T? F6<T>() where T : default => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F6").WithArguments("B.F6<T>()", "A.F6<T>()", "T?").WithLocation(9, 24), // (9,27): error CS8822: Method 'B.F6<T>()' specifies a 'default' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F6<T>()' is constrained to a reference type or a value type. // public override T? F6<T>() where T : default => default; Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "T").WithArguments("B.F6<T>()", "T", "T", "A.F6<T>()").WithLocation(9, 27)); var sourceB3 = @"#nullable enable class B : A { public override T? F1<T>() where T : class => default; public override T? F2<T>() where T : class => default; public override T? F3<T>() where T : class => default; public override T? F4<T>() where T : class => default; public override T? F5<T>() where T : class => default; public override T? F6<T>() where T : class => default; public override T? F7<T>() where T : class => default; public override T? F8<T>() where T : class => default; }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,27): error CS8665: Method 'B.F1<T>()' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F1<T>()' is not a reference type. // public override T? F1<T>() where T : class => default; Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("B.F1<T>()", "T", "T", "A.F1<T>()").WithLocation(4, 27), // (7,24): error CS0508: 'B.F4<T>()': return type must be 'T?' to match overridden member 'A.F4<T>()' // public override T? F4<T>() where T : class => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F4").WithArguments("B.F4<T>()", "A.F4<T>()", "T?").WithLocation(7, 24), // (7,27): error CS8665: Method 'B.F4<T>()' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F4<T>()' is not a reference type. // public override T? F4<T>() where T : class => default; Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("B.F4<T>()", "T", "T", "A.F4<T>()").WithLocation(7, 27), // (8,27): error CS8665: Method 'B.F5<T>()' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F5<T>()' is not a reference type. // public override T? F5<T>() where T : class => default; Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("B.F5<T>()", "T", "T", "A.F5<T>()").WithLocation(8, 27), // (9,24): error CS0508: 'B.F6<T>()': return type must be 'T?' to match overridden member 'A.F6<T>()' // public override T? F6<T>() where T : class => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F6").WithArguments("B.F6<T>()", "A.F6<T>()", "T?").WithLocation(9, 24), // (9,27): error CS8665: Method 'B.F6<T>()' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F6<T>()' is not a reference type. // public override T? F6<T>() where T : class => default; Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("B.F6<T>()", "T", "T", "A.F6<T>()").WithLocation(9, 27), // (10,27): error CS8665: Method 'B.F7<T>()' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F7<T>()' is not a reference type. // public override T? F7<T>() where T : class => default; Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("B.F7<T>()", "T", "T", "A.F7<T>()").WithLocation(10, 27), // (11,27): error CS8665: Method 'B.F8<T>()' specifies a 'class' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F8<T>()' is not a reference type. // public override T? F8<T>() where T : class => default; Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "T").WithArguments("B.F8<T>()", "T", "T", "A.F8<T>()").WithLocation(11, 27)); var sourceB4 = @"#nullable enable class B : A { public override T? F1<T>() where T : struct => default; public override T? F2<T>() where T : struct => default; public override T? F3<T>() where T : struct => default; public override T? F4<T>() where T : struct => default; public override T? F5<T>() where T : struct => default; public override T? F6<T>() where T : struct => default; public override T? F7<T>() where T : struct => default; public override T? F8<T>() where T : struct => default; }"; comp = CreateCompilation(sourceB4, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,24): error CS0508: 'B.F1<T>()': return type must be 'T' to match overridden member 'A.F1<T>()' // public override T? F1<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F1").WithArguments("B.F1<T>()", "A.F1<T>()", "T").WithLocation(4, 24), // (4,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F1<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F1").WithArguments("System.Nullable<T>", "T", "T").WithLocation(4, 24), // (4,27): error CS8666: Method 'B.F1<T>()' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F1<T>()' is not a non-nullable value type. // public override T? F1<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("B.F1<T>()", "T", "T", "A.F1<T>()").WithLocation(4, 27), // (5,24): error CS0508: 'B.F2<T>()': return type must be 'T' to match overridden member 'A.F2<T>()' // public override T? F2<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F2").WithArguments("B.F2<T>()", "A.F2<T>()", "T").WithLocation(5, 24), // (5,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F2<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F2").WithArguments("System.Nullable<T>", "T", "T").WithLocation(5, 24), // (5,27): error CS8666: Method 'B.F2<T>()' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F2<T>()' is not a non-nullable value type. // public override T? F2<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("B.F2<T>()", "T", "T", "A.F2<T>()").WithLocation(5, 27), // (6,24): error CS0508: 'B.F3<T>()': return type must be 'T' to match overridden member 'A.F3<T>()' // public override T? F3<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F3").WithArguments("B.F3<T>()", "A.F3<T>()", "T").WithLocation(6, 24), // (6,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F3<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F3").WithArguments("System.Nullable<T>", "T", "T").WithLocation(6, 24), // (6,27): error CS8666: Method 'B.F3<T>()' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F3<T>()' is not a non-nullable value type. // public override T? F3<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("B.F3<T>()", "T", "T", "A.F3<T>()").WithLocation(6, 27), // (8,24): error CS0508: 'B.F5<T>()': return type must be 'T' to match overridden member 'A.F5<T>()' // public override T? F5<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F5").WithArguments("B.F5<T>()", "A.F5<T>()", "T").WithLocation(8, 24), // (8,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F5<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F5").WithArguments("System.Nullable<T>", "T", "T").WithLocation(8, 24), // (8,27): error CS8666: Method 'B.F5<T>()' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F5<T>()' is not a non-nullable value type. // public override T? F5<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("B.F5<T>()", "T", "T", "A.F5<T>()").WithLocation(8, 27), // (10,24): error CS0508: 'B.F7<T>()': return type must be 'T' to match overridden member 'A.F7<T>()' // public override T? F7<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F7").WithArguments("B.F7<T>()", "A.F7<T>()", "T").WithLocation(10, 24), // (10,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F7<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F7").WithArguments("System.Nullable<T>", "T", "T").WithLocation(10, 24), // (10,27): error CS8666: Method 'B.F7<T>()' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F7<T>()' is not a non-nullable value type. // public override T? F7<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("B.F7<T>()", "T", "T", "A.F7<T>()").WithLocation(10, 27), // (11,24): error CS0508: 'B.F8<T>()': return type must be 'T' to match overridden member 'A.F8<T>()' // public override T? F8<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F8").WithArguments("B.F8<T>()", "A.F8<T>()", "T").WithLocation(11, 24), // (11,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F8<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F8").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 24), // (11,27): error CS8666: Method 'B.F8<T>()' specifies a 'struct' constraint for type parameter 'T', but corresponding type parameter 'T' of overridden or explicitly implemented method 'A.F8<T>()' is not a non-nullable value type. // public override T? F8<T>() where T : struct => default; Diagnostic(ErrorCode.ERR_OverrideValConstraintNotSatisfied, "T").WithArguments("B.F8<T>()", "T", "T", "A.F8<T>()").WithLocation(11, 27)); } // All pairs of methods "static void F<T>(T[?] t) [where T : _constraint_] { }". [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_06( [CombinatorialValues(null, "class", "class?", "struct", "notnull", "unmanaged", "I", "I?")] string constraintA, bool annotatedA, [CombinatorialValues(null, "class", "class?", "struct", "notnull", "unmanaged", "I", "I?")] string constraintB, bool annotatedB) { var source = $@"#nullable enable class C {{ {getMethod(constraintA, annotatedA)} {getMethod(constraintB, annotatedB)} }} interface I {{ }}"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); var expectedDiagnostics = (isNullableOfT(constraintA, annotatedA) == isNullableOfT(constraintB, annotatedB)) ? new[] { // (5,17): error CS0111: Type 'C' already defines a member called 'F' with the same parameter types Diagnostic(ErrorCode.ERR_MemberAlreadyExists, "F").WithArguments("F", "C").WithLocation(5, 17), } : Array.Empty<DiagnosticDescription>(); comp.VerifyDiagnostics(expectedDiagnostics); static string getMethod(string constraint, bool annotated) => $"static void F<T>(T{(annotated ? "?" : "")} t) {(constraint is null ? "" : $"where T : {constraint}")} {{ }}"; static bool isNullableOfT(string constraint, bool annotated) => (constraint == "struct" || constraint == "unmanaged") && annotated; } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_07( [CombinatorialValues(null, "notnull", "I", "I?")] string constraint, bool useCompilationReference) { var sourceA = $@"#nullable enable public interface I {{ }} public abstract class A {{ public abstract void F<T>(T? t) {(constraint is null ? "" : $"where T : {constraint}")}; public abstract void F<T>(T? t) where T : struct; }}"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable enable class B1 : A { public override void F<T>(T? t) { } } class B2 : A { public override void F<T>(T? t) where T : default { } } class B3 : A { public override void F<T>(T? t) where T : struct { } } class B4 : A { public override void F<T>(T? t) where T : default { } public override void F<T>(T? t) where T : struct { } }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (2,7): error CS0534: 'B1' does not implement inherited abstract member 'A.F<T>(T?)' // class B1 : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B1").WithArguments("B1", "A.F<T>(T?)").WithLocation(2, 7), // (6,7): error CS0534: 'B2' does not implement inherited abstract member 'A.F<T>(T?)' // class B2 : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A.F<T>(T?)").WithLocation(6, 7), // (10,7): error CS0534: 'B3' does not implement inherited abstract member 'A.F<T>(T?)' // class B3 : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B3").WithArguments("B3", "A.F<T>(T?)").WithLocation(10, 7)); Assert.True(comp.GetMember<MethodSymbol>("B1.F").TypeParameters[0].IsValueType); Assert.False(comp.GetMember<MethodSymbol>("B2.F").TypeParameters[0].IsValueType); Assert.True(comp.GetMember<MethodSymbol>("B3.F").TypeParameters[0].IsValueType); } [Fact] public void UnconstrainedTypeParameter_08() { var source = @"abstract class A<T> { public abstract void F1<U>(T t); public abstract void F1<U>(object o) where U : class; public abstract void F2<U>(T t) where U : struct; public abstract void F2<U>(object o); } abstract class B1 : A<object> { public override void F1<U>(object o) { } public override void F2<U>(object o) { } } abstract class B2 : A<object> { public override void F1<U>(object o) where U : class { } public override void F2<U>(object o) where U : struct { } } abstract class B3 : A<object> { public override void F1<U>(object o) where U : default { } public override void F2<U>(object o) where U : default { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (3,26): warning CS1957: Member 'B1.F1<U>(object)' overrides 'A<object>.F1<U>(object)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. // public abstract void F1<U>(T t); Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F1").WithArguments("A<object>.F1<U>(object)", "B1.F1<U>(object)").WithLocation(3, 26), // (3,26): warning CS1957: Member 'B2.F1<U>(object)' overrides 'A<object>.F1<U>(object)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. // public abstract void F1<U>(T t); Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F1").WithArguments("A<object>.F1<U>(object)", "B2.F1<U>(object)").WithLocation(3, 26), // (3,26): warning CS1957: Member 'B3.F1<U>(object)' overrides 'A<object>.F1<U>(object)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. // public abstract void F1<U>(T t); Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F1").WithArguments("A<object>.F1<U>(object)", "B3.F1<U>(object)").WithLocation(3, 26), // (5,26): warning CS1957: Member 'B1.F2<U>(object)' overrides 'A<object>.F2<U>(object)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. // public abstract void F2<U>(T t) where U : struct; Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F2").WithArguments("A<object>.F2<U>(object)", "B1.F2<U>(object)").WithLocation(5, 26), // (5,26): warning CS1957: Member 'B2.F2<U>(object)' overrides 'A<object>.F2<U>(object)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. // public abstract void F2<U>(T t) where U : struct; Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F2").WithArguments("A<object>.F2<U>(object)", "B2.F2<U>(object)").WithLocation(5, 26), // (5,26): warning CS1957: Member 'B3.F2<U>(object)' overrides 'A<object>.F2<U>(object)'. There are multiple override candidates at run-time. It is implementation dependent which method will be called. // public abstract void F2<U>(T t) where U : struct; Diagnostic(ErrorCode.WRN_MultipleRuntimeOverrideMatches, "F2").WithArguments("A<object>.F2<U>(object)", "B3.F2<U>(object)").WithLocation(5, 26), // (10,26): error CS0462: The inherited members 'A<T>.F1<U>(T)' and 'A<T>.F1<U>(object)' have the same signature in type 'B1', so they cannot be overridden // public override void F1<U>(object o) { } Diagnostic(ErrorCode.ERR_AmbigOverride, "F1").WithArguments("A<T>.F1<U>(T)", "A<T>.F1<U>(object)", "B1").WithLocation(10, 26), // (11,26): error CS0462: The inherited members 'A<T>.F2<U>(T)' and 'A<T>.F2<U>(object)' have the same signature in type 'B1', so they cannot be overridden // public override void F2<U>(object o) { } Diagnostic(ErrorCode.ERR_AmbigOverride, "F2").WithArguments("A<T>.F2<U>(T)", "A<T>.F2<U>(object)", "B1").WithLocation(11, 26), // (15,26): error CS0462: The inherited members 'A<T>.F1<U>(T)' and 'A<T>.F1<U>(object)' have the same signature in type 'B2', so they cannot be overridden // public override void F1<U>(object o) where U : class { } Diagnostic(ErrorCode.ERR_AmbigOverride, "F1").WithArguments("A<T>.F1<U>(T)", "A<T>.F1<U>(object)", "B2").WithLocation(15, 26), // (15,29): error CS8665: Method 'B2.F1<U>(object)' specifies a 'class' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<object>.F1<U>(object)' is not a reference type. // public override void F1<U>(object o) where U : class { } Diagnostic(ErrorCode.ERR_OverrideRefConstraintNotSatisfied, "U").WithArguments("B2.F1<U>(object)", "U", "U", "A<object>.F1<U>(object)").WithLocation(15, 29), // (16,26): error CS0462: The inherited members 'A<T>.F2<U>(T)' and 'A<T>.F2<U>(object)' have the same signature in type 'B2', so they cannot be overridden // public override void F2<U>(object o) where U : struct { } Diagnostic(ErrorCode.ERR_AmbigOverride, "F2").WithArguments("A<T>.F2<U>(T)", "A<T>.F2<U>(object)", "B2").WithLocation(16, 26), // (20,26): error CS0462: The inherited members 'A<T>.F1<U>(T)' and 'A<T>.F1<U>(object)' have the same signature in type 'B3', so they cannot be overridden // public override void F1<U>(object o) where U : default { } Diagnostic(ErrorCode.ERR_AmbigOverride, "F1").WithArguments("A<T>.F1<U>(T)", "A<T>.F1<U>(object)", "B3").WithLocation(20, 26), // (21,26): error CS0462: The inherited members 'A<T>.F2<U>(T)' and 'A<T>.F2<U>(object)' have the same signature in type 'B3', so they cannot be overridden // public override void F2<U>(object o) where U : default { } Diagnostic(ErrorCode.ERR_AmbigOverride, "F2").WithArguments("A<T>.F2<U>(T)", "A<T>.F2<U>(object)", "B3").WithLocation(21, 26), // (21,29): error CS8822: Method 'B3.F2<U>(object)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<object>.F2<U>(object)' is constrained to a reference type or a value type. // public override void F2<U>(object o) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B3.F2<U>(object)", "U", "U", "A<object>.F2<U>(object)").WithLocation(21, 29)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_09(bool useCompilationReference) { var sourceA = @"#nullable enable public abstract class A<T> { public abstract void F1<U>(U u) where U : T; public abstract void F2<U>(U? u) where U : T; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable class B1<T> : A<T> { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2<T> : A<T> { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3<T> : A<T?> { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4<T> : A<T?> { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5<T> : A<T?> { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6<T> : A<T?> { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(5, 26), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F1<U>(U)' // class B2<T> : A<T> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F2<U>(U?)' // class B2<T> : A<T> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F2<U>(U?)").WithLocation(7, 7), // (9,26): error CS0115: 'B2<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2<T>.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2<T>.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (15,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(15, 26), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F1<U>(U)' // class B4<T> : A<T?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F2<U>(U?)' // class B4<T> : A<T?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F2<U>(U?)").WithLocation(17, 7), // (19,26): error CS0115: 'B4<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4<T>.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4<T>.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (25,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(25, 26)); comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(5, 26), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F1<U>(U)' // class B2<T> : A<T> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F2<U>(U?)' // class B2<T> : A<T> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F2<U>(U?)").WithLocation(7, 7), // (9,26): error CS0115: 'B2<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2<T>.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2<T>.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (15,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(15, 26), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F1<U>(U)' // class B4<T> : A<T?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F2<U>(U?)' // class B4<T> : A<T?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F2<U>(U?)").WithLocation(17, 7), // (19,26): error CS0115: 'B4<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4<T>.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4<T>.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (25,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(25, 26)); var sourceB2 = @"#nullable enable class B1<T> : A<T> where T : class { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2<T> : A<T> where T : class { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3<T> : A<T?> where T : class { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4<T> : A<T?> where T : class { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5<T> : A<T?> where T : class { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6<T> : A<T?> where T : class { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(5, 26), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F1<U>(U)' // class B2<T> : A<T> where T : class Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F2<U>(U?)' // class B2<T> : A<T> where T : class Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F2<U>(U?)").WithLocation(7, 7), // (9,26): error CS0115: 'B2<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2<T>.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2<T>.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (15,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(15, 26), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F1<U>(U)' // class B4<T> : A<T?> where T : class Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F2<U>(U?)' // class B4<T> : A<T?> where T : class Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F2<U>(U?)").WithLocation(17, 7), // (19,26): error CS0115: 'B4<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4<T>.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4<T>.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (25,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(25, 26)); var sourceB3 = @"#nullable enable class B1<T> : A<T> where T : class? { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2<T> : A<T> where T : class? { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3<T> : A<T?> where T : class? { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4<T> : A<T?> where T : class? { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5<T> : A<T?> where T : class? { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6<T> : A<T?> where T : class? { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(5, 26), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F1<U>(U)' // class B2<T> : A<T> where T : class? Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F2<U>(U?)' // class B2<T> : A<T> where T : class? Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F2<U>(U?)").WithLocation(7, 7), // (9,26): error CS0115: 'B2<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2<T>.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2<T>.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (15,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(15, 26), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F1<U>(U)' // class B4<T> : A<T?> where T : class? Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F2<U>(U?)' // class B4<T> : A<T?> where T : class? Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F2<U>(U?)").WithLocation(17, 7), // (19,26): error CS0115: 'B4<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4<T>.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4<T>.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (25,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(25, 26)); var sourceB4 = @"#nullable enable class B1<T> : A<T> where T : struct { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2<T> : A<T> where T : struct { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3<T> : A<T?> where T : struct { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4<T> : A<T?> where T : struct { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5<T> : A<T?> where T : struct { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6<T> : A<T?> where T : struct { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB4, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F1<U>(U)' // class B2<T> : A<T> where T : struct Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F2<U>(U)' // class B2<T> : A<T> where T : struct Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F2<U>(U)").WithLocation(7, 7), // (9,26): error CS0115: 'B2<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2<T>.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2<T>.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F1<U>(U)' // class B4<T> : A<T?> where T : struct Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F2<U>(U)' // class B4<T> : A<T?> where T : struct Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F2<U>(U)").WithLocation(17, 7), // (19,26): error CS0115: 'B4<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4<T>.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4<T>.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (24,29): error CS8822: Method 'B5<T>.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<T?>.F1<U>(U)' is constrained to a reference type or a value type. // public override void F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B5<T>.F1<U>(U)", "U", "U", "A<T?>.F1<U>(U)").WithLocation(24, 29), // (25,29): error CS8822: Method 'B5<T>.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<T?>.F2<U>(U)' is constrained to a reference type or a value type. // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B5<T>.F2<U>(U)", "U", "U", "A<T?>.F2<U>(U)").WithLocation(25, 29), // (29,29): error CS8822: Method 'B6<T>.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<T?>.F1<U>(U)' is constrained to a reference type or a value type. // public override void F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B6<T>.F1<U>(U)", "U", "U", "A<T?>.F1<U>(U)").WithLocation(29, 29), // (30,29): error CS8822: Method 'B6<T>.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<T?>.F2<U>(U)' is constrained to a reference type or a value type. // public override void F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B6<T>.F2<U>(U)", "U", "U", "A<T?>.F2<U>(U)").WithLocation(30, 29)); var sourceB5 = @"#nullable enable class B1<T> : A<T> where T : notnull { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2<T> : A<T> where T : notnull { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3<T> : A<T?> where T : notnull { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4<T> : A<T?> where T : notnull { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5<T> : A<T?> where T : notnull { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6<T> : A<T?> where T : notnull { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB5, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(5, 26), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F1<U>(U)' // class B2<T> : A<T> where T : notnull Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2<T>' does not implement inherited abstract member 'A<T>.F2<U>(U?)' // class B2<T> : A<T> where T : notnull Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2<T>", "A<T>.F2<U>(U?)").WithLocation(7, 7), // (9,26): error CS0115: 'B2<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2<T>.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2<T>.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (15,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(15, 26), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F1<U>(U)' // class B4<T> : A<T?> where T : notnull Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4<T>' does not implement inherited abstract member 'A<T?>.F2<U>(U?)' // class B4<T> : A<T?> where T : notnull Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4<T>", "A<T?>.F2<U>(U?)").WithLocation(17, 7), // (19,26): error CS0115: 'B4<T>.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4<T>.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4<T>.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4<T>.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (25,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(25, 26)); var sourceB6 = @"#nullable enable class B1 : A<string> { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2 : A<string> { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3 : A<string?> { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4 : A<string?> { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5 : A<string?> { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6 : A<string?> { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB6, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(5, 26), // (7,7): error CS0534: 'B2' does not implement inherited abstract member 'A<string>.F1<U>(U)' // class B2 : A<string> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A<string>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2' does not implement inherited abstract member 'A<string>.F2<U>(U?)' // class B2 : A<string> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A<string>.F2<U>(U?)").WithLocation(7, 7), // (9,26): error CS0115: 'B2.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (15,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(15, 26), // (17,7): error CS0534: 'B4' does not implement inherited abstract member 'A<string?>.F1<U>(U)' // class B4 : A<string?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4", "A<string?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4' does not implement inherited abstract member 'A<string?>.F2<U>(U?)' // class B4 : A<string?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4", "A<string?>.F2<U>(U?)").WithLocation(17, 7), // (19,26): error CS0115: 'B4.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (24,29): error CS8822: Method 'B5.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<string?>.F1<U>(U)' is constrained to a reference type or a value type. // public override void F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B5.F1<U>(U)", "U", "U", "A<string?>.F1<U>(U)").WithLocation(24, 29), // (25,26): warning CS8765: Nullability of type of parameter 'u' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("u").WithLocation(25, 26), // (25,29): error CS8822: Method 'B5.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<string?>.F2<U>(U?)' is constrained to a reference type or a value type. // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B5.F2<U>(U)", "U", "U", "A<string?>.F2<U>(U?)").WithLocation(25, 29), // (29,29): error CS8822: Method 'B6.F1<U>(U?)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<string?>.F1<U>(U)' is constrained to a reference type or a value type. // public override void F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B6.F1<U>(U?)", "U", "U", "A<string?>.F1<U>(U)").WithLocation(29, 29), // (30,29): error CS8822: Method 'B6.F2<U>(U?)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<string?>.F2<U>(U?)' is constrained to a reference type or a value type. // public override void F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B6.F2<U>(U?)", "U", "U", "A<string?>.F2<U>(U?)").WithLocation(30, 29)); var sourceB7 = @"#nullable enable class B1 : A<int> { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B2 : A<int> { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B3 : A<int?> { public override void F1<U>(U u) { } public override void F2<U>(U u) { } } class B4 : A<int?> { public override void F1<U>(U? u) { } public override void F2<U>(U? u) { } } class B5 : A<int?> { public override void F1<U>(U u) where U : default { } public override void F2<U>(U u) where U : default { } } class B6 : A<int?> { public override void F1<U>(U? u) where U : default { } public override void F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB7, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,7): error CS0534: 'B2' does not implement inherited abstract member 'A<int>.F1<U>(U)' // class B2 : A<int> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A<int>.F1<U>(U)").WithLocation(7, 7), // (7,7): error CS0534: 'B2' does not implement inherited abstract member 'A<int>.F2<U>(U)' // class B2 : A<int> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A<int>.F2<U>(U)").WithLocation(7, 7), // (9,26): error CS0115: 'B2.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2.F1<U>(U?)").WithLocation(9, 26), // (9,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 35), // (10,26): error CS0115: 'B2.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2.F2<U>(U?)").WithLocation(10, 26), // (10,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 35), // (17,7): error CS0534: 'B4' does not implement inherited abstract member 'A<int?>.F1<U>(U)' // class B4 : A<int?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4", "A<int?>.F1<U>(U)").WithLocation(17, 7), // (17,7): error CS0534: 'B4' does not implement inherited abstract member 'A<int?>.F2<U>(U)' // class B4 : A<int?> Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B4").WithArguments("B4", "A<int?>.F2<U>(U)").WithLocation(17, 7), // (19,26): error CS0115: 'B4.F1<U>(U?)': no suitable method found to override // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B4.F1<U>(U?)").WithLocation(19, 26), // (19,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 35), // (20,26): error CS0115: 'B4.F2<U>(U?)': no suitable method found to override // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B4.F2<U>(U?)").WithLocation(20, 26), // (20,35): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 35), // (24,29): error CS8822: Method 'B5.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<int?>.F1<U>(U)' is constrained to a reference type or a value type. // public override void F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B5.F1<U>(U)", "U", "U", "A<int?>.F1<U>(U)").WithLocation(24, 29), // (25,29): error CS8822: Method 'B5.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<int?>.F2<U>(U)' is constrained to a reference type or a value type. // public override void F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B5.F2<U>(U)", "U", "U", "A<int?>.F2<U>(U)").WithLocation(25, 29), // (29,29): error CS8822: Method 'B6.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<int?>.F1<U>(U)' is constrained to a reference type or a value type. // public override void F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B6.F1<U>(U)", "U", "U", "A<int?>.F1<U>(U)").WithLocation(29, 29), // (30,29): error CS8822: Method 'B6.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'A<int?>.F2<U>(U)' is constrained to a reference type or a value type. // public override void F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("B6.F2<U>(U)", "U", "U", "A<int?>.F2<U>(U)").WithLocation(30, 29)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_10(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I<T> { void F1<U>(U u) where U : T; void F2<U>(U? u) where U : T; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable class C1<T> : I<T> { void I<T>.F1<U>(U u) { } void I<T>.F2<U>(U u) { } } class C2<T> : I<T> { void I<T>.F1<U>(U? u) { } void I<T>.F2<U>(U? u) { } } class C3<T> : I<T?> { void I<T?>.F1<U>(U u) { } void I<T?>.F2<U>(U u) { } } class C4<T> : I<T?> { void I<T?>.F1<U>(U? u) { } void I<T?>.F2<U>(U? u) { } } class C5<T> : I<T?> { void I<T?>.F1<U>(U u) where U : default { } void I<T?>.F2<U>(U u) where U : default { } } class C6<T> : I<T?> { void I<T?>.F1<U>(U? u) where U : default { } void I<T?>.F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (5,15): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<T>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<T>.F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<T>.F2<U>(U? u)").WithLocation(5, 15), // (7,15): error CS0535: 'C2<T>' does not implement interface member 'I<T>.F2<U>(U?)' // class C2<T> : I<T> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T>").WithArguments("C2<T>", "I<T>.F2<U>(U?)").WithLocation(7, 15), // (7,15): error CS0535: 'C2<T>' does not implement interface member 'I<T>.F1<U>(U)' // class C2<T> : I<T> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T>").WithArguments("C2<T>", "I<T>.F1<U>(U)").WithLocation(7, 15), // (9,15): error CS0539: 'C2<T>.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C2<T>.F1<U>(U?)").WithLocation(9, 15), // (9,24): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 24), // (10,15): error CS0539: 'C2<T>.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C2<T>.F2<U>(U?)").WithLocation(10, 15), // (10,24): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 24), // (12,17): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C3<T> : I<T?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(12, 17), // (14,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F1<U>(U u) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(14, 12), // (15,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F2<U>(U u) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(15, 12), // (15,16): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<T?>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<T?>.F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<T?>.F2<U>(U? u)").WithLocation(15, 16), // (17,15): error CS0535: 'C4<T>' does not implement interface member 'I<T?>.F2<U>(U?)' // class C4<T> : I<T?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T?>").WithArguments("C4<T>", "I<T?>.F2<U>(U?)").WithLocation(17, 15), // (17,15): error CS0535: 'C4<T>' does not implement interface member 'I<T?>.F1<U>(U)' // class C4<T> : I<T?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T?>").WithArguments("C4<T>", "I<T?>.F1<U>(U)").WithLocation(17, 15), // (17,17): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C4<T> : I<T?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(17, 17), // (19,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(19, 12), // (19,16): error CS0539: 'C4<T>.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C4<T>.F1<U>(U?)").WithLocation(19, 16), // (19,25): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 25), // (20,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(20, 12), // (20,16): error CS0539: 'C4<T>.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C4<T>.F2<U>(U?)").WithLocation(20, 16), // (20,25): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 25), // (22,17): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C5<T> : I<T?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(22, 17), // (24,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(24, 12), // (24,37): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // void I<T?>.F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(24, 37), // (25,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(25, 12), // (25,16): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<T?>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<T?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<T?>.F2<U>(U? u)").WithLocation(25, 16), // (25,37): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // void I<T?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(25, 37), // (27,17): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // class C6<T> : I<T?> Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(27, 17), // (29,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(29, 12), // (29,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(29, 22), // (29,38): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // void I<T?>.F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(29, 38), // (30,12): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(30, 12), // (30,22): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // void I<T?>.F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "U?").WithArguments("9.0").WithLocation(30, 22), // (30,38): error CS8400: Feature 'default type parameter constraints' is not available in C# 8.0. Please use language version 9.0 or greater. // void I<T?>.F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion8, "default").WithArguments("default type parameter constraints", "9.0").WithLocation(30, 38)); comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,15): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<T>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<T>.F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<T>.F2<U>(U? u)").WithLocation(5, 15), // (7,15): error CS0535: 'C2<T>' does not implement interface member 'I<T>.F2<U>(U?)' // class C2<T> : I<T> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T>").WithArguments("C2<T>", "I<T>.F2<U>(U?)").WithLocation(7, 15), // (7,15): error CS0535: 'C2<T>' does not implement interface member 'I<T>.F1<U>(U)' // class C2<T> : I<T> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T>").WithArguments("C2<T>", "I<T>.F1<U>(U)").WithLocation(7, 15), // (9,15): error CS0539: 'C2<T>.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C2<T>.F1<U>(U?)").WithLocation(9, 15), // (9,24): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 24), // (10,15): error CS0539: 'C2<T>.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C2<T>.F2<U>(U?)").WithLocation(10, 15), // (10,24): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 24), // (15,16): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<T?>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<T?>.F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<T?>.F2<U>(U? u)").WithLocation(15, 16), // (17,15): error CS0535: 'C4<T>' does not implement interface member 'I<T?>.F2<U>(U?)' // class C4<T> : I<T?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T?>").WithArguments("C4<T>", "I<T?>.F2<U>(U?)").WithLocation(17, 15), // (17,15): error CS0535: 'C4<T>' does not implement interface member 'I<T?>.F1<U>(U)' // class C4<T> : I<T?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<T?>").WithArguments("C4<T>", "I<T?>.F1<U>(U)").WithLocation(17, 15), // (19,16): error CS0539: 'C4<T>.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C4<T>.F1<U>(U?)").WithLocation(19, 16), // (19,25): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 25), // (20,16): error CS0539: 'C4<T>.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<T?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C4<T>.F2<U>(U?)").WithLocation(20, 16), // (20,25): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<T?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 25), // (25,16): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<T?>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<T?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<T?>.F2<U>(U? u)").WithLocation(25, 16)); var sourceB2 = @"#nullable enable class C1 : I<string> { void I<string>.F1<U>(U u) { } void I<string>.F2<U>(U u) { } } class C2 : I<string> { void I<string>.F1<U>(U? u) { } void I<string>.F2<U>(U? u) { } } class C3 : I<string?> { void I<string?>.F1<U>(U u) { } void I<string?>.F2<U>(U u) { } } class C4 : I<string?> { void I<string?>.F1<U>(U? u) { } void I<string?>.F2<U>(U? u) { } } class C5 : I<string?> { void I<string?>.F1<U>(U u) where U : default { } void I<string?>.F2<U>(U u) where U : default { } } class C6 : I<string?> { void I<string?>.F1<U>(U? u) where U : default { } void I<string?>.F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,20): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<string>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<string>.F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<string>.F2<U>(U? u)").WithLocation(5, 20), // (7,12): error CS0535: 'C2' does not implement interface member 'I<string>.F2<U>(U?)' // class C2 : I<string> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<string>").WithArguments("C2", "I<string>.F2<U>(U?)").WithLocation(7, 12), // (7,12): error CS0535: 'C2' does not implement interface member 'I<string>.F1<U>(U)' // class C2 : I<string> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<string>").WithArguments("C2", "I<string>.F1<U>(U)").WithLocation(7, 12), // (9,20): error CS0539: 'C2.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<string>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C2.F1<U>(U?)").WithLocation(9, 20), // (9,29): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<string>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 29), // (10,20): error CS0539: 'C2.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<string>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C2.F2<U>(U?)").WithLocation(10, 20), // (10,29): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<string>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 29), // (15,21): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<string?>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<string?>.F2<U>(U u) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<string?>.F2<U>(U? u)").WithLocation(15, 21), // (17,12): error CS0535: 'C4' does not implement interface member 'I<string?>.F2<U>(U?)' // class C4 : I<string?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<string?>").WithArguments("C4", "I<string?>.F2<U>(U?)").WithLocation(17, 12), // (17,12): error CS0535: 'C4' does not implement interface member 'I<string?>.F1<U>(U)' // class C4 : I<string?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<string?>").WithArguments("C4", "I<string?>.F1<U>(U)").WithLocation(17, 12), // (19,21): error CS0539: 'C4.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<string?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C4.F1<U>(U?)").WithLocation(19, 21), // (19,30): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<string?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 30), // (20,21): error CS0539: 'C4.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<string?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C4.F2<U>(U?)").WithLocation(20, 21), // (20,30): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<string?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 30), // (24,24): error CS8822: Method 'C5.I<string?>.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<string?>.F1<U>(U)' is constrained to a reference type or a value type. // void I<string?>.F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C5.I<string?>.F1<U>(U)", "U", "U", "I<string?>.F1<U>(U)").WithLocation(24, 24), // (25,21): warning CS8769: Nullability of reference types in type of parameter 'u' doesn't match implemented member 'void I<string?>.F2<U>(U? u)' (possibly because of nullability attributes). // void I<string?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnExplicitImplementation, "F2").WithArguments("u", "void I<string?>.F2<U>(U? u)").WithLocation(25, 21), // (25,24): error CS8822: Method 'C5.I<string?>.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<string?>.F2<U>(U?)' is constrained to a reference type or a value type. // void I<string?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C5.I<string?>.F2<U>(U)", "U", "U", "I<string?>.F2<U>(U?)").WithLocation(25, 24), // (29,24): error CS8822: Method 'C6.I<string?>.F1<U>(U?)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<string?>.F1<U>(U)' is constrained to a reference type or a value type. // void I<string?>.F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C6.I<string?>.F1<U>(U?)", "U", "U", "I<string?>.F1<U>(U)").WithLocation(29, 24), // (30,24): error CS8822: Method 'C6.I<string?>.F2<U>(U?)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<string?>.F2<U>(U?)' is constrained to a reference type or a value type. // void I<string?>.F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C6.I<string?>.F2<U>(U?)", "U", "U", "I<string?>.F2<U>(U?)").WithLocation(30, 24)); var sourceB3 = @"#nullable enable class C1 : I<int> { void I<int>.F1<U>(U u) { } void I<int>.F2<U>(U u) { } } class C2 : I<int> { void I<int>.F1<U>(U? u) { } void I<int>.F2<U>(U? u) { } } class C3 : I<int?> { void I<int?>.F1<U>(U u) { } void I<int?>.F2<U>(U u) { } } class C4 : I<int?> { void I<int?>.F1<U>(U? u) { } void I<int?>.F2<U>(U? u) { } } class C5 : I<int?> { void I<int?>.F1<U>(U u) where U : default { } void I<int?>.F2<U>(U u) where U : default { } } class C6 : I<int?> { void I<int?>.F1<U>(U? u) where U : default { } void I<int?>.F2<U>(U? u) where U : default { } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,12): error CS0535: 'C2' does not implement interface member 'I<int>.F2<U>(U)' // class C2 : I<int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<int>").WithArguments("C2", "I<int>.F2<U>(U)").WithLocation(7, 12), // (7,12): error CS0535: 'C2' does not implement interface member 'I<int>.F1<U>(U)' // class C2 : I<int> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<int>").WithArguments("C2", "I<int>.F1<U>(U)").WithLocation(7, 12), // (9,17): error CS0539: 'C2.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<int>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C2.F1<U>(U?)").WithLocation(9, 17), // (9,26): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<int>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(9, 26), // (10,17): error CS0539: 'C2.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<int>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C2.F2<U>(U?)").WithLocation(10, 17), // (10,26): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<int>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(10, 26), // (17,12): error CS0535: 'C4' does not implement interface member 'I<int?>.F2<U>(U)' // class C4 : I<int?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<int?>").WithArguments("C4", "I<int?>.F2<U>(U)").WithLocation(17, 12), // (17,12): error CS0535: 'C4' does not implement interface member 'I<int?>.F1<U>(U)' // class C4 : I<int?> Diagnostic(ErrorCode.ERR_UnimplementedInterfaceMember, "I<int?>").WithArguments("C4", "I<int?>.F1<U>(U)").WithLocation(17, 12), // (19,18): error CS0539: 'C4.F1<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<int?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F1").WithArguments("C4.F1<U>(U?)").WithLocation(19, 18), // (19,27): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<int?>.F1<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(19, 27), // (20,18): error CS0539: 'C4.F2<U>(U?)' in explicit interface declaration is not found among members of the interface that can be implemented // void I<int?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_InterfaceMemberNotFound, "F2").WithArguments("C4.F2<U>(U?)").WithLocation(20, 18), // (20,27): error CS0453: The type 'U' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // void I<int?>.F2<U>(U? u) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "u").WithArguments("System.Nullable<T>", "T", "U").WithLocation(20, 27), // (24,21): error CS8822: Method 'C5.I<int?>.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<int?>.F1<U>(U)' is constrained to a reference type or a value type. // void I<int?>.F1<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C5.I<int?>.F1<U>(U)", "U", "U", "I<int?>.F1<U>(U)").WithLocation(24, 21), // (25,21): error CS8822: Method 'C5.I<int?>.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<int?>.F2<U>(U)' is constrained to a reference type or a value type. // void I<int?>.F2<U>(U u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C5.I<int?>.F2<U>(U)", "U", "U", "I<int?>.F2<U>(U)").WithLocation(25, 21), // (29,21): error CS8822: Method 'C6.I<int?>.F1<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<int?>.F1<U>(U)' is constrained to a reference type or a value type. // void I<int?>.F1<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C6.I<int?>.F1<U>(U)", "U", "U", "I<int?>.F1<U>(U)").WithLocation(29, 21), // (30,21): error CS8822: Method 'C6.I<int?>.F2<U>(U)' specifies a 'default' constraint for type parameter 'U', but corresponding type parameter 'U' of overridden or explicitly implemented method 'I<int?>.F2<U>(U)' is constrained to a reference type or a value type. // void I<int?>.F2<U>(U? u) where U : default { } Diagnostic(ErrorCode.ERR_OverrideDefaultConstraintNotSatisfied, "U").WithArguments("C6.I<int?>.F2<U>(U)", "U", "U", "I<int?>.F2<U>(U)").WithLocation(30, 21)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_11(bool useCompilationReference) { var sourceA = @"#nullable enable public class A { public static T F1<T>(T t) => default!; public static T? F2<T>(T t) => default; public static T F3<T>(T? t) => default!; public static T? F4<T>(T? t) => default; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3 F4(x).ToString(); // 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); // 7 F4(y).ToString(); // 8 F1(default(T)).ToString(); // 9 F2(default(T?)).ToString(); // 10 F3(default(T)).ToString(); // 11 F4(default(T?)).ToString(); // 12 } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB2 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : class { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); // 3 F2(y).ToString(); // 4 F3(y).ToString(); F4(y).ToString(); // 5 F1(default(T)).ToString(); // 6 F2(default(T?)).ToString(); // 7 F3(default(T)).ToString(); F4(default(T?)).ToString(); // 8 } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB3 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : class? { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3 F4(x).ToString(); // 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); // 7 F4(y).ToString(); // 8 F1(default(T)).ToString(); // 9 F2(default(T?)).ToString(); // 10 F3(default(T)).ToString(); // 11 F4(default(T?)).ToString(); // 12 } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB4 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : struct { F1(x).ToString(); F2(x).ToString(); F3(x).ToString(); F4(x).ToString(); F1(y).Value.ToString(); // 1 F2(y).Value.ToString(); // 2 F3(y).Value.ToString(); // 3 F4(y).Value.ToString(); // 4 F1(default(T)).ToString(); F2(default(T?)).Value.ToString(); // 5 F3(default(T?)).Value.ToString(); // 6 F4(default(T?)).Value.ToString(); // 7 } }"; comp = CreateCompilation(sourceB4, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y)").WithLocation(14, 9), // (16,9): warning CS8629: Nullable value type may be null. // F2(default(T?)).Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8629: Nullable value type may be null. // F3(default(T?)).Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(default(T?))").WithLocation(17, 9), // (18,9): warning CS8629: Nullable value type may be null. // F4(default(T?)).Value.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(default(T?))").WithLocation(18, 9)); var sourceB5 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : notnull { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); F2(y).ToString(); // 3 F3(y).ToString(); F4(y).ToString(); // 4 F1(default(T)).ToString(); // 5 F2(default(T?)).ToString(); // 6 F3(default(T)).ToString(); F4(default(T?)).ToString(); // 7 } }"; comp = CreateCompilation(sourceB5, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB6 = @"#nullable enable using static A; class B { static void M(string x, string? y) { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); // 3 F2(y).ToString(); // 4 F3(y).ToString(); F4(y).ToString(); // 5 F1(default(string)).ToString(); // 6 F2(default(string?)).ToString(); // 7 F3(default(string)).ToString(); F4(default(string?)).ToString(); // 8 } }"; comp = CreateCompilation(sourceB6, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(string)).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(string))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(string?)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(string?))").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(string?)).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(string?))").WithLocation(18, 9)); var sourceB7 = @"#nullable enable using static A; class B { static void M(int x, int? y) { F1(x).ToString(); F2(x).ToString(); F3(x).ToString(); F4(x).ToString(); F1(y).Value.ToString(); // 1 F2(y).Value.ToString(); // 2 F3(y).Value.ToString(); // 3 F4(y).Value.ToString(); // 4 F1(default(int)).ToString(); F2(default(int?)).Value.ToString(); // 5 F3(default(int?)).Value.ToString(); // 6 F4(default(int?)).Value.ToString(); // 7 } }"; comp = CreateCompilation(sourceB7, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y)").WithLocation(14, 9), // (16,9): warning CS8629: Nullable value type may be null. // F2(default(int?)).Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(default(int?))").WithLocation(16, 9), // (17,9): warning CS8629: Nullable value type may be null. // F3(default(int?)).Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(default(int?))").WithLocation(17, 9), // (18,9): warning CS8629: Nullable value type may be null. // F4(default(int?)).Value.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(default(int?))").WithLocation(18, 9)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_12(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I<T> { T P { get; } } public class A { public static I<T> F1<T>(T t) => default!; public static I<T?> F2<T>(T t) => default!; public static I<T> F3<T>(T? t) => default!; public static I<T?> F4<T>(T? t) => default!; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) { F1(x).P.ToString(); // 1 F2(x).P.ToString(); // 2 F3(x).P.ToString(); // 3 F4(x).P.ToString(); // 4 F1(y).P.ToString(); // 5 F2(y).P.ToString(); // 6 F3(y).P.ToString(); // 7 F4(y).P.ToString(); // 8 F1(default(T)).P.ToString(); // 9 F2(default(T?)).P.ToString(); // 10 F3(default(T)).P.ToString(); // 11 F4(default(T?)).P.ToString(); // 12 } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x).P").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x).P").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x).P").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x).P").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).P.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y).P").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).P.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y).P").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).P.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y).P").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).P.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T)).P").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).P.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?)).P").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).P.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T)).P").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).P.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?)).P").WithLocation(18, 9)); var sourceB2 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : class { F1(x).P.ToString(); F2(x).P.ToString(); // 1 F3(x).P.ToString(); F4(x).P.ToString(); // 2 F1(y).P.ToString(); // 3 F2(y).P.ToString(); // 4 F3(y).P.ToString(); F4(y).P.ToString(); // 5 F1(default(T)).P.ToString(); // 6 F2(default(T?)).P.ToString(); // 7 F3(default(T)).P.ToString(); F4(default(T?)).P.ToString(); // 8 } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x).P").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x).P").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y).P").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).P.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y).P").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T)).P").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).P.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?)).P").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).P.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?)).P").WithLocation(18, 9)); var sourceB3 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : class? { F1(x).P.ToString(); // 1 F2(x).P.ToString(); // 2 F3(x).P.ToString(); // 3 F4(x).P.ToString(); // 4 F1(y).P.ToString(); // 5 F2(y).P.ToString(); // 6 F3(y).P.ToString(); // 7 F4(y).P.ToString(); // 8 F1(default(T)).P.ToString(); // 9 F2(default(T?)).P.ToString(); // 10 F3(default(T)).P.ToString(); // 11 F4(default(T?)).P.ToString(); // 12 } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x).P").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x).P").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x).P").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x).P").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).P.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y).P").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).P.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y).P").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).P.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y).P").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).P.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T)).P").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).P.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?)).P").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).P.ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T)).P").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).P.ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?)).P").WithLocation(18, 9)); var sourceB4 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : struct { F1(x).P.ToString(); F2(x).P.ToString(); F3(x).P.ToString(); F4(x).P.ToString(); F1(y).P.Value.ToString(); // 1 F2(y).P.Value.ToString(); // 2 F3(y).P.Value.ToString(); // 3 F4(y).P.Value.ToString(); // 4 F1(default(T)).P.ToString(); F2(default(T?)).P.Value.ToString(); // 5 F3(default(T?)).P.Value.ToString(); // 6 F4(default(T?)).P.Value.ToString(); // 7 } }"; comp = CreateCompilation(sourceB4, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).P.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).P.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y).P").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).P.Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y).P").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).P.Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y).P").WithLocation(14, 9), // (16,9): warning CS8629: Nullable value type may be null. // F2(default(T?)).P.Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(default(T?)).P").WithLocation(16, 9), // (17,9): warning CS8629: Nullable value type may be null. // F3(default(T?)).P.Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(default(T?)).P").WithLocation(17, 9), // (18,9): warning CS8629: Nullable value type may be null. // F4(default(T?)).P.Value.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(default(T?)).P").WithLocation(18, 9)); var sourceB5 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : notnull { F1(x).P.ToString(); F2(x).P.ToString(); // 1 F3(x).P.ToString(); F4(x).P.ToString(); // 2 F1(y).P.ToString(); F2(y).P.ToString(); // 3 F3(y).P.ToString(); F4(y).P.ToString(); // 4 F1(default(T)).P.ToString(); // 5 F2(default(T?)).P.ToString(); // 6 F3(default(T)).P.ToString(); F4(default(T?)).P.ToString(); // 7 } }"; comp = CreateCompilation(sourceB5, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x).P").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x).P").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).P.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y).P").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y).P").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).P.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T)).P").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?)).P").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).P.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?)).P").WithLocation(18, 9)); var sourceB6 = @"#nullable enable using static A; class B { static void M(string x, string? y) { F1(x).P.ToString(); F2(x).P.ToString(); // 1 F3(x).P.ToString(); F4(x).P.ToString(); // 2 F1(y).P.ToString(); // 3 F2(y).P.ToString(); // 4 F3(y).P.ToString(); F4(y).P.ToString(); // 5 F1(default(string)).P.ToString(); // 6 F2(default(string?)).P.ToString(); // 7 F3(default(string)).P.ToString(); F4(default(string?)).P.ToString(); // 8 } }"; comp = CreateCompilation(sourceB6, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).P.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x).P").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).P.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x).P").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).P.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).P.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y).P").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).P.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y).P").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(string)).P.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(string)).P").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(string?)).P.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(string?)).P").WithLocation(16, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(string?)).P.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(string?)).P").WithLocation(18, 9)); var sourceB7 = @"#nullable enable using static A; class B { static void M(int x, int? y) { F1(x).P.ToString(); F2(x).P.ToString(); F3(x).P.ToString(); F4(x).P.ToString(); F1(y).P.Value.ToString(); // 1 F2(y).P.Value.ToString(); // 2 F3(y).P.Value.ToString(); // 3 F4(y).P.Value.ToString(); // 4 F1(default(int)).P.ToString(); F2(default(int?)).P.Value.ToString(); // 5 F3(default(int?)).P.Value.ToString(); // 6 F4(default(int?)).P.Value.ToString(); // 7 } }"; comp = CreateCompilation(sourceB7, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).P.Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y).P").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).P.Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y).P").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).P.Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y).P").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).P.Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y).P").WithLocation(14, 9), // (16,9): warning CS8629: Nullable value type may be null. // F2(default(int?)).P.Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(default(int?)).P").WithLocation(16, 9), // (17,9): warning CS8629: Nullable value type may be null. // F3(default(int?)).P.Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(default(int?)).P").WithLocation(17, 9), // (18,9): warning CS8629: Nullable value type may be null. // F4(default(int?)).P.Value.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(default(int?)).P").WithLocation(18, 9)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_13(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I<T> { } public class A { public static T F1<T>(I<T> t) => default!; public static T? F2<T>(I<T> t) => default; public static T F3<T>(I<T?> t) => default!; public static T? F4<T>(I<T?> t) => default; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable using static A; class B { static void M<T>(I<T> x, I<T?> y) { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3, 4 F4(x).ToString(); // 5, 6 F1(y).ToString(); // 7 F2(y).ToString(); // 8 F3(y).ToString(); // 9 F4(y).ToString(); // 10 } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(9, 9), // (9,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T A.F3<T>(I<T?> t)' due to differences in the nullability of reference types. // F3(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T A.F3<T>(I<T?> t)").WithLocation(9, 12), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 5, 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (10,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T? A.F4<T>(I<T?> t)' due to differences in the nullability of reference types. // F4(x).ToString(); // 5, 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T? A.F4<T>(I<T?> t)").WithLocation(10, 12), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9)); var sourceB2 = @"#nullable enable using static A; class B { static void M<T>(I<T> x, I<T?> y) where T : class { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); // 2 F4(x).ToString(); // 3, 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); F4(y).ToString(); // 7 } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T A.F3<T>(I<T?> t)' due to differences in the nullability of reference types. // F3(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T A.F3<T>(I<T?> t)").WithLocation(9, 12), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (10,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T? A.F4<T>(I<T?> t)' due to differences in the nullability of reference types. // F4(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T? A.F4<T>(I<T?> t)").WithLocation(10, 12), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9)); var sourceB3 = @"#nullable enable using static A; class B { static void M<T>(I<T> x, I<T?> y) where T : class? { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3, 4 F4(x).ToString(); // 5, 6 F1(y).ToString(); // 7 F2(y).ToString(); // 8 F3(y).ToString(); // 9 F4(y).ToString(); // 10 } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(9, 9), // (9,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T A.F3<T>(I<T?> t)' due to differences in the nullability of reference types. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T A.F3<T>(I<T?> t)").WithLocation(9, 12), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (10,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T? A.F4<T>(I<T?> t)' due to differences in the nullability of reference types. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T? A.F4<T>(I<T?> t)").WithLocation(10, 12), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9)); var sourceB4 = @"#nullable enable using static A; class B { static void M<T>(I<T> x, I<T?> y) where T : struct { F1(x).ToString(); F2(x).ToString(); F3(x).ToString(); F4(x).ToString(); F1(y).Value.ToString(); // 1 F2(y).Value.ToString(); // 2 F3(y).Value.ToString(); // 3 F4(y).Value.ToString(); // 4 } }"; comp = CreateCompilation(sourceB4, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y)").WithLocation(14, 9)); var sourceB5 = @"#nullable enable using static A; class B { static void M<T>(I<T> x, I<T?> y) where T : notnull { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); // 2 F4(x).ToString(); // 3, 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); F4(y).ToString(); // 7 } }"; comp = CreateCompilation(sourceB5, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T A.F3<T>(I<T?> t)' due to differences in the nullability of reference types. // F3(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T A.F3<T>(I<T?> t)").WithLocation(9, 12), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (10,12): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 't' of type 'I<T?>' in 'T? A.F4<T>(I<T?> t)' due to differences in the nullability of reference types. // F4(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<T>", "I<T?>", "t", "T? A.F4<T>(I<T?> t)").WithLocation(10, 12), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9)); var sourceB6 = @"#nullable enable using static A; class B { static void M(I<string> x, I<string?> y) { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); // 2 F4(x).ToString(); // 3, 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); F4(y).ToString(); // 7 } }"; comp = CreateCompilation(sourceB6, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,12): warning CS8620: Argument of type 'I<string>' cannot be used for parameter 't' of type 'I<string?>' in 'string A.F3<string>(I<string?> t)' due to differences in the nullability of reference types. // F3(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<string>", "I<string?>", "t", "string A.F3<string>(I<string?> t)").WithLocation(9, 12), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (10,12): warning CS8620: Argument of type 'I<string>' cannot be used for parameter 't' of type 'I<string?>' in 'string? A.F4<string>(I<string?> t)' due to differences in the nullability of reference types. // F4(x).ToString(); // 3, 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x").WithArguments("I<string>", "I<string?>", "t", "string? A.F4<string>(I<string?> t)").WithLocation(10, 12), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9)); var sourceB7 = @"#nullable enable using static A; class B { static void M(I<int> x, I<int?> y) { F1(x).ToString(); F2(x).ToString(); F3(x).ToString(); F4(x).ToString(); F1(y).Value.ToString(); // 1 F2(y).Value.ToString(); // 2 F3(y).Value.ToString(); // 3 F4(y).Value.ToString(); // 4 } }"; comp = CreateCompilation(sourceB7, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y)").WithLocation(14, 9)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_14(bool useCompilationReference) { var sourceA = @"#nullable enable using System.Diagnostics.CodeAnalysis; public class A { public static T F1<T>(T t) => default!; [return: MaybeNull] public static T F2<T>(T t) => default; public static T F3<T>([AllowNull]T t) => default!; [return: MaybeNull] public static T F4<T>([AllowNull]T t) => default; }"; var comp = CreateCompilation(new[] { sourceA, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3 F4(x).ToString(); // 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); // 7 F4(y).ToString(); // 8 F1(default(T)).ToString(); // 9 F2(default(T?)).ToString(); // 10 F3(default(T)).ToString(); // 11 F4(default(T?)).ToString(); // 12 } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB2 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : class { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); // 3 F2(y).ToString(); // 4 F3(y).ToString(); // 5 F4(y).ToString(); // 6 F1(default(T)).ToString(); // 7 F2(default(T?)).ToString(); // 8 F3(default(T)).ToString(); // 9 F4(default(T?)).ToString(); // 10 } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB3 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : class? { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3 F4(x).ToString(); // 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); // 7 F4(y).ToString(); // 8 F1(default(T)).ToString(); // 9 F2(default(T?)).ToString(); // 10 F3(default(T)).ToString(); // 11 F4(default(T?)).ToString(); // 12 } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(7, 9), // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); var sourceB4 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : struct { F1(x).ToString(); F2(x).ToString(); F3(x).ToString(); F4(x).ToString(); F1(y).Value.ToString(); // 1 F2(y).Value.ToString(); // 2 F3(y).Value.ToString(); // 3 F4(y).Value.ToString(); // 4 F1(default(T)).ToString(); F2(default(T?)).Value.ToString(); // 5 F3(default(T?)).Value.ToString(); // 6 F4(default(T?)).Value.ToString(); // 7 } }"; comp = CreateCompilation(sourceB4, references: new[] { refA }); comp.VerifyDiagnostics( // (11,9): warning CS8629: Nullable value type may be null. // F1(y).Value.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8629: Nullable value type may be null. // F2(y).Value.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8629: Nullable value type may be null. // F3(y).Value.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8629: Nullable value type may be null. // F4(y).Value.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(y)").WithLocation(14, 9), // (16,9): warning CS8629: Nullable value type may be null. // F2(default(T?)).Value.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8629: Nullable value type may be null. // F3(default(T?)).Value.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F3(default(T?))").WithLocation(17, 9), // (18,9): warning CS8629: Nullable value type may be null. // F4(default(T?)).Value.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "F4(default(T?))").WithLocation(18, 9)); var sourceB5 = @"#nullable enable using static A; class B { static void M<T>(T x, T? y) where T : notnull { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); F2(y).ToString(); // 3 F3(y).ToString(); // 4 F4(y).ToString(); // 5 F1(default(T)).ToString(); // 6 F2(default(T?)).ToString(); // 7 F3(default(T)).ToString(); // 8 F4(default(T?)).ToString(); // 9 } }"; comp = CreateCompilation(sourceB5, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(8, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T?)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T?))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T?)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T?))").WithLocation(18, 9)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_15(bool useCompilationReference) { var sourceA = @"#nullable enable public class A { public static T F1<T>(T t) => default!; public static T? F2<T>(T t) => default; public static T F3<T>(T? t) => default!; public static T? F4<T>(T? t) => default; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable using System.Diagnostics.CodeAnalysis; using static A; class B { static void M<T>(T x, [AllowNull]T y) { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3 F4(x).ToString(); // 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); // 7 F4(y).ToString(); // 8 F1(default(T)).ToString(); // 9 F2(default(T)).ToString(); // 10 F3(default(T)).ToString(); // 11 F4(default(T)).ToString(); // 12 } }"; comp = CreateCompilation(new[] { sourceB1, AllowNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T)).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T))").WithLocation(19, 9)); var sourceB3 = @"#nullable enable using System.Diagnostics.CodeAnalysis; using static A; class B { static void M<T>(T x, [AllowNull]T y) where T : class? { F1(x).ToString(); // 1 F2(x).ToString(); // 2 F3(x).ToString(); // 3 F4(x).ToString(); // 4 F1(y).ToString(); // 5 F2(y).ToString(); // 6 F3(y).ToString(); // 7 F4(y).ToString(); // 8 F1(default(T)).ToString(); // 9 F2(default(T)).ToString(); // 10 F3(default(T)).ToString(); // 11 F4(default(T)).ToString(); // 12 } }"; comp = CreateCompilation(new[] { sourceB3, AllowNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // F1(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(x)").WithLocation(8, 9), // (9,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(9, 9), // (10,9): warning CS8602: Dereference of a possibly null reference. // F3(x).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(x)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // F3(y).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(y)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T)).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T))").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // F3(default(T)).ToString(); // 11 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F3(default(T))").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T)).ToString(); // 12 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T))").WithLocation(19, 9)); var sourceB5 = @"#nullable enable using System.Diagnostics.CodeAnalysis; using static A; class B { static void M<T>(T x, [AllowNull]T y) where T : notnull { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); F2(y).ToString(); // 3 F3(y).ToString(); F4(y).ToString(); // 4 F1(default(T)).ToString(); // 5 F2(default(T)).ToString(); // 6 F3(default(T)).ToString(); F4(default(T)).ToString(); // 7 } }"; comp = CreateCompilation(new[] { sourceB5, AllowNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F1(default(T)).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(T))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F2(default(T)).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(T))").WithLocation(17, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // F4(default(T)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(T))").WithLocation(19, 9)); var sourceB6 = @"#nullable enable using System.Diagnostics.CodeAnalysis; using static A; class B { static void M(string x, [AllowNull]string y) { F1(x).ToString(); F2(x).ToString(); // 1 F3(x).ToString(); F4(x).ToString(); // 2 F1(y).ToString(); // 3 F2(y).ToString(); // 4 F3(y).ToString(); F4(y).ToString(); // 5 F1(default(string)).ToString(); // 6 F2(default(string)).ToString(); // 7 F3(default(string)).ToString(); F4(default(string)).ToString(); // 8 } }"; comp = CreateCompilation(new[] { sourceB6, AllowNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics( // (9,9): warning CS8602: Dereference of a possibly null reference. // F2(x).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(x)").WithLocation(9, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // F4(x).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(x)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // F1(y).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(y)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // F2(y).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(y)").WithLocation(13, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // F4(y).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(y)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // F1(default(string)).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F1(default(string))").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // F2(default(string)).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F2(default(string))").WithLocation(17, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // F4(default(string)).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "F4(default(string))").WithLocation(19, 9)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_16(bool useCompilationReference) { var sourceA = @"#nullable enable using System.Diagnostics.CodeAnalysis; public interface I { } public abstract class A1 { [return: MaybeNull] public abstract T F1<T>(); [return: MaybeNull] public abstract T F2<T>() where T : class; [return: MaybeNull] public abstract T F3<T>() where T : class?; [return: MaybeNull] public abstract T F4<T>() where T : notnull; [return: MaybeNull] public abstract T F5<T>() where T : I; [return: MaybeNull] public abstract T F6<T>() where T : I?; } public abstract class A2 { public abstract void F1<T>([AllowNull] T t); public abstract void F2<T>([AllowNull] T t) where T : class; public abstract void F3<T>([AllowNull] T t) where T : class?; public abstract void F4<T>([AllowNull] T t) where T : notnull; public abstract void F5<T>([AllowNull] T t) where T : I; public abstract void F6<T>([AllowNull] T t) where T : I?; }"; var comp = CreateCompilation(new[] { sourceA, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable class B1 : A1 { public override T F1<T>() => default!; public override T F2<T>() => default!; public override T F3<T>() => default!; public override T F4<T>() => default!; public override T F5<T>() => default!; public override T F6<T>() => default!; } class B2 : A2 { public override void F1<T>(T t) { } // 1 public override void F2<T>(T t) { } // 2 public override void F3<T>(T t) { } // 3 public override void F4<T>(T t) { } // 4 public override void F5<T>(T t) { } // 5 public override void F6<T>(T t) { } // 6 }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>(T t) { } // 1 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t").WithLocation(13, 26), // (14,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<T>(T t) { } // 2 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t").WithLocation(14, 26), // (15,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F3<T>(T t) { } // 3 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t").WithLocation(15, 26), // (16,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F4<T>(T t) { } // 4 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t").WithLocation(16, 26), // (17,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F5<T>(T t) { } // 5 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t").WithLocation(17, 26), // (18,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F6<T>(T t) { } // 6 Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t").WithLocation(18, 26)); var sourceB2 = @"#nullable enable class B1 : A1 { public override T? F1<T>() => default; // 1 public override T? F2<T>() => default; // 2 public override T? F3<T>() => default; // 3 public override T? F4<T>() => default; // 4 public override T? F5<T>() => default; // 5 public override T? F6<T>() => default; // 6 } class B2 : A2 { public override void F1<T>(T? t) { } // 7 public override void F2<T>(T? t) { } // 8 public override void F3<T>(T? t) { } // 9 public override void F4<T>(T? t) { } // 10 public override void F5<T>(T? t) { } // 11 public override void F6<T>(T? t) { } // 12 }"; comp = CreateCompilation(sourceB2, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,24): error CS0508: 'B1.F1<T>()': return type must be 'T' to match overridden member 'A1.F1<T>()' // public override T? F1<T>() => default; // 1 Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F1").WithArguments("B1.F1<T>()", "A1.F1<T>()", "T").WithLocation(4, 24), // (4,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F1<T>() => default; // 1 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F1").WithArguments("System.Nullable<T>", "T", "T").WithLocation(4, 24), // (5,24): error CS0508: 'B1.F2<T>()': return type must be 'T' to match overridden member 'A1.F2<T>()' // public override T? F2<T>() => default; // 2 Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F2").WithArguments("B1.F2<T>()", "A1.F2<T>()", "T").WithLocation(5, 24), // (5,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F2<T>() => default; // 2 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F2").WithArguments("System.Nullable<T>", "T", "T").WithLocation(5, 24), // (6,24): error CS0508: 'B1.F3<T>()': return type must be 'T' to match overridden member 'A1.F3<T>()' // public override T? F3<T>() => default; // 3 Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F3").WithArguments("B1.F3<T>()", "A1.F3<T>()", "T").WithLocation(6, 24), // (6,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F3<T>() => default; // 3 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F3").WithArguments("System.Nullable<T>", "T", "T").WithLocation(6, 24), // (7,24): error CS0508: 'B1.F4<T>()': return type must be 'T' to match overridden member 'A1.F4<T>()' // public override T? F4<T>() => default; // 4 Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F4").WithArguments("B1.F4<T>()", "A1.F4<T>()", "T").WithLocation(7, 24), // (7,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F4<T>() => default; // 4 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F4").WithArguments("System.Nullable<T>", "T", "T").WithLocation(7, 24), // (8,24): error CS0508: 'B1.F5<T>()': return type must be 'T' to match overridden member 'A1.F5<T>()' // public override T? F5<T>() => default; // 5 Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F5").WithArguments("B1.F5<T>()", "A1.F5<T>()", "T").WithLocation(8, 24), // (8,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F5<T>() => default; // 5 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F5").WithArguments("System.Nullable<T>", "T", "T").WithLocation(8, 24), // (9,24): error CS0508: 'B1.F6<T>()': return type must be 'T' to match overridden member 'A1.F6<T>()' // public override T? F6<T>() => default; // 6 Diagnostic(ErrorCode.ERR_CantChangeReturnTypeOnOverride, "F6").WithArguments("B1.F6<T>()", "A1.F6<T>()", "T").WithLocation(9, 24), // (9,24): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override T? F6<T>() => default; // 6 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F6").WithArguments("System.Nullable<T>", "T", "T").WithLocation(9, 24), // (11,7): error CS0534: 'B2' does not implement inherited abstract member 'A2.F5<T>(T)' // class B2 : A2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A2.F5<T>(T)").WithLocation(11, 7), // (11,7): error CS0534: 'B2' does not implement inherited abstract member 'A2.F4<T>(T)' // class B2 : A2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A2.F4<T>(T)").WithLocation(11, 7), // (11,7): error CS0534: 'B2' does not implement inherited abstract member 'A2.F6<T>(T)' // class B2 : A2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A2.F6<T>(T)").WithLocation(11, 7), // (11,7): error CS0534: 'B2' does not implement inherited abstract member 'A2.F1<T>(T)' // class B2 : A2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A2.F1<T>(T)").WithLocation(11, 7), // (11,7): error CS0534: 'B2' does not implement inherited abstract member 'A2.F3<T>(T)' // class B2 : A2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A2.F3<T>(T)").WithLocation(11, 7), // (11,7): error CS0534: 'B2' does not implement inherited abstract member 'A2.F2<T>(T)' // class B2 : A2 Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B2").WithArguments("B2", "A2.F2<T>(T)").WithLocation(11, 7), // (13,26): error CS0115: 'B2.F1<T>(T?)': no suitable method found to override // public override void F1<T>(T? t) { } // 7 Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F1").WithArguments("B2.F1<T>(T?)").WithLocation(13, 26), // (13,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F1<T>(T? t) { } // 7 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(13, 35), // (14,26): error CS0115: 'B2.F2<T>(T?)': no suitable method found to override // public override void F2<T>(T? t) { } // 8 Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F2").WithArguments("B2.F2<T>(T?)").WithLocation(14, 26), // (14,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F2<T>(T? t) { } // 8 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(14, 35), // (15,26): error CS0115: 'B2.F3<T>(T?)': no suitable method found to override // public override void F3<T>(T? t) { } // 9 Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F3").WithArguments("B2.F3<T>(T?)").WithLocation(15, 26), // (15,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F3<T>(T? t) { } // 9 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(15, 35), // (16,26): error CS0115: 'B2.F4<T>(T?)': no suitable method found to override // public override void F4<T>(T? t) { } // 10 Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F4").WithArguments("B2.F4<T>(T?)").WithLocation(16, 26), // (16,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F4<T>(T? t) { } // 10 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(16, 35), // (17,26): error CS0115: 'B2.F5<T>(T?)': no suitable method found to override // public override void F5<T>(T? t) { } // 11 Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F5").WithArguments("B2.F5<T>(T?)").WithLocation(17, 26), // (17,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F5<T>(T? t) { } // 11 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(17, 35), // (18,26): error CS0115: 'B2.F6<T>(T?)': no suitable method found to override // public override void F6<T>(T? t) { } // 12 Diagnostic(ErrorCode.ERR_OverrideNotExpected, "F6").WithArguments("B2.F6<T>(T?)").WithLocation(18, 26), // (18,35): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void F6<T>(T? t) { } // 12 Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "t").WithArguments("System.Nullable<T>", "T", "T").WithLocation(18, 35)); var sourceB3 = @"#nullable enable class B1 : A1 { public override T? F1<T>() where T : default => default; public override T? F2<T>() where T : class => default; public override T? F3<T>() where T : class => default; public override T? F4<T>() where T : default => default; public override T? F5<T>() where T : default => default; public override T? F6<T>() where T : default => default; } class B2 : A2 { public override void F1<T>(T? t) where T : default { } public override void F2<T>(T? t) where T : class { } public override void F3<T>(T? t) where T : class { } public override void F4<T>(T? t) where T : default { } public override void F5<T>(T? t) where T : default { } public override void F6<T>(T? t) where T : default { } }"; comp = CreateCompilation(sourceB3, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_17(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I { } public abstract class A1 { public abstract T? F1<T>(); public abstract T? F2<T>() where T : class; public abstract T? F3<T>() where T : class?; public abstract T? F4<T>() where T : notnull; public abstract T? F5<T>() where T : I; public abstract T? F6<T>() where T : I?; } public abstract class A2 { public abstract void F1<T>(T? t); public abstract void F2<T>(T? t) where T : class; public abstract void F3<T>(T? t) where T : class?; public abstract void F4<T>(T? t) where T : notnull; public abstract void F5<T>(T? t) where T : I; public abstract void F6<T>(T? t) where T : I?; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable class B1 : A1 { public override T F1<T>() => default!; public override T F2<T>() => default!; public override T F3<T>() => default!; public override T F4<T>() => default!; public override T F5<T>() => default!; public override T F6<T>() => default!; } class B2 : A2 { public override void F1<T>(T t) { } public override void F2<T>(T t) { } public override void F3<T>(T t) { } public override void F4<T>(T t) { } public override void F5<T>(T t) { } public override void F6<T>(T t) { } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }); comp.VerifyDiagnostics( // (13,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>(T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t").WithLocation(13, 26), // (14,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<T>(T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t").WithLocation(14, 26), // (15,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F3<T>(T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t").WithLocation(15, 26), // (16,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F4<T>(T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t").WithLocation(16, 26), // (17,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F5<T>(T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t").WithLocation(17, 26), // (18,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F6<T>(T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t").WithLocation(18, 26)); var sourceB2 = @"#nullable enable using System.Diagnostics.CodeAnalysis; class B1 : A1 { [return: MaybeNull] public override T F1<T>() => default; [return: MaybeNull] public override T F2<T>() => default; [return: MaybeNull] public override T F3<T>() => default; [return: MaybeNull] public override T F4<T>() => default; [return: MaybeNull] public override T F5<T>() => default; [return: MaybeNull] public override T F6<T>() => default; } class B2 : A2 { public override void F1<T>([AllowNull] T t) { } public override void F2<T>([AllowNull] T t) { } public override void F3<T>([AllowNull] T t) { } public override void F4<T>([AllowNull] T t) { } public override void F5<T>([AllowNull] T t) { } public override void F6<T>([AllowNull] T t) { } }"; comp = CreateCompilation(new[] { sourceB2, AllowNullAttributeDefinition, MaybeNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics(); } [Fact] public void UnconstrainedTypeParameter_18() { var source = @"#nullable enable class Program { static void F<T>(T t) { } static void F1<T1>() { F<T1>(default); // 1 F<T1?>(default); } static void F2<T2>() where T2 : class { F<T2>(default); // 2 F<T2?>(default); } static void F3<T3>() where T3 : class? { F<T3>(default); // 3 F<T3?>(default); } static void F4<T4>() where T4 : struct { F<T4>(default); F<T4?>(default); } static void F5<T5>() where T5 : notnull { F<T5>(default); // 4 F<T5?>(default); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F<T1>(T1 t)'. // F<T1>(default); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void Program.F<T1>(T1 t)").WithLocation(9, 15), // (14,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F<T2>(default); // 2 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(14, 15), // (19,15): warning CS8625: Cannot convert null literal to non-nullable reference type. // F<T3>(default); // 3 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(19, 15), // (29,15): warning CS8604: Possible null reference argument for parameter 't' in 'void Program.F<T5>(T5 t)'. // F<T5>(default); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void Program.F<T5>(T5 t)").WithLocation(29, 15)); } [Fact] public void UnconstrainedTypeParameter_19() { var source1 = @"#nullable enable class Program { static T1 F1<T1>() => default(T1); // 1 static T2 F2<T2>() where T2 : class => default(T2); // 2 static T3 F3<T3>() where T3 : class? => default(T3); // 3 static T4 F4<T4>() where T4 : notnull => default(T4); // 4 }"; var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,27): warning CS8603: Possible null reference return. // static T1 F1<T1>() => default(T1); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T1)").WithLocation(4, 27), // (5,44): warning CS8603: Possible null reference return. // static T2 F2<T2>() where T2 : class => default(T2); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T2)").WithLocation(5, 44), // (6,45): warning CS8603: Possible null reference return. // static T3 F3<T3>() where T3 : class? => default(T3); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T3)").WithLocation(6, 45), // (7,46): warning CS8603: Possible null reference return. // static T4 F4<T4>() where T4 : notnull => default(T4); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T4)").WithLocation(7, 46)); var source2 = @"#nullable enable class Program { static T1? F1<T1>() => default(T1); static T2? F2<T2>() where T2 : class => default(T2); static T3? F3<T3>() where T3 : class? => default(T3); static T4? F4<T4>() where T4 : notnull => default(T4); }"; comp = CreateCompilation(source2, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var source3 = @"#nullable enable class Program { static T1 F1<T1>() => default(T1?); // 1 static T2 F2<T2>() where T2 : class => default(T2?); // 2 static T3 F3<T3>() where T3 : class? => default(T3?); // 3 static T4 F4<T4>() where T4 : notnull => default(T4?); // 4 }"; comp = CreateCompilation(source3, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,27): warning CS8603: Possible null reference return. // static T1 F1<T1>() => default(T1?); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T1?)").WithLocation(4, 27), // (5,44): warning CS8603: Possible null reference return. // static T2 F2<T2>() where T2 : class => default(T2?); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T2?)").WithLocation(5, 44), // (6,45): warning CS8603: Possible null reference return. // static T3 F3<T3>() where T3 : class? => default(T3?); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T3?)").WithLocation(6, 45), // (7,46): warning CS8603: Possible null reference return. // static T4 F4<T4>() where T4 : notnull => default(T4?); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default(T4?)").WithLocation(7, 46)); var source4 = @"#nullable enable class Program { static T1? F1<T1>() => default(T1?); static T2? F2<T2>() where T2 : class => default(T2?); static T3? F3<T3>() where T3 : class? => default(T3?); static T4? F4<T4>() where T4 : notnull => default(T4?); }"; comp = CreateCompilation(source4, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void UnconstrainedTypeParameter_20() { var source = @"#nullable enable delegate T D1<T>(); delegate T? D2<T>(); class Program { static T F1<T>(D1<T> d) => default!; static T F2<T>(D2<T> d) => default!; static void M1<T>() { var x1 = F1<T>(() => default); // 1 var x2 = F2<T>(() => default); var x3 = F1<T?>(() => default); var x4 = F2<T?>(() => default); x1.ToString(); // 2 x2.ToString(); // 3 x3.ToString(); // 4 x4.ToString(); // 5 } static void M2<T>() { var x1 = F1(() => default(T)); // 6 var x2 = F2(() => default(T)); var y1 = F1(() => default(T?)); var y2 = F2(() => default(T?)); x1.ToString(); // 7 x2.ToString(); // 8 y1.ToString(); // 9 y2.ToString(); // 10 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,30): warning CS8603: Possible null reference return. // var x1 = F1<T>(() => default); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "default").WithLocation(10, 30), // (14,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // x3.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x3").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // x4.ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x4").WithLocation(17, 9), // (25,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(25, 9), // (26,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(26, 9), // (27,9): warning CS8602: Dereference of a possibly null reference. // y1.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y1").WithLocation(27, 9), // (28,9): warning CS8602: Dereference of a possibly null reference. // y2.ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y2").WithLocation(28, 9)); } [WorkItem(46044, "https://github.com/dotnet/roslyn/issues/46044")] [Fact] public void UnconstrainedTypeParameter_21() { var source = @"#nullable enable class C<T> { static void F1(T t) { } static void F2(T? t) { } static void M(bool b, T x, T? y) { if (b) F2(x); if (b) F2((T)x); if (b) F2((T?)x); if (b) F1(y); // 1 if (b) F1((T)y); // 2, 3 if (b) F1((T?)y); // 4 if (b) F1(default); // 5 if (b) F1(default(T)); // 6 if (b) F2(default); if (b) F2(default(T)); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,19): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F1(T t)'. // if (b) F1(y); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("t", "void C<T>.F1(T t)").WithLocation(11, 19), // (12,19): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (b) F1((T)y); // 2, 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)y").WithLocation(12, 19), // (12,19): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F1(T t)'. // if (b) F1((T)y); // 2, 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(T)y").WithArguments("t", "void C<T>.F1(T t)").WithLocation(12, 19), // (13,19): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F1(T t)'. // if (b) F1((T?)y); // 4 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "(T?)y").WithArguments("t", "void C<T>.F1(T t)").WithLocation(13, 19), // (14,19): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F1(T t)'. // if (b) F1(default); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "void C<T>.F1(T t)").WithLocation(14, 19), // (15,19): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F1(T t)'. // if (b) F1(default(T)); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default(T)").WithArguments("t", "void C<T>.F1(T t)").WithLocation(15, 19)); } [Fact] public void UnconstrainedTypeParameter_22() { var source = @"#nullable enable using System.Collections.Generic; class C<T> { static void F1(IEnumerable<T> e) { } static void F2(IEnumerable<T?> e) { } static void M1(IEnumerable<T> x1, IEnumerable<T?> y1) { F1(x1); F1(y1); // 1 F2(x1); F2(y1); } static void M2(List<T> x2, List<T?> y2) { F1(x2); F1(y2); // 2 F2(x2); F2(y2); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,12): warning CS8620: Argument of type 'IEnumerable<T?>' cannot be used for parameter 'e' of type 'IEnumerable<T>' in 'void C<T>.F1(IEnumerable<T> e)' due to differences in the nullability of reference types. // F1(y1); // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y1").WithArguments("System.Collections.Generic.IEnumerable<T?>", "System.Collections.Generic.IEnumerable<T>", "e", "void C<T>.F1(IEnumerable<T> e)").WithLocation(10, 12), // (17,12): warning CS8620: Argument of type 'List<T?>' cannot be used for parameter 'e' of type 'IEnumerable<T>' in 'void C<T>.F1(IEnumerable<T> e)' due to differences in the nullability of reference types. // F1(y2); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y2").WithArguments("System.Collections.Generic.List<T?>", "System.Collections.Generic.IEnumerable<T>", "e", "void C<T>.F1(IEnumerable<T> e)").WithLocation(17, 12)); } [Fact] public void UnconstrainedTypeParameter_23() { var source = @"#nullable enable using System.Collections.Generic; class C<T> { static void F(T t) { } static void M1(IEnumerable<T?> e) { foreach (var o in e) F(o); // 1 } static void M2(T?[] a) { foreach (var o in a) F(o); // 2 } static void M3(List<T?> l) { foreach (var o in l) F(o); // 3 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (11,15): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F(T t)'. // F(o); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("t", "void C<T>.F(T t)").WithLocation(11, 15), // (16,15): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F(T t)'. // F(o); // 2 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("t", "void C<T>.F(T t)").WithLocation(16, 15), // (21,15): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F(T t)'. // F(o); // 3 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "o").WithArguments("t", "void C<T>.F(T t)").WithLocation(21, 15)); } [Fact] public void UnconstrainedTypeParameter_24() { var source = @"#nullable enable using System.Collections.Generic; static class E { internal static IEnumerable<T> GetEnumerable<T>(this T t) => new[] { t }; } class C<T> { static void F(T t) { } static void M1(T x) { foreach (var ix in x.GetEnumerable()) F(ix); // 1 } static void M2(T? y) { foreach (var iy in y.GetEnumerable()) F(iy); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (20,15): warning CS8604: Possible null reference argument for parameter 't' in 'void C<T>.F(T t)'. // F(iy); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "iy").WithArguments("t", "void C<T>.F(T t)").WithLocation(20, 15)); } [Fact] public void UnconstrainedTypeParameter_25() { var source = @"#nullable enable interface I<out T> { } class Program { static void F1<T>(bool b, T x1, T? y1) { T? t1 = b ? x1 : x1; T? t2 = b ? x1 : y1; T? t3 = b ? y1 : x1; T? t4 = b ? y1 : y1; } static void F2<T>(bool b, T x2, T? y2) { ref T t1 = ref b ? ref x2 : ref x2; ref T? t2 = ref b ? ref x2 : ref y2; // 1 ref T? t3 = ref b ? ref y2 : ref x2; // 2 ref T? t4 = ref b ? ref y2 : ref y2; } static void F3<T>(bool b, I<T> x3, I<T?> y3) { I<T?> t1 = b ? x3 : x3; I<T?> t2 = b ? x3 : y3; I<T?> t3 = b ? y3 : x3; I<T?> t4 = b ? y3 : y3; } static void F4<T>(bool b, I<T> x4, I<T?> y4) { ref I<T> t1 = ref b ? ref x4 : ref x4; ref I<T?> t2 = ref b ? ref x4 : ref y4; // 3 ref I<T?> t3 = ref b ? ref y4 : ref x4; // 4 ref I<T?> t4 = ref b ? ref y4 : ref y4; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (15,25): warning CS8619: Nullability of reference types in value of type 'T' doesn't match target type 'T?'. // ref T? t2 = ref b ? ref x2 : ref y2; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x2 : ref y2").WithArguments("T", "T?").WithLocation(15, 25), // (15,25): warning CS8619: Nullability of reference types in value of type 'T' doesn't match target type 'T?'. // ref T? t2 = ref b ? ref x2 : ref y2; // 1 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x2 : ref y2").WithArguments("T", "T?").WithLocation(15, 25), // (16,25): warning CS8619: Nullability of reference types in value of type 'T?' doesn't match target type 'T'. // ref T? t3 = ref b ? ref y2 : ref x2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y2 : ref x2").WithArguments("T?", "T").WithLocation(16, 25), // (16,25): warning CS8619: Nullability of reference types in value of type 'T' doesn't match target type 'T?'. // ref T? t3 = ref b ? ref y2 : ref x2; // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y2 : ref x2").WithArguments("T", "T?").WithLocation(16, 25), // (29,28): warning CS8619: Nullability of reference types in value of type 'I<T>' doesn't match target type 'I<T?>'. // ref I<T?> t2 = ref b ? ref x4 : ref y4; // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref x4 : ref y4").WithArguments("I<T>", "I<T?>").WithLocation(29, 28), // (30,28): warning CS8619: Nullability of reference types in value of type 'I<T?>' doesn't match target type 'I<T>'. // ref I<T?> t3 = ref b ? ref y4 : ref x4; // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "b ? ref y4 : ref x4").WithArguments("I<T?>", "I<T>").WithLocation(30, 28)); } [Fact] public void UnconstrainedTypeParameter_26() { var source = @"#nullable enable interface I<out T> { } class Program { static void FA<T>(ref T x, ref T? y) { } static void FB<T>(ref I<T> x, ref I<T?> y) { } static void F1<T>(T x1, T? y1) { FA(ref x1, ref y1); } static void F2<T>(T x2, T? y2) { FA(ref y2, ref x2); // 1 } static void F3<T>(T x3, T? y3) { FA<T>(ref x3, ref y3); } static void F4<T>(T x4, T? y4) { FA<T?>(ref x4, ref y4); } static void F5<T>(I<T> x5, I<T?> y5) { FB(ref x5, ref y5); } static void F6<T>(I<T> x6, I<T?> y6) { FB(ref y6, ref x6); // 2, 3 } static void F7<T>(I<T> x7, I<T?> y7) { FB<T>(ref x7, ref y7); } static void F8<T>(I<T> x8, I<T?> y8) { FB<T?>(ref x8, ref y8); // 4 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (13,16): warning CS8601: Possible null reference assignment. // FA(ref y2, ref x2); // 1 Diagnostic(ErrorCode.WRN_NullReferenceAssignment, "y2").WithLocation(13, 16), // (13,24): warning CS8600: Converting null literal or possible null value to non-nullable type. // FA(ref y2, ref x2); // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x2").WithLocation(13, 24), // (21,20): warning CS8600: Converting null literal or possible null value to non-nullable type. // FA<T?>(ref x4, ref y4); Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x4").WithLocation(21, 20), // (29,16): warning CS8620: Argument of type 'I<T?>' cannot be used for parameter 'x' of type 'I<T>' in 'void Program.FB<T>(ref I<T> x, ref I<T?> y)' due to differences in the nullability of reference types. // FB(ref y6, ref x6); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "y6").WithArguments("I<T?>", "I<T>", "x", "void Program.FB<T>(ref I<T> x, ref I<T?> y)").WithLocation(29, 16), // (29,24): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 'y' of type 'I<T?>' in 'void Program.FB<T>(ref I<T> x, ref I<T?> y)' due to differences in the nullability of reference types. // FB(ref y6, ref x6); // 2, 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x6").WithArguments("I<T>", "I<T?>", "y", "void Program.FB<T>(ref I<T> x, ref I<T?> y)").WithLocation(29, 24), // (37,20): warning CS8620: Argument of type 'I<T>' cannot be used for parameter 'x' of type 'I<T?>' in 'void Program.FB<T?>(ref I<T?> x, ref I<T?> y)' due to differences in the nullability of reference types. // FB<T?>(ref x8, ref y8); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInArgument, "x8").WithArguments("I<T>", "I<T?>", "x", "void Program.FB<T?>(ref I<T?> x, ref I<T?> y)").WithLocation(37, 20)); } [Fact] [WorkItem(46150, "https://github.com/dotnet/roslyn/issues/46150")] public void UnconstrainedTypeParameter_27() { var source1 = @"#nullable enable class A<T> { static T F1<U>(U u) where U : T => u; static T F2<U>(U u) where U : T? => u; // 1 static T? F3<U>(U u) where U : T => u; static T? F4<U>(U u) where U : T? => u; static T F5<U>(U? u) where U : T => u; // 2 static T F6<U>(U? u) where U : T? => u; // 3 static T? F7<U>(U? u) where U : T => u; static T? F8<U>(U? u) where U : T? => u; }"; var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,41): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 41), // (8,41): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 41), // (9,42): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 42)); var source2 = @"#nullable enable class A<T> where T : class { static T F1<U>(U u) where U : T => u; static T F2<U>(U u) where U : T? => u; // 1 static T? F3<U>(U u) where U : T => u; static T? F4<U>(U u) where U : T? => u; static T F5<U>(U? u) where U : T => u; // 2 static T F6<U>(U? u) where U : T? => u; // 3 static T? F7<U>(U? u) where U : T => u; static T? F8<U>(U? u) where U : T? => u; }"; comp = CreateCompilation(source2, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,41): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 41), // (8,41): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 41), // (9,42): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 42)); var source3 = @"#nullable enable class A<T> where T : class? { static T F1<U>(U u) where U : T => u; static T F2<U>(U u) where U : T? => u; // 1 static T? F3<U>(U u) where U : T => u; static T? F4<U>(U u) where U : T? => u; static T F5<U>(U? u) where U : T => u; // 2 static T F6<U>(U? u) where U : T? => u; // 3 static T? F7<U>(U? u) where U : T => u; static T? F8<U>(U? u) where U : T? => u; }"; comp = CreateCompilation(source3, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,41): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 41), // (8,41): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 41), // (9,42): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 42)); var source4 = @"#nullable enable class A<T> where T : notnull { static T F1<U>(U u) where U : T => u; static T F2<U>(U u) where U : T? => u; // 1 static T? F3<U>(U u) where U : T => u; static T? F4<U>(U u) where U : T? => u; static T F5<U>(U? u) where U : T => u; // 2 static T F6<U>(U? u) where U : T? => u; // 3 static T? F7<U>(U? u) where U : T => u; static T? F8<U>(U? u) where U : T? => u; }"; comp = CreateCompilation(source4, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,41): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 41), // (8,41): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 41), // (9,42): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 42)); var source5 = @"#nullable enable interface I { } class A<T> where T : I { static T F1<U>(U u) where U : T => u; static T F2<U>(U u) where U : T? => u; // 1 static T? F3<U>(U u) where U : T => u; static T? F4<U>(U u) where U : T? => u; static T F5<U>(U? u) where U : T => u; // 2 static T F6<U>(U? u) where U : T? => u; // 3 static T? F7<U>(U? u) where U : T => u; static T? F8<U>(U? u) where U : T? => u; }"; comp = CreateCompilation(source5, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,41): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(6, 41), // (9,41): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 41), // (10,42): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 42)); var source6 = @"#nullable enable interface I { } class A<T> where T : I? { static T F1<U>(U u) where U : T => u; static T F2<U>(U u) where U : T? => u; // 1 static T? F3<U>(U u) where U : T => u; static T? F4<U>(U u) where U : T? => u; static T F5<U>(U? u) where U : T => u; // 2 static T F6<U>(U? u) where U : T? => u; // 3 static T? F7<U>(U? u) where U : T => u; static T? F8<U>(U? u) where U : T? => u; }"; comp = CreateCompilation(source6, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,41): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(6, 41), // (9,41): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 41), // (10,42): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 42)); } [Fact] [WorkItem(46150, "https://github.com/dotnet/roslyn/issues/46150")] public void UnconstrainedTypeParameter_28() { var source = @"#nullable disable class A<T, U> where U : T #nullable enable { static T F1(U u) => u; static T? F2(U u) => u; static T F3(U? u) => u; // 1 static T? F4(U? u) => u; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,26): warning CS8603: Possible null reference return. // static T F3(U? u) => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(7, 26)); } [Fact] [WorkItem(46150, "https://github.com/dotnet/roslyn/issues/46150")] public void UnconstrainedTypeParameter_29() { var source1 = @"#nullable enable class A { static object F1<T>(T t) => t; // 1 static object? F2<T>(T t) => t; static object F3<T>(T? t) => t; // 2 static object? F4<T>(T? t) => t; }"; var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,33): warning CS8603: Possible null reference return. // static object F1<T>(T t) => t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(4, 33), // (6,34): warning CS8603: Possible null reference return. // static object F3<T>(T? t) => t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 34)); var source2 = @"#nullable enable class A { static object F1<T>(T t) where T : class => t; static object? F2<T>(T t) where T : class => t; static object F3<T>(T? t) where T : class => t; // 1 static object? F4<T>(T? t) where T : class => t; }"; comp = CreateCompilation(source2); comp.VerifyDiagnostics( // (6,50): warning CS8603: Possible null reference return. // static object F3<T>(T? t) where T : class => t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 50)); var source3 = @"#nullable enable class A { static object F1<T>(T t) where T : class? => t; // 1 static object? F2<T>(T t) where T : class? => t; static object F3<T>(T? t) where T : class? => t; // 2 static object? F4<T>(T? t) where T : class? => t; }"; comp = CreateCompilation(source3, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,50): warning CS8603: Possible null reference return. // static object F1<T>(T t) where T : class? => t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(4, 50), // (6,51): warning CS8603: Possible null reference return. // static object F3<T>(T? t) where T : class? => t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 51)); var source4 = @"#nullable enable class A { static object F1<T>(T t) where T : struct => t; static object? F2<T>(T t) where T : struct => t; static object F3<T>(T? t) where T : struct => t; // 1 static object? F4<T>(T? t) where T : struct => t; }"; comp = CreateCompilation(source4); comp.VerifyDiagnostics( // (6,51): warning CS8603: Possible null reference return. // static object F3<T>(T? t) where T : struct => t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 51)); var source5 = @"#nullable enable class A { static object F1<T>(T t) where T : notnull => t; static object? F2<T>(T t) where T : notnull => t; static object F3<T>(T? t) where T : notnull => t; // 1 static object? F4<T>(T? t) where T : notnull => t; }"; comp = CreateCompilation(source5, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,52): warning CS8603: Possible null reference return. // static object F3<T>(T? t) where T : notnull => t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 52)); } [Fact] public void UnconstrainedTypeParameter_30() { var source1 = @"#nullable enable interface I { } class Program { static I F1<T>(T t) where T : I => t; static I F2<T>(T t) where T : I? => t; // 1 static I? F3<T>(T t) where T : I => t; static I? F4<T>(T t) where T : I? => t; static I F5<T>(T? t) where T : I => t; // 2 static I F6<T>(T? t) where T : I? => t; // 3 static I? F7<T>(T? t) where T : I => t; static I? F8<T>(T? t) where T : I? => t; }"; var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,41): warning CS8603: Possible null reference return. // static I F2<T>(T t) where T : I? => t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(6, 41), // (9,41): warning CS8603: Possible null reference return. // static I F5<T>(T? t) where T : I => t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(9, 41), // (10,42): warning CS8603: Possible null reference return. // static I F6<T>(T? t) where T : I? => t; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(10, 42)); } [Fact] [WorkItem(46150, "https://github.com/dotnet/roslyn/issues/46150")] public void UnconstrainedTypeParameter_31() { var source1 = @"#nullable enable class A<T> { static T F1<U>(U u) where U : class, T => u; static T F2<U>(U u) where U : class, T? => u; static T? F3<U>(U u) where U : class, T => u; static T? F4<U>(U u) where U : class, T? => u; static T F5<U>(U? u) where U : class, T => u; // 1 static T F6<U>(U? u) where U : class, T? => u; // 2 static T? F7<U>(U? u) where U : class, T => u; static T? F8<U>(U? u) where U : class, T? => u; }"; var comp = CreateCompilation(source1, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,48): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : class, T => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 48), // (9,49): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : class, T? => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 49)); var source2 = @"#nullable enable class A<T> { static T F1<U>(U u) where U : class?, T => u; static T F2<U>(U u) where U : class?, T? => u; // 1 static T? F3<U>(U u) where U : class?, T => u; static T? F4<U>(U u) where U : class?, T? => u; static T F5<U>(U? u) where U : class?, T => u; // 2 static T F6<U>(U? u) where U : class?, T? => u; // 3 static T? F7<U>(U? u) where U : class?, T => u; static T? F8<U>(U? u) where U : class?, T? => u; }"; comp = CreateCompilation(source2, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,49): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : class?, T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(5, 49), // (8,49): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : class?, T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 49), // (9,50): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : class?, T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 50)); var source3 = @"#nullable enable class A<T> { static T F1<U>(U u) where U : notnull, T => u; static T F2<U>(U u) where U : notnull, T? => u; static T? F3<U>(U u) where U : notnull, T => u; static T? F4<U>(U u) where U : notnull, T? => u; static T F5<U>(U? u) where U : notnull, T => u; // 1 static T F6<U>(U? u) where U : notnull, T? => u; // 2 static T? F7<U>(U? u) where U : notnull, T => u; static T? F8<U>(U? u) where U : notnull, T? => u; }"; comp = CreateCompilation(source3, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,50): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : notnull, T => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(8, 50), // (9,51): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : notnull, T? => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 51)); var source4 = @"#nullable enable interface I { } class A<T> { static T F1<U>(U u) where U : I, T => u; static T F2<U>(U u) where U : I, T? => u; static T? F3<U>(U u) where U : I, T => u; static T? F4<U>(U u) where U : I, T? => u; static T F5<U>(U? u) where U : I, T => u; // 1 static T F6<U>(U? u) where U : I, T? => u; // 2 static T? F7<U>(U? u) where U : I, T => u; static T? F8<U>(U? u) where U : I, T? => u; }"; comp = CreateCompilation(source4, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (9,44): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : I, T => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 44), // (10,45): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : I, T? => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 45)); var source5 = @"#nullable enable interface I { } class A<T> { static T F1<U>(U u) where U : I?, T => u; static T F2<U>(U u) where U : I?, T? => u; // 1 static T? F3<U>(U u) where U : I?, T => u; static T? F4<U>(U u) where U : I?, T? => u; static T F5<U>(U? u) where U : I?, T => u; // 2 static T F6<U>(U? u) where U : I?, T? => u; // 3 static T? F7<U>(U? u) where U : I?, T => u; static T? F8<U>(U? u) where U : I?, T? => u; }"; comp = CreateCompilation(source5, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,45): warning CS8603: Possible null reference return. // static T F2<U>(U u) where U : I?, T? => u; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(6, 45), // (9,45): warning CS8603: Possible null reference return. // static T F5<U>(U? u) where U : I?, T => u; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(9, 45), // (10,46): warning CS8603: Possible null reference return. // static T F6<U>(U? u) where U : I?, T? => u; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(10, 46)); } [Fact] [WorkItem(46150, "https://github.com/dotnet/roslyn/issues/46150")] public void UnconstrainedTypeParameter_32() { var source = @"#nullable enable class A<T> { static T F1<U, V>(V v) where U : T where V : U => v; static T F2<U, V>(V v) where U : T? where V : U => v; // 1 static T F3<U, V>(V v) where U : T where V : U? => v; // 2 static T F4<U, V>(V v) where U : T? where V : U? => v; // 3 static T? F5<U, V>(V v) where U : T where V : U => v; static T? F6<U, V>(V v) where U : T? where V : U => v; static T? F7<U, V>(V v) where U : T where V : U? => v; static T? F8<U, V>(V v) where U : T? where V : U? => v; static T F9<U, V>(V? v) where U : T where V : U => v; // 4 static T F10<U, V>(V? v) where U : T? where V : U => v; // 5 static T F11<U, V>(V? v) where U : T where V : U? => v; // 6 static T F12<U, V>(V? v) where U : T? where V : U? => v; // 7 static T? F13<U, V>(V? v) where U : T where V : U => v; static T? F14<U, V>(V? v) where U : T? where V : U => v; static T? F15<U, V>(V? v) where U : T where V : U? => v; static T? F16<U, V>(V? v) where U : T? where V : U? => v; }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,56): warning CS8603: Possible null reference return. // static T F2<U, V>(V v) where U : T? where V : U => v; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(5, 56), // (6,56): warning CS8603: Possible null reference return. // static T F3<U, V>(V v) where U : T where V : U? => v; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(6, 56), // (7,57): warning CS8603: Possible null reference return. // static T F4<U, V>(V v) where U : T? where V : U? => v; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(7, 57), // (12,56): warning CS8603: Possible null reference return. // static T F9<U, V>(V? v) where U : T where V : U => v; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(12, 56), // (13,58): warning CS8603: Possible null reference return. // static T F10<U, V>(V? v) where U : T? where V : U => v; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(13, 58), // (14,58): warning CS8603: Possible null reference return. // static T F11<U, V>(V? v) where U : T where V : U? => v; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(14, 58), // (15,59): warning CS8603: Possible null reference return. // static T F12<U, V>(V? v) where U : T? where V : U? => v; // 7 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(15, 59)); } [Fact] [WorkItem(46150, "https://github.com/dotnet/roslyn/issues/46150")] public void UnconstrainedTypeParameter_33() { var source = @"#nullable enable class A<T> { static T F1<U, V>(V v) where U : T where V : U, T => v; static T F2<U, V>(V v) where U : T where V : U, T? => v; static T F3<U, V>(V v) where U : T where V : U?, T => v; static T F4<U, V>(V v) where U : T where V : U?, T? => v; // 1 static T F5<U, V>(V? v) where U : T where V : U, T => v; // 2 static T F6<U, V>(V? v) where U : T where V : U, T? => v; // 3 static T F7<U, V>(V? v) where U : T where V : U?, T => v; // 4 static T F8<U, V>(V? v) where U : T where V : U?, T? => v; // 5 static T F9<U, V>(V v) where U : T? where V : U, T => v; static T F10<U, V>(V v) where U : T? where V : U, T? => v; // 6 static T F11<U, V>(V v) where U : T? where V : U?, T => v; static T F12<U, V>(V v) where U : T? where V : U?, T? => v; // 7 static T F13<U, V>(V? v) where U : T? where V : U, T => v; // 8 static T F14<U, V>(V? v) where U : T? where V : U, T? => v; // 9 static T F15<U, V>(V? v) where U : T? where V : U?, T => v; // 10 static T F16<U, V>(V? v) where U : T? where V : U?, T? => v; // 11 }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,60): warning CS8603: Possible null reference return. // static T F4<U, V>(V v) where U : T where V : U?, T? => v; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(7, 60), // (8,59): warning CS8603: Possible null reference return. // static T F5<U, V>(V? v) where U : T where V : U, T => v; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(8, 59), // (9,60): warning CS8603: Possible null reference return. // static T F6<U, V>(V? v) where U : T where V : U, T? => v; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(9, 60), // (10,60): warning CS8603: Possible null reference return. // static T F7<U, V>(V? v) where U : T where V : U?, T => v; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(10, 60), // (11,61): warning CS8603: Possible null reference return. // static T F8<U, V>(V? v) where U : T where V : U?, T? => v; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(11, 61), // (13,61): warning CS8603: Possible null reference return. // static T F10<U, V>(V v) where U : T? where V : U, T? => v; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(13, 61), // (15,62): warning CS8603: Possible null reference return. // static T F12<U, V>(V v) where U : T? where V : U?, T? => v; // 7 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(15, 62), // (16,61): warning CS8603: Possible null reference return. // static T F13<U, V>(V? v) where U : T? where V : U, T => v; // 8 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(16, 61), // (17,62): warning CS8603: Possible null reference return. // static T F14<U, V>(V? v) where U : T? where V : U, T? => v; // 9 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(17, 62), // (18,62): warning CS8603: Possible null reference return. // static T F15<U, V>(V? v) where U : T? where V : U?, T => v; // 10 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(18, 62), // (19,63): warning CS8603: Possible null reference return. // static T F16<U, V>(V? v) where U : T? where V : U?, T? => v; // 11 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "v").WithLocation(19, 63)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_34([CombinatorialValues(null, "class", "class?", "notnull")] string constraint, bool useCompilationReference) { var sourceA = @"#nullable enable public class A<T> { public static void F<U>(U u) where U : T { } }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var fullConstraint = constraint is null ? "" : ("where T : " + constraint); var sourceB = $@"#nullable enable class B {{ static void M1<T, U>(bool b, U x, U? y) {fullConstraint} where U : T {{ if (b) A<T>.F<U>(x); if (b) A<T>.F<U>(y); // 1 if (b) A<T>.F<U?>(x); // 2 if (b) A<T>.F<U?>(y); // 3 A<T>.F(x); A<T>.F(y); // 4 }} static void M2<T, U>(bool b, U x, U? y) {fullConstraint} where U : T? {{ if (b) A<T>.F<U>(x); // 5 if (b) A<T>.F<U>(y); // 6 if (b) A<T>.F<U?>(x); // 7 if (b) A<T>.F<U?>(y); // 8 if (b) A<T>.F(x); // 9 if (b) A<T>.F(y); // 10 }} }}"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,26): warning CS8604: Possible null reference argument for parameter 'u' in 'void A<T>.F<U>(U u)'. // if (b) A<T>.F<U>(y); // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("u", "void A<T>.F<U>(U u)").WithLocation(7, 26), // (8,16): warning CS8631: The type 'U?' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U?' doesn't match constraint type 'T'. // if (b) A<T>.F<U?>(x); // 2 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F<U?>").WithArguments("A<T>.F<U>(U)", "T", "U", "U?").WithLocation(8, 16), // (9,16): warning CS8631: The type 'U?' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U?' doesn't match constraint type 'T'. // if (b) A<T>.F<U?>(y); // 3 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F<U?>").WithArguments("A<T>.F<U>(U)", "T", "U", "U?").WithLocation(9, 16), // (11,9): warning CS8631: The type 'U?' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U?' doesn't match constraint type 'T'. // A<T>.F(y); // 4 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F").WithArguments("A<T>.F<U>(U)", "T", "U", "U?").WithLocation(11, 9), // (15,16): warning CS8631: The type 'U' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U' doesn't match constraint type 'T'. // if (b) A<T>.F<U>(x); // 5 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F<U>").WithArguments("A<T>.F<U>(U)", "T", "U", "U").WithLocation(15, 16), // (16,16): warning CS8631: The type 'U' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U' doesn't match constraint type 'T'. // if (b) A<T>.F<U>(y); // 6 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F<U>").WithArguments("A<T>.F<U>(U)", "T", "U", "U").WithLocation(16, 16), // (16,26): warning CS8604: Possible null reference argument for parameter 'u' in 'void A<T>.F<U>(U u)'. // if (b) A<T>.F<U>(y); // 6 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("u", "void A<T>.F<U>(U u)").WithLocation(16, 26), // (17,16): warning CS8631: The type 'U?' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U?' doesn't match constraint type 'T'. // if (b) A<T>.F<U?>(x); // 7 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F<U?>").WithArguments("A<T>.F<U>(U)", "T", "U", "U?").WithLocation(17, 16), // (18,16): warning CS8631: The type 'U?' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U?' doesn't match constraint type 'T'. // if (b) A<T>.F<U?>(y); // 8 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F<U?>").WithArguments("A<T>.F<U>(U)", "T", "U", "U?").WithLocation(18, 16), // (19,16): warning CS8631: The type 'U' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U' doesn't match constraint type 'T'. // if (b) A<T>.F(x); // 9 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F").WithArguments("A<T>.F<U>(U)", "T", "U", "U").WithLocation(19, 16), // (20,16): warning CS8631: The type 'U?' cannot be used as type parameter 'U' in the generic type or method 'A<T>.F<U>(U)'. Nullability of type argument 'U?' doesn't match constraint type 'T'. // if (b) A<T>.F(y); // 10 Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterConstraint, "A<T>.F").WithArguments("A<T>.F<U>(U)", "T", "U", "U?").WithLocation(20, 16)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_35(bool useCompilationReference) { var sourceA = @"#nullable enable public abstract class A<T> { public abstract U? F1<U>(U u) where U : T; public abstract U F2<U>(U? u) where U : T; public abstract U? F3<U>(U u) where U : T?; public abstract U F4<U>(U? u) where U : T?; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable enable class B1<T> : A<T> { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B2<T> : A<T?> { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B3<T> : A<T> where T : class { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B4<T> : A<T?> where T : class { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B5<T> : A<T> where T : class? { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B6<T> : A<T?> where T : class? { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B7<T> : A<T> where T : struct { public override U F1<U>(U u) where U : struct => default; public override U F2<U>(U u) where U : struct => default!; public override U F3<U>(U u) where U : struct => default; public override U F4<U>(U u) where U : struct => default!; } class B8<T> : A<T?> where T : struct { public override U F1<U>(U u) => default; public override U F2<U>(U u) => default!; public override U F3<U>(U u) => default; public override U F4<U>(U u) => default!; } class B9<T> : A<T> where T : notnull { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B10<T> : A<T?> where T : notnull { public override U? F1<U>(U u) where U : default => default; public override U F2<U>(U? u) where U : default => default!; public override U? F3<U>(U u) where U : default => default; public override U F4<U>(U? u) where U : default => default!; } class B11 : A<string> { public override U? F1<U>(U u) where U : class => default; public override U F2<U>(U? u) where U : class => default!; public override U? F3<U>(U u) where U : class => default; public override U F4<U>(U? u) where U : class => default!; } class B12 : A<string?> { public override U? F1<U>(U u) where U : class => default; public override U F2<U>(U? u) where U : class => default!; public override U? F3<U>(U u) where U : class => default; public override U F4<U>(U? u) where U : class => default!; } class B13 : A<int> { public override U F1<U>(U u) where U : struct => default; public override U F2<U>(U u) where U : struct => default; public override U F3<U>(U u) where U : struct => default; public override U F4<U>(U u) where U : struct => default; } class B14 : A<int?> { public override U F1<U>(U u) => default; public override U F2<U>(U u) => default; public override U F3<U>(U u) => default; public override U F4<U>(U u) => default; }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); } [Fact] public void UnconstrainedTypeParameter_36() { var source = @"#nullable enable class Program { static void F<T1, T2, T3, T4, T5>() where T2 : class where T3 : class? where T4 : notnull where T5 : T1? { default(T1).ToString(); // 1 default(T1?).ToString(); // 2 default(T2).ToString(); // 3 default(T2?).ToString(); // 4 default(T3).ToString(); // 5 default(T3?).ToString(); // 6 default(T4).ToString(); // 7 default(T4?).ToString(); // 8 default(T5).ToString(); // 9 default(T5?).ToString(); // 10 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (10,9): warning CS8602: Dereference of a possibly null reference. // default(T1).ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T1)").WithLocation(10, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // default(T1?).ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T1?)").WithLocation(11, 9), // (12,9): warning CS8602: Dereference of a possibly null reference. // default(T2).ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T2)").WithLocation(12, 9), // (13,9): warning CS8602: Dereference of a possibly null reference. // default(T2?).ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T2?)").WithLocation(13, 9), // (14,9): warning CS8602: Dereference of a possibly null reference. // default(T3).ToString(); // 5 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T3)").WithLocation(14, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // default(T3?).ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T3?)").WithLocation(15, 9), // (16,9): warning CS8602: Dereference of a possibly null reference. // default(T4).ToString(); // 7 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T4)").WithLocation(16, 9), // (17,9): warning CS8602: Dereference of a possibly null reference. // default(T4?).ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T4?)").WithLocation(17, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // default(T5).ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T5)").WithLocation(18, 9), // (19,9): warning CS8602: Dereference of a possibly null reference. // default(T5?).ToString(); // 10 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "default(T5?)").WithLocation(19, 9)); } [Fact] public void UnconstrainedTypeParameter_37() { var source = @"#nullable enable class Program { static T F1<T>() { T? t1 = default(T); return t1; // 1 } static T F2<T>() where T : class { T? t2 = default(T); return t2; // 2 } static T F3<T>() where T : class? { T? t3 = default(T); return t3; // 3 } static T F4<T>() where T : notnull { T? t4 = default(T); return t4; // 4 } static T F5<T, U>() where U : T? { T? t5 = default(U); return t5; // 5 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (7,16): warning CS8603: Possible null reference return. // return t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t1").WithLocation(7, 16), // (12,16): warning CS8603: Possible null reference return. // return t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t2").WithLocation(12, 16), // (17,16): warning CS8603: Possible null reference return. // return t3; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t3").WithLocation(17, 16), // (22,16): warning CS8603: Possible null reference return. // return t4; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t4").WithLocation(22, 16), // (27,16): warning CS8603: Possible null reference return. // return t5; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t5").WithLocation(27, 16)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var locals = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); Assert.Equal(5, locals.Length); VerifyVariableAnnotation(model, locals[0], "T? t1", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[1], "T? t2", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[2], "T? t3", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[3], "T? t4", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[4], "T? t5", NullableAnnotation.Annotated); } [Fact] [WorkItem(46236, "https://github.com/dotnet/roslyn/issues/46236")] public void UnconstrainedTypeParameter_38() { var source = @"#nullable enable class Program { static T F1<T>(T x1) { var y1 = x1; y1 = default(T); return y1; // 1 } static T F2<T>(T x2) where T : class { var y2 = x2; y2 = default(T); return y2; // 2 } static T F3<T>(T x3) where T : class? { var y3 = x3; y3 = default(T); return y3; // 3 } static T F4<T>(T x4) where T : notnull { var y4 = x4; y4 = default(T); return y4; // 4 } static T F5<T, U>(U x5) where U : T? { var y5 = x5; y5 = default(U); return y5; // 5 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (8,16): warning CS8603: Possible null reference return. // return y1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y1").WithLocation(8, 16), // (14,16): warning CS8603: Possible null reference return. // return y2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y2").WithLocation(14, 16), // (20,16): warning CS8603: Possible null reference return. // return y3; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y3").WithLocation(20, 16), // (26,16): warning CS8603: Possible null reference return. // return y4; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y4").WithLocation(26, 16), // (32,16): warning CS8603: Possible null reference return. // return y5; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "y5").WithLocation(32, 16)); var tree = comp.SyntaxTrees[0]; var model = comp.GetSemanticModel(tree); var locals = tree.GetRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().ToArray(); Assert.Equal(5, locals.Length); // https://github.com/dotnet/roslyn/issues/46236: Locals should be treated as annotated. VerifyVariableAnnotation(model, locals[0], "T? y1", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[1], "T? y2", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[2], "T? y3", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[3], "T? y4", NullableAnnotation.Annotated); VerifyVariableAnnotation(model, locals[4], "U? y5", NullableAnnotation.Annotated); } private static void VerifyVariableAnnotation(SemanticModel model, VariableDeclaratorSyntax syntax, string expectedDisplay, NullableAnnotation expectedAnnotation) { var symbol = (ILocalSymbol)model.GetDeclaredSymbol(syntax); Assert.Equal(expectedDisplay, symbol.ToTestDisplayString(includeNonNullable: true)); Assert.Equal( (expectedAnnotation == NullableAnnotation.Annotated) ? CodeAnalysis.NullableAnnotation.Annotated : CodeAnalysis.NullableAnnotation.NotAnnotated, symbol.Type.NullableAnnotation); Assert.Equal(expectedAnnotation, symbol.GetSymbol<LocalSymbol>().TypeWithAnnotations.NullableAnnotation); } [Fact] public void UnconstrainedTypeParameter_39() { var source = @"#nullable enable class Program { static T F1<T>(T t1) { return (T?)t1; // 1 } static T F2<T>(T t2) where T : class { return (T?)t2; // 2 } static T F3<T>(T t3) where T : class? { return (T?)t3; // 3 } static T F4<T>(T t4) where T : notnull { return (T?)t4; // 4 } static T F5<T, U>(U t5) where U : T? { return (T?)t5; // 5 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,16): warning CS8603: Possible null reference return. // return (T?)t1; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T?)t1").WithLocation(6, 16), // (10,16): warning CS8603: Possible null reference return. // return (T?)t2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T?)t2").WithLocation(10, 16), // (14,16): warning CS8603: Possible null reference return. // return (T?)t3; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T?)t3").WithLocation(14, 16), // (18,16): warning CS8603: Possible null reference return. // return (T?)t4; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T?)t4").WithLocation(18, 16), // (22,16): warning CS8603: Possible null reference return. // return (T?)t5; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "(T?)t5").WithLocation(22, 16)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_40(bool useCompilationReference) { var sourceA = @"#nullable enable using System.Diagnostics.CodeAnalysis; public interface I { } public abstract class A1 { [return: NotNull] public abstract T F1<T>(); [return: NotNull] public abstract T F2<T>() where T : class; [return: NotNull] public abstract T F3<T>() where T : class?; [return: NotNull] public abstract T F4<T>() where T : notnull; [return: NotNull] public abstract T F5<T>() where T : I; [return: NotNull] public abstract T F6<T>() where T : I?; } public abstract class A2 { public abstract void F1<T>([DisallowNull] T t); public abstract void F2<T>([DisallowNull] T t) where T : class; public abstract void F3<T>([DisallowNull] T t) where T : class?; public abstract void F4<T>([DisallowNull] T t) where T : notnull; public abstract void F5<T>([DisallowNull] T t) where T : I; public abstract void F6<T>([DisallowNull] T t) where T : I?; }"; var comp = CreateCompilation(new[] { sourceA, DisallowNullAttributeDefinition, NotNullAttributeDefinition }); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable enable class B1 : A1 { public override T F1<T>() where T : default => default!; public override T F2<T>() where T : class => default!; public override T F3<T>() where T : class => default!; public override T F4<T>() where T : default => default!; public override T F5<T>() where T : default => default!; public override T F6<T>() where T : default => default!; } class B2 : A2 { public override void F1<T>(T t) where T : default { } public override void F2<T>(T t) where T : class { } public override void F3<T>(T t) where T : class { } public override void F4<T>(T t) where T : default { } public override void F5<T>(T t) where T : default { } public override void F6<T>(T t) where T : default { } }"; comp = CreateCompilation(sourceB1, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,23): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T F1<T>() where T : default => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F1").WithLocation(4, 23), // (9,23): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T F6<T>() where T : default => default; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F6").WithLocation(9, 23)); var sourceB2 = @"#nullable enable class B1 : A1 { public override T? F1<T>() where T : default => default!; public override T? F2<T>() where T : class => default!; public override T? F3<T>() where T : class => default!; public override T? F4<T>() where T : default => default!; public override T? F5<T>() where T : default => default!; public override T? F6<T>() where T : default => default!; } class B2 : A2 { public override void F1<T>(T? t) where T : default { } public override void F2<T>(T? t) where T : class { } public override void F3<T>(T? t) where T : class { } public override void F4<T>(T? t) where T : default { } public override void F5<T>(T? t) where T : default { } public override void F6<T>(T? t) where T : default { } }"; comp = CreateCompilation(sourceB2, references: new[] { refA }, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (4,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F1<T>() where T : default => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F1").WithLocation(4, 24), // (5,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F2<T>() where T : class => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F2").WithLocation(5, 24), // (6,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F3<T>() where T : class => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F3").WithLocation(6, 24), // (7,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F4<T>() where T : default => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F4").WithLocation(7, 24), // (8,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F5<T>() where T : default => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F5").WithLocation(8, 24), // (9,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? F6<T>() where T : default => default!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "F6").WithLocation(9, 24)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_41(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I { } public abstract class A1 { public abstract T F1<T>(); public abstract T F2<T>() where T : class; public abstract T F3<T>() where T : class?; public abstract T F4<T>() where T : notnull; public abstract T F5<T>() where T : I; public abstract T F6<T>() where T : I?; } public abstract class A2 { public abstract void F1<T>(T t); public abstract void F2<T>(T t) where T : class; public abstract void F3<T>(T t) where T : class?; public abstract void F4<T>(T t) where T : notnull; public abstract void F5<T>(T t) where T : I; public abstract void F6<T>(T t) where T : I?; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable enable using System.Diagnostics.CodeAnalysis; class B1 : A1 { [return: NotNull] public override T F1<T>() => default!; [return: NotNull] public override T F2<T>() => default!; [return: NotNull] public override T F3<T>() => default!; [return: NotNull] public override T F4<T>() => default!; [return: NotNull] public override T F5<T>() => default!; [return: NotNull] public override T F6<T>() => default!; } class B2 : A2 { public override void F1<T>([DisallowNull] T t) { } public override void F2<T>([DisallowNull] T t) { } public override void F3<T>([DisallowNull] T t) { } public override void F4<T>([DisallowNull] T t) { } public override void F5<T>([DisallowNull] T t) { } public override void F6<T>([DisallowNull] T t) { } }"; comp = CreateCompilation(new[] { sourceB, DisallowNullAttributeDefinition, NotNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics( // (14,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t").WithLocation(14, 26), // (19,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F6<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t").WithLocation(19, 26) ); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_42(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I { } public abstract class A1 { public abstract T? F1<T>(); public abstract T? F2<T>() where T : class; public abstract T? F3<T>() where T : class?; public abstract T? F4<T>() where T : notnull; public abstract T? F5<T>() where T : I; public abstract T? F6<T>() where T : I?; } public abstract class A2 { public abstract void F1<T>(T? t); public abstract void F2<T>(T? t) where T : class; public abstract void F3<T>(T? t) where T : class?; public abstract void F4<T>(T? t) where T : notnull; public abstract void F5<T>(T? t) where T : I; public abstract void F6<T>(T? t) where T : I?; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable enable using System.Diagnostics.CodeAnalysis; class B1 : A1 { [return: NotNull] public override T F1<T>() => default!; [return: NotNull] public override T F2<T>() => default!; [return: NotNull] public override T F3<T>() => default!; [return: NotNull] public override T F4<T>() => default!; [return: NotNull] public override T F5<T>() => default!; [return: NotNull] public override T F6<T>() => default!; } class B2 : A2 { public override void F1<T>([DisallowNull] T t) { } public override void F2<T>([DisallowNull] T t) { } public override void F3<T>([DisallowNull] T t) { } public override void F4<T>([DisallowNull] T t) { } public override void F5<T>([DisallowNull] T t) { } public override void F6<T>([DisallowNull] T t) { } }"; comp = CreateCompilation(new[] { sourceB, DisallowNullAttributeDefinition, NotNullAttributeDefinition }, references: new[] { refA }); comp.VerifyDiagnostics( // (14,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F1<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F1").WithArguments("t").WithLocation(14, 26), // (15,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t").WithLocation(15, 26), // (16,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F3<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F3").WithArguments("t").WithLocation(16, 26), // (17,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F4<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F4").WithArguments("t").WithLocation(17, 26), // (18,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F5<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F5").WithArguments("t").WithLocation(18, 26), // (19,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F6<T>([DisallowNull] T t) { } Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F6").WithArguments("t").WithLocation(19, 26)); } [Fact] public void UnconstrainedTypeParameter_43() { var source = @"#nullable enable class Program { static T F1<T>(bool b, T x1, T? y1) { if (b) return new[] { y1, x1 }[0]; // 1 return new[] { x1, y1 }[0]; // 2 } static T F2<T>(bool b, T x2, T? y2) where T : class? { if (b) return new[] { y2, x2 }[0]; // 3 return new[] { x2, y2 }[0]; // 4 } static T F3<T>(bool b, T x3, T? y3) where T : notnull { if (b) return new[] { y3, x3 }[0]; // 5 return new[] { x3, y3 }[0]; // 6 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,23): warning CS8603: Possible null reference return. // if (b) return new[] { y1, x1 }[0]; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { y1, x1 }[0]").WithLocation(6, 23), // (7,16): warning CS8603: Possible null reference return. // return new[] { x1, y1 }[0]; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { x1, y1 }[0]").WithLocation(7, 16), // (11,23): warning CS8603: Possible null reference return. // if (b) return new[] { y2, x2 }[0]; // 3 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { y2, x2 }[0]").WithLocation(11, 23), // (12,16): warning CS8603: Possible null reference return. // return new[] { x2, y2 }[0]; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { x2, y2 }[0]").WithLocation(12, 16), // (16,23): warning CS8603: Possible null reference return. // if (b) return new[] { y3, x3 }[0]; // 5 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { y3, x3 }[0]").WithLocation(16, 23), // (17,16): warning CS8603: Possible null reference return. // return new[] { x3, y3 }[0]; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "new[] { x3, y3 }[0]").WithLocation(17, 16)); } [Fact] public void UnconstrainedTypeParameter_44() { var source = @"class Program { static void F1<T>(T? t) { } static void F2<T>(T? t) where T : class? { } static void F3<T>(T? t) where T : notnull { } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (3,23): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F1<T>(T? t) { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(3, 23), // (3,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F1<T>(T? t) { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 24), // (4,23): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F2<T>(T? t) where T : class? { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(4, 23), // (4,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F2<T>(T? t) where T : class? { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 24), // (4,44): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F2<T>(T? t) where T : class? { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 44), // (5,23): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // static void F3<T>(T? t) where T : notnull { } Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(5, 23), // (5,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F3<T>(T? t) where T : notnull { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 24)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (3,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F1<T>(T? t) { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(3, 24), // (4,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F2<T>(T? t) where T : class? { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 24), // (4,44): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F2<T>(T? t) where T : class? { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(4, 44), // (5,24): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // static void F3<T>(T? t) where T : notnull { } Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(5, 24)); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_45(bool useCompilationReference) { var sourceA = @"#nullable disable public interface I { } public abstract class A1 { public abstract T F1<T>(); public abstract T F2<T>() where T : class; public abstract T F4<T>() where T : notnull; public abstract T F5<T>() where T : I; } public abstract class A2 { public abstract void F1<T>(T t); public abstract void F2<T>(T t) where T : class; public abstract void F4<T>(T t) where T : notnull; public abstract void F5<T>(T t) where T : I; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable enable class B1 : A1 { public override T? F1<T>() where T : default => default!; public override T? F2<T>() where T : class => default!; public override T? F4<T>() where T : default => default!; public override T? F5<T>() where T : default => default!; } class B2 : A2 { public override void F1<T>(T? t) where T : default { } public override void F2<T>(T? t) where T : class { } public override void F4<T>(T? t) where T : default { } public override void F5<T>(T? t) where T : default { } }"; comp = CreateCompilation(sourceB, references: new[] { refA }); comp.VerifyDiagnostics(); } [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_46(bool useCompilationReference) { var sourceA = @"#nullable enable public interface I { } public abstract class A1 { public abstract T? F1<T>(); public abstract T? F2<T>() where T : class; public abstract T? F3<T>() where T : class?; public abstract T? F4<T>() where T : notnull; public abstract T? F5<T>() where T : I; public abstract T? F6<T>() where T : I?; } public abstract class A2 { public abstract void F1<T>(T? t); public abstract void F2<T>(T? t) where T : class; public abstract void F3<T>(T? t) where T : class?; public abstract void F4<T>(T? t) where T : notnull; public abstract void F5<T>(T? t) where T : I; public abstract void F6<T>(T? t) where T : I?; }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB = @"#nullable disable class B1 : A1 { public override T F1<T>() => default!; public override T F2<T>() => default!; public override T F3<T>() => default!; public override T F4<T>() => default!; public override T F5<T>() => default!; public override T F6<T>() => default!; } class B2 : A2 { public override void F1<T>(T t) { } public override void F2<T>(T t) { } public override void F3<T>(T t) { } public override void F4<T>(T t) { } public override void F5<T>(T t) { } public override void F6<T>(T t) { } }"; comp = CreateCompilation(sourceB, references: new[] { refA }, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics(); } [WorkItem(49131, "https://github.com/dotnet/roslyn/issues/49131")] [Theory] [CombinatorialData] public void UnconstrainedTypeParameter_47(bool useCompilationReference) { var sourceA = @"public abstract class A { #nullable disable public abstract void F1<T>(out T t); #nullable enable public abstract void F2<T>(out T t); public abstract void F3<T>(out T? t); }"; var comp = CreateCompilation(sourceA, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB1 = @"#nullable disable class B : A { public override void F1<T>(out T t) => throw null; public override void F2<T>(out T t) => throw null; public override void F3<T>(out T t) => throw null; }"; comp = CreateCompilation(sourceB1, references: new[] { refA }); comp.VerifyDiagnostics(); var sourceB2 = @"#nullable enable class B : A { public override void F1<T>(out T t) => throw null!; public override void F2<T>(out T t) => throw null!; public override void F3<T>(out T t) => throw null!; }"; comp = CreateCompilation(sourceB2, references: new[] { refA }); comp.VerifyDiagnostics(); var sourceB3 = @"#nullable enable class B : A { public override void F1<T>(out T t) where T : default => throw null!; public override void F2<T>(out T t) where T : default => throw null!; public override void F3<T>(out T t) where T : default => throw null!; }"; comp = CreateCompilation(sourceB3, references: new[] { refA }); comp.VerifyDiagnostics(); var sourceB4 = @"#nullable enable class B : A { public override void F1<T>(out T? t) where T : default => throw null!; public override void F2<T>(out T? t) where T : default => throw null!; public override void F3<T>(out T? t) where T : default => throw null!; }"; comp = CreateCompilation(sourceB4, references: new[] { refA }); comp.VerifyDiagnostics( // (5,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void F2<T>(out T? t) where T : default => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "F2").WithArguments("t").WithLocation(5, 26) ); } [Theory] [InlineData("")] [InlineData("where T : class")] [InlineData("where T : class?")] [InlineData("where T : notnull")] [InlineData("where T : I")] [InlineData("where T : I?")] public void UnconstrainedTypeParameter_48(string constraint) { var source = $@"#pragma warning disable 219 #nullable enable interface I {{ }} class A<T> {constraint} {{ static void F1() {{ T t = default; }} // 1 static void F2() {{ T? t = default; }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,30): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F1() { T t = default; } // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(6, 30)); } [Theory] [InlineData("")] [InlineData("where T : class")] [InlineData("where T : class?")] [InlineData("where T : notnull")] [InlineData("where T : I")] [InlineData("where T : I?")] public void UnconstrainedTypeParameter_49(string constraint) { var source = $@"#nullable enable interface I {{ }} class A<T> {constraint} {{ static void F1(T x) {{ T y = x; }} static void F2(T? x) {{ T y = x; }} // 1 static void F3(T x) {{ T? y = x; }} static void F4(T? x) {{ T? y = x; }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,34): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F2(T? x) { T y = x; } // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "x").WithLocation(6, 34)); } [Theory] [InlineData("")] [InlineData("where T : class")] [InlineData("where T : class?")] [InlineData("where T : notnull")] [InlineData("where T : I")] [InlineData("where T : I?")] public void UnconstrainedTypeParameter_50(string constraint) { var source = $@"#pragma warning disable 219 #nullable enable interface I {{ }} class A<T> {constraint} {{ static void F1<U>() where U : T {{ T t = default(U); }} // 1 static void F2<U>() where U : T? {{ T t = default(U); }} // 2 static void F3<U>() where U : T {{ T? t = default(U); }} static void F4<U>() where U : T? {{ T? t = default(U); }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,45): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F1<U>() where U : T { T t = default(U); } // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(U)").WithLocation(6, 45), // (7,46): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F2<U>() where U : T? { T t = default(U); } // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default(U)").WithLocation(7, 46)); } [Theory] [InlineData("")] [InlineData("where T : class")] [InlineData("where T : class?")] [InlineData("where T : notnull")] [InlineData("where T : I")] [InlineData("where T : I?")] public void UnconstrainedTypeParameter_51(string constraint) { var source = $@"#nullable enable interface I {{ }} class A<T> {constraint} {{ static void F1<U>(U u) where U : T {{ T t = u; }} static void F2<U>(U u) where U : T? {{ T t = u; }} // 1 static void F3<U>(U u) where U : T {{ T? t = u; }} static void F4<U>(U u) where U : T? {{ T? t = u; }} static void F5<U>(U? u) where U : T {{ T t = u; }} // 2 static void F6<U>(U? u) where U : T? {{ T t = u; }} // 3 static void F7<U>(U? u) where U : T {{ T? t = u; }} static void F8<U>(U? u) where U : T? {{ T? t = u; }} }}"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (6,49): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F2<U>(U u) where U : T? { T t = u; } // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(6, 49), // (9,49): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F5<U>(U? u) where U : T { T t = u; } // 2 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(9, 49), // (10,50): warning CS8600: Converting null literal or possible null value to non-nullable type. // static void F6<U>(U? u) where U : T? { T t = u; } // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "u").WithLocation(10, 50)); } [Fact] public void UnconstrainedTypeParameter_52() { var source = @"#nullable enable class Program { static T F1<T>() { T t = default; // 1 return t; // 2 } static T F2<T>(object? o) { T t = (T)o; // 3 return t; // 4 } static U F3<T, U>(T t) where U : T { U u = (U)t; // 5 return u; // 6 } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (7,16): warning CS8603: Possible null reference return. // return t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(7, 16), // (12,16): warning CS8603: Possible null reference return. // return t; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(12, 16), // (17,16): warning CS8603: Possible null reference return. // return u; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(17, 16)); comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (6,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t = default; // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(6, 15), // (7,16): warning CS8603: Possible null reference return. // return t; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(7, 16), // (11,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t = (T)o; // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(T)o").WithLocation(11, 15), // (12,16): warning CS8603: Possible null reference return. // return t; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(12, 16), // (16,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // U u = (U)t; // 5 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "(U)t").WithLocation(16, 15), // (17,16): warning CS8603: Possible null reference return. // return u; // 6 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "u").WithLocation(17, 16)); } [Fact] public void UnconstrainedTypeParameter_53() { var source = @"#nullable enable class Pair<T, U> { internal void Deconstruct(out T x, out U y) => throw null!; } class Program { static T F2<T>(T x) { T y; (y, _) = (x, x); return y; } static T F3<T>() { var p = new Pair<T, T>(); T t; (t, _) = p; return t; } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(39540, "https://github.com/dotnet/roslyn/issues/39540")] public void IsObjectAndNotIsNull() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C { void F0(int? i) { _ = i.Value; // 1 } void F1(int? i) { MyAssert(i is object); _ = i.Value; } void F2(int? i) { MyAssert(i is object); MyAssert(!(i is null)); _ = i.Value; } void F3(int? i) { MyAssert(!(i is null)); _ = i.Value; } void F5(object? o) { _ = o.ToString(); // 2 } void F6(object? o) { MyAssert(o is object); _ = o.ToString(); } void F7(object? o) { MyAssert(o is object); MyAssert(!(o is null)); _ = o.ToString(); } void F8(object? o) { MyAssert(!(o is null)); _ = o.ToString(); } void MyAssert([DoesNotReturnIf(false)] bool condition) => throw null!; }"; var comp = CreateCompilation(new[] { source, DoesNotReturnIfAttributeDefinition }); comp.VerifyDiagnostics( // (10,13): warning CS8629: Nullable value type may be null. // _ = i.Value; // 1 Diagnostic(ErrorCode.WRN_NullableValueTypeMayBeNull, "i").WithLocation(10, 13), // (34,13): warning CS8602: Dereference of a possibly null reference. // _ = o.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "o").WithLocation(34, 13) ); } [Fact, WorkItem(38030, "https://github.com/dotnet/roslyn/issues/38030")] public void CastOnDefault() { string source = @" #nullable enable public struct S { public string field; public S(string s) => throw null!; public static void M() { S s = (S) (S) default; s.field.ToString(); // 1 S s2 = (S) default; s2.field.ToString(); // 2 S s3 = (S) (S) default(S); s3.field.ToString(); // 3 S s4 = (S) default(S); s4.field.ToString(); // 4 } }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (12,9): warning CS8602: Dereference of a possibly null reference. // s.field.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s.field").WithLocation(12, 9), // (15,9): warning CS8602: Dereference of a possibly null reference. // s2.field.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s2.field").WithLocation(15, 9), // (18,9): warning CS8602: Dereference of a possibly null reference. // s3.field.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s3.field").WithLocation(18, 9), // (21,9): warning CS8602: Dereference of a possibly null reference. // s4.field.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "s4.field").WithLocation(21, 9) ); } [Fact] [WorkItem(38586, "https://github.com/dotnet/roslyn/issues/38586")] public void SuppressSwitchExpressionInput() { var source = @"#nullable enable public class C { public int M0(C a) => a switch { C _ => 0 }; // ok public int M1(C? a) => a switch { C _ => 0 }; // warns public int M2(C? a) => a! switch { C _ => 0 }; // ok public int M3(C a) => (1, a) switch { (_, C _) => 0 }; // ok public int M4(C? a) => (1, a) switch { (_, C _) => 0 }; // warns public int M5(C? a) => (1, a!) switch { (_, C _) => 0 }; // warns public void M6(C? a, bool b) { if (a == null) return; switch (a!) { case C _: break; case null: // does not affect knowledge of 'a' break; } a.ToString(); } public void M7(C? a, bool b) { if (a == null) return; switch (a) { case C _: break; case null: // affects knowledge of a break; } a.ToString(); // warns } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,30): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern 'null' is not covered. // public int M1(C? a) => a switch { C _ => 0 }; // warns Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("null").WithLocation(4, 30), // (8,35): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(_, null)' is not covered. // public int M4(C? a) => (1, a) switch { (_, C _) => 0 }; // warns Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(_, null)").WithLocation(8, 35), // (9,36): warning CS8655: The switch expression does not handle some null inputs (it is not exhaustive). For example, the pattern '(_, null)' is not covered. // public int M5(C? a) => (1, a!) switch { (_, C _) => 0 }; // warns Diagnostic(ErrorCode.WRN_SwitchExpressionNotExhaustiveForNull, "switch").WithArguments("(_, null)").WithLocation(9, 36), // (36,9): warning CS8602: Dereference of a possibly null reference. // a.ToString(); // warns Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "a").WithLocation(36, 9) ); } [Theory] [InlineData(true)] [InlineData(false)] [WorkItem(40430, "https://github.com/dotnet/roslyn/issues/40430")] public void DecodingWithMissingNullableAttribute(bool useImageReference) { var nullableAttrComp = CreateCompilation(NullableAttributeDefinition); nullableAttrComp.VerifyDiagnostics(); var nullableAttrRef = useImageReference ? nullableAttrComp.EmitToImageReference() : nullableAttrComp.ToMetadataReference(); var lib_cs = @" #nullable enable public class C3<T1, T2, T3> { } public class SelfReferencing : C3<SelfReferencing, string?, string> { public SelfReferencing() { System.Console.Write(""ran""); } } "; var lib = CreateCompilation(lib_cs, references: new[] { nullableAttrRef }); lib.VerifyDiagnostics(); var libRef = useImageReference ? lib.EmitToImageReference() : lib.ToMetadataReference(); var source_cs = @" public class C2 { public static void M() { _ = new SelfReferencing(); } } "; var comp = CreateCompilation(source_cs, references: new[] { libRef }); comp.VerifyEmitDiagnostics(); var executable_cs = @" public class C { public static void Main() { C2.M(); } }"; var executeComp = CreateCompilation(executable_cs, references: new[] { comp.EmitToImageReference(), libRef, nullableAttrRef }, options: TestOptions.DebugExe); CompileAndVerify(executeComp, expectedOutput: "ran"); } [Fact, WorkItem(41437, "https://github.com/dotnet/roslyn/issues/41437")] public void CannotAssignMaybeNullToTNotNull() { var source = @" class C { TNotNull M<TNotNull>(TNotNull t) where TNotNull : notnull { if (t is null) System.Console.WriteLine(); return t; // 1 } }"; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics( // (8,16): warning CS8603: Possible null reference return. // return t; // 1 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "t").WithLocation(8, 16) ); } [Fact, WorkItem(41437, "https://github.com/dotnet/roslyn/issues/41437")] public void CanAssignMaybeNullToMaybeNullTNotNull() { var source = @" using System.Diagnostics.CodeAnalysis; class C { [return: MaybeNull] TNotNull M<TNotNull>(TNotNull t) where TNotNull : notnull { if (t is null) System.Console.WriteLine(); return t; } }"; var comp = CreateNullableCompilation(new[] { source, MaybeNullAttributeDefinition }); comp.VerifyDiagnostics(); } [Fact] [WorkItem(35602, "https://github.com/dotnet/roslyn/issues/35602")] public void PureNullTestOnUnconstrainedType() { var source = @" class C { static T GetGeneric<T>(T t) { if (t is null) return t; return Id(t); } static T Id<T>(T t) => throw null!; } "; // If the null test changed the state of the variable to MaybeDefault // we would introduce an annoying warning var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] public void VarLocalUsedInLocalFunction() { var source = @"#nullable enable public class C { void M() { var x = """"; var y = """"; System.Action z = local; void local() => x.ToString(); void local2() => y.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,14): warning CS8321: The local function 'local2' is declared but never used // void local2() => y.ToString(); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local2").WithArguments("local2").WithLocation(11, 14), // (11,26): warning CS8602: Dereference of a possibly null reference. // void local2() => y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 26) ); } [Fact] public void ExplicitNullableLocalUsedInLocalFunction() { var source = @"#nullable enable public class C { void M() { string? x = """"; string? y = """"; System.Action z = local; void local() => x.ToString(); void local2() => y.ToString(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,14): warning CS8321: The local function 'local2' is declared but never used // void local2() => y.ToString(); Diagnostic(ErrorCode.WRN_UnreferencedLocalFunction, "local2").WithArguments("local2").WithLocation(11, 14), // (11,26): warning CS8602: Dereference of a possibly null reference. // void local2() => y.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(11, 26) ); } [Fact, WorkItem(40925, "https://github.com/dotnet/roslyn/issues/40925")] public void GetTypeInfoOnNullableType() { var source = @"#nullable enable #nullable enable class Program2 { } class Program { void Method(Program x) { (global::Program y1, global::Program? y2) = (x, x); global::Program y3 = x; global::Program? y4 = x; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var identifiers = tree.GetRoot().DescendantNodes().Where(n => n.ToString() == "global::Program").ToArray(); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, model.GetTypeInfo(identifiers[0]).Nullability.Annotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfo(identifiers[1]).Nullability.Annotation); Assert.Equal(CodeAnalysis.NullableAnnotation.NotAnnotated, model.GetTypeInfo(identifiers[2]).Nullability.Annotation); Assert.Equal(CodeAnalysis.NullableAnnotation.None, model.GetTypeInfo(identifiers[3]).Nullability.Annotation); // Note: this discrepancy causes some issues with type simplification in the IDE layer } [Fact, WorkItem(39417, "https://github.com/dotnet/roslyn/issues/39417")] public void ConfigureAwait_DetectSettingNullableToNonNullableType() { var source = @"using System.Threading.Tasks; #nullable enable class Request { public string? Name { get; } public Task<string?> GetName() => Task.FromResult(Name); } class Handler { public async Task Handle(Request request) { string a = request.Name; string b = await request.GetName().ConfigureAwait(false); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "request.Name").WithLocation(12, 20), Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "await request.GetName().ConfigureAwait(false)").WithLocation(13, 20) ); } [Fact] [WorkItem(44049, "https://github.com/dotnet/roslyn/issues/44049")] public void MemberNotNull_InstanceMemberOnStaticMethod() { var source = @"using System.Diagnostics.CodeAnalysis; class C { public string? field; [MemberNotNull(""field"")] public static void M() { } public void Test() { M(); field.ToString(); } }"; var comp = CreateCompilation( new[] { source }, options: WithNullableEnable(), targetFramework: TargetFramework.NetCoreApp, parseOptions: TestOptions.Regular9); comp.VerifyDiagnostics( // (5,20): warning CS0649: Field 'C.field' is never assigned to, and will always have its default value null // public string? field; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "field").WithArguments("C.field", "null").WithLocation(5, 20), // (15,9): warning CS8602: Dereference of a possibly null reference. // field.ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "field").WithLocation(15, 9)); } [Fact, WorkItem(39417, "https://github.com/dotnet/roslyn/issues/39417")] public void CustomAwaitable_DetectSettingNullableToNonNullableType() { var source = @"using System.Runtime.CompilerServices; using System.Threading.Tasks; #nullable enable static class TaskExtensions { public static ConfiguredTaskAwaitable<TResult> NoSync<TResult>(this Task<TResult> task) { return task.ConfigureAwait(false); } } class Request { public string? Name { get; } public Task<string?> GetName() => Task.FromResult(Name); } class Handler { public async Task Handle(Request request) { string a = await request.GetName().NoSync(); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "await request.GetName().NoSync()").WithLocation(20, 20) ); } [Fact] [WorkItem(39220, "https://github.com/dotnet/roslyn/issues/39220")] public void GotoMayCauseAnotherAnalysisPass_01() { var source = @"#nullable enable class Program { static void Test(string? s) { if (s == null) return; heck: var c = GetC(s); var prop = c.Property; prop.ToString(); // Dereference of null value (after goto) s = null; goto heck; } static void Main() { Test(""""); } public static C<T> GetC<T>(T t) => new C<T>(t); } class C<T> { public C(T t) => Property = t; public T Property { get; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,9): warning CS8602: Dereference of a possibly null reference. // prop.ToString(); // BOOM (after goto) Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "prop").WithLocation(11, 9) ); } [Fact] [WorkItem(40904, "https://github.com/dotnet/roslyn/issues/40904")] public void GotoMayCauseAnotherAnalysisPass_02() { var source = @"#nullable enable public class C { public void M(bool b) { string? s = ""x""; if (b) goto L2; L1: var x = Create(s); x.F.ToString(); // warning: x.F might be null. L2: s = null; goto L1; } private G<T> Create<T>(T t) where T : class? => new G<T>(t); } class G<T> where T : class? { public G(T f) => F = f; public T F; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x.F.ToString(); // warning: x.F might be null. Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(8, 9) ); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/40904")] [WorkItem(40904, "https://github.com/dotnet/roslyn/issues/40904")] public void GotoMayCauseAnotherAnalysisPass_03() { var source = @"#nullable enable public class C { public void M(bool b) { string? s = ""x""; if (b) goto L2; L1: _ = Create(s) is var x; x.F.ToString(); // warning: x.F might be null. L2: s = null; goto L1; } private G<T> Create<T>(T t) where T : class? => new G<T>(t); } class G<T> where T : class? { public G(T f) => F = f; public T F; }"; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x.F.ToString(); // warning: x.F might be null. Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x.F").WithLocation(8, 9) ); } [Fact] public void FunctionPointerSubstitutedGenericNullableWarning() { var comp = CreateCompilation(@" #nullable enable unsafe class C { static void M<T>(delegate*<T, void> ptr1, delegate*<T> ptr2) { T t = default; ptr1(t); ptr2().ToString(); } }", parseOptions: TestOptions.Regular9, options: TestOptions.UnsafeReleaseDll); comp.VerifyDiagnostics( // (7,15): warning CS8600: Converting null literal or possible null value to non-nullable type. // T t = default; Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "default").WithLocation(7, 15), // (8,14): warning CS8604: Possible null reference argument for parameter '' in 'delegate*<T, void>'. // ptr1(t); Diagnostic(ErrorCode.WRN_NullReferenceArgument, "t").WithArguments("", "delegate*<T, void>").WithLocation(8, 14), // (9,9): warning CS8602: Dereference of a possibly null reference. // ptr2().ToString(); Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "ptr2()").WithLocation(9, 9) ); } [Fact, WorkItem(44438, "https://github.com/dotnet/roslyn/issues/44438")] public void BadOverride_NestedNullableTypeParameter() { var comp = CreateNullableCompilation(@" class A { public virtual void M1<T>(C<System.Nullable<T>> x) where T : struct { } } class B : A { public override void M1<T>(C<System.Nullable<T?> x) { } } class C<T> {} "); comp.VerifyDiagnostics( // (11,32): error CS0305: Using the generic type 'C<T>' requires 1 type arguments // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_BadArity, "C<System.Nullable<T?> x").WithArguments("C<T>", "type", "1").WithLocation(11, 32), // (11,54): error CS1003: Syntax error, ',' expected // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_SyntaxError, "x").WithArguments(",", "").WithLocation(11, 54), // (11,54): error CS0246: The type or namespace name 'x' could not be found (are you missing a using directive or an assembly reference?) // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "x").WithArguments("x").WithLocation(11, 54), // (11,55): error CS1003: Syntax error, '>' expected // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_SyntaxError, ")").WithArguments(">", ")").WithLocation(11, 55), // (11,55): error CS1001: Identifier expected // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(11, 55), // (11,55): error CS0453: The type 'T?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "").WithArguments("System.Nullable<T>", "T", "T?").WithLocation(11, 55), // (11,55): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(C<System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 55) ); } [Fact, WorkItem(44438, "https://github.com/dotnet/roslyn/issues/44438")] public void Override_NestedNullableTypeParameter() { var comp = CreateNullableCompilation(@" class A { public virtual void M1<T>(int x) { } } class B : A { public override void M1<T>(System.Nullable<T?> x) { } } "); comp.VerifyDiagnostics( // (11,26): error CS0115: 'B.M1<T>(T??)': no suitable method found to override // public override void M1<T>(System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "M1").WithArguments("B.M1<T>(T??)").WithLocation(11, 26), // (11,52): error CS0453: The type 'T?' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T?").WithLocation(11, 52), // (11,52): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public override void M1<T>(System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 52) ); } [Fact, WorkItem(44438, "https://github.com/dotnet/roslyn/issues/44438")] public void Hide_NestedNullableTypeParameter() { var comp = CreateNullableCompilation(@" class A { public virtual void M1<T>(int x) { } } class B : A { public new void M1<T>(System.Nullable<T?> x) { } } ", parseOptions: TestOptions.Regular8); comp.VerifyDiagnostics( // (11,21): warning CS0109: The member 'B.M1<T>(T??)' does not hide an accessible member. The new keyword is not required. // public new void M1<T>(System.Nullable<T?> x) Diagnostic(ErrorCode.WRN_NewNotRequired, "M1").WithArguments("B.M1<T>(T??)").WithLocation(11, 21), // (11,43): error CS8627: A nullable type parameter must be known to be a value type or non-nullable reference type unless language version '9.0' or greater is used. Consider changing the language version or adding a 'class', 'struct', or type constraint. // public new void M1<T>(System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_NullableUnconstrainedTypeParameter, "T?").WithArguments("9.0").WithLocation(11, 43), // (11,47): error CS0453: The type 'T' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable<T>' // public new void M1<T>(System.Nullable<T?> x) Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "x").WithArguments("System.Nullable<T>", "T", "T").WithLocation(11, 47) ); } [Fact, WorkItem(43071, "https://github.com/dotnet/roslyn/issues/43071")] public void LocalFunctionInLambdaWithReturnStatement() { var source = @" using System; using System.Collections.Generic; public class C<T> { public static C<string> ReproFunction(C<string> collection) { return collection .SelectMany(allStrings => { return new[] { getSomeString(""custard"") }; string getSomeString(string substring) { return substring; } }); } } public static class Extension { public static C<TResult> SelectMany<TSource, TResult>(this C<TSource> source, Func<TSource, IEnumerable<TResult>> selector) { throw null!; } } "; var comp = CreateNullableCompilation(source); comp.VerifyDiagnostics(); } [Fact] [WorkItem(44348, "https://github.com/dotnet/roslyn/issues/44348")] public void NestedTypeConstraints_01() { var source = @"class A<T, U> { internal interface IA { } internal class C { } } #nullable enable class B<T, U> : A<T, U> where T : B<T, U>.IB where U : A<T, U>.C { internal interface IB : IA { } }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(45713, "https://github.com/dotnet/roslyn/issues/45713")] public void NestedTypeConstraints_02() { var source = @"class A<T> { internal interface IA { } } #nullable enable class B<T> : A<T> where T : B<T>.IA { }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(45713, "https://github.com/dotnet/roslyn/issues/45713")] public void NestedTypeConstraints_03() { var source = @"class A<T> { internal interface IA { } } #nullable enable class B<T> : A<T> where T : B<T?>.IA { }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(45713, "https://github.com/dotnet/roslyn/issues/45713")] public void NestedTypeConstraints_04() { var source = @"class A<T> { internal interface IA { } } #nullable enable class B<T> : A<T> #nullable disable where T : B<T>.IA { }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(45713, "https://github.com/dotnet/roslyn/issues/45713")] public void NestedTypeConstraints_05() { var source = @"class A<T> { internal interface IA { } } #nullable enable class B<T> : A<T> #nullable disable where T : B<T?>.IA { }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics( // (8,18): warning CS8632: The annotation for nullable reference types should only be used in code within a '#nullable' annotations context. // where T : B<T?>.IA Diagnostic(ErrorCode.WRN_MissingNonNullTypesContextForAnnotation, "?").WithLocation(8, 18)); } [Fact] [WorkItem(45713, "https://github.com/dotnet/roslyn/issues/45713")] public void NestedTypeConstraints_06() { var source0 = @"public class A<T> { public interface IA { } } #nullable enable public class B<T> : A<T> where T : B<T>.IA { }"; var comp = CreateCompilation(source0); var ref0 = comp.EmitToImageReference(); var source1 = @"class A : A<A>.IA { } class Program { static B<A> F() => new(); static void Main() { System.Console.WriteLine(F()); } }"; CompileAndVerify(source1, references: new[] { ref0 }, expectedOutput: "B`1[A]"); } [Fact] [WorkItem(45863, "https://github.com/dotnet/roslyn/issues/45863")] public void NestedTypeConstraints_07() { var source = @"#nullable enable interface IA<T> { } interface IB<T, U> : IA<T> where U : IB<T, U>.IC { interface IC { } }"; var comp = CreateCompilation(source); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(45863, "https://github.com/dotnet/roslyn/issues/45863")] public void NestedTypeConstraints_08() { var source0 = @"#nullable enable public interface IA<T> { } public interface IB<T, U> : IA<T> where U : IB<T, U>.IC { public interface IC { } }"; var comp = CreateCompilation(source0); var ref0 = comp.EmitToImageReference(); var source1 = @"class C : IB<object, C>.IC { } class Program { static C F() => new(); static void Main() { System.Console.WriteLine(F()); } }"; CompileAndVerify(source1, references: new[] { ref0 }, expectedOutput: "C"); } [Fact] [WorkItem(46342, "https://github.com/dotnet/roslyn/issues/46342")] public void LambdaNullReturn_01() { var source = @"#nullable enable using System; class Program { static void F<T>(Func<T> f) { } static void M1<T>(bool b, T t) where T : class { F(() => { if (b) return null; return t; }); } static void M2<T>(bool b, T t) where T : class? { F(() => { if (b) return null; return t; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(46342, "https://github.com/dotnet/roslyn/issues/46342")] public void LambdaNullReturn_02() { var source = @"#nullable enable using System; class Program { static void F<T>(Func<T> f) { } static void M1<T>(T? t) where T : class { F(() => { if (t is null) return null; return t; }); } static void M2<T>(T? t) where T : class? { F(() => { if (t is null) return null; return t; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(46342, "https://github.com/dotnet/roslyn/issues/46342")] public void LambdaNullReturn_03() { var source = @"#nullable enable using System; using System.Threading.Tasks; class Program { static void F<T>(Func<Task<T>> f) { } static void M1<T>(T? t) where T : class { F(async () => { await Task.Yield(); if (t is null) return null; return t; }); } static void M2<T>(T? t) where T : class? { F(async () => { await Task.Yield(); if (t is null) return null; return t; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] public void LambdaNullReturn_04() { var source = @"#nullable enable using System; class Program { static void F<T>(Func<T> f) { } static void M1<T>(bool b, T t) where T : class { F(() => { if (b) return default; return t; }); } static void M2<T>(bool b, T t) where T : class? { F(() => { if (b) return default; return t; }); } }"; var comp = CreateCompilation(source); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var invocationNode = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("void Program.F<T?>(System.Func<T?> f)", model.GetSymbolInfo(invocationNode).Symbol.ToTestDisplayString()); var invocationNode2 = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Last(); Assert.Equal("void Program.F<T?>(System.Func<T?> f)", model.GetSymbolInfo(invocationNode2).Symbol.ToTestDisplayString()); comp.VerifyEmitDiagnostics(); } [Fact] public void LambdaNullReturn_05() { var source = @"#nullable enable using System; class Program { static void F<T>(Func<T> f) { } static void M1<T>(bool b, T t) where T : class { F(() => { if (b) return default(T); return t; }); } static void M2<T>(bool b, T t) where T : class? { F(() => { if (b) return default(T); return t; }); } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(45862, "https://github.com/dotnet/roslyn/issues/45862")] public void Issue_45862() { var source = @"#nullable enable class C { void M() { _ = 0 switch { 0 = _ = null, }; } }"; var comp = CreateCompilation(source, parseOptions: TestOptions.Regular9); comp.VerifyEmitDiagnostics( // (9,15): error CS1003: Syntax error, '=>' expected // 0 = Diagnostic(ErrorCode.ERR_SyntaxError, "=").WithArguments("=>", "=").WithLocation(9, 15), // (9,15): error CS1525: Invalid expression term '=' // 0 = Diagnostic(ErrorCode.ERR_InvalidExprTerm, "=").WithArguments("=").WithLocation(9, 15), // (10,13): error CS8183: Cannot infer the type of implicitly-typed discard. // _ = null, Diagnostic(ErrorCode.ERR_DiscardTypeInferenceFailed, "_").WithLocation(10, 13)); } [Fact, WorkItem(48126, "https://github.com/dotnet/roslyn/issues/48126")] public void EnforcedInMethodBody_MaybeNullWhen_Issue_48126() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C { static bool NullWhenFalseA(bool a, [MaybeNullWhen(false)] out string s1) { s1 = null; return a; } static bool NullWhenFalseNotA(bool a, [MaybeNullWhen(false)] out string s1) { s1 = null; return !a; } static bool NullWhenTrueA(bool a, [MaybeNullWhen(true)] out string s1) { s1 = null; return a; } static bool NullWhenTrueNotA(bool a, [MaybeNullWhen(true)] out string s1) { s1 = null; return !a; } }"; var comp = CreateCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyEmitDiagnostics(); } [Fact, WorkItem(48126, "https://github.com/dotnet/roslyn/issues/48126")] public void EnforcedInMethodBody_MaybeNullWhen_Issue_48126_2() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C { static bool M1([MaybeNullWhen(false)] out string s1) { const bool b = true; s1 = null; return b; // 1 } static bool M2([MaybeNullWhen(false)] out string s1) { s1 = null; return (bool)true; // 2 } }"; var comp = CreateCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyEmitDiagnostics( // (12,9): warning CS8762: Parameter 's1' must have a non-null value when exiting with 'true'. // return b; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return b;").WithArguments("s1", "true").WithLocation(12, 9), // (18,9): warning CS8762: Parameter 's1' must have a non-null value when exiting with 'true'. // return (bool)true; // 2 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return (bool)true;").WithArguments("s1", "true").WithLocation(18, 9) ); } [Fact, WorkItem(48126, "https://github.com/dotnet/roslyn/issues/48126")] public void EnforcedInMethodBody_MaybeNullWhen_Issue_48126_3() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C { static bool M1([MaybeNullWhen(false)] out string s1) { const bool b = true; s1 = null; return b; // 1 } static bool M2([MaybeNullWhen(false)] out string s1) { const bool b = true; s1 = null; return b && true; // 2 } static bool M3([MaybeNullWhen(false)] out string s1) { const bool b = false; s1 = null; return b; } }"; var comp = CreateCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyEmitDiagnostics( // (12,9): warning CS8762: Parameter 's1' must have a non-null value when exiting with 'true'. // return b; // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return b;").WithArguments("s1", "true").WithLocation(12, 9), // (19,9): warning CS8762: Parameter 's1' must have a non-null value when exiting with 'true'. // return b && true; // 2 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return b && true;").WithArguments("s1", "true").WithLocation(19, 9) ); } [Fact, WorkItem(48126, "https://github.com/dotnet/roslyn/issues/48126")] public void EnforcedInMethodBody_MaybeNullWhen_Issue_48126_4() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable class C { static bool M1([MaybeNullWhen(false)] out string s1) { return M1(out s1); } static bool M2([MaybeNullWhen(false)] out string s1) { return !M1(out s1); // 1 } static bool M3([MaybeNullWhen(true)] out string s1) { return !M1(out s1); } }"; var comp = CreateCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyEmitDiagnostics( // (15,9): warning CS8762: Parameter 's1' must have a non-null value when exiting with 'true'. // return !M1(out s1); // 1 Diagnostic(ErrorCode.WRN_ParameterConditionallyDisallowsNull, "return !M1(out s1);").WithArguments("s1", "true").WithLocation(15, 9) ); } [Fact, WorkItem(48126, "https://github.com/dotnet/roslyn/issues/48126")] public void EnforcedInMethodBody_MaybeNullWhen_Issue_48126_5() { var source = @" using System.Diagnostics.CodeAnalysis; #nullable enable internal static class Program { public static bool M1([MaybeNullWhen(true)] out string s) { s = null; return HasAnnotation(out _); } public static bool M2([MaybeNullWhen(true)] out string s) { s = null; return NoAnnotations(); } private static bool HasAnnotation([MaybeNullWhen(true)] out string s) { s = null; return true; } private static bool NoAnnotations() => true; }"; var comp = CreateCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyEmitDiagnostics(); } [Fact] [WorkItem(47221, "https://github.com/dotnet/roslyn/issues/47221")] public void PropertyAccessorWithNullableContextAttribute_01() { var source0 = @"#nullable enable public class A { public object? this[object x, object? y] => null; public static A F(object x) => new A(); public static A F(object x, object? y) => new A(); }"; var comp = CreateCompilation(source0); var ref0 = comp.EmitToImageReference(); var source1 = @"#nullable enable class B { static void F(object x, object? y) { var a = A.F(x, y); var b = a[x, y]; b.ToString(); // 1 } }"; comp = CreateCompilation(source1, references: new[] { ref0 }); comp.VerifyEmitDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // b.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "b").WithLocation(8, 9)); } [Fact] [WorkItem(47221, "https://github.com/dotnet/roslyn/issues/47221")] public void PropertyAccessorWithNullableContextAttribute_02() { var source0 = @"#nullable enable public class A { public object this[object? x, object y] => new object(); public static A? F0; public static A? F1; public static A? F2; public static A? F3; public static A? F4; }"; var comp = CreateCompilation(source0); var ref0 = comp.EmitToImageReference(); var source1 = @"#nullable enable class B { static void F(object x, object? y) { var a = new A(); var b = a[x, y]; // 1 b.ToString(); } }"; comp = CreateCompilation(source1, references: new[] { ref0 }); comp.VerifyEmitDiagnostics( // (7,22): warning CS8604: Possible null reference argument for parameter 'y' in 'object A.this[object? x, object y]'. // var b = a[x, y]; // 1 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "y").WithArguments("y", "object A.this[object? x, object y]").WithLocation(7, 22)); } [Fact] [WorkItem(49754, "https://github.com/dotnet/roslyn/issues/49754")] public void Issue49754() { var source0 = @" using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; #nullable enable namespace Repro { public class Test { public void Test(IEnumerable<(int test, int score)> scores) { scores.Select(s => (s.test, s.score switch { })); } } }" ; var comp = CreateCompilation(source0); comp.VerifyEmitDiagnostics( // (12,15): error CS0542: 'Test': member names cannot be the same as their enclosing type // public void Test(IEnumerable<(int test, int score)> scores) Diagnostic(ErrorCode.ERR_MemberNameSameAsType, "Test").WithArguments("Test").WithLocation(12, 15), // (14,11): error CS0411: The type arguments for method 'Enumerable.Select<TSource, TResult>(IEnumerable<TSource>, Func<TSource, TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // scores.Select(s => (s.test, s.score switch Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Select").WithArguments("System.Linq.Enumerable.Select<TSource, TResult>(System.Collections.Generic.IEnumerable<TSource>, System.Func<TSource, TResult>)").WithLocation(14, 11) ); } [Fact] [WorkItem(48992, "https://github.com/dotnet/roslyn/issues/48992")] public void TryGetValue_GenericMethod() { var source = @"#nullable enable using System.Diagnostics.CodeAnalysis; class Collection { public bool TryGetValue<T>(object key, [MaybeNullWhen(false)] out T value) { value = default; return false; } } class Program { static string GetValue1(Collection c, object key) { // out string if (c.TryGetValue(key, out string s1)) // 1 { return s1; } // out string? if (c.TryGetValue(key, out string? s2)) { return s2; // 2 } // out string?, explicit type argument if (c.TryGetValue<string>(key, out string? s3)) { return s3; } // out var, explicit type argument if (c.TryGetValue<string>(key, out var s4)) { return s4; } return string.Empty; } static T GetValue2<T>(Collection c, object key) { // out T if (c.TryGetValue(key, out T s1)) // 3 { return s1; } // out T? if (c.TryGetValue(key, out T? s2)) { return s2; // 4 } // out T?, explicit type argument if (c.TryGetValue<T>(key, out T? s3)) { return s3; } // out var, explicit type argument if (c.TryGetValue<T>(key, out var s4)) { return s4; } return default!; } }"; var comp = CreateCompilation(new[] { source, MaybeNullWhenAttributeDefinition }); comp.VerifyEmitDiagnostics( // (16,36): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (c.TryGetValue(key, out string s1)) // 1 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "string s1").WithLocation(16, 36), // (23,20): warning CS8603: Possible null reference return. // return s2; // 2 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s2").WithLocation(23, 20), // (40,36): warning CS8600: Converting null literal or possible null value to non-nullable type. // if (c.TryGetValue(key, out T s1)) // 3 Diagnostic(ErrorCode.WRN_ConvertingNullableToNonNullable, "T s1").WithLocation(40, 36), // (47,20): warning CS8603: Possible null reference return. // return s2; // 4 Diagnostic(ErrorCode.WRN_NullReferenceReturn, "s2").WithLocation(47, 20)); } [Theory, WorkItem(41368, "https://github.com/dotnet/roslyn/issues/41368")] [CombinatorialData] public void TypeSubstitution(bool useCompilationReference) { var sourceA = @" #nullable enable public class C { public static TQ? FTQ<TQ>(TQ? t) => throw null!; // T-question public static T FT<T>(T t) => throw null!; // plain-T public static TC FTC<TC>(TC t) where TC : class => throw null!; // T-class #nullable disable public static TO FTO<TO>(TO t) => throw null!; // T-oblivious public static TCO FTCO<TCO>(TCO t) where TCO : class => throw null!; // T-class-oblivious }"; var comp = CreateCompilation(sourceA); comp.VerifyDiagnostics(); var refA = AsReference(comp, useCompilationReference); var sourceB2 = @" #nullable enable class CTQ<TQ> { void M() { var x0 = C.FTQ<TQ?>(default); x0.ToString(); // 1 var x1 = C.FT<TQ?>(default); x1.ToString(); // 2 C.FTC<TQ?>(default).ToString(); // illegal var x2 = C.FTO<TQ?>(default); x2.ToString(); // 3 var x3 = C.FTCO<TQ?>(default); // illegal x3.ToString(); } } class CT<T> { void M() { var x0 = C.FTQ<T>(default); x0.ToString(); // 4 var x1 = C.FT<T>(default); // 5 x1.ToString(); // 6 C.FTC<T>(default).ToString(); // illegal var x2 = C.FTO<T>(default); // 7 x2.ToString(); // 8 C.FTCO<T>(default).ToString(); // illegal } } class CTC<TC> where TC : class { void M() { var x0 = C.FTQ<TC>(default); x0.ToString(); // 9 var x1 = C.FT<TC>(default); // 10 x1.ToString(); var x2 = C.FTC<TC>(default); // 11 x2.ToString(); var x3 = C.FTO<TC>(default); // 12 x3.ToString(); var x4 = C.FTCO<TC>(default); // 13 x4.ToString(); } } class CTO<TO> { void M() { #nullable disable C.FTQ<TO> #nullable enable (default).ToString(); #nullable disable C.FT<TO> #nullable enable (default).ToString(); #nullable disable C.FTC<TO> // illegal #nullable enable (default).ToString(); #nullable disable C.FTO<TO> #nullable enable (default).ToString(); #nullable disable C.FTCO<TO> // illegal #nullable enable (default).ToString(); } } class CTCO<TCO> where TCO : class { void M() { var x0 = #nullable disable C.FTQ<TCO> #nullable enable (default); x0.ToString(); // 14 #nullable disable C.FT<TCO> #nullable enable (default).ToString(); var x1 = #nullable disable C.FTC<TCO> #nullable enable (default); // 15 x1.ToString(); #nullable disable C.FTO<TCO> #nullable enable (default).ToString(); #nullable disable C.FTCO<TCO> #nullable enable (default).ToString(); } } "; comp = CreateCompilation(new[] { sourceB2 }, references: new[] { refA }); comp.VerifyDiagnostics( // (8,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(8, 9), // (11,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 2 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(11, 9), // (13,11): error CS0452: The type 'TQ' must be a reference type in order to use it as parameter 'TC' in the generic type or method 'C.FTC<TC>(TC)' // C.FTC<TQ?>(default).ToString(); // illegal Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "FTC<TQ?>").WithArguments("C.FTC<TC>(TC)", "TC", "TQ").WithLocation(13, 11), // (16,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 3 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(16, 9), // (18,20): error CS0452: The type 'TQ' must be a reference type in order to use it as parameter 'TCO' in the generic type or method 'C.FTCO<TCO>(TCO)' // var x3 = C.FTCO<TQ?>(default); // illegal Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "FTCO<TQ?>").WithArguments("C.FTCO<TCO>(TCO)", "TCO", "TQ").WithLocation(18, 20), // (28,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); // 4 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(28, 9), // (30,26): warning CS8604: Possible null reference argument for parameter 't' in 'T C.FT<T>(T t)'. // var x1 = C.FT<T>(default); // 5 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "T C.FT<T>(T t)").WithLocation(30, 26), // (31,9): warning CS8602: Dereference of a possibly null reference. // x1.ToString(); // 6 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x1").WithLocation(31, 9), // (33,11): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'TC' in the generic type or method 'C.FTC<TC>(TC)' // C.FTC<T>(default).ToString(); // illegal Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "FTC<T>").WithArguments("C.FTC<TC>(TC)", "TC", "T").WithLocation(33, 11), // (35,27): warning CS8604: Possible null reference argument for parameter 't' in 'T C.FTO<T>(T t)'. // var x2 = C.FTO<T>(default); // 7 Diagnostic(ErrorCode.WRN_NullReferenceArgument, "default").WithArguments("t", "T C.FTO<T>(T t)").WithLocation(35, 27), // (36,9): warning CS8602: Dereference of a possibly null reference. // x2.ToString(); // 8 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x2").WithLocation(36, 9), // (38,11): error CS0452: The type 'T' must be a reference type in order to use it as parameter 'TCO' in the generic type or method 'C.FTCO<TCO>(TCO)' // C.FTCO<T>(default).ToString(); // illegal Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "FTCO<T>").WithArguments("C.FTCO<TCO>(TCO)", "TCO", "T").WithLocation(38, 11), // (46,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); // 9 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(46, 9), // (48,27): warning CS8625: Cannot convert null literal to non-nullable reference type. // var x1 = C.FT<TC>(default); // 10 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(48, 27), // (51,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // var x2 = C.FTC<TC>(default); // 11 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(51, 28), // (54,28): warning CS8625: Cannot convert null literal to non-nullable reference type. // var x3 = C.FTO<TC>(default); // 12 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(54, 28), // (57,29): warning CS8625: Cannot convert null literal to non-nullable reference type. // var x4 = C.FTCO<TC>(default); // 13 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(57, 29), // (76,11): error CS0452: The type 'TO' must be a reference type in order to use it as parameter 'TC' in the generic type or method 'C.FTC<TC>(TC)' // C.FTC<TO> // illegal Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "FTC<TO>").WithArguments("C.FTC<TC>(TC)", "TC", "TO").WithLocation(76, 11), // (86,11): error CS0452: The type 'TO' must be a reference type in order to use it as parameter 'TCO' in the generic type or method 'C.FTCO<TCO>(TCO)' // C.FTCO<TO> // illegal Diagnostic(ErrorCode.ERR_RefConstraintNotSatisfied, "FTCO<TO>").WithArguments("C.FTCO<TCO>(TCO)", "TCO", "TO").WithLocation(86, 11), // (100,9): warning CS8602: Dereference of a possibly null reference. // x0.ToString(); // 14 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "x0").WithLocation(100, 9), // (111,14): warning CS8625: Cannot convert null literal to non-nullable reference type. // (default); // 15 Diagnostic(ErrorCode.WRN_NullAsNonNullable, "default").WithLocation(111, 14) ); } [Fact] public void DefaultParameterValue() { var src = @" #nullable enable C<string?> one = new(); C<string?> other = new(); _ = one.SequenceEqual(other); _ = one.SequenceEqual(other, comparer: null); public interface IIn<in t> { } static class Extension { public static bool SequenceEqual<TDerived, TBase>(this C<TBase> one, C<TDerived> other, IIn<TBase>? comparer = null) where TDerived : TBase => throw null!; } public class C<T> { } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyDiagnostics(); } [Fact] public void IgnoredNullability_CopyTypeModifiers_ImplicitContainingType() { var src = @" #nullable enable var c = new C<string>(); c.Property.Property2 = null; public interface I<T> { T Property { get; set; } } public class C<U> : I<C<U>.Nested> { public Nested Property { get; set; } // implicitly means C<U>.Nested public class Nested { public U Property2 { get; set; } } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (5,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.Property.Property2 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 24), // (13,19): warning CS8618: Non-nullable property 'Property' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public Nested Property { get; set; } // implicitly means C<U>.Nested Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Property").WithArguments("property", "Property").WithLocation(13, 19), // (16,18): warning CS8618: Non-nullable property 'Property2' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public U Property2 { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Property2").WithArguments("property", "Property2").WithLocation(16, 18) ); } [Fact] public void IgnoredNullability_CopyTypeModifiers_ExplicitContainingType() { var src = @" #nullable enable var c = new C<string>(); c.Property.Property2 = null; public interface I<T> { public T Property { get; set; } } public class C<U> : I<C<U>.Nested> { public C<U>.Nested Property { get; set; } public class Nested { public U Property2 { get; set; } } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe); comp.VerifyDiagnostics( // (5,24): warning CS8625: Cannot convert null literal to non-nullable reference type. // c.Property.Property2 = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(5, 24), // (13,24): warning CS8618: Non-nullable property 'Property' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public C<U>.Nested Property { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Property").WithArguments("property", "Property").WithLocation(13, 24), // (16,18): warning CS8618: Non-nullable property 'Property2' must contain a non-null value when exiting constructor. Consider declaring the property as nullable. // public U Property2 { get; set; } Diagnostic(ErrorCode.WRN_UninitializedNonNullableField, "Property2").WithArguments("property", "Property2").WithLocation(16, 18) ); } [Fact] public void IgnoredNullability_ConditionalWithThis() { var src = @" #nullable enable internal class C<T> { public C<T> M(bool b) { if (b) return b ? this : new C<T>(); else return b ? new C<T>() : this; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void IgnoredNullability_ImplicitlyTypedArrayWithThis() { var src = @" #nullable enable internal class C<T> { public C<T>[] M(bool b) { if (b) return new[] { this, new C<T>() }; else return new[] { new C<T>(), this }; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact, WorkItem(49722, "https://github.com/dotnet/roslyn/issues/49722")] public void IgnoredNullability_ImplicitlyTypedArrayWithThis_DifferentNullability() { var src = @" #nullable enable internal class C<T> { public void M(bool b) { _ = b ? this : new C<T?>(); } } "; var comp = CreateCompilation(src); // missing warning comp.VerifyDiagnostics(); } [Fact] public void IgnoredNullability_StaticField() { var src = @" #nullable enable public class C<T> { public static int field; public void M() { var x = field; var y = C<T>.field; #nullable disable var z = C<T>.field; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var declarators = tree.GetRoot().DescendantNodes().OfType<EqualsValueClauseSyntax>().ToArray(); Assert.Equal("field", declarators[0].Value.ToString()); var field1 = model.GetSymbolInfo(declarators[0].Value).Symbol; Assert.Equal("C<T>.field", declarators[1].Value.ToString()); var field2 = model.GetSymbolInfo(declarators[1].Value).Symbol; Assert.Equal("C<T>.field", declarators[2].Value.ToString()); var field3 = model.GetSymbolInfo(declarators[2].Value).Symbol; Assert.True(field2.Equals(field3, SymbolEqualityComparer.Default)); Assert.False(field2.Equals(field3, SymbolEqualityComparer.IncludeNullability)); Assert.True(field3.Equals(field2, SymbolEqualityComparer.Default)); Assert.False(field3.Equals(field2, SymbolEqualityComparer.IncludeNullability)); Assert.Equal(field2.GetHashCode(), field3.GetHashCode()); Assert.True(field1.Equals(field2, SymbolEqualityComparer.Default)); Assert.False(field1.Equals(field2, SymbolEqualityComparer.IncludeNullability)); Assert.True(field2.Equals(field1, SymbolEqualityComparer.Default)); Assert.False(field2.Equals(field1, SymbolEqualityComparer.IncludeNullability)); Assert.Equal(field1.GetHashCode(), field2.GetHashCode()); Assert.True(field1.Equals(field3, SymbolEqualityComparer.Default)); Assert.True(field1.Equals(field3, SymbolEqualityComparer.IncludeNullability)); Assert.True(field3.Equals(field1, SymbolEqualityComparer.Default)); Assert.True(field3.Equals(field1, SymbolEqualityComparer.IncludeNullability)); Assert.Equal(field1.GetHashCode(), field3.GetHashCode()); } [Fact, WorkItem(49798, "https://github.com/dotnet/roslyn/issues/49798")] public void IgnoredNullability_MethodSymbol() { var src = @" #nullable enable public class C { public void M<T>(out T x) { M<T>(out x); #nullable disable M<T>(out x); } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var method1 = model.GetDeclaredSymbol(tree.GetRoot().DescendantNodes().OfType<MethodDeclarationSyntax>().Single()); Assert.True(method1.IsDefinition); var invocations = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().ToArray(); Assert.Equal("M<T>(out x)", invocations[0].ToString()); var method2 = model.GetSymbolInfo(invocations[0]).Symbol; Assert.False(method2.IsDefinition); Assert.Equal("M<T>(out x)", invocations[1].ToString()); var method3 = model.GetSymbolInfo(invocations[1]).Symbol; Assert.True(method3.IsDefinition); // definitions and substituted symbols should be equal when ignoring nullability // Tracked by issue https://github.com/dotnet/roslyn/issues/49798 Assert.False(method2.Equals(method3, SymbolEqualityComparer.Default)); Assert.False(method2.Equals(method3, SymbolEqualityComparer.IncludeNullability)); Assert.False(method3.Equals(method2, SymbolEqualityComparer.Default)); Assert.False(method3.Equals(method2, SymbolEqualityComparer.IncludeNullability)); //Assert.Equal(method2.GetHashCode(), method3.GetHashCode()); Assert.False(method1.Equals(method2, SymbolEqualityComparer.Default)); Assert.False(method1.Equals(method2, SymbolEqualityComparer.IncludeNullability)); Assert.False(method2.Equals(method1, SymbolEqualityComparer.Default)); Assert.False(method2.Equals(method1, SymbolEqualityComparer.IncludeNullability)); //Assert.Equal(method1.GetHashCode(), method2.GetHashCode()); Assert.True(method1.Equals(method3, SymbolEqualityComparer.Default)); Assert.True(method1.Equals(method3, SymbolEqualityComparer.IncludeNullability)); Assert.True(method3.Equals(method1, SymbolEqualityComparer.Default)); Assert.True(method3.Equals(method1, SymbolEqualityComparer.IncludeNullability)); Assert.Equal(method1.GetHashCode(), method3.GetHashCode()); } [Fact] public void IgnoredNullability_OverrideReturnType_WithoutConstraint() { var src = @" #nullable enable public class C { public virtual T M<T>() => throw null!; } public class D : C { public override T? M<T>() where T : default => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? M<T>() where T : class => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M").WithLocation(10, 24) ); } [Fact] public void IgnoredNullability_OverrideReturnType_WithClassConstraint() { var src = @" #nullable enable public class C { public virtual T M<T>() where T : class => throw null!; } public class D : C { public override T? M<T>() where T : class => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,24): warning CS8764: Nullability of return type doesn't match overridden member (possibly because of nullability attributes). // public override T? M<T>() where T : class => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnOverride, "M").WithLocation(10, 24) ); } [Fact, WorkItem(49131, "https://github.com/dotnet/roslyn/issues/49131")] public void IgnoredNullability_OverrideOutParameterType_WithoutConstraint() { var src = @" #nullable enable public class C { public virtual void M<T>(out T t) => throw null!; } public class D : C { public override void M<T>(out T? t) where T : default => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void M<T>(out T? t) where T : default => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("t").WithLocation(10, 26) ); } [Fact, WorkItem(49131, "https://github.com/dotnet/roslyn/issues/49131")] public void IgnoredNullability_OverrideOutParameterType_WithClassConstraint() { var src = @" #nullable enable public class C { public virtual void M<T>(out T t) where T : class => throw null!; } public class D : C { public override void M<T>(out T? t) where T : class => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,26): warning CS8765: Nullability of type of parameter 't' doesn't match overridden member (possibly because of nullability attributes). // public override void M<T>(out T? t) where T : class => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInParameterTypeOnOverride, "M").WithArguments("t").WithLocation(10, 26) ); } [Fact] public void IgnoredNullability_ImplementationReturnType_WithoutConstraint() { var src = @" #nullable enable public interface I { T M<T>(); } public class D : I { public T? M<T>() => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,15): warning CS8766: Nullability of reference types in return type of 'T? D.M<T>()' doesn't match implicitly implemented member 'T I.M<T>()' (possibly because of nullability attributes). // public T? M<T>() => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M").WithArguments("T? D.M<T>()", "T I.M<T>()").WithLocation(10, 15) ); } [Fact] public void IgnoredNullability_ImplementationReturnType_WithClassConstraint() { var src = @" #nullable enable public interface I { T M<T>() where T : class; } public class D : I { public T? M<T>() where T : class => throw null!; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,15): warning CS8766: Nullability of reference types in return type of 'T? D.M<T>()' doesn't match implicitly implemented member 'T I.M<T>()' (possibly because of nullability attributes). // public T? M<T>() where T : class => throw null!; Diagnostic(ErrorCode.WRN_TopLevelNullabilityMismatchInReturnTypeOnImplicitImplementation, "M").WithArguments("T? D.M<T>()", "T I.M<T>()").WithLocation(10, 15) ); } [Fact, WorkItem(49071, "https://github.com/dotnet/roslyn/issues/49071")] public void IgnoredNullability_PartialMethodReturnType_WithoutConstraint() { var src = @" #nullable enable partial class C { public partial T F<T>(); } partial class C { public partial T? F<T>() => default; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,23): warning CS8819: Nullability of reference types in return type doesn't match partial method declaration. // public partial T? F<T>() => default; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial, "F").WithLocation(10, 23) ); } [Fact, WorkItem(49071, "https://github.com/dotnet/roslyn/issues/49071")] public void IgnoredNullability_PartialMethodReturnType_WithClassConstraint() { var src = @" #nullable enable partial class C { public partial T F<T>() where T : class; } partial class C { public partial T? F<T>() where T : class => default; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (10,23): warning CS8819: Nullability of reference types in return type doesn't match partial method declaration. // public partial T? F<T>() where T : class => default; Diagnostic(ErrorCode.WRN_NullabilityMismatchInReturnTypeOnPartial, "F").WithLocation(10, 23) ); } [Fact] [WorkItem(50097, "https://github.com/dotnet/roslyn/issues/50097")] public void Issue50097() { var src = @" using System; public class C { static void Main() { } public record AuditedItem<T>(T Value, string ConcurrencyToken, DateTimeOffset LastChange) where T : class; public record FieldItem(object? Value, string ConcurrencyToken, DateTimeOffset LastChange) : AuditedItem<object?>(Value, ConcurrencyToken, LastChange); } namespace System.Runtime.CompilerServices { public static class IsExternalInit { } } "; var comp = CreateCompilation(src, options: TestOptions.DebugExe.WithNullableContextOptions(NullableContextOptions.Enable)); var diagnostics = comp.GetEmitDiagnostics(); diagnostics.Verify( // (13,19): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C.AuditedItem<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // public record FieldItem(object? Value, string ConcurrencyToken, DateTimeOffset LastChange) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "FieldItem").WithArguments("C.AuditedItem<T>", "T", "object?").WithLocation(13, 19), // (13,19): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C.AuditedItem<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // public record FieldItem(object? Value, string ConcurrencyToken, DateTimeOffset LastChange) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "FieldItem").WithArguments("C.AuditedItem<T>", "T", "object?").WithLocation(13, 19), // (13,19): warning CS8634: The type 'object?' cannot be used as type parameter 'T' in the generic type or method 'C.AuditedItem<T>'. Nullability of type argument 'object?' doesn't match 'class' constraint. // public record FieldItem(object? Value, string ConcurrencyToken, DateTimeOffset LastChange) Diagnostic(ErrorCode.WRN_NullabilityMismatchInTypeParameterReferenceTypeConstraint, "FieldItem").WithArguments("C.AuditedItem<T>", "T", "object?").WithLocation(13, 19) ); var reportedDiagnostics = new HashSet<Diagnostic>(); reportedDiagnostics.AddAll(diagnostics); Assert.Equal(1, reportedDiagnostics.Count); } [Fact] public void AmbigMember_DynamicDifferences() { var src = @" interface I<T> { T Item { get; } } interface I2<T> : I<T> { } interface I3 : I<dynamic>, I2<object> { } public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,11): error CS8779: 'I<object>' is already listed in the interface list on type 'I3' as 'I<dynamic>'. // interface I3 : I<dynamic>, I2<object> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithDifferencesInBaseList, "I3").WithArguments("I<object>", "I<dynamic>", "I3").WithLocation(6, 11), // (6,16): error CS1966: 'I3': cannot implement a dynamic interface 'I<dynamic>' // interface I3 : I<dynamic>, I2<object> { } Diagnostic(ErrorCode.ERR_DeriveFromConstructedDynamic, "I<dynamic>").WithArguments("I3", "I<dynamic>").WithLocation(6, 16), // (12,15): error CS0229: Ambiguity between 'I<dynamic>.Item' and 'I<object>.Item' // _ = i.Item; Diagnostic(ErrorCode.ERR_AmbigMember, "Item").WithArguments("I<dynamic>.Item", "I<object>.Item").WithLocation(12, 15) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<dynamic>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<dynamic>", "I2<object>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_TupleDifferences() { var src = @" interface I<T> { T Item { get; } } interface I2<T> : I<T> { } interface I3 : I<(int a, int b)>, I2<(int notA, int notB)> { } public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (6,11): error CS8140: 'I<(int notA, int notB)>' is already listed in the interface list on type 'I3' with different tuple element names, as 'I<(int a, int b)>'. // interface I3 : I<(int a, int b)>, I2<(int notA, int notB)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "I3").WithArguments("I<(int notA, int notB)>", "I<(int a, int b)>", "I3").WithLocation(6, 11), // (12,15): error CS0229: Ambiguity between 'I<(int a, int b)>.Item' and 'I<(int notA, int notB)>.Item' // _ = i.Item; Diagnostic(ErrorCode.ERR_AmbigMember, "Item").WithArguments("I<(int a, int b)>.Item", "I<(int notA, int notB)>.Item").WithLocation(12, 15) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<(int a, int b)>", "I2<(int notA, int notB)>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<(int a, int b)>", "I2<(int notA, int notB)>", "I<(int notA, int notB)>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_TupleAndNullabilityDifferences() { var src = @" #nullable disable interface I<T> { T Item { get; } } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I<(object a, object b)>, I2<(object notA, object notB)> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,11): error CS8140: 'I<(object notA, object notB)>' is already listed in the interface list on type 'I3' with different tuple element names, as 'I<(object a, object b)>'. // interface I3 : I<(object a, object b)>, I2<(object notA, object notB)> { } Diagnostic(ErrorCode.ERR_DuplicateInterfaceWithTupleNamesInBaseList, "I3").WithArguments("I<(object notA, object notB)>", "I<(object a, object b)>", "I3").WithLocation(9, 11), // (16,15): error CS0229: Ambiguity between 'I<(object a, object b)>.Item' and 'I<(object notA, object notB)>.Item' // _ = i.Item; Diagnostic(ErrorCode.ERR_AmbigMember, "Item").WithArguments("I<(object a, object b)>.Item", "I<(object notA, object notB)>.Item").WithLocation(16, 15) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<(object a, object b)>", "I2<(object notA, object notB)>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<(object a, object b)>", "I2<(object notA, object notB)>", "I<(object notA, object notB)>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_NoDifference() { var src = @" interface I<T> { T Item { get; } } interface I2<T> : I<T> { } interface I3 : I<object>, I2<object> { } public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I2<object>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithoutConstraint() { var src = @" #nullable disable interface I<T> { T Item { get; set; } } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I2<object>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("i.Item", item.ToString()); Assert.Equal("object", ((IPropertySymbol)model.GetSymbolInfo(item).Symbol).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); var found = model.LookupSymbols(item.SpanStart, i3.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithoutConstraint_Indexer() { var src = @" #nullable disable interface I<T> { T this[int i] { get; set; } } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i[0]; i[0] = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().First(); Assert.Equal("i[0]", item.ToString()); Assert.Equal("object", ((IPropertySymbol)model.GetSymbolInfo(item).Symbol).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithoutConstraint_Event() { var src = @" using System; #nullable disable interface I<T> { event Func<T, T> Event; } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i, Func<object, object> f1, Func<object?, object?> f2) { i.Event += f1; i.Event += f2; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithoutConstraint_Nested() { var src = @" #nullable disable interface I<T> { interface Inner { static T Item { get; set; } } } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M() { _ = I3.Inner.Item; I3.Inner.Item = null; } } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithoutConstraint_Method() { var src = @" #nullable disable interface I<T> { ref T Get(); } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Get(); i.Get() = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("i.Get()", item.ToString()); Assert.Equal("object", ((IMethodSymbol)model.GetSymbolInfo(item).Symbol).ReturnType.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithoutConstraint_ReverseOrder() { var src = @" #nullable disable interface I<T> { T Item { get; set; } } #nullable enable interface I2<T> : I<T> { } #nullable disable interface I3 : I2<object>, I<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I2<object>", "I<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I2<object>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.Equal("i.Item", item.ToString()); Assert.Equal("object", ((IPropertySymbol)model.GetSymbolInfo(item).Symbol).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); var found = model.LookupSymbols(item.SpanStart, i3.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<object>", "I2<object>", "I<object!>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.True(model.LookupNames(item.SpanStart, i3.GetPublicSymbol()).Contains("Item")); var found = model.LookupSymbols(item.SpanStart, i3.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_OnTypeParameter() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M<T>(T i) where T : I3 { _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<object>", "I2<object>", "I<object!>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); Assert.True(model.LookupNames(item.SpanStart, i3.GetPublicSymbol()).Contains("Item")); var t = ((MethodSymbol)comp.GetMember("C.M")).TypeParameters.Single(); var found = model.LookupSymbols(item.SpanStart, t.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_OnTypeParameterImplementingBothInterfaces() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } public class C { #nullable disable void M<T>(T i) where T : I<object>, I2<object> { #nullable enable _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); var t = ((MethodSymbol)comp.GetMember("C.M")).TypeParameters.Single(); Assert.True(model.LookupNames(item.SpanStart, t.GetPublicSymbol()).Contains("Item")); var found = model.LookupSymbols(item.SpanStart, t.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_Indexer() { var src = @" #nullable disable interface I<T> where T : class { T this[int i] { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i[0]; i[0] = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().First(); Assert.Equal("i[0]", item.ToString()); Assert.Equal("object", ((IPropertySymbol)model.GetSymbolInfo(item).Symbol).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_Event() { var src = @" using System; #nullable disable interface I<T> where T : class { event Func<T, T> Event; } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i, Func<object, object> f1, Func<object?, object?> f2) { i.Event += f1; i.Event += f2; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_Nested() { var src = @" #nullable disable interface I<T> where T : class { interface Inner { static T Item { get; set; } } } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M() { _ = I3.Inner.Item; I3.Inner.Item = null; } } "; var comp = CreateCompilation(src, targetFramework: TargetFramework.NetCoreApp); comp.VerifyDiagnostics(); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_Method() { var src = @" #nullable disable interface I<T> where T : class { ref T Get(); } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I<object>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Get(); i.Get() = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().First(); Assert.Equal("i.Get()", item.ToString()); Assert.Equal("object", ((IMethodSymbol)model.GetSymbolInfo(item).Symbol).ReturnType.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); var i3 = comp.GetTypeByMetadataName("I3"); Assert.True(model.LookupNames(item.SpanStart, i3.GetPublicSymbol()).Contains("Get")); var found = model.LookupSymbols(item.SpanStart, i3.GetPublicSymbol()).Single(s => s.Name == "Get"); Assert.Equal("object", ((IMethodSymbol)found).ReturnType.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_ReverseOrder() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I2<object>, I<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (17,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // i.Item = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(17, 18) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I2<object>", "I<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I2<object>", "I<object!>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); var found = model.LookupSymbols(item.SpanStart, i3.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object!", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_ReverseOrder_OnTypeParameter() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } #nullable disable interface I3 : I2<object>, I<object> { } #nullable enable public class C { void M<T>(T i) where T : I3 { _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (17,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // i.Item = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(17, 18) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I2<object>", "I<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I2<object>", "I<object!>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); var t = ((MethodSymbol)comp.GetMember("C.M")).TypeParameters.Single(); var found = model.LookupSymbols(item.SpanStart, t.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object!", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNonnullableAndOblivious_WithConstraint_ReverseOrder_OnTypeParameterImplementingBothInterfaces() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; set; } } #nullable enable interface I2<T> : I<T> where T : class { } public class C { #nullable disable void M<T>(T i) where T : I2<object>, I<object> { #nullable enable _ = i.Item; i.Item = null; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (15,18): warning CS8625: Cannot convert null literal to non-nullable reference type. // i.Item = null; Diagnostic(ErrorCode.WRN_NullAsNonNullable, "null").WithLocation(15, 18) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var item = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().First(); var t = ((MethodSymbol)comp.GetMember("C.M")).TypeParameters.Single(); var found = model.LookupSymbols(item.SpanStart, t.GetPublicSymbol()).Single(s => s.Name == "Item"); Assert.Equal("object!", ((IPropertySymbol)found).Type.ToDisplayString(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNullableAndOblivious_WithConstraint() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; } } #nullable enable interface I2<T> : I<T> where T : class { } interface I3 : I<object?>, #nullable disable I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,11): warning CS8645: 'I<object>' is already listed in the interface list on type 'I3' with different nullability of reference types. // interface I3 : I<object?>, Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I3").WithArguments("I<object>", "I3").WithLocation(8, 11) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object?>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<object?>", "I2<object>", "I<object!>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNullableAndOblivious_WithoutConstraint() { var src = @" #nullable disable interface I<T> { T Item { get; } } #nullable enable interface I2<T> : I<T> { } interface I3 : I<object?>, #nullable disable I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object?>", "I2<object>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<object?>", "I2<object>", "I<object>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void AmbigMember_DifferenceBetweenNullableAndNonnullable() { var src = @" #nullable disable interface I<T> where T : class { T Item { get; } } #nullable enable interface I2<T> : I<T> where T : class { } interface I3 : I<object?>, I2<object> { } #nullable enable public class C { void M(I3 i) { _ = i.Item; } } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (8,11): warning CS8645: 'I<object>' is already listed in the interface list on type 'I3' with different nullability of reference types. // interface I3 : I<object?>, I2<object> { } Diagnostic(ErrorCode.WRN_DuplicateInterfaceWithNullabilityMismatchInBaseList, "I3").WithArguments("I<object>", "I3").WithLocation(8, 11) ); var i3 = comp.GetTypeByMetadataName("I3"); AssertEx.Equal(new string[] { "I<object?>", "I2<object!>" }, i3.Interfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); AssertEx.Equal(new string[] { "I<object?>", "I2<object!>", "I<object!>" }, i3.AllInterfaces().ToTestDisplayStrings(TypeWithAnnotations.TestDisplayFormat)); } [Fact] public void VarPatternDeclaration_TopLevel() { var src = @" #nullable enable public class C { public void M(string? x) { if (Identity(x) is var y) { y.ToString(); // 1 } if (Identity(x) is not null and var z) { z.ToString(); } } public T Identity<T>(T t) => t; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(9, 13) ); } [Fact] public void VarPatternDeclaration_Nested() { var src = @" #nullable enable public class Container<T> { public T Item { get; set; } = default!; } public class C { public void M(Container<string?> x) { if (Identity(x) is { Item: var y }) { y.ToString(); // 1 } if (Identity(x) is { Item: not null and var z }) { z.ToString(); } } public T Identity<T>(T t) => t; } "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (13,13): warning CS8602: Dereference of a possibly null reference. // y.ToString(); // 1 Diagnostic(ErrorCode.WRN_NullReferenceReceiver, "y").WithLocation(13, 13) ); } [Theory, WorkItem(52925, "https://github.com/dotnet/roslyn/issues/52925")] [WorkItem(46236, "https://github.com/dotnet/roslyn/issues/46236")] [InlineData("")] [InlineData(" where T : notnull")] [InlineData(" where T : class")] [InlineData(" where T : class?")] public void VarDeclarationWithGenericType(string constraint) { var src = $@" #nullable enable class C<T> {constraint} {{ void M(T initial, System.Func<T, T?> selector) {{ for (var current = initial; current != null; current = selector(current)) {{ }} var current2 = initial; current2 = default; for (T? current3 = initial; current3 != null; current3 = selector(current3)) {{ }} T? current4 = initial; current4 = default; }} }} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree, ignoreAccessibility: false); var declarations = tree.GetRoot().DescendantNodes().OfType<VariableDeclarationSyntax>(); foreach (var declaration in declarations) { var local = (ILocalSymbol)model.GetDeclaredSymbol(declaration.Variables.Single()); Assert.Equal("T?", local.Type.ToTestDisplayString()); Assert.Equal(CodeAnalysis.NullableAnnotation.Annotated, local.Type.NullableAnnotation); } } [Theory, WorkItem(52925, "https://github.com/dotnet/roslyn/issues/52925")] [InlineData("")] [InlineData(" where T : notnull")] [InlineData(" where T : class")] [InlineData(" where T : class?")] public void VarDeclarationWithGenericType_RefValue(string constraint) { var src = $@" #nullable enable class C<T> {constraint} {{ ref T Passthrough(ref T value) {{ ref var value2 = ref value; return ref value2; }} }} "; var comp = CreateCompilation(src); comp.VerifyDiagnostics( // (9,20): warning CS8619: Nullability of reference types in value of type 'T?' doesn't match target type 'T'. // return ref value2; Diagnostic(ErrorCode.WRN_NullabilityMismatchInAssignment, "value2").WithArguments("T?", "T").WithLocation(9, 20) ); } [Fact, WorkItem(55227, "https://github.com/dotnet/roslyn/issues/55227")] public void Issue55227_01() { var source = @" #nullable enable static class Program { public static void Main() { } public static object Test(object a) { var isNullCheck = new global::System.Func<object, object>((p) => { switch (p == null) { case var isnull: return isnull; } }); return isNullCheck(a); } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(55227, "https://github.com/dotnet/roslyn/issues/55227")] public void Issue55227_02() { var source = @" #nullable enable static class Program { public static void Main() { } public static object Test(object a) { var isNullCheck = new global::System.Func<object, object>((p) => (p == null) switch { var isnull => isnull } ); return isNullCheck(a); } } "; CreateCompilation(source).VerifyDiagnostics(); } } }
1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/CSharp/Test/Semantic/Semantics/OverloadResolutionTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class OverloadResolutionTests : OverloadResolutionTestBase { [Fact] public void TestBug12439() { // The spec has an omission; I believe we intended it to say that there is no // conversion from any old-style anonymous method expression to any expression tree // type. This is the rule the native compiler enforces; Roslyn should as well, and // we should clarify the specification. string source = @" using System; using System.Linq.Expressions; class Program { static void Main() { Goo(delegate { }); // No error; chooses the non-expression version. } static void Goo(Action a) { } static void Goo(Expression<Action> a) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [Fact] public void TestBug11961() { // This test verifies a deliberate spec violation that we have implemented // to ensure backwards compatibility. // // When doing overload resolution, we must find the best applicable method. // // When tiebreaking between two applicable candidate methods, we examine each conversion from the // argument to the corresponding parameter type to determine which method is better *in that parameter*. // If a method is *not worse* in every parameter and better in at least one, then that method // wins. Under what circumstances is one conversion better than another? // // * A conversion from the argument to a more specific parameter type is better than a conversion to a less // specific parameter type. If we have M(null) and candidates M(string) and M(object) then the conversion to // string is better because string is more specific. // // * If the argument is a lambda and the parameter types are delegate types, then the conversion to the // delegate type with the more specific return type wins. If we have M(()=>null) and we are choosing between // M(ObjectReturningDelegate) and M(StringReturningDelegate), the latter wins. // // In C# 3, these rules were never in conflict because no delegate type was ever more or less specific // than another. But in C# 4 we added delegate covariance and contravariance, and now there are delegate // types that are more specific than others. We did not correctly update the C# 4 compiler to handle this // situation. // // Unfortunately, real-world code exists that depends on this bad behavior, so we are going to preserve it. // // The essence of the bug is: the correct behavior is to do the first tiebreaker first, and the second tiebreaker // if necessary. The native compiler, and now Roslyn, does this wrong. It says "is the argument a lambda?" If so, // then it applies the second tiebreaker and ignores the first. Otherwise, it applies the first tiebreaker and // ignores the second. // // Let's take a look at some examples of where it does and does not make a difference: // // On the first call, the native compiler and Roslyn agree that overload 2 is better. (Remember, Action<T> is // contravariant, so Action<object> is more specific than Action<string>. Every action that takes an object // is also an action that takes a string, so an action that takes an object is more specific.) This is the correct // behavior. The compiler uses the first tiebreaker. // On the second call, the native compiler incorrectly believes that overload 3 is better, because it // does not correctly determine that Action<object> is more specific than Action<string> when the argument is // a lambda. The correct behavior according to the spec would be to produce an ambiguity error. (Why? // because overload 3 is more specific in its first parameter type, and less specific in its second parameter type. // And vice-versa for overload 4. No overload is not-worse in all parameters.) string source1 = @" using System; class P { static void M(Action<string> a) { Console.Write(1); } static void M(Action<object> a) { Console.Write(2); } static void M(string x, Action<string> a) { Console.Write(3); } static void M(object x, Action<object> a) { Console.Write(4); } static void M1(string x, Func<object> a) { Console.Write(5); } static void M1(object x, Func<ValueType> a) { Console.Write(6); } static void M2(Func<object> a, string x) { Console.Write(7); } static void M2(Func<ValueType> a, object x) { Console.Write(8); } static void M3(Func<object> a, Action<object> b, string x) { Console.Write(9); } static void M3(Func<ValueType> a, Action<string> b, object x) { Console.Write('A'); } static void M5(Action<object> b, string x, Func<object> a) { Console.Write('D'); } static void M5(Action<string> b, object x, Func<ValueType> a) { Console.Write('E'); } static void Main() { M(null); M((string)null, q=>{}); M(q=>{}); M1((string)null, ()=>{ throw new NotImplementedException();}); M2(()=>{ throw new NotImplementedException();}, (string)null); M3(()=>{ throw new NotImplementedException();}, q=> {}, (string)null); M5(q=> {}, (string)null, ()=>{ throw new NotImplementedException();}); } }"; CompileAndVerify(source1, expectedOutput: @"232579D"); // Now let's look at some ambiguity errors: // // On the first call, the native compiler incorrectly produces an ambiguity error. The correct behavior according // to the specification is to choose overload 2, because it is more specific. Because the argument is a lambda // we incorrectly skip the first tiebreaker entirely and go straight to the second tiebreaker. We are now in a situation // where we have two delegate types that are both void returning, and so by the second tiebreaker, neither is better. // On the second call, the native compiler correctly produces an ambiguity error. Overload 3 is better that the // overload 4 in its first parameter and worse in its second parameter, and similarly for overload 4. Since // neither overload is not-worse in all parameters, neither is the best choice. string source2 = @" using System; class P { static void M(Action<string> a) { } static void M(Action<object> a) { } static void M(string x, Action<string> a) { } static void M(object x, Action<object> a) { } static void M1(string x, Func<object> a) { Console.Write(5); } static void M1(object x, Func<ValueType> a) { Console.Write(6); } static void M4(Func<object> a, Action<object> b, Action<string> x) { Console.Write('B'); } static void M4(Func<ValueType> a, Action<string> b, Action<object> x) { Console.Write('C'); } static void M6(Action<object> b, string x, object a) { Console.Write('F'); } static void M6(Action<string> b, object x, string a) { Console.Write('G'); } static void Main() { M((string)null, null); M1((string)null, ()=>{ return 5;}); M4(()=>{ throw new NotImplementedException();}, q=> {}, q=> {}); M6(q=> {},(string)null, (string)null); } }"; CreateCompilation(source2).VerifyDiagnostics( // (18,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M(string, System.Action<string>)' and 'P.M(object, System.Action<object>)' // M((string)null, null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("P.M(string, System.Action<string>)", "P.M(object, System.Action<object>)"), // (19,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M1(string, System.Func<object>)' and 'P.M1(object, System.Func<System.ValueType>)' // M1((string)null, ()=>{ return 5;}); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("P.M1(string, System.Func<object>)", "P.M1(object, System.Func<System.ValueType>)"), // (20,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M4(System.Func<object>, System.Action<object>, System.Action<string>)' and 'P.M4(System.Func<System.ValueType>, System.Action<string>, System.Action<object>)' // M4(()=>{ throw new NotImplementedException();}, q=> {}, q=> {}); Diagnostic(ErrorCode.ERR_AmbigCall, "M4").WithArguments("P.M4(System.Func<object>, System.Action<object>, System.Action<string>)", "P.M4(System.Func<System.ValueType>, System.Action<string>, System.Action<object>)"), // (21,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M6(System.Action<object>, string, object)' and 'P.M6(System.Action<string>, object, string)' // M6(q=> {},(string)null, (string)null); Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("P.M6(System.Action<object>, string, object)", "P.M6(System.Action<string>, object, string)") ); // By comparing these two programs, it becomes clear how unfortunate this is. M(q=>null) is ambiguous, // M(null) is unambiguous. But M((string)null, q=>{}) is unambiguous, M((string)null, null) is ambiguous! string source3 = @" using System; using System.Collections.Generic; class SyntaxNode {} class ExpressionSyntax : SyntaxNode {} class IdentifierNameSyntax : ExpressionSyntax {} class SyntaxAnnotation {} static class P { public static TRoot ReplaceNodes1<TRoot>(this TRoot root, IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, SyntaxNode, SyntaxNode> computeReplacementNode) where TRoot : SyntaxNode { Console.Write('A'); return null; } public static TRoot ReplaceNodes1<TRoot, TNode>(this TRoot root, IEnumerable<TNode> nodes, Func<TNode, TNode, SyntaxNode> computeReplacementNode) where TRoot : SyntaxNode where TNode : SyntaxNode { Console.Write('B'); return null; } public static TNode WithAdditionalAnnotations<TNode>(this TNode node, params SyntaxAnnotation[] annotations) where TNode : SyntaxNode { return null; } public static TRoot ReplaceNodes2<TRoot, TNode>(this TRoot root, IEnumerable<TNode> nodes, Func<TNode, TNode, SyntaxNode> computeReplacementNode) where TRoot : SyntaxNode where TNode : SyntaxNode { Console.Write('B'); return null; } public static TRoot ReplaceNodes2<TRoot>(this TRoot root, IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, SyntaxNode, SyntaxNode> computeReplacementNode) where TRoot : SyntaxNode { Console.Write('A'); return null; } static void Main() { ExpressionSyntax expr = null; var identifierNodes = new List<IdentifierNameSyntax>(); var myAnnotation = new SyntaxAnnotation(); expr.ReplaceNodes1(identifierNodes, (e, e2) => e2.WithAdditionalAnnotations(myAnnotation)); expr.ReplaceNodes2(identifierNodes, (e, e2) => e2.WithAdditionalAnnotations(myAnnotation)); } }"; CompileAndVerify(source3, expectedOutput: @"BB"); } [Fact] public void DeviationFromSpec() { string source1 = @" using System; class P { static void M1(int a) { Console.Write(1); } static void M1(uint? a) { Console.Write(2); } static void M2(int? a) { Console.Write(3); } static void M2(uint a) { Console.Write(4); } static void Main() { int i = 0; int? ni = 0; uint u = 0; uint? nu = 0; short s = 0; short? ns = 0; ushort us = 0; ushort? nus = 0; M1(null); M1(i); Console.Write("" "");//M1(ni); M1(u); M1(nu); M1(s); Console.Write("" "");//M1(ns); M1(us); M1(nus); M2(null); M2(i); M2(ni); M2(u); Console.Write("" "");//M2(nu); M2(s); M2(ns); M2(us); M2(nus); } }"; CompileAndVerify(source1, expectedOutput: @"21 221 123334 3333"); string source2 = @" using System; class P { static void M1(int a) { Console.Write(1); } static void M1(uint? a) { Console.Write(2); } static void M2(int? a) { Console.Write(3); } static void M2(uint a) { Console.Write(4); } static void Main() { int? ni = 0; uint? nu = 0; short? ns = 0; //ushort us = 0; M1(ni); M1(ns); M2(nu); } }"; CreateCompilation(source2).VerifyDiagnostics( // (16,8): error CS1503: Argument 1: cannot convert from 'int?' to 'int' // M1(ni); Diagnostic(ErrorCode.ERR_BadArgType, "ni").WithArguments("1", "int?", "int"), // (17,8): error CS1503: Argument 1: cannot convert from 'short?' to 'int' // M1(ns); Diagnostic(ErrorCode.ERR_BadArgType, "ns").WithArguments("1", "short?", "int"), // (19,8): error CS1503: Argument 1: cannot convert from 'uint?' to 'int?' // M2(nu); Diagnostic(ErrorCode.ERR_BadArgType, "nu").WithArguments("1", "uint?", "int?") ); } [Fact] public void ParametersExactlyMatchExpression() { string source2 = @" using System; class P { delegate int DA(); delegate int DB(); static void M1(DA a) { Console.Write(1); } static void M1(DB a) { Console.Write(2); } static void Main() { int x = 1; M1(() => x); } }"; CreateCompilation(source2).VerifyDiagnostics( // (14,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M1(P.DA)' and 'P.M1(P.DB)' // M1(() => x); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("P.M1(P.DA)", "P.M1(P.DB)") ); } [Fact] public void ExactlyMatchingNestedLambda() { string source1 = @" using System; class P { delegate Func<int> DA(); delegate Func<object> DB(); static void M1(DA a) { Console.Write(1); } static void M1(DB a) { Console.Write(2); } static void Main() { int i = 0; M1(() => () => i); } }"; CompileAndVerify(source1, expectedOutput: @"1"); string source2 = @" using System; class P { delegate Func<int> DA(); delegate Func<object> DB(); static void M1(DA a, object b) { Console.Write(1); } static void M1(DB a, int b) { Console.Write(2); } static void Main() { int i = 0; M1(() => () => i, i); } }"; CompileAndVerify(source2, parseOptions: TestOptions.Regular9, expectedOutput: @"2"); var comp = CreateCompilation(source2); comp.VerifyDiagnostics( // (15,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M1(P.DA, object)' and 'P.M1(P.DB, int)' // M1(() => () => i, i); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("P.M1(P.DA, object)", "P.M1(P.DB, int)").WithLocation(15, 5)); } [Fact] public void ParametersImplicitlyConvertibleToEachOther() { string source1 = @" using System; class CA { public static implicit operator CA(int x) { return null; } public static implicit operator CA(CB x) { return null; } } class CB { public static implicit operator CB(int x) { return null; } public static implicit operator CB(CA x) { return null; } } class P { static void M1(CA a) { Console.Write(1); } static void M1(CB a) { Console.Write(2); } static void Main() { int i = 0; M1(i); } }"; CreateCompilation(source1).VerifyDiagnostics( // (36,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M1(CA)' and 'P.M1(CB)' // M1(i); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("P.M1(CA)", "P.M1(CB)") ); } [Fact] public void BetterTaskType() { string source1 = @" using System; using System.Threading.Tasks; class P { static void M1(Task<int> a) { Console.Write(1); } static void M1(Task<uint> a) { Console.Write(2); } static void Main() { M1(null); } }"; CompileAndVerify(source1, expectedOutput: @"1"); string source2 = @" using System; using System.Threading.Tasks; class P { static void M1(Task<int> a, uint b) { Console.Write(1); } static void M1(Task<uint> a, int b) { Console.Write(2); } static void Main() { M1(null,0); } }"; CreateCompilation(source2).VerifyDiagnostics( // (11,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M1(System.Threading.Tasks.Task<int>, uint)' and 'P.M1(System.Threading.Tasks.Task<uint>, int)' // M1(null,0); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("P.M1(System.Threading.Tasks.Task<int>, uint)", "P.M1(System.Threading.Tasks.Task<uint>, int)") ); } [Fact] public void BetterTasklikeType() { string source1 = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static void Main() { h(async () => { await (Task)null; return 1; }); } static void h<T>(Func<Task<T>> lambda) { } static void h<T>(Func<MyTask<T>> lambda) { } } [AsyncMethodBuilder(typeof(MyTaskBuilder<>))] public class MyTask<T> { } public class MyTaskBuilder<T> { public static MyTaskBuilder<T> Create() => null; public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void SetResult(T result) { } public void SetException(Exception exception) { } public MyTask<T> Task => default(MyTask<T>); public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; CreateCompilationWithMscorlib45(source1).VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.h<T>(Func<Task<T>>)' and 'C.h<T>(Func<MyTask<T>>)' // h(async () => { await (Task)null; return 1; }); Diagnostic(ErrorCode.ERR_AmbigCall, "h").WithArguments("C.h<T>(System.Func<System.Threading.Tasks.Task<T>>)", "C.h<T>(System.Func<MyTask<T>>)").WithLocation(9, 9) ); string source2 = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static void Main() { k(async () => { await (Task)null; return 1; }); } static void k<T>(Func<YourTask<T>> lambda) { } static void k<T>(Func<MyTask<T>> lambda) { } } [AsyncMethodBuilder(typeof(MyTaskBuilder<>))] public class MyTask<T> { } public class MyTaskBuilder<T> { public static MyTaskBuilder<T> Create() => null; public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void SetResult(T result) { } public void SetException(Exception exception) { } public MyTask<T> Task => default(MyTask<T>); public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } } [AsyncMethodBuilder(typeof(YourTask<>))] public class YourTask<T> { } public class YourTaskBuilder<T> { public static YourTaskBuilder<T> Create() => null; public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void SetResult(T result) { } public void SetException(Exception exception) { } public YourTask<T> Task => default(YourTask<T>); public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; CreateCompilationWithMscorlib45(source2).VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.k<T>(Func<YourTask<T>>)' and 'C.k<T>(Func<MyTask<T>>)' // k(async () => { await (Task)null; return 1; }); Diagnostic(ErrorCode.ERR_AmbigCall, "k").WithArguments("C.k<T>(System.Func<YourTask<T>>)", "C.k<T>(System.Func<MyTask<T>>)").WithLocation(9, 9) ); } [Fact] public void NormalizeTaskTypes() { string source = @" using System.Runtime.CompilerServices; class A<T> { internal struct B<U> { } } unsafe class C<T, U> { #pragma warning disable CS0169 static MyTask F0; static MyTask<T> F1; static C<MyTask, MyTask[]>[,] F2; static A<MyTask<MyTask>>.B<C<int, MyTask>> F3; static int* F4; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder))] struct MyTask { } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] struct MyTask<T> { } struct MyTaskMethodBuilder { public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder(); } struct MyTaskMethodBuilder<T> { public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeDebugDll); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F1").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<T>", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<T>", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F2").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("C<MyTask, MyTask[]>[,]", type.ToTestDisplayString()); Assert.Equal("C<System.Threading.Tasks.Task, System.Threading.Tasks.Task[]>[,]", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F3").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("A<MyTask<MyTask>>.B<C<System.Int32, MyTask>>", type.ToTestDisplayString()); Assert.Equal("A<System.Threading.Tasks.Task<System.Threading.Tasks.Task>>.B<C<System.Int32, System.Threading.Tasks.Task>>", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F4").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("System.Int32*", type.ToTestDisplayString()); Assert.Equal("System.Int32*", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_Tuples() { string source = @"using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C<T, U> { #pragma warning disable CS0169 static MyTask<ValueTuple<MyTask, T>> F0; static ((MyTask a, T b) c, MyTask<(U, MyTask<T>)[]> d) F1; static Task<(Task, object)[]> F2; static (MyTask, char, byte, short, ushort, int, uint, long, ulong, char, byte, short, ushort, int, uint, long, MyTask<T>) F3; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder))] struct MyTask { } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] struct MyTask<T> { } struct MyTaskMethodBuilder { public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder(); } struct MyTaskMethodBuilder<T> { public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(); } namespace System { struct ValueTuple<T1, T2> { } struct ValueTuple<T1, T2, T3> { } struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, T8> { } } namespace System.Runtime.CompilerServices { class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] names) { } } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source, assemblyName: "comp"); compilation.VerifyDiagnostics( // (10,12): error CS8128: Member 'Rest' was not found on type 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, T8>' from assembly comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // static (MyTask, char, byte, short, ushort, int, uint, long, ulong, char, byte, short, ushort, int, uint, long, MyTask<T>) F3; Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "(MyTask, char, byte, short, ushort, int, uint, long, ulong, char, byte, short, ushort, int, uint, long, MyTask<T>)").WithArguments("Rest", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, T8>", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(10, 12)); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<(MyTask, T)>", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<(System.Threading.Tasks.Task, T)>", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F1").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("((MyTask a, T b) c, MyTask<(U, MyTask<T>)[]> d)", type.ToTestDisplayString()); Assert.Equal("((System.Threading.Tasks.Task a, T b) c, System.Threading.Tasks.Task<(U, System.Threading.Tasks.Task<T>)[]> d)", normalized.ToTestDisplayString()); // No changes. type = compilation.GetMember<FieldSymbol>("C.F2").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("System.Threading.Tasks.Task<(System.Threading.Tasks.Task, System.Object)[]>", type.ToTestDisplayString()); Assert.Same(type, normalized); // Nested System.ValueTuple<>. type = compilation.GetMember<FieldSymbol>("C.F3").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("(MyTask, System.Char, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.UInt64, System.Char, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, MyTask<T>)", type.ToTestDisplayString()); Assert.Equal("(System.Threading.Tasks.Task, System.Char, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.UInt64, System.Char, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.Threading.Tasks.Task<T>)", normalized.ToTestDisplayString()); Assert.Equal("(System.UInt32, System.Int64, MyTask<T>)", GetUnderlyingTupleTypeRest(type).ToTestDisplayString()); Assert.Equal("(System.UInt32, System.Int64, System.Threading.Tasks.Task<T>)", GetUnderlyingTupleTypeRest(normalized).ToTestDisplayString()); } // Return the underlying type of the most-nested part of the TupleTypeSymbol. private static NamedTypeSymbol GetUnderlyingTupleTypeRest(TypeSymbol type) { while (type.IsTupleType) { var typeArgs = ((NamedTypeSymbol)type).TypeArguments(); if (typeArgs.Length < 8) { return (NamedTypeSymbol)type; } type = typeArgs[7]; } return null; } // Preserve type argument custom modifiers. [WorkItem(592, "https://github.com/dotnet/roslyn/issues/12615")] [Fact] public void NormalizeTaskTypes_TypeArgumentCustomModifiers() { var ilSource = @".class public C { .field public static class MyTask`1<class MyTask modopt(class MyTask`1<object>)> F0 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTask { .custom instance void System.Runtime.CompilerServices.AsyncMethodBuilderAttribute::.ctor(class [mscorlib]System.Type) = { type(MyTaskMethodBuilder) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTask`1<T> { .custom instance void System.Runtime.CompilerServices.AsyncMethodBuilderAttribute::.ctor(class [mscorlib]System.Type) = { type(MyTaskMethodBuilder`1) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTaskMethodBuilder { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTaskMethodBuilder`1<T> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .namespace System.Runtime.CompilerServices { .class public AsyncMethodBuilderAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class [mscorlib]System.Type t) cil managed { ret } } } "; var source = @""; var reference = CompileIL(ilSource); var compilation = CreateCompilationWithMscorlib45(source, references: new[] { reference }); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<MyTask modopt(MyTask<System.Object>)>", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<System.Threading.Tasks.Task modopt(MyTask<System.Object>)>", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_Pointers() { string source = @" using System.Runtime.CompilerServices; unsafe class C<T> { #pragma warning disable CS0169 static C<MyTask<int>>* F0; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] struct MyTask<T> { } struct MyTaskMethodBuilder<T> { public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeDebugDll); compilation.VerifyDiagnostics( // (6,28): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C<MyTask<int>>') // static C<MyTask<int>>* F0; Diagnostic(ErrorCode.ERR_ManagedAddr, "F0").WithArguments("C<MyTask<int>>").WithLocation(6, 28)); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("C<MyTask<System.Int32>>*", type.ToTestDisplayString()); Assert.Equal("C<System.Threading.Tasks.Task<System.Int32>>*", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_PointersCustomModifiers() { var ilSource = @".class public C { .field public static class MyTask modopt(class MyTask) *[] F0 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTask { .custom instance void System.Runtime.CompilerServices.AsyncMethodBuilderAttribute::.ctor(class [mscorlib]System.Type) = { type(MyTaskMethodBuilder) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTaskMethodBuilder { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .namespace System.Runtime.CompilerServices { .class public AsyncMethodBuilderAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class [mscorlib]System.Type t) cil managed { ret } } } "; var source = @""; var reference = CompileIL(ilSource); var compilation = CreateCompilationWithMscorlib45(source, references: new[] { reference }); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask modopt(MyTask) *[]", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task modopt(MyTask) *[]", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_FunctionPointers() { string source = @" using System.Runtime.CompilerServices; unsafe class C<T> { #pragma warning disable CS0169 static delegate*<int, int, C<MyTask<int>>> F0; static delegate*<C<MyTask<int>>, int, int> F1; static delegate*<int, C<MyTask<int>>, int> F2; static delegate*<int, int, int> F3; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] struct MyTask<T> { } struct MyTaskMethodBuilder<T> { public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics(); assert("F0", "delegate*<System.Int32, System.Int32, C<MyTask<System.Int32>>>", "delegate*<System.Int32, System.Int32, C<System.Threading.Tasks.Task<System.Int32>>>"); assert("F1", "delegate*<C<MyTask<System.Int32>>, System.Int32, System.Int32>", "delegate*<C<System.Threading.Tasks.Task<System.Int32>>, System.Int32, System.Int32>"); assert("F2", "delegate*<System.Int32, C<MyTask<System.Int32>>, System.Int32>", "delegate*<System.Int32, C<System.Threading.Tasks.Task<System.Int32>>, System.Int32>"); assert("F3", "delegate*<System.Int32, System.Int32, System.Int32>", normalized: null); void assert(string fieldName, string original, string normalized) { var type = compilation.GetMember<FieldSymbol>($"C.{fieldName}").Type; FunctionPointerUtilities.CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)type); var normalizedType = type.NormalizeTaskTypes(compilation); Assert.Equal(original, type.ToTestDisplayString()); if (normalized is object) { Assert.Equal(normalized, normalizedType.ToTestDisplayString()); } else { Assert.Same(type, normalizedType); } } } [Fact] public void NormalizeTaskTypes_FunctionPointersCustomModifiers() { var ilSource = @".class public C { .field public static method class MyTask modopt(class MyTask) *(class MyTask modopt(class MyTask)) F0 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTask { .custom instance void System.Runtime.CompilerServices.AsyncMethodBuilderAttribute::.ctor(class [mscorlib]System.Type) = { type(MyTaskMethodBuilder) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTaskMethodBuilder { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .namespace System.Runtime.CompilerServices { .class public AsyncMethodBuilderAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class [mscorlib]System.Type t) cil managed { ret } } } "; var source = @""; var reference = CompileIL(ilSource); var compilation = CreateCompilationWithMscorlib45(source, references: new[] { reference }); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("delegate*<MyTask modopt(MyTask), MyTask modopt(MyTask)>", type.ToTestDisplayString()); Assert.Equal("delegate*<System.Threading.Tasks.Task modopt(MyTask), System.Threading.Tasks.Task modopt(MyTask)>", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_Errors() { string source = @" using System.Runtime.CompilerServices; class C { #pragma warning disable CS0169 static A<int, MyTask> F0; static MyTask<B> F1; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder))] struct MyTask { } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] struct MyTask<T> { } struct MyTaskMethodBuilder { public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder(); } struct MyTaskMethodBuilder<T> { public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.VerifyDiagnostics( // (5,19): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // static MyTask<B> F1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 19), // (4,12): error CS0246: The type or namespace name 'A<,>' could not be found (are you missing a using directive or an assembly reference?) // static A<int, MyTask> F0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A<int, MyTask>").WithArguments("A<,>").WithLocation(6, 12)); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; Assert.Equal(TypeKind.Error, type.TypeKind); var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("A<System.Int32, MyTask>", type.ToTestDisplayString()); Assert.Equal("A<System.Int32, System.Threading.Tasks.Task>", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F1").Type; Assert.Equal(TypeKind.Error, ((NamedTypeSymbol)type).TypeArguments()[0].TypeKind); normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<B>", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<B>", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_Inner() { string source = @" using System.Runtime.CompilerServices; class C<T, U> { #pragma warning disable CS0169 static MyTask<U> F0; static C<U, MyTask>.MyTask F1; static C<T, MyTask<U>>.Inner F2; #pragma warning restore CS0169 class Inner { } [AsyncMethodBuilder(typeof(C<,>.MyTaskMethodBuilder))] class MyTask { } [AsyncMethodBuilder(typeof(C<,>.MyTaskMethodBuilder<>))] class MyTask<V> { } class MyTaskMethodBuilder { public static MyTaskMethodBuilder Create() => null; } class MyTaskMethodBuilder<V> { public static MyTaskMethodBuilder<V> Create() => null; } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("C<T, U>.MyTask<U>", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<U>", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F1").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("C<U, C<T, U>.MyTask>.MyTask", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F2").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("C<T, C<T, U>.MyTask<U>>.Inner", type.ToTestDisplayString()); Assert.Equal("C<T, System.Threading.Tasks.Task<U>>.Inner", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_Outer() { string source = @" using System.Runtime.CompilerServices; class C { #pragma warning disable CS0169 static MyTask<MyTask.A> F0; static MyTask<MyTask<object>>.B F1; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder))] class MyTask { internal class A { } } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] class MyTask<V> { internal class B { } } class MyTaskMethodBuilder { public static MyTaskMethodBuilder Create() => null; } class MyTaskMethodBuilder<V> { public static MyTaskMethodBuilder<V> Create() => null; } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<MyTask.A>", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<MyTask.A>", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F1").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<MyTask<System.Object>>.B", type.ToTestDisplayString()); Assert.Equal("MyTask<System.Threading.Tasks.Task<System.Object>>.B", normalized.ToTestDisplayString()); } /// <summary> /// Normalize should have no effect if System.Threading.Tasks.Task /// and System.Threading.Tasks.Task&lt;T&gt; are not available. /// </summary> [Fact] public void NormalizeTaskTypes_MissingWellKnownTypes() { string source = @" using System.Runtime.CompilerServices; class C { #pragma warning disable CS0169 static MyTask<MyTask> F; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder))] struct MyTask { } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] struct MyTask<T> { } struct MyTaskMethodBuilder { public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder(); } struct MyTaskMethodBuilder<T> { public MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateEmptyCompilation(source, references: new[] { MscorlibRef_v20 }); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<MyTask>", type.ToTestDisplayString()); Assert.Equal("MyTask<MyTask>", normalized.ToTestDisplayString()); } [Fact] public void BetterDelegateType_01() { string source1 = @" using System; class P { static void M1(Func<int> a) { Console.Write(1); } static void M1(Func<uint> a) { Console.Write(2); } static void M2(Func<int> a) { Console.Write(3); } static void M2(Action a) { Console.Write(4); } static void Main() { M1(null); M2(null); } }"; CompileAndVerify(source1, expectedOutput: @"13"); string source2 = @" using System; class P { static void M1(Func<int> a, uint b) { Console.Write(1); } static void M1(Func<uint> a, int b) { Console.Write(2); } static void M2(Func<int> a, uint b) { Console.Write(3); } static void M2(Action a, int b) { Console.Write(4); } static void Main() { M1(null,0); M2(null,0); } }"; CreateCompilation(source2).VerifyDiagnostics( // (13,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M1(System.Func<int>, uint)' and 'P.M1(System.Func<uint>, int)' // M1(null,0); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("P.M1(System.Func<int>, uint)", "P.M1(System.Func<uint>, int)"), // (14,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M2(System.Func<int>, uint)' and 'P.M2(System.Action, int)' // M2(null,0); Diagnostic(ErrorCode.ERR_AmbigCall, "M2").WithArguments("P.M2(System.Func<int>, uint)", "P.M2(System.Action, int)") ); } [Fact, WorkItem(6560, "https://github.com/dotnet/roslyn/issues/6560")] public void BetterDelegateType_02() { string source1 = @" using System; class C { public static void Main() { Run1(() => MethodReturnsVoid()); Run1(MethodReturnsVoid); Run2(() => MethodReturnsVoid()); Run2(MethodReturnsVoid); } public static object Run1(Action action) { Console.WriteLine(""Run1(Action action)""); action(); return null; } public static object Run1(Func<object> action, bool optional = false) { Console.WriteLine(""Run1(Func<object> action, bool optional = false)""); return action(); } public static object Run2(Func<object> action, bool optional = false) { Console.WriteLine(""Run2(Func<object> action, bool optional = false)""); return action(); } public static object Run2(Action action) { Console.WriteLine(""Run2(Action action)""); action(); return null; } private static void MethodReturnsVoid() { } } "; CompileAndVerify(source1, expectedOutput: @"Run1(Action action) Run1(Action action) Run2(Action action) Run2(Action action)"); } [Fact] public void TestBug9851() { // We should ensure that we do not report "no method M takes n parameters" if in fact // there is any method M that could take n parameters. var source = @" class C { static void J<T>(T t1, T t2) {} static void J(int x) {} public static void M() { J(123.0, 456.0m); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'C.J<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // J(123.0, 456.0m); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "J").WithArguments("C.J<T>(T, T)").WithLocation(8, 9)); } [Fact] public void TestLambdaErrorReporting() { var source = @" using System; class C { static void J(Action<int> action) {} static void J(Action<string> action) {} static void K(Action<decimal> action) {} static void K(Action<double> action) {} static void K(Action<string> action) {} public static void M() { // If there are multiple possible bindings for a lambda and both of them produce // 'the same' errors then we should report those errors to the exclusion of any // errors produced on only some of the bindings. // // For instance, here the binding of x as int produces two errors: // * int does not have ToStrign // * int does not have Length // the binding of x as string produces two errors: // * string does not have ToStrign // * cannot multiply strings // We should only report the common error. J(x=>{ Console.WriteLine(x.ToStrign(), x.Length, x * 2); }); // If there is no common error then we should report both errors: J(y=>{ Console.WriteLine(y == string.Empty, y / 4.5); }); // If there is an error that is in common to two of three bindings, // then we should report it but only report it once. // For instance, here the binding of x as decimal produces: // * no decimal == string // * no decimal - double // The binding as double produces: // * no double == string // The binding as string produces: // * no string - double // // There is no error common to all three bindings. However, of the // four errors we should only report two of them. K(z=>{ Console.WriteLine(z == string.Empty, z - 4.5); }); } }"; CreateCompilation(source).VerifyDiagnostics( // (26,36): error CS1061: 'string' does not contain a definition for 'ToStrign' and no extension method 'ToStrign' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // J(x=>{ Console.WriteLine(x.ToStrign(), x.Length, x * 2); }); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ToStrign").WithArguments("string", "ToStrign").WithLocation(26, 36), // (30,34): error CS0019: Operator '==' cannot be applied to operands of type 'int' and 'string' // J(y=>{ Console.WriteLine(y == string.Empty, y / 4.5); }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "y == string.Empty").WithArguments("==", "int", "string").WithLocation(30, 34), // (30,53): error CS0019: Operator '/' cannot be applied to operands of type 'string' and 'double' // J(y=>{ Console.WriteLine(y == string.Empty, y / 4.5); }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "y / 4.5").WithArguments("/", "string", "double").WithLocation(30, 53), // (45,53): error CS0019: Operator '-' cannot be applied to operands of type 'string' and 'double' // K(z=>{ Console.WriteLine(z == string.Empty, z - 4.5); }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "z - 4.5").WithArguments("-", "string", "double").WithLocation(45, 53), // (45,34): error CS0019: Operator '==' cannot be applied to operands of type 'double' and 'string' // K(z=>{ Console.WriteLine(z == string.Empty, z - 4.5); }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "z == string.Empty").WithArguments("==", "double", "string").WithLocation(45, 34)); } [Fact] public void TestRefOutAnonymousDelegate() { string source = @" using System; using System.Linq.Expressions; class p { static void Goo<T>(ref Func<T, T> a) { } static void Bar<T>(out Func<T, T> a) { a = null; } static void Goo2<T>(ref Expression<Func<T, T>> a) { } static void Bar2<T>(out Expression<Func<T, T>> a) { a = null; } static void Main() { Goo<string>(x => x); Bar<string>(x => x); Goo2<string>(x => x); Bar2<string>(x => x); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (14,21): error CS1503: Argument 1: cannot convert from 'lambda expression' to 'ref Func<string, string>' // Goo<string>(x => x); Diagnostic(ErrorCode.ERR_BadArgType, "x => x").WithArguments("1", "lambda expression", "ref System.Func<string, string>").WithLocation(14, 21), // (15,21): error CS1503: Argument 1: cannot convert from 'lambda expression' to 'out Func<string, string>' // Bar<string>(x => x); Diagnostic(ErrorCode.ERR_BadArgType, "x => x").WithArguments("1", "lambda expression", "out System.Func<string, string>").WithLocation(15, 21), // (16,22): error CS1503: Argument 1: cannot convert from 'lambda expression' to 'ref Expression<Func<string, string>>' // Goo2<string>(x => x); Diagnostic(ErrorCode.ERR_BadArgType, "x => x").WithArguments("1", "lambda expression", "ref System.Linq.Expressions.Expression<System.Func<string, string>>").WithLocation(16, 22), // (17,22): error CS1503: Argument 1: cannot convert from 'lambda expression' to 'out Expression<Func<string, string>>' // Bar2<string>(x => x); Diagnostic(ErrorCode.ERR_BadArgType, "x => x").WithArguments("1", "lambda expression", "out System.Linq.Expressions.Expression<System.Func<string, string>>").WithLocation(17, 22)); } [Fact, WorkItem(1157097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1157097"), WorkItem(2298, "https://github.com/dotnet/roslyn/issues/2298")] public void TestOverloadResolutionTiebreaker() { // Testing that we get the same ambiguity error as the one reported by the native compiler. string source = @" class C { static void X(params string[] s) {} static void X<T>(T t){} static void X(string s, object o = null) {} public void M() { X((string)null); //-C.X(string, object) } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.X(params string[])' and 'C.X<T>(T)' // X((string)null); //-C.X(string, object) Diagnostic(ErrorCode.ERR_AmbigCall, "X").WithArguments("C.X(params string[])", "C.X<T>(T)").WithLocation(9, 9) ); } [Fact] public void TestConstraintViolationApplicabilityErrors() { // The rules for constraint satisfaction during overload resolution are a bit odd. If a constraint // *on a formal parameter type* is not met then the candidate is not applicable. But if a constraint // is violated *on the method type parameter itself* then the method can be chosen as the best // applicable candidate, and then rejected during "final validation". // // Furthermore: most of the time a constraint violation on a formal type parameter will also // be a constraint violation on the method type parameter. The latter seems like the better // error to report. We only report the violation on the formal parameter if the constraint // is not violated on the method type parameter. var source = @" class C { static string MakeString() { return null; } struct L<S> where S : struct {} class N<T> where T : struct {} public static void M() { string s = MakeString(); // We violate the constraint on both T and U. // The method is not applicable. // Overload resolution fails and reports the violation on U, // even though technically it was the violation on U that caused // the method to be inapplicable. Test1<string>(s, null); // Type inference successfully infers that V is string; // we now should do exactly the same as the previous case. Test2(s, null); // In the previous two tests it is not clear whether the compiler is // allowing overload resolution to succeed and then final validation // fails, or if the candidate set really is empty. We must verify // that the generic version is actually an inapplicable candidate. // // Even though its arguments under construction are better, // the generic version is inapplicable because the constraint // on T is violated. Therefore there is no error; the object // version wins: Test3(s, null); // By contrast, here overload resolution infers that X<string> is the // best possible match, and then final validation fails: Test4(s); // When a method is inapplicable because of a constraint violation we // prefer to state the violation on the method type parameter constraint. // In an error recovery scenario we might not be able to do that. // Here there are two errors: first, the declaration of Test5 is bad because // Y does not meet the constraint on T. Second, the method call is bad // because string does not meet the constraint on T. We cannot say that // string does not meet the constraint on Y because, erroneously, there is // no such constraint. Test5(s, null); // Here we have another error recovery scenario. L<string> is clearly // illegal, but what if we try to do overload resolution anyway? // The constraint is not violated on Z because L<string> is a struct. // Overload resolution fails because the constraint on L is violated in // N<L<string>>. Thus that is the overload resolution error we report. // We therefore end up reporting this error twice, unfortunately; we // should consider putting some gear in place to suppress the cascading // error. Test6<L<string>>(null); } static void Test1<U>(U u, N<U> nu) where U : struct { } static void Test2<V>(V v, N<V> nv) where V : struct { } static void Test3<W>(W w, N<W> nw) where W : struct { } static void Test3(object o1, object o2) {} static void Test4<X>(X x) where X : struct { } static void Test4(object x) {} static void Test5<Y>(Y y, N<Y> ny) { } static void Test6<Z>(N<Z> nz) where Z : struct {} }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (67,36): error CS0453: The type 'Y' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'C.N<T>' // static void Test5<Y>(Y y, N<Y> ny) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "ny").WithArguments("C.N<T>", "T", "Y").WithLocation(67, 36), // (17,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.Test1<U>(U, C.N<U>)' // Test1<string>(s, null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test1<string>").WithArguments("C.Test1<U>(U, C.N<U>)", "U", "string").WithLocation(17, 9), // (21,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'V' in the generic type or method 'C.Test2<V>(V, C.N<V>)' // Test2(s, null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test2").WithArguments("C.Test2<V>(V, C.N<V>)", "V", "string").WithLocation(21, 9), // (36,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'X' in the generic type or method 'C.Test4<X>(X)' // Test4(s); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test4").WithArguments("C.Test4<X>(X)", "X", "string").WithLocation(36, 9), // (47,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'C.N<T>' // Test5(s, null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test5").WithArguments("C.N<T>", "T", "string").WithLocation(47, 9), // (58,17): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'S' in the generic type or method 'C.L<S>' // Test6<L<string>>(null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("C.L<S>", "S", "string").WithLocation(58, 17), // (58,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'S' in the generic type or method 'C.L<S>' // Test6<L<string>>(null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test6<L<string>>").WithArguments("C.L<S>", "S", "string").WithLocation(58, 9)); CreateCompilation(source).VerifyDiagnostics( // (67,36): error CS0453: The type 'Y' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'C.N<T>' // static void Test5<Y>(Y y, N<Y> ny) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "ny").WithArguments("C.N<T>", "T", "Y").WithLocation(67, 36), // (17,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.Test1<U>(U, C.N<U>)' // Test1<string>(s, null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test1<string>").WithArguments("C.Test1<U>(U, C.N<U>)", "U", "string").WithLocation(17, 9), // (21,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'V' in the generic type or method 'C.Test2<V>(V, C.N<V>)' // Test2(s, null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test2").WithArguments("C.Test2<V>(V, C.N<V>)", "V", "string").WithLocation(21, 9), // (47,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'C.N<T>' // Test5(s, null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test5").WithArguments("C.N<T>", "T", "string").WithLocation(47, 9), // (58,17): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'S' in the generic type or method 'C.L<S>' // Test6<L<string>>(null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("C.L<S>", "S", "string").WithLocation(58, 17), // (58,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'S' in the generic type or method 'C.L<S>' // Test6<L<string>>(null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test6<L<string>>").WithArguments("C.L<S>", "S", "string").WithLocation(58, 9)); } [Fact] public void TestBug9583() { var source = @" class C { public static void M() { Goo(); } static void Goo<T>(params T[] x) { } }"; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0411: The type arguments for method 'C.Goo<T>(params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Goo(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Goo").WithArguments("C.Goo<T>(params T[])").WithLocation(6, 9)); } [Fact] public void TestMoreOverloadResolutionErrors() { var source = @" class C { static void VoidReturning() {} static void M() { byte b = new byte(1); System.Console.WriteLine(VoidReturning()); } }"; CreateCompilation(source).VerifyDiagnostics( // (7,22): error CS1729: 'byte' does not contain a constructor that takes 1 arguments // byte b = new byte(1); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "byte").WithArguments("byte", "1").WithLocation(7, 22), // (8,34): error CS1503: Argument 1: cannot convert from 'void' to 'bool' // System.Console.WriteLine(VoidReturning()); Diagnostic(ErrorCode.ERR_BadArgType, "VoidReturning()").WithArguments("1", "void", "bool").WithLocation(8, 34)); } [Fact] public void TestBug6156() { TestOverloadResolutionWithDiff( @" class C { public static void M() { int y = 123; Out2 o2 = new Out2(); Ref2 r2 = o2; Out1 o1 = o2; Ref1 r1 = o2; r1.M(ref y); //-Ref1.M(ref int) o1.M(ref y); //-Ref1.M(ref int) o1.M(out y); //-Out1.M(out int) r2.M(ref y); //-Ref2.M(ref int) r2.M(out y); //-Out1.M(out int) o2.M(ref y); //-Ref2.M(ref int) o2.M(out y); //-Out2.M(out int) } } class Ref1 { public virtual void M(ref int x) { x = 1; } // SLOT1 } class Out1 : Ref1 { public virtual void M(out int x) { x = 2; } // SLOT2 } class Ref2 : Out1 { public override void M(ref int x) { x = 3; } // CLR says this overrides SLOT2, even though there is a ref/out mismatch with Out1. // C# says this overrides SLOT1 } class Out2 : Ref2 { public override void M(out int x) { x = 4; } // CLR says this overrides SLOT2, even though there is a ref/out mismatch with Ref2.M. // C# says this overrides SLOT2 }"); } [Fact] public void TestGenericMethods() { TestOverloadResolutionWithDiff( @" class C { class D<T> { public static void N<U>(U u){} public class E<V> { public static void O<W>(W w){} } } void M() { D<int>.N<byte>(1); //-C.D<int>.N<byte>(byte) D<int>.E<double>.O<short>(1); //-C.D<int>.E<double>.O<short>(short) } }"); } [Fact] public void TestDelegateBetterness() { TestOverloadResolutionWithDiff( @" delegate void Action(); delegate void Action<in A>(A a); delegate R Func<out R>(); delegate R Func<in A, out R>(A a); delegate R Func2<in A, out R>(A a); class Animal {} class Mammal : Animal {} class Tiger : Mammal {} class C { static void N1(Func<object> f){} static void N1(Func<string> f){} static void N2(Func<int, object> f){} static void N2(Action<int> f){} static void N3(Func<int, Tiger> f){} static void N3(Func2<int, Mammal> f){} static void N4(Func<int, Animal> f){} static void N4(Func2<int, Mammal> f){} void M() { // If we have a lambda argument and two delegates, the rules are: // First, if one delegate is convertible to the other but not vice-versa // then the more specific delegate wins. A Func<string> is convertible to Func<object> // but not vice-versa, so Func<string> must be more specific: // This test is disabled; see the comments to TestBug11961 above. // N1(()=>null); // Second, if the delegates have identical parameters, then the non-void one wins. // This lambda could be both an action and a func; we don't know if the construction // is being done for its value or for its side effects. N2(x=>new System.Object()); //-C.N2(Func<int, object>) // Third, if the delegates have identical parameters and both have a return type // and the lambda has an inferred return type, then the better delegate is the // one where the delegate return type exactly matches the lambda return type. N3(x=>new Tiger()); //-C.N3(Func<int, Tiger>) // Fourth, if the delegate return type does not exactly match the lambda return // type then the most specific delegate return type wins. N4(x=>new Tiger()); //-C.N4(Func2<int, Mammal>) } } "); } [Fact] public void TestTieBreakers() { TestOverloadResolutionWithDiff( @" class C { class D<TD>{} void N1<T1>(T1 p1) {} void N1(int p1) {} void N2(int p1) {} void N2(params int[] p1) {} void N3(int p1, int p2, params int[] p3) {} void N3(int p1, params int[] p3) {} void N4(int p1, int p2 = 0) {} void N4(int p1) {} void N51<T51>(T51 p1, double p2 = 0) {} void N51<T51>(int p1, string p2 = null ) {} void N52<T52>(D<T52> p1, double p2 = 0) {} void N52<T52>(D<int> p1, string p2 = null ) {} void N53<T53>(T53[] p1, double p2 = 0) {} void N53<T53>(int[] p1, string p2 = null ) {} void M() { // If due to construction or dynamicness all the effective parameters of two methods are identical // then we do a series of tiebreaking rules. // 1: A generic method is worse than a non-generic method. N1(123); //-C.N1(int) // 2: A method applicable in normal form is better than one applicable only in expanded form. N2(123); //-C.N2(int) // 3: If both methods are applicable in expanded form then the one with more 'real' parameters wins. N3(1, 2, 3, 4, 5, 6); //-C.N3(int, int, params int[]) // 4: If one method has no default arguments substituted and the other has one or more, the one // with no defaults wins. N4(1); //-C.N4(int) // 5: The more specific method wins. One method's declared parameter types list is more specific than // anothers if, for each position in the list, the type of one is not less specific than that // of the other, and, for at least one position, the type is more specific than that of the other. // 5.1: A type parameter is less specific than any other type. // 5.2: A constructed type C<X, Y> is less specific than C<A, B> if the type list <X, Y> is less specific than <A, B> // 5.3: An array type X[] is less specific than Y[] if X is less specific than Y. // 5.4: NOT TESTED: A pointer type X* is less specific than Y* if X is less specific than Y*. //EDMAURER removed the next three tests that fail due to the fact that omitted optional parameters are not supported. // N51<int>(123); //C.N51<int>(int, string) // N52<int>(null); //C.N52<int>(C.D<int>, string) // N53<int>(null); //C.N53<int>(int[], string) // 6: NOT TESTED: A non-lifted operator is better than a lifted operator. } } "); } [WorkItem(540153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540153")] [Fact] public void TestOverridingMismatchedParamsErrorCase_Source() { // Tests: // Replace params with non-params in signature of overridden member (and vice-versa) var source = @" abstract class Base { public abstract void Method1(Derived c1, Derived c2, params Derived[] c3); public abstract void Method2(Derived c1, Derived c2, Derived[] c3); } class Derived : Base { public override void Method1(Derived C1, Derived C2, Derived[] C3) { } //removes 'params' public override void Method2(Derived C1, Derived C2, params Derived[] C3) { } //adds 'params' } class Test2 { public static void Main2() { Derived d = new Derived(); Base b = d; b.Method1(d, d, d, d, d); // Fine d.Method1(d, d, d, d, d); // Fine b.Method2(d, d, d, d, d); // Should report error - No overload for Method2 takes 5 arguments d.Method2(d, d, d, d, d); // Should report error - No overload for Method2 takes 5 arguments } }"; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgCount, "Method2").WithArguments("Method2", "5"), Diagnostic(ErrorCode.ERR_BadArgCount, "Method2").WithArguments("Method2", "5")); } [Fact] public void TestImplicitImplMismatchedParamsErrorCase_Source() { // Tests: // Replace params with non-params in signature of implemented member (and vice-versa) var source = @" interface Base { void Method1(Derived c1, Derived c2, params Derived[] c3); void Method2(Derived c1, Derived c2, Derived[] c3); } class Derived : Base { public void Method1(Derived C1, Derived C2, Derived[] C3) { } //removes 'params' public void Method2(Derived C1, Derived C2, params Derived[] C3) { } //adds 'params' } class Test2 { public static void Main2() { Derived d = new Derived(); Base b = d; b.Method1(d, d, d, d, d); // Fine d.Method1(d, d, d, d, d); // Should report error - No overload for Method1 takes 5 arguments b.Method2(d, d, d, d, d); // Should report error - No overload for Method2 takes 5 arguments d.Method2(d, d, d, d, d); // Fine } }"; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgCount, "Method1").WithArguments("Method1", "5"), Diagnostic(ErrorCode.ERR_BadArgCount, "Method2").WithArguments("Method2", "5")); } [Fact] public void TestExplicitImplMismatchedParamsErrorCase_Source() { // Tests: // Replace params with non-params in signature of implemented member (and vice-versa) var source = @" interface Base { void Method1(Derived c1, Derived c2, params Derived[] c3); void Method2(Derived c1, Derived c2, Derived[] c3); } class Derived : Base { void Base.Method1(Derived C1, Derived C2, Derived[] C3) { } //removes 'params' void Base.Method2(Derived C1, Derived C2, params Derived[] C3) { } //adds 'params' - CS0466 } class Test2 { public static void Main2() { Derived d = new Derived(); Base b = d; b.Method1(d, d, d, d, d); // Fine b.Method2(d, d, d, d, d); // Should report error - No overload for Method2 takes 5 arguments } }"; CreateCompilation(source).VerifyDiagnostics( // (10,15): error CS0466: 'Derived.Base.Method2(Derived, Derived, params Derived[])' should not have a params parameter since 'Base.Method2(Derived, Derived, Derived[])' does not Diagnostic(ErrorCode.ERR_ExplicitImplParams, "Method2").WithArguments("Derived.Base.Method2(Derived, Derived, params Derived[])", "Base.Method2(Derived, Derived, Derived[])"), // (19,9): error CS1501: No overload for method 'Method2' takes 5 arguments Diagnostic(ErrorCode.ERR_BadArgCount, "Method2").WithArguments("Method2", "5")); } [WorkItem(540153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540153")] [WorkItem(540406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540406")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void TestOverridingMismatchedParamsErrorCase_Metadata() { // Tests: // Replace params with non-params in signature of overridden member (and vice-versa) var ilSource = @" .class public abstract auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig newslot abstract virtual instance void Method1(class Derived c1, class Derived c2, class Derived[] c3) cil managed { .param [3] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {} } // end of method Base::Method1 .method public hidebysig newslot abstract virtual instance void Method2(class Derived c1, class Derived c2, class Derived[] c3) cil managed { } // end of method Base::Method2 .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor } // end of class Base .class public auto ansi beforefieldinit Derived extends Base { .method public hidebysig virtual instance void Method1(class Derived C1, class Derived C2, class Derived[] C3) cil managed { ret } // end of method Derived::Method1 //// Adds 'params' //// .method public hidebysig virtual instance void Method2(class Derived C1, class Derived C2, class Derived[] C3) cil managed { .param [3] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {} ret } // end of method Derived::Method2 //// Removes 'params' //// .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base::.ctor() IL_0006: ret } // end of method Derived::.ctor } // end of class Derived "; var csharpSource = @" class Test2 { public static void Main2() { Derived d = new Derived(); Base b = d; b.Method1(d, d, d, d, d); // Fine d.Method1(d, d, d, d, d); // Fine b.Method2(d, d, d, d, d); // Should report error - No overload for Method2 takes 5 arguments d.Method2(d, d, d, d, d); // Should report error - No overload for Method2 takes 5 arguments } }"; // Same errors as in source case var comp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource); comp.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgCount, "Method2").WithArguments("Method2", "5"), Diagnostic(ErrorCode.ERR_BadArgCount, "Method2").WithArguments("Method2", "5")); } [WorkItem(6353, "DevDiv_Projects/Roslyn")] [Fact()] public void TestBaseAccessForAbstractMembers() { // Tests: // Override virtual member with abstract member – override this abstract member in further derived class // Test that call to abstract member fails when calling through "base." var source = @" abstract class Base<T, U> { T f = default(T); public abstract void Method(T i, U j); public virtual T Property { get { return f; } set { } } } class Base2<A, B> : Base<A, B> { public override void Method(A a, B b) { base.Method(a, b); // Error - Cannot call abstract base member } public override A Property { set { } } } abstract class Base3<T, U> : Base2<T, U> { public override abstract void Method(T x, U y); public override abstract T Property { set; } } class Base4<U, V> : Base3<U, V> { U f; public override void Method(U x, V y) { base.Method(x, y); // Error - Cannot call abstract base member } public override U Property { set { f = base.Property; // No error - Only setter is abstract in base class base.Property = f; // Error - Cannot call abstract base member } } }"; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Method").WithArguments("Base<A, B>.Method(A, B)"), Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Method").WithArguments("Base3<U, V>.Method(U, V)"), Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property").WithArguments("Base3<U, V>.Property")); } [WorkItem(6353, "DevDiv_Projects/Roslyn")] [Fact()] public void TestBaseAccessForAbstractMembers1() { // Tests: // Override virtual member with abstract member – override this abstract member in further derived class // Test that assigning an abstract member referenced through "base." to a delegate fails var source = @" using System; abstract class Base<T, U> { public abstract void Method(T i, U j); } class Base2<A, B> : Base<A, B> { public override void Method(A a, B b) { Action<A, B> m = base.Method; // Error - Cannot call abstract base member } }"; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Method").WithArguments("Base<A, B>.Method(A, B)")); } [WorkItem(6353, "DevDiv_Projects/Roslyn")] [Fact()] public void TestBaseAccessForAbstractMembers2() { var source = @" namespace A { abstract class Base<T> { public abstract T Method(int x); } abstract class Base2<A> : Base<A> { A f = default(A); public override A Method(int x) { return f; } public abstract A Method(A x); } class Derived : Base2<long> { // Surprisingly in Dev10 base.Method seems to bind to the second overload above and reports error (can't call abstract method) public override long Method(int x) { base.Method(x); return 1; } public override long Method(long x) { return 2; } } } namespace B { abstract class Base2<A> { A f = default(A); public virtual A Method(int x) { return f; } public abstract A Method(A x); } class Derived : Base2<long> { // But the same call seems to work in this case in Dev10 i.e. base.Method correctly binds to the first overload public override long Method(int x) { base.Method(x); return 1; } public override long Method(long x) { return 2; } } } "; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Method").WithArguments("A.Base2<long>.Method(long)")); } [Fact] public void Bug8766_ConstructorOverloadResolution_PrivateCtor() { var source = @"using System; public class A { const int C = 1; private A(int x) { Console.WriteLine(""int""); } public A(long x) { Console.WriteLine(""long""); } public void Goo() { A a = new A(C); } static void Main() { A a = new A(C); a.Goo(); B.Goo(); } } public class B { const int C = 1; public static void Goo() { A a = new A(C);} } "; CompileAndVerify(source, expectedOutput: @"int int long "); } [Fact] public void Bug8766_ConstructorOverloadResolution_ProtectedCtor() { var source = @"using System; public class A { const int C = 1; protected A(int x) { Console.WriteLine(""int""); } public A(long x) { Console.WriteLine(""long""); } public void Goo() { A a = new A(C); } static void Main() { A a = new A(C); a.Goo(); B.Goo(); } } public class B { const int C = 1; public static void Goo() { A a = new A(C);} } "; CompileAndVerify(source, expectedOutput: @"int int long "); } [Fact, WorkItem(546694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546694")] public void Bug16581_ConstructorOverloadResolution_BaseClass() { var source = @" using System; class A { private A(int x) { } public A(long x) { Console.WriteLine(""PASS""); } private void M(int x) { } public void M(long x) { Console.WriteLine(""PASS""); } } class B: A { public B(): base(123) { base.M(123); } public static void Main() { var unused = new B(); } } "; CompileAndVerify(source, expectedOutput: @"PASS PASS"); } [Fact, WorkItem(529847, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529847")] public void Bug14585_ConstructorOverloadResolution_BaseClass() { var source = @" public class Base { protected Base() { } public Base(int i) { } } class Test { static void Main(string[] args) { var a = new Base(); } } "; CreateCompilation(source).VerifyDiagnostics( // (17,21): error CS0122: 'Base.Base()' is inaccessible due to its protection level // var a = new Base(); Diagnostic(ErrorCode.ERR_BadAccess, "Base").WithArguments("Base.Base()")); } [Fact] public void Bug8766_MethodOverloadResolution() { var source = @"using System; public class A { const int C = 1; void AA(int x) { Console.WriteLine(""int""); } public void AA(long x) { Console.Write(""long""); } public void Goo() { A a = new A(); a.AA(C); } static void Main() { A a = new A(); a.Goo(); B.Goo(); } } public class B { const int C = 1; public static void Goo() { A a = new A(); a.AA(C);} } "; CompileAndVerify(source, expectedOutput: @"int long "); } [Fact] public void RegressionTestForIEnumerableOfDynamic() { TestOverloadResolutionWithDiff( @"using System; using System.Collections.Generic; class C { class DynamicWrapper { public IEnumerable<dynamic> Value { get; set; } } static void M() { DynamicWrapper[] array = null; Goo(array, x => x.Value, (x, y) => string.Empty); //-C.Goo(System.Collections.Generic.IEnumerable<C.DynamicWrapper>, System.Func<C.DynamicWrapper, System.Collections.Generic.IEnumerable<dynamic>>, System.Func<C.DynamicWrapper, dynamic, string>) } static IEnumerable<dynamic> Goo( object source, Func<dynamic, IEnumerable<dynamic>> collectionSelector, Func<dynamic, dynamic, dynamic> resultSelector) { return null; } static IEnumerable<string> Goo( IEnumerable<DynamicWrapper> source, Func<DynamicWrapper, IEnumerable<dynamic>> collectionSelector, Func<DynamicWrapper, dynamic, string> resultSelector) { return null; } }"); } [Fact] public void MissingBaseTypeAndParamsCtor() { var cCommon = CreateCompilation(@" public class TCommon {} ", assemblyName: "cCommon"); Assert.Empty(cCommon.GetDiagnostics()); var cCS = CreateCompilation(@" public class MProvider : TCommon {} ", new MetadataReference[] { new CSharpCompilationReference(cCommon) }, assemblyName: "cCS"); Assert.Empty(cCS.GetDiagnostics()); var cFinal = CreateCompilation(@" public class T : MProvider {} class PArray { public PArray(TCommon t, params object[] p) { } } class Goo { void M() { T t = new T(); var x = new PArray(t, 1, 2); } } ", //note that the reference to the 'cCS' compilation is missing. new MetadataReference[] { new CSharpCompilationReference(cCommon) }); cFinal.GetDiagnostics(); } [Fact] public void RefOmittedComCall_Basic() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, int y); } public class Ref1Impl : IRef1 { public int M(ref int x, int y) { return x + y; } } class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int ret = ref1.M(10, 10); Console.WriteLine(ret); return ret; } } "; CompileAndVerify(source, expectedOutput: @"20"); } [WorkItem(546733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546733")] [Fact] public void RefOmittedComCall_Iterator() { var source = @"using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, int y); } public class Ref1Impl : IRef1 { public int M(ref int x, int y) { return x + y; } } class Test { static IEnumerable<int> M() { IRef1 ref1 = new Ref1Impl(); int ret = ref1.M(10, 2); yield return ret; } public static void Main() { Console.WriteLine(M().First()); } }"; CompileAndVerify(source, expectedOutput: @"12"); } [Fact] public void RefOmittedComCall_ArgumentNotAddressTaken_01() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, ref int y); } public class Ref1Impl : IRef1 { public int M(ref int x, ref int y) { int ret = x + y; x = -1; y = 0; return ret; } } class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int x = 10, y = 10; int ret = ref1.M(x, ref y); Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(ret); return ret; } } "; CompileAndVerify(source, expectedOutput: @"10 0 20"); } [Fact] public void RefOmittedComCall_ArgumentNotAddressTaken_02() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, int y); } public class Ref1Impl : IRef1 { public int M(ref int x, int y) { int ret = x + y; x = 0; return ret; } } class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int x = 10, y = 10; int ret = ref1.M(x, y); Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(ret); return ret; } } "; CompileAndVerify(source, expectedOutput: @"10 10 20"); } [Fact] public void RefOmittedComCall_NamedArguments() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, ref int y); } public class Ref1Impl : IRef1 { public int M(ref int x, ref int y) { int ret = x + y; x = -1; y = 0; return ret; } } class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int y = 10; int ret = ref1.M(y: ref y, x: y); Console.WriteLine(y); Console.WriteLine(ret); return ret; } } "; CompileAndVerify(source, expectedOutput: @"0 20"); } [Fact] public void RefOmittedComCall_MethodCallArgument() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, ref int y, ref int z); } public class Ref1Impl : IRef1 { public int M(ref int x, ref int y, ref int z) { int ret = x + y + z; x = -1; y = -2; z = -3; return ret; } } class Test { public static int Goo(ref int x) { Console.WriteLine(x); x++; return x; } public static int Main() { IRef1 ref1 = new Ref1Impl(); int a = 10; int ret = ref1.M( z: Goo(ref a), // Print 10 y: ref1.M(z: ref a, y: a, x: ref a), x: Goo(ref a)); // Print -3 Console.WriteLine(a); // Print -2 Console.WriteLine(ret); // Print 42 int b = 1, c = 2; ret = ref1.M( z: Goo(ref c), // Print 2 y: ref1.M(z: ref b, y: b + c, x: b), x: Goo(ref b)); // Print -3 Console.WriteLine(b); // Print -2 Console.WriteLine(c); // Print 3 Console.WriteLine(ret); // Print 7 return ret; } } "; CompileAndVerify(source, expectedOutput: @"10 -3 -2 42 2 -3 -2 3 7"); } [Fact] public void RefOmittedComCall_AssignToRefParam() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, ref int y); } public class Ref1Impl : IRef1 { public int M(ref int x, ref int y) { x = 1; y = 2; return x + y; } } class Test { public static int Goo(ref int x) { Console.WriteLine(x); x++; return x; } public static int Main() { IRef1 ref1 = new Ref1Impl(); int a = 10; int ret = ref1.M(a, a) + ref1.M(10, 10); Console.WriteLine(ret); return ret; } } "; CompileAndVerify(source, expectedOutput: @"6"); } [Fact] public void RefOmittedComCall_ExternMethod() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public class Ref1Impl { public extern int M(ref int x, int y); } class Test { public static int Main() { var ref1 = new Ref1Impl(); int ret = ref1.M(10, 10); Console.WriteLine(ret); return ret; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(530747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530747")] public void RefOmittedComCall_Unsafe() { // Native compiler generates invalid IL for ref omitted argument of pointer type, while Roslyn generates correct IL. // See Won't Fixed Devdiv bug #16837 for details. var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] unsafe public interface IRef1 { void M(ref int* x); void M2(ref int* x, ref int* y); void M3(ref int* x, ref int* y); } unsafe public class Ref1Impl : IRef1 { public void M(ref int* x) { *x = *x + 1; x = null; } public void M2(ref int* x, ref int* y) { *y = *y + 1; } public void M3(ref int* x, ref int* y) { x = null; *y = *y + 1; } } unsafe class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int a = 1; int *p = &a; ref1.M(ref p); Console.WriteLine(a); Console.WriteLine(p == null); p = &a; ref1.M2(&a, ref p); Console.WriteLine(a); Console.WriteLine(*p); ref1.M3(p, ref p); Console.WriteLine(a); Console.WriteLine(*p); return 0; } } "; CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"2 True 3 3 4 4"); } [Fact()] public void RefOmittedComCall_ERR_ComImportWithImpl() { var source = @"using System; using System.Runtime.InteropServices; public interface IRef1 { int M(ref int x, int y); } [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public class Ref1Impl : IRef1 { public int M(ref int x, int y) { return x + y; } } class Test { public static int Main() { var ref1 = new Ref1Impl(); int ret = ref1.M(10, 10); Console.WriteLine(ret); return ret; } } "; CreateCompilation(source).VerifyDiagnostics( // (13,16): error CS0423: Since 'Ref1Impl' has the ComImport attribute, 'Ref1Impl.M(ref int, int)' must be extern or abstract // public int M(ref int x, int y) { return x + y; } Diagnostic(ErrorCode.ERR_ComImportWithImpl, "M").WithArguments("Ref1Impl.M(ref int, int)", "Ref1Impl").WithLocation(13, 16)); } [Fact] public void RefOmittedComCall_Error_NonComImportType() { var source = @"using System; using System.Runtime.InteropServices; public interface IRef1 { int M(ref int x, int y); } [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public class Ref1Impl: IRef1 { public extern int M(ref int x, int y); } class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int ret = ref1.M(10, 10); Console.WriteLine(ret); return ret; } } "; CreateCompilation(source).VerifyDiagnostics( // (21,25): error CS1620: Argument 1 must be passed with the 'ref' keyword // int ret = ref1.M(10, 10); Diagnostic(ErrorCode.ERR_BadArgRef, "10").WithArguments("1", "ref").WithLocation(21, 25)); } [Fact] public void RefOmittedComCall_Error_OutParam() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(out int x, int y); } public class Ref1Impl : IRef1 { public int M(out int x, int y) { x = 1; return y; } } class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int x; int ret = ref1.M(x, 10); Console.WriteLine(ret); return ret; } }"; CreateCompilation(source).VerifyDiagnostics( // (22,25): error CS1620: Argument 1 must be passed with the 'out' keyword // int ret = ref1.M(x, 10); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "out").WithLocation(22, 25), // (22,25): error CS0165: Use of unassigned local variable 'x' // int ret = ref1.M(x, 10); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(22, 25)); } [Fact] public void RefOmittedComCall_Error_WithinAttributeContext() { var source = @" using System; using System.Runtime.InteropServices; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class Attr: Attribute { public Attr(int x) {} } [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] class Attr2: Attribute { public Attr2(ref int x) {} } [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] [Attr(new Goo().M1(1, 1))] [Attr(Goo.M2(1, 1))] [Attr2(1)] public class Goo { public extern int M1(ref int x, int y); public static extern int M2(ref int x, int y); }"; CreateCompilation(source).VerifyDiagnostics( // (13,7): error CS0424: 'Attr2': a class with the ComImport attribute cannot specify a base class // class Attr2: Attribute Diagnostic(ErrorCode.ERR_ComImportWithBase, "Attr2").WithArguments("Attr2").WithLocation(13, 7), // (15,12): error CS0669: A class with the ComImport attribute cannot have a user-defined constructor // public Attr2(ref int x) {} Diagnostic(ErrorCode.ERR_ComImportWithUserCtor, "Attr2").WithLocation(15, 12), // (20,20): error CS1620: Argument 1 must be passed with the 'ref' keyword // [Attr(new Goo().M1(1, 1))] Diagnostic(ErrorCode.ERR_BadArgRef, "1").WithArguments("1", "ref").WithLocation(20, 20), // (21,14): error CS1620: Argument 1 must be passed with the 'ref' keyword // [Attr(Goo.M2(1, 1))] Diagnostic(ErrorCode.ERR_BadArgRef, "1").WithArguments("1", "ref").WithLocation(21, 14), // (22,8): error CS1620: Argument 1 must be passed with the 'ref' keyword // [Attr2(1)] Diagnostic(ErrorCode.ERR_BadArgRef, "1").WithArguments("1", "ref").WithLocation(22, 8)); } [Fact] public void RefOmittedComCall_CtorWithRefArgument() { var ilSource = @" .class public auto ansi import beforefieldinit Ref1 extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 41 38 38 41 31 37 35 44 2D 32 34 34 38 // ..$A88A175D-2448 2D 34 34 37 41 2D 42 37 38 36 2D 36 34 36 38 32 // -447A-B786-64682 43 42 45 46 31 35 36 00 00 ) // CBEF156.. .method public hidebysig specialname rtspecialname instance void .ctor(int32& x) runtime managed internalcall { } // end of method Ref1::.ctor } // end of class Ref1 "; var source = @" public class MainClass { public static int Main () { int x = 0; var r = new Ref1(x); return 0; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource); compilation.VerifyDiagnostics( // (7,26): error CS1620: Argument 1 must be passed with the 'ref' keyword // var r = new Ref1(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref").WithLocation(7, 26)); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122")] public void TestComImportOverloadResolutionCantOmitRef() { string source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] abstract class C { extern public void M(ref short p); extern public void M(sbyte p); } class D : C { public static void Goo() { short x = 123; sbyte s = 123; new D().M(x); C c = new D(); c.M(x); new D().M(s); } } "; CreateCompilation(source).VerifyDiagnostics( // (18,19): error CS1620: Argument 1 must be passed with the 'ref' keyword // new D().M(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref")); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122")] public void RefOmittedComCall_BaseTypeComImport() { string source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] abstract class E { extern public void M(ref short p); } class F : E { [DllImport(""goo"")] extern public void M(sbyte p); public static void Goo() { short x = 123; sbyte s = 123; new F().M(x); E e = new F(); e.M(x); new F().M(s); } } [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] abstract class G { extern public void M(sbyte p); } class H : G { extern public void M(ref short p); public static void Goo() { short x = 123; sbyte s = 123; new H().M(x); G g = new H(); g.M(x); new H().M(s); } } [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] abstract class I { } class J : I { extern public void M(sbyte p); extern public void M(ref short p); public static void Goo() { short x = 123; sbyte s = 123; new J().M(x); I i = new J(); i.M(x); new J().M(s); } } "; CreateCompilation(source).VerifyDiagnostics( // (12,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' // [DllImport("goo")] Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport"), // (20,19): error CS1503: Argument 1: cannot convert from 'short' to 'sbyte' // new F().M(x); Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "short", "sbyte"), // (36,24): warning CS0626: Method, operator, or accessor 'H.M(ref short)' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern public void M(ref short p); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("H.M(ref short)"), // (43,19): error CS1620: Argument 1 must be passed with the 'ref' keyword // new H().M(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref"), // (46,13): error CS1503: Argument 1: cannot convert from 'short' to 'sbyte' // g.M(x); Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "short", "sbyte"), // (58,24): warning CS0626: Method, operator, or accessor 'J.M(sbyte)' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern public void M(sbyte p); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("J.M(sbyte)"), // (59,24): warning CS0626: Method, operator, or accessor 'J.M(ref short)' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern public void M(ref short p); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("J.M(ref short)"), // (66,19): error CS1503: Argument 1: cannot convert from 'short' to 'sbyte' // new J().M(x); Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "short", "sbyte"), // (69,11): error CS1061: 'I' does not contain a definition for 'M' and no extension method 'M' accepting a first argument of type 'I' could be found (are you missing a using directive or an assembly reference?) // i.M(x); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("I", "M")); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122")] public void RefOmittedComCall_DerivedComImport() { string source = @" using System; using System.Runtime.InteropServices; interface A { void M(ref short p); void M(sbyte p); } [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] interface B: A { } class C: B { public void M(ref short p) {} public void M(sbyte p) {} public static void Goo() { short x = 123; sbyte s = 123; A a = new C(); B b = new C(); C c = new C(); a.M(x); b.M(x); c.M(x); a.M(s); b.M(s); c.M(s); } } "; CreateCompilation(source).VerifyDiagnostics( // (30,13): error CS1620: Argument 1 must be passed with the 'ref' keyword // a.M(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref"), // (32,13): error CS1620: Argument 1 must be passed with the 'ref' keyword // c.M(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref")); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122")] public void RefOmittedComCall_TypeParameterConstrainedToComImportType() { string source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] class K { public extern void M(ref short p); public extern void M(sbyte p); } class H<T> where T: K, new() { public static void Goo() { short x = 123; T t = new T(); t.M(x); } } "; CreateCompilation(source).VerifyDiagnostics( // (18,13): error CS1620: Argument 1 must be passed with the 'ref' keyword // t.M(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref")); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122")] public void RefOmittedComCall_StaticMethod1() { string source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] static class E { public extern static void M(ref short p); public extern static void M(sbyte p); } class Y { public static void Goo() { short x = 123; E.M(x); // Dev11 reports CS1620 (missing 'ref') } } "; // BREAK: Dev11 does not allow this, but it's probably an accident. // That is, it inspects the receiver type of the invocation and it // finds no receiver for a static method invocation. // MITIGATION: Candidates with 'ref' omitted lose tie-breakers, so // it should not be possible for this to cause overload resolution // to succeed in a different way. CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122")] public void RefOmittedComCall_StaticMethod2() { string source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] class E { public extern static void M(ref short p); } [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF137"")] class F { public extern static void M(ref short p); } class Y { public static void Main() { short x = 123; E E = null; E.M(x); // Allowed in dev11. F.M(x); // CS1620 (missing 'ref') in dev11. } } "; // BREAK: Dev11 produces an error. It doesn't make sense that the introduction // of a color-color local would eliminate an error, since it does not affect the // outcome of overload resolution. CreateCompilation(source).VerifyDiagnostics( // (22,11): warning CS0219: The variable 'E' is assigned but its value is never used // E E = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "E").WithArguments("E").WithLocation(22, 11)); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122"), WorkItem(842476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842476")] public void RefOmittedComCall_ExtensionMethod() { string source = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] class C { } static class CExtensions { public static void M(this C c, ref short p) {} public static void M(this C c, sbyte p) {} public static void I(this C c, ref int p) {} } class X { public static void Goo() { short x = 123; C c = new C(); c.M(x); c.I(123); } } "; CompileAndVerify(source); } [Fact] public void RefOmittedComCall_OverloadResolution_SingleArgument() { var source = @" using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { void M1(int x); void M1(ref int x); void M2(long x); void M2(ref int x); void M3(char x); void M3(ref int x); void M4(out uint x); void M4(ref int x); void M5(ref int x); void M5(ref long x); void M6(ref char x); void M6(ref long x); void M7(ref long x); void M7(int x); void M8(ref long x); void M8(char x); void M9(ref char x); void M9(long x); } public class Ref1Impl : IRef1 { public void M1(int x) { Console.WriteLine(1); } public void M1(ref int x) { Console.WriteLine(2); } public void M2(long x) { Console.WriteLine(3); } public void M2(ref int x) { Console.WriteLine(4); } public void M3(char x) { Console.WriteLine(5); } public void M3(ref int x) { Console.WriteLine(6); } public void M4(out uint x) { x = 0; Console.WriteLine(7); } public void M4(ref int x) { Console.WriteLine(8); } public void M5(ref int x) { Console.WriteLine(9); } public void M5(ref long x) { Console.WriteLine(10); } public void M6(ref char x) { Console.WriteLine(11); } public void M6(ref long x) { Console.WriteLine(12); } public void M7(ref long x) { Console.WriteLine(13); } public void M7(int x) { Console.WriteLine(14); } public void M8(ref long x) { Console.WriteLine(15); } public void M8(char x) { Console.WriteLine(16); } public void M9(ref char x) { Console.WriteLine(17); } public void M9(long x) { Console.WriteLine(18); } } class Test { public static void Main() { IRef1 ref1 = new Ref1Impl(); int i = 1; long l = 1; char c = 'c'; // void M1(int x); // void M1(ref int x); ref1.M1(10); //ref1.M1(10L); CS1503 ref1.M1('c'); ref1.M1(i); //ref1.M1(l); CS1503 ref1.M1(c); ref1.M1(ref i); //ref1.M1(ref l); CS1615 //ref1.M1(ref c); CS1615 // void M2(long x); // void M2(ref int x); Console.WriteLine(); ref1.M2(10); ref1.M2(10L); ref1.M2('c'); ref1.M2(i); ref1.M2(l); ref1.M2(c); ref1.M2(ref i); //ref1.M2(ref l); CS1615 //ref1.M2(ref c); CS1615 // void M3(char x); // void M3(ref int x); Console.WriteLine(); ref1.M3(10); //ref1.M3(10L); CS1503 ref1.M3('c'); ref1.M3(i); //ref1.M3(l); CS1503 ref1.M3(c); ref1.M3(ref i); //ref1.M3(ref l); CS1615 //ref1.M3(ref c); CS1615 // void M4(out uint x); // void M4(ref int x); Console.WriteLine(); ref1.M4(10); //ref1.M4(10L); CS1620 ref1.M4('c'); ref1.M4(i); //ref1.M4(l); CS1620 ref1.M4(c); ref1.M4(ref i); //ref1.M4(ref l); CS1620 //ref1.M4(ref c); CS1620 // void M5(ref int x); // void M5(ref long x); Console.WriteLine(); //ref1.M5(10); CS0121 ref1.M5(10L); //ref1.M5('c'); CS0121 //ref1.M5(i); CS0121 ref1.M5(l); //ref1.M5(c); CS0121 ref1.M5(ref i); ref1.M5(ref l); //ref1.M5(ref c); CS1503 // void M6(ref char x); // void M6(ref long x); Console.WriteLine(); ref1.M6(10); ref1.M6(10L); //ref1.M6('c'); CS0121 ref1.M6(i); ref1.M6(l); //ref1.M6(c); CS0121 //ref1.M6(ref i); CS1503 ref1.M6(ref l); ref1.M6(ref c); // void M7(ref long x); // void M7(int x); Console.WriteLine(); ref1.M7(10); ref1.M7(10L); ref1.M7('c'); ref1.M7(i); ref1.M7(l); ref1.M7(c); //ref1.M7(ref i); CS1503 ref1.M7(ref l); //ref1.M7(ref c); CS1503 // void M8(ref long x); // void M8(char x); Console.WriteLine(); ref1.M8(10); ref1.M8(10L); ref1.M8('c'); ref1.M8(i); ref1.M8(l); ref1.M8(c); //ref1.M8(ref i); CS1503 ref1.M8(ref l); //ref1.M8(ref c); CS1503 // void M9(ref char x); // void M9(long x); Console.WriteLine(); ref1.M9(10); ref1.M9(10L); ref1.M9('c'); ref1.M9(i); ref1.M9(l); ref1.M9(c); //ref1.M9(ref i); CS1503 //ref1.M9(ref l); CS1503 ref1.M9(ref c); } } "; CompileAndVerify(source, expectedOutput: @"1 1 1 1 2 3 3 3 3 3 3 4 6 5 6 5 6 8 8 8 8 8 10 10 9 10 12 12 12 12 12 11 14 13 14 14 13 14 13 15 15 16 15 15 16 15 18 18 18 18 18 18 17"); } [Fact] public void RefOmittedComCall_OverloadResolution_SingleArgument_ErrorCases() { var source = @" using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { void M1(int x); void M1(ref int x); void M2(long x); void M2(ref int x); void M3(char x); void M3(ref int x); void M4(out uint x); void M4(ref int x); void M5(ref int x); void M5(ref long x); void M6(ref char x); void M6(ref long x); void M7(ref long x); void M7(int x); void M8(ref long x); void M8(char x); void M9(ref char x); void M9(long x); } public class Ref1Impl : IRef1 { public void M1(int x) { Console.WriteLine(1); } public void M1(ref int x) { Console.WriteLine(2); } public void M2(long x) { Console.WriteLine(3); } public void M2(ref int x) { Console.WriteLine(4); } public void M3(char x) { Console.WriteLine(5); } public void M3(ref int x) { Console.WriteLine(6); } public void M4(out uint x) { x = 0; Console.WriteLine(7); } public void M4(ref int x) { Console.WriteLine(8); } public void M5(ref int x) { Console.WriteLine(9); } public void M5(ref long x) { Console.WriteLine(10); } public void M6(ref char x) { Console.WriteLine(11); } public void M6(ref long x) { Console.WriteLine(12); } public void M7(ref long x) { Console.WriteLine(13); } public void M7(int x) { Console.WriteLine(14); } public void M8(ref long x) { Console.WriteLine(15); } public void M8(char x) { Console.WriteLine(16); } public void M9(ref char x) { Console.WriteLine(17); } public void M9(long x) { Console.WriteLine(18); } } class Test { public static void Main() { IRef1 ref1 = new Ref1Impl(); int i = 1; long l = 1; char c = 'c'; // void M1(int x); // void M1(ref int x); ref1.M1(10L); // CS1503 ref1.M1(l); // CS1503 ref1.M1(ref l); // CS1615 ref1.M1(ref c); // CS1615 // void M2(long x); // void M2(ref int x); Console.WriteLine(); ref1.M2(ref l); // CS1615 ref1.M2(ref c); // CS1615 // void M3(char x); // void M3(ref int x); Console.WriteLine(); ref1.M3(10L); // CS1503 ref1.M3(l); // CS1503 ref1.M3(ref l); // CS1615 ref1.M3(ref c); // CS1615 // void M4(out uint x); // void M4(ref int x); Console.WriteLine(); ref1.M4(10L); // CS1620 ref1.M4(l); // CS1620 ref1.M4(ref l); // CS1620 ref1.M4(ref c); // CS1620 // void M5(ref int x); // void M5(ref long x); Console.WriteLine(); ref1.M5(10); // CS0121 ref1.M5('c'); // CS0121 ref1.M5(i); // CS0121 ref1.M5(c); // CS0121 ref1.M5(ref c); // CS1503 // void M6(ref char x); // void M6(ref long x); Console.WriteLine(); ref1.M6('c'); // CS0121 ref1.M6(c); // CS0121 ref1.M6(ref i); // CS1503 // void M7(ref long x); // void M7(int x); Console.WriteLine(); ref1.M7(ref i); // CS1503 ref1.M7(ref c); // CS1503 // void M8(ref long x); // void M8(char x); Console.WriteLine(); ref1.M8(ref i); // CS1503 ref1.M8(ref c); // CS1503 // void M9(ref char x); // void M9(long x); Console.WriteLine(); ref1.M9(ref i); // CS1503 ref1.M9(ref l); // CS1503 } } "; CreateCompilation(source).VerifyDiagnostics( // (79,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M1(10L); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "10L").WithArguments("1", "long", "int"), // (80,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M1(l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (81,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (82,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (89,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (90,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (97,16): error CS1503: Argument 1: cannot convert from 'long' to 'char' // ref1.M3(10L); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "10L").WithArguments("1", "long", "char"), // (98,16): error CS1503: Argument 1: cannot convert from 'long' to 'char' // ref1.M3(l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "char"), // (99,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M3(ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (100,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M3(ref c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (107,16): error CS1620: Argument 1 must be passed with the 'out' keyword // ref1.M4(10L); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "10L").WithArguments("1", "out"), // (108,16): error CS1620: Argument 1 must be passed with the 'out' keyword // ref1.M4(l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "out"), // (109,20): error CS1620: Argument 1 must be passed with the 'out' keyword // ref1.M4(ref l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "out"), // (110,20): error CS1620: Argument 1 must be passed with the 'out' keyword // ref1.M4(ref c); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "c").WithArguments("1", "out"), // (117,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M5(ref int)' and 'IRef1.M5(ref long)' // ref1.M5(10); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M5").WithArguments("IRef1.M5(ref int)", "IRef1.M5(ref long)"), // (118,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M5(ref int)' and 'IRef1.M5(ref long)' // ref1.M5('c'); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M5").WithArguments("IRef1.M5(ref int)", "IRef1.M5(ref long)"), // (119,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M5(ref int)' and 'IRef1.M5(ref long)' // ref1.M5(i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M5").WithArguments("IRef1.M5(ref int)", "IRef1.M5(ref long)"), // (120,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M5(ref int)' and 'IRef1.M5(ref long)' // ref1.M5(c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M5").WithArguments("IRef1.M5(ref int)", "IRef1.M5(ref long)"), // (121,20): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref int' // ref1.M5(ref c); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref int"), // (128,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M6(ref char)' and 'IRef1.M6(ref long)' // ref1.M6('c'); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("IRef1.M6(ref char)", "IRef1.M6(ref long)"), // (129,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M6(ref char)' and 'IRef1.M6(ref long)' // ref1.M6(c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("IRef1.M6(ref char)", "IRef1.M6(ref long)"), // (130,20): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref char' // ref1.M6(ref i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref char"), // (137,20): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // ref1.M7(ref i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (138,20): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // ref1.M7(ref c); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (145,20): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // ref1.M8(ref i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (146,20): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // ref1.M8(ref c); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (153,20): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref char' // ref1.M9(ref i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref char"), // (154,20): error CS1503: Argument 1: cannot convert from 'ref long' to 'ref char' // ref1.M9(ref l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "ref long", "ref char")); } [Fact, WorkItem(546176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546176")] public void RefOmittedComCall_OverloadResolution_SingleArgument_IndexedProperties() { var source1 = @" .class interface public abstract import IA { .custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 ) .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 ) .property instance int32 P1(int32) { .get instance int32 IA::get_P1(int32) .set instance void IA::set_P1(int32, int32) } .property instance int32 P1(int32&) { .get instance int32 IA::get_P1(int32&) .set instance void IA::set_P1(int32&, int32) } .method public abstract virtual instance int32 get_P1(int32 i) { } .method public abstract virtual instance void set_P1(int32 i, int32 v) { } .method public abstract virtual instance int32 get_P1(int32& i) { } .method public abstract virtual instance void set_P1(int32& i, int32 v) { } .property instance int32 P2(int64) { .get instance int32 IA::get_P2(int64) .set instance void IA::set_P2(int64, int32) } .property instance int32 P2(int32&) { .get instance int32 IA::get_P2(int32&) .set instance void IA::set_P2(int32&, int32) } .method public abstract virtual instance int32 get_P2(int64 i) { } .method public abstract virtual instance void set_P2(int64 i, int32 v) { } .method public abstract virtual instance int32 get_P2(int32& i) { } .method public abstract virtual instance void set_P2(int32& i, int32 v) { } .property instance int32 P3(char) { .get instance int32 IA::get_P3(char) .set instance void IA::set_P3(char, int32) } .property instance int32 P3(int32&) { .get instance int32 IA::get_P3(int32&) .set instance void IA::set_P3(int32&, int32) } .method public abstract virtual instance int32 get_P3(char i) { } .method public abstract virtual instance void set_P3(char i, int32 v) { } .method public abstract virtual instance int32 get_P3(int32& i) { } .method public abstract virtual instance void set_P3(int32& i, int32 v) { } .property instance int32 P4(int64&) { .get instance int32 IA::get_P4(int64&) .set instance void IA::set_P4(int64&, int32) } .property instance int32 P4(int32&) { .get instance int32 IA::get_P4(int32&) .set instance void IA::set_P4(int32&, int32) } .method public abstract virtual instance int32 get_P4(int64& i) { } .method public abstract virtual instance void set_P4(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P4(int32& i) { } .method public abstract virtual instance void set_P4(int32& i, int32 v) { } .property instance int32 P5(int64&) { .get instance int32 IA::get_P5(int64&) .set instance void IA::set_P5(int64&, int32) } .property instance int32 P5(char&) { .get instance int32 IA::get_P5(char&) .set instance void IA::set_P5(char&, int32) } .method public abstract virtual instance int32 get_P5(int64& i) { } .method public abstract virtual instance void set_P5(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P5(char& i) { } .method public abstract virtual instance void set_P5(char& i, int32 v) { } .property instance int32 P6(int64&) { .get instance int32 IA::get_P6(int64&) .set instance void IA::set_P6(int64&, int32) } .property instance int32 P6(int32) { .get instance int32 IA::get_P6(int32) .set instance void IA::set_P6(int32, int32) } .method public abstract virtual instance int32 get_P6(int64& i) { } .method public abstract virtual instance void set_P6(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P6(int32 i) { } .method public abstract virtual instance void set_P6(int32 i, int32 v) { } .property instance int32 P7(int64&) { .get instance int32 IA::get_P7(int64&) .set instance void IA::set_P7(int64&, int32) } .property instance int32 P7(char) { .get instance int32 IA::get_P7(char) .set instance void IA::set_P7(char, int32) } .method public abstract virtual instance int32 get_P7(int64& i) { } .method public abstract virtual instance void set_P7(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P7(char i) { } .method public abstract virtual instance void set_P7(char i, int32 v) { } .property instance int32 P8(int64) { .get instance int32 IA::get_P8(int64) .set instance void IA::set_P8(int64, int32) } .property instance int32 P8(char&) { .get instance int32 IA::get_P8(char&) .set instance void IA::set_P8(char&, int32) } .method public abstract virtual instance int32 get_P8(int64 i) { } .method public abstract virtual instance void set_P8(int64 i, int32 v) { } .method public abstract virtual instance int32 get_P8(char& i) { } .method public abstract virtual instance void set_P8(char& i, int32 v) { } } .class public A implements IA { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .property instance int32 P1(int32) { .get instance int32 A::get_P1(int32) .set instance void A::set_P1(int32, int32) } .property instance int32 P1(int32&) { .get instance int32 A::get_P1(int32&) .set instance void A::set_P1(int32&, int32) } .method public virtual instance int32 get_P1(int32 i) { ldc.i4.1 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P1(int32 i, int32 v) { ldc.i4.2 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P1(int32& i) { ldc.i4.3 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P1(int32& i, int32 v) { ldc.i4.4 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P2(int64) { .get instance int32 A::get_P2(int64) .set instance void A::set_P2(int64, int32) } .property instance int32 P2(int32&) { .get instance int32 A::get_P2(int32&) .set instance void A::set_P2(int32&, int32) } .method public virtual instance int32 get_P2(int64 i) { ldc.i4.5 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P2(int64 i, int32 v) { ldc.i4.6 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P2(int32& i) { ldc.i4.7 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P2(int32& i, int32 v) { ldc.i4.8 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P3(char) { .get instance int32 A::get_P3(char) .set instance void A::set_P3(char, int32) } .property instance int32 P3(int32&) { .get instance int32 A::get_P3(int32&) .set instance void A::set_P3(int32&, int32) } .method public virtual instance int32 get_P3(char i) { ldc.i4.s 9 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P3(char i, int32 v) { ldc.i4.s 10 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P3(int32& i) { ldc.i4.s 11 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P3(int32& i, int32 v) { ldc.i4.s 12 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P4(int64&) { .get instance int32 A::get_P4(int64&) .set instance void A::set_P4(int64&, int32) } .property instance int32 P4(int32&) { .get instance int32 A::get_P4(int32&) .set instance void A::set_P4(int32&, int32) } .method public virtual instance int32 get_P4(int64& i) { ldc.i4.s 13 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P4(int64& i, int32 v) { ldc.i4.s 14 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P4(int32& i) { ldc.i4.s 15 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P4(int32& i, int32 v) { ldc.i4.s 16 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P5(int64&) { .get instance int32 A::get_P5(int64&) .set instance void A::set_P5(int64&, int32) } .property instance int32 P5(char&) { .get instance int32 A::get_P5(char&) .set instance void A::set_P5(char&, int32) } .method public virtual instance int32 get_P5(int64& i) { ldc.i4.s 17 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P5(int64& i, int32 v) { ldc.i4.s 18 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P5(char& i) { ldc.i4.s 19 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P5(char& i, int32 v) { ldc.i4.s 20 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P6(int64&) { .get instance int32 A::get_P6(int64&) .set instance void A::set_P6(int64&, int32) } .property instance int32 P6(int32) { .get instance int32 A::get_P6(int32) .set instance void A::set_P6(int32, int32) } .method public virtual instance int32 get_P6(int64& i) { ldc.i4.s 21 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P6(int64& i, int32 v) { ldc.i4.s 22 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P6(int32 i) { ldc.i4.s 23 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P6(int32 i, int32 v) { ldc.i4.s 24 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P7(int64&) { .get instance int32 A::get_P7(int64&) .set instance void A::set_P7(int64&, int32) } .property instance int32 P7(char) { .get instance int32 A::get_P7(char) .set instance void A::set_P7(char, int32) } .method public virtual instance int32 get_P7(int64& i) { ldc.i4.s 25 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P7(int64& i, int32 v) { ldc.i4.s 26 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P7(char i) { ldc.i4.s 27 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P7(char i, int32 v) { ldc.i4.s 28 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P8(int64) { .get instance int32 A::get_P8(int64) .set instance void A::set_P8(int64, int32) } .property instance int32 P8(char&) { .get instance int32 A::get_P8(char&) .set instance void A::set_P8(char&, int32) } .method public virtual instance int32 get_P8(int64 i) { ldc.i4.s 29 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P8(int64 i, int32 v) { ldc.i4.s 30 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P8(char& i) { ldc.i4.s 31 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P8(char& i, int32 v) { ldc.i4.s 32 call void [mscorlib]System.Console::WriteLine(int32) ret } } "; var source2 = @" using System; using System.Runtime.InteropServices; class Test { public static void Main() { IA a = new A(); int i = 1; long l = 1; char c = 'c'; int value; // int P1(int) { get; set; } // int P1(ref int) { get; set; } value = a.P1[10]; a.P1[10] = value; //value = a.P1[10L]; CS1503 //a.P1[10L] = value; CS1503 value = a.P1['c']; a.P1['c'] = value; value = a.P1[i]; a.P1[i] = value; //value = a.P1[l]; CS1503 //a.P1[l] = value; CS1503 value = a.P1[c]; a.P1[c] = value; value = a.P1[ref i]; a.P1[ref i] = value; //value = a.P1[ref l]; CS1615 //a.P1[ref l] = value; CS1615 //value = a.P1[ref c]; CS1615 //a.P1[ref c] = value; CS1615 // int P2(long) { get; set; } // int P2(ref int) { get; set; } Console.WriteLine(); value = a.P2[10]; a.P2[10] = value; value = a.P2[10L]; a.P2[10L] = value; value = a.P2['c']; a.P2['c'] = value; value = a.P2[i]; a.P2[i] = value; value = a.P2[l]; a.P2[l] = value; value = a.P2[c]; a.P2[c] = value; value = a.P2[ref i]; a.P2[ref i] = value; //value = a.P2[ref l]; CS1615 //a.P2[ref l] = value; CS1615 //value = a.P2[ref c]; CS1615 //a.P2[ref c] = value; CS1615 // int P3(char) { get; set; } // int P3(ref int) { get; set; } Console.WriteLine(); value = a.P3[10]; a.P3[10] = value; //value = a.P3[10L]; CS1503 //a.P3[10L] = value; CS1503 value = a.P3['c']; a.P3['c'] = value; value = a.P3[i]; a.P3[i] = value; //value = a.P3[l]; CS1503 //a.P3[l] = value; CS1503 value = a.P3[c]; a.P3[c] = value; value = a.P3[ref i]; a.P3[ref i] = value; //value = a.P3[ref l]; CS1615 //a.P3[ref l] = value; CS1615 //value = a.P3[ref c]; CS1615 //a.P3[ref c] = value; CS1615 // int P4(ref int) { get; set; } // int P4(ref long) { get; set; } Console.WriteLine(); //value = a.P4[10]; CS0121 //a.P4[10] = value; CS0121 value = a.P4[10L]; a.P4[10L] = value; //value = a.P4['c']; CS0121 //a.P4['c'] = value; CS0121 //value = a.P4[i]; CS0121 //a.P4[i] = value; CS0121 value = a.P4[l]; a.P4[l] = value; //value = a.P4[c]; CS0121 //a.P4[c] = value; CS0121 value = a.P4[ref i]; a.P4[ref i] = value; value = a.P4[ref l]; a.P4[ref l] = value; //value = a.P4[ref c]; CS1503 //a.P4[ref c] = value; CS1503 // int P5(ref char) { get; set; } // int P5(ref long) { get; set; } Console.WriteLine(); value = a.P5[10]; a.P5[10] = value; value = a.P5[10L]; a.P5[10L] = value; //value = a.P5['c']; CS0121 //a.P5['c'] = value; CS0121 value = a.P5[i]; a.P5[i] = value; value = a.P5[l]; a.P5[l] = value; //value = a.P5[c]; CS0121 //a.P5[c] = value; CS0121 //value = a.P5[ref i]; CS1503 //a.P5[ref i] = value; CS1503 value = a.P5[ref l]; a.P5[ref l] = value; value = a.P5[ref c]; a.P5[ref c] = value; // int P6(ref long) { get; set; } // int P6(int) { get; set; } Console.WriteLine(); value = a.P6[10]; a.P6[10] = value; value = a.P6[10L]; a.P6[10L] = value; value = a.P6['c']; a.P6['c'] = value; value = a.P6[i]; a.P6[i] = value; value = a.P6[l]; a.P6[l] = value; value = a.P6[c]; a.P6[c] = value; //value = a.P6[ref i]; CS1503 //a.P6[ref i] = value; CS1503 value = a.P6[ref l]; a.P6[ref l] = value; //value = a.P6[ref c]; CS1503 //a.P6[ref c] = value; CS1503 // int P7(ref long) { get; set; } // int P7(char) { get; set; } Console.WriteLine(); value = a.P7[10]; a.P7[10] = value; value = a.P7[10L]; a.P7[10L] = value; value = a.P7['c']; a.P7['c'] = value; value = a.P7[i]; a.P7[i] = value; value = a.P7[l]; a.P7[l] = value; value = a.P7[c]; a.P7[c] = value; //value = a.P7[ref i]; CS1503 //a.P7[ref i] = value; CS1503 value = a.P7[ref l]; a.P7[ref l] = value; //value = a.P7[ref c]; CS1503 //a.P7[ref c] = value; CS1503 // int P8(ref char) { get; set; } // int P8(long) { get; set; } Console.WriteLine(); value = a.P8[10]; a.P8[10] = value; value = a.P8[10L]; a.P8[10L] = value; value = a.P8['c']; a.P8['c'] = value; value = a.P8[i]; a.P8[i] = value; value = a.P8[l]; a.P8[l] = value; value = a.P8[c]; a.P8[c] = value; //value = a.P8[ref i]; CS1615 //a.P8[ref i] = value; CS1615 //value = a.P8[ref l]; CS1615 //a.P8[ref l] = value; CS1615 value = a.P8[ref c]; a.P8[ref c] = value; } } "; var expectedOutput = @"1 2 1 2 1 2 1 2 3 4 5 6 5 6 5 6 5 6 5 6 5 6 7 8 11 12 9 10 11 12 9 10 11 12 13 14 13 14 15 16 13 14 17 18 17 18 17 18 17 18 17 18 19 20 23 24 21 22 23 24 23 24 21 22 23 24 21 22 25 26 25 26 27 28 25 26 25 26 27 28 25 26 29 30 29 30 29 30 29 30 29 30 29 30 31 32"; var compilation = CreateCompilationWithILAndMscorlib40(source2, source1, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(546176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546176")] public void RefOmittedComCall_OverloadResolution_SingleArgument_IndexedProperties_ErrorCases() { var source1 = @" .class interface public abstract import IA { .custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 ) .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 ) .property instance int32 P1(int32) { .get instance int32 IA::get_P1(int32) .set instance void IA::set_P1(int32, int32) } .property instance int32 P1(int32&) { .get instance int32 IA::get_P1(int32&) .set instance void IA::set_P1(int32&, int32) } .method public abstract virtual instance int32 get_P1(int32 i) { } .method public abstract virtual instance void set_P1(int32 i, int32 v) { } .method public abstract virtual instance int32 get_P1(int32& i) { } .method public abstract virtual instance void set_P1(int32& i, int32 v) { } .property instance int32 P2(int64) { .get instance int32 IA::get_P2(int64) .set instance void IA::set_P2(int64, int32) } .property instance int32 P2(int32&) { .get instance int32 IA::get_P2(int32&) .set instance void IA::set_P2(int32&, int32) } .method public abstract virtual instance int32 get_P2(int64 i) { } .method public abstract virtual instance void set_P2(int64 i, int32 v) { } .method public abstract virtual instance int32 get_P2(int32& i) { } .method public abstract virtual instance void set_P2(int32& i, int32 v) { } .property instance int32 P3(char) { .get instance int32 IA::get_P3(char) .set instance void IA::set_P3(char, int32) } .property instance int32 P3(int32&) { .get instance int32 IA::get_P3(int32&) .set instance void IA::set_P3(int32&, int32) } .method public abstract virtual instance int32 get_P3(char i) { } .method public abstract virtual instance void set_P3(char i, int32 v) { } .method public abstract virtual instance int32 get_P3(int32& i) { } .method public abstract virtual instance void set_P3(int32& i, int32 v) { } .property instance int32 P4(int64&) { .get instance int32 IA::get_P4(int64&) .set instance void IA::set_P4(int64&, int32) } .property instance int32 P4(int32&) { .get instance int32 IA::get_P4(int32&) .set instance void IA::set_P4(int32&, int32) } .method public abstract virtual instance int32 get_P4(int64& i) { } .method public abstract virtual instance void set_P4(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P4(int32& i) { } .method public abstract virtual instance void set_P4(int32& i, int32 v) { } .property instance int32 P5(int64&) { .get instance int32 IA::get_P5(int64&) .set instance void IA::set_P5(int64&, int32) } .property instance int32 P5(char&) { .get instance int32 IA::get_P5(char&) .set instance void IA::set_P5(char&, int32) } .method public abstract virtual instance int32 get_P5(int64& i) { } .method public abstract virtual instance void set_P5(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P5(char& i) { } .method public abstract virtual instance void set_P5(char& i, int32 v) { } .property instance int32 P6(int64&) { .get instance int32 IA::get_P6(int64&) .set instance void IA::set_P6(int64&, int32) } .property instance int32 P6(int32) { .get instance int32 IA::get_P6(int32) .set instance void IA::set_P6(int32, int32) } .method public abstract virtual instance int32 get_P6(int64& i) { } .method public abstract virtual instance void set_P6(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P6(int32 i) { } .method public abstract virtual instance void set_P6(int32 i, int32 v) { } .property instance int32 P7(int64&) { .get instance int32 IA::get_P7(int64&) .set instance void IA::set_P7(int64&, int32) } .property instance int32 P7(char) { .get instance int32 IA::get_P7(char) .set instance void IA::set_P7(char, int32) } .method public abstract virtual instance int32 get_P7(int64& i) { } .method public abstract virtual instance void set_P7(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P7(char i) { } .method public abstract virtual instance void set_P7(char i, int32 v) { } .property instance int32 P8(int64) { .get instance int32 IA::get_P8(int64) .set instance void IA::set_P8(int64, int32) } .property instance int32 P8(char&) { .get instance int32 IA::get_P8(char&) .set instance void IA::set_P8(char&, int32) } .method public abstract virtual instance int32 get_P8(int64 i) { } .method public abstract virtual instance void set_P8(int64 i, int32 v) { } .method public abstract virtual instance int32 get_P8(char& i) { } .method public abstract virtual instance void set_P8(char& i, int32 v) { } } .class public A implements IA { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .property instance int32 P1(int32) { .get instance int32 A::get_P1(int32) .set instance void A::set_P1(int32, int32) } .property instance int32 P1(int32&) { .get instance int32 A::get_P1(int32&) .set instance void A::set_P1(int32&, int32) } .method public virtual instance int32 get_P1(int32 i) { ldc.i4.1 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P1(int32 i, int32 v) { ldc.i4.2 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P1(int32& i) { ldc.i4.3 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P1(int32& i, int32 v) { ldc.i4.4 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P2(int64) { .get instance int32 A::get_P2(int64) .set instance void A::set_P2(int64, int32) } .property instance int32 P2(int32&) { .get instance int32 A::get_P2(int32&) .set instance void A::set_P2(int32&, int32) } .method public virtual instance int32 get_P2(int64 i) { ldc.i4.5 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P2(int64 i, int32 v) { ldc.i4.6 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P2(int32& i) { ldc.i4.7 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P2(int32& i, int32 v) { ldc.i4.8 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P3(char) { .get instance int32 A::get_P3(char) .set instance void A::set_P3(char, int32) } .property instance int32 P3(int32&) { .get instance int32 A::get_P3(int32&) .set instance void A::set_P3(int32&, int32) } .method public virtual instance int32 get_P3(char i) { ldc.i4.s 9 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P3(char i, int32 v) { ldc.i4.s 10 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P3(int32& i) { ldc.i4.s 11 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P3(int32& i, int32 v) { ldc.i4.s 12 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P4(int64&) { .get instance int32 A::get_P4(int64&) .set instance void A::set_P4(int64&, int32) } .property instance int32 P4(int32&) { .get instance int32 A::get_P4(int32&) .set instance void A::set_P4(int32&, int32) } .method public virtual instance int32 get_P4(int64& i) { ldc.i4.s 13 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P4(int64& i, int32 v) { ldc.i4.s 14 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P4(int32& i) { ldc.i4.s 15 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P4(int32& i, int32 v) { ldc.i4.s 16 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P5(int64&) { .get instance int32 A::get_P5(int64&) .set instance void A::set_P5(int64&, int32) } .property instance int32 P5(char&) { .get instance int32 A::get_P5(char&) .set instance void A::set_P5(char&, int32) } .method public virtual instance int32 get_P5(int64& i) { ldc.i4.s 17 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P5(int64& i, int32 v) { ldc.i4.s 18 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P5(char& i) { ldc.i4.s 19 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P5(char& i, int32 v) { ldc.i4.s 20 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P6(int64&) { .get instance int32 A::get_P6(int64&) .set instance void A::set_P6(int64&, int32) } .property instance int32 P6(int32) { .get instance int32 A::get_P6(int32) .set instance void A::set_P6(int32, int32) } .method public virtual instance int32 get_P6(int64& i) { ldc.i4.s 21 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P6(int64& i, int32 v) { ldc.i4.s 22 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P6(int32 i) { ldc.i4.s 23 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P6(int32 i, int32 v) { ldc.i4.s 24 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P7(int64&) { .get instance int32 A::get_P7(int64&) .set instance void A::set_P7(int64&, int32) } .property instance int32 P7(char) { .get instance int32 A::get_P7(char) .set instance void A::set_P7(char, int32) } .method public virtual instance int32 get_P7(int64& i) { ldc.i4.s 25 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P7(int64& i, int32 v) { ldc.i4.s 26 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P7(char i) { ldc.i4.s 27 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P7(char i, int32 v) { ldc.i4.s 28 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P8(int64) { .get instance int32 A::get_P8(int64) .set instance void A::set_P8(int64, int32) } .property instance int32 P8(char&) { .get instance int32 A::get_P8(char&) .set instance void A::set_P8(char&, int32) } .method public virtual instance int32 get_P8(int64 i) { ldc.i4.s 29 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P8(int64 i, int32 v) { ldc.i4.s 30 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P8(char& i) { ldc.i4.s 31 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P8(char& i, int32 v) { ldc.i4.s 32 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } } "; var source2 = @" class Test { public static void Main() { IA a = new A(); int i = 1; long l = 1; char c = 'c'; int value; // int P1(int) { get; set; } // int P1(ref int) { get; set; } value = a.P1[10L]; // CS1503 a.P1[10L] = value; // CS1503 value = a.P1[l]; // CS1503 a.P1[l] = value; // CS1503 value = a.P1[ref l]; // CS1615 a.P1[ref l] = value; // CS1615 value = a.P1[ref c]; // CS1615 a.P1[ref c] = value; // CS1615 // int P2(long) { get; set; } // int P2(ref int) { get; set; } value = a.P2[ref l]; // CS1615 a.P2[ref l] = value; // CS1615 value = a.P2[ref c]; // CS1615 a.P2[ref c] = value; // CS1615 // int P3(char) { get; set; } // int P3(ref int) { get; set; } value = a.P3[10L]; // CS1503 a.P3[10L] = value; // CS1503 value = a.P3[l]; // CS1503 a.P3[l] = value; // CS1503 value = a.P3[ref l]; // CS1615 a.P3[ref l] = value; // CS1615 value = a.P3[ref c]; // CS1615 a.P3[ref c] = value; // CS1615 // int P4(ref int) { get; set; } // int P4(ref long) { get; set; } value = a.P4[10]; // CS0121 a.P4[10] = value; // CS0121 value = a.P4['c']; // CS0121 a.P4['c'] = value; // CS0121 value = a.P4[i]; // CS0121 a.P4[i] = value; // CS0121 value = a.P4[c]; // CS0121 a.P4[c] = value; // CS0121 value = a.P4[ref c]; // CS1503 a.P4[ref c] = value; // CS1503 // int P5(ref char) { get; set; } // int P5(ref long) { get; set; } value = a.P5['c']; // CS0121 a.P5['c'] = value; // CS0121 value = a.P5[c]; // CS0121 a.P5[c] = value; // CS0121 value = a.P5[ref i]; // CS1503 a.P5[ref i] = value; // CS1503 // int P6(ref long) { get; set; } // int P6(int) { get; set; } value = a.P6[ref i]; // CS1503 a.P6[ref i] = value; // CS1503 value = a.P6[ref c]; // CS1503 a.P6[ref c] = value; // CS1503 // int P7(ref long) { get; set; } // int P7(char) { get; set; } value = a.P7[ref i]; // CS1503 a.P7[ref i] = value; // CS1503 value = a.P7[ref c]; // CS1503 a.P7[ref c] = value; // CS1503 // int P8(ref char) { get; set; } // int P8(long) { get; set; } value = a.P8[ref i]; // CS1615 a.P8[ref i] = value; // CS1615 value = a.P8[ref l]; // CS1615 a.P8[ref l] = value; // CS1615 } } "; CreateCompilationWithILAndMscorlib40(source2, source1).VerifyDiagnostics( // (15,21): error CS1503: Argument 1: cannot convert from 'long' to 'int' // value = a.P1[10L]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "10L").WithArguments("1", "long", "int"), // (16,13): error CS1503: Argument 1: cannot convert from 'long' to 'int' // a.P1[10L] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "10L").WithArguments("1", "long", "int"), // (17,21): error CS1503: Argument 1: cannot convert from 'long' to 'int' // value = a.P1[l]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (18,13): error CS1503: Argument 1: cannot convert from 'long' to 'int' // a.P1[l] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (19,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P1[ref l]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (20,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P1[ref l] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (21,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P1[ref c]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (22,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P1[ref c] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (27,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P2[ref l]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (28,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P2[ref l] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (29,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P2[ref c]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (30,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P2[ref c] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (35,21): error CS1503: Argument 1: cannot convert from 'long' to 'char' // value = a.P3[10L]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "10L").WithArguments("1", "long", "char"), // (36,13): error CS1503: Argument 1: cannot convert from 'long' to 'char' // a.P3[10L] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "10L").WithArguments("1", "long", "char"), // (37,21): error CS1503: Argument 1: cannot convert from 'long' to 'char' // value = a.P3[l]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "char"), // (38,13): error CS1503: Argument 1: cannot convert from 'long' to 'char' // a.P3[l] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "char"), // (39,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P3[ref l]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (40,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P3[ref l] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (41,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P3[ref c]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (42,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P3[ref c] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (47,16): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // value = a.P4[10]; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4[10]").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (58,8): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // a.P4[10] = value; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4[10]").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (49,16): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // value = a.P4['c']; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4['c']").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (50,8): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // a.P4['c'] = value; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4['c']").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (51,16): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // value = a.P4[i]; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4[i]").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (52,8): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // a.P4[i] = value; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4[i]").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (53,16): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // value = a.P4[c]; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4[c]").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (54,8): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // a.P4[c] = value; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4[c]").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (55,25): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // value = a.P4[ref c]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (56,17): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // a.P4[ref c] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (61,16): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P5[ref long]' and 'IA.P5[ref char]' // value = a.P5['c']; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P5['c']").WithArguments("IA.P5[ref long]", "IA.P5[ref char]"), // (62,8): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P5[ref long]' and 'IA.P5[ref char]' // a.P5['c'] = value; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P5['c']").WithArguments("IA.P5[ref long]", "IA.P5[ref char]"), // (63,16): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P5[ref long]' and 'IA.P5[ref char]' // value = a.P5[c]; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P5[c]").WithArguments("IA.P5[ref long]", "IA.P5[ref char]"), // (64,8): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P5[ref long]' and 'IA.P5[ref char]' // a.P5[c] = value; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P5[c]").WithArguments("IA.P5[ref long]", "IA.P5[ref char]"), // (65,25): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // value = a.P5[ref i]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (66,17): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // a.P5[ref i] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (71,25): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // value = a.P6[ref i]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (72,17): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // a.P6[ref i] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (73,25): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // value = a.P6[ref c]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (74,17): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // a.P6[ref c] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (79,25): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // value = a.P7[ref i]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (80,17): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // a.P7[ref i] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (81,25): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // value = a.P7[ref c]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (82,17): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // a.P7[ref c] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (87,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P8[ref i]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (88,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P8[ref i] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (89,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P8[ref l]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (90,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P8[ref l] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref")); } [Fact] public void RefOmittedComCall_OverloadResolution_MultipleArguments() { var source = @" using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { void M1(int x, long y); void M1(ref int x, int y); void M2(int x, char y); void M2(ref int x, int y); void M3(ref int x, char y); void M3(ref long x, int y); void M4(ref int x, long y); void M4(ref int x, ref int y); void M5(ref int x, char y); void M5(ref long x, int y); void M6(ref int x, int y); void M6(ref long x, int y); void M7(ref int x, long y); void M7(ref long x, ref int y); void M8(long x, ref int y); void M8(ref long x, int y); void M9(ref long x, ref int y); void M9(ref int x, ref long y); } public class Ref1Impl : IRef1 { public void M1(int x, long y) { Console.WriteLine(1); } public void M1(ref int x, int y) { Console.WriteLine(2); } public void M2(int x, char y) { Console.WriteLine(3); } public void M2(ref int x, int y) { Console.WriteLine(4); } public void M3(ref int x, char y) { Console.WriteLine(5); } public void M3(ref long x, int y) { Console.WriteLine(6); } public void M4(ref int x, long y) { Console.WriteLine(7); } public void M4(ref int x, ref int y) { Console.WriteLine(8); } public void M5(ref int x, char y) { Console.WriteLine(9); } public void M5(ref long x, int y) { Console.WriteLine(10); } public void M6(ref int x, int y) { Console.WriteLine(11); } public void M6(ref long x, int y) { Console.WriteLine(12); } public void M7(ref int x, long y) { Console.WriteLine(13); } public void M7(ref long x, ref int y) { Console.WriteLine(14); } public void M8(long x, ref int y) { Console.WriteLine(15); } public void M8(ref long x, int y) { Console.WriteLine(16); } public void M9(ref long x, ref int y) { Console.WriteLine(17); } public void M9(ref int x, ref long y) { Console.WriteLine(18); } } class Test { public static void Main() { IRef1 ref1 = new Ref1Impl(); int i = 1; long l = 1; char c = 'c'; // void M1(int x, long y); // void M1(ref int x, int y); ref1.M1(i, i); ref1.M1(i, l); ref1.M1(i, c); //ref1.M1(l, i); CS1503 //ref1.M1(l, l); CS1503 //ref1.M1(l, c); CS1503 ref1.M1(c, i); ref1.M1(c, l); ref1.M1(c, c); ref1.M1(ref i, i); //ref1.M1(ref i, l); CS1615 ref1.M1(ref i, c); //ref1.M1(ref l, i); CS1615 //ref1.M1(ref l, l); CS1615 //ref1.M1(ref l, c); CS1615 //ref1.M1(ref c, i); CS1615 //ref1.M1(ref c, l); CS1615 //ref1.M1(ref c, c); CS1615 // void M2(int x, char y); // void M2(ref int x, int y); Console.WriteLine(); ref1.M2(i, i); //ref1.M2(i, l); CS1503 ref1.M2(i, c); //ref1.M2(l, i); CS1503, CS1503 //ref1.M2(l, l); CS1503, CS1503 //ref1.M2(l, c); CS1503 ref1.M2(c, i); //ref1.M2(c, l); CS1503 ref1.M2(c, c); ref1.M2(ref i, i); //ref1.M2(ref i, l); CS1615, CS1503 ref1.M2(ref i, c); //ref1.M2(ref l, i); CS1615, CS1503 //ref1.M2(ref l, l); CS1615, CS1503 //ref1.M2(ref l, c); CS1615 //ref1.M2(ref c, i); CS1615, CS1503 //ref1.M2(ref c, l); CS1615, CS1503 //ref1.M2(ref c, c); CS1615 // void M3(ref int x, char y); // void M3(ref long x, int y); Console.WriteLine(); ref1.M3(i, i); //ref1.M3(i, l); CS1503 ref1.M3(i, c); ref1.M3(l, i); //ref1.M3(l, l); CS1620, CS1503 ref1.M3(l, c); ref1.M3(c, i); //ref1.M3(c, l); CS1503 ref1.M3(c, c); //ref1.M3(ref i, i); CS1503 //ref1.M3(ref i, l); CS1503 ref1.M3(ref i, c); ref1.M3(ref l, i); //ref1.M3(ref l, l); CS1503, CS1503 ref1.M3(ref l, c); //ref1.M3(ref c, i); CS1503, CS1503 //ref1.M3(ref c, l); CS1503, CS1503 //ref1.M3(ref c, c); CS1503 // void M4(ref int x, long y); // void M4(ref int x, ref int y); Console.WriteLine(); //ref1.M4(i, i); CS0121 ref1.M4(i, l); //ref1.M4(i, c); CS0121 //ref1.M4(l, i); CS1620 //ref1.M4(l, l); CS1620 //ref1.M4(l, c); CS1620 //ref1.M4(c, i); CS0121 ref1.M4(c, l); //ref1.M4(c, c); CS0121 ref1.M4(i, ref i); //ref1.M4(l, ref i); CS1620, CS1615 ref1.M4(c, ref i); //ref1.M4(i, ref l); CS1615 //ref1.M4(l, ref l); CS1620 //ref1.M4(c, ref l); CS1615 ref1.M4(ref i, i); ref1.M4(ref i, l); ref1.M4(ref i, c); ref1.M4(ref i, ref i); // void M5(ref int x, char y); // void M5(ref long x, int y); Console.WriteLine(); ref1.M5(i, i); //ref1.M5(i, l); CS1503 ref1.M5(i, c); ref1.M5(l, i); //ref1.M5(l, l); CS1620, CS1503 ref1.M5(l, c); ref1.M5(c, i); //ref1.M5(c, l); CS1503 ref1.M5(c, c); //ref1.M5(ref i, i); CS1503 //ref1.M5(ref i, l); CS1503 ref1.M5(ref i, c); ref1.M5(ref l, i); //ref1.M5(ref l, l); CS1503 ref1.M5(ref l, c); // void M6(ref int x, int y); // void M6(ref long x, int y); Console.WriteLine(); //ref1.M6(i, i); CS0121 //ref1.M6(i, l); CS1503 //ref1.M6(i, c); CS0121 ref1.M6(l, i); //ref1.M6(l, l); CS1620, CS1503 ref1.M6(l, c); //ref1.M6(c, i); CS0121 //ref1.M6(c, l); CS1503 //ref1.M6(c, c); CS0121 ref1.M6(ref i, i); //ref1.M6(ref i, l); CS1503 ref1.M6(ref i, c); ref1.M6(ref l, i); //ref1.M6(ref l, l); CS1503, CS1503 ref1.M6(ref l, c); // void M7(ref int x, long y); // void M7(ref long x, ref int y); Console.WriteLine(); //ref1.M7(i, i); CS0121 ref1.M7(i, l); //ref1.M7(i, c); CS0121 ref1.M7(l, i); //ref1.M7(l, l); CS1620 ref1.M7(l, c); //ref1.M7(c, i); CS0121 ref1.M7(c, l); //ref1.M7(c, c); CS0121 ref1.M7(i, ref i); ref1.M7(l, ref i); ref1.M7(c, ref i); //ref1.M7(i, ref l); CS1615 //ref1.M7(l, ref l); CS1620, CS1615 //ref1.M7(c, ref l); CS1615 ref1.M7(ref i, i); ref1.M7(ref i, l); ref1.M7(ref i, c); //ref1.M7(ref i, ref i); CS1615 // void M8(long x, ref int y); // void M8(ref long x, int y); Console.WriteLine(); ref1.M8(i, i); //ref1.M8(i, l); CS1620 //ref1.M8(i, c); CS0121 //ref1.M8(l, i); CS0121 //ref1.M8(l, l); CS1620 ref1.M8(l, c); ref1.M8(c, i); //ref1.M8(c, l); CS1620 //ref1.M8(c, c); CS0121 ref1.M8(i, ref i); ref1.M8(l, ref i); ref1.M8(c, ref i); //ref1.M8(i, ref l); CS1503 //ref1.M8(l, ref l); CS1503 //ref1.M8(c, ref l); CS1503 //ref1.M8(ref i, i); CS1615 //ref1.M8(ref i, l); CS1615, CS1620 //ref1.M8(ref i, c); CS1615 ref1.M8(ref l, i); //ref1.M8(ref l, l); CS1615, CS1620 ref1.M8(ref l, c); //ref1.M8(ref i, ref i); CS1615 //ref1.M8(ref i, ref l); CS1615, CS1503 //ref1.M8(ref l, ref i); CS1615 //ref1.M8(ref l, ref l); CS1615, CS1503 // void M9(ref long x, ref int y); // void M9(ref int x, ref long y); Console.WriteLine(); //ref1.M9(i, i); CS0121 ref1.M9(i, l); //ref1.M9(i, c); CS0121 ref1.M9(l, i); //ref1.M9(l, l); CS1620 ref1.M9(l, c); //ref1.M9(c, i); CS0121 ref1.M9(c, l); //ref1.M9(c, c); CS0121 ref1.M9(i, ref i); ref1.M9(l, ref i); ref1.M9(c, ref i); ref1.M9(i, ref l); //ref1.M9(l, ref l); CS1503 ref1.M9(c, ref l); ref1.M9(ref i, i); ref1.M9(ref i, l); ref1.M9(ref i, c); ref1.M9(ref l, i); //ref1.M9(ref l, l); CS1620 ref1.M9(ref l, c); //ref1.M9(ref i, ref i); CS1503 ref1.M9(ref i, ref l); ref1.M9(ref l, ref i); //ref1.M9(ref l, ref l); CS1503 } } "; CompileAndVerify(source, expectedOutput: @"1 1 1 1 1 1 2 2 4 3 4 3 4 4 6 5 6 6 6 5 5 6 6 7 7 8 8 7 7 7 8 10 9 10 10 10 9 9 10 10 12 12 11 11 12 12 13 14 14 13 14 14 14 13 13 13 16 15 16 15 15 15 16 16 18 17 17 18 17 17 17 18 18 18 18 18 17 17 18 17"); } [Fact] public void RefOmittedComCall_OverloadResolution_MultipleArguments_ErrorCases() { var source = @" using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { void M1(int x, long y); void M1(ref int x, int y); void M2(int x, char y); void M2(ref int x, int y); void M3(ref int x, char y); void M3(ref long x, int y); void M4(ref int x, long y); void M4(ref int x, ref int y); void M5(ref int x, char y); void M5(ref long x, int y); void M6(ref int x, int y); void M6(ref long x, int y); void M7(ref int x, long y); void M7(ref long x, ref int y); void M8(long x, ref int y); void M8(ref long x, int y); void M9(ref long x, ref int y); void M9(ref int x, ref long y); } public class Ref1Impl : IRef1 { public void M1(int x, long y) { Console.WriteLine(1); } public void M1(ref int x, int y) { Console.WriteLine(2); } public void M2(int x, char y) { Console.WriteLine(3); } public void M2(ref int x, int y) { Console.WriteLine(4); } public void M3(ref int x, char y) { Console.WriteLine(5); } public void M3(ref long x, int y) { Console.WriteLine(6); } public void M4(ref int x, long y) { Console.WriteLine(7); } public void M4(ref int x, ref int y) { Console.WriteLine(8); } public void M5(ref int x, char y) { Console.WriteLine(9); } public void M5(ref long x, int y) { Console.WriteLine(10); } public void M6(ref int x, int y) { Console.WriteLine(11); } public void M6(ref long x, int y) { Console.WriteLine(12); } public void M7(ref int x, long y) { Console.WriteLine(13); } public void M7(ref long x, ref int y) { Console.WriteLine(14); } public void M8(long x, ref int y) { Console.WriteLine(15); } public void M8(ref long x, int y) { Console.WriteLine(16); } public void M9(ref long x, ref int y) { Console.WriteLine(17); } public void M9(ref int x, ref long y) { Console.WriteLine(18); } } class Test { public static void Main() { IRef1 ref1 = new Ref1Impl(); int i = 1; long l = 1; char c = 'c'; // void M1(int x, long y); // void M1(ref int x, int y); ref1.M1(l, i); // CS1503 ref1.M1(l, l); // CS1503 ref1.M1(l, c); // CS1503 ref1.M1(ref i, l); // CS1615 ref1.M1(ref l, i); // CS1615 ref1.M1(ref l, l); // CS1615 ref1.M1(ref l, c); // CS1615 ref1.M1(ref c, i); // CS1615 ref1.M1(ref c, l); // CS1615 ref1.M1(ref c, c); // CS1615 // void M2(int x, char y); // void M2(ref int x, int y); Console.WriteLine(); ref1.M2(i, l); // CS1503 ref1.M2(l, i); // CS1503, CS1503 ref1.M2(l, l); // CS1503, CS1503 ref1.M2(l, c); // CS1503 ref1.M2(c, l); // CS1503 ref1.M2(ref i, l); // CS1615, CS1503 ref1.M2(ref l, i); // CS1615, CS1503 ref1.M2(ref l, l); // CS1615, CS1503 ref1.M2(ref l, c); // CS1615 ref1.M2(ref c, i); // CS1615, CS1503 ref1.M2(ref c, l); // CS1615, CS1503 ref1.M2(ref c, c); // CS1615 // void M3(ref int x, char y); // void M3(ref long x, int y); Console.WriteLine(); ref1.M3(i, l); // CS1503 ref1.M3(l, l); // CS1620, CS1503 ref1.M3(c, l); // CS1503 ref1.M3(ref i, i); // CS1503 ref1.M3(ref i, l); // CS1503 ref1.M3(ref l, l); // CS1503, CS1503 ref1.M3(ref c, i); // CS1503, CS1503 ref1.M3(ref c, l); // CS1503, CS1503 ref1.M3(ref c, c); // CS1503 // void M4(ref int x, long y); // void M4(ref int x, ref int y); Console.WriteLine(); ref1.M4(i, i); // CS0121 ref1.M4(i, c); // CS0121 ref1.M4(l, i); // CS1620 ref1.M4(l, l); // CS1620 ref1.M4(l, c); // CS1620 ref1.M4(c, i); // CS0121 ref1.M4(c, c); // CS0121 ref1.M4(l, ref i); // CS1620, CS1615 ref1.M4(i, ref l); // CS1615 ref1.M4(l, ref l); // CS1620 ref1.M4(c, ref l); // CS1615 // void M5(ref int x, char y); // void M5(ref long x, int y); Console.WriteLine(); ref1.M5(i, l); // CS1503 ref1.M5(l, l); // CS1620, CS1503 ref1.M5(c, l); // CS1503 ref1.M5(ref i, i); // CS1503 ref1.M5(ref i, l); // CS1503 ref1.M5(ref l, l); // CS1503 // void M6(ref int x, int y); // void M6(ref long x, int y); Console.WriteLine(); ref1.M6(i, i); // CS0121 ref1.M6(i, l); // CS1503 ref1.M6(i, c); // CS0121 ref1.M6(l, l); // CS1620, CS1503 ref1.M6(c, i); // CS0121 ref1.M6(c, l); // CS1503 ref1.M6(c, c); // CS0121 ref1.M6(ref i, l); // CS1503 ref1.M6(ref l, l); // CS1503, CS1503 // void M7(ref int x, long y); // void M7(ref long x, ref int y); Console.WriteLine(); ref1.M7(i, i); // CS0121 ref1.M7(i, c); // CS0121 ref1.M7(l, l); // CS1620 ref1.M7(c, i); // CS0121 ref1.M7(c, c); // CS0121 ref1.M7(i, ref l); // CS1615 ref1.M7(l, ref l); // CS1620, CS1615 ref1.M7(c, ref l); // CS1615 ref1.M7(ref i, ref i); // CS1615 // void M8(long x, ref int y); // void M8(ref long x, int y); Console.WriteLine(); ref1.M8(i, l); // CS1620 ref1.M8(i, c); // CS0121 ref1.M8(l, i); // CS0121 ref1.M8(l, l); // CS1620 ref1.M8(c, l); // CS1620 ref1.M8(c, c); // CS0121 ref1.M8(i, ref l); // CS1503 ref1.M8(l, ref l); // CS1503 ref1.M8(c, ref l); // CS1503 ref1.M8(ref i, i); // CS1615 ref1.M8(ref i, l); // CS1615, CS1620 ref1.M8(ref i, c); // CS1615 ref1.M8(ref l, l); // CS1615, CS1620 ref1.M8(ref i, ref i); // CS1615 ref1.M8(ref i, ref l); // CS1615, CS1503 ref1.M8(ref l, ref i); // CS1615 ref1.M8(ref l, ref l); // CS1615, CS1503 // void M9(ref long x, ref int y); // void M9(ref int x, ref long y); Console.WriteLine(); ref1.M9(i, i); // CS0121 ref1.M9(i, c); // CS0121 ref1.M9(l, l); // CS1620 ref1.M9(c, i); // CS0121 ref1.M9(c, c); // CS0121 ref1.M9(l, ref l); // CS1503 ref1.M9(ref l, l); // CS1620 ref1.M9(ref i, ref i); // CS1503 ref1.M9(ref l, ref l); // CS1503 } } "; CreateCompilation(source).VerifyDiagnostics( // (80,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M1(l, i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (81,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M1(l, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (82,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M1(l, c); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (83,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref i, l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (84,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref l, i); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (85,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref l, l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (86,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref l, c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (87,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref c, i); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (88,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref c, l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (89,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref c, c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (96,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M2(i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (97,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M2(l, i); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (97,19): error CS1503: Argument 2: cannot convert from 'int' to 'char' // ref1.M2(l, i); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("2", "int", "char"), // (98,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M2(l, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (98,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M2(l, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (99,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M2(l, c); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (100,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M2(c, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (101,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref i, l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (101,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M2(ref i, l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (102,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref l, i); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (102,23): error CS1503: Argument 2: cannot convert from 'int' to 'char' // ref1.M2(ref l, i); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("2", "int", "char"), // (103,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref l, l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (103,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M2(ref l, l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (104,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref l, c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (105,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref c, i); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (105,23): error CS1503: Argument 2: cannot convert from 'int' to 'char' // ref1.M2(ref c, i); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("2", "int", "char"), // (106,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref c, l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (106,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M2(ref c, l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (107,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref c, c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (114,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M3(i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (115,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M3(l, l); // CS1620, CS1503 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (115,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M3(l, l); // CS1620, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (116,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M3(c, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (117,23): error CS1503: Argument 2: cannot convert from 'int' to 'char' // ref1.M3(ref i, i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("2", "int", "char"), // (118,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M3(ref i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (119,20): error CS1503: Argument 1: cannot convert from 'ref long' to 'ref int' // ref1.M3(ref l, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "ref long", "ref int"), // (119,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M3(ref l, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (120,20): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref int' // ref1.M3(ref c, i); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref int"), // (120,23): error CS1503: Argument 2: cannot convert from 'int' to 'char' // ref1.M3(ref c, i); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("2", "int", "char"), // (121,20): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref int' // ref1.M3(ref c, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref int"), // (121,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M3(ref c, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (122,20): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref int' // ref1.M3(ref c, c); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref int"), // (129,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M4(ref int, long)' and 'IRef1.M4(ref int, ref int)' // ref1.M4(i, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M4").WithArguments("IRef1.M4(ref int, long)", "IRef1.M4(ref int, ref int)"), // (130,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M4(ref int, long)' and 'IRef1.M4(ref int, ref int)' // ref1.M4(i, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M4").WithArguments("IRef1.M4(ref int, long)", "IRef1.M4(ref int, ref int)"), // (131,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M4(l, i); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (132,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M4(l, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (133,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M4(l, c); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (134,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M4(ref int, long)' and 'IRef1.M4(ref int, ref int)' // ref1.M4(c, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M4").WithArguments("IRef1.M4(ref int, long)", "IRef1.M4(ref int, ref int)"), // (135,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M4(ref int, long)' and 'IRef1.M4(ref int, ref int)' // ref1.M4(c, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M4").WithArguments("IRef1.M4(ref int, long)", "IRef1.M4(ref int, ref int)"), // (136,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M4(l, ref i); // CS1620, CS1615 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (136,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M4(l, ref i); // CS1620, CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("2", "ref"), // (137,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M4(i, ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("2", "ref"), // (138,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M4(l, ref l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (138,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M4(l, ref l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("2", "ref"), // (139,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M4(c, ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("2", "ref"), // (146,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M5(i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (147,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M5(l, l); // CS1620, CS1503 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (147,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M5(l, l); // CS1620, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (148,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M5(c, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (149,23): error CS1503: Argument 2: cannot convert from 'int' to 'char' // ref1.M5(ref i, i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("2", "int", "char"), // (150,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M5(ref i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (151,20): error CS1503: Argument 1: cannot convert from 'ref long' to 'ref int' // ref1.M5(ref l, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "ref long", "ref int"), // (151,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M5(ref l, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (158,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M6(ref int, int)' and 'IRef1.M6(ref long, int)' // ref1.M6(i, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("IRef1.M6(ref int, int)", "IRef1.M6(ref long, int)"), // (159,19): error CS1503: Argument 2: cannot convert from 'long' to 'int' // ref1.M6(i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "int"), // (160,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M6(ref int, int)' and 'IRef1.M6(ref long, int)' // ref1.M6(i, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("IRef1.M6(ref int, int)", "IRef1.M6(ref long, int)"), // (161,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M6(l, l); // CS1620, CS1503 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (161,19): error CS1503: Argument 2: cannot convert from 'long' to 'int' // ref1.M6(l, l); // CS1620, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "int"), // (162,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M6(ref int, int)' and 'IRef1.M6(ref long, int)' // ref1.M6(c, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("IRef1.M6(ref int, int)", "IRef1.M6(ref long, int)"), // (163,19): error CS1503: Argument 2: cannot convert from 'long' to 'int' // ref1.M6(c, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "int"), // (164,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M6(ref int, int)' and 'IRef1.M6(ref long, int)' // ref1.M6(c, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("IRef1.M6(ref int, int)", "IRef1.M6(ref long, int)"), // (165,23): error CS1503: Argument 2: cannot convert from 'long' to 'int' // ref1.M6(ref i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "int"), // (166,20): error CS1503: Argument 1: cannot convert from 'ref long' to 'ref int' // ref1.M6(ref l, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "ref long", "ref int"), // (166,23): error CS1503: Argument 2: cannot convert from 'long' to 'int' // ref1.M6(ref l, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "int"), // (173,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M7(ref int, long)' and 'IRef1.M7(ref long, ref int)' // ref1.M7(i, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M7").WithArguments("IRef1.M7(ref int, long)", "IRef1.M7(ref long, ref int)"), // (174,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M7(ref int, long)' and 'IRef1.M7(ref long, ref int)' // ref1.M7(i, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M7").WithArguments("IRef1.M7(ref int, long)", "IRef1.M7(ref long, ref int)"), // (175,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M7(l, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (176,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M7(ref int, long)' and 'IRef1.M7(ref long, ref int)' // ref1.M7(c, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M7").WithArguments("IRef1.M7(ref int, long)", "IRef1.M7(ref long, ref int)"), // (177,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M7(ref int, long)' and 'IRef1.M7(ref long, ref int)' // ref1.M7(c, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M7").WithArguments("IRef1.M7(ref int, long)", "IRef1.M7(ref long, ref int)"), // (178,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M7(i, ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("2", "ref"), // (179,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M7(l, ref l); // CS1620, CS1615 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (179,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M7(l, ref l); // CS1620, CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("2", "ref"), // (180,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M7(c, ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("2", "ref"), // (181,27): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M7(ref i, ref i); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("2", "ref"), // (188,19): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M8(i, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (189,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M8(long, ref int)' and 'IRef1.M8(ref long, int)' // ref1.M8(i, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M8").WithArguments("IRef1.M8(long, ref int)", "IRef1.M8(ref long, int)"), // (190,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M8(long, ref int)' and 'IRef1.M8(ref long, int)' // ref1.M8(l, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M8").WithArguments("IRef1.M8(long, ref int)", "IRef1.M8(ref long, int)"), // (191,19): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M8(l, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (192,19): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M8(c, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (193,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M8(long, ref int)' and 'IRef1.M8(ref long, int)' // ref1.M8(c, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M8").WithArguments("IRef1.M8(long, ref int)", "IRef1.M8(ref long, int)"), // (194,23): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M8(i, ref l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int"), // (195,23): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M8(l, ref l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int"), // (196,23): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M8(c, ref l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int"), // (197,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref i, i); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (198,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref i, l); // CS1615, CS1620 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (198,23): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M8(ref i, l); // CS1615, CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (199,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref i, c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (200,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref l, l); // CS1615, CS1620 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (200,23): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M8(ref l, l); // CS1615, CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (201,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref i, ref i); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (202,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref i, ref l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (202,27): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M8(ref i, ref l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int"), // (203,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref l, ref i); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (204,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref l, ref l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (204,27): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M8(ref l, ref l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int"), // (211,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M9(ref long, ref int)' and 'IRef1.M9(ref int, ref long)' // ref1.M9(i, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M9").WithArguments("IRef1.M9(ref long, ref int)", "IRef1.M9(ref int, ref long)"), // (212,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M9(ref long, ref int)' and 'IRef1.M9(ref int, ref long)' // ref1.M9(i, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M9").WithArguments("IRef1.M9(ref long, ref int)", "IRef1.M9(ref int, ref long)"), // (213,19): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M9(l, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (214,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M9(ref long, ref int)' and 'IRef1.M9(ref int, ref long)' // ref1.M9(c, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M9").WithArguments("IRef1.M9(ref long, ref int)", "IRef1.M9(ref int, ref long)"), // (215,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M9(ref long, ref int)' and 'IRef1.M9(ref int, ref long)' // ref1.M9(c, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M9").WithArguments("IRef1.M9(ref long, ref int)", "IRef1.M9(ref int, ref long)"), // (216,23): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M9(l, ref l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int"), // (217,23): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M9(ref l, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (218,20): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // ref1.M9(ref i, ref i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (219,27): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M9(ref l, ref l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int")); } [Fact] public void FailedToConvertToParameterArrayElementType() { var source = @" class C { static void Main() { M1(1, null); M1(null, 1); M2(""a"", null); M2(null, ""a""); M3(1, null); M3(null, 1); M3(""a"", null); M3(null, ""a""); M1(1, ""A""); M2(1, ""A""); M3<int>(1, ""A""); M3<string>(1, ""A""); } static void M1(params int[] a) { } static void M2(params string[] a) { } static void M3<T>(params T[] a) { } } "; CreateCompilation(source).VerifyDiagnostics( // (6,15): error CS1503: Argument 2: cannot convert from '<null>' to 'int' // M1(1, null); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("2", "<null>", "int"), // (7,12): error CS1503: Argument 1: cannot convert from '<null>' to 'int' // M1(null, 1); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "int"), // (12,15): error CS1503: Argument 2: cannot convert from '<null>' to 'int' // M3(1, null); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("2", "<null>", "int"), // (13,12): error CS1503: Argument 1: cannot convert from '<null>' to 'int' // M3(null, 1); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "int"), // (18,15): error CS1503: Argument 2: cannot convert from 'string' to 'int' // M1(1, "A"); Diagnostic(ErrorCode.ERR_BadArgType, @"""A""").WithArguments("2", "string", "int"), // (19,12): error CS1503: Argument 1: cannot convert from 'int' to 'string' // M2(1, "A"); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string"), // (20,20): error CS1503: Argument 2: cannot convert from 'string' to 'int' // M3<int>(1, "A"); Diagnostic(ErrorCode.ERR_BadArgType, @"""A""").WithArguments("2", "string", "int"), // (21,20): error CS1503: Argument 1: cannot convert from 'int' to 'string' // M3<string>(1, "A"); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string")); } [Fact] public void TypeInferenceFailures() { var source = @" public interface I { } public interface I1<T> { } public interface I2<S, T> { } public class A : I { } public class B { } public class C { } public class G1<T> : I1<T> { } public class G2<S, T> : G1<S>, I2<S, T> { } public class AggTest { public static A a = new A(); public static I i = a; public static G1<A> g1a = new G1<A>(); public static G1<G1<B>> g11b = new G1<G1<B>>(); public static G1<G1<G1<C>>> g111c = new G1<G1<G1<C>>>(); public static G1<G2<A, B>> g12ab = new G1<G2<A, B>>(); public static G2<A, B> g2ab = new G2<A, B>(); public static G2<G1<A>, B> g21ab = new G2<G1<A>, B>(); public static G2<A, G1<B>> g2a1b = new G2<A, G1<B>>(); public static G2<G1<A>, G1<B>> g21a1b = new G2<G1<A>, G1<B>>(); public static G2<G2<A, B>, C> g22abc = new G2<G2<A, B>, C>(); public static G2<A, G2<B, C>> g2a2bc = new G2<A, G2<B, C>>(); public static G2<G2<A, B>, G1<C>> g22ab1c = new G2<G2<A, B>, G1<C>>(); public static G2<G1<A>, G2<B, C>> g21a2bc = new G2<G1<A>, G2<B, C>>(); public class B1 { // Nesting >= 2 public static void M3<S, T>(G1<G2<S, T>> a) { } public static void M3<S, T>(G2<G1<S>, T> a) { } public static void M3<S, T>(G2<S, G1<T>> a) { } public static void M3<S, T>(G2<G1<S>, G1<T>> a) { } } public class ClassTestGen : B1 { public static void Run() { M3(null); // Can't infer M3(a); // Can't infer M3(i); // Can't infer M3(g1a); // Can't infer M3(g11b); // Can't infer M3(g111c); // Can't infer M3(g12ab); // OK M3(g2ab); // Can't infer M3(g21ab); // OK M3(g2a1b); // OK M3(g21a1b); // Ambiguous M3(g22abc); // OK M3(g2a2bc); // Can't infer M3(g22ab1c); // OK M3(g21a2bc); // OK } } } "; CreateCompilation(source).VerifyDiagnostics( // (43,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(null); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // (44,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(a); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // (45,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(i); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // (46,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(g1a); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // (47,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(g11b); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // (48,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(g111c); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // NOTE: Dev10 reports "AggTest.B1.M3<S,T>(G2<G1<S>,T>)" for the last two, but this seems just as good (type inference fails for both). // (50,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(g2ab); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // (55,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(g2a2bc); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)")); } [WorkItem(528425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528425")] [WorkItem(528425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528425")] [Fact(Skip = "528425")] public void ExactInaccessibleMatch() { var source = @" public class C { public static void Main() { D d = new D(); d.M(4, 5, ""b""); } } public class D { public void M(int i) { } private void M(int i, int j, string s) { } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0122: 'D.M(int, int, string)' is inaccessible due to its protection level // d.M(4, 5, "b"); Diagnostic(ErrorCode.ERR_BadAccess, "d.M")); } [WorkItem(545382, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545382")] [Fact] public void Whidbey133503a() { var source = @" class Ambig { static void Main() { overload1(1, 1); overload2(1, 1); } // causes ambiguity because first and third method, but depending on the order, the compiler // reports them incorrectly. VSWhidbey:133503 static void overload1(byte b, goo f) { } static void overload1(sbyte b, bar f) { } static void overload1(int b, baz f) { } static void overload2(int b, baz f) { } static void overload2(sbyte b, bar f) { } static void overload2(byte b, goo f) { } } class goo { public static implicit operator goo(int i) { return new goo(); } } class bar { public static implicit operator bar(int i) { return new bar(); } } class baz { public static implicit operator baz(int i) { return new baz(); } public static implicit operator baz(goo f) { return new baz(); } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Ambig.overload1(byte, goo)' and 'Ambig.overload1(int, baz)' // overload1(1, 1); Diagnostic(ErrorCode.ERR_AmbigCall, "overload1").WithArguments("Ambig.overload1(byte, goo)", "Ambig.overload1(int, baz)").WithLocation(6, 9), // (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'Ambig.overload2(int, baz)' and 'Ambig.overload2(byte, goo)' // overload2(1, 1); Diagnostic(ErrorCode.ERR_AmbigCall, "overload2").WithArguments("Ambig.overload2(int, baz)", "Ambig.overload2(byte, goo)").WithLocation(7, 9) ); } [WorkItem(545382, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545382")] [Fact] public void Whidbey133503b() { var source = @" class Ambig { static void Main() { F(new Q()); } // causes ambiguity because of conversion cycle. So the compiler // arbitrarily picks the 'first' 2 methods to report (which turn out to be // the last 2 overloads declared). Also VSWhidbey:133503 public static void F(P1 p) { } public static void F(P2 p) { } public static void F(P3 p) { } } public class P1 { public static implicit operator P1(P2 p) { return null; } } public class P2 { public static implicit operator P2(P3 p) { return null; } } public class P3 { public static implicit operator P3(P1 p) { return null; } } public class Q { public static implicit operator P1(Q p) { return null; } public static implicit operator P2(Q p) { return null; } public static implicit operator P3(Q p) { return null; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Ambig.F(P1)' and 'Ambig.F(P2)' // F(new Q()); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Ambig.F(P1)", "Ambig.F(P2)")); } [WorkItem(545467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545467")] [Fact] public void ClassPlusLambda1() { // ACASEY: EricLi's comment provides good context on the // nature of the problems that arise in such situations and the behavior of the native // compiler. However, the comments about Roslyn's behavior are no longer accurate. // Unfortunately, we discovered real-world code that depended on the native behavior // so we need to replicate it in Roslyn. Effectively, null literal conversions become // standard implicit conversions (we expect the spec to be revised) and anonymous function // and method group conversions are specifically allowed if there is an explicit cast // (this will likely not be spec'd). As for the betterness rule, we only go down the // delegate path if BOTH target types are delegate types. Otherwise, the normal betterness // rules apply. // ERICLI: This test illustrates an unfortunate situation where neither Roslyn nor the // native compiler are compliant with the specification, and the native compiler's // behavior is unusual. In this particular situation, the native compiler is // getting the right answer completely by accident; it is the confluence of two incorrect // decisions adding up accidentally to a correct decision. // // Problem 1: // // The spec says that there must be a *standard implicit conversion* from the expression being // converted to the parameter type of the user-defined implicit conversion. Unfortunately, the // specification does not say that null literal conversions, constant numeric conversions, // method group conversions, or lambda conversions are "standard" conversions. It seems reasonable // that these be allowed; we will probably amend the specification to allow them. // // Now we get to the unusual part. The native compiler allows null literal and constant numeric // conversions to be counted as standard conversions; this is contrary to the exact wording of // the specification but as we said, it is a reasonable rule and we should allow it in the spec. // The unusual part is: the native compiler effectively treats a lambda conversion and a method // group conversion as a standard implicit conversion *if a cast appears in the code*. // // That is, suppose there is an implicit conversion from Action to S. The native compiler allows // // S s = (S)(()=>{}); // // but does not allow // // S s = ()=>{}; // // it is strange indeed that an *implicit* conversion should require a *cast*! // // Roslyn allows all those conversions to be used when converting the expression to the parameter // type of the user-defined implicit conversion, regardless of whether a cast appears in the code. // // Problem 2: // // The native compiler gets the "betterness" rules wrong when lambdas are involved. The right thing // to do is to first, check to see if one method has a more specific formal parameter type than the other. // If betterness cannot be determined by formal parameter types, and the argument is a lambda, then // a special rule regarding the inferred return type of the lambda is used. What the native compiler does // is, if there is a lambda, then it skips doing the formal parameter type check and goes straight to the // lambda check. // // After some debate, we decided a while back to replicate this bug in Roslyn. // // Now we see how these two bugs work together in the native compiler to produce the correct result // for the wrong reason. Suppose we have a simplified version of the code below: r = r + (x=>x); // What happens? // // The correct behavior according to the spec is to say that there are two possible operators, // MC + EXPR and MC + MC. Are either of them *applicable*? Clearly both are good in their left // hand operand. Can the right-hand operand, a lambda, be converted via implicit conversion to // the expression tree type? Obviously yes. Can the lambda be converted to MainClass? // // Not directly, because MainClass is not a delegate or expression tree type. But we examine // the user-defined conversions on MainClass and discover an implicit conversion from expression // tree to MainClass. Can we use that? // // The spec says no, because the conversion from lambda to expression tree is not a "standard" // implicit conversion. // // The native compiler says no because it enforces that rule when there is no cast in the code. // Had there been a cast in the code, the native compiler would say yes, there is. // // Roslyn says yes; it allows the lambda conversion as a standard conversion regardless of whether // there is a cast in the code. // // In the native compiler there is now only one operator in the candidate set of applicable operators; // the choice is therefore easy; the MC + EXPR wins. // // In Roslyn, there are now two operators in the candidate set of applicable operators. Which one wins? // // The correct behavior is to say that the more specific one wins. Since there is an implicit conversion // from EXPR to MC but not from MC to EXPR, the MC + EXPR candidate must be better, so it wins. // // But that is not what Roslyn does; remember, Roslyn is being bug-compatible with the native compiler. // The native compiler does not check for betterness on types when a lambda is involved. // Therefore Roslyn checks the lambda, and is unable to deduce from it which candidate is better. // // Therefore Roslyn gives an ambiguity error, even though (1) by rights the candidate set should // contain a single operator, and (2) even if it contains two, one of them is clearly better. // var source = @" class MainClass { static void Main() { MainClass r = new MainClass(); // The lambda contains an ambiguity error, and therefore we cannot work out // the overload resolution problem on the outermost addition, so we give // a bad binary operator error. r = r + ((MainClass x) => x + ((MainClass y) => (y + null))); // The lambda body no longer contains an error, thanks to the cast. // Therefore, this becomes an ambiguity error, for reasons detailed above. r = r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null))); } public static MainClass operator +(MainClass r1, MainClass r2) { return r1; } public static MainClass operator +(MainClass r1, System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) { return r1; } public static implicit operator MainClass( System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) { return new MainClass(); } } "; // Roslyn matches the native behavior - it compiles cleanly. var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [WorkItem(545467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545467")] [Fact] public void ClassPlusLambda2() { // Here we remove one of the operators from the previous test. Of course the // first one is no longer ambiguous, and the second one no longer works because // now the lambda contains an addition that has no applicable operator, and // so the outer addition cannot work either. var source = @" class MainClass { static void Main() { MainClass r = new MainClass(); r = r + ((MainClass x) => x + ((MainClass y) => (y + null))); r = r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null))); } // public static MainClass operator +(MainClass r1, MainClass r2) { return r1; } public static MainClass operator +(MainClass r1, System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) { return r1; } public static implicit operator MainClass( System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) { return new MainClass(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (8,13): error CS0019: Operator '+' cannot be applied to operands of type 'MainClass' and 'lambda expression' // r = r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null))); Diagnostic(ErrorCode.ERR_BadBinaryOps, "r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null)))").WithArguments("+", "MainClass", "lambda expression")); } [WorkItem(545467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545467")] [Fact] public void ClassPlusLambda3() { // In this variation we remove the other addition operator. The native compiler // disallows three of these additions, because as mentioned above, it is inconsistent // about when a user-defined conversion may be from a lambda. The native compiler says // that the user-defined conversion may only be from a lambda if a cast appears in // the source; in three of the four conversions from lambdas here, there is no cast. // // Roslyn replicates this bug. var source = @" class MainClass { public static void Main() { MainClass r = new MainClass(); r = r + ((MainClass x) => (x + ((MainClass y) => (y + null)))); r = r + ((MainClass x) => (x + (MainClass)((MainClass y) => (y + null)))); System.Func<MainClass, MainClass> f = x => x + (y => y); } public static MainClass operator +(MainClass r1, MainClass r2) { return r1; } // public static MainClass operator +(MainClass r1, // System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) // { return r1; } public static implicit operator MainClass( System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) { return new MainClass(); } } "; // NOTE: roslyn suppresses the error for (x + (...)) in the first assignment, // but it's still an error (as indicated by the standalone test below). var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '+' cannot be applied to operands of type 'MainClass' and 'lambda expression' // r = r + ((MainClass x) => (x + ((MainClass y) => (y + null)))); Diagnostic(ErrorCode.ERR_BadBinaryOps, "r + ((MainClass x) => (x + ((MainClass y) => (y + null))))").WithArguments("+", "MainClass", "lambda expression"), // (8,13): error CS0019: Operator '+' cannot be applied to operands of type 'MainClass' and 'lambda expression' // r = r + ((MainClass x) => (x + (MainClass)((MainClass y) => (y + null)))); Diagnostic(ErrorCode.ERR_BadBinaryOps, "r + ((MainClass x) => (x + (MainClass)((MainClass y) => (y + null))))").WithArguments("+", "MainClass", "lambda expression"), // (9,52): error CS0019: Operator '+' cannot be applied to operands of type 'MainClass' and 'lambda expression' // System.Func<MainClass, MainClass> f = x => x + (y => y); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x + (y => y)").WithArguments("+", "MainClass", "lambda expression")); } [WorkItem(545467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545467")] [Fact] public void ClassPlusLambda4() { // In this final variation, we remove the user-defined conversion. And now of course we cannot // add MainClass to the lambda at all; the native compiler and Roslyn agree. var source = @" class MainClass { static void Main() { MainClass r = new MainClass(); r = r + ((MainClass x) => x + ((MainClass y) => (y + null))); r = r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null))); } public static MainClass operator +(MainClass r1, MainClass r2) { return r1; } public static MainClass operator +(MainClass r1, System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) { return r1; } // public static implicit operator MainClass( // System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) // { return new MainClass(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '+' cannot be applied to operands of type 'MainClass' and 'lambda expression' // r = r + ((MainClass x) => x + ((MainClass y) => (y + null))); Diagnostic(ErrorCode.ERR_BadBinaryOps, "r + ((MainClass x) => x + ((MainClass y) => (y + null)))").WithArguments("+", "MainClass", "lambda expression"), // (8,13): error CS0019: Operator '+' cannot be applied to operands of type 'MainClass' and 'lambda expression' // r = r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null))); Diagnostic(ErrorCode.ERR_BadBinaryOps, "r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null)))").WithArguments("+", "MainClass", "lambda expression")); } [WorkItem(546875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546875")] [WorkItem(530930, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530930")] [Fact] public void BigVisitor() { // Reduced from Microsoft.Data.Schema.Sql.dll. var source = @" public class Test { static void Main() { var visitor = new ConcreteVisitor(); visitor.Visit(new Class090()); } } "; var libRef = TestReferences.SymbolsTests.BigVisitor; var start = DateTime.UtcNow; CreateCompilationWithMscorlib40AndSystemCore(source, new[] { libRef }).VerifyDiagnostics(); var elapsed = DateTime.UtcNow - start; Assert.InRange(elapsed.TotalSeconds, 0, 10.0); // Was originally over 30 minutes, so we have some wiggle room here. } [WorkItem(546730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546730"), WorkItem(546739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546739")] [Fact] public void TestNamedParamsParam() { CompileAndVerify(@" class C { static void M( int x, double y, params string[] z) { System.Console.WriteLine(1); } static void M( int x, params string[] z) { System.Console.WriteLine(2); } static void Main() { C.M(0, z: """"); } }", expectedOutput: "2").VerifyDiagnostics(); } [WorkItem(531173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531173")] [Fact] public void InvokeMethodOverridingNothing() { var source = @" public class C { public override T Override<T>(T t) { return t; } public void Test<T>(T t) { Override(t); } } "; CreateCompilation(source).VerifyDiagnostics( // (4,20): error CS0115: 'C.Override<T>(T)': no suitable method found to override // public override T Override<T>(T t) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Override").WithArguments("C.Override<T>(T)")); } [WorkItem(547186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547186")] [Fact, WorkItem(531613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531613")] public void IndexerWithoutAccessors() { var source = @" class Program { public static void Main() { C c = new C(); c[""""] = 10; } } abstract class A { public abstract int this[string arg] { set; } } class C : A { public override int this[string arg] // Not finished typing yet. "; // Doesn't assert. CreateCompilation(source).VerifyDiagnostics( // (18,41): error CS1514: { expected // public override int this[string arg] Diagnostic(ErrorCode.ERR_LbraceExpected, ""), // (18,41): error CS1513: } expected // public override int this[string arg] Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (18,41): error CS1513: } expected // public override int this[string arg] Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (18,25): error CS0548: 'C.this[string]': property or indexer must have at least one accessor // public override int this[string arg] Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("C.this[string]"), // (16,7): error CS0534: 'C' does not implement inherited abstract member 'A.this[string].set' // class C : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.this[string].set")); } [Fact] public void DynamicVsTypeParameters() { string source = @" using System; public class B<T> { public void F(T p1) { } public void F(dynamic p1) { } } class C { void M(B<C> b) { b.F(null); //-B<C>.F(C) } }"; TestOverloadResolutionWithDiff(source, new[] { CSharpRef, SystemCoreRef }); } [Fact] public void DynamicByRef() { string source = @" using System; public class C { public static int F(int p1, char p2, ref dynamic p3) { return 2; } public static int F(C p1, params dynamic[] p2) { return 3; } public static implicit operator int(C t) { return 1; } public static implicit operator C(int t) { return new C(); } static void M() { dynamic d1 = null; C c = null; C.F(c, 'a', ref d1); //-C.F(int, char, ref dynamic) } }"; TestOverloadResolutionWithDiff(source); } [Fact, WorkItem(624410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624410")] public void DynamicTypeInferenceAndPointer() { string source = @" public unsafe class C { public static void M() { dynamic x = null; Bar(x); } static void Bar<T>(D<T>.E*[] x) { } } class D<T> { public enum E { } } "; // Dev11 reports error CS0411: The type arguments for method 'C.Bar<T>(D<T>.E*[])' cannot be inferred from the usage. Try // specifying the type arguments explicitly. CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact, WorkItem(598032, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598032"), WorkItem(1157097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1157097"), WorkItem(2298, "https://github.com/dotnet/roslyn/issues/2298")] public void GenericVsOptionalParameter() { string source = @" using System; class C { public static int Goo(int x, string y = null) { return 1; } public static int Goo<T>(T x) { return 0; } public static void Main() { System.Console.WriteLine(Goo(0)); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: "0"); } [WorkItem(598029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598029")] [Fact] public void TypeParameterInterfaceVersusNonInterface() { string source = @" interface IA { int Goo(int x = 0); } class C : IA { public int Goo(int x) { return x; } static int M<T>(T x) where T : A, IA { return x.Goo(); //-IA.Goo(int) } } "; TestOverloadResolutionWithDiff(source); } [WorkItem(649807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649807")] [Fact] public void OverloadResolution649807() { var source = @" public class Test { public delegate dynamic nongenerics(dynamic id); public delegate T generics< T>(dynamic id); public dynamic Goo(nongenerics Meth, dynamic id) { return null; } public T Goo<T>(generics<T> Meth, dynamic id) { return default(T); } public dynamic method(dynamic id) { return System.String.Empty; } public dynamic testGoo(dynamic id) { return Goo(method, ""abc""); } static void Main(string[] args) { } }"; // Doesn't assert. CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (20,16): error CS0121: The call is ambiguous between the following methods or properties: 'Test.Goo(Test.nongenerics, dynamic)' and 'Test.Goo<T>(Test.generics<T>, dynamic)' // return Goo(method, "abc"); Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("Test.Goo(Test.nongenerics, dynamic)", "Test.Goo<T>(Test.generics<T>, dynamic)") ); } [WorkItem(662641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/662641")] [Fact] public void GenericMethodConversionToDelegateWithDynamic() { var source = @" using System; public delegate void D002<T1, T2>(T1 t1, T2 t2); public delegate void D003(dynamic t1, object t2); public class Goo { static internal void M11<T1, T2>(T1 t1, T2 t2) { } } public struct start { static void M(D002<dynamic, object> d) {} static public void Main() { dynamic d1 = null; object o1 = null; Goo.M11<dynamic, object>(d1, o1); Goo.M11(d1, o1); D002<dynamic, object> dd02 = new D002<dynamic, object>(Goo.M11); D002<dynamic, object> dd03 = Goo.M11; D002<dynamic, object> dd04 = (D002<dynamic, object>)Goo.M11; D003 dd05 = Goo.M11; M(Goo.M11); Console.WriteLine(dd02); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( ); } [WorkItem(690966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690966")] [Fact] public void OptionalParameterInDelegateConversion() { var source = @" using System; class C { static void M1(Func<string, int> f) { } static void M1(Func<string, string, int> f) { } static int M2(string s, string t = null) { return 0; } static void Main() { M1(M2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var callSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void C.M1(System.Func<System.String, System.String, System.Int32> f)", model.GetSymbolInfo(callSyntax).Symbol.ToTestDisplayString()); } [WorkItem(718294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718294")] [Fact] public void MethodGroupConversion_BetterCandidateHasOptionalParameter() { var source = @" using System; class Test { void M(IViewable2 v) { v.View(v.Add); } } interface IViewable { void View(Action viewer); } interface IViewable2 : IViewable { } static class Extensions { [Obsolete(""A"", error: false)] public static void Add(this IViewable2 @this) { } [Obsolete(""B"", error: false)] public static void Add(this IViewable @this, object obj = null) { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (8,16): warning CS0618: 'Extensions.Add(IViewable2)' is obsolete: 'A' // v.View(v.Add); Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "v.Add").WithArguments("Extensions.Add(IViewable2)", "A")); } [WorkItem(718294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718294")] [Fact] public void MethodGroupConversion_BetterCandidateHasParameterArray() { var source = @" using System; class Test { void M(IViewable2 v) { v.View(v.Add); } } interface IViewable { void View(Action viewer); } interface IViewable2 : IViewable { } static class Extensions { [Obsolete(""A"", error: false)] public static void Add(this IViewable2 @this) { } [Obsolete(""B"", error: false)] public static void Add(this IViewable @this, params object[] obj) { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (8,16): warning CS0618: 'Extensions.Add(IViewable2)' is obsolete: 'A' // v.View(v.Add); Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "v.Add").WithArguments("Extensions.Add(IViewable2)", "A")); } [WorkItem(709114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709114")] [Fact] public void RenameTypeParameterInOverride() { var source = @" public class Base { public virtual void M<T1>(T1 t) { } } public class Derived : Base { public override void M<T2>(T2 t) { } void Test(int c) { M(c); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var callSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var methodSymbol = (IMethodSymbol)model.GetSymbolInfo(callSyntax).Symbol; Assert.Equal(SpecialType.System_Int32, methodSymbol.TypeArguments.Single().SpecialType); } [Fact] [WorkItem(675327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/675327")] public void OverloadInheritanceAsync() { string source = @" using System.Threading.Tasks; using System; class Test { public virtual async Task<int> Goo<U>(Func<Task<U>> f) { await Task.Delay(10); return 1; } } class TestCase : Test { public override async Task<int> Goo<T>(Func<Task<T>> f) { await Task.Delay(10); return 3; } public async Task<int> Goo(Func<Task<long>> f) { await Task.Delay(10); return 2; } public async void Run() { var xxx = await Goo(async () => { // Roslyn error here await Task.Delay(10); return 5m; }); Console.WriteLine(xxx); // 3; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] [WorkItem(675327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/675327")] public void OverloadInheritance001() { string source = @" using System; class Test { public virtual int Goo<U>(Func<U> f) { return 1; } } class TestCase : Test { public override int Goo<T>(Func<T> f) { return 3; } public void Run() { var xxx = Goo(() => { // Roslyn error here return 5m; }); Console.WriteLine(xxx); // 3; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact, WorkItem(718294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718294")] public void ResolveExtensionMethodGroupOverloadWithOptional() { string source = @" using System; class Viewable { static void Main() { IViewable2<object> v = null; v.View(v.Add); } } interface IViewable<T> { void View(Action<T> viewer); } interface IViewable2<T> : IViewable<T> { } static class Extensions { public static void Add<T>(this IViewable<T> @this, T item) { } public static void Add<T>(this IViewable2<T> @this, T item, object obj = null) { } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact, WorkItem(667132, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667132")] public void ExtensionMethodOnComInterfaceMissingRefToken() { string source = @"using System; using System.Runtime.InteropServices; [ComImport, Guid(""cb4ac859-0589-483e-934d-b27845d5fe74"")] interface IGoo { } static class Program { public static void Bar(this IGoo self, ref Guid id) { id = Guid.NewGuid(); } static void Main() { Goo(null); } static void Goo(IGoo o) { Guid g = Guid.NewGuid(); Console.WriteLine(g); o.Bar(g); Console.WriteLine(g); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] [WorkItem(737971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737971")] public void Repro737971a() { var source = @" using System; public class Color { } public class ColorToColor { public static implicit operator ColorToColor(Func<Color, Color> F) { return null; } } public class Test { public void M() { N(_ => default(Color)); } public void N(ColorToColor F) { } public void N(Func<Color, Color> F) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(syntax).Symbol; // Func<Color, Color> is convertible to ColorToColor, but the converse is not true. Assert.Equal("void Test.N(System.Func<Color, Color> F)", symbol.ToTestDisplayString()); } [Fact] [WorkItem(737971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737971")] public void Repro737971b() { var source = @" using System; public class Color { } public class ColorToColor { public static implicit operator ColorToColor(Func<Color, Color> F) { throw null; } } public class Test { public void M() { N(() => _ => default(Color)); } public void N(Func<ColorToColor> F) { } public void N(Func<Func<Color, Color>> F) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(syntax).Symbol; // Func<Func<Color, Color>> is convertible to Func<ColorToColor>, but the converse is not true. Assert.Equal("void Test.N(System.Func<System.Func<Color, Color>> F)", symbol.ToTestDisplayString()); } [Fact] [WorkItem(754406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754406")] public void TestBug754406() { string source = @"interface I {} class G<T> where T : I {} class Program { static void Main(string[] args) { } static void M<T>(G<T> gt1, params int[] i) { M(gt1, 1, 2); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (9,27): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'G<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'I'. // static void M<T>(G<T> gt1, params int[] i) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "gt1").WithArguments("G<T>", "I", "T", "T"), // (11,9): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'G<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'I'. // M(gt1, 1, 2); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "M").WithArguments("G<T>", "I", "T", "T") ); } [Fact] [WorkItem(528811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528811")] public void TestBug528811() { string source = @"using System; delegate byte DL(); class Test { void goo() { EventHandler y = null; y += goo; y += x => 2; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (9,14): error CS0123: No overload for 'goo' matches delegate 'System.EventHandler' // y += goo; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "goo").WithArguments("goo", "System.EventHandler"), // (10,14): error CS1593: Delegate 'System.EventHandler' does not take 1 arguments // y += x => 2; Diagnostic(ErrorCode.ERR_BadDelArgCount, "x => 2").WithArguments("System.EventHandler", "1") ); } [Fact] public void IndexMemberAccessErr005() { var source = @" using System.Collections.Generic; class Program { static void Main(string[] args) { var d = new Dictionary<int, int>() {[""aaa""] = 3}; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,46): error CS1503: Argument 1: cannot convert from 'string' to 'int' // var d = new Dictionary<int, int>() {["aaa"] = 3}; Diagnostic(ErrorCode.ERR_BadArgType, @"""aaa""").WithArguments("1", "string", "int").WithLocation(8, 46) ); } [Fact] public void IndexMemberAccessErr006() { var source = @" using System.Collections.Generic; class Program { static void Main(string[] args) { var d = new int[] {[1] = 3 }; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,28): error CS1513: } expected // var d = new int[] {[1] = 3 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "[").WithLocation(8, 28), // (8,36): error CS1002: ; expected // var d = new int[] {[1] = 3 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(8, 36), // (8,37): error CS1597: Semicolon after method or accessor block is not valid // var d = new int[] {[1] = 3 }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(8, 37), // (10,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(10, 1), // (2,1): info CS8019: Unnecessary using directive. // using System.Collections.Generic; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;").WithLocation(2, 1) ); } [Fact] [WorkItem(655409, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/655409")] public void TestBug655409() { string source = @" using System; class C { static void Main() { M(a => M(b => M(c => M(d => M(e => M(f => a)))))); System.Console.WriteLine(""success""); } static T M<T>(Func<bool, T> x) { return default(T); } static T M<T>(Func<byte, T> x) { return default(T); } static T M<T>(Func<uint, T> x) { return default(T); } static T M<T>(Func<long, T> x) { return default(T); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (8,44): error CS0121: The call is ambiguous between the following methods or properties: 'C.M<T>(System.Func<bool, T>)' and 'C.M<T>(System.Func<byte, T>)' // M(a => M(b => M(c => M(d => M(e => M(f => a)))))); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M<T>(System.Func<bool, T>)", "C.M<T>(System.Func<byte, T>)").WithLocation(8, 44) ); } [Fact, WorkItem(30, "https://roslyn.codeplex.com/workitem/30")] public void BugCodePlex_30_01() { string source1 = @" using System; class C { static void Main() { Goo(() => { return () => 0; ; }); Goo(() => { return () => 0; }); } static void Goo(Func<Func<short>> x) { Console.WriteLine(1); } static void Goo(Func<Func<int>> x) { Console.WriteLine(2); } } "; CompileAndVerify(source1, expectedOutput: @"2 2"); } [Fact, WorkItem(30, "https://roslyn.codeplex.com/workitem/30")] public void BugCodePlex_30_02() { string source1 = @" using System; class C { static void Main() { Test(false); } static void Test(bool val) { Goo(() => { if (val) return () => 0; else return () => (short)0; }); Goo(() => { if (val) return () => (short)0; else return () => 0; }); } static void Goo(Func<Func<short>> x) { Console.WriteLine(1); } static void Goo(Func<Func<int>> x) { Console.WriteLine(2); } } "; CompileAndVerify(source1, expectedOutput: @"1 1"); } [Fact, WorkItem(30, "https://roslyn.codeplex.com/workitem/30")] public void BugCodePlex_30_03() { string source1 = @" using System; class C { static void Main() { Test(false); } static void Test(bool val) { Goo(() => { if (val) return () => 0; else return () => 0; }); } static void Goo(Func<Func<short>> x) { Console.WriteLine(1); } static void Goo(Func<Func<int>> x) { Console.WriteLine(2); } } "; CompileAndVerify(source1, expectedOutput: @"2"); } [Fact] public void ExactlyMatchingAsyncLambda_01() { string source1 = @" using System; using System.Threading.Tasks; class C { static void Main() { #pragma warning disable 1998 Goo(async () => { return 0; ; }); Goo(async () => { return 0; }); Goo(async () => 0); Goo(async () => { return (short)0; ; }); Goo(async () => { return (short)0; }); Goo(async () => (short)0); } static void Goo(Func<Task<short>> x) { Console.WriteLine(1); } static void Goo(Func<Task<int>> x) { Console.WriteLine(2); } } "; var compilation = CreateCompilationWithMscorlib45(source1, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"2 2 2 1 1 1"); } [Fact] public void ExactlyMatchingAsyncLambda_02() { string source1 = @" using System; using System.Threading.Tasks; class C { static void Main() { #pragma warning disable 1998 Goo(() => async () => { return 0; ; }); Goo(() => async () => { return 0; }); Goo(() => async () => 0); Goo(() => { return async () => 0; ; }); Goo(() => { return async () => 0; }); } static void Goo(Func<Func<Task<short>>> x) { Console.WriteLine(1); } static void Goo(Func<Func<Task<int>>> x) { Console.WriteLine(2); } } "; var compilation = CreateCompilationWithMscorlib45(source1, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"2 2 2 2 2"); } [Fact] public void ExactlyMatchingAsyncLambda_03() { string source1 = @" using System; using System.Threading.Tasks; class C { static void Main() { #pragma warning disable 1998 Goo(async () => { return () => 0; }); Goo(async () => { return () => (short)0; }); } static void Goo(Func<Task<Func<short>>> x) { Console.WriteLine(1); } static void Goo(Func<Task<Func<int>>> x) { Console.WriteLine(2); } } "; var compilation = CreateCompilationWithMscorlib45(source1, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"2 1"); } [Fact] [WorkItem(1079899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079899")] [WorkItem(364, "CodePlex")] public void TestBug1079899() { string source = @" namespace A.B { static class X { public static int Test(this int o) { return 1; } } } namespace A.C { static class X { public static int Test(this int o) { return 2; } } } namespace C { using A.B; using static A.C.X; class M { public static int Main() { if (1.Test() != 1) return 1; return 0; } } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (31,19): error CS0121: The call is ambiguous between the following methods or properties: 'X.Test(int)' and 'X.Test(int)' // if (1.Test() != 1) Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("A.B.X.Test(int)", "A.C.X.Test(int)").WithLocation(30, 19) ); Assert.Equal("(30,19): error CS0121: The call is ambiguous between the following methods or properties: 'A.B.X.Test(int)' and 'A.C.X.Test(int)'", DiagnosticFormatter.Instance.Format(comp.GetDiagnostics()[0], EnsureEnglishUICulture.PreferredOrNull)); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_0() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static bool IsThing(Goo t) { return false; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, bool> filter) { System.Console.WriteLine(""Create(Func<T, bool> filter)""); return null; } public static Bar<T, V> Create(Func<T, V> propertyPrev, Func<T, bool> filter = null) { System.Console.WriteLine(""Create(Func<T, V> propertyPrev, Func<T, bool> filter = null)""); return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"Create(Func<T, bool> filter)"); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_1() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static bool IsThing(Goo t) { return false; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, bool> filter) { System.Console.WriteLine(""Create(Func < T, bool > filter)""); return null; } public static Bar<T, V> Create(Func<T, V> propertyPrev, params Func<T, bool>[] filter) { System.Console.WriteLine(""Create(Func<T, V> propertyPrev, params Func<T, bool>[] filter""); return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (25,38): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Bar<T, V>.Create(Func<T, bool>)' and 'Program.Bar<T, V>.Create(Func<T, V>, params Func<T, bool>[])' // var x = Bar<Goo, double>.Create(Goo.IsThing); Diagnostic(ErrorCode.ERR_AmbigCall, "Create").WithArguments("ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, bool>)", "ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, V>, params System.Func<T, bool>[])").WithLocation(25, 38) ); CreateCompilation(source1, options: TestOptions.DebugExe).VerifyDiagnostics( ); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_2() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static double IsThing(Goo t) { return 0; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, bool> filter, params int[] dummy) { System.Console.WriteLine(""Create(Func<T, bool> filter, params int[] dummy)""); return null; } public static Bar<T, V> Create(Func<T, V> propertyPrev, Func<T, bool> filter = null) { System.Console.WriteLine(""Create(Func<T, V> propertyPrev, Func<T, bool> filter = null)""); return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"Create(Func<T, V> propertyPrev, Func<T, bool> filter = null)"); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_3() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static double IsThing(Goo t) { return 0; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, bool> filter, params int[] dummy) { System.Console.WriteLine(""Create(Func<T, bool> filter, params int[] dummy)""); return null; } public static Bar<T, V> Create(Func<T, V> propertyPrev) { System.Console.WriteLine(""Create(Func<T, V> propertyPrev)""); return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (25,38): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Bar<T, V>.Create(Func<T, bool>, params int[])' and 'Program.Bar<T, V>.Create(Func<T, V>)' // var x = Bar<Goo, double>.Create(Goo.IsThing); Diagnostic(ErrorCode.ERR_AmbigCall, "Create").WithArguments("ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, bool>, params int[])", "ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, V>)").WithLocation(25, 38) ); CreateCompilation(source1, options: TestOptions.DebugExe).VerifyDiagnostics( ); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_4() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static double IsThing(Goo t) { return 0; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, V> propertyPrev) { System.Console.WriteLine(""Create(Func<T, V> propertyPrev)""); return null; } public static Bar<T, V> Create(Func<T, bool> filter, params int[] dummy) { System.Console.WriteLine(""Create(Func<T, bool> filter, params int[] dummy)""); return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (25,38): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Bar<T, V>.Create(Func<T, V>)' and 'Program.Bar<T, V>.Create(Func<T, bool>, params int[])' // var x = Bar<Goo, double>.Create(Goo.IsThing); Diagnostic(ErrorCode.ERR_AmbigCall, "Create").WithArguments("ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, V>)", "ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, bool>, params int[])").WithLocation(25, 38) ); CreateCompilation(source1, options: TestOptions.DebugExe).VerifyDiagnostics( ); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_5() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static bool IsThing(Goo t) { return false; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, V> propertyPrev, params Func<T, bool>[] filter) { System.Console.WriteLine(""Create(Func<T, V> propertyPrev, params Func<T, bool>[] filter""); return null; } public static Bar<T, V> Create(Func<T, bool> filter) { System.Console.WriteLine(""Create(Func < T, bool > filter)""); return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (25,38): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Bar<T, V>.Create(Func<T, V>, params Func<T, bool>[])' and 'Program.Bar<T, V>.Create(Func<T, bool>)' // var x = Bar<Goo, double>.Create(Goo.IsThing); Diagnostic(ErrorCode.ERR_AmbigCall, "Create").WithArguments("ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, V>, params System.Func<T, bool>[])", "ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, bool>)").WithLocation(25, 38) ); CreateCompilation(source1, options: TestOptions.DebugExe).VerifyDiagnostics( ); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_6() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static bool IsThing(Goo t) { return false; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, bool> filter, params int[] extra) { return null; } public static Bar<T, V> Create(Func<T, V> propertyPrev, params int[] extra) { return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (23,38): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Bar<T, V>.Create(Func<T, bool>, params int[])' and 'Program.Bar<T, V>.Create(Func<T, V>, params int[])' // var x = Bar<Goo, double>.Create(Goo.IsThing); Diagnostic(ErrorCode.ERR_AmbigCall, "Create").WithArguments("ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, bool>, params int[])", "ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, V>, params int[])").WithLocation(23, 38) ); CreateCompilation(source1, options: TestOptions.DebugExe).VerifyDiagnostics( ); } [Fact, WorkItem(1081302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081302"), WorkItem(371, "Devdiv")] public void Bug1081302_0() { string source1 = @" using System; namespace ConsoleApplication2 { public static class Goo { public static U IfNotNull<T, U>(this T value, Func<T, U> selector, U defaultValue = default(U)) { System.Console.WriteLine(""IfNotNull<T, U>(this T value, Func<T, U> selector, U defaultValue = default(U))""); return value != null ? selector(value) : defaultValue; } public static U IfNotNull<T, U>(this T? source, Func<T, U> selector) where T : struct { System.Console.WriteLine(""IfNotNull<T, U>(this T? source, Func<T, U> selector)""); return source.HasValue ? selector(source.Value) : default(U); } } class Program { static void Main(string[] args) { double? val = null; var d1 = val.IfNotNull(v => v / 100); var d2 = Goo.IfNotNull(val, v => v / 100); } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"IfNotNull<T, U>(this T? source, Func<T, U> selector) IfNotNull<T, U>(this T? source, Func<T, U> selector)"); } [Fact, WorkItem(1081302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081302"), WorkItem(371, "Devdiv")] public void Bug1081302_1() { string source1 = @" using System; namespace ConsoleApplication2 { public static class Goo { public static U IfNotNull<T, U>(this T value, Func<T, U> selector, params U[] defaultValue) { System.Console.WriteLine(""IfNotNull<T, U>(this T value, Func<T, U> selector, params U[] defaultValue)""); return value != null ? selector(value) : defaultValue[0]; } public static U IfNotNull<T, U>(this T? source, Func<T, U> selector) where T : struct { System.Console.WriteLine(""IfNotNull<T, U>(this T? source, Func<T, U> selector)""); return source.HasValue ? selector(source.Value) : default(U); } } class Program { static void Main(string[] args) { double? val = null; var d1 = val.IfNotNull(v => v / 100); var d2 = Goo.IfNotNull(val, v => v / 100); } } } "; var compilation = CreateCompilationWithMscorlib40(source1, new[] { TestMetadata.Net40.SystemCore }, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); } [Fact, WorkItem(1081302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081302"), WorkItem(371, "Devdiv")] public void Bug1081302_2() { string source1 = @" using System; namespace ConsoleApplication2 { public static class Goo { public static U IfNotNull<T, U>(this T? source, Func<T, U> selector) where T : struct { System.Console.WriteLine(""IfNotNull<T, U>(this T? source, Func<T, U> selector)""); return source.HasValue ? selector(source.Value) : default(U); } public static U IfNotNull<T, U>(this T value, Func<T, U> selector, params U[] defaultValue) { System.Console.WriteLine(""IfNotNull<T, U>(this T value, Func<T, U> selector, params U[] defaultValue)""); return value != null ? selector(value) : defaultValue[0]; } } class Program { static void Main(string[] args) { double? val = null; var d1 = val.IfNotNull(v => v / 100); var d2 = Goo.IfNotNull(val, v => v / 100); } } } "; var compilation = CreateCompilationWithMscorlib40(source1, new[] { TestMetadata.Net40.SystemCore }, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); } [Fact] public void ExactParameterMatchAndOptionals() { string source1 = @" class CTest { static void Main() { M1(0); } static void M1(int x) { System.Console.WriteLine(""M1(int x)""); } static void M1(int x, int y = 0) { System.Console.WriteLine(""M1(int x, int y = 0)""); } static void M1(int x, params int [] y) { System.Console.WriteLine(""M1(int x, params int [] y)""); } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"M1(int x)"); } [Fact] [WorkItem(1034429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1034429")] public void TestBug1034429() { string source = @" using System.Security.Permissions; class Program { [A(SecurityAction.Assert)] [B(p2: SecurityAction.Assert, p1: 0)] [C(p3: ""again"", p2: SecurityAction.Assert, p1: 0)] static void Main() { } } public class A : CodeAccessSecurityAttribute { public A(params SecurityAction) { } } public class B : CodeAccessSecurityAttribute { public B(int p1, params SecurityAction p2) { } } public class C : CodeAccessSecurityAttribute { public C(int p1, params SecurityAction p2, string p3) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (16,35): error CS1001: Identifier expected // public A(params SecurityAction) Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(16, 35), // (30,22): error CS0231: A params parameter must be the last parameter in a formal parameter list // public C(int p1, params SecurityAction p2, string p3) Diagnostic(ErrorCode.ERR_ParamsLast, "params SecurityAction p2").WithLocation(30, 22), // (14,14): error CS0534: 'A' does not implement inherited abstract member 'SecurityAttribute.CreatePermission()' // public class A : CodeAccessSecurityAttribute Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "A").WithArguments("A", "System.Security.Permissions.SecurityAttribute.CreatePermission()").WithLocation(14, 14), // (28,14): error CS0534: 'C' does not implement inherited abstract member 'SecurityAttribute.CreatePermission()' // public class C : CodeAccessSecurityAttribute Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "System.Security.Permissions.SecurityAttribute.CreatePermission()").WithLocation(28, 14), // (21,14): error CS0534: 'B' does not implement inherited abstract member 'SecurityAttribute.CreatePermission()' // public class B : CodeAccessSecurityAttribute Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "System.Security.Permissions.SecurityAttribute.CreatePermission()").WithLocation(21, 14), // (16,14): error CS0225: The params parameter must be a single dimensional array // public A(params SecurityAction) Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(16, 14), // (23,22): error CS0225: The params parameter must be a single dimensional array // public B(int p1, params SecurityAction p2) Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(23, 22), // (30,22): error CS0225: The params parameter must be a single dimensional array // public C(int p1, params SecurityAction p2, string p3) Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(30, 22), // (7,6): error CS7048: First argument to a security attribute must be a valid SecurityAction // [B(p2: SecurityAction.Assert, p1: 0)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "B").WithLocation(7, 6), // (8,6): error CS7048: First argument to a security attribute must be a valid SecurityAction // [C(p3: "again", p2: SecurityAction.Assert, p1: 0)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "C").WithLocation(8, 6), // (16,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'CodeAccessSecurityAttribute.CodeAccessSecurityAttribute(SecurityAction)' // public A(params SecurityAction) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "A").WithArguments("action", "System.Security.Permissions.CodeAccessSecurityAttribute.CodeAccessSecurityAttribute(System.Security.Permissions.SecurityAction)").WithLocation(16, 12), // (23,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'CodeAccessSecurityAttribute.CodeAccessSecurityAttribute(SecurityAction)' // public B(int p1, params SecurityAction p2) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "B").WithArguments("action", "System.Security.Permissions.CodeAccessSecurityAttribute.CodeAccessSecurityAttribute(System.Security.Permissions.SecurityAction)").WithLocation(23, 12), // (30,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'CodeAccessSecurityAttribute.CodeAccessSecurityAttribute(SecurityAction)' // public C(int p1, params SecurityAction p2, string p3) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("action", "System.Security.Permissions.CodeAccessSecurityAttribute.CodeAccessSecurityAttribute(System.Security.Permissions.SecurityAction)").WithLocation(30, 12)); } [WorkItem(18875, "https://github.com/dotnet/roslyn/issues/18875")] [Fact] public void InvalidParamsPositionCSharp() { const string source = @" public class A { public static void Goo(params int[] vals, bool truth) { } public static void Bar() { // 1 shouldn't show CS1503 Argument 1: cannot convert from 'int' to 'int' Goo(1, true); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,28): error CS0231: A params parameter must be the last parameter in a formal parameter list // public static void Goo(params int[] vals, bool truth) Diagnostic(ErrorCode.ERR_ParamsLast, "params int[] vals"), // (12,13): error CS1503: Argument 1: cannot convert from 'int' to 'params int[]' // Goo(1, true); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "params int[]").WithLocation(12, 13)); } [WorkItem(2249, "https://github.com/dotnet/roslyn/issues/2249")] [Fact] public void TestRefMethodGroup() { var source = @"using System; class Program { static void M() { Console.WriteLine(""pass""); } public static void Main(string[] args) { Action a1 = new Action(ref M); a1(); Action a2 = new Action(out a1); a2(); } }"; CompileAndVerify(source, expectedOutput: @"pass pass").VerifyDiagnostics(); CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (12,36): error CS1657: Cannot use 'M' as a ref or out value because it is a 'method group' // Action a1 = new Action(ref M); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "M").WithArguments("M", "method group").WithLocation(12, 36), // (14,36): error CS0149: Method name expected // Action a2 = new Action(out a1); Diagnostic(ErrorCode.ERR_MethodNameExpected, "a1").WithLocation(14, 36) ); } [Fact, WorkItem(1157097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1157097"), WorkItem(2298, "https://github.com/dotnet/roslyn/issues/2298")] public void ParamsAndOptionals() { string source1 = @" using System; using System.Collections.Generic; using VS2015CompilerBug; public static class Extensions { //extension with params keyword public static int Properties(this IFirstInterface source, params int[] x) { System.Console.WriteLine(""int Properties(this IFirstInterface source, params int[] x)""); return 0; } public static bool Properties(this ISecondInterface source, int x = 0, params int[] y) { System.Console.WriteLine(""bool Properties(this ISecondInterface source, int x = 0, params int[] y)""); return true; } //extension without params keyword public static int Properties2(this IFirstInterface source) { System.Console.WriteLine(""int Properties2(this IFirstInterface source)""); return 0; } public static bool Properties2(this ISecondInterface source, int x = 0) { System.Console.WriteLine(""bool Properties2(this ISecondInterface source, int x = 0)""); return true; } } namespace VS2015CompilerBug { public interface IFirstInterface { } public interface ISecondInterface { } public interface IFinalInterface : ISecondInterface, IFirstInterface { } public class VS2015CompilerBug { public static void Main() { IFinalInterface x = default(IFinalInterface); var properties = x.Properties(); var properties2 = x.Properties2(); (new VS2015CompilerBug()).Test2(); } private void Test2(int x = 5, params int[] y) { System.Console.WriteLine(""void Test2(int x = 5, params int[] y)""); } private void Test2(params int[] x) { System.Console.WriteLine(""void Test2(params int[] x)""); } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"int Properties(this IFirstInterface source, params int[] x) int Properties2(this IFirstInterface source) void Test2(params int[] x)"); } [Fact, WorkItem(1157097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1157097"), WorkItem(2298, "https://github.com/dotnet/roslyn/issues/2298")] public void TieBreakOnNumberOfDeclaredParameters_01() { string source1 = @" namespace VS2015CompilerBug { public class VS2015CompilerBug { public static void Main() { (new VS2015CompilerBug()).Test2(1); (new VS2015CompilerBug()).Test2(1, 2); (new VS2015CompilerBug()).Test2(1, 2, 3); (new VS2015CompilerBug()).Test3(1, 2); (new VS2015CompilerBug()).Test3(1, 2, 3); (new VS2015CompilerBug()).Test3(1, 2, 3, 4); } private void Test2(int x, params int[] y) { System.Console.WriteLine(""void Test2(int x, params int[] y)""); } private void Test2(params int[] x) { System.Console.WriteLine(""void Test2(params int[] x)""); } private void Test3(int x, int y, params int[] z) { System.Console.WriteLine(""void Test3(int x, int y, params int[] z)""); } private void Test3(int x, params int[] y) { System.Console.WriteLine(""void Test3(int x, params int[] y)""); } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"void Test2(int x, params int[] y) void Test2(int x, params int[] y) void Test2(int x, params int[] y) void Test3(int x, int y, params int[] z) void Test3(int x, int y, params int[] z) void Test3(int x, int y, params int[] z)"); } [Fact, WorkItem(1157097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1157097"), WorkItem(2298, "https://github.com/dotnet/roslyn/issues/2298")] public void TieBreakOnNumberOfDeclaredParameters_02() { string source1 = @" namespace VS2015CompilerBug { public class VS2015CompilerBug { public static void Main() { (new VS2015CompilerBug()).Test2(1, 2); (new VS2015CompilerBug()).Test3(1, 2, 3); } private void Test2(int x = 0, int y = 0) { System.Console.WriteLine(""void Test2(int x = 0, int y = 0)""); } private void Test2(int x, int y = 0, int z = 0) { System.Console.WriteLine(""void Test2(int x, int y = 0, int z = 0)""); } private void Test3(int x, int y, int z = 0, int u = 0) { System.Console.WriteLine(""void Test3(int x, int y, int z = 0, int u = 0)""); } private void Test3(int x, int y = 0, int z = 0) { System.Console.WriteLine(""void Test3(int x, int y = 0, int z = 0)""); } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"void Test2(int x = 0, int y = 0) void Test3(int x, int y = 0, int z = 0)"); } [Fact, WorkItem(1157097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1157097"), WorkItem(2298, "https://github.com/dotnet/roslyn/issues/2298")] public void TieBreakOnNumberOfDeclaredParameters_03() { string source1 = @" namespace VS2015CompilerBug { public class VS2015CompilerBug { public static void Main() { (new VS2015CompilerBug()).Test2(1); (new VS2015CompilerBug()).Test3(1, 2); } private void Test2(int x = 0, int y = 0) { } private void Test2(int x, int y = 0, int z = 0) { } private void Test3(int x, int y, int z = 0, int u = 0) { } private void Test3(int x, int y = 0, int z = 0) { } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (9,39): error CS0121: The call is ambiguous between the following methods or properties: 'VS2015CompilerBug.Test2(int, int)' and 'VS2015CompilerBug.Test2(int, int, int)' // (new VS2015CompilerBug()).Test2(1); Diagnostic(ErrorCode.ERR_AmbigCall, "Test2").WithArguments("VS2015CompilerBug.VS2015CompilerBug.Test2(int, int)", "VS2015CompilerBug.VS2015CompilerBug.Test2(int, int, int)").WithLocation(9, 39), // (10,39): error CS0121: The call is ambiguous between the following methods or properties: 'VS2015CompilerBug.Test3(int, int, int, int)' and 'VS2015CompilerBug.Test3(int, int, int)' // (new VS2015CompilerBug()).Test3(1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "Test3").WithArguments("VS2015CompilerBug.VS2015CompilerBug.Test3(int, int, int, int)", "VS2015CompilerBug.VS2015CompilerBug.Test3(int, int, int)").WithLocation(10, 39) ); } [Fact, WorkItem(2533, "https://github.com/dotnet/roslyn/issues/2533")] public void TieBreakOnNumberOfDeclaredParameters_04() { string source1 = @" public class Test { static void M1(object o, object o1, string s, object o2 = null) { System.Console.WriteLine(""void M1(object o, object o1, string s, object o2 = null) ""); } static void M1(string s, object o1, object o2) { System.Console.WriteLine(""void M1(string s, object o1, object o2)""); } public static void Main() { M1(""M"", null, null); } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"void M1(string s, object o1, object o2)"); } [Fact, WorkItem(2533, "https://github.com/dotnet/roslyn/issues/2533")] public void TieBreakOnNumberOfDeclaredParameters_05() { string source1 = @" public class Test { static void M1(object o, object o1, string s) { } static void M1(string s, object o1, object o2) { } public static void Main() { M1(""M"", null, null); } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.M1(object, object, string)' and 'Test.M1(string, object, object)' // M1("M", null, null); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("Test.M1(object, object, string)", "Test.M1(string, object, object)").WithLocation(14, 9) ); } [Fact, WorkItem(4424, "https://github.com/dotnet/roslyn/issues/4424")] public void TieBreakOnNumberOfDeclaredParameters_06() { string source1 = @" class Test { static void Fn(string x = """", string y = """", params object[] p) { System.Console.WriteLine(1); } static void Fn(string x, params object[] p) { System.Console.WriteLine(2); } static void Main() { Fn(""Hello"", p: ""World""); } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"2"); } [Fact, WorkItem(1099752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099752"), WorkItem(2291, "https://github.com/dotnet/roslyn/issues/2291")] public void BetterErrorMessage_01() { string source1 = @" class C { static void F1(object x, object y) { } static void F1(object x, object w, object z) { } static void F2(object x, object w, object z) { } static void F2(object x, object y) { } static void Main() { F1(x: 1, y: 2, z: 3); F2(x: 1, y: 2, z: 3); M1(0, x: 1); M2(0, x: 1); M3(0, x: 1); M4(0, x: 1); M5(0, x: 1); M6(0, x: 1); M7(0, x: 1); M9(0, x: 1); M8(0, x: 1); M10(0, x: 1); M11(x: 1, y: 2, z: 3); M12(1, 2, 3, 4); M13(1, 2, 3, 4); M14(1, 2, 3); M15(1, z: 0); M16(1, z: 0); M17(1, x: 2, y: 3); M18(1, x: 2, y: 3); M19(1, x: 2, y: 3); } static void M1() { } static void M2() { } static void M2(int u, int w) { } static void M3(int u, int w) { } static void M3() { } static void M4() { } static void M4(int u, int w) { } static void M4(int x) { } static void M5() { } static void M5(int x) { } static void M5(int u, int w) { } static void M6(int x) { } static void M6() { } static void M6(int u, int w) { } static void M7() { } static void M7(int u, int w) { } static void M7(int x) { } static void M7(int u, int x, int w) { } static void M8() { } static void M8(int u, int w) { } static void M8(int u, int x, int w) { } static void M8(int x) { } static void M9() { } static void M9(int u, int x, int w) { } static void M9(int u, int w) { } static void M9(int x) { } static void M10(int u, int x, int w) { } static void M10() { } static void M10(int u, int w) { } static void M10(int x) { } static void M11(object x, int y) { } static void M11(object x, short y) { } static void M12(object x, object y) { } static void M12(object x, object y, object z) { } static void M13(object x, object y, object z) { } static void M13(object x, object y) { } static void M14(object x, int y) { } static void M14(object x, short y) { } static void M15(object x, int y, object z = null) { } static void M15(object x, short y, object z = null) { } static void M16(object x, int y, object z = null) { } static void M16(object x, short y, object z = null) { } static void M17(object x, int y, int z) { } static void M17(object y, short x, int z) { } static void M18(object y, int x, int z) { } static void M18(object x, short y, int z) { } static void M19(object x, int y, int z) { } static void M19(object x, short y, int z) { } } "; var compilation = CreateCompilation(source1); compilation.VerifyDiagnostics( // (12,24): error CS1739: The best overload for 'F1' does not have a parameter named 'z' // F1(x: 1, y: 2, z: 3); Diagnostic(ErrorCode.ERR_BadNamedArgument, "z").WithArguments("F1", "z").WithLocation(12, 24), // (13,24): error CS1739: The best overload for 'F2' does not have a parameter named 'z' // F2(x: 1, y: 2, z: 3); Diagnostic(ErrorCode.ERR_BadNamedArgument, "z").WithArguments("F2", "z").WithLocation(13, 24), // (15,9): error CS1501: No overload for method 'M1' takes 2 arguments // M1(0, x: 1); Diagnostic(ErrorCode.ERR_BadArgCount, "M1").WithArguments("M1", "2").WithLocation(15, 9), // (17,15): error CS1739: The best overload for 'M2' does not have a parameter named 'x' // M2(0, x: 1); Diagnostic(ErrorCode.ERR_BadNamedArgument, "x").WithArguments("M2", "x").WithLocation(17, 15), // (18,15): error CS1739: The best overload for 'M3' does not have a parameter named 'x' // M3(0, x: 1); Diagnostic(ErrorCode.ERR_BadNamedArgument, "x").WithArguments("M3", "x").WithLocation(18, 15), // (20,15): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // M4(0, x: 1); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(20, 15), // (21,15): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // M5(0, x: 1); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(21, 15), // (22,15): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // M6(0, x: 1); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(22, 15), // (24,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'w' of 'C.M7(int, int, int)' // M7(0, x: 1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M7").WithArguments("w", "C.M7(int, int, int)").WithLocation(24, 9), // (25,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'w' of 'C.M9(int, int, int)' // M9(0, x: 1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M9").WithArguments("w", "C.M9(int, int, int)").WithLocation(25, 9), // (26,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'w' of 'C.M8(int, int, int)' // M8(0, x: 1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M8").WithArguments("w", "C.M8(int, int, int)").WithLocation(26, 9), // (27,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'w' of 'C.M10(int, int, int)' // M10(0, x: 1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M10").WithArguments("w", "C.M10(int, int, int)").WithLocation(27, 9), // (29,25): error CS1739: The best overload for 'M11' does not have a parameter named 'z' // M11(x: 1, y: 2, z: 3); Diagnostic(ErrorCode.ERR_BadNamedArgument, "z").WithArguments("M11", "z").WithLocation(29, 25), // (31,9): error CS1501: No overload for method 'M12' takes 4 arguments // M12(1, 2, 3, 4); Diagnostic(ErrorCode.ERR_BadArgCount, "M12").WithArguments("M12", "4").WithLocation(31, 9), // (32,9): error CS1501: No overload for method 'M13' takes 4 arguments // M13(1, 2, 3, 4); Diagnostic(ErrorCode.ERR_BadArgCount, "M13").WithArguments("M13", "4").WithLocation(32, 9), // (34,9): error CS1501: No overload for method 'M14' takes 3 arguments // M14(1, 2, 3); Diagnostic(ErrorCode.ERR_BadArgCount, "M14").WithArguments("M14", "3").WithLocation(34, 9), // (36,9): error CS1501: No overload for method 'M15' takes 2 arguments // M15(1, z: 0); Diagnostic(ErrorCode.ERR_BadArgCount, "M15").WithArguments("M15", "2").WithLocation(36, 9), // (37,9): error CS1501: No overload for method 'M16' takes 2 arguments // M16(1, z: 0); Diagnostic(ErrorCode.ERR_BadArgCount, "M16").WithArguments("M16", "2").WithLocation(37, 9), // (39,22): error CS1744: Named argument 'y' specifies a parameter for which a positional argument has already been given // M17(1, x: 2, y: 3); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "y").WithArguments("y").WithLocation(39, 22), // (40,22): error CS1744: Named argument 'y' specifies a parameter for which a positional argument has already been given // M18(1, x: 2, y: 3); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "y").WithArguments("y").WithLocation(40, 22), // (41,16): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // M19(1, x: 2, y: 3); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(41, 16) ); } [Fact, WorkItem(2631, "https://github.com/dotnet/roslyn/issues/2631")] public void ArglistCompilerCrash() { var source = @"class Program { static void M(object x) { } static void M(object x, object y) { } static void M(object x, object y, object z) { } static void M(object x, object y, object z, __arglist) { } static void M(object x, params object[] args) { } static void Main(string[] args) { M(x: 1, y: 2, z: 3); } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [Fact, WorkItem(1171723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1171723"), WorkItem(2985, "https://github.com/dotnet/roslyn/issues/2985")] public void BetterErrorMessage_02() { string source1 = @" using FluentAssertions; using Extensions; using System; using System.Collections.Generic; using System.Collections; namespace FluentAssertions { public static class AssertionExtensions { public static object Should(this object actualValue) { throw null; } public static object Should(this IEnumerable actualValue) { throw null; } public static object Should<T>(this IEnumerable<T> actualValue) { throw null; } public static object Should<TKey, TValue>(this IDictionary<TKey, TValue> actualValue) { throw null; } } } namespace Extensions { public static class TestExtensions { public static object Should<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> actualValue) { throw null; } } } namespace ClassLibraryOverloadResolution { public class Class1 { void goo() { Dictionary<String, String> dict = null; dict.Should(); } } }"; var compilation = CreateCompilationWithMscorlib45(source1); compilation.VerifyDiagnostics( // (34,18): error CS0121: The call is ambiguous between the following methods or properties: 'FluentAssertions.AssertionExtensions.Should<TKey, TValue>(System.Collections.Generic.IDictionary<TKey, TValue>)' and 'Extensions.TestExtensions.Should<TKey, TValue>(System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>)' // dict.Should(); Diagnostic(ErrorCode.ERR_AmbigCall, "Should").WithArguments("FluentAssertions.AssertionExtensions.Should<TKey, TValue>(System.Collections.Generic.IDictionary<TKey, TValue>)", "Extensions.TestExtensions.Should<TKey, TValue>(System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>)").WithLocation(34, 18) ); } [Fact, WorkItem(4970, "https://github.com/dotnet/roslyn/issues/4970")] public void GenericExtensionMethodWithConstraintsAsADelegate() { var source = @" using System; public interface IDetail<T> { } public interface IMain<T> { } public class MyClass { static void Main() { Principal aPrincipal = new Principal(); Test(aPrincipal.RemoveDetail); Test(aPrincipal.RemoveDetail<Principal,Permission>); Action<Permission> a; a = aPrincipal.RemoveDetail; a(null); a = aPrincipal.RemoveDetail<Principal,Permission>; a(null); } static void Test(Action<Permission> a) { a(null); } } public class Permission : IDetail<Principal> { } public class Principal : IMain<Permission> { } public static class Class { public static void RemoveDetail<TMain, TChild>(this TMain main, TChild child) where TMain : class, IMain<TChild> where TChild : class, IDetail<TMain> { System.Console.WriteLine(""RemoveDetail""); } }"; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"RemoveDetail RemoveDetail RemoveDetail RemoveDetail"); } [Fact, WorkItem(2544, "https://github.com/dotnet/roslyn/issues/2544")] public void GetSymbolInfo_Inaccessible() { var source = @" class C { private void M(D d) { d.M(1); } } class D { private void M(int i) { } private void M(double d) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (6,11): error CS0122: 'D.M(int)' is inaccessible due to its protection level // d.M(1); Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("D.M(int)").WithLocation(6, 11) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var callSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(callSyntax); Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.Equal("void D.M(System.Int32 i)", candidates[0].ToTestDisplayString()); Assert.Equal("void D.M(System.Double d)", candidates[1].ToTestDisplayString()); } [Fact, WorkItem(12061, "https://github.com/dotnet/roslyn/issues/12061")] public void RecursiveBetterBetterness01() { string source = @" delegate Del1 Del1(); delegate Del2 Del2(); class Program { static void Method(Del1 del1) { } static void Method(Del2 del2) { } static void Main() { Method(() => null); } } "; CreateCompilation(source).VerifyDiagnostics( // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(Del1)' and 'Program.Method(Del2)' // Method(() => null); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(Del1)", "Program.Method(Del2)").WithLocation(11, 9) ); } [Fact, WorkItem(12061, "https://github.com/dotnet/roslyn/issues/12061")] public void RecursiveBetterBetterness02() { string source = @" delegate Del2 Del1(); delegate Del1 Del2(); class Program { static void Method(Del1 del1) { } static void Method(Del2 del2) { } static void Main() { Method(() => null); } } "; CreateCompilation(source).VerifyDiagnostics( // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(Del1)' and 'Program.Method(Del2)' // Method(() => null); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(Del1)", "Program.Method(Del2)").WithLocation(11, 9) ); } [Fact, WorkItem(12061, "https://github.com/dotnet/roslyn/issues/12061")] public void RecursiveBetterBetterness03() { string source = @" delegate Del2<Del1<T>> Del1<T>(); delegate Del1<Del2<T>> Del2<T>(); class Program { static void Method(Del1<string> del1) { } static void Method(Del2<string> del2) { } static void Main() { Method(() => null); } } "; CreateCompilation(source).VerifyDiagnostics( // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(Del1<string>)' and 'Program.Method(Del2<string>)' // Method(() => null); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(Del1<string>)", "Program.Method(Del2<string>)").WithLocation(11, 9) ); } [Fact, WorkItem(12061, "https://github.com/dotnet/roslyn/issues/12061")] public void RecursiveBetterBetterness04() { string source = @" using System.Threading.Tasks; delegate Task<Del2> Del1(); delegate Task<Del1> Del2(); class Program { static void Method(Del1 del1) { } static void Method(Del2 del2) { } static void Main() { Method(() => null); } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(Del1)' and 'Program.Method(Del2)' // Method(() => null); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(Del1)", "Program.Method(Del2)").WithLocation(12, 9) ); } [Fact, WorkItem(13380, "https://github.com/dotnet/roslyn/issues/13380")] public void ImplicitNullableOperatorInEquality() { string source = @"public class Class1 { public static void Main(string[] args) { var a = default(Registration<Something>); var x = (a == Something.Bad); //this line fails in VS2015.3 System.Console.WriteLine(x); } } public struct Registration<T> where T : struct { public static implicit operator T? (Registration<T> registration) { return null; } } public enum Something { Good, Bad }"; // should be NO errors. CompileAndVerify(source, expectedOutput: @"False"); } [Fact, WorkItem(16478, "https://github.com/dotnet/roslyn/issues/16478")] public void AmbiguousInference_01() { string source = @" using System; using System.Collections.Generic; public class Test { public static void Assert<T>(T a, T b) { Console.WriteLine(""Non collection""); } public static void Assert<T>(IEnumerable<T> a, IEnumerable<T> b) { Console.WriteLine(""Collection""); } public static void Main() { string[] a = new[] { ""A"" }; StringValues b = new StringValues(); Assert(a, b); Assert(b, a); } private class StringValues : List<string> { public static implicit operator StringValues(string[] values) { return new StringValues(); } public static implicit operator string[] (StringValues value) { return new string[0]; } } }"; CompileAndVerify(source, expectedOutput: @"Collection Collection"); } [Fact, WorkItem(16478, "https://github.com/dotnet/roslyn/issues/16478")] public void AmbiguousInference_02() { string source = @" using System; using System.Collections.Generic; public class Test { public static void Assert<T>(T a, T b) { Console.WriteLine(""Non collection""); } public static void Main() { string[] a = new[] { ""A"" }; StringValues b = new StringValues(); Assert(a, b); Assert(b, a); } private class StringValues : List<string> { public static implicit operator StringValues(string[] values) { return new StringValues(); } public static implicit operator string[] (StringValues value) { return new string[0]; } } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (17,9): error CS0411: The type arguments for method 'Test.Assert<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Assert(a, b); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Assert").WithArguments("Test.Assert<T>(T, T)").WithLocation(17, 9), // (18,9): error CS0411: The type arguments for method 'Test.Assert<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Assert(b, a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Assert").WithArguments("Test.Assert<T>(T, T)").WithLocation(18, 9) ); } /// <summary> /// Inapplicable extension methods with bad arguments, with overloads where /// the instance argument can be converted to 'this' before overloads where the /// instance argument cannot be converted. Overload resolution should choose /// a method with convertible 'this', as with the native compiler. /// </summary> [Fact] public void InapplicableExtensionMethods_1() { string source = @"using System; class A { } class B { } class C { static void Main() { var a = new A(); a.F(o => {}, a); } } static class E { internal static void F(this A x, Action<object> y) { } internal static void F(this A x, Action<object> y, B z) { } internal static void F(this B x, Action<object> y) { } internal static void F(this B x, Action<object> y, A z) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (9,22): error CS1503: Argument 3: cannot convert from 'A' to 'B' // a.F(o => {}, a); Diagnostic(ErrorCode.ERR_BadArgType, "a").WithArguments("3", "A", "B").WithLocation(9, 22)); } /// <summary> /// Inapplicable extension methods with bad arguments, with overloads where /// the instance argument can be converted to 'this' after overloads where the /// instance argument cannot be converted. Overload resolution should choose /// a method where non-convertible 'this', as with the native compiler. /// </summary> [Fact] public void InapplicableExtensionMethods_2() { string source = @"using System; class A { } class B { } class C { static void Main() { var a = new A(); a.F(o => {}, a); } } static class E { internal static void F(this B x, Action<object> y) { } internal static void F(this B x, Action<object> y, A z) { } internal static void F(this A x, Action<object> y) { } internal static void F(this A x, Action<object> y, B z) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (9,9): error CS1929: 'A' does not contain a definition for 'F' and the best extension method overload 'E.F(B, Action<object>, A)' requires a receiver of type 'B' // a.F(o => {}, a); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("A", "F", "E.F(B, System.Action<object>, A)", "B").WithLocation(9, 9)); } [Fact] public void CircularImplicitConversions() { string source = @" class A { public static implicit operator B(A a) => null; } class B { public static implicit operator C(B b) => null; } class C { public static implicit operator A(C c) => null; } class D { public static implicit operator A(D d) => null; public static implicit operator B(D d) => null; public static implicit operator C(D d) => null; } class E { public static void F(A a) {} public static void F(B b) {} public static void F(C c) {} } public class Program { public static void Main() => E.F(new D()); } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (28,36): error CS0121: The call is ambiguous between the following methods or properties: 'E.F(A)' and 'E.F(B)' // public static void Main() => E.F(new D()); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("E.F(A)", "E.F(B)").WithLocation(28, 36) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var callSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(callSyntax); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(3, candidates.Length); Assert.Equal("void E.F(A a)", candidates[0].ToTestDisplayString()); Assert.Equal("void E.F(B b)", candidates[1].ToTestDisplayString()); Assert.Equal("void E.F(C c)", candidates[2].ToTestDisplayString()); } [Fact] public void PassingArgumentsToInParameters_RefKind_None() { var code = @" public static class Program { public static void Method(in int p) { System.Console.WriteLine(p); } public static void Main() { int x = 5; Method(x); } }"; CompileAndVerify(code, expectedOutput: "5"); } [Fact] public void PassingArgumentsToInParameters_RefKind_Ref() { var code = @" public static class Program { public static void Method(in int p) { System.Console.WriteLine(p); } public static void Main() { int x = 5; Method(ref x); } }"; CreateCompilation(code).VerifyDiagnostics( // (11,20): error CS1615: Argument 1 may not be passed with the 'ref' keyword // Method(ref x); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "x").WithArguments("1", "ref").WithLocation(11, 20)); } [Fact] public void PassingArgumentsToInParameters_RefKind_Out() { var code = @" public static class Program { public static void Method(in int p) { System.Console.WriteLine(p); } public static void Main() { int x; Method(out x); } }"; CreateCompilation(code).VerifyDiagnostics( // (11,20): error CS1615: Argument 1 may not be passed with the 'out' keyword // Method(out x); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "x").WithArguments("1", "out").WithLocation(11, 20)); } [Fact] public void PassingArgumentsToInParameters_RefKind_In() { var code = @" public static class Program { public static void Method(in int p) { System.Console.WriteLine(p); } public static void Main() { int x = 5; Method(in x); } }"; CompileAndVerify(code, expectedOutput: "5"); } [WorkItem(20799, "https://github.com/dotnet/roslyn/issues/20799")] [Fact] public void PassingArgumentsToInParameters_RefKind_None_WrongType() { var code = @" public static class Program { public static void Method(in int p) { System.Console.WriteLine(p); } public static void Main() { System.Exception x = null; Method(x); } }"; CreateCompilation(code).VerifyDiagnostics( // (11,16): error CS1503: Argument 1: cannot convert from 'System.Exception' to 'in int' // Method(x); Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "System.Exception", "in int").WithLocation(11, 16) ); } [WorkItem(20799, "https://github.com/dotnet/roslyn/issues/20799")] [Fact] public void PassingArgumentsToRefParameters_RefKind_None_WrongType() { var code = @" public static class Program { public static void Method(ref int p) { System.Console.WriteLine(p); } public static void Main() { System.Exception x = null; Method(x); } }"; CreateCompilation(code).VerifyDiagnostics( // (11,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // Method(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref").WithLocation(11, 16) ); } [Fact] public void PassingInArgumentsOverloadedOnIn() { var code = @" public static class Program { public static void Method(in int x) { System.Console.WriteLine(""in: "" + x); } public static void Method(int x) { System.Console.WriteLine(""val: "" + x); } public static void Main() { int x = 5; Method(in x); Method(x); Method(5); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 5 val: 5 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_Inverse() { var code = @" public static class Program { public static void Method(int x) { System.Console.WriteLine(""val: "" + x); } public static void Method(in int x) { System.Console.WriteLine(""in: "" + x); } public static void Main() { int x = 5; Method(in x); Method(x); Method(5); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 5 val: 5 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_BinaryOperators() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(Test a, Test b) => ""val""; public static string operator +(in Test a, in Test b) => ""in""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_BinaryOperators_Inverse() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(in Test a, in Test b) => ""in""; public static string operator +(Test a, Test b) => ""val""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_UnaryOperators() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator !(Test a) => ""val""; public static string operator !(in Test a) => ""in""; } class Program { static void Main() { var a = new Test { Value = 1 }; Console.WriteLine(!a); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_UnaryOperators_Inverse() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator !(in Test a) => ""in""; public static string operator !(Test a) => ""val""; } class Program { static void Main() { var a = new Test { Value = 1 }; Console.WriteLine(!a); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_FirstArgument() { var code = @" public static class Program { public static void Method(in int x, int ignore) { System.Console.WriteLine(""in: "" + x); } public static void Method(int x, int ignore) { System.Console.WriteLine(""val: "" + x); } public static void Main() { int x = 5; Method(in x, 0); Method(x, 0); Method(5, 0); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 5 val: 5 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_FirstArgument_Inverse() { var code = @" public static class Program { public static void Method(int x, int ignore) { System.Console.WriteLine(""val: "" + x); } public static void Method(in int x, int ignore) { System.Console.WriteLine(""in: "" + x); } public static void Main() { int x = 5; Method(in x, 0); Method(x, 0); Method(5, 0); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 5 val: 5 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_FirstArgument_BinaryOperators() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(Test a, Test b) => ""val""; public static string operator +(in Test a, Test b) => ""in""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_FirstArgument_BinaryOperators_Inverse() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(in Test a, Test b) => ""in""; public static string operator +(Test a, Test b) => ""val""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_SecondArgument() { var code = @" public static class Program { public static void Method(int ignore, in int x) { System.Console.WriteLine(""in: "" + x); } public static void Method(int ignore, int x) { System.Console.WriteLine(""val: "" + x); } public static void Main() { int x = 5; Method(0, in x); Method(0, x); Method(0, 5); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 5 val: 5 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_SecondArgument_Inverse() { var code = @" public static class Program { public static void Method(int ignore, int x) { System.Console.WriteLine(""val: "" + x); } public static void Method(int ignore, in int x) { System.Console.WriteLine(""in: "" + x); } public static void Main() { int x = 5; Method(0, in x); Method(0, x); Method(0, 5); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 5 val: 5 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_SecondArgument_BinaryOperators() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(Test a, Test b) => ""val""; public static string operator +(Test a, in Test b) => ""in""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_SecondArgument_BinaryOperators_Inverse() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(Test a, in Test b) => ""in""; public static string operator +(Test a, Test b) => ""val""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_ConflictingParameters() { var code = @" public static class Program { public static void Method(in int x, int y) { System.Console.WriteLine($""in {x} | val {y}""); } public static void Method(int x, in int y) { System.Console.WriteLine($""val {x} | in {y}""); } public static void Main() { int x = 1, y = 2; Method(x, in y); Method(in x, y); } }"; CompileAndVerify(code, expectedOutput: @" val 1 | in 2 in 1 | val 2 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_ConflictingParameters_Inverse() { var code = @" public static class Program { public static void Method(int x, in int y) { System.Console.WriteLine($""val {x} | in {y}""); } public static void Method(in int x, int y) { System.Console.WriteLine($""in {x} | val {y}""); } public static void Main() { int x = 1, y = 2; Method(x, in y); Method(in x, y); } }"; CompileAndVerify(code, expectedOutput: @" val 1 | in 2 in 1 | val 2 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_ConflictingParameters_Error() { var code = @" public static class Program { public static void Method(in int x, int y) { System.Console.WriteLine($""in {x} val {y}""); } public static void Method(int x, in int y) { System.Console.WriteLine($""val {x} in {y}""); } public static void Main() { int x = 1, y = 2; Method(x, y); Method(3, 4); } }"; CreateCompilation(code).VerifyDiagnostics( // (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(in int, int)' and 'Program.Method(int, in int)' // Method(x, y); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(in int, int)", "Program.Method(int, in int)").WithLocation(18, 9), // (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(in int, int)' and 'Program.Method(int, in int)' // Method(3, 4); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(in int, int)", "Program.Method(int, in int)").WithLocation(19, 9)); } [Fact] public void PassingInArgumentsOverloadedOnIn_ConflictingParameters_Error_Inverse() { var code = @" public static class Program { public static void Method(int x, in int y) { System.Console.WriteLine($""val {x} in {y}""); } public static void Method(in int x, int y) { System.Console.WriteLine($""in {x} val {y}""); } public static void Main() { int x = 1, y = 2; Method(x, y); Method(3, 4); } }"; CreateCompilation(code).VerifyDiagnostics( // (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(int, in int)' and 'Program.Method(in int, int)' // Method(x, y); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(int, in int)", "Program.Method(in int, int)").WithLocation(18, 9), // (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(int, in int)' and 'Program.Method(in int, int)' // Method(3, 4); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(int, in int)", "Program.Method(in int, int)").WithLocation(19, 9)); } [Fact] public void PassingInArgumentsOverloadedOnIn_ThreeConflictingParameters_Error() { var code = @" public static class Program { public static void Method(in int x, int y, in int z) { System.Console.WriteLine($""in {x} val {y} in {z}""); } public static void Method(int x, in int y, int z) { System.Console.WriteLine($""val {x} in {y} val {z}""); } public static void Main() { int x = 1, y = 2, z = 3; Method(x, y, z); Method(4, 5, 6); } }"; CreateCompilation(code).VerifyDiagnostics( // (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(in int, int, in int)' and 'Program.Method(int, in int, int)' // Method(x, y, z); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(in int, int, in int)", "Program.Method(int, in int, int)").WithLocation(18, 9), // (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(in int, int, in int)' and 'Program.Method(int, in int, int)' // Method(4, 5, 6); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(in int, int, in int)", "Program.Method(int, in int, int)").WithLocation(19, 9)); } [Fact] public void PassingInArgumentsOverloadedOnIn_ThreeConflictingParameters_Error_Inverse() { var code = @" public static class Program { public static void Method(int x, in int y, int z) { System.Console.WriteLine($""val {x} in {y} val {z}""); } public static void Method(in int x, int y, in int z) { System.Console.WriteLine($""in {x} val {y} in {z}""); } public static void Main() { int x = 1, y = 2, z = 3; Method(x, y, z); Method(4, 5, 6); } }"; CreateCompilation(code).VerifyDiagnostics( // (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(int, in int, int)' and 'Program.Method(in int, int, in int)' // Method(x, y, z); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(int, in int, int)", "Program.Method(in int, int, in int)").WithLocation(18, 9), // (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(int, in int, int)' and 'Program.Method(in int, int, in int)' // Method(4, 5, 6); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(int, in int, int)", "Program.Method(in int, int, in int)").WithLocation(19, 9)); } [Fact] public void PassingInArgumentsOverloadedOnIn_ConflictingParameters_Error_BinaryOperators() { CreateCompilation(@" using System; class Test { public int Value { get; set; } public static string operator +(in Test a, Test b) => ""left""; public static string operator +(Test a, in Test b) => ""right""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }").VerifyDiagnostics( // (15,27): error CS0034: Operator '+' is ambiguous on operands of type 'Test' and 'Test' // Console.WriteLine(a + b); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "a + b").WithArguments("+", "Test", "Test").WithLocation(15, 27)); } [Fact] public void PassingInArgumentsOverloadedOnIn_ConflictingParameters_Error_BinaryOperators_Inverse() { CreateCompilation(@" using System; class Test { public int Value { get; set; } public static string operator +(Test a, in Test b) => ""right""; public static string operator +(in Test a, Test b) => ""left""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }").VerifyDiagnostics( // (15,27): error CS0034: Operator '+' is ambiguous on operands of type 'Test' and 'Test' // Console.WriteLine(a + b); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "a + b").WithArguments("+", "Test", "Test").WithLocation(15, 27)); } [Fact] public void PassingInArgumentsOverloadedOnIn_UnusedConflictingParameters() { var code = @" public static class Program { public static void Method(in int x, int y = 0) { System.Console.WriteLine($""in: {x}""); } public static void Method(int x, in int y = 0) { System.Console.WriteLine($""val: {x}""); } public static void Main() { int x = 1; Method(x); Method(in x); Method(2); } }"; CompileAndVerify(code, expectedOutput: @" val: 1 in: 1 val: 2"); } [Fact] public void PassingInArgumentsOverloadedOnIn_UnorderedNamedParameters() { var code = @" public static class Program { public static void Method(int a, int b) { System.Console.WriteLine($""val a: {a} | val b: {b}""); } public static void Method(in int b, int a) { System.Console.WriteLine($""in b: {b} | val a: {a}""); } public static void Main() { int a = 1, b = 2; Method(b: b, a: a); Method(a: a, b: in b); } }"; CompileAndVerify(code, expectedOutput: @" val a: 1 | val b: 2 in b: 2 | val a: 1"); } [Fact] public void PassingInArgumentsOverloadedOnIn_OptionalParameters() { var code = @" public static class Program { public static void Method(in int x, int op1 = 0, int op2 = 0) { System.Console.WriteLine(""in: "" + x); } public static void Method(int x, int op1 = 0, int op2 = 0, int op3 = 0) { System.Console.WriteLine(""val: "" + x); } public static void Main() { int x = 1; Method(x); Method(in x); Method(1); x = 2; Method(x, 0); Method(in x, 0); Method(2, 0); x = 3; Method(x, op3: 0); } }"; CompileAndVerify(code, expectedOutput: @" val: 1 in: 1 val: 1 val: 2 in: 2 val: 2 val: 3 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_OptionalParameters_Error() { var code = @" public static class Program { public static void Method(in int x, int op1 = 0, int op2 = 0) { System.Console.WriteLine(""in: "" + x); } public static void Method(int x, int op1 = 0, int op2 = 0, int op3 = 0) { System.Console.WriteLine(""val: "" + x); } public static void Main() { int x = 1; Method(in x, op3: 0); // ERROR } }"; CreateCompilation(code).VerifyDiagnostics( // (17,19): error CS1615: Argument 1 may not be passed with the 'in' keyword // Method(in x, op3: 0); // ERROR Diagnostic(ErrorCode.ERR_BadArgExtraRef, "x").WithArguments("1", "in").WithLocation(17, 19)); } [Fact] public void PassingInArgumentsOverloadedOnIn_Named() { var code = @" public static class Program { public static void Method(in int inP) { System.Console.WriteLine(""in: "" + inP); } public static void Method(int valP) { System.Console.WriteLine(""val: "" + valP); } public static void Main() { int x = 5; Method(in x); Method(valP: 3); Method(inP: 2); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 3 in: 2 "); } [Fact] public void PassingInArgumentsOverloadedOnInErr() { var code = @" public static class Program { public static void Method(in int inP) { System.Console.WriteLine(""in: "" + inP); } public static void Method(int valP) { System.Console.WriteLine(""val: "" + valP); } public static void Main() { byte x = 5; Method(in x); Method('Q'); Method(3); Method(valP: out 2); Method(valP: in 2); } }"; CreateCompilation(code).VerifyDiagnostics( // (17,19): error CS1503: Argument 1: cannot convert from 'in byte' to 'in int' // Method(in x); Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "in byte", "in int").WithLocation(17, 19), // (20,26): error CS1510: A ref or out value must be an assignable variable // Method(valP: out 2); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "2").WithLocation(20, 26), // (21,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // Method(valP: in 2); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "2").WithLocation(21, 25) ); } [Fact] public void PassingInArgumentsOverloadedOnInIndexer() { var code = @" public class Program { public int this[in int inP] { get { System.Console.WriteLine(""in: "" + inP); return 1; } } public int this[int valP] { get { System.Console.WriteLine(""val: "" + valP); return 1; } } public static void Main() { var p = new Program(); int x = 5; _ = p[0]; _ = p[x]; _ = p[in x]; _ = p[valP: 3]; _ = p[inP: 2]; } } "; CompileAndVerify(code, expectedOutput: @" val: 0 val: 5 in: 5 val: 3 in: 2 "); } [Fact] public void PassingInArgumentsOverloadedOnInIndexerErr() { var code = @" public class Program { public int this[in int inP] { get { System.Console.WriteLine(""in: "" + inP); return 1; } } public int this[int valP] { get { System.Console.WriteLine(""val: "" + valP); return 1; } } public static void Main() { var p = new Program(); byte x = 5; _ = p[in x]; _ = p['Q']; _ = p[3]; _ = p[valP: out 2]; _ = p[inP: in 2]; } }"; CreateCompilation(code).VerifyDiagnostics( // (27,18): error CS1503: Argument 1: cannot convert from 'in byte' to 'in int' // _ = p[in x]; Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "in byte", "in int").WithLocation(27, 18), // (30,25): error CS1510: A ref or out value must be an assignable variable // _ = p[valP: out 2]; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "2").WithLocation(30, 25), // (31,23): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // _ = p[inP: in 2]; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "2").WithLocation(31, 23)); } [Fact] public void PassingInArgumentsOverloadedOnInOptionalParameters() { var code = @" public static class Program { public static void Method(in int inP = 0) { System.Console.WriteLine(""in: "" + inP); } public static void Method(int valP = 0) { System.Console.WriteLine(""val: "" + valP); } public static void Main() { Method(valP: 1); Method(inP: 2); int x = 3; Method(in x); } }"; CompileAndVerify(code, expectedOutput: @" val: 1 in: 2 in: 3 "); } [Fact] public void PassingInArgumentsOverloadedOnInParams() { var code = @" using System; class Program { void M(in int x) { Console.WriteLine(""in: "" + x); } void M(params int[] p) { Console.WriteLine(""params: "" + p.Length); } static void Main() { var p = new Program(); p.M(); p.M(1); p.M(1, 2); int x = 3; p.M(in x); } }"; CompileAndVerify(code, expectedOutput: @"params: 0 in: 1 params: 2 in: 3"); } [Fact] public void PassingInArgumentsOverloadedOnInParams_Array() { var code = @" using System; class Program { void M(in int[] p) { Console.WriteLine(""in: "" + p.Length); } void M(params int[] p) { Console.WriteLine(""params: "" + p.Length); } static void Main() { var p = new Program(); p.M(); p.M(1); p.M(1, 2); var x = new int[] { }; p.M(x); p.M(in x); p.M(new int[] { }); x = new int[] { 1 }; p.M(x); p.M(in x); p.M(new int[] { 1 }); } }"; CompileAndVerify(code, expectedOutput: @"params: 0 params: 1 params: 2 params: 0 in: 0 params: 0 params: 1 in: 1 params: 1"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_ExtensionMethods() { CompileAndVerify(@" using System; static class Extensions { public static void M(this Program instance, in int x) { Console.WriteLine(""in: "" + x); } } class Program { void M(int x) { Console.WriteLine(""val: "" + x); } static void Main() { var instance = new Program(); int x = 1; instance.M(x); x = 2; instance.M(in x); instance.M(3); } }", expectedOutput: @"val: 1 in: 2 val: 3"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_Indexers() { CompileAndVerify(@" using System; class Program { public string this[int x] => ""val: "" + x; public string this[in int x] => ""in: "" + x; static void Main() { var instance = new Program(); int x = 1; Console.WriteLine(instance[x]); x = 2; Console.WriteLine(instance[in x]); Console.WriteLine(instance[3]); } }", expectedOutput: @"val: 1 in: 2 val: 3"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_TypeConversions_In() { CompileAndVerify(@" using System; class Program { static void M(in byte x) { Console.WriteLine(""in: "" + x); } static void M(int x) { Console.WriteLine(""val: "" + x); } static void Main() { M(0); int intX = 1; byte byteX = 1; M(intX); M(byteX); M((int)2); M((byte)2); } }", expectedOutput: @" val: 0 val: 1 in: 1 val: 2 in: 2"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_TypeConversions_Val() { CompileAndVerify(@" using System; class Program { static void M(byte x) { Console.WriteLine(""val: "" + x); } static void M(in int x) { Console.WriteLine(""in: "" + x); } static void Main() { M(0); int intX = 1; byte byteX = 1; M(intX); M(byteX); M((int)2); M((byte)2); } }", expectedOutput: @" in: 0 in: 1 val: 1 in: 2 val: 2"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_TypeConversions_BinaryOperators() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(int a, Test b) => ""val""; public static string operator +(in byte a, Test b) => ""in""; } class Program { static void Main() { int intX = 1; byte byteX = 1; var b = new Test { Value = 2 }; Console.WriteLine(intX + b); Console.WriteLine(byteX + b); Console.WriteLine(1 + b); Console.WriteLine(((byte)1) + b); } }", expectedOutput: @" val in val in"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_TypeConversions_NonConvertible() { CompileAndVerify(@" using System; using System.Text; class Program { static void M(string x) { Console.WriteLine(""val""); } static void M(in StringBuilder x) { Console.WriteLine(""in""); } static void Main() { M(null); } }", expectedOutput: "val"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_TypeConversions_NonConvertible_Error() { CreateCompilation(@" using System; using System.Text; class Program { static void M(string x) { Console.WriteLine(""val""); } static void M(StringBuilder x) { Console.WriteLine(""in""); } static void Main() { M(null); } }").VerifyDiagnostics( // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(string)' and 'Program.M(StringBuilder)' // M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(string)", "Program.M(System.Text.StringBuilder)").WithLocation(11, 9)); } [Fact] public void GenericInferenceOnIn() { var code = @" using System; class Program { public static void M1<T>(in T arg1, in T arg2) { System.Console.WriteLine(typeof(T).ToString()); } static void Main() { int x = 1; byte y = 2; M1(null, (string)null); M1(default, 1); M1(new Object(), new Exception()); M1(new Object(), 1); M1(in x, in x); // valid, same type M1(y, in x); // valid, byval x sets lower bound, byte converts to int } } "; CompileAndVerify(code, expectedOutput: @" System.String System.Int32 System.Object System.Object System.Int32 System.Int32 "); } [Fact] public void GenericInferenceOnInErr() { var code = @" class Program { public static void M1<T>(in T arg1, in T arg2) { System.Console.WriteLine(typeof(T).ToString()); } static void Main() { int x = 1; byte y = 2; var rl = default(RefLike); M1(null, null); M1(null, 1); M1(new object(), default(RefLike)); M1(rl, rl); M1(in rl, in rl); M1(in y, in x); M1(in y, x); } ref struct RefLike{} } "; CreateCompilation(code).VerifyDiagnostics( // (15,9): error CS0411: The type arguments for method 'Program.M1<T>(in T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1(null, null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(in T, in T)").WithLocation(15, 9), // (16,12): error CS1503: Argument 1: cannot convert from '<null>' to 'in int' // M1(null, 1); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "in int").WithLocation(16, 12), // (17,9): error CS0411: The type arguments for method 'Program.M1<T>(in T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1(new object(), default(RefLike)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(in T, in T)").WithLocation(17, 9), // (19,9): error CS0306: The type 'Program.RefLike' may not be used as a type argument // M1(rl, rl); Diagnostic(ErrorCode.ERR_BadTypeArgument, "M1").WithArguments("Program.RefLike").WithLocation(19, 9), // (20,9): error CS0306: The type 'Program.RefLike' may not be used as a type argument // M1(in rl, in rl); Diagnostic(ErrorCode.ERR_BadTypeArgument, "M1").WithArguments("Program.RefLike").WithLocation(20, 9), // (22,9): error CS0411: The type arguments for method 'Program.M1<T>(in T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1(in y, in x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(in T, in T)").WithLocation(22, 9), // (23,9): error CS0411: The type arguments for method 'Program.M1<T>(in T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1(in y, x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(in T, in T)").WithLocation(23, 9) ); } [Fact] public void GenericInferenceOnInTuples() { var code = @" using System; class Program { public static void Method<T>(in (T arg1, T arg2) p) { System.Console.WriteLine(typeof(T).ToString()); } static void Main() { int x = 1; byte y = 2; Method((null, (string)null)); Method((default, x)); Method((new Object(), new Exception())); Method((new Object(), x)); Method((x, x)); // valid, same type Method((y, x)); // valid, byval x sets lower bound, byte converts to int } } "; CompileAndVerifyWithMscorlib40(code, references: new[] { SystemRuntimeFacadeRef, ValueTupleRef }, expectedOutput: @" System.String System.Int32 System.Object System.Object System.Int32 System.Int32 "); } [Fact] public void GenericInferenceOnInErrTuples() { var code = @" class Program { public static void Method<T>(in (T arg1, T arg2) p) { System.Console.WriteLine(typeof(T).ToString()); } static void Main() { int x = 1; byte y = 2; var rl = default(RefLike); Method((null, null)); Method((null, 1)); Method((new object(), default(RefLike))); Method((rl, rl)); Method(in (rl, rl)); Method(in (y, x)); } ref struct RefLike{} } "; CreateCompilationWithMscorlib40(code, references: new[] { SystemRuntimeFacadeRef, ValueTupleRef }).VerifyDiagnostics( // (15,9): error CS0411: The type arguments for method 'Program.Method<T>(in (T arg1, T arg2))' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Method((null, null)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Method").WithArguments("Program.Method<T>(in (T arg1, T arg2))").WithLocation(15, 9), // (16,16): error CS1503: Argument 1: cannot convert from '(<null>, int)' to 'in (int arg1, int arg2)' // Method((null, 1)); Diagnostic(ErrorCode.ERR_BadArgType, "(null, 1)").WithArguments("1", "(<null>, int)", "in (int arg1, int arg2)").WithLocation(16, 16), // (17,31): error CS0306: The type 'Program.RefLike' may not be used as a type argument // Method((new object(), default(RefLike))); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(RefLike)").WithArguments("Program.RefLike").WithLocation(17, 31), // (17,9): error CS0411: The type arguments for method 'Program.Method<T>(in (T arg1, T arg2))' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Method((new object(), default(RefLike))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Method").WithArguments("Program.Method<T>(in (T arg1, T arg2))").WithLocation(17, 9), // (19,17): error CS0306: The type 'Program.RefLike' may not be used as a type argument // Method((rl, rl)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "rl").WithArguments("Program.RefLike").WithLocation(19, 17), // (19,21): error CS0306: The type 'Program.RefLike' may not be used as a type argument // Method((rl, rl)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "rl").WithArguments("Program.RefLike").WithLocation(19, 21), // (19,9): error CS0306: The type 'Program.RefLike' may not be used as a type argument // Method((rl, rl)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "Method").WithArguments("Program.RefLike").WithLocation(19, 9), // (20,20): error CS0306: The type 'Program.RefLike' may not be used as a type argument // Method(in (rl, rl)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "rl").WithArguments("Program.RefLike").WithLocation(20, 20), // (20,24): error CS0306: The type 'Program.RefLike' may not be used as a type argument // Method(in (rl, rl)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "rl").WithArguments("Program.RefLike").WithLocation(20, 24), // (20,19): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // Method(in (rl, rl)); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "(rl, rl)").WithLocation(20, 19), // (22,19): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // Method(in (y, x)); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "(y, x)").WithLocation(22, 19)); } [Fact] public void GenericInferenceLambdaVariance() { var code = @" class Program { public delegate void D1<T>(in T arg1, in T arg2); public static void M1<T>(T arg1, T arg2) { System.Console.WriteLine(typeof(T).ToString()); } static void Main() { M1((in int arg1, in int arg2) => throw null, (in int arg1, in int arg2) => throw null); } } "; CreateCompilation(code).VerifyDiagnostics( // (13,9): error CS0411: The type arguments for method 'Program.M1<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1((in int arg1, in int arg2) => throw null, (in int arg1, in int arg2) => throw null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T, T)").WithLocation(13, 9) ); } [Fact] public void DelegateConversions() { var librarySrc = @" public class C { public void RR_input(in int x) => throw null; public ref readonly int RR_output() => throw null; public ref readonly int P => throw null; public ref readonly int this[in int i] => throw null; public delegate ref readonly int Delegate(in int i); } public static class Extensions { public static void RR_extension(in this int x) => throw null; public static void R_extension(ref this int x) => throw null; } "; var libComp = CreateCompilationWithMscorlib40(librarySrc, references: new[] { TestMetadata.Net40.SystemCore }).VerifyDiagnostics(); var code = @" class D { void M(C c, in int y) { c.RR_input(y); VerifyRR(c.RR_output()); VerifyRR(c.P); VerifyRR(c[y]); C.Delegate x = VerifyDelegate; y.RR_extension(); 1.RR_extension(); y.R_extension(); // error 1 1.R_extension(); // error 2 } void VerifyRR(in int y) => throw null; ref readonly int VerifyDelegate(in int y) => throw null; } "; CreateCompilation(code, references: new[] { libComp.EmitToImageReference() }).VerifyDiagnostics( // (13,10): error CS8329: Cannot use variable 'in int' as a ref or out value because it is a readonly variable // y.R_extension(); // error 1 Diagnostic(ErrorCode.ERR_RefReadonlyNotField, "y").WithArguments("variable", "in int").WithLocation(13, 10), // (14,10): error CS1510: A ref or out value must be an assignable variable // 1.R_extension(); // error 2 Diagnostic(ErrorCode.ERR_RefLvalueExpected, "1").WithLocation(14, 10) ); CreateCompilation(code, references: new[] { libComp.ToMetadataReference() }).VerifyDiagnostics( // (13,10): error CS8329: Cannot use variable 'in int' as a ref or out value because it is a readonly variable // y.R_extension(); // error 1 Diagnostic(ErrorCode.ERR_RefReadonlyNotField, "y").WithArguments("variable", "in int").WithLocation(13, 10), // (14,10): error CS1510: A ref or out value must be an assignable variable // 1.R_extension(); // error 2 Diagnostic(ErrorCode.ERR_RefLvalueExpected, "1").WithLocation(14, 10) ); } [Fact] public void MethodGroupConversionVal2In() { var code = @" using System; class Program { static void F(in DateTime x) { Console.WriteLine(x); } static void Main() { Action<DateTime> a = F; a(DateTime.MaxValue); } } "; CreateCompilation(code).VerifyDiagnostics( // (13,30): error CS0123: No overload for 'F' matches delegate 'Action<DateTime>' // Action<DateTime> a = F; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F").WithArguments("F", "System.Action<System.DateTime>").WithLocation(13, 30) ); } [Fact] public void MethodGroupConversionVal2Overloaded() { var code = @" using System; class Program { static void F(in DateTime x) { Console.WriteLine('1'); } static void F(DateTime x) { Console.WriteLine('2'); } static void Main() { Action<DateTime> a = F; a(DateTime.MaxValue); } } "; CompileAndVerify(code, expectedOutput: @"2"); } [Fact] public void MethodGroupConversionIn2Overloaded() { var code = @" using System; class Program { delegate void D(in DateTime d); static void F(in DateTime x) { Console.WriteLine('1'); } static void F(DateTime x) { Console.WriteLine('2'); } static void Main() { D a = F; a(DateTime.MaxValue); } } "; CompileAndVerify(code, expectedOutput: @"1", verify: Verification.Fails); } [Fact] public void MethodGroupConversionRoReadonlyReturn() { var code = @" using System; class Program { delegate int D(in DateTime d); static ref readonly int F(in DateTime x) { Console.WriteLine('1'); return ref (new int[1])[0]; } static void Main() { D a = F; a(DateTime.MaxValue); } } "; CreateCompilation(code).VerifyDiagnostics ( // (16,15): error CS8189: Ref mismatch between 'Program.F(in DateTime)' and delegate 'Program.D' // D a = F; Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "F").WithArguments("Program.F(in System.DateTime)", "Program.D").WithLocation(16, 15) ); } [Fact] public void MethodGroupConversionRoReadonlyReturnType() { var code = @" using System; class Program { delegate ref readonly object D(in DateTime d); static ref readonly string F(in DateTime x) { Console.WriteLine('1'); return ref (new string[1])[0]; } static void Main() { D a = F; a(DateTime.MaxValue); } } "; CreateCompilation(code).VerifyDiagnostics ( // (16,15): error CS0407: 'string Program.F(in DateTime)' has the wrong return type // D a = F; Diagnostic(ErrorCode.ERR_BadRetType, "F").WithArguments("Program.F(in System.DateTime)", "string").WithLocation(16, 15) ); } [Fact, WorkItem(25813, "https://github.com/dotnet/roslyn/issues/25813")] public void InaccessibleExtensionMethod() { var code = @" using System; using System.Collections.Generic; using System.Linq; public class Program { static void Main(string[] args) { var a = new[] { 0, 1, 3 }; var b = new[] { 1, 2, 3, 4, 5 }; Console.WriteLine(b.Count(a.Contains)); } } public static class Extensions { // NOTE: private access modifier simulates internal class public method in referenced assembly. private static bool Contains<T>(this System.Collections.Generic.IEnumerable<T> a, T value) => throw new NotImplementedException(); }"; CompileAndVerify(code, expectedOutput: @"2"); } [Fact] public void GenericTypeOverriddenMethod() { var source0 = @"public class Base<TKey, TValue> where TKey : class where TValue : class { public virtual TValue F(TKey key) => throw null; }"; var source1 = @"public class A { } public class Derived<TValue> : Base<A, TValue> where TValue : class { public override TValue F(A key) => throw null; }"; var source2 = @"class B { } class Program { static void M(Derived<B> d, A a) { _ = d.F(a); } }"; var comp = CreateCompilation(new[] { source0, source1, source2 }); comp.VerifyEmitDiagnostics(); verify(comp, comp.SyntaxTrees[2]); var ref0 = CreateCompilation(source0).EmitToImageReference(); var ref1 = CreateCompilation(source1, references: new[] { ref0 }).EmitToImageReference(); comp = CreateCompilation(source2, references: new[] { ref0, ref1 }); comp.VerifyEmitDiagnostics(); verify(comp, comp.SyntaxTrees[0]); static void verify(CSharpCompilation comp, SyntaxTree tree) { var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(expr).Symbol.GetSymbol<MethodSymbol>(); Assert.Equal("B Derived<B>.F(A key)", symbol.ToTestDisplayString()); symbol = symbol.GetLeastOverriddenMethod(accessingTypeOpt: null); Assert.Equal("B Base<A, B>.F(A key)", symbol.ToTestDisplayString()); } } [Fact] [WorkItem(46549, "https://github.com/dotnet/roslyn/issues/46549")] public void GenericTypeOverriddenProperty() { var source0 = @"public class Base<TKey, TValue> where TKey : class where TValue : class { public virtual TValue this[TKey key] => throw null; }"; var source1 = @"public class A { } public class Derived<TValue> : Base<A, TValue> where TValue : class { public override TValue this[A key] => throw null; }"; var source2 = @"class B { } class Program { static void M(Derived<B> d, A a) { _ = d[a]; } }"; var comp = CreateCompilation(new[] { source0, source1, source2 }); comp.VerifyEmitDiagnostics(); verify(comp, comp.SyntaxTrees[2]); var ref0 = CreateCompilation(source0).EmitToImageReference(); var ref1 = CreateCompilation(source1, references: new[] { ref0 }).EmitToImageReference(); comp = CreateCompilation(source2, references: new[] { ref0, ref1 }); comp.VerifyEmitDiagnostics(); verify(comp, comp.SyntaxTrees[0]); static void verify(CSharpCompilation comp, SyntaxTree tree) { var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(expr).Symbol.GetSymbol<PropertySymbol>(); Assert.Equal("B Derived<B>.this[A key] { get; }", symbol.ToTestDisplayString()); symbol = symbol.GetLeastOverriddenProperty(accessingTypeOpt: null); Assert.Equal("B Base<A, B>.this[A key] { get; }", symbol.ToTestDisplayString()); } } [Fact] [WorkItem(46549, "https://github.com/dotnet/roslyn/issues/46549")] public void GenericTypeOverriddenEvent() { var source0 = @"public delegate TValue D<TKey, TValue>(TKey key); public abstract class Base<TKey, TValue> where TKey : class where TValue : class { public abstract event D<TKey, TValue> E; }"; var source1 = @"public class A { } public class Derived<TValue> : Base<A, TValue> where TValue : class { public override event D<A, TValue> E { add { } remove { } } }"; var source2 = @"class B { } class Program { static void M(Derived<B> d, A a) { d.E += (A a) => default(B); } }"; var comp = CreateCompilation(new[] { source0, source1, source2 }); comp.VerifyEmitDiagnostics(); verify(comp, comp.SyntaxTrees[2]); var ref0 = CreateCompilation(source0).EmitToImageReference(); var ref1 = CreateCompilation(source1, references: new[] { ref0 }).EmitToImageReference(); comp = CreateCompilation(source2, references: new[] { ref0, ref1 }); comp.VerifyEmitDiagnostics(); verify(comp, comp.SyntaxTrees[0]); static void verify(CSharpCompilation comp, SyntaxTree tree) { var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(expr).Symbol.GetSymbol<EventSymbol>(); Assert.Equal("event D<A, B> Derived<B>.E", symbol.ToTestDisplayString()); symbol = symbol.GetLeastOverriddenEvent(accessingTypeOpt: null); Assert.Equal("event D<A, B> Base<A, B>.E", symbol.ToTestDisplayString()); } } [Fact] [WorkItem(52701, "https://github.com/dotnet/roslyn/issues/52701")] public void Issue52701_01() { var source = @" class A { internal void F<T>(T t) where T : class {} } class B : A { internal new void F<T>(T t) where T : struct { } void M() { System.Action<object> d = F<object>; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,35): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // System.Action<object> d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(11, 35) ); } [Fact] [WorkItem(52701, "https://github.com/dotnet/roslyn/issues/52701")] public void Issue52701_02() { var source = @" class A { internal void F<T>(T t) where T : class {} } class B : A { internal new void F<T>(T t) where T : struct { } void M() { F<object>(default); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,9): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // F<object>(default); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(11, 9) ); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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 Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class OverloadResolutionTests : OverloadResolutionTestBase { [Fact] public void TestBug12439() { // The spec has an omission; I believe we intended it to say that there is no // conversion from any old-style anonymous method expression to any expression tree // type. This is the rule the native compiler enforces; Roslyn should as well, and // we should clarify the specification. string source = @" using System; using System.Linq.Expressions; class Program { static void Main() { Goo(delegate { }); // No error; chooses the non-expression version. } static void Goo(Action a) { } static void Goo(Expression<Action> a) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [Fact] public void TestBug11961() { // This test verifies a deliberate spec violation that we have implemented // to ensure backwards compatibility. // // When doing overload resolution, we must find the best applicable method. // // When tiebreaking between two applicable candidate methods, we examine each conversion from the // argument to the corresponding parameter type to determine which method is better *in that parameter*. // If a method is *not worse* in every parameter and better in at least one, then that method // wins. Under what circumstances is one conversion better than another? // // * A conversion from the argument to a more specific parameter type is better than a conversion to a less // specific parameter type. If we have M(null) and candidates M(string) and M(object) then the conversion to // string is better because string is more specific. // // * If the argument is a lambda and the parameter types are delegate types, then the conversion to the // delegate type with the more specific return type wins. If we have M(()=>null) and we are choosing between // M(ObjectReturningDelegate) and M(StringReturningDelegate), the latter wins. // // In C# 3, these rules were never in conflict because no delegate type was ever more or less specific // than another. But in C# 4 we added delegate covariance and contravariance, and now there are delegate // types that are more specific than others. We did not correctly update the C# 4 compiler to handle this // situation. // // Unfortunately, real-world code exists that depends on this bad behavior, so we are going to preserve it. // // The essence of the bug is: the correct behavior is to do the first tiebreaker first, and the second tiebreaker // if necessary. The native compiler, and now Roslyn, does this wrong. It says "is the argument a lambda?" If so, // then it applies the second tiebreaker and ignores the first. Otherwise, it applies the first tiebreaker and // ignores the second. // // Let's take a look at some examples of where it does and does not make a difference: // // On the first call, the native compiler and Roslyn agree that overload 2 is better. (Remember, Action<T> is // contravariant, so Action<object> is more specific than Action<string>. Every action that takes an object // is also an action that takes a string, so an action that takes an object is more specific.) This is the correct // behavior. The compiler uses the first tiebreaker. // On the second call, the native compiler incorrectly believes that overload 3 is better, because it // does not correctly determine that Action<object> is more specific than Action<string> when the argument is // a lambda. The correct behavior according to the spec would be to produce an ambiguity error. (Why? // because overload 3 is more specific in its first parameter type, and less specific in its second parameter type. // And vice-versa for overload 4. No overload is not-worse in all parameters.) string source1 = @" using System; class P { static void M(Action<string> a) { Console.Write(1); } static void M(Action<object> a) { Console.Write(2); } static void M(string x, Action<string> a) { Console.Write(3); } static void M(object x, Action<object> a) { Console.Write(4); } static void M1(string x, Func<object> a) { Console.Write(5); } static void M1(object x, Func<ValueType> a) { Console.Write(6); } static void M2(Func<object> a, string x) { Console.Write(7); } static void M2(Func<ValueType> a, object x) { Console.Write(8); } static void M3(Func<object> a, Action<object> b, string x) { Console.Write(9); } static void M3(Func<ValueType> a, Action<string> b, object x) { Console.Write('A'); } static void M5(Action<object> b, string x, Func<object> a) { Console.Write('D'); } static void M5(Action<string> b, object x, Func<ValueType> a) { Console.Write('E'); } static void Main() { M(null); M((string)null, q=>{}); M(q=>{}); M1((string)null, ()=>{ throw new NotImplementedException();}); M2(()=>{ throw new NotImplementedException();}, (string)null); M3(()=>{ throw new NotImplementedException();}, q=> {}, (string)null); M5(q=> {}, (string)null, ()=>{ throw new NotImplementedException();}); } }"; CompileAndVerify(source1, expectedOutput: @"232579D"); // Now let's look at some ambiguity errors: // // On the first call, the native compiler incorrectly produces an ambiguity error. The correct behavior according // to the specification is to choose overload 2, because it is more specific. Because the argument is a lambda // we incorrectly skip the first tiebreaker entirely and go straight to the second tiebreaker. We are now in a situation // where we have two delegate types that are both void returning, and so by the second tiebreaker, neither is better. // On the second call, the native compiler correctly produces an ambiguity error. Overload 3 is better that the // overload 4 in its first parameter and worse in its second parameter, and similarly for overload 4. Since // neither overload is not-worse in all parameters, neither is the best choice. string source2 = @" using System; class P { static void M(Action<string> a) { } static void M(Action<object> a) { } static void M(string x, Action<string> a) { } static void M(object x, Action<object> a) { } static void M1(string x, Func<object> a) { Console.Write(5); } static void M1(object x, Func<ValueType> a) { Console.Write(6); } static void M4(Func<object> a, Action<object> b, Action<string> x) { Console.Write('B'); } static void M4(Func<ValueType> a, Action<string> b, Action<object> x) { Console.Write('C'); } static void M6(Action<object> b, string x, object a) { Console.Write('F'); } static void M6(Action<string> b, object x, string a) { Console.Write('G'); } static void Main() { M((string)null, null); M1((string)null, ()=>{ return 5;}); M4(()=>{ throw new NotImplementedException();}, q=> {}, q=> {}); M6(q=> {},(string)null, (string)null); } }"; CreateCompilation(source2).VerifyDiagnostics( // (18,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M(string, System.Action<string>)' and 'P.M(object, System.Action<object>)' // M((string)null, null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("P.M(string, System.Action<string>)", "P.M(object, System.Action<object>)"), // (19,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M1(string, System.Func<object>)' and 'P.M1(object, System.Func<System.ValueType>)' // M1((string)null, ()=>{ return 5;}); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("P.M1(string, System.Func<object>)", "P.M1(object, System.Func<System.ValueType>)"), // (20,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M4(System.Func<object>, System.Action<object>, System.Action<string>)' and 'P.M4(System.Func<System.ValueType>, System.Action<string>, System.Action<object>)' // M4(()=>{ throw new NotImplementedException();}, q=> {}, q=> {}); Diagnostic(ErrorCode.ERR_AmbigCall, "M4").WithArguments("P.M4(System.Func<object>, System.Action<object>, System.Action<string>)", "P.M4(System.Func<System.ValueType>, System.Action<string>, System.Action<object>)"), // (21,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M6(System.Action<object>, string, object)' and 'P.M6(System.Action<string>, object, string)' // M6(q=> {},(string)null, (string)null); Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("P.M6(System.Action<object>, string, object)", "P.M6(System.Action<string>, object, string)") ); // By comparing these two programs, it becomes clear how unfortunate this is. M(q=>null) is ambiguous, // M(null) is unambiguous. But M((string)null, q=>{}) is unambiguous, M((string)null, null) is ambiguous! string source3 = @" using System; using System.Collections.Generic; class SyntaxNode {} class ExpressionSyntax : SyntaxNode {} class IdentifierNameSyntax : ExpressionSyntax {} class SyntaxAnnotation {} static class P { public static TRoot ReplaceNodes1<TRoot>(this TRoot root, IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, SyntaxNode, SyntaxNode> computeReplacementNode) where TRoot : SyntaxNode { Console.Write('A'); return null; } public static TRoot ReplaceNodes1<TRoot, TNode>(this TRoot root, IEnumerable<TNode> nodes, Func<TNode, TNode, SyntaxNode> computeReplacementNode) where TRoot : SyntaxNode where TNode : SyntaxNode { Console.Write('B'); return null; } public static TNode WithAdditionalAnnotations<TNode>(this TNode node, params SyntaxAnnotation[] annotations) where TNode : SyntaxNode { return null; } public static TRoot ReplaceNodes2<TRoot, TNode>(this TRoot root, IEnumerable<TNode> nodes, Func<TNode, TNode, SyntaxNode> computeReplacementNode) where TRoot : SyntaxNode where TNode : SyntaxNode { Console.Write('B'); return null; } public static TRoot ReplaceNodes2<TRoot>(this TRoot root, IEnumerable<SyntaxNode> nodes, Func<SyntaxNode, SyntaxNode, SyntaxNode> computeReplacementNode) where TRoot : SyntaxNode { Console.Write('A'); return null; } static void Main() { ExpressionSyntax expr = null; var identifierNodes = new List<IdentifierNameSyntax>(); var myAnnotation = new SyntaxAnnotation(); expr.ReplaceNodes1(identifierNodes, (e, e2) => e2.WithAdditionalAnnotations(myAnnotation)); expr.ReplaceNodes2(identifierNodes, (e, e2) => e2.WithAdditionalAnnotations(myAnnotation)); } }"; CompileAndVerify(source3, expectedOutput: @"BB"); } [Fact] public void DeviationFromSpec() { string source1 = @" using System; class P { static void M1(int a) { Console.Write(1); } static void M1(uint? a) { Console.Write(2); } static void M2(int? a) { Console.Write(3); } static void M2(uint a) { Console.Write(4); } static void Main() { int i = 0; int? ni = 0; uint u = 0; uint? nu = 0; short s = 0; short? ns = 0; ushort us = 0; ushort? nus = 0; M1(null); M1(i); Console.Write("" "");//M1(ni); M1(u); M1(nu); M1(s); Console.Write("" "");//M1(ns); M1(us); M1(nus); M2(null); M2(i); M2(ni); M2(u); Console.Write("" "");//M2(nu); M2(s); M2(ns); M2(us); M2(nus); } }"; CompileAndVerify(source1, expectedOutput: @"21 221 123334 3333"); string source2 = @" using System; class P { static void M1(int a) { Console.Write(1); } static void M1(uint? a) { Console.Write(2); } static void M2(int? a) { Console.Write(3); } static void M2(uint a) { Console.Write(4); } static void Main() { int? ni = 0; uint? nu = 0; short? ns = 0; //ushort us = 0; M1(ni); M1(ns); M2(nu); } }"; CreateCompilation(source2).VerifyDiagnostics( // (16,8): error CS1503: Argument 1: cannot convert from 'int?' to 'int' // M1(ni); Diagnostic(ErrorCode.ERR_BadArgType, "ni").WithArguments("1", "int?", "int"), // (17,8): error CS1503: Argument 1: cannot convert from 'short?' to 'int' // M1(ns); Diagnostic(ErrorCode.ERR_BadArgType, "ns").WithArguments("1", "short?", "int"), // (19,8): error CS1503: Argument 1: cannot convert from 'uint?' to 'int?' // M2(nu); Diagnostic(ErrorCode.ERR_BadArgType, "nu").WithArguments("1", "uint?", "int?") ); } [Fact] public void ParametersExactlyMatchExpression() { string source2 = @" using System; class P { delegate int DA(); delegate int DB(); static void M1(DA a) { Console.Write(1); } static void M1(DB a) { Console.Write(2); } static void Main() { int x = 1; M1(() => x); } }"; CreateCompilation(source2).VerifyDiagnostics( // (14,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M1(P.DA)' and 'P.M1(P.DB)' // M1(() => x); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("P.M1(P.DA)", "P.M1(P.DB)") ); } [Fact] public void ExactlyMatchingNestedLambda() { string source1 = @" using System; class P { delegate Func<int> DA(); delegate Func<object> DB(); static void M1(DA a) { Console.Write(1); } static void M1(DB a) { Console.Write(2); } static void Main() { int i = 0; M1(() => () => i); } }"; CompileAndVerify(source1, expectedOutput: @"1"); string source2 = @" using System; class P { delegate Func<int> DA(); delegate Func<object> DB(); static void M1(DA a, object b) { Console.Write(1); } static void M1(DB a, int b) { Console.Write(2); } static void Main() { int i = 0; M1(() => () => i, i); } }"; CompileAndVerify(source2, parseOptions: TestOptions.Regular9, expectedOutput: @"2"); var comp = CreateCompilation(source2); comp.VerifyDiagnostics( // (15,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M1(P.DA, object)' and 'P.M1(P.DB, int)' // M1(() => () => i, i); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("P.M1(P.DA, object)", "P.M1(P.DB, int)").WithLocation(15, 5)); } [Fact] public void ParametersImplicitlyConvertibleToEachOther() { string source1 = @" using System; class CA { public static implicit operator CA(int x) { return null; } public static implicit operator CA(CB x) { return null; } } class CB { public static implicit operator CB(int x) { return null; } public static implicit operator CB(CA x) { return null; } } class P { static void M1(CA a) { Console.Write(1); } static void M1(CB a) { Console.Write(2); } static void Main() { int i = 0; M1(i); } }"; CreateCompilation(source1).VerifyDiagnostics( // (36,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M1(CA)' and 'P.M1(CB)' // M1(i); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("P.M1(CA)", "P.M1(CB)") ); } [Fact] public void BetterTaskType() { string source1 = @" using System; using System.Threading.Tasks; class P { static void M1(Task<int> a) { Console.Write(1); } static void M1(Task<uint> a) { Console.Write(2); } static void Main() { M1(null); } }"; CompileAndVerify(source1, expectedOutput: @"1"); string source2 = @" using System; using System.Threading.Tasks; class P { static void M1(Task<int> a, uint b) { Console.Write(1); } static void M1(Task<uint> a, int b) { Console.Write(2); } static void Main() { M1(null,0); } }"; CreateCompilation(source2).VerifyDiagnostics( // (11,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M1(System.Threading.Tasks.Task<int>, uint)' and 'P.M1(System.Threading.Tasks.Task<uint>, int)' // M1(null,0); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("P.M1(System.Threading.Tasks.Task<int>, uint)", "P.M1(System.Threading.Tasks.Task<uint>, int)") ); } [Fact] public void BetterTasklikeType() { string source1 = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static void Main() { h(async () => { await (Task)null; return 1; }); } static void h<T>(Func<Task<T>> lambda) { } static void h<T>(Func<MyTask<T>> lambda) { } } [AsyncMethodBuilder(typeof(MyTaskBuilder<>))] public class MyTask<T> { } public class MyTaskBuilder<T> { public static MyTaskBuilder<T> Create() => null; public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void SetResult(T result) { } public void SetException(Exception exception) { } public MyTask<T> Task => default(MyTask<T>); public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; CreateCompilationWithMscorlib45(source1).VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.h<T>(Func<Task<T>>)' and 'C.h<T>(Func<MyTask<T>>)' // h(async () => { await (Task)null; return 1; }); Diagnostic(ErrorCode.ERR_AmbigCall, "h").WithArguments("C.h<T>(System.Func<System.Threading.Tasks.Task<T>>)", "C.h<T>(System.Func<MyTask<T>>)").WithLocation(9, 9) ); string source2 = @" using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C { static void Main() { k(async () => { await (Task)null; return 1; }); } static void k<T>(Func<YourTask<T>> lambda) { } static void k<T>(Func<MyTask<T>> lambda) { } } [AsyncMethodBuilder(typeof(MyTaskBuilder<>))] public class MyTask<T> { } public class MyTaskBuilder<T> { public static MyTaskBuilder<T> Create() => null; public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void SetResult(T result) { } public void SetException(Exception exception) { } public MyTask<T> Task => default(MyTask<T>); public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } } [AsyncMethodBuilder(typeof(YourTask<>))] public class YourTask<T> { } public class YourTaskBuilder<T> { public static YourTaskBuilder<T> Create() => null; public void Start<TStateMachine>(ref TStateMachine stateMachine) where TStateMachine : IAsyncStateMachine { } public void SetStateMachine(IAsyncStateMachine stateMachine) { } public void SetResult(T result) { } public void SetException(Exception exception) { } public YourTask<T> Task => default(YourTask<T>); public void AwaitOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : INotifyCompletion where TStateMachine : IAsyncStateMachine { } public void AwaitUnsafeOnCompleted<TAwaiter, TStateMachine>(ref TAwaiter awaiter, ref TStateMachine stateMachine) where TAwaiter : ICriticalNotifyCompletion where TStateMachine : IAsyncStateMachine { } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; CreateCompilationWithMscorlib45(source2).VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.k<T>(Func<YourTask<T>>)' and 'C.k<T>(Func<MyTask<T>>)' // k(async () => { await (Task)null; return 1; }); Diagnostic(ErrorCode.ERR_AmbigCall, "k").WithArguments("C.k<T>(System.Func<YourTask<T>>)", "C.k<T>(System.Func<MyTask<T>>)").WithLocation(9, 9) ); } [Fact] public void NormalizeTaskTypes() { string source = @" using System.Runtime.CompilerServices; class A<T> { internal struct B<U> { } } unsafe class C<T, U> { #pragma warning disable CS0169 static MyTask F0; static MyTask<T> F1; static C<MyTask, MyTask[]>[,] F2; static A<MyTask<MyTask>>.B<C<int, MyTask>> F3; static int* F4; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder))] struct MyTask { } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] struct MyTask<T> { } struct MyTaskMethodBuilder { public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder(); } struct MyTaskMethodBuilder<T> { public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeDebugDll); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F1").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<T>", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<T>", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F2").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("C<MyTask, MyTask[]>[,]", type.ToTestDisplayString()); Assert.Equal("C<System.Threading.Tasks.Task, System.Threading.Tasks.Task[]>[,]", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F3").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("A<MyTask<MyTask>>.B<C<System.Int32, MyTask>>", type.ToTestDisplayString()); Assert.Equal("A<System.Threading.Tasks.Task<System.Threading.Tasks.Task>>.B<C<System.Int32, System.Threading.Tasks.Task>>", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F4").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("System.Int32*", type.ToTestDisplayString()); Assert.Equal("System.Int32*", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_Tuples() { string source = @"using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; class C<T, U> { #pragma warning disable CS0169 static MyTask<ValueTuple<MyTask, T>> F0; static ((MyTask a, T b) c, MyTask<(U, MyTask<T>)[]> d) F1; static Task<(Task, object)[]> F2; static (MyTask, char, byte, short, ushort, int, uint, long, ulong, char, byte, short, ushort, int, uint, long, MyTask<T>) F3; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder))] struct MyTask { } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] struct MyTask<T> { } struct MyTaskMethodBuilder { public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder(); } struct MyTaskMethodBuilder<T> { public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(); } namespace System { struct ValueTuple<T1, T2> { } struct ValueTuple<T1, T2, T3> { } struct ValueTuple<T1, T2, T3, T4, T5, T6, T7, T8> { } } namespace System.Runtime.CompilerServices { class TupleElementNamesAttribute : Attribute { public TupleElementNamesAttribute(string[] names) { } } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source, assemblyName: "comp"); compilation.VerifyDiagnostics( // (10,12): error CS8128: Member 'Rest' was not found on type 'ValueTuple<T1, T2, T3, T4, T5, T6, T7, T8>' from assembly comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'. // static (MyTask, char, byte, short, ushort, int, uint, long, ulong, char, byte, short, ushort, int, uint, long, MyTask<T>) F3; Diagnostic(ErrorCode.ERR_PredefinedTypeMemberNotFoundInAssembly, "(MyTask, char, byte, short, ushort, int, uint, long, ulong, char, byte, short, ushort, int, uint, long, MyTask<T>)").WithArguments("Rest", "System.ValueTuple<T1, T2, T3, T4, T5, T6, T7, T8>", "comp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null").WithLocation(10, 12)); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<(MyTask, T)>", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<(System.Threading.Tasks.Task, T)>", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F1").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("((MyTask a, T b) c, MyTask<(U, MyTask<T>)[]> d)", type.ToTestDisplayString()); Assert.Equal("((System.Threading.Tasks.Task a, T b) c, System.Threading.Tasks.Task<(U, System.Threading.Tasks.Task<T>)[]> d)", normalized.ToTestDisplayString()); // No changes. type = compilation.GetMember<FieldSymbol>("C.F2").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("System.Threading.Tasks.Task<(System.Threading.Tasks.Task, System.Object)[]>", type.ToTestDisplayString()); Assert.Same(type, normalized); // Nested System.ValueTuple<>. type = compilation.GetMember<FieldSymbol>("C.F3").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("(MyTask, System.Char, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.UInt64, System.Char, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, MyTask<T>)", type.ToTestDisplayString()); Assert.Equal("(System.Threading.Tasks.Task, System.Char, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.UInt64, System.Char, System.Byte, System.Int16, System.UInt16, System.Int32, System.UInt32, System.Int64, System.Threading.Tasks.Task<T>)", normalized.ToTestDisplayString()); Assert.Equal("(System.UInt32, System.Int64, MyTask<T>)", GetUnderlyingTupleTypeRest(type).ToTestDisplayString()); Assert.Equal("(System.UInt32, System.Int64, System.Threading.Tasks.Task<T>)", GetUnderlyingTupleTypeRest(normalized).ToTestDisplayString()); } // Return the underlying type of the most-nested part of the TupleTypeSymbol. private static NamedTypeSymbol GetUnderlyingTupleTypeRest(TypeSymbol type) { while (type.IsTupleType) { var typeArgs = ((NamedTypeSymbol)type).TypeArguments(); if (typeArgs.Length < 8) { return (NamedTypeSymbol)type; } type = typeArgs[7]; } return null; } // Preserve type argument custom modifiers. [WorkItem(592, "https://github.com/dotnet/roslyn/issues/12615")] [Fact] public void NormalizeTaskTypes_TypeArgumentCustomModifiers() { var ilSource = @".class public C { .field public static class MyTask`1<class MyTask modopt(class MyTask`1<object>)> F0 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTask { .custom instance void System.Runtime.CompilerServices.AsyncMethodBuilderAttribute::.ctor(class [mscorlib]System.Type) = { type(MyTaskMethodBuilder) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTask`1<T> { .custom instance void System.Runtime.CompilerServices.AsyncMethodBuilderAttribute::.ctor(class [mscorlib]System.Type) = { type(MyTaskMethodBuilder`1) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTaskMethodBuilder { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTaskMethodBuilder`1<T> { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .namespace System.Runtime.CompilerServices { .class public AsyncMethodBuilderAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class [mscorlib]System.Type t) cil managed { ret } } } "; var source = @""; var reference = CompileIL(ilSource); var compilation = CreateCompilationWithMscorlib45(source, references: new[] { reference }); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<MyTask modopt(MyTask<System.Object>)>", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<System.Threading.Tasks.Task modopt(MyTask<System.Object>)>", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_Pointers() { string source = @" using System.Runtime.CompilerServices; unsafe class C<T> { #pragma warning disable CS0169 static C<MyTask<int>>* F0; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] struct MyTask<T> { } struct MyTaskMethodBuilder<T> { public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeDebugDll); compilation.VerifyDiagnostics( // (6,28): error CS0208: Cannot take the address of, get the size of, or declare a pointer to a managed type ('C<MyTask<int>>') // static C<MyTask<int>>* F0; Diagnostic(ErrorCode.ERR_ManagedAddr, "F0").WithArguments("C<MyTask<int>>").WithLocation(6, 28)); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("C<MyTask<System.Int32>>*", type.ToTestDisplayString()); Assert.Equal("C<System.Threading.Tasks.Task<System.Int32>>*", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_PointersCustomModifiers() { var ilSource = @".class public C { .field public static class MyTask modopt(class MyTask) *[] F0 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTask { .custom instance void System.Runtime.CompilerServices.AsyncMethodBuilderAttribute::.ctor(class [mscorlib]System.Type) = { type(MyTaskMethodBuilder) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTaskMethodBuilder { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .namespace System.Runtime.CompilerServices { .class public AsyncMethodBuilderAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class [mscorlib]System.Type t) cil managed { ret } } } "; var source = @""; var reference = CompileIL(ilSource); var compilation = CreateCompilationWithMscorlib45(source, references: new[] { reference }); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask modopt(MyTask) *[]", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task modopt(MyTask) *[]", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_FunctionPointers() { string source = @" using System.Runtime.CompilerServices; unsafe class C<T> { #pragma warning disable CS0169 static delegate*<int, int, C<MyTask<int>>> F0; static delegate*<C<MyTask<int>>, int, int> F1; static delegate*<int, C<MyTask<int>>, int> F2; static delegate*<int, int, int> F3; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] struct MyTask<T> { } struct MyTaskMethodBuilder<T> { public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.UnsafeDebugDll, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics(); assert("F0", "delegate*<System.Int32, System.Int32, C<MyTask<System.Int32>>>", "delegate*<System.Int32, System.Int32, C<System.Threading.Tasks.Task<System.Int32>>>"); assert("F1", "delegate*<C<MyTask<System.Int32>>, System.Int32, System.Int32>", "delegate*<C<System.Threading.Tasks.Task<System.Int32>>, System.Int32, System.Int32>"); assert("F2", "delegate*<System.Int32, C<MyTask<System.Int32>>, System.Int32>", "delegate*<System.Int32, C<System.Threading.Tasks.Task<System.Int32>>, System.Int32>"); assert("F3", "delegate*<System.Int32, System.Int32, System.Int32>", normalized: null); void assert(string fieldName, string original, string normalized) { var type = compilation.GetMember<FieldSymbol>($"C.{fieldName}").Type; FunctionPointerUtilities.CommonVerifyFunctionPointer((FunctionPointerTypeSymbol)type); var normalizedType = type.NormalizeTaskTypes(compilation); Assert.Equal(original, type.ToTestDisplayString()); if (normalized is object) { Assert.Equal(normalized, normalizedType.ToTestDisplayString()); } else { Assert.Same(type, normalizedType); } } } [Fact] public void NormalizeTaskTypes_FunctionPointersCustomModifiers() { var ilSource = @".class public C { .field public static method class MyTask modopt(class MyTask) *(class MyTask modopt(class MyTask)) F0 .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTask { .custom instance void System.Runtime.CompilerServices.AsyncMethodBuilderAttribute::.ctor(class [mscorlib]System.Type) = { type(MyTaskMethodBuilder) } .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .class public MyTaskMethodBuilder { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ret } } .namespace System.Runtime.CompilerServices { .class public AsyncMethodBuilderAttribute extends [mscorlib]System.Attribute { .method public hidebysig specialname rtspecialname instance void .ctor(class [mscorlib]System.Type t) cil managed { ret } } } "; var source = @""; var reference = CompileIL(ilSource); var compilation = CreateCompilationWithMscorlib45(source, references: new[] { reference }); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("delegate*<MyTask modopt(MyTask), MyTask modopt(MyTask)>", type.ToTestDisplayString()); Assert.Equal("delegate*<System.Threading.Tasks.Task modopt(MyTask), System.Threading.Tasks.Task modopt(MyTask)>", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_Errors() { string source = @" using System.Runtime.CompilerServices; class C { #pragma warning disable CS0169 static A<int, MyTask> F0; static MyTask<B> F1; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder))] struct MyTask { } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] struct MyTask<T> { } struct MyTaskMethodBuilder { public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder(); } struct MyTaskMethodBuilder<T> { public static MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.VerifyDiagnostics( // (5,19): error CS0246: The type or namespace name 'B' could not be found (are you missing a using directive or an assembly reference?) // static MyTask<B> F1; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "B").WithArguments("B").WithLocation(7, 19), // (4,12): error CS0246: The type or namespace name 'A<,>' could not be found (are you missing a using directive or an assembly reference?) // static A<int, MyTask> F0; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "A<int, MyTask>").WithArguments("A<,>").WithLocation(6, 12)); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; Assert.Equal(TypeKind.Error, type.TypeKind); var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("A<System.Int32, MyTask>", type.ToTestDisplayString()); Assert.Equal("A<System.Int32, System.Threading.Tasks.Task>", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F1").Type; Assert.Equal(TypeKind.Error, ((NamedTypeSymbol)type).TypeArguments()[0].TypeKind); normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<B>", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<B>", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_Inner() { string source = @" using System.Runtime.CompilerServices; class C<T, U> { #pragma warning disable CS0169 static MyTask<U> F0; static C<U, MyTask>.MyTask F1; static C<T, MyTask<U>>.Inner F2; #pragma warning restore CS0169 class Inner { } [AsyncMethodBuilder(typeof(C<,>.MyTaskMethodBuilder))] class MyTask { } [AsyncMethodBuilder(typeof(C<,>.MyTaskMethodBuilder<>))] class MyTask<V> { } class MyTaskMethodBuilder { public static MyTaskMethodBuilder Create() => null; } class MyTaskMethodBuilder<V> { public static MyTaskMethodBuilder<V> Create() => null; } } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("C<T, U>.MyTask<U>", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<U>", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F1").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("C<U, C<T, U>.MyTask>.MyTask", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F2").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("C<T, C<T, U>.MyTask<U>>.Inner", type.ToTestDisplayString()); Assert.Equal("C<T, System.Threading.Tasks.Task<U>>.Inner", normalized.ToTestDisplayString()); } [Fact] public void NormalizeTaskTypes_Outer() { string source = @" using System.Runtime.CompilerServices; class C { #pragma warning disable CS0169 static MyTask<MyTask.A> F0; static MyTask<MyTask<object>>.B F1; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder))] class MyTask { internal class A { } } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] class MyTask<V> { internal class B { } } class MyTaskMethodBuilder { public static MyTaskMethodBuilder Create() => null; } class MyTaskMethodBuilder<V> { public static MyTaskMethodBuilder<V> Create() => null; } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateCompilationWithMscorlib45(source); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F0").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<MyTask.A>", type.ToTestDisplayString()); Assert.Equal("System.Threading.Tasks.Task<MyTask.A>", normalized.ToTestDisplayString()); type = compilation.GetMember<FieldSymbol>("C.F1").Type; normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<MyTask<System.Object>>.B", type.ToTestDisplayString()); Assert.Equal("MyTask<System.Threading.Tasks.Task<System.Object>>.B", normalized.ToTestDisplayString()); } /// <summary> /// Normalize should have no effect if System.Threading.Tasks.Task /// and System.Threading.Tasks.Task&lt;T&gt; are not available. /// </summary> [Fact] public void NormalizeTaskTypes_MissingWellKnownTypes() { string source = @" using System.Runtime.CompilerServices; class C { #pragma warning disable CS0169 static MyTask<MyTask> F; #pragma warning restore CS0169 } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder))] struct MyTask { } [AsyncMethodBuilder(typeof(MyTaskMethodBuilder<>))] struct MyTask<T> { } struct MyTaskMethodBuilder { public static MyTaskMethodBuilder Create() => new MyTaskMethodBuilder(); } struct MyTaskMethodBuilder<T> { public MyTaskMethodBuilder<T> Create() => new MyTaskMethodBuilder<T>(); } namespace System.Runtime.CompilerServices { class AsyncMethodBuilderAttribute : System.Attribute { public AsyncMethodBuilderAttribute(System.Type t) { } } } "; var compilation = CreateEmptyCompilation(source, references: new[] { MscorlibRef_v20 }); compilation.VerifyDiagnostics(); var type = compilation.GetMember<FieldSymbol>("C.F").Type; var normalized = type.NormalizeTaskTypes(compilation); Assert.Equal("MyTask<MyTask>", type.ToTestDisplayString()); Assert.Equal("MyTask<MyTask>", normalized.ToTestDisplayString()); } [Fact] public void BetterDelegateType_01() { string source1 = @" using System; class P { static void M1(Func<int> a) { Console.Write(1); } static void M1(Func<uint> a) { Console.Write(2); } static void M2(Func<int> a) { Console.Write(3); } static void M2(Action a) { Console.Write(4); } static void Main() { M1(null); M2(null); } }"; CompileAndVerify(source1, expectedOutput: @"13"); string source2 = @" using System; class P { static void M1(Func<int> a, uint b) { Console.Write(1); } static void M1(Func<uint> a, int b) { Console.Write(2); } static void M2(Func<int> a, uint b) { Console.Write(3); } static void M2(Action a, int b) { Console.Write(4); } static void Main() { M1(null,0); M2(null,0); } }"; CreateCompilation(source2).VerifyDiagnostics( // (13,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M1(System.Func<int>, uint)' and 'P.M1(System.Func<uint>, int)' // M1(null,0); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("P.M1(System.Func<int>, uint)", "P.M1(System.Func<uint>, int)"), // (14,5): error CS0121: The call is ambiguous between the following methods or properties: 'P.M2(System.Func<int>, uint)' and 'P.M2(System.Action, int)' // M2(null,0); Diagnostic(ErrorCode.ERR_AmbigCall, "M2").WithArguments("P.M2(System.Func<int>, uint)", "P.M2(System.Action, int)") ); } [Fact, WorkItem(6560, "https://github.com/dotnet/roslyn/issues/6560")] public void BetterDelegateType_02() { string source1 = @" using System; class C { public static void Main() { Run1(() => MethodReturnsVoid()); Run1(MethodReturnsVoid); Run2(() => MethodReturnsVoid()); Run2(MethodReturnsVoid); } public static object Run1(Action action) { Console.WriteLine(""Run1(Action action)""); action(); return null; } public static object Run1(Func<object> action, bool optional = false) { Console.WriteLine(""Run1(Func<object> action, bool optional = false)""); return action(); } public static object Run2(Func<object> action, bool optional = false) { Console.WriteLine(""Run2(Func<object> action, bool optional = false)""); return action(); } public static object Run2(Action action) { Console.WriteLine(""Run2(Action action)""); action(); return null; } private static void MethodReturnsVoid() { } } "; CompileAndVerify(source1, expectedOutput: @"Run1(Action action) Run1(Action action) Run2(Action action) Run2(Action action)"); } [Fact] public void TestBug9851() { // We should ensure that we do not report "no method M takes n parameters" if in fact // there is any method M that could take n parameters. var source = @" class C { static void J<T>(T t1, T t2) {} static void J(int x) {} public static void M() { J(123.0, 456.0m); } }"; CreateCompilation(source).VerifyDiagnostics( // (8,9): error CS0411: The type arguments for method 'C.J<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // J(123.0, 456.0m); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "J").WithArguments("C.J<T>(T, T)").WithLocation(8, 9)); } [Fact] public void TestLambdaErrorReporting() { var source = @" using System; class C { static void J(Action<int> action) {} static void J(Action<string> action) {} static void K(Action<decimal> action) {} static void K(Action<double> action) {} static void K(Action<string> action) {} public static void M() { // If there are multiple possible bindings for a lambda and both of them produce // 'the same' errors then we should report those errors to the exclusion of any // errors produced on only some of the bindings. // // For instance, here the binding of x as int produces two errors: // * int does not have ToStrign // * int does not have Length // the binding of x as string produces two errors: // * string does not have ToStrign // * cannot multiply strings // We should only report the common error. J(x=>{ Console.WriteLine(x.ToStrign(), x.Length, x * 2); }); // If there is no common error then we should report both errors: J(y=>{ Console.WriteLine(y == string.Empty, y / 4.5); }); // If there is an error that is in common to two of three bindings, // then we should report it but only report it once. // For instance, here the binding of x as decimal produces: // * no decimal == string // * no decimal - double // The binding as double produces: // * no double == string // The binding as string produces: // * no string - double // // There is no error common to all three bindings. However, of the // four errors we should only report two of them. K(z=>{ Console.WriteLine(z == string.Empty, z - 4.5); }); } }"; CreateCompilation(source).VerifyDiagnostics( // (26,36): error CS1061: 'string' does not contain a definition for 'ToStrign' and no extension method 'ToStrign' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) // J(x=>{ Console.WriteLine(x.ToStrign(), x.Length, x * 2); }); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "ToStrign").WithArguments("string", "ToStrign").WithLocation(26, 36), // (30,34): error CS0019: Operator '==' cannot be applied to operands of type 'int' and 'string' // J(y=>{ Console.WriteLine(y == string.Empty, y / 4.5); }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "y == string.Empty").WithArguments("==", "int", "string").WithLocation(30, 34), // (30,53): error CS0019: Operator '/' cannot be applied to operands of type 'string' and 'double' // J(y=>{ Console.WriteLine(y == string.Empty, y / 4.5); }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "y / 4.5").WithArguments("/", "string", "double").WithLocation(30, 53), // (45,53): error CS0019: Operator '-' cannot be applied to operands of type 'string' and 'double' // K(z=>{ Console.WriteLine(z == string.Empty, z - 4.5); }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "z - 4.5").WithArguments("-", "string", "double").WithLocation(45, 53), // (45,34): error CS0019: Operator '==' cannot be applied to operands of type 'double' and 'string' // K(z=>{ Console.WriteLine(z == string.Empty, z - 4.5); }); Diagnostic(ErrorCode.ERR_BadBinaryOps, "z == string.Empty").WithArguments("==", "double", "string").WithLocation(45, 34)); } [Fact] public void TestRefOutAnonymousDelegate() { string source = @" using System; using System.Linq.Expressions; class p { static void Goo<T>(ref Func<T, T> a) { } static void Bar<T>(out Func<T, T> a) { a = null; } static void Goo2<T>(ref Expression<Func<T, T>> a) { } static void Bar2<T>(out Expression<Func<T, T>> a) { a = null; } static void Main() { Goo<string>(x => x); Bar<string>(x => x); Goo2<string>(x => x); Bar2<string>(x => x); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (14,21): error CS1503: Argument 1: cannot convert from 'lambda expression' to 'ref Func<string, string>' // Goo<string>(x => x); Diagnostic(ErrorCode.ERR_BadArgType, "x => x").WithArguments("1", "lambda expression", "ref System.Func<string, string>").WithLocation(14, 21), // (15,21): error CS1503: Argument 1: cannot convert from 'lambda expression' to 'out Func<string, string>' // Bar<string>(x => x); Diagnostic(ErrorCode.ERR_BadArgType, "x => x").WithArguments("1", "lambda expression", "out System.Func<string, string>").WithLocation(15, 21), // (16,22): error CS1503: Argument 1: cannot convert from 'lambda expression' to 'ref Expression<Func<string, string>>' // Goo2<string>(x => x); Diagnostic(ErrorCode.ERR_BadArgType, "x => x").WithArguments("1", "lambda expression", "ref System.Linq.Expressions.Expression<System.Func<string, string>>").WithLocation(16, 22), // (17,22): error CS1503: Argument 1: cannot convert from 'lambda expression' to 'out Expression<Func<string, string>>' // Bar2<string>(x => x); Diagnostic(ErrorCode.ERR_BadArgType, "x => x").WithArguments("1", "lambda expression", "out System.Linq.Expressions.Expression<System.Func<string, string>>").WithLocation(17, 22)); } [Fact, WorkItem(1157097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1157097"), WorkItem(2298, "https://github.com/dotnet/roslyn/issues/2298")] public void TestOverloadResolutionTiebreaker() { // Testing that we get the same ambiguity error as the one reported by the native compiler. string source = @" class C { static void X(params string[] s) {} static void X<T>(T t){} static void X(string s, object o = null) {} public void M() { X((string)null); //-C.X(string, object) } }"; var compilation = CreateCompilation(source, options: TestOptions.DebugDll); compilation.VerifyDiagnostics( // (9,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.X(params string[])' and 'C.X<T>(T)' // X((string)null); //-C.X(string, object) Diagnostic(ErrorCode.ERR_AmbigCall, "X").WithArguments("C.X(params string[])", "C.X<T>(T)").WithLocation(9, 9) ); } [Fact] public void TestConstraintViolationApplicabilityErrors() { // The rules for constraint satisfaction during overload resolution are a bit odd. If a constraint // *on a formal parameter type* is not met then the candidate is not applicable. But if a constraint // is violated *on the method type parameter itself* then the method can be chosen as the best // applicable candidate, and then rejected during "final validation". // // Furthermore: most of the time a constraint violation on a formal type parameter will also // be a constraint violation on the method type parameter. The latter seems like the better // error to report. We only report the violation on the formal parameter if the constraint // is not violated on the method type parameter. var source = @" class C { static string MakeString() { return null; } struct L<S> where S : struct {} class N<T> where T : struct {} public static void M() { string s = MakeString(); // We violate the constraint on both T and U. // The method is not applicable. // Overload resolution fails and reports the violation on U, // even though technically it was the violation on U that caused // the method to be inapplicable. Test1<string>(s, null); // Type inference successfully infers that V is string; // we now should do exactly the same as the previous case. Test2(s, null); // In the previous two tests it is not clear whether the compiler is // allowing overload resolution to succeed and then final validation // fails, or if the candidate set really is empty. We must verify // that the generic version is actually an inapplicable candidate. // // Even though its arguments under construction are better, // the generic version is inapplicable because the constraint // on T is violated. Therefore there is no error; the object // version wins: Test3(s, null); // By contrast, here overload resolution infers that X<string> is the // best possible match, and then final validation fails: Test4(s); // When a method is inapplicable because of a constraint violation we // prefer to state the violation on the method type parameter constraint. // In an error recovery scenario we might not be able to do that. // Here there are two errors: first, the declaration of Test5 is bad because // Y does not meet the constraint on T. Second, the method call is bad // because string does not meet the constraint on T. We cannot say that // string does not meet the constraint on Y because, erroneously, there is // no such constraint. Test5(s, null); // Here we have another error recovery scenario. L<string> is clearly // illegal, but what if we try to do overload resolution anyway? // The constraint is not violated on Z because L<string> is a struct. // Overload resolution fails because the constraint on L is violated in // N<L<string>>. Thus that is the overload resolution error we report. // We therefore end up reporting this error twice, unfortunately; we // should consider putting some gear in place to suppress the cascading // error. Test6<L<string>>(null); } static void Test1<U>(U u, N<U> nu) where U : struct { } static void Test2<V>(V v, N<V> nv) where V : struct { } static void Test3<W>(W w, N<W> nw) where W : struct { } static void Test3(object o1, object o2) {} static void Test4<X>(X x) where X : struct { } static void Test4(object x) {} static void Test5<Y>(Y y, N<Y> ny) { } static void Test6<Z>(N<Z> nz) where Z : struct {} }"; CreateCompilation(source, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (67,36): error CS0453: The type 'Y' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'C.N<T>' // static void Test5<Y>(Y y, N<Y> ny) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "ny").WithArguments("C.N<T>", "T", "Y").WithLocation(67, 36), // (17,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.Test1<U>(U, C.N<U>)' // Test1<string>(s, null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test1<string>").WithArguments("C.Test1<U>(U, C.N<U>)", "U", "string").WithLocation(17, 9), // (21,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'V' in the generic type or method 'C.Test2<V>(V, C.N<V>)' // Test2(s, null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test2").WithArguments("C.Test2<V>(V, C.N<V>)", "V", "string").WithLocation(21, 9), // (36,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'X' in the generic type or method 'C.Test4<X>(X)' // Test4(s); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test4").WithArguments("C.Test4<X>(X)", "X", "string").WithLocation(36, 9), // (47,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'C.N<T>' // Test5(s, null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test5").WithArguments("C.N<T>", "T", "string").WithLocation(47, 9), // (58,17): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'S' in the generic type or method 'C.L<S>' // Test6<L<string>>(null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("C.L<S>", "S", "string").WithLocation(58, 17), // (58,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'S' in the generic type or method 'C.L<S>' // Test6<L<string>>(null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test6<L<string>>").WithArguments("C.L<S>", "S", "string").WithLocation(58, 9)); CreateCompilation(source).VerifyDiagnostics( // (67,36): error CS0453: The type 'Y' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'C.N<T>' // static void Test5<Y>(Y y, N<Y> ny) { } Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "ny").WithArguments("C.N<T>", "T", "Y").WithLocation(67, 36), // (17,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'U' in the generic type or method 'C.Test1<U>(U, C.N<U>)' // Test1<string>(s, null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test1<string>").WithArguments("C.Test1<U>(U, C.N<U>)", "U", "string").WithLocation(17, 9), // (21,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'V' in the generic type or method 'C.Test2<V>(V, C.N<V>)' // Test2(s, null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test2").WithArguments("C.Test2<V>(V, C.N<V>)", "V", "string").WithLocation(21, 9), // (47,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'C.N<T>' // Test5(s, null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test5").WithArguments("C.N<T>", "T", "string").WithLocation(47, 9), // (58,17): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'S' in the generic type or method 'C.L<S>' // Test6<L<string>>(null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "string").WithArguments("C.L<S>", "S", "string").WithLocation(58, 17), // (58,9): error CS0453: The type 'string' must be a non-nullable value type in order to use it as parameter 'S' in the generic type or method 'C.L<S>' // Test6<L<string>>(null); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "Test6<L<string>>").WithArguments("C.L<S>", "S", "string").WithLocation(58, 9)); } [Fact] public void TestBug9583() { var source = @" class C { public static void M() { Goo(); } static void Goo<T>(params T[] x) { } }"; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0411: The type arguments for method 'C.Goo<T>(params T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Goo(); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Goo").WithArguments("C.Goo<T>(params T[])").WithLocation(6, 9)); } [Fact] public void TestMoreOverloadResolutionErrors() { var source = @" class C { static void VoidReturning() {} static void M() { byte b = new byte(1); System.Console.WriteLine(VoidReturning()); } }"; CreateCompilation(source).VerifyDiagnostics( // (7,22): error CS1729: 'byte' does not contain a constructor that takes 1 arguments // byte b = new byte(1); Diagnostic(ErrorCode.ERR_BadCtorArgCount, "byte").WithArguments("byte", "1").WithLocation(7, 22), // (8,34): error CS1503: Argument 1: cannot convert from 'void' to 'bool' // System.Console.WriteLine(VoidReturning()); Diagnostic(ErrorCode.ERR_BadArgType, "VoidReturning()").WithArguments("1", "void", "bool").WithLocation(8, 34)); } [Fact] public void TestBug6156() { TestOverloadResolutionWithDiff( @" class C { public static void M() { int y = 123; Out2 o2 = new Out2(); Ref2 r2 = o2; Out1 o1 = o2; Ref1 r1 = o2; r1.M(ref y); //-Ref1.M(ref int) o1.M(ref y); //-Ref1.M(ref int) o1.M(out y); //-Out1.M(out int) r2.M(ref y); //-Ref2.M(ref int) r2.M(out y); //-Out1.M(out int) o2.M(ref y); //-Ref2.M(ref int) o2.M(out y); //-Out2.M(out int) } } class Ref1 { public virtual void M(ref int x) { x = 1; } // SLOT1 } class Out1 : Ref1 { public virtual void M(out int x) { x = 2; } // SLOT2 } class Ref2 : Out1 { public override void M(ref int x) { x = 3; } // CLR says this overrides SLOT2, even though there is a ref/out mismatch with Out1. // C# says this overrides SLOT1 } class Out2 : Ref2 { public override void M(out int x) { x = 4; } // CLR says this overrides SLOT2, even though there is a ref/out mismatch with Ref2.M. // C# says this overrides SLOT2 }"); } [Fact] public void TestGenericMethods() { TestOverloadResolutionWithDiff( @" class C { class D<T> { public static void N<U>(U u){} public class E<V> { public static void O<W>(W w){} } } void M() { D<int>.N<byte>(1); //-C.D<int>.N<byte>(byte) D<int>.E<double>.O<short>(1); //-C.D<int>.E<double>.O<short>(short) } }"); } [Fact] public void TestDelegateBetterness() { TestOverloadResolutionWithDiff( @" delegate void Action(); delegate void Action<in A>(A a); delegate R Func<out R>(); delegate R Func<in A, out R>(A a); delegate R Func2<in A, out R>(A a); class Animal {} class Mammal : Animal {} class Tiger : Mammal {} class C { static void N1(Func<object> f){} static void N1(Func<string> f){} static void N2(Func<int, object> f){} static void N2(Action<int> f){} static void N3(Func<int, Tiger> f){} static void N3(Func2<int, Mammal> f){} static void N4(Func<int, Animal> f){} static void N4(Func2<int, Mammal> f){} void M() { // If we have a lambda argument and two delegates, the rules are: // First, if one delegate is convertible to the other but not vice-versa // then the more specific delegate wins. A Func<string> is convertible to Func<object> // but not vice-versa, so Func<string> must be more specific: // This test is disabled; see the comments to TestBug11961 above. // N1(()=>null); // Second, if the delegates have identical parameters, then the non-void one wins. // This lambda could be both an action and a func; we don't know if the construction // is being done for its value or for its side effects. N2(x=>new System.Object()); //-C.N2(Func<int, object>) // Third, if the delegates have identical parameters and both have a return type // and the lambda has an inferred return type, then the better delegate is the // one where the delegate return type exactly matches the lambda return type. N3(x=>new Tiger()); //-C.N3(Func<int, Tiger>) // Fourth, if the delegate return type does not exactly match the lambda return // type then the most specific delegate return type wins. N4(x=>new Tiger()); //-C.N4(Func2<int, Mammal>) } } "); } [Fact] public void TestTieBreakers() { TestOverloadResolutionWithDiff( @" class C { class D<TD>{} void N1<T1>(T1 p1) {} void N1(int p1) {} void N2(int p1) {} void N2(params int[] p1) {} void N3(int p1, int p2, params int[] p3) {} void N3(int p1, params int[] p3) {} void N4(int p1, int p2 = 0) {} void N4(int p1) {} void N51<T51>(T51 p1, double p2 = 0) {} void N51<T51>(int p1, string p2 = null ) {} void N52<T52>(D<T52> p1, double p2 = 0) {} void N52<T52>(D<int> p1, string p2 = null ) {} void N53<T53>(T53[] p1, double p2 = 0) {} void N53<T53>(int[] p1, string p2 = null ) {} void M() { // If due to construction or dynamicness all the effective parameters of two methods are identical // then we do a series of tiebreaking rules. // 1: A generic method is worse than a non-generic method. N1(123); //-C.N1(int) // 2: A method applicable in normal form is better than one applicable only in expanded form. N2(123); //-C.N2(int) // 3: If both methods are applicable in expanded form then the one with more 'real' parameters wins. N3(1, 2, 3, 4, 5, 6); //-C.N3(int, int, params int[]) // 4: If one method has no default arguments substituted and the other has one or more, the one // with no defaults wins. N4(1); //-C.N4(int) // 5: The more specific method wins. One method's declared parameter types list is more specific than // anothers if, for each position in the list, the type of one is not less specific than that // of the other, and, for at least one position, the type is more specific than that of the other. // 5.1: A type parameter is less specific than any other type. // 5.2: A constructed type C<X, Y> is less specific than C<A, B> if the type list <X, Y> is less specific than <A, B> // 5.3: An array type X[] is less specific than Y[] if X is less specific than Y. // 5.4: NOT TESTED: A pointer type X* is less specific than Y* if X is less specific than Y*. //EDMAURER removed the next three tests that fail due to the fact that omitted optional parameters are not supported. // N51<int>(123); //C.N51<int>(int, string) // N52<int>(null); //C.N52<int>(C.D<int>, string) // N53<int>(null); //C.N53<int>(int[], string) // 6: NOT TESTED: A non-lifted operator is better than a lifted operator. } } "); } [WorkItem(540153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540153")] [Fact] public void TestOverridingMismatchedParamsErrorCase_Source() { // Tests: // Replace params with non-params in signature of overridden member (and vice-versa) var source = @" abstract class Base { public abstract void Method1(Derived c1, Derived c2, params Derived[] c3); public abstract void Method2(Derived c1, Derived c2, Derived[] c3); } class Derived : Base { public override void Method1(Derived C1, Derived C2, Derived[] C3) { } //removes 'params' public override void Method2(Derived C1, Derived C2, params Derived[] C3) { } //adds 'params' } class Test2 { public static void Main2() { Derived d = new Derived(); Base b = d; b.Method1(d, d, d, d, d); // Fine d.Method1(d, d, d, d, d); // Fine b.Method2(d, d, d, d, d); // Should report error - No overload for Method2 takes 5 arguments d.Method2(d, d, d, d, d); // Should report error - No overload for Method2 takes 5 arguments } }"; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgCount, "Method2").WithArguments("Method2", "5"), Diagnostic(ErrorCode.ERR_BadArgCount, "Method2").WithArguments("Method2", "5")); } [Fact] public void TestImplicitImplMismatchedParamsErrorCase_Source() { // Tests: // Replace params with non-params in signature of implemented member (and vice-versa) var source = @" interface Base { void Method1(Derived c1, Derived c2, params Derived[] c3); void Method2(Derived c1, Derived c2, Derived[] c3); } class Derived : Base { public void Method1(Derived C1, Derived C2, Derived[] C3) { } //removes 'params' public void Method2(Derived C1, Derived C2, params Derived[] C3) { } //adds 'params' } class Test2 { public static void Main2() { Derived d = new Derived(); Base b = d; b.Method1(d, d, d, d, d); // Fine d.Method1(d, d, d, d, d); // Should report error - No overload for Method1 takes 5 arguments b.Method2(d, d, d, d, d); // Should report error - No overload for Method2 takes 5 arguments d.Method2(d, d, d, d, d); // Fine } }"; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgCount, "Method1").WithArguments("Method1", "5"), Diagnostic(ErrorCode.ERR_BadArgCount, "Method2").WithArguments("Method2", "5")); } [Fact] public void TestExplicitImplMismatchedParamsErrorCase_Source() { // Tests: // Replace params with non-params in signature of implemented member (and vice-versa) var source = @" interface Base { void Method1(Derived c1, Derived c2, params Derived[] c3); void Method2(Derived c1, Derived c2, Derived[] c3); } class Derived : Base { void Base.Method1(Derived C1, Derived C2, Derived[] C3) { } //removes 'params' void Base.Method2(Derived C1, Derived C2, params Derived[] C3) { } //adds 'params' - CS0466 } class Test2 { public static void Main2() { Derived d = new Derived(); Base b = d; b.Method1(d, d, d, d, d); // Fine b.Method2(d, d, d, d, d); // Should report error - No overload for Method2 takes 5 arguments } }"; CreateCompilation(source).VerifyDiagnostics( // (10,15): error CS0466: 'Derived.Base.Method2(Derived, Derived, params Derived[])' should not have a params parameter since 'Base.Method2(Derived, Derived, Derived[])' does not Diagnostic(ErrorCode.ERR_ExplicitImplParams, "Method2").WithArguments("Derived.Base.Method2(Derived, Derived, params Derived[])", "Base.Method2(Derived, Derived, Derived[])"), // (19,9): error CS1501: No overload for method 'Method2' takes 5 arguments Diagnostic(ErrorCode.ERR_BadArgCount, "Method2").WithArguments("Method2", "5")); } [WorkItem(540153, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540153")] [WorkItem(540406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540406")] [ClrOnlyFact(ClrOnlyReason.Ilasm)] public void TestOverridingMismatchedParamsErrorCase_Metadata() { // Tests: // Replace params with non-params in signature of overridden member (and vice-versa) var ilSource = @" .class public abstract auto ansi beforefieldinit Base extends [mscorlib]System.Object { .method public hidebysig newslot abstract virtual instance void Method1(class Derived c1, class Derived c2, class Derived[] c3) cil managed { .param [3] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {} } // end of method Base::Method1 .method public hidebysig newslot abstract virtual instance void Method2(class Derived c1, class Derived c2, class Derived[] c3) cil managed { } // end of method Base::Method2 .method family hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [mscorlib]System.Object::.ctor() IL_0006: ret } // end of method Base::.ctor } // end of class Base .class public auto ansi beforefieldinit Derived extends Base { .method public hidebysig virtual instance void Method1(class Derived C1, class Derived C2, class Derived[] C3) cil managed { ret } // end of method Derived::Method1 //// Adds 'params' //// .method public hidebysig virtual instance void Method2(class Derived C1, class Derived C2, class Derived[] C3) cil managed { .param [3] .custom instance void [mscorlib]System.ParamArrayAttribute::.ctor() = {} ret } // end of method Derived::Method2 //// Removes 'params' //// .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { // Code size 7 (0x7) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void Base::.ctor() IL_0006: ret } // end of method Derived::.ctor } // end of class Derived "; var csharpSource = @" class Test2 { public static void Main2() { Derived d = new Derived(); Base b = d; b.Method1(d, d, d, d, d); // Fine d.Method1(d, d, d, d, d); // Fine b.Method2(d, d, d, d, d); // Should report error - No overload for Method2 takes 5 arguments d.Method2(d, d, d, d, d); // Should report error - No overload for Method2 takes 5 arguments } }"; // Same errors as in source case var comp = CreateCompilationWithILAndMscorlib40(csharpSource, ilSource); comp.VerifyDiagnostics( Diagnostic(ErrorCode.ERR_BadArgCount, "Method2").WithArguments("Method2", "5"), Diagnostic(ErrorCode.ERR_BadArgCount, "Method2").WithArguments("Method2", "5")); } [WorkItem(6353, "DevDiv_Projects/Roslyn")] [Fact()] public void TestBaseAccessForAbstractMembers() { // Tests: // Override virtual member with abstract member – override this abstract member in further derived class // Test that call to abstract member fails when calling through "base." var source = @" abstract class Base<T, U> { T f = default(T); public abstract void Method(T i, U j); public virtual T Property { get { return f; } set { } } } class Base2<A, B> : Base<A, B> { public override void Method(A a, B b) { base.Method(a, b); // Error - Cannot call abstract base member } public override A Property { set { } } } abstract class Base3<T, U> : Base2<T, U> { public override abstract void Method(T x, U y); public override abstract T Property { set; } } class Base4<U, V> : Base3<U, V> { U f; public override void Method(U x, V y) { base.Method(x, y); // Error - Cannot call abstract base member } public override U Property { set { f = base.Property; // No error - Only setter is abstract in base class base.Property = f; // Error - Cannot call abstract base member } } }"; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Method").WithArguments("Base<A, B>.Method(A, B)"), Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Method").WithArguments("Base3<U, V>.Method(U, V)"), Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Property").WithArguments("Base3<U, V>.Property")); } [WorkItem(6353, "DevDiv_Projects/Roslyn")] [Fact()] public void TestBaseAccessForAbstractMembers1() { // Tests: // Override virtual member with abstract member – override this abstract member in further derived class // Test that assigning an abstract member referenced through "base." to a delegate fails var source = @" using System; abstract class Base<T, U> { public abstract void Method(T i, U j); } class Base2<A, B> : Base<A, B> { public override void Method(A a, B b) { Action<A, B> m = base.Method; // Error - Cannot call abstract base member } }"; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Method").WithArguments("Base<A, B>.Method(A, B)")); } [WorkItem(6353, "DevDiv_Projects/Roslyn")] [Fact()] public void TestBaseAccessForAbstractMembers2() { var source = @" namespace A { abstract class Base<T> { public abstract T Method(int x); } abstract class Base2<A> : Base<A> { A f = default(A); public override A Method(int x) { return f; } public abstract A Method(A x); } class Derived : Base2<long> { // Surprisingly in Dev10 base.Method seems to bind to the second overload above and reports error (can't call abstract method) public override long Method(int x) { base.Method(x); return 1; } public override long Method(long x) { return 2; } } } namespace B { abstract class Base2<A> { A f = default(A); public virtual A Method(int x) { return f; } public abstract A Method(A x); } class Derived : Base2<long> { // But the same call seems to work in this case in Dev10 i.e. base.Method correctly binds to the first overload public override long Method(int x) { base.Method(x); return 1; } public override long Method(long x) { return 2; } } } "; CreateCompilation(source).VerifyDiagnostics( Diagnostic(ErrorCode.ERR_AbstractBaseCall, "base.Method").WithArguments("A.Base2<long>.Method(long)")); } [Fact] public void Bug8766_ConstructorOverloadResolution_PrivateCtor() { var source = @"using System; public class A { const int C = 1; private A(int x) { Console.WriteLine(""int""); } public A(long x) { Console.WriteLine(""long""); } public void Goo() { A a = new A(C); } static void Main() { A a = new A(C); a.Goo(); B.Goo(); } } public class B { const int C = 1; public static void Goo() { A a = new A(C);} } "; CompileAndVerify(source, expectedOutput: @"int int long "); } [Fact] public void Bug8766_ConstructorOverloadResolution_ProtectedCtor() { var source = @"using System; public class A { const int C = 1; protected A(int x) { Console.WriteLine(""int""); } public A(long x) { Console.WriteLine(""long""); } public void Goo() { A a = new A(C); } static void Main() { A a = new A(C); a.Goo(); B.Goo(); } } public class B { const int C = 1; public static void Goo() { A a = new A(C);} } "; CompileAndVerify(source, expectedOutput: @"int int long "); } [Fact, WorkItem(546694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546694")] public void Bug16581_ConstructorOverloadResolution_BaseClass() { var source = @" using System; class A { private A(int x) { } public A(long x) { Console.WriteLine(""PASS""); } private void M(int x) { } public void M(long x) { Console.WriteLine(""PASS""); } } class B: A { public B(): base(123) { base.M(123); } public static void Main() { var unused = new B(); } } "; CompileAndVerify(source, expectedOutput: @"PASS PASS"); } [Fact, WorkItem(529847, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529847")] public void Bug14585_ConstructorOverloadResolution_BaseClass() { var source = @" public class Base { protected Base() { } public Base(int i) { } } class Test { static void Main(string[] args) { var a = new Base(); } } "; CreateCompilation(source).VerifyDiagnostics( // (17,21): error CS0122: 'Base.Base()' is inaccessible due to its protection level // var a = new Base(); Diagnostic(ErrorCode.ERR_BadAccess, "Base").WithArguments("Base.Base()")); } [Fact] public void Bug8766_MethodOverloadResolution() { var source = @"using System; public class A { const int C = 1; void AA(int x) { Console.WriteLine(""int""); } public void AA(long x) { Console.Write(""long""); } public void Goo() { A a = new A(); a.AA(C); } static void Main() { A a = new A(); a.Goo(); B.Goo(); } } public class B { const int C = 1; public static void Goo() { A a = new A(); a.AA(C);} } "; CompileAndVerify(source, expectedOutput: @"int long "); } [Fact] public void RegressionTestForIEnumerableOfDynamic() { TestOverloadResolutionWithDiff( @"using System; using System.Collections.Generic; class C { class DynamicWrapper { public IEnumerable<dynamic> Value { get; set; } } static void M() { DynamicWrapper[] array = null; Goo(array, x => x.Value, (x, y) => string.Empty); //-C.Goo(System.Collections.Generic.IEnumerable<C.DynamicWrapper>, System.Func<C.DynamicWrapper, System.Collections.Generic.IEnumerable<dynamic>>, System.Func<C.DynamicWrapper, dynamic, string>) } static IEnumerable<dynamic> Goo( object source, Func<dynamic, IEnumerable<dynamic>> collectionSelector, Func<dynamic, dynamic, dynamic> resultSelector) { return null; } static IEnumerable<string> Goo( IEnumerable<DynamicWrapper> source, Func<DynamicWrapper, IEnumerable<dynamic>> collectionSelector, Func<DynamicWrapper, dynamic, string> resultSelector) { return null; } }"); } [Fact] public void MissingBaseTypeAndParamsCtor() { var cCommon = CreateCompilation(@" public class TCommon {} ", assemblyName: "cCommon"); Assert.Empty(cCommon.GetDiagnostics()); var cCS = CreateCompilation(@" public class MProvider : TCommon {} ", new MetadataReference[] { new CSharpCompilationReference(cCommon) }, assemblyName: "cCS"); Assert.Empty(cCS.GetDiagnostics()); var cFinal = CreateCompilation(@" public class T : MProvider {} class PArray { public PArray(TCommon t, params object[] p) { } } class Goo { void M() { T t = new T(); var x = new PArray(t, 1, 2); } } ", //note that the reference to the 'cCS' compilation is missing. new MetadataReference[] { new CSharpCompilationReference(cCommon) }); cFinal.GetDiagnostics(); } [Fact] public void RefOmittedComCall_Basic() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, int y); } public class Ref1Impl : IRef1 { public int M(ref int x, int y) { return x + y; } } class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int ret = ref1.M(10, 10); Console.WriteLine(ret); return ret; } } "; CompileAndVerify(source, expectedOutput: @"20"); } [WorkItem(546733, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546733")] [Fact] public void RefOmittedComCall_Iterator() { var source = @"using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, int y); } public class Ref1Impl : IRef1 { public int M(ref int x, int y) { return x + y; } } class Test { static IEnumerable<int> M() { IRef1 ref1 = new Ref1Impl(); int ret = ref1.M(10, 2); yield return ret; } public static void Main() { Console.WriteLine(M().First()); } }"; CompileAndVerify(source, expectedOutput: @"12"); } [Fact] public void RefOmittedComCall_ArgumentNotAddressTaken_01() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, ref int y); } public class Ref1Impl : IRef1 { public int M(ref int x, ref int y) { int ret = x + y; x = -1; y = 0; return ret; } } class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int x = 10, y = 10; int ret = ref1.M(x, ref y); Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(ret); return ret; } } "; CompileAndVerify(source, expectedOutput: @"10 0 20"); } [Fact] public void RefOmittedComCall_ArgumentNotAddressTaken_02() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, int y); } public class Ref1Impl : IRef1 { public int M(ref int x, int y) { int ret = x + y; x = 0; return ret; } } class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int x = 10, y = 10; int ret = ref1.M(x, y); Console.WriteLine(x); Console.WriteLine(y); Console.WriteLine(ret); return ret; } } "; CompileAndVerify(source, expectedOutput: @"10 10 20"); } [Fact] public void RefOmittedComCall_NamedArguments() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, ref int y); } public class Ref1Impl : IRef1 { public int M(ref int x, ref int y) { int ret = x + y; x = -1; y = 0; return ret; } } class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int y = 10; int ret = ref1.M(y: ref y, x: y); Console.WriteLine(y); Console.WriteLine(ret); return ret; } } "; CompileAndVerify(source, expectedOutput: @"0 20"); } [Fact] public void RefOmittedComCall_MethodCallArgument() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, ref int y, ref int z); } public class Ref1Impl : IRef1 { public int M(ref int x, ref int y, ref int z) { int ret = x + y + z; x = -1; y = -2; z = -3; return ret; } } class Test { public static int Goo(ref int x) { Console.WriteLine(x); x++; return x; } public static int Main() { IRef1 ref1 = new Ref1Impl(); int a = 10; int ret = ref1.M( z: Goo(ref a), // Print 10 y: ref1.M(z: ref a, y: a, x: ref a), x: Goo(ref a)); // Print -3 Console.WriteLine(a); // Print -2 Console.WriteLine(ret); // Print 42 int b = 1, c = 2; ret = ref1.M( z: Goo(ref c), // Print 2 y: ref1.M(z: ref b, y: b + c, x: b), x: Goo(ref b)); // Print -3 Console.WriteLine(b); // Print -2 Console.WriteLine(c); // Print 3 Console.WriteLine(ret); // Print 7 return ret; } } "; CompileAndVerify(source, expectedOutput: @"10 -3 -2 42 2 -3 -2 3 7"); } [Fact] public void RefOmittedComCall_AssignToRefParam() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(ref int x, ref int y); } public class Ref1Impl : IRef1 { public int M(ref int x, ref int y) { x = 1; y = 2; return x + y; } } class Test { public static int Goo(ref int x) { Console.WriteLine(x); x++; return x; } public static int Main() { IRef1 ref1 = new Ref1Impl(); int a = 10; int ret = ref1.M(a, a) + ref1.M(10, 10); Console.WriteLine(ret); return ret; } } "; CompileAndVerify(source, expectedOutput: @"6"); } [Fact] public void RefOmittedComCall_ExternMethod() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public class Ref1Impl { public extern int M(ref int x, int y); } class Test { public static int Main() { var ref1 = new Ref1Impl(); int ret = ref1.M(10, 10); Console.WriteLine(ret); return ret; } } "; CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(530747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530747")] public void RefOmittedComCall_Unsafe() { // Native compiler generates invalid IL for ref omitted argument of pointer type, while Roslyn generates correct IL. // See Won't Fixed Devdiv bug #16837 for details. var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] unsafe public interface IRef1 { void M(ref int* x); void M2(ref int* x, ref int* y); void M3(ref int* x, ref int* y); } unsafe public class Ref1Impl : IRef1 { public void M(ref int* x) { *x = *x + 1; x = null; } public void M2(ref int* x, ref int* y) { *y = *y + 1; } public void M3(ref int* x, ref int* y) { x = null; *y = *y + 1; } } unsafe class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int a = 1; int *p = &a; ref1.M(ref p); Console.WriteLine(a); Console.WriteLine(p == null); p = &a; ref1.M2(&a, ref p); Console.WriteLine(a); Console.WriteLine(*p); ref1.M3(p, ref p); Console.WriteLine(a); Console.WriteLine(*p); return 0; } } "; CompileAndVerify(source, options: TestOptions.UnsafeReleaseExe, verify: Verification.Fails, expectedOutput: @"2 True 3 3 4 4"); } [Fact()] public void RefOmittedComCall_ERR_ComImportWithImpl() { var source = @"using System; using System.Runtime.InteropServices; public interface IRef1 { int M(ref int x, int y); } [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public class Ref1Impl : IRef1 { public int M(ref int x, int y) { return x + y; } } class Test { public static int Main() { var ref1 = new Ref1Impl(); int ret = ref1.M(10, 10); Console.WriteLine(ret); return ret; } } "; CreateCompilation(source).VerifyDiagnostics( // (13,16): error CS0423: Since 'Ref1Impl' has the ComImport attribute, 'Ref1Impl.M(ref int, int)' must be extern or abstract // public int M(ref int x, int y) { return x + y; } Diagnostic(ErrorCode.ERR_ComImportWithImpl, "M").WithArguments("Ref1Impl.M(ref int, int)", "Ref1Impl").WithLocation(13, 16)); } [Fact] public void RefOmittedComCall_Error_NonComImportType() { var source = @"using System; using System.Runtime.InteropServices; public interface IRef1 { int M(ref int x, int y); } [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public class Ref1Impl: IRef1 { public extern int M(ref int x, int y); } class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int ret = ref1.M(10, 10); Console.WriteLine(ret); return ret; } } "; CreateCompilation(source).VerifyDiagnostics( // (21,25): error CS1620: Argument 1 must be passed with the 'ref' keyword // int ret = ref1.M(10, 10); Diagnostic(ErrorCode.ERR_BadArgRef, "10").WithArguments("1", "ref").WithLocation(21, 25)); } [Fact] public void RefOmittedComCall_Error_OutParam() { var source = @"using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { int M(out int x, int y); } public class Ref1Impl : IRef1 { public int M(out int x, int y) { x = 1; return y; } } class Test { public static int Main() { IRef1 ref1 = new Ref1Impl(); int x; int ret = ref1.M(x, 10); Console.WriteLine(ret); return ret; } }"; CreateCompilation(source).VerifyDiagnostics( // (22,25): error CS1620: Argument 1 must be passed with the 'out' keyword // int ret = ref1.M(x, 10); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "out").WithLocation(22, 25), // (22,25): error CS0165: Use of unassigned local variable 'x' // int ret = ref1.M(x, 10); Diagnostic(ErrorCode.ERR_UseDefViolation, "x").WithArguments("x").WithLocation(22, 25)); } [Fact] public void RefOmittedComCall_Error_WithinAttributeContext() { var source = @" using System; using System.Runtime.InteropServices; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] class Attr: Attribute { public Attr(int x) {} } [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] class Attr2: Attribute { public Attr2(ref int x) {} } [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] [Attr(new Goo().M1(1, 1))] [Attr(Goo.M2(1, 1))] [Attr2(1)] public class Goo { public extern int M1(ref int x, int y); public static extern int M2(ref int x, int y); }"; CreateCompilation(source).VerifyDiagnostics( // (13,7): error CS0424: 'Attr2': a class with the ComImport attribute cannot specify a base class // class Attr2: Attribute Diagnostic(ErrorCode.ERR_ComImportWithBase, "Attr2").WithArguments("Attr2").WithLocation(13, 7), // (15,12): error CS0669: A class with the ComImport attribute cannot have a user-defined constructor // public Attr2(ref int x) {} Diagnostic(ErrorCode.ERR_ComImportWithUserCtor, "Attr2").WithLocation(15, 12), // (20,20): error CS1620: Argument 1 must be passed with the 'ref' keyword // [Attr(new Goo().M1(1, 1))] Diagnostic(ErrorCode.ERR_BadArgRef, "1").WithArguments("1", "ref").WithLocation(20, 20), // (21,14): error CS1620: Argument 1 must be passed with the 'ref' keyword // [Attr(Goo.M2(1, 1))] Diagnostic(ErrorCode.ERR_BadArgRef, "1").WithArguments("1", "ref").WithLocation(21, 14), // (22,8): error CS1620: Argument 1 must be passed with the 'ref' keyword // [Attr2(1)] Diagnostic(ErrorCode.ERR_BadArgRef, "1").WithArguments("1", "ref").WithLocation(22, 8)); } [Fact] public void RefOmittedComCall_CtorWithRefArgument() { var ilSource = @" .class public auto ansi import beforefieldinit Ref1 extends [mscorlib]System.Object { .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 41 38 38 41 31 37 35 44 2D 32 34 34 38 // ..$A88A175D-2448 2D 34 34 37 41 2D 42 37 38 36 2D 36 34 36 38 32 // -447A-B786-64682 43 42 45 46 31 35 36 00 00 ) // CBEF156.. .method public hidebysig specialname rtspecialname instance void .ctor(int32& x) runtime managed internalcall { } // end of method Ref1::.ctor } // end of class Ref1 "; var source = @" public class MainClass { public static int Main () { int x = 0; var r = new Ref1(x); return 0; } }"; var compilation = CreateCompilationWithILAndMscorlib40(source, ilSource); compilation.VerifyDiagnostics( // (7,26): error CS1620: Argument 1 must be passed with the 'ref' keyword // var r = new Ref1(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref").WithLocation(7, 26)); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122")] public void TestComImportOverloadResolutionCantOmitRef() { string source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] abstract class C { extern public void M(ref short p); extern public void M(sbyte p); } class D : C { public static void Goo() { short x = 123; sbyte s = 123; new D().M(x); C c = new D(); c.M(x); new D().M(s); } } "; CreateCompilation(source).VerifyDiagnostics( // (18,19): error CS1620: Argument 1 must be passed with the 'ref' keyword // new D().M(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref")); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122")] public void RefOmittedComCall_BaseTypeComImport() { string source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] abstract class E { extern public void M(ref short p); } class F : E { [DllImport(""goo"")] extern public void M(sbyte p); public static void Goo() { short x = 123; sbyte s = 123; new F().M(x); E e = new F(); e.M(x); new F().M(s); } } [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] abstract class G { extern public void M(sbyte p); } class H : G { extern public void M(ref short p); public static void Goo() { short x = 123; sbyte s = 123; new H().M(x); G g = new H(); g.M(x); new H().M(s); } } [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] abstract class I { } class J : I { extern public void M(sbyte p); extern public void M(ref short p); public static void Goo() { short x = 123; sbyte s = 123; new J().M(x); I i = new J(); i.M(x); new J().M(s); } } "; CreateCompilation(source).VerifyDiagnostics( // (12,6): error CS0601: The DllImport attribute must be specified on a method marked 'static' and 'extern' // [DllImport("goo")] Diagnostic(ErrorCode.ERR_DllImportOnInvalidMethod, "DllImport"), // (20,19): error CS1503: Argument 1: cannot convert from 'short' to 'sbyte' // new F().M(x); Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "short", "sbyte"), // (36,24): warning CS0626: Method, operator, or accessor 'H.M(ref short)' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern public void M(ref short p); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("H.M(ref short)"), // (43,19): error CS1620: Argument 1 must be passed with the 'ref' keyword // new H().M(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref"), // (46,13): error CS1503: Argument 1: cannot convert from 'short' to 'sbyte' // g.M(x); Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "short", "sbyte"), // (58,24): warning CS0626: Method, operator, or accessor 'J.M(sbyte)' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern public void M(sbyte p); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("J.M(sbyte)"), // (59,24): warning CS0626: Method, operator, or accessor 'J.M(ref short)' is marked external and has no attributes on it. Consider adding a DllImport attribute to specify the external implementation. // extern public void M(ref short p); Diagnostic(ErrorCode.WRN_ExternMethodNoImplementation, "M").WithArguments("J.M(ref short)"), // (66,19): error CS1503: Argument 1: cannot convert from 'short' to 'sbyte' // new J().M(x); Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "short", "sbyte"), // (69,11): error CS1061: 'I' does not contain a definition for 'M' and no extension method 'M' accepting a first argument of type 'I' could be found (are you missing a using directive or an assembly reference?) // i.M(x); Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "M").WithArguments("I", "M")); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122")] public void RefOmittedComCall_DerivedComImport() { string source = @" using System; using System.Runtime.InteropServices; interface A { void M(ref short p); void M(sbyte p); } [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] interface B: A { } class C: B { public void M(ref short p) {} public void M(sbyte p) {} public static void Goo() { short x = 123; sbyte s = 123; A a = new C(); B b = new C(); C c = new C(); a.M(x); b.M(x); c.M(x); a.M(s); b.M(s); c.M(s); } } "; CreateCompilation(source).VerifyDiagnostics( // (30,13): error CS1620: Argument 1 must be passed with the 'ref' keyword // a.M(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref"), // (32,13): error CS1620: Argument 1 must be passed with the 'ref' keyword // c.M(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref")); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122")] public void RefOmittedComCall_TypeParameterConstrainedToComImportType() { string source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] class K { public extern void M(ref short p); public extern void M(sbyte p); } class H<T> where T: K, new() { public static void Goo() { short x = 123; T t = new T(); t.M(x); } } "; CreateCompilation(source).VerifyDiagnostics( // (18,13): error CS1620: Argument 1 must be passed with the 'ref' keyword // t.M(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref")); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122")] public void RefOmittedComCall_StaticMethod1() { string source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] static class E { public extern static void M(ref short p); public extern static void M(sbyte p); } class Y { public static void Goo() { short x = 123; E.M(x); // Dev11 reports CS1620 (missing 'ref') } } "; // BREAK: Dev11 does not allow this, but it's probably an accident. // That is, it inspects the receiver type of the invocation and it // finds no receiver for a static method invocation. // MITIGATION: Candidates with 'ref' omitted lose tie-breakers, so // it should not be possible for this to cause overload resolution // to succeed in a different way. CreateCompilation(source).VerifyDiagnostics(); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122")] public void RefOmittedComCall_StaticMethod2() { string source = @" using System; using System.Runtime.InteropServices; [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] class E { public extern static void M(ref short p); } [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF137"")] class F { public extern static void M(ref short p); } class Y { public static void Main() { short x = 123; E E = null; E.M(x); // Allowed in dev11. F.M(x); // CS1620 (missing 'ref') in dev11. } } "; // BREAK: Dev11 produces an error. It doesn't make sense that the introduction // of a color-color local would eliminate an error, since it does not affect the // outcome of overload resolution. CreateCompilation(source).VerifyDiagnostics( // (22,11): warning CS0219: The variable 'E' is assigned but its value is never used // E E = null; Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "E").WithArguments("E").WithLocation(22, 11)); } [Fact, WorkItem(546122, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546122"), WorkItem(842476, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/842476")] public void RefOmittedComCall_ExtensionMethod() { string source = @" using System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; [ComImport, Guid(""1234C65D-1234-447A-B786-64682CBEF136"")] class C { } static class CExtensions { public static void M(this C c, ref short p) {} public static void M(this C c, sbyte p) {} public static void I(this C c, ref int p) {} } class X { public static void Goo() { short x = 123; C c = new C(); c.M(x); c.I(123); } } "; CompileAndVerify(source); } [Fact] public void RefOmittedComCall_OverloadResolution_SingleArgument() { var source = @" using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { void M1(int x); void M1(ref int x); void M2(long x); void M2(ref int x); void M3(char x); void M3(ref int x); void M4(out uint x); void M4(ref int x); void M5(ref int x); void M5(ref long x); void M6(ref char x); void M6(ref long x); void M7(ref long x); void M7(int x); void M8(ref long x); void M8(char x); void M9(ref char x); void M9(long x); } public class Ref1Impl : IRef1 { public void M1(int x) { Console.WriteLine(1); } public void M1(ref int x) { Console.WriteLine(2); } public void M2(long x) { Console.WriteLine(3); } public void M2(ref int x) { Console.WriteLine(4); } public void M3(char x) { Console.WriteLine(5); } public void M3(ref int x) { Console.WriteLine(6); } public void M4(out uint x) { x = 0; Console.WriteLine(7); } public void M4(ref int x) { Console.WriteLine(8); } public void M5(ref int x) { Console.WriteLine(9); } public void M5(ref long x) { Console.WriteLine(10); } public void M6(ref char x) { Console.WriteLine(11); } public void M6(ref long x) { Console.WriteLine(12); } public void M7(ref long x) { Console.WriteLine(13); } public void M7(int x) { Console.WriteLine(14); } public void M8(ref long x) { Console.WriteLine(15); } public void M8(char x) { Console.WriteLine(16); } public void M9(ref char x) { Console.WriteLine(17); } public void M9(long x) { Console.WriteLine(18); } } class Test { public static void Main() { IRef1 ref1 = new Ref1Impl(); int i = 1; long l = 1; char c = 'c'; // void M1(int x); // void M1(ref int x); ref1.M1(10); //ref1.M1(10L); CS1503 ref1.M1('c'); ref1.M1(i); //ref1.M1(l); CS1503 ref1.M1(c); ref1.M1(ref i); //ref1.M1(ref l); CS1615 //ref1.M1(ref c); CS1615 // void M2(long x); // void M2(ref int x); Console.WriteLine(); ref1.M2(10); ref1.M2(10L); ref1.M2('c'); ref1.M2(i); ref1.M2(l); ref1.M2(c); ref1.M2(ref i); //ref1.M2(ref l); CS1615 //ref1.M2(ref c); CS1615 // void M3(char x); // void M3(ref int x); Console.WriteLine(); ref1.M3(10); //ref1.M3(10L); CS1503 ref1.M3('c'); ref1.M3(i); //ref1.M3(l); CS1503 ref1.M3(c); ref1.M3(ref i); //ref1.M3(ref l); CS1615 //ref1.M3(ref c); CS1615 // void M4(out uint x); // void M4(ref int x); Console.WriteLine(); ref1.M4(10); //ref1.M4(10L); CS1620 ref1.M4('c'); ref1.M4(i); //ref1.M4(l); CS1620 ref1.M4(c); ref1.M4(ref i); //ref1.M4(ref l); CS1620 //ref1.M4(ref c); CS1620 // void M5(ref int x); // void M5(ref long x); Console.WriteLine(); //ref1.M5(10); CS0121 ref1.M5(10L); //ref1.M5('c'); CS0121 //ref1.M5(i); CS0121 ref1.M5(l); //ref1.M5(c); CS0121 ref1.M5(ref i); ref1.M5(ref l); //ref1.M5(ref c); CS1503 // void M6(ref char x); // void M6(ref long x); Console.WriteLine(); ref1.M6(10); ref1.M6(10L); //ref1.M6('c'); CS0121 ref1.M6(i); ref1.M6(l); //ref1.M6(c); CS0121 //ref1.M6(ref i); CS1503 ref1.M6(ref l); ref1.M6(ref c); // void M7(ref long x); // void M7(int x); Console.WriteLine(); ref1.M7(10); ref1.M7(10L); ref1.M7('c'); ref1.M7(i); ref1.M7(l); ref1.M7(c); //ref1.M7(ref i); CS1503 ref1.M7(ref l); //ref1.M7(ref c); CS1503 // void M8(ref long x); // void M8(char x); Console.WriteLine(); ref1.M8(10); ref1.M8(10L); ref1.M8('c'); ref1.M8(i); ref1.M8(l); ref1.M8(c); //ref1.M8(ref i); CS1503 ref1.M8(ref l); //ref1.M8(ref c); CS1503 // void M9(ref char x); // void M9(long x); Console.WriteLine(); ref1.M9(10); ref1.M9(10L); ref1.M9('c'); ref1.M9(i); ref1.M9(l); ref1.M9(c); //ref1.M9(ref i); CS1503 //ref1.M9(ref l); CS1503 ref1.M9(ref c); } } "; CompileAndVerify(source, expectedOutput: @"1 1 1 1 2 3 3 3 3 3 3 4 6 5 6 5 6 8 8 8 8 8 10 10 9 10 12 12 12 12 12 11 14 13 14 14 13 14 13 15 15 16 15 15 16 15 18 18 18 18 18 18 17"); } [Fact] public void RefOmittedComCall_OverloadResolution_SingleArgument_ErrorCases() { var source = @" using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { void M1(int x); void M1(ref int x); void M2(long x); void M2(ref int x); void M3(char x); void M3(ref int x); void M4(out uint x); void M4(ref int x); void M5(ref int x); void M5(ref long x); void M6(ref char x); void M6(ref long x); void M7(ref long x); void M7(int x); void M8(ref long x); void M8(char x); void M9(ref char x); void M9(long x); } public class Ref1Impl : IRef1 { public void M1(int x) { Console.WriteLine(1); } public void M1(ref int x) { Console.WriteLine(2); } public void M2(long x) { Console.WriteLine(3); } public void M2(ref int x) { Console.WriteLine(4); } public void M3(char x) { Console.WriteLine(5); } public void M3(ref int x) { Console.WriteLine(6); } public void M4(out uint x) { x = 0; Console.WriteLine(7); } public void M4(ref int x) { Console.WriteLine(8); } public void M5(ref int x) { Console.WriteLine(9); } public void M5(ref long x) { Console.WriteLine(10); } public void M6(ref char x) { Console.WriteLine(11); } public void M6(ref long x) { Console.WriteLine(12); } public void M7(ref long x) { Console.WriteLine(13); } public void M7(int x) { Console.WriteLine(14); } public void M8(ref long x) { Console.WriteLine(15); } public void M8(char x) { Console.WriteLine(16); } public void M9(ref char x) { Console.WriteLine(17); } public void M9(long x) { Console.WriteLine(18); } } class Test { public static void Main() { IRef1 ref1 = new Ref1Impl(); int i = 1; long l = 1; char c = 'c'; // void M1(int x); // void M1(ref int x); ref1.M1(10L); // CS1503 ref1.M1(l); // CS1503 ref1.M1(ref l); // CS1615 ref1.M1(ref c); // CS1615 // void M2(long x); // void M2(ref int x); Console.WriteLine(); ref1.M2(ref l); // CS1615 ref1.M2(ref c); // CS1615 // void M3(char x); // void M3(ref int x); Console.WriteLine(); ref1.M3(10L); // CS1503 ref1.M3(l); // CS1503 ref1.M3(ref l); // CS1615 ref1.M3(ref c); // CS1615 // void M4(out uint x); // void M4(ref int x); Console.WriteLine(); ref1.M4(10L); // CS1620 ref1.M4(l); // CS1620 ref1.M4(ref l); // CS1620 ref1.M4(ref c); // CS1620 // void M5(ref int x); // void M5(ref long x); Console.WriteLine(); ref1.M5(10); // CS0121 ref1.M5('c'); // CS0121 ref1.M5(i); // CS0121 ref1.M5(c); // CS0121 ref1.M5(ref c); // CS1503 // void M6(ref char x); // void M6(ref long x); Console.WriteLine(); ref1.M6('c'); // CS0121 ref1.M6(c); // CS0121 ref1.M6(ref i); // CS1503 // void M7(ref long x); // void M7(int x); Console.WriteLine(); ref1.M7(ref i); // CS1503 ref1.M7(ref c); // CS1503 // void M8(ref long x); // void M8(char x); Console.WriteLine(); ref1.M8(ref i); // CS1503 ref1.M8(ref c); // CS1503 // void M9(ref char x); // void M9(long x); Console.WriteLine(); ref1.M9(ref i); // CS1503 ref1.M9(ref l); // CS1503 } } "; CreateCompilation(source).VerifyDiagnostics( // (79,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M1(10L); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "10L").WithArguments("1", "long", "int"), // (80,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M1(l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (81,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (82,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (89,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (90,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (97,16): error CS1503: Argument 1: cannot convert from 'long' to 'char' // ref1.M3(10L); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "10L").WithArguments("1", "long", "char"), // (98,16): error CS1503: Argument 1: cannot convert from 'long' to 'char' // ref1.M3(l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "char"), // (99,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M3(ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (100,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M3(ref c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (107,16): error CS1620: Argument 1 must be passed with the 'out' keyword // ref1.M4(10L); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "10L").WithArguments("1", "out"), // (108,16): error CS1620: Argument 1 must be passed with the 'out' keyword // ref1.M4(l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "out"), // (109,20): error CS1620: Argument 1 must be passed with the 'out' keyword // ref1.M4(ref l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "out"), // (110,20): error CS1620: Argument 1 must be passed with the 'out' keyword // ref1.M4(ref c); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "c").WithArguments("1", "out"), // (117,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M5(ref int)' and 'IRef1.M5(ref long)' // ref1.M5(10); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M5").WithArguments("IRef1.M5(ref int)", "IRef1.M5(ref long)"), // (118,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M5(ref int)' and 'IRef1.M5(ref long)' // ref1.M5('c'); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M5").WithArguments("IRef1.M5(ref int)", "IRef1.M5(ref long)"), // (119,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M5(ref int)' and 'IRef1.M5(ref long)' // ref1.M5(i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M5").WithArguments("IRef1.M5(ref int)", "IRef1.M5(ref long)"), // (120,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M5(ref int)' and 'IRef1.M5(ref long)' // ref1.M5(c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M5").WithArguments("IRef1.M5(ref int)", "IRef1.M5(ref long)"), // (121,20): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref int' // ref1.M5(ref c); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref int"), // (128,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M6(ref char)' and 'IRef1.M6(ref long)' // ref1.M6('c'); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("IRef1.M6(ref char)", "IRef1.M6(ref long)"), // (129,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M6(ref char)' and 'IRef1.M6(ref long)' // ref1.M6(c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("IRef1.M6(ref char)", "IRef1.M6(ref long)"), // (130,20): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref char' // ref1.M6(ref i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref char"), // (137,20): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // ref1.M7(ref i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (138,20): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // ref1.M7(ref c); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (145,20): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // ref1.M8(ref i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (146,20): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // ref1.M8(ref c); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (153,20): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref char' // ref1.M9(ref i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref char"), // (154,20): error CS1503: Argument 1: cannot convert from 'ref long' to 'ref char' // ref1.M9(ref l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "ref long", "ref char")); } [Fact, WorkItem(546176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546176")] public void RefOmittedComCall_OverloadResolution_SingleArgument_IndexedProperties() { var source1 = @" .class interface public abstract import IA { .custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 ) .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 ) .property instance int32 P1(int32) { .get instance int32 IA::get_P1(int32) .set instance void IA::set_P1(int32, int32) } .property instance int32 P1(int32&) { .get instance int32 IA::get_P1(int32&) .set instance void IA::set_P1(int32&, int32) } .method public abstract virtual instance int32 get_P1(int32 i) { } .method public abstract virtual instance void set_P1(int32 i, int32 v) { } .method public abstract virtual instance int32 get_P1(int32& i) { } .method public abstract virtual instance void set_P1(int32& i, int32 v) { } .property instance int32 P2(int64) { .get instance int32 IA::get_P2(int64) .set instance void IA::set_P2(int64, int32) } .property instance int32 P2(int32&) { .get instance int32 IA::get_P2(int32&) .set instance void IA::set_P2(int32&, int32) } .method public abstract virtual instance int32 get_P2(int64 i) { } .method public abstract virtual instance void set_P2(int64 i, int32 v) { } .method public abstract virtual instance int32 get_P2(int32& i) { } .method public abstract virtual instance void set_P2(int32& i, int32 v) { } .property instance int32 P3(char) { .get instance int32 IA::get_P3(char) .set instance void IA::set_P3(char, int32) } .property instance int32 P3(int32&) { .get instance int32 IA::get_P3(int32&) .set instance void IA::set_P3(int32&, int32) } .method public abstract virtual instance int32 get_P3(char i) { } .method public abstract virtual instance void set_P3(char i, int32 v) { } .method public abstract virtual instance int32 get_P3(int32& i) { } .method public abstract virtual instance void set_P3(int32& i, int32 v) { } .property instance int32 P4(int64&) { .get instance int32 IA::get_P4(int64&) .set instance void IA::set_P4(int64&, int32) } .property instance int32 P4(int32&) { .get instance int32 IA::get_P4(int32&) .set instance void IA::set_P4(int32&, int32) } .method public abstract virtual instance int32 get_P4(int64& i) { } .method public abstract virtual instance void set_P4(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P4(int32& i) { } .method public abstract virtual instance void set_P4(int32& i, int32 v) { } .property instance int32 P5(int64&) { .get instance int32 IA::get_P5(int64&) .set instance void IA::set_P5(int64&, int32) } .property instance int32 P5(char&) { .get instance int32 IA::get_P5(char&) .set instance void IA::set_P5(char&, int32) } .method public abstract virtual instance int32 get_P5(int64& i) { } .method public abstract virtual instance void set_P5(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P5(char& i) { } .method public abstract virtual instance void set_P5(char& i, int32 v) { } .property instance int32 P6(int64&) { .get instance int32 IA::get_P6(int64&) .set instance void IA::set_P6(int64&, int32) } .property instance int32 P6(int32) { .get instance int32 IA::get_P6(int32) .set instance void IA::set_P6(int32, int32) } .method public abstract virtual instance int32 get_P6(int64& i) { } .method public abstract virtual instance void set_P6(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P6(int32 i) { } .method public abstract virtual instance void set_P6(int32 i, int32 v) { } .property instance int32 P7(int64&) { .get instance int32 IA::get_P7(int64&) .set instance void IA::set_P7(int64&, int32) } .property instance int32 P7(char) { .get instance int32 IA::get_P7(char) .set instance void IA::set_P7(char, int32) } .method public abstract virtual instance int32 get_P7(int64& i) { } .method public abstract virtual instance void set_P7(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P7(char i) { } .method public abstract virtual instance void set_P7(char i, int32 v) { } .property instance int32 P8(int64) { .get instance int32 IA::get_P8(int64) .set instance void IA::set_P8(int64, int32) } .property instance int32 P8(char&) { .get instance int32 IA::get_P8(char&) .set instance void IA::set_P8(char&, int32) } .method public abstract virtual instance int32 get_P8(int64 i) { } .method public abstract virtual instance void set_P8(int64 i, int32 v) { } .method public abstract virtual instance int32 get_P8(char& i) { } .method public abstract virtual instance void set_P8(char& i, int32 v) { } } .class public A implements IA { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .property instance int32 P1(int32) { .get instance int32 A::get_P1(int32) .set instance void A::set_P1(int32, int32) } .property instance int32 P1(int32&) { .get instance int32 A::get_P1(int32&) .set instance void A::set_P1(int32&, int32) } .method public virtual instance int32 get_P1(int32 i) { ldc.i4.1 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P1(int32 i, int32 v) { ldc.i4.2 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P1(int32& i) { ldc.i4.3 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P1(int32& i, int32 v) { ldc.i4.4 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P2(int64) { .get instance int32 A::get_P2(int64) .set instance void A::set_P2(int64, int32) } .property instance int32 P2(int32&) { .get instance int32 A::get_P2(int32&) .set instance void A::set_P2(int32&, int32) } .method public virtual instance int32 get_P2(int64 i) { ldc.i4.5 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P2(int64 i, int32 v) { ldc.i4.6 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P2(int32& i) { ldc.i4.7 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P2(int32& i, int32 v) { ldc.i4.8 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P3(char) { .get instance int32 A::get_P3(char) .set instance void A::set_P3(char, int32) } .property instance int32 P3(int32&) { .get instance int32 A::get_P3(int32&) .set instance void A::set_P3(int32&, int32) } .method public virtual instance int32 get_P3(char i) { ldc.i4.s 9 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P3(char i, int32 v) { ldc.i4.s 10 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P3(int32& i) { ldc.i4.s 11 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P3(int32& i, int32 v) { ldc.i4.s 12 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P4(int64&) { .get instance int32 A::get_P4(int64&) .set instance void A::set_P4(int64&, int32) } .property instance int32 P4(int32&) { .get instance int32 A::get_P4(int32&) .set instance void A::set_P4(int32&, int32) } .method public virtual instance int32 get_P4(int64& i) { ldc.i4.s 13 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P4(int64& i, int32 v) { ldc.i4.s 14 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P4(int32& i) { ldc.i4.s 15 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P4(int32& i, int32 v) { ldc.i4.s 16 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P5(int64&) { .get instance int32 A::get_P5(int64&) .set instance void A::set_P5(int64&, int32) } .property instance int32 P5(char&) { .get instance int32 A::get_P5(char&) .set instance void A::set_P5(char&, int32) } .method public virtual instance int32 get_P5(int64& i) { ldc.i4.s 17 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P5(int64& i, int32 v) { ldc.i4.s 18 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P5(char& i) { ldc.i4.s 19 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P5(char& i, int32 v) { ldc.i4.s 20 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P6(int64&) { .get instance int32 A::get_P6(int64&) .set instance void A::set_P6(int64&, int32) } .property instance int32 P6(int32) { .get instance int32 A::get_P6(int32) .set instance void A::set_P6(int32, int32) } .method public virtual instance int32 get_P6(int64& i) { ldc.i4.s 21 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P6(int64& i, int32 v) { ldc.i4.s 22 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P6(int32 i) { ldc.i4.s 23 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P6(int32 i, int32 v) { ldc.i4.s 24 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P7(int64&) { .get instance int32 A::get_P7(int64&) .set instance void A::set_P7(int64&, int32) } .property instance int32 P7(char) { .get instance int32 A::get_P7(char) .set instance void A::set_P7(char, int32) } .method public virtual instance int32 get_P7(int64& i) { ldc.i4.s 25 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P7(int64& i, int32 v) { ldc.i4.s 26 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P7(char i) { ldc.i4.s 27 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P7(char i, int32 v) { ldc.i4.s 28 call void [mscorlib]System.Console::WriteLine(int32) ret } .property instance int32 P8(int64) { .get instance int32 A::get_P8(int64) .set instance void A::set_P8(int64, int32) } .property instance int32 P8(char&) { .get instance int32 A::get_P8(char&) .set instance void A::set_P8(char&, int32) } .method public virtual instance int32 get_P8(int64 i) { ldc.i4.s 29 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P8(int64 i, int32 v) { ldc.i4.s 30 call void [mscorlib]System.Console::WriteLine(int32) ret } .method public virtual instance int32 get_P8(char& i) { ldc.i4.s 31 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P8(char& i, int32 v) { ldc.i4.s 32 call void [mscorlib]System.Console::WriteLine(int32) ret } } "; var source2 = @" using System; using System.Runtime.InteropServices; class Test { public static void Main() { IA a = new A(); int i = 1; long l = 1; char c = 'c'; int value; // int P1(int) { get; set; } // int P1(ref int) { get; set; } value = a.P1[10]; a.P1[10] = value; //value = a.P1[10L]; CS1503 //a.P1[10L] = value; CS1503 value = a.P1['c']; a.P1['c'] = value; value = a.P1[i]; a.P1[i] = value; //value = a.P1[l]; CS1503 //a.P1[l] = value; CS1503 value = a.P1[c]; a.P1[c] = value; value = a.P1[ref i]; a.P1[ref i] = value; //value = a.P1[ref l]; CS1615 //a.P1[ref l] = value; CS1615 //value = a.P1[ref c]; CS1615 //a.P1[ref c] = value; CS1615 // int P2(long) { get; set; } // int P2(ref int) { get; set; } Console.WriteLine(); value = a.P2[10]; a.P2[10] = value; value = a.P2[10L]; a.P2[10L] = value; value = a.P2['c']; a.P2['c'] = value; value = a.P2[i]; a.P2[i] = value; value = a.P2[l]; a.P2[l] = value; value = a.P2[c]; a.P2[c] = value; value = a.P2[ref i]; a.P2[ref i] = value; //value = a.P2[ref l]; CS1615 //a.P2[ref l] = value; CS1615 //value = a.P2[ref c]; CS1615 //a.P2[ref c] = value; CS1615 // int P3(char) { get; set; } // int P3(ref int) { get; set; } Console.WriteLine(); value = a.P3[10]; a.P3[10] = value; //value = a.P3[10L]; CS1503 //a.P3[10L] = value; CS1503 value = a.P3['c']; a.P3['c'] = value; value = a.P3[i]; a.P3[i] = value; //value = a.P3[l]; CS1503 //a.P3[l] = value; CS1503 value = a.P3[c]; a.P3[c] = value; value = a.P3[ref i]; a.P3[ref i] = value; //value = a.P3[ref l]; CS1615 //a.P3[ref l] = value; CS1615 //value = a.P3[ref c]; CS1615 //a.P3[ref c] = value; CS1615 // int P4(ref int) { get; set; } // int P4(ref long) { get; set; } Console.WriteLine(); //value = a.P4[10]; CS0121 //a.P4[10] = value; CS0121 value = a.P4[10L]; a.P4[10L] = value; //value = a.P4['c']; CS0121 //a.P4['c'] = value; CS0121 //value = a.P4[i]; CS0121 //a.P4[i] = value; CS0121 value = a.P4[l]; a.P4[l] = value; //value = a.P4[c]; CS0121 //a.P4[c] = value; CS0121 value = a.P4[ref i]; a.P4[ref i] = value; value = a.P4[ref l]; a.P4[ref l] = value; //value = a.P4[ref c]; CS1503 //a.P4[ref c] = value; CS1503 // int P5(ref char) { get; set; } // int P5(ref long) { get; set; } Console.WriteLine(); value = a.P5[10]; a.P5[10] = value; value = a.P5[10L]; a.P5[10L] = value; //value = a.P5['c']; CS0121 //a.P5['c'] = value; CS0121 value = a.P5[i]; a.P5[i] = value; value = a.P5[l]; a.P5[l] = value; //value = a.P5[c]; CS0121 //a.P5[c] = value; CS0121 //value = a.P5[ref i]; CS1503 //a.P5[ref i] = value; CS1503 value = a.P5[ref l]; a.P5[ref l] = value; value = a.P5[ref c]; a.P5[ref c] = value; // int P6(ref long) { get; set; } // int P6(int) { get; set; } Console.WriteLine(); value = a.P6[10]; a.P6[10] = value; value = a.P6[10L]; a.P6[10L] = value; value = a.P6['c']; a.P6['c'] = value; value = a.P6[i]; a.P6[i] = value; value = a.P6[l]; a.P6[l] = value; value = a.P6[c]; a.P6[c] = value; //value = a.P6[ref i]; CS1503 //a.P6[ref i] = value; CS1503 value = a.P6[ref l]; a.P6[ref l] = value; //value = a.P6[ref c]; CS1503 //a.P6[ref c] = value; CS1503 // int P7(ref long) { get; set; } // int P7(char) { get; set; } Console.WriteLine(); value = a.P7[10]; a.P7[10] = value; value = a.P7[10L]; a.P7[10L] = value; value = a.P7['c']; a.P7['c'] = value; value = a.P7[i]; a.P7[i] = value; value = a.P7[l]; a.P7[l] = value; value = a.P7[c]; a.P7[c] = value; //value = a.P7[ref i]; CS1503 //a.P7[ref i] = value; CS1503 value = a.P7[ref l]; a.P7[ref l] = value; //value = a.P7[ref c]; CS1503 //a.P7[ref c] = value; CS1503 // int P8(ref char) { get; set; } // int P8(long) { get; set; } Console.WriteLine(); value = a.P8[10]; a.P8[10] = value; value = a.P8[10L]; a.P8[10L] = value; value = a.P8['c']; a.P8['c'] = value; value = a.P8[i]; a.P8[i] = value; value = a.P8[l]; a.P8[l] = value; value = a.P8[c]; a.P8[c] = value; //value = a.P8[ref i]; CS1615 //a.P8[ref i] = value; CS1615 //value = a.P8[ref l]; CS1615 //a.P8[ref l] = value; CS1615 value = a.P8[ref c]; a.P8[ref c] = value; } } "; var expectedOutput = @"1 2 1 2 1 2 1 2 3 4 5 6 5 6 5 6 5 6 5 6 5 6 7 8 11 12 9 10 11 12 9 10 11 12 13 14 13 14 15 16 13 14 17 18 17 18 17 18 17 18 17 18 19 20 23 24 21 22 23 24 23 24 21 22 23 24 21 22 25 26 25 26 27 28 25 26 25 26 27 28 25 26 29 30 29 30 29 30 29 30 29 30 29 30 31 32"; var compilation = CreateCompilationWithILAndMscorlib40(source2, source1, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: expectedOutput); } [Fact, WorkItem(546176, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546176")] public void RefOmittedComCall_OverloadResolution_SingleArgument_IndexedProperties_ErrorCases() { var source1 = @" .class interface public abstract import IA { .custom instance void [mscorlib]System.Runtime.InteropServices.CoClassAttribute::.ctor(class [mscorlib]System.Type) = ( 01 00 01 41 00 00 ) .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 36 35 46 37 35 32 44 2D 45 39 43 34 2D 34 46 37 45 2D 42 30 44 30 2D 43 44 46 44 37 41 33 36 45 32 31 31 00 00 ) .property instance int32 P1(int32) { .get instance int32 IA::get_P1(int32) .set instance void IA::set_P1(int32, int32) } .property instance int32 P1(int32&) { .get instance int32 IA::get_P1(int32&) .set instance void IA::set_P1(int32&, int32) } .method public abstract virtual instance int32 get_P1(int32 i) { } .method public abstract virtual instance void set_P1(int32 i, int32 v) { } .method public abstract virtual instance int32 get_P1(int32& i) { } .method public abstract virtual instance void set_P1(int32& i, int32 v) { } .property instance int32 P2(int64) { .get instance int32 IA::get_P2(int64) .set instance void IA::set_P2(int64, int32) } .property instance int32 P2(int32&) { .get instance int32 IA::get_P2(int32&) .set instance void IA::set_P2(int32&, int32) } .method public abstract virtual instance int32 get_P2(int64 i) { } .method public abstract virtual instance void set_P2(int64 i, int32 v) { } .method public abstract virtual instance int32 get_P2(int32& i) { } .method public abstract virtual instance void set_P2(int32& i, int32 v) { } .property instance int32 P3(char) { .get instance int32 IA::get_P3(char) .set instance void IA::set_P3(char, int32) } .property instance int32 P3(int32&) { .get instance int32 IA::get_P3(int32&) .set instance void IA::set_P3(int32&, int32) } .method public abstract virtual instance int32 get_P3(char i) { } .method public abstract virtual instance void set_P3(char i, int32 v) { } .method public abstract virtual instance int32 get_P3(int32& i) { } .method public abstract virtual instance void set_P3(int32& i, int32 v) { } .property instance int32 P4(int64&) { .get instance int32 IA::get_P4(int64&) .set instance void IA::set_P4(int64&, int32) } .property instance int32 P4(int32&) { .get instance int32 IA::get_P4(int32&) .set instance void IA::set_P4(int32&, int32) } .method public abstract virtual instance int32 get_P4(int64& i) { } .method public abstract virtual instance void set_P4(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P4(int32& i) { } .method public abstract virtual instance void set_P4(int32& i, int32 v) { } .property instance int32 P5(int64&) { .get instance int32 IA::get_P5(int64&) .set instance void IA::set_P5(int64&, int32) } .property instance int32 P5(char&) { .get instance int32 IA::get_P5(char&) .set instance void IA::set_P5(char&, int32) } .method public abstract virtual instance int32 get_P5(int64& i) { } .method public abstract virtual instance void set_P5(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P5(char& i) { } .method public abstract virtual instance void set_P5(char& i, int32 v) { } .property instance int32 P6(int64&) { .get instance int32 IA::get_P6(int64&) .set instance void IA::set_P6(int64&, int32) } .property instance int32 P6(int32) { .get instance int32 IA::get_P6(int32) .set instance void IA::set_P6(int32, int32) } .method public abstract virtual instance int32 get_P6(int64& i) { } .method public abstract virtual instance void set_P6(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P6(int32 i) { } .method public abstract virtual instance void set_P6(int32 i, int32 v) { } .property instance int32 P7(int64&) { .get instance int32 IA::get_P7(int64&) .set instance void IA::set_P7(int64&, int32) } .property instance int32 P7(char) { .get instance int32 IA::get_P7(char) .set instance void IA::set_P7(char, int32) } .method public abstract virtual instance int32 get_P7(int64& i) { } .method public abstract virtual instance void set_P7(int64& i, int32 v) { } .method public abstract virtual instance int32 get_P7(char i) { } .method public abstract virtual instance void set_P7(char i, int32 v) { } .property instance int32 P8(int64) { .get instance int32 IA::get_P8(int64) .set instance void IA::set_P8(int64, int32) } .property instance int32 P8(char&) { .get instance int32 IA::get_P8(char&) .set instance void IA::set_P8(char&, int32) } .method public abstract virtual instance int32 get_P8(int64 i) { } .method public abstract virtual instance void set_P8(int64 i, int32 v) { } .method public abstract virtual instance int32 get_P8(char& i) { } .method public abstract virtual instance void set_P8(char& i, int32 v) { } } .class public A implements IA { .method public hidebysig specialname rtspecialname instance void .ctor() { ret } .property instance int32 P1(int32) { .get instance int32 A::get_P1(int32) .set instance void A::set_P1(int32, int32) } .property instance int32 P1(int32&) { .get instance int32 A::get_P1(int32&) .set instance void A::set_P1(int32&, int32) } .method public virtual instance int32 get_P1(int32 i) { ldc.i4.1 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P1(int32 i, int32 v) { ldc.i4.2 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P1(int32& i) { ldc.i4.3 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P1(int32& i, int32 v) { ldc.i4.4 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P2(int64) { .get instance int32 A::get_P2(int64) .set instance void A::set_P2(int64, int32) } .property instance int32 P2(int32&) { .get instance int32 A::get_P2(int32&) .set instance void A::set_P2(int32&, int32) } .method public virtual instance int32 get_P2(int64 i) { ldc.i4.5 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P2(int64 i, int32 v) { ldc.i4.6 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P2(int32& i) { ldc.i4.7 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P2(int32& i, int32 v) { ldc.i4.8 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P3(char) { .get instance int32 A::get_P3(char) .set instance void A::set_P3(char, int32) } .property instance int32 P3(int32&) { .get instance int32 A::get_P3(int32&) .set instance void A::set_P3(int32&, int32) } .method public virtual instance int32 get_P3(char i) { ldc.i4.s 9 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P3(char i, int32 v) { ldc.i4.s 10 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P3(int32& i) { ldc.i4.s 11 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P3(int32& i, int32 v) { ldc.i4.s 12 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P4(int64&) { .get instance int32 A::get_P4(int64&) .set instance void A::set_P4(int64&, int32) } .property instance int32 P4(int32&) { .get instance int32 A::get_P4(int32&) .set instance void A::set_P4(int32&, int32) } .method public virtual instance int32 get_P4(int64& i) { ldc.i4.s 13 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P4(int64& i, int32 v) { ldc.i4.s 14 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P4(int32& i) { ldc.i4.s 15 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P4(int32& i, int32 v) { ldc.i4.s 16 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P5(int64&) { .get instance int32 A::get_P5(int64&) .set instance void A::set_P5(int64&, int32) } .property instance int32 P5(char&) { .get instance int32 A::get_P5(char&) .set instance void A::set_P5(char&, int32) } .method public virtual instance int32 get_P5(int64& i) { ldc.i4.s 17 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P5(int64& i, int32 v) { ldc.i4.s 18 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P5(char& i) { ldc.i4.s 19 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P5(char& i, int32 v) { ldc.i4.s 20 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P6(int64&) { .get instance int32 A::get_P6(int64&) .set instance void A::set_P6(int64&, int32) } .property instance int32 P6(int32) { .get instance int32 A::get_P6(int32) .set instance void A::set_P6(int32, int32) } .method public virtual instance int32 get_P6(int64& i) { ldc.i4.s 21 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P6(int64& i, int32 v) { ldc.i4.s 22 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P6(int32 i) { ldc.i4.s 23 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P6(int32 i, int32 v) { ldc.i4.s 24 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P7(int64&) { .get instance int32 A::get_P7(int64&) .set instance void A::set_P7(int64&, int32) } .property instance int32 P7(char) { .get instance int32 A::get_P7(char) .set instance void A::set_P7(char, int32) } .method public virtual instance int32 get_P7(int64& i) { ldc.i4.s 25 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P7(int64& i, int32 v) { ldc.i4.s 26 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P7(char i) { ldc.i4.s 27 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P7(char i, int32 v) { ldc.i4.s 28 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .property instance int32 P8(int64) { .get instance int32 A::get_P8(int64) .set instance void A::set_P8(int64, int32) } .property instance int32 P8(char&) { .get instance int32 A::get_P8(char&) .set instance void A::set_P8(char&, int32) } .method public virtual instance int32 get_P8(int64 i) { ldc.i4.s 29 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P8(int64 i, int32 v) { ldc.i4.s 30 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance int32 get_P8(char& i) { ldc.i4.s 31 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } .method public virtual instance void set_P8(char& i, int32 v) { ldc.i4.s 32 call void [mscorlib]System.Console::WriteLine(int32) ldc.i4.0 ret } } "; var source2 = @" class Test { public static void Main() { IA a = new A(); int i = 1; long l = 1; char c = 'c'; int value; // int P1(int) { get; set; } // int P1(ref int) { get; set; } value = a.P1[10L]; // CS1503 a.P1[10L] = value; // CS1503 value = a.P1[l]; // CS1503 a.P1[l] = value; // CS1503 value = a.P1[ref l]; // CS1615 a.P1[ref l] = value; // CS1615 value = a.P1[ref c]; // CS1615 a.P1[ref c] = value; // CS1615 // int P2(long) { get; set; } // int P2(ref int) { get; set; } value = a.P2[ref l]; // CS1615 a.P2[ref l] = value; // CS1615 value = a.P2[ref c]; // CS1615 a.P2[ref c] = value; // CS1615 // int P3(char) { get; set; } // int P3(ref int) { get; set; } value = a.P3[10L]; // CS1503 a.P3[10L] = value; // CS1503 value = a.P3[l]; // CS1503 a.P3[l] = value; // CS1503 value = a.P3[ref l]; // CS1615 a.P3[ref l] = value; // CS1615 value = a.P3[ref c]; // CS1615 a.P3[ref c] = value; // CS1615 // int P4(ref int) { get; set; } // int P4(ref long) { get; set; } value = a.P4[10]; // CS0121 a.P4[10] = value; // CS0121 value = a.P4['c']; // CS0121 a.P4['c'] = value; // CS0121 value = a.P4[i]; // CS0121 a.P4[i] = value; // CS0121 value = a.P4[c]; // CS0121 a.P4[c] = value; // CS0121 value = a.P4[ref c]; // CS1503 a.P4[ref c] = value; // CS1503 // int P5(ref char) { get; set; } // int P5(ref long) { get; set; } value = a.P5['c']; // CS0121 a.P5['c'] = value; // CS0121 value = a.P5[c]; // CS0121 a.P5[c] = value; // CS0121 value = a.P5[ref i]; // CS1503 a.P5[ref i] = value; // CS1503 // int P6(ref long) { get; set; } // int P6(int) { get; set; } value = a.P6[ref i]; // CS1503 a.P6[ref i] = value; // CS1503 value = a.P6[ref c]; // CS1503 a.P6[ref c] = value; // CS1503 // int P7(ref long) { get; set; } // int P7(char) { get; set; } value = a.P7[ref i]; // CS1503 a.P7[ref i] = value; // CS1503 value = a.P7[ref c]; // CS1503 a.P7[ref c] = value; // CS1503 // int P8(ref char) { get; set; } // int P8(long) { get; set; } value = a.P8[ref i]; // CS1615 a.P8[ref i] = value; // CS1615 value = a.P8[ref l]; // CS1615 a.P8[ref l] = value; // CS1615 } } "; CreateCompilationWithILAndMscorlib40(source2, source1).VerifyDiagnostics( // (15,21): error CS1503: Argument 1: cannot convert from 'long' to 'int' // value = a.P1[10L]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "10L").WithArguments("1", "long", "int"), // (16,13): error CS1503: Argument 1: cannot convert from 'long' to 'int' // a.P1[10L] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "10L").WithArguments("1", "long", "int"), // (17,21): error CS1503: Argument 1: cannot convert from 'long' to 'int' // value = a.P1[l]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (18,13): error CS1503: Argument 1: cannot convert from 'long' to 'int' // a.P1[l] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (19,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P1[ref l]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (20,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P1[ref l] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (21,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P1[ref c]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (22,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P1[ref c] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (27,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P2[ref l]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (28,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P2[ref l] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (29,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P2[ref c]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (30,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P2[ref c] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (35,21): error CS1503: Argument 1: cannot convert from 'long' to 'char' // value = a.P3[10L]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "10L").WithArguments("1", "long", "char"), // (36,13): error CS1503: Argument 1: cannot convert from 'long' to 'char' // a.P3[10L] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "10L").WithArguments("1", "long", "char"), // (37,21): error CS1503: Argument 1: cannot convert from 'long' to 'char' // value = a.P3[l]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "char"), // (38,13): error CS1503: Argument 1: cannot convert from 'long' to 'char' // a.P3[l] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "char"), // (39,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P3[ref l]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (40,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P3[ref l] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (41,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P3[ref c]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (42,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P3[ref c] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (47,16): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // value = a.P4[10]; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4[10]").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (58,8): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // a.P4[10] = value; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4[10]").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (49,16): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // value = a.P4['c']; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4['c']").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (50,8): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // a.P4['c'] = value; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4['c']").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (51,16): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // value = a.P4[i]; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4[i]").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (52,8): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // a.P4[i] = value; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4[i]").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (53,16): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // value = a.P4[c]; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4[c]").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (54,8): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P4[ref long]' and 'IA.P4[ref int]' // a.P4[c] = value; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P4[c]").WithArguments("IA.P4[ref long]", "IA.P4[ref int]"), // (55,25): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // value = a.P4[ref c]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (56,17): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // a.P4[ref c] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (61,16): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P5[ref long]' and 'IA.P5[ref char]' // value = a.P5['c']; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P5['c']").WithArguments("IA.P5[ref long]", "IA.P5[ref char]"), // (62,8): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P5[ref long]' and 'IA.P5[ref char]' // a.P5['c'] = value; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P5['c']").WithArguments("IA.P5[ref long]", "IA.P5[ref char]"), // (63,16): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P5[ref long]' and 'IA.P5[ref char]' // value = a.P5[c]; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P5[c]").WithArguments("IA.P5[ref long]", "IA.P5[ref char]"), // (64,8): error CS0121: The call is ambiguous between the following methods or properties: 'IA.P5[ref long]' and 'IA.P5[ref char]' // a.P5[c] = value; // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "a.P5[c]").WithArguments("IA.P5[ref long]", "IA.P5[ref char]"), // (65,25): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // value = a.P5[ref i]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (66,17): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // a.P5[ref i] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (71,25): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // value = a.P6[ref i]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (72,17): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // a.P6[ref i] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (73,25): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // value = a.P6[ref c]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (74,17): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // a.P6[ref c] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (79,25): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // value = a.P7[ref i]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (80,17): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // a.P7[ref i] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (81,25): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // value = a.P7[ref c]; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (82,17): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref long' // a.P7[ref c] = value; // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref long"), // (87,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P8[ref i]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (88,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P8[ref i] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (89,25): error CS1615: Argument 1 should not be passed with the 'ref' keyword // value = a.P8[ref l]; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (90,17): error CS1615: Argument 1 should not be passed with the 'ref' keyword // a.P8[ref l] = value; // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref")); } [Fact] public void RefOmittedComCall_OverloadResolution_MultipleArguments() { var source = @" using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { void M1(int x, long y); void M1(ref int x, int y); void M2(int x, char y); void M2(ref int x, int y); void M3(ref int x, char y); void M3(ref long x, int y); void M4(ref int x, long y); void M4(ref int x, ref int y); void M5(ref int x, char y); void M5(ref long x, int y); void M6(ref int x, int y); void M6(ref long x, int y); void M7(ref int x, long y); void M7(ref long x, ref int y); void M8(long x, ref int y); void M8(ref long x, int y); void M9(ref long x, ref int y); void M9(ref int x, ref long y); } public class Ref1Impl : IRef1 { public void M1(int x, long y) { Console.WriteLine(1); } public void M1(ref int x, int y) { Console.WriteLine(2); } public void M2(int x, char y) { Console.WriteLine(3); } public void M2(ref int x, int y) { Console.WriteLine(4); } public void M3(ref int x, char y) { Console.WriteLine(5); } public void M3(ref long x, int y) { Console.WriteLine(6); } public void M4(ref int x, long y) { Console.WriteLine(7); } public void M4(ref int x, ref int y) { Console.WriteLine(8); } public void M5(ref int x, char y) { Console.WriteLine(9); } public void M5(ref long x, int y) { Console.WriteLine(10); } public void M6(ref int x, int y) { Console.WriteLine(11); } public void M6(ref long x, int y) { Console.WriteLine(12); } public void M7(ref int x, long y) { Console.WriteLine(13); } public void M7(ref long x, ref int y) { Console.WriteLine(14); } public void M8(long x, ref int y) { Console.WriteLine(15); } public void M8(ref long x, int y) { Console.WriteLine(16); } public void M9(ref long x, ref int y) { Console.WriteLine(17); } public void M9(ref int x, ref long y) { Console.WriteLine(18); } } class Test { public static void Main() { IRef1 ref1 = new Ref1Impl(); int i = 1; long l = 1; char c = 'c'; // void M1(int x, long y); // void M1(ref int x, int y); ref1.M1(i, i); ref1.M1(i, l); ref1.M1(i, c); //ref1.M1(l, i); CS1503 //ref1.M1(l, l); CS1503 //ref1.M1(l, c); CS1503 ref1.M1(c, i); ref1.M1(c, l); ref1.M1(c, c); ref1.M1(ref i, i); //ref1.M1(ref i, l); CS1615 ref1.M1(ref i, c); //ref1.M1(ref l, i); CS1615 //ref1.M1(ref l, l); CS1615 //ref1.M1(ref l, c); CS1615 //ref1.M1(ref c, i); CS1615 //ref1.M1(ref c, l); CS1615 //ref1.M1(ref c, c); CS1615 // void M2(int x, char y); // void M2(ref int x, int y); Console.WriteLine(); ref1.M2(i, i); //ref1.M2(i, l); CS1503 ref1.M2(i, c); //ref1.M2(l, i); CS1503, CS1503 //ref1.M2(l, l); CS1503, CS1503 //ref1.M2(l, c); CS1503 ref1.M2(c, i); //ref1.M2(c, l); CS1503 ref1.M2(c, c); ref1.M2(ref i, i); //ref1.M2(ref i, l); CS1615, CS1503 ref1.M2(ref i, c); //ref1.M2(ref l, i); CS1615, CS1503 //ref1.M2(ref l, l); CS1615, CS1503 //ref1.M2(ref l, c); CS1615 //ref1.M2(ref c, i); CS1615, CS1503 //ref1.M2(ref c, l); CS1615, CS1503 //ref1.M2(ref c, c); CS1615 // void M3(ref int x, char y); // void M3(ref long x, int y); Console.WriteLine(); ref1.M3(i, i); //ref1.M3(i, l); CS1503 ref1.M3(i, c); ref1.M3(l, i); //ref1.M3(l, l); CS1620, CS1503 ref1.M3(l, c); ref1.M3(c, i); //ref1.M3(c, l); CS1503 ref1.M3(c, c); //ref1.M3(ref i, i); CS1503 //ref1.M3(ref i, l); CS1503 ref1.M3(ref i, c); ref1.M3(ref l, i); //ref1.M3(ref l, l); CS1503, CS1503 ref1.M3(ref l, c); //ref1.M3(ref c, i); CS1503, CS1503 //ref1.M3(ref c, l); CS1503, CS1503 //ref1.M3(ref c, c); CS1503 // void M4(ref int x, long y); // void M4(ref int x, ref int y); Console.WriteLine(); //ref1.M4(i, i); CS0121 ref1.M4(i, l); //ref1.M4(i, c); CS0121 //ref1.M4(l, i); CS1620 //ref1.M4(l, l); CS1620 //ref1.M4(l, c); CS1620 //ref1.M4(c, i); CS0121 ref1.M4(c, l); //ref1.M4(c, c); CS0121 ref1.M4(i, ref i); //ref1.M4(l, ref i); CS1620, CS1615 ref1.M4(c, ref i); //ref1.M4(i, ref l); CS1615 //ref1.M4(l, ref l); CS1620 //ref1.M4(c, ref l); CS1615 ref1.M4(ref i, i); ref1.M4(ref i, l); ref1.M4(ref i, c); ref1.M4(ref i, ref i); // void M5(ref int x, char y); // void M5(ref long x, int y); Console.WriteLine(); ref1.M5(i, i); //ref1.M5(i, l); CS1503 ref1.M5(i, c); ref1.M5(l, i); //ref1.M5(l, l); CS1620, CS1503 ref1.M5(l, c); ref1.M5(c, i); //ref1.M5(c, l); CS1503 ref1.M5(c, c); //ref1.M5(ref i, i); CS1503 //ref1.M5(ref i, l); CS1503 ref1.M5(ref i, c); ref1.M5(ref l, i); //ref1.M5(ref l, l); CS1503 ref1.M5(ref l, c); // void M6(ref int x, int y); // void M6(ref long x, int y); Console.WriteLine(); //ref1.M6(i, i); CS0121 //ref1.M6(i, l); CS1503 //ref1.M6(i, c); CS0121 ref1.M6(l, i); //ref1.M6(l, l); CS1620, CS1503 ref1.M6(l, c); //ref1.M6(c, i); CS0121 //ref1.M6(c, l); CS1503 //ref1.M6(c, c); CS0121 ref1.M6(ref i, i); //ref1.M6(ref i, l); CS1503 ref1.M6(ref i, c); ref1.M6(ref l, i); //ref1.M6(ref l, l); CS1503, CS1503 ref1.M6(ref l, c); // void M7(ref int x, long y); // void M7(ref long x, ref int y); Console.WriteLine(); //ref1.M7(i, i); CS0121 ref1.M7(i, l); //ref1.M7(i, c); CS0121 ref1.M7(l, i); //ref1.M7(l, l); CS1620 ref1.M7(l, c); //ref1.M7(c, i); CS0121 ref1.M7(c, l); //ref1.M7(c, c); CS0121 ref1.M7(i, ref i); ref1.M7(l, ref i); ref1.M7(c, ref i); //ref1.M7(i, ref l); CS1615 //ref1.M7(l, ref l); CS1620, CS1615 //ref1.M7(c, ref l); CS1615 ref1.M7(ref i, i); ref1.M7(ref i, l); ref1.M7(ref i, c); //ref1.M7(ref i, ref i); CS1615 // void M8(long x, ref int y); // void M8(ref long x, int y); Console.WriteLine(); ref1.M8(i, i); //ref1.M8(i, l); CS1620 //ref1.M8(i, c); CS0121 //ref1.M8(l, i); CS0121 //ref1.M8(l, l); CS1620 ref1.M8(l, c); ref1.M8(c, i); //ref1.M8(c, l); CS1620 //ref1.M8(c, c); CS0121 ref1.M8(i, ref i); ref1.M8(l, ref i); ref1.M8(c, ref i); //ref1.M8(i, ref l); CS1503 //ref1.M8(l, ref l); CS1503 //ref1.M8(c, ref l); CS1503 //ref1.M8(ref i, i); CS1615 //ref1.M8(ref i, l); CS1615, CS1620 //ref1.M8(ref i, c); CS1615 ref1.M8(ref l, i); //ref1.M8(ref l, l); CS1615, CS1620 ref1.M8(ref l, c); //ref1.M8(ref i, ref i); CS1615 //ref1.M8(ref i, ref l); CS1615, CS1503 //ref1.M8(ref l, ref i); CS1615 //ref1.M8(ref l, ref l); CS1615, CS1503 // void M9(ref long x, ref int y); // void M9(ref int x, ref long y); Console.WriteLine(); //ref1.M9(i, i); CS0121 ref1.M9(i, l); //ref1.M9(i, c); CS0121 ref1.M9(l, i); //ref1.M9(l, l); CS1620 ref1.M9(l, c); //ref1.M9(c, i); CS0121 ref1.M9(c, l); //ref1.M9(c, c); CS0121 ref1.M9(i, ref i); ref1.M9(l, ref i); ref1.M9(c, ref i); ref1.M9(i, ref l); //ref1.M9(l, ref l); CS1503 ref1.M9(c, ref l); ref1.M9(ref i, i); ref1.M9(ref i, l); ref1.M9(ref i, c); ref1.M9(ref l, i); //ref1.M9(ref l, l); CS1620 ref1.M9(ref l, c); //ref1.M9(ref i, ref i); CS1503 ref1.M9(ref i, ref l); ref1.M9(ref l, ref i); //ref1.M9(ref l, ref l); CS1503 } } "; CompileAndVerify(source, expectedOutput: @"1 1 1 1 1 1 2 2 4 3 4 3 4 4 6 5 6 6 6 5 5 6 6 7 7 8 8 7 7 7 8 10 9 10 10 10 9 9 10 10 12 12 11 11 12 12 13 14 14 13 14 14 14 13 13 13 16 15 16 15 15 15 16 16 18 17 17 18 17 17 17 18 18 18 18 18 17 17 18 17"); } [Fact] public void RefOmittedComCall_OverloadResolution_MultipleArguments_ErrorCases() { var source = @" using System; using System.Runtime.InteropServices; [ComImport] [Guid(""A88A175D-2448-447A-B786-64682CBEF156"")] public interface IRef1 { void M1(int x, long y); void M1(ref int x, int y); void M2(int x, char y); void M2(ref int x, int y); void M3(ref int x, char y); void M3(ref long x, int y); void M4(ref int x, long y); void M4(ref int x, ref int y); void M5(ref int x, char y); void M5(ref long x, int y); void M6(ref int x, int y); void M6(ref long x, int y); void M7(ref int x, long y); void M7(ref long x, ref int y); void M8(long x, ref int y); void M8(ref long x, int y); void M9(ref long x, ref int y); void M9(ref int x, ref long y); } public class Ref1Impl : IRef1 { public void M1(int x, long y) { Console.WriteLine(1); } public void M1(ref int x, int y) { Console.WriteLine(2); } public void M2(int x, char y) { Console.WriteLine(3); } public void M2(ref int x, int y) { Console.WriteLine(4); } public void M3(ref int x, char y) { Console.WriteLine(5); } public void M3(ref long x, int y) { Console.WriteLine(6); } public void M4(ref int x, long y) { Console.WriteLine(7); } public void M4(ref int x, ref int y) { Console.WriteLine(8); } public void M5(ref int x, char y) { Console.WriteLine(9); } public void M5(ref long x, int y) { Console.WriteLine(10); } public void M6(ref int x, int y) { Console.WriteLine(11); } public void M6(ref long x, int y) { Console.WriteLine(12); } public void M7(ref int x, long y) { Console.WriteLine(13); } public void M7(ref long x, ref int y) { Console.WriteLine(14); } public void M8(long x, ref int y) { Console.WriteLine(15); } public void M8(ref long x, int y) { Console.WriteLine(16); } public void M9(ref long x, ref int y) { Console.WriteLine(17); } public void M9(ref int x, ref long y) { Console.WriteLine(18); } } class Test { public static void Main() { IRef1 ref1 = new Ref1Impl(); int i = 1; long l = 1; char c = 'c'; // void M1(int x, long y); // void M1(ref int x, int y); ref1.M1(l, i); // CS1503 ref1.M1(l, l); // CS1503 ref1.M1(l, c); // CS1503 ref1.M1(ref i, l); // CS1615 ref1.M1(ref l, i); // CS1615 ref1.M1(ref l, l); // CS1615 ref1.M1(ref l, c); // CS1615 ref1.M1(ref c, i); // CS1615 ref1.M1(ref c, l); // CS1615 ref1.M1(ref c, c); // CS1615 // void M2(int x, char y); // void M2(ref int x, int y); Console.WriteLine(); ref1.M2(i, l); // CS1503 ref1.M2(l, i); // CS1503, CS1503 ref1.M2(l, l); // CS1503, CS1503 ref1.M2(l, c); // CS1503 ref1.M2(c, l); // CS1503 ref1.M2(ref i, l); // CS1615, CS1503 ref1.M2(ref l, i); // CS1615, CS1503 ref1.M2(ref l, l); // CS1615, CS1503 ref1.M2(ref l, c); // CS1615 ref1.M2(ref c, i); // CS1615, CS1503 ref1.M2(ref c, l); // CS1615, CS1503 ref1.M2(ref c, c); // CS1615 // void M3(ref int x, char y); // void M3(ref long x, int y); Console.WriteLine(); ref1.M3(i, l); // CS1503 ref1.M3(l, l); // CS1620, CS1503 ref1.M3(c, l); // CS1503 ref1.M3(ref i, i); // CS1503 ref1.M3(ref i, l); // CS1503 ref1.M3(ref l, l); // CS1503, CS1503 ref1.M3(ref c, i); // CS1503, CS1503 ref1.M3(ref c, l); // CS1503, CS1503 ref1.M3(ref c, c); // CS1503 // void M4(ref int x, long y); // void M4(ref int x, ref int y); Console.WriteLine(); ref1.M4(i, i); // CS0121 ref1.M4(i, c); // CS0121 ref1.M4(l, i); // CS1620 ref1.M4(l, l); // CS1620 ref1.M4(l, c); // CS1620 ref1.M4(c, i); // CS0121 ref1.M4(c, c); // CS0121 ref1.M4(l, ref i); // CS1620, CS1615 ref1.M4(i, ref l); // CS1615 ref1.M4(l, ref l); // CS1620 ref1.M4(c, ref l); // CS1615 // void M5(ref int x, char y); // void M5(ref long x, int y); Console.WriteLine(); ref1.M5(i, l); // CS1503 ref1.M5(l, l); // CS1620, CS1503 ref1.M5(c, l); // CS1503 ref1.M5(ref i, i); // CS1503 ref1.M5(ref i, l); // CS1503 ref1.M5(ref l, l); // CS1503 // void M6(ref int x, int y); // void M6(ref long x, int y); Console.WriteLine(); ref1.M6(i, i); // CS0121 ref1.M6(i, l); // CS1503 ref1.M6(i, c); // CS0121 ref1.M6(l, l); // CS1620, CS1503 ref1.M6(c, i); // CS0121 ref1.M6(c, l); // CS1503 ref1.M6(c, c); // CS0121 ref1.M6(ref i, l); // CS1503 ref1.M6(ref l, l); // CS1503, CS1503 // void M7(ref int x, long y); // void M7(ref long x, ref int y); Console.WriteLine(); ref1.M7(i, i); // CS0121 ref1.M7(i, c); // CS0121 ref1.M7(l, l); // CS1620 ref1.M7(c, i); // CS0121 ref1.M7(c, c); // CS0121 ref1.M7(i, ref l); // CS1615 ref1.M7(l, ref l); // CS1620, CS1615 ref1.M7(c, ref l); // CS1615 ref1.M7(ref i, ref i); // CS1615 // void M8(long x, ref int y); // void M8(ref long x, int y); Console.WriteLine(); ref1.M8(i, l); // CS1620 ref1.M8(i, c); // CS0121 ref1.M8(l, i); // CS0121 ref1.M8(l, l); // CS1620 ref1.M8(c, l); // CS1620 ref1.M8(c, c); // CS0121 ref1.M8(i, ref l); // CS1503 ref1.M8(l, ref l); // CS1503 ref1.M8(c, ref l); // CS1503 ref1.M8(ref i, i); // CS1615 ref1.M8(ref i, l); // CS1615, CS1620 ref1.M8(ref i, c); // CS1615 ref1.M8(ref l, l); // CS1615, CS1620 ref1.M8(ref i, ref i); // CS1615 ref1.M8(ref i, ref l); // CS1615, CS1503 ref1.M8(ref l, ref i); // CS1615 ref1.M8(ref l, ref l); // CS1615, CS1503 // void M9(ref long x, ref int y); // void M9(ref int x, ref long y); Console.WriteLine(); ref1.M9(i, i); // CS0121 ref1.M9(i, c); // CS0121 ref1.M9(l, l); // CS1620 ref1.M9(c, i); // CS0121 ref1.M9(c, c); // CS0121 ref1.M9(l, ref l); // CS1503 ref1.M9(ref l, l); // CS1620 ref1.M9(ref i, ref i); // CS1503 ref1.M9(ref l, ref l); // CS1503 } } "; CreateCompilation(source).VerifyDiagnostics( // (80,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M1(l, i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (81,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M1(l, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (82,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M1(l, c); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (83,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref i, l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (84,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref l, i); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (85,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref l, l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (86,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref l, c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (87,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref c, i); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (88,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref c, l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (89,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M1(ref c, c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (96,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M2(i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (97,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M2(l, i); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (97,19): error CS1503: Argument 2: cannot convert from 'int' to 'char' // ref1.M2(l, i); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("2", "int", "char"), // (98,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M2(l, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (98,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M2(l, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (99,16): error CS1503: Argument 1: cannot convert from 'long' to 'int' // ref1.M2(l, c); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "long", "int"), // (100,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M2(c, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (101,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref i, l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (101,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M2(ref i, l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (102,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref l, i); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (102,23): error CS1503: Argument 2: cannot convert from 'int' to 'char' // ref1.M2(ref l, i); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("2", "int", "char"), // (103,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref l, l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (103,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M2(ref l, l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (104,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref l, c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (105,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref c, i); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (105,23): error CS1503: Argument 2: cannot convert from 'int' to 'char' // ref1.M2(ref c, i); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("2", "int", "char"), // (106,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref c, l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (106,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M2(ref c, l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (107,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M2(ref c, c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "c").WithArguments("1", "ref"), // (114,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M3(i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (115,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M3(l, l); // CS1620, CS1503 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (115,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M3(l, l); // CS1620, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (116,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M3(c, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (117,23): error CS1503: Argument 2: cannot convert from 'int' to 'char' // ref1.M3(ref i, i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("2", "int", "char"), // (118,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M3(ref i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (119,20): error CS1503: Argument 1: cannot convert from 'ref long' to 'ref int' // ref1.M3(ref l, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "ref long", "ref int"), // (119,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M3(ref l, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (120,20): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref int' // ref1.M3(ref c, i); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref int"), // (120,23): error CS1503: Argument 2: cannot convert from 'int' to 'char' // ref1.M3(ref c, i); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("2", "int", "char"), // (121,20): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref int' // ref1.M3(ref c, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref int"), // (121,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M3(ref c, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (122,20): error CS1503: Argument 1: cannot convert from 'ref char' to 'ref int' // ref1.M3(ref c, c); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "c").WithArguments("1", "ref char", "ref int"), // (129,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M4(ref int, long)' and 'IRef1.M4(ref int, ref int)' // ref1.M4(i, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M4").WithArguments("IRef1.M4(ref int, long)", "IRef1.M4(ref int, ref int)"), // (130,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M4(ref int, long)' and 'IRef1.M4(ref int, ref int)' // ref1.M4(i, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M4").WithArguments("IRef1.M4(ref int, long)", "IRef1.M4(ref int, ref int)"), // (131,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M4(l, i); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (132,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M4(l, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (133,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M4(l, c); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (134,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M4(ref int, long)' and 'IRef1.M4(ref int, ref int)' // ref1.M4(c, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M4").WithArguments("IRef1.M4(ref int, long)", "IRef1.M4(ref int, ref int)"), // (135,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M4(ref int, long)' and 'IRef1.M4(ref int, ref int)' // ref1.M4(c, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M4").WithArguments("IRef1.M4(ref int, long)", "IRef1.M4(ref int, ref int)"), // (136,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M4(l, ref i); // CS1620, CS1615 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (136,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M4(l, ref i); // CS1620, CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("2", "ref"), // (137,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M4(i, ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("2", "ref"), // (138,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M4(l, ref l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (138,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M4(l, ref l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("2", "ref"), // (139,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M4(c, ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("2", "ref"), // (146,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M5(i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (147,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M5(l, l); // CS1620, CS1503 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (147,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M5(l, l); // CS1620, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (148,19): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M5(c, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (149,23): error CS1503: Argument 2: cannot convert from 'int' to 'char' // ref1.M5(ref i, i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("2", "int", "char"), // (150,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M5(ref i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (151,20): error CS1503: Argument 1: cannot convert from 'ref long' to 'ref int' // ref1.M5(ref l, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "ref long", "ref int"), // (151,23): error CS1503: Argument 2: cannot convert from 'long' to 'char' // ref1.M5(ref l, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "char"), // (158,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M6(ref int, int)' and 'IRef1.M6(ref long, int)' // ref1.M6(i, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("IRef1.M6(ref int, int)", "IRef1.M6(ref long, int)"), // (159,19): error CS1503: Argument 2: cannot convert from 'long' to 'int' // ref1.M6(i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "int"), // (160,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M6(ref int, int)' and 'IRef1.M6(ref long, int)' // ref1.M6(i, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("IRef1.M6(ref int, int)", "IRef1.M6(ref long, int)"), // (161,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M6(l, l); // CS1620, CS1503 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (161,19): error CS1503: Argument 2: cannot convert from 'long' to 'int' // ref1.M6(l, l); // CS1620, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "int"), // (162,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M6(ref int, int)' and 'IRef1.M6(ref long, int)' // ref1.M6(c, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("IRef1.M6(ref int, int)", "IRef1.M6(ref long, int)"), // (163,19): error CS1503: Argument 2: cannot convert from 'long' to 'int' // ref1.M6(c, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "int"), // (164,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M6(ref int, int)' and 'IRef1.M6(ref long, int)' // ref1.M6(c, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M6").WithArguments("IRef1.M6(ref int, int)", "IRef1.M6(ref long, int)"), // (165,23): error CS1503: Argument 2: cannot convert from 'long' to 'int' // ref1.M6(ref i, l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "int"), // (166,20): error CS1503: Argument 1: cannot convert from 'ref long' to 'ref int' // ref1.M6(ref l, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("1", "ref long", "ref int"), // (166,23): error CS1503: Argument 2: cannot convert from 'long' to 'int' // ref1.M6(ref l, l); // CS1503, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "long", "int"), // (173,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M7(ref int, long)' and 'IRef1.M7(ref long, ref int)' // ref1.M7(i, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M7").WithArguments("IRef1.M7(ref int, long)", "IRef1.M7(ref long, ref int)"), // (174,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M7(ref int, long)' and 'IRef1.M7(ref long, ref int)' // ref1.M7(i, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M7").WithArguments("IRef1.M7(ref int, long)", "IRef1.M7(ref long, ref int)"), // (175,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M7(l, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (176,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M7(ref int, long)' and 'IRef1.M7(ref long, ref int)' // ref1.M7(c, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M7").WithArguments("IRef1.M7(ref int, long)", "IRef1.M7(ref long, ref int)"), // (177,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M7(ref int, long)' and 'IRef1.M7(ref long, ref int)' // ref1.M7(c, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M7").WithArguments("IRef1.M7(ref int, long)", "IRef1.M7(ref long, ref int)"), // (178,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M7(i, ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("2", "ref"), // (179,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // ref1.M7(l, ref l); // CS1620, CS1615 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("1", "ref"), // (179,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M7(l, ref l); // CS1620, CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("2", "ref"), // (180,23): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M7(c, ref l); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("2", "ref"), // (181,27): error CS1615: Argument 2 should not be passed with the 'ref' keyword // ref1.M7(ref i, ref i); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("2", "ref"), // (188,19): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M8(i, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (189,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M8(long, ref int)' and 'IRef1.M8(ref long, int)' // ref1.M8(i, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M8").WithArguments("IRef1.M8(long, ref int)", "IRef1.M8(ref long, int)"), // (190,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M8(long, ref int)' and 'IRef1.M8(ref long, int)' // ref1.M8(l, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M8").WithArguments("IRef1.M8(long, ref int)", "IRef1.M8(ref long, int)"), // (191,19): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M8(l, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (192,19): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M8(c, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (193,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M8(long, ref int)' and 'IRef1.M8(ref long, int)' // ref1.M8(c, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M8").WithArguments("IRef1.M8(long, ref int)", "IRef1.M8(ref long, int)"), // (194,23): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M8(i, ref l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int"), // (195,23): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M8(l, ref l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int"), // (196,23): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M8(c, ref l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int"), // (197,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref i, i); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (198,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref i, l); // CS1615, CS1620 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (198,23): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M8(ref i, l); // CS1615, CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (199,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref i, c); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (200,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref l, l); // CS1615, CS1620 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (200,23): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M8(ref l, l); // CS1615, CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (201,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref i, ref i); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (202,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref i, ref l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "i").WithArguments("1", "ref"), // (202,27): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M8(ref i, ref l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int"), // (203,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref l, ref i); // CS1615 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (204,20): error CS1615: Argument 1 should not be passed with the 'ref' keyword // ref1.M8(ref l, ref l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgExtraRef, "l").WithArguments("1", "ref"), // (204,27): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M8(ref l, ref l); // CS1615, CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int"), // (211,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M9(ref long, ref int)' and 'IRef1.M9(ref int, ref long)' // ref1.M9(i, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M9").WithArguments("IRef1.M9(ref long, ref int)", "IRef1.M9(ref int, ref long)"), // (212,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M9(ref long, ref int)' and 'IRef1.M9(ref int, ref long)' // ref1.M9(i, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M9").WithArguments("IRef1.M9(ref long, ref int)", "IRef1.M9(ref int, ref long)"), // (213,19): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M9(l, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (214,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M9(ref long, ref int)' and 'IRef1.M9(ref int, ref long)' // ref1.M9(c, i); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M9").WithArguments("IRef1.M9(ref long, ref int)", "IRef1.M9(ref int, ref long)"), // (215,8): error CS0121: The call is ambiguous between the following methods or properties: 'IRef1.M9(ref long, ref int)' and 'IRef1.M9(ref int, ref long)' // ref1.M9(c, c); // CS0121 Diagnostic(ErrorCode.ERR_AmbigCall, "M9").WithArguments("IRef1.M9(ref long, ref int)", "IRef1.M9(ref int, ref long)"), // (216,23): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M9(l, ref l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int"), // (217,23): error CS1620: Argument 2 must be passed with the 'ref' keyword // ref1.M9(ref l, l); // CS1620 Diagnostic(ErrorCode.ERR_BadArgRef, "l").WithArguments("2", "ref"), // (218,20): error CS1503: Argument 1: cannot convert from 'ref int' to 'ref long' // ref1.M9(ref i, ref i); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "i").WithArguments("1", "ref int", "ref long"), // (219,27): error CS1503: Argument 2: cannot convert from 'ref long' to 'ref int' // ref1.M9(ref l, ref l); // CS1503 Diagnostic(ErrorCode.ERR_BadArgType, "l").WithArguments("2", "ref long", "ref int")); } [Fact] public void FailedToConvertToParameterArrayElementType() { var source = @" class C { static void Main() { M1(1, null); M1(null, 1); M2(""a"", null); M2(null, ""a""); M3(1, null); M3(null, 1); M3(""a"", null); M3(null, ""a""); M1(1, ""A""); M2(1, ""A""); M3<int>(1, ""A""); M3<string>(1, ""A""); } static void M1(params int[] a) { } static void M2(params string[] a) { } static void M3<T>(params T[] a) { } } "; CreateCompilation(source).VerifyDiagnostics( // (6,15): error CS1503: Argument 2: cannot convert from '<null>' to 'int' // M1(1, null); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("2", "<null>", "int"), // (7,12): error CS1503: Argument 1: cannot convert from '<null>' to 'int' // M1(null, 1); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "int"), // (12,15): error CS1503: Argument 2: cannot convert from '<null>' to 'int' // M3(1, null); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("2", "<null>", "int"), // (13,12): error CS1503: Argument 1: cannot convert from '<null>' to 'int' // M3(null, 1); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "int"), // (18,15): error CS1503: Argument 2: cannot convert from 'string' to 'int' // M1(1, "A"); Diagnostic(ErrorCode.ERR_BadArgType, @"""A""").WithArguments("2", "string", "int"), // (19,12): error CS1503: Argument 1: cannot convert from 'int' to 'string' // M2(1, "A"); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string"), // (20,20): error CS1503: Argument 2: cannot convert from 'string' to 'int' // M3<int>(1, "A"); Diagnostic(ErrorCode.ERR_BadArgType, @"""A""").WithArguments("2", "string", "int"), // (21,20): error CS1503: Argument 1: cannot convert from 'int' to 'string' // M3<string>(1, "A"); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "string")); } [Fact] public void TypeInferenceFailures() { var source = @" public interface I { } public interface I1<T> { } public interface I2<S, T> { } public class A : I { } public class B { } public class C { } public class G1<T> : I1<T> { } public class G2<S, T> : G1<S>, I2<S, T> { } public class AggTest { public static A a = new A(); public static I i = a; public static G1<A> g1a = new G1<A>(); public static G1<G1<B>> g11b = new G1<G1<B>>(); public static G1<G1<G1<C>>> g111c = new G1<G1<G1<C>>>(); public static G1<G2<A, B>> g12ab = new G1<G2<A, B>>(); public static G2<A, B> g2ab = new G2<A, B>(); public static G2<G1<A>, B> g21ab = new G2<G1<A>, B>(); public static G2<A, G1<B>> g2a1b = new G2<A, G1<B>>(); public static G2<G1<A>, G1<B>> g21a1b = new G2<G1<A>, G1<B>>(); public static G2<G2<A, B>, C> g22abc = new G2<G2<A, B>, C>(); public static G2<A, G2<B, C>> g2a2bc = new G2<A, G2<B, C>>(); public static G2<G2<A, B>, G1<C>> g22ab1c = new G2<G2<A, B>, G1<C>>(); public static G2<G1<A>, G2<B, C>> g21a2bc = new G2<G1<A>, G2<B, C>>(); public class B1 { // Nesting >= 2 public static void M3<S, T>(G1<G2<S, T>> a) { } public static void M3<S, T>(G2<G1<S>, T> a) { } public static void M3<S, T>(G2<S, G1<T>> a) { } public static void M3<S, T>(G2<G1<S>, G1<T>> a) { } } public class ClassTestGen : B1 { public static void Run() { M3(null); // Can't infer M3(a); // Can't infer M3(i); // Can't infer M3(g1a); // Can't infer M3(g11b); // Can't infer M3(g111c); // Can't infer M3(g12ab); // OK M3(g2ab); // Can't infer M3(g21ab); // OK M3(g2a1b); // OK M3(g21a1b); // Ambiguous M3(g22abc); // OK M3(g2a2bc); // Can't infer M3(g22ab1c); // OK M3(g21a2bc); // OK } } } "; CreateCompilation(source).VerifyDiagnostics( // (43,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(null); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // (44,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(a); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // (45,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(i); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // (46,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(g1a); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // (47,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(g11b); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // (48,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(g111c); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // NOTE: Dev10 reports "AggTest.B1.M3<S,T>(G2<G1<S>,T>)" for the last two, but this seems just as good (type inference fails for both). // (50,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(g2ab); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)"), // (55,13): error CS0411: The type arguments for method 'AggTest.B1.M3<S, T>(G1<G2<S, T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M3(g2a2bc); // Can't infer Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M3").WithArguments("AggTest.B1.M3<S, T>(G1<G2<S, T>>)")); } [WorkItem(528425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528425")] [WorkItem(528425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528425")] [Fact(Skip = "528425")] public void ExactInaccessibleMatch() { var source = @" public class C { public static void Main() { D d = new D(); d.M(4, 5, ""b""); } } public class D { public void M(int i) { } private void M(int i, int j, string s) { } } "; CreateCompilation(source).VerifyDiagnostics( // (7,9): error CS0122: 'D.M(int, int, string)' is inaccessible due to its protection level // d.M(4, 5, "b"); Diagnostic(ErrorCode.ERR_BadAccess, "d.M")); } [WorkItem(545382, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545382")] [Fact] public void Whidbey133503a() { var source = @" class Ambig { static void Main() { overload1(1, 1); overload2(1, 1); } // causes ambiguity because first and third method, but depending on the order, the compiler // reports them incorrectly. VSWhidbey:133503 static void overload1(byte b, goo f) { } static void overload1(sbyte b, bar f) { } static void overload1(int b, baz f) { } static void overload2(int b, baz f) { } static void overload2(sbyte b, bar f) { } static void overload2(byte b, goo f) { } } class goo { public static implicit operator goo(int i) { return new goo(); } } class bar { public static implicit operator bar(int i) { return new bar(); } } class baz { public static implicit operator baz(int i) { return new baz(); } public static implicit operator baz(goo f) { return new baz(); } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Ambig.overload1(byte, goo)' and 'Ambig.overload1(int, baz)' // overload1(1, 1); Diagnostic(ErrorCode.ERR_AmbigCall, "overload1").WithArguments("Ambig.overload1(byte, goo)", "Ambig.overload1(int, baz)").WithLocation(6, 9), // (7,9): error CS0121: The call is ambiguous between the following methods or properties: 'Ambig.overload2(int, baz)' and 'Ambig.overload2(byte, goo)' // overload2(1, 1); Diagnostic(ErrorCode.ERR_AmbigCall, "overload2").WithArguments("Ambig.overload2(int, baz)", "Ambig.overload2(byte, goo)").WithLocation(7, 9) ); } [WorkItem(545382, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545382")] [Fact] public void Whidbey133503b() { var source = @" class Ambig { static void Main() { F(new Q()); } // causes ambiguity because of conversion cycle. So the compiler // arbitrarily picks the 'first' 2 methods to report (which turn out to be // the last 2 overloads declared). Also VSWhidbey:133503 public static void F(P1 p) { } public static void F(P2 p) { } public static void F(P3 p) { } } public class P1 { public static implicit operator P1(P2 p) { return null; } } public class P2 { public static implicit operator P2(P3 p) { return null; } } public class P3 { public static implicit operator P3(P1 p) { return null; } } public class Q { public static implicit operator P1(Q p) { return null; } public static implicit operator P2(Q p) { return null; } public static implicit operator P3(Q p) { return null; } } "; CreateCompilation(source).VerifyDiagnostics( // (6,9): error CS0121: The call is ambiguous between the following methods or properties: 'Ambig.F(P1)' and 'Ambig.F(P2)' // F(new Q()); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("Ambig.F(P1)", "Ambig.F(P2)")); } [WorkItem(545467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545467")] [Fact] public void ClassPlusLambda1() { // ACASEY: EricLi's comment provides good context on the // nature of the problems that arise in such situations and the behavior of the native // compiler. However, the comments about Roslyn's behavior are no longer accurate. // Unfortunately, we discovered real-world code that depended on the native behavior // so we need to replicate it in Roslyn. Effectively, null literal conversions become // standard implicit conversions (we expect the spec to be revised) and anonymous function // and method group conversions are specifically allowed if there is an explicit cast // (this will likely not be spec'd). As for the betterness rule, we only go down the // delegate path if BOTH target types are delegate types. Otherwise, the normal betterness // rules apply. // ERICLI: This test illustrates an unfortunate situation where neither Roslyn nor the // native compiler are compliant with the specification, and the native compiler's // behavior is unusual. In this particular situation, the native compiler is // getting the right answer completely by accident; it is the confluence of two incorrect // decisions adding up accidentally to a correct decision. // // Problem 1: // // The spec says that there must be a *standard implicit conversion* from the expression being // converted to the parameter type of the user-defined implicit conversion. Unfortunately, the // specification does not say that null literal conversions, constant numeric conversions, // method group conversions, or lambda conversions are "standard" conversions. It seems reasonable // that these be allowed; we will probably amend the specification to allow them. // // Now we get to the unusual part. The native compiler allows null literal and constant numeric // conversions to be counted as standard conversions; this is contrary to the exact wording of // the specification but as we said, it is a reasonable rule and we should allow it in the spec. // The unusual part is: the native compiler effectively treats a lambda conversion and a method // group conversion as a standard implicit conversion *if a cast appears in the code*. // // That is, suppose there is an implicit conversion from Action to S. The native compiler allows // // S s = (S)(()=>{}); // // but does not allow // // S s = ()=>{}; // // it is strange indeed that an *implicit* conversion should require a *cast*! // // Roslyn allows all those conversions to be used when converting the expression to the parameter // type of the user-defined implicit conversion, regardless of whether a cast appears in the code. // // Problem 2: // // The native compiler gets the "betterness" rules wrong when lambdas are involved. The right thing // to do is to first, check to see if one method has a more specific formal parameter type than the other. // If betterness cannot be determined by formal parameter types, and the argument is a lambda, then // a special rule regarding the inferred return type of the lambda is used. What the native compiler does // is, if there is a lambda, then it skips doing the formal parameter type check and goes straight to the // lambda check. // // After some debate, we decided a while back to replicate this bug in Roslyn. // // Now we see how these two bugs work together in the native compiler to produce the correct result // for the wrong reason. Suppose we have a simplified version of the code below: r = r + (x=>x); // What happens? // // The correct behavior according to the spec is to say that there are two possible operators, // MC + EXPR and MC + MC. Are either of them *applicable*? Clearly both are good in their left // hand operand. Can the right-hand operand, a lambda, be converted via implicit conversion to // the expression tree type? Obviously yes. Can the lambda be converted to MainClass? // // Not directly, because MainClass is not a delegate or expression tree type. But we examine // the user-defined conversions on MainClass and discover an implicit conversion from expression // tree to MainClass. Can we use that? // // The spec says no, because the conversion from lambda to expression tree is not a "standard" // implicit conversion. // // The native compiler says no because it enforces that rule when there is no cast in the code. // Had there been a cast in the code, the native compiler would say yes, there is. // // Roslyn says yes; it allows the lambda conversion as a standard conversion regardless of whether // there is a cast in the code. // // In the native compiler there is now only one operator in the candidate set of applicable operators; // the choice is therefore easy; the MC + EXPR wins. // // In Roslyn, there are now two operators in the candidate set of applicable operators. Which one wins? // // The correct behavior is to say that the more specific one wins. Since there is an implicit conversion // from EXPR to MC but not from MC to EXPR, the MC + EXPR candidate must be better, so it wins. // // But that is not what Roslyn does; remember, Roslyn is being bug-compatible with the native compiler. // The native compiler does not check for betterness on types when a lambda is involved. // Therefore Roslyn checks the lambda, and is unable to deduce from it which candidate is better. // // Therefore Roslyn gives an ambiguity error, even though (1) by rights the candidate set should // contain a single operator, and (2) even if it contains two, one of them is clearly better. // var source = @" class MainClass { static void Main() { MainClass r = new MainClass(); // The lambda contains an ambiguity error, and therefore we cannot work out // the overload resolution problem on the outermost addition, so we give // a bad binary operator error. r = r + ((MainClass x) => x + ((MainClass y) => (y + null))); // The lambda body no longer contains an error, thanks to the cast. // Therefore, this becomes an ambiguity error, for reasons detailed above. r = r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null))); } public static MainClass operator +(MainClass r1, MainClass r2) { return r1; } public static MainClass operator +(MainClass r1, System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) { return r1; } public static implicit operator MainClass( System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) { return new MainClass(); } } "; // Roslyn matches the native behavior - it compiles cleanly. var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics(); } [WorkItem(545467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545467")] [Fact] public void ClassPlusLambda2() { // Here we remove one of the operators from the previous test. Of course the // first one is no longer ambiguous, and the second one no longer works because // now the lambda contains an addition that has no applicable operator, and // so the outer addition cannot work either. var source = @" class MainClass { static void Main() { MainClass r = new MainClass(); r = r + ((MainClass x) => x + ((MainClass y) => (y + null))); r = r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null))); } // public static MainClass operator +(MainClass r1, MainClass r2) { return r1; } public static MainClass operator +(MainClass r1, System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) { return r1; } public static implicit operator MainClass( System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) { return new MainClass(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (8,13): error CS0019: Operator '+' cannot be applied to operands of type 'MainClass' and 'lambda expression' // r = r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null))); Diagnostic(ErrorCode.ERR_BadBinaryOps, "r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null)))").WithArguments("+", "MainClass", "lambda expression")); } [WorkItem(545467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545467")] [Fact] public void ClassPlusLambda3() { // In this variation we remove the other addition operator. The native compiler // disallows three of these additions, because as mentioned above, it is inconsistent // about when a user-defined conversion may be from a lambda. The native compiler says // that the user-defined conversion may only be from a lambda if a cast appears in // the source; in three of the four conversions from lambdas here, there is no cast. // // Roslyn replicates this bug. var source = @" class MainClass { public static void Main() { MainClass r = new MainClass(); r = r + ((MainClass x) => (x + ((MainClass y) => (y + null)))); r = r + ((MainClass x) => (x + (MainClass)((MainClass y) => (y + null)))); System.Func<MainClass, MainClass> f = x => x + (y => y); } public static MainClass operator +(MainClass r1, MainClass r2) { return r1; } // public static MainClass operator +(MainClass r1, // System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) // { return r1; } public static implicit operator MainClass( System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) { return new MainClass(); } } "; // NOTE: roslyn suppresses the error for (x + (...)) in the first assignment, // but it's still an error (as indicated by the standalone test below). var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '+' cannot be applied to operands of type 'MainClass' and 'lambda expression' // r = r + ((MainClass x) => (x + ((MainClass y) => (y + null)))); Diagnostic(ErrorCode.ERR_BadBinaryOps, "r + ((MainClass x) => (x + ((MainClass y) => (y + null))))").WithArguments("+", "MainClass", "lambda expression"), // (8,13): error CS0019: Operator '+' cannot be applied to operands of type 'MainClass' and 'lambda expression' // r = r + ((MainClass x) => (x + (MainClass)((MainClass y) => (y + null)))); Diagnostic(ErrorCode.ERR_BadBinaryOps, "r + ((MainClass x) => (x + (MainClass)((MainClass y) => (y + null))))").WithArguments("+", "MainClass", "lambda expression"), // (9,52): error CS0019: Operator '+' cannot be applied to operands of type 'MainClass' and 'lambda expression' // System.Func<MainClass, MainClass> f = x => x + (y => y); Diagnostic(ErrorCode.ERR_BadBinaryOps, "x + (y => y)").WithArguments("+", "MainClass", "lambda expression")); } [WorkItem(545467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545467")] [Fact] public void ClassPlusLambda4() { // In this final variation, we remove the user-defined conversion. And now of course we cannot // add MainClass to the lambda at all; the native compiler and Roslyn agree. var source = @" class MainClass { static void Main() { MainClass r = new MainClass(); r = r + ((MainClass x) => x + ((MainClass y) => (y + null))); r = r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null))); } public static MainClass operator +(MainClass r1, MainClass r2) { return r1; } public static MainClass operator +(MainClass r1, System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) { return r1; } // public static implicit operator MainClass( // System.Linq.Expressions.Expression<System.Func<MainClass, MainClass>> e) // { return new MainClass(); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (7,13): error CS0019: Operator '+' cannot be applied to operands of type 'MainClass' and 'lambda expression' // r = r + ((MainClass x) => x + ((MainClass y) => (y + null))); Diagnostic(ErrorCode.ERR_BadBinaryOps, "r + ((MainClass x) => x + ((MainClass y) => (y + null)))").WithArguments("+", "MainClass", "lambda expression"), // (8,13): error CS0019: Operator '+' cannot be applied to operands of type 'MainClass' and 'lambda expression' // r = r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null))); Diagnostic(ErrorCode.ERR_BadBinaryOps, "r + ((MainClass x) => x + (MainClass)((MainClass y) => (y + null)))").WithArguments("+", "MainClass", "lambda expression")); } [WorkItem(546875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546875")] [WorkItem(530930, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530930")] [Fact] public void BigVisitor() { // Reduced from Microsoft.Data.Schema.Sql.dll. var source = @" public class Test { static void Main() { var visitor = new ConcreteVisitor(); visitor.Visit(new Class090()); } } "; var libRef = TestReferences.SymbolsTests.BigVisitor; var start = DateTime.UtcNow; CreateCompilationWithMscorlib40AndSystemCore(source, new[] { libRef }).VerifyDiagnostics(); var elapsed = DateTime.UtcNow - start; Assert.InRange(elapsed.TotalSeconds, 0, 10.0); // Was originally over 30 minutes, so we have some wiggle room here. } [WorkItem(546730, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546730"), WorkItem(546739, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546739")] [Fact] public void TestNamedParamsParam() { CompileAndVerify(@" class C { static void M( int x, double y, params string[] z) { System.Console.WriteLine(1); } static void M( int x, params string[] z) { System.Console.WriteLine(2); } static void Main() { C.M(0, z: """"); } }", expectedOutput: "2").VerifyDiagnostics(); } [WorkItem(531173, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531173")] [Fact] public void InvokeMethodOverridingNothing() { var source = @" public class C { public override T Override<T>(T t) { return t; } public void Test<T>(T t) { Override(t); } } "; CreateCompilation(source).VerifyDiagnostics( // (4,20): error CS0115: 'C.Override<T>(T)': no suitable method found to override // public override T Override<T>(T t) Diagnostic(ErrorCode.ERR_OverrideNotExpected, "Override").WithArguments("C.Override<T>(T)")); } [WorkItem(547186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/547186")] [Fact, WorkItem(531613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/531613")] public void IndexerWithoutAccessors() { var source = @" class Program { public static void Main() { C c = new C(); c[""""] = 10; } } abstract class A { public abstract int this[string arg] { set; } } class C : A { public override int this[string arg] // Not finished typing yet. "; // Doesn't assert. CreateCompilation(source).VerifyDiagnostics( // (18,41): error CS1514: { expected // public override int this[string arg] Diagnostic(ErrorCode.ERR_LbraceExpected, ""), // (18,41): error CS1513: } expected // public override int this[string arg] Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (18,41): error CS1513: } expected // public override int this[string arg] Diagnostic(ErrorCode.ERR_RbraceExpected, ""), // (18,25): error CS0548: 'C.this[string]': property or indexer must have at least one accessor // public override int this[string arg] Diagnostic(ErrorCode.ERR_PropertyWithNoAccessors, "this").WithArguments("C.this[string]"), // (16,7): error CS0534: 'C' does not implement inherited abstract member 'A.this[string].set' // class C : A Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "A.this[string].set")); } [Fact] public void DynamicVsTypeParameters() { string source = @" using System; public class B<T> { public void F(T p1) { } public void F(dynamic p1) { } } class C { void M(B<C> b) { b.F(null); //-B<C>.F(C) } }"; TestOverloadResolutionWithDiff(source, new[] { CSharpRef, SystemCoreRef }); } [Fact] public void DynamicByRef() { string source = @" using System; public class C { public static int F(int p1, char p2, ref dynamic p3) { return 2; } public static int F(C p1, params dynamic[] p2) { return 3; } public static implicit operator int(C t) { return 1; } public static implicit operator C(int t) { return new C(); } static void M() { dynamic d1 = null; C c = null; C.F(c, 'a', ref d1); //-C.F(int, char, ref dynamic) } }"; TestOverloadResolutionWithDiff(source); } [Fact, WorkItem(624410, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/624410")] public void DynamicTypeInferenceAndPointer() { string source = @" public unsafe class C { public static void M() { dynamic x = null; Bar(x); } static void Bar<T>(D<T>.E*[] x) { } } class D<T> { public enum E { } } "; // Dev11 reports error CS0411: The type arguments for method 'C.Bar<T>(D<T>.E*[])' cannot be inferred from the usage. Try // specifying the type arguments explicitly. CreateCompilationWithMscorlib40AndSystemCore(source, options: TestOptions.UnsafeReleaseDll).VerifyDiagnostics(); } [Fact, WorkItem(598032, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598032"), WorkItem(1157097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1157097"), WorkItem(2298, "https://github.com/dotnet/roslyn/issues/2298")] public void GenericVsOptionalParameter() { string source = @" using System; class C { public static int Goo(int x, string y = null) { return 1; } public static int Goo<T>(T x) { return 0; } public static void Main() { System.Console.WriteLine(Goo(0)); } } "; var compilation = CreateCompilation(source, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: "0"); } [WorkItem(598029, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/598029")] [Fact] public void TypeParameterInterfaceVersusNonInterface() { string source = @" interface IA { int Goo(int x = 0); } class C : IA { public int Goo(int x) { return x; } static int M<T>(T x) where T : A, IA { return x.Goo(); //-IA.Goo(int) } } "; TestOverloadResolutionWithDiff(source); } [WorkItem(649807, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/649807")] [Fact] public void OverloadResolution649807() { var source = @" public class Test { public delegate dynamic nongenerics(dynamic id); public delegate T generics< T>(dynamic id); public dynamic Goo(nongenerics Meth, dynamic id) { return null; } public T Goo<T>(generics<T> Meth, dynamic id) { return default(T); } public dynamic method(dynamic id) { return System.String.Empty; } public dynamic testGoo(dynamic id) { return Goo(method, ""abc""); } static void Main(string[] args) { } }"; // Doesn't assert. CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (20,16): error CS0121: The call is ambiguous between the following methods or properties: 'Test.Goo(Test.nongenerics, dynamic)' and 'Test.Goo<T>(Test.generics<T>, dynamic)' // return Goo(method, "abc"); Diagnostic(ErrorCode.ERR_AmbigCall, "Goo").WithArguments("Test.Goo(Test.nongenerics, dynamic)", "Test.Goo<T>(Test.generics<T>, dynamic)") ); } [WorkItem(662641, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/662641")] [Fact] public void GenericMethodConversionToDelegateWithDynamic() { var source = @" using System; public delegate void D002<T1, T2>(T1 t1, T2 t2); public delegate void D003(dynamic t1, object t2); public class Goo { static internal void M11<T1, T2>(T1 t1, T2 t2) { } } public struct start { static void M(D002<dynamic, object> d) {} static public void Main() { dynamic d1 = null; object o1 = null; Goo.M11<dynamic, object>(d1, o1); Goo.M11(d1, o1); D002<dynamic, object> dd02 = new D002<dynamic, object>(Goo.M11); D002<dynamic, object> dd03 = Goo.M11; D002<dynamic, object> dd04 = (D002<dynamic, object>)Goo.M11; D003 dd05 = Goo.M11; M(Goo.M11); Console.WriteLine(dd02); } }"; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( ); } [WorkItem(690966, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/690966")] [Fact] public void OptionalParameterInDelegateConversion() { var source = @" using System; class C { static void M1(Func<string, int> f) { } static void M1(Func<string, string, int> f) { } static int M2(string s, string t = null) { return 0; } static void Main() { M1(M2); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var callSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); Assert.Equal("void C.M1(System.Func<System.String, System.String, System.Int32> f)", model.GetSymbolInfo(callSyntax).Symbol.ToTestDisplayString()); } [WorkItem(718294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718294")] [Fact] public void MethodGroupConversion_BetterCandidateHasOptionalParameter() { var source = @" using System; class Test { void M(IViewable2 v) { v.View(v.Add); } } interface IViewable { void View(Action viewer); } interface IViewable2 : IViewable { } static class Extensions { [Obsolete(""A"", error: false)] public static void Add(this IViewable2 @this) { } [Obsolete(""B"", error: false)] public static void Add(this IViewable @this, object obj = null) { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (8,16): warning CS0618: 'Extensions.Add(IViewable2)' is obsolete: 'A' // v.View(v.Add); Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "v.Add").WithArguments("Extensions.Add(IViewable2)", "A")); } [WorkItem(718294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718294")] [Fact] public void MethodGroupConversion_BetterCandidateHasParameterArray() { var source = @" using System; class Test { void M(IViewable2 v) { v.View(v.Add); } } interface IViewable { void View(Action viewer); } interface IViewable2 : IViewable { } static class Extensions { [Obsolete(""A"", error: false)] public static void Add(this IViewable2 @this) { } [Obsolete(""B"", error: false)] public static void Add(this IViewable @this, params object[] obj) { } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (8,16): warning CS0618: 'Extensions.Add(IViewable2)' is obsolete: 'A' // v.View(v.Add); Diagnostic(ErrorCode.WRN_DeprecatedSymbolStr, "v.Add").WithArguments("Extensions.Add(IViewable2)", "A")); } [WorkItem(709114, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/709114")] [Fact] public void RenameTypeParameterInOverride() { var source = @" public class Base { public virtual void M<T1>(T1 t) { } } public class Derived : Base { public override void M<T2>(T2 t) { } void Test(int c) { M(c); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var callSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var methodSymbol = (IMethodSymbol)model.GetSymbolInfo(callSyntax).Symbol; Assert.Equal(SpecialType.System_Int32, methodSymbol.TypeArguments.Single().SpecialType); } [Fact] [WorkItem(675327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/675327")] public void OverloadInheritanceAsync() { string source = @" using System.Threading.Tasks; using System; class Test { public virtual async Task<int> Goo<U>(Func<Task<U>> f) { await Task.Delay(10); return 1; } } class TestCase : Test { public override async Task<int> Goo<T>(Func<Task<T>> f) { await Task.Delay(10); return 3; } public async Task<int> Goo(Func<Task<long>> f) { await Task.Delay(10); return 2; } public async void Run() { var xxx = await Goo(async () => { // Roslyn error here await Task.Delay(10); return 5m; }); Console.WriteLine(xxx); // 3; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] [WorkItem(675327, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/675327")] public void OverloadInheritance001() { string source = @" using System; class Test { public virtual int Goo<U>(Func<U> f) { return 1; } } class TestCase : Test { public override int Goo<T>(Func<T> f) { return 3; } public void Run() { var xxx = Goo(() => { // Roslyn error here return 5m; }); Console.WriteLine(xxx); // 3; } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact, WorkItem(718294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/718294")] public void ResolveExtensionMethodGroupOverloadWithOptional() { string source = @" using System; class Viewable { static void Main() { IViewable2<object> v = null; v.View(v.Add); } } interface IViewable<T> { void View(Action<T> viewer); } interface IViewable2<T> : IViewable<T> { } static class Extensions { public static void Add<T>(this IViewable<T> @this, T item) { } public static void Add<T>(this IViewable2<T> @this, T item, object obj = null) { } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact, WorkItem(667132, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/667132")] public void ExtensionMethodOnComInterfaceMissingRefToken() { string source = @"using System; using System.Runtime.InteropServices; [ComImport, Guid(""cb4ac859-0589-483e-934d-b27845d5fe74"")] interface IGoo { } static class Program { public static void Bar(this IGoo self, ref Guid id) { id = Guid.NewGuid(); } static void Main() { Goo(null); } static void Goo(IGoo o) { Guid g = Guid.NewGuid(); Console.WriteLine(g); o.Bar(g); Console.WriteLine(g); } }"; CreateCompilationWithMscorlib45(source).VerifyDiagnostics(); } [Fact] [WorkItem(737971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737971")] public void Repro737971a() { var source = @" using System; public class Color { } public class ColorToColor { public static implicit operator ColorToColor(Func<Color, Color> F) { return null; } } public class Test { public void M() { N(_ => default(Color)); } public void N(ColorToColor F) { } public void N(Func<Color, Color> F) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(syntax).Symbol; // Func<Color, Color> is convertible to ColorToColor, but the converse is not true. Assert.Equal("void Test.N(System.Func<Color, Color> F)", symbol.ToTestDisplayString()); } [Fact] [WorkItem(737971, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/737971")] public void Repro737971b() { var source = @" using System; public class Color { } public class ColorToColor { public static implicit operator ColorToColor(Func<Color, Color> F) { throw null; } } public class Test { public void M() { N(() => _ => default(Color)); } public void N(Func<ColorToColor> F) { } public void N(Func<Func<Color, Color>> F) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics(); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var syntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(syntax).Symbol; // Func<Func<Color, Color>> is convertible to Func<ColorToColor>, but the converse is not true. Assert.Equal("void Test.N(System.Func<System.Func<Color, Color>> F)", symbol.ToTestDisplayString()); } [Fact] [WorkItem(754406, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/754406")] public void TestBug754406() { string source = @"interface I {} class G<T> where T : I {} class Program { static void Main(string[] args) { } static void M<T>(G<T> gt1, params int[] i) { M(gt1, 1, 2); } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (9,27): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'G<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'I'. // static void M<T>(G<T> gt1, params int[] i) Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "gt1").WithArguments("G<T>", "I", "T", "T"), // (11,9): error CS0314: The type 'T' cannot be used as type parameter 'T' in the generic type or method 'G<T>'. There is no boxing conversion or type parameter conversion from 'T' to 'I'. // M(gt1, 1, 2); Diagnostic(ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar, "M").WithArguments("G<T>", "I", "T", "T") ); } [Fact] [WorkItem(528811, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528811")] public void TestBug528811() { string source = @"using System; delegate byte DL(); class Test { void goo() { EventHandler y = null; y += goo; y += x => 2; } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (9,14): error CS0123: No overload for 'goo' matches delegate 'System.EventHandler' // y += goo; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "goo").WithArguments("goo", "System.EventHandler"), // (10,14): error CS1593: Delegate 'System.EventHandler' does not take 1 arguments // y += x => 2; Diagnostic(ErrorCode.ERR_BadDelArgCount, "x => 2").WithArguments("System.EventHandler", "1") ); } [Fact] public void IndexMemberAccessErr005() { var source = @" using System.Collections.Generic; class Program { static void Main(string[] args) { var d = new Dictionary<int, int>() {[""aaa""] = 3}; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,46): error CS1503: Argument 1: cannot convert from 'string' to 'int' // var d = new Dictionary<int, int>() {["aaa"] = 3}; Diagnostic(ErrorCode.ERR_BadArgType, @"""aaa""").WithArguments("1", "string", "int").WithLocation(8, 46) ); } [Fact] public void IndexMemberAccessErr006() { var source = @" using System.Collections.Generic; class Program { static void Main(string[] args) { var d = new int[] {[1] = 3 }; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (8,28): error CS1513: } expected // var d = new int[] {[1] = 3 }; Diagnostic(ErrorCode.ERR_RbraceExpected, "[").WithLocation(8, 28), // (8,36): error CS1002: ; expected // var d = new int[] {[1] = 3 }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(8, 36), // (8,37): error CS1597: Semicolon after method or accessor block is not valid // var d = new int[] {[1] = 3 }; Diagnostic(ErrorCode.ERR_UnexpectedSemicolon, ";").WithLocation(8, 37), // (10,1): error CS1022: Type or namespace definition, or end-of-file expected // } Diagnostic(ErrorCode.ERR_EOFExpected, "}").WithLocation(10, 1), // (2,1): info CS8019: Unnecessary using directive. // using System.Collections.Generic; Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Collections.Generic;").WithLocation(2, 1) ); } [Fact] [WorkItem(655409, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/655409")] public void TestBug655409() { string source = @" using System; class C { static void Main() { M(a => M(b => M(c => M(d => M(e => M(f => a)))))); System.Console.WriteLine(""success""); } static T M<T>(Func<bool, T> x) { return default(T); } static T M<T>(Func<byte, T> x) { return default(T); } static T M<T>(Func<uint, T> x) { return default(T); } static T M<T>(Func<long, T> x) { return default(T); } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (8,44): error CS0121: The call is ambiguous between the following methods or properties: 'C.M<T>(System.Func<bool, T>)' and 'C.M<T>(System.Func<byte, T>)' // M(a => M(b => M(c => M(d => M(e => M(f => a)))))); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("C.M<T>(System.Func<bool, T>)", "C.M<T>(System.Func<byte, T>)").WithLocation(8, 44) ); } [Fact, WorkItem(30, "https://roslyn.codeplex.com/workitem/30")] public void BugCodePlex_30_01() { string source1 = @" using System; class C { static void Main() { Goo(() => { return () => 0; ; }); Goo(() => { return () => 0; }); } static void Goo(Func<Func<short>> x) { Console.WriteLine(1); } static void Goo(Func<Func<int>> x) { Console.WriteLine(2); } } "; CompileAndVerify(source1, expectedOutput: @"2 2"); } [Fact, WorkItem(30, "https://roslyn.codeplex.com/workitem/30")] public void BugCodePlex_30_02() { string source1 = @" using System; class C { static void Main() { Test(false); } static void Test(bool val) { Goo(() => { if (val) return () => 0; else return () => (short)0; }); Goo(() => { if (val) return () => (short)0; else return () => 0; }); } static void Goo(Func<Func<short>> x) { Console.WriteLine(1); } static void Goo(Func<Func<int>> x) { Console.WriteLine(2); } } "; CompileAndVerify(source1, expectedOutput: @"1 1"); } [Fact, WorkItem(30, "https://roslyn.codeplex.com/workitem/30")] public void BugCodePlex_30_03() { string source1 = @" using System; class C { static void Main() { Test(false); } static void Test(bool val) { Goo(() => { if (val) return () => 0; else return () => 0; }); } static void Goo(Func<Func<short>> x) { Console.WriteLine(1); } static void Goo(Func<Func<int>> x) { Console.WriteLine(2); } } "; CompileAndVerify(source1, expectedOutput: @"2"); } [Fact] public void ExactlyMatchingAsyncLambda_01() { string source1 = @" using System; using System.Threading.Tasks; class C { static void Main() { #pragma warning disable 1998 Goo(async () => { return 0; ; }); Goo(async () => { return 0; }); Goo(async () => 0); Goo(async () => { return (short)0; ; }); Goo(async () => { return (short)0; }); Goo(async () => (short)0); } static void Goo(Func<Task<short>> x) { Console.WriteLine(1); } static void Goo(Func<Task<int>> x) { Console.WriteLine(2); } } "; var compilation = CreateCompilationWithMscorlib45(source1, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"2 2 2 1 1 1"); } [Fact] public void ExactlyMatchingAsyncLambda_02() { string source1 = @" using System; using System.Threading.Tasks; class C { static void Main() { #pragma warning disable 1998 Goo(() => async () => { return 0; ; }); Goo(() => async () => { return 0; }); Goo(() => async () => 0); Goo(() => { return async () => 0; ; }); Goo(() => { return async () => 0; }); } static void Goo(Func<Func<Task<short>>> x) { Console.WriteLine(1); } static void Goo(Func<Func<Task<int>>> x) { Console.WriteLine(2); } } "; var compilation = CreateCompilationWithMscorlib45(source1, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"2 2 2 2 2"); } [Fact] public void ExactlyMatchingAsyncLambda_03() { string source1 = @" using System; using System.Threading.Tasks; class C { static void Main() { #pragma warning disable 1998 Goo(async () => { return () => 0; }); Goo(async () => { return () => (short)0; }); } static void Goo(Func<Task<Func<short>>> x) { Console.WriteLine(1); } static void Goo(Func<Task<Func<int>>> x) { Console.WriteLine(2); } } "; var compilation = CreateCompilationWithMscorlib45(source1, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"2 1"); } [Fact] [WorkItem(1079899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1079899")] [WorkItem(364, "CodePlex")] public void TestBug1079899() { string source = @" namespace A.B { static class X { public static int Test(this int o) { return 1; } } } namespace A.C { static class X { public static int Test(this int o) { return 2; } } } namespace C { using A.B; using static A.C.X; class M { public static int Main() { if (1.Test() != 1) return 1; return 0; } } } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (31,19): error CS0121: The call is ambiguous between the following methods or properties: 'X.Test(int)' and 'X.Test(int)' // if (1.Test() != 1) Diagnostic(ErrorCode.ERR_AmbigCall, "Test").WithArguments("A.B.X.Test(int)", "A.C.X.Test(int)").WithLocation(30, 19) ); Assert.Equal("(30,19): error CS0121: The call is ambiguous between the following methods or properties: 'A.B.X.Test(int)' and 'A.C.X.Test(int)'", DiagnosticFormatter.Instance.Format(comp.GetDiagnostics()[0], EnsureEnglishUICulture.PreferredOrNull)); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_0() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static bool IsThing(Goo t) { return false; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, bool> filter) { System.Console.WriteLine(""Create(Func<T, bool> filter)""); return null; } public static Bar<T, V> Create(Func<T, V> propertyPrev, Func<T, bool> filter = null) { System.Console.WriteLine(""Create(Func<T, V> propertyPrev, Func<T, bool> filter = null)""); return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"Create(Func<T, bool> filter)"); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_1() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static bool IsThing(Goo t) { return false; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, bool> filter) { System.Console.WriteLine(""Create(Func < T, bool > filter)""); return null; } public static Bar<T, V> Create(Func<T, V> propertyPrev, params Func<T, bool>[] filter) { System.Console.WriteLine(""Create(Func<T, V> propertyPrev, params Func<T, bool>[] filter""); return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (25,38): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Bar<T, V>.Create(Func<T, bool>)' and 'Program.Bar<T, V>.Create(Func<T, V>, params Func<T, bool>[])' // var x = Bar<Goo, double>.Create(Goo.IsThing); Diagnostic(ErrorCode.ERR_AmbigCall, "Create").WithArguments("ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, bool>)", "ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, V>, params System.Func<T, bool>[])").WithLocation(25, 38) ); CreateCompilation(source1, options: TestOptions.DebugExe).VerifyDiagnostics( ); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_2() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static double IsThing(Goo t) { return 0; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, bool> filter, params int[] dummy) { System.Console.WriteLine(""Create(Func<T, bool> filter, params int[] dummy)""); return null; } public static Bar<T, V> Create(Func<T, V> propertyPrev, Func<T, bool> filter = null) { System.Console.WriteLine(""Create(Func<T, V> propertyPrev, Func<T, bool> filter = null)""); return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"Create(Func<T, V> propertyPrev, Func<T, bool> filter = null)"); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_3() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static double IsThing(Goo t) { return 0; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, bool> filter, params int[] dummy) { System.Console.WriteLine(""Create(Func<T, bool> filter, params int[] dummy)""); return null; } public static Bar<T, V> Create(Func<T, V> propertyPrev) { System.Console.WriteLine(""Create(Func<T, V> propertyPrev)""); return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (25,38): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Bar<T, V>.Create(Func<T, bool>, params int[])' and 'Program.Bar<T, V>.Create(Func<T, V>)' // var x = Bar<Goo, double>.Create(Goo.IsThing); Diagnostic(ErrorCode.ERR_AmbigCall, "Create").WithArguments("ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, bool>, params int[])", "ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, V>)").WithLocation(25, 38) ); CreateCompilation(source1, options: TestOptions.DebugExe).VerifyDiagnostics( ); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_4() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static double IsThing(Goo t) { return 0; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, V> propertyPrev) { System.Console.WriteLine(""Create(Func<T, V> propertyPrev)""); return null; } public static Bar<T, V> Create(Func<T, bool> filter, params int[] dummy) { System.Console.WriteLine(""Create(Func<T, bool> filter, params int[] dummy)""); return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (25,38): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Bar<T, V>.Create(Func<T, V>)' and 'Program.Bar<T, V>.Create(Func<T, bool>, params int[])' // var x = Bar<Goo, double>.Create(Goo.IsThing); Diagnostic(ErrorCode.ERR_AmbigCall, "Create").WithArguments("ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, V>)", "ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, bool>, params int[])").WithLocation(25, 38) ); CreateCompilation(source1, options: TestOptions.DebugExe).VerifyDiagnostics( ); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_5() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static bool IsThing(Goo t) { return false; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, V> propertyPrev, params Func<T, bool>[] filter) { System.Console.WriteLine(""Create(Func<T, V> propertyPrev, params Func<T, bool>[] filter""); return null; } public static Bar<T, V> Create(Func<T, bool> filter) { System.Console.WriteLine(""Create(Func < T, bool > filter)""); return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (25,38): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Bar<T, V>.Create(Func<T, V>, params Func<T, bool>[])' and 'Program.Bar<T, V>.Create(Func<T, bool>)' // var x = Bar<Goo, double>.Create(Goo.IsThing); Diagnostic(ErrorCode.ERR_AmbigCall, "Create").WithArguments("ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, V>, params System.Func<T, bool>[])", "ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, bool>)").WithLocation(25, 38) ); CreateCompilation(source1, options: TestOptions.DebugExe).VerifyDiagnostics( ); } [Fact, WorkItem(1080896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1080896"), WorkItem(367, "Devdiv")] public void Bug1080896_6() { string source1 = @" using System; namespace ConsoleApplication2 { class Program { public class Goo { public static bool IsThing(Goo t) { return false; } } public class Bar<T, V> where T : class { public static Bar<T, V> Create(Func<T, bool> filter, params int[] extra) { return null; } public static Bar<T, V> Create(Func<T, V> propertyPrev, params int[] extra) { return null; } } static void Main(string[] args) { var x = Bar<Goo, double>.Create(Goo.IsThing); } } } "; CreateCompilation(source1, options: TestOptions.DebugExe, parseOptions: TestOptions.WithoutImprovedOverloadCandidates).VerifyDiagnostics( // (23,38): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Bar<T, V>.Create(Func<T, bool>, params int[])' and 'Program.Bar<T, V>.Create(Func<T, V>, params int[])' // var x = Bar<Goo, double>.Create(Goo.IsThing); Diagnostic(ErrorCode.ERR_AmbigCall, "Create").WithArguments("ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, bool>, params int[])", "ConsoleApplication2.Program.Bar<T, V>.Create(System.Func<T, V>, params int[])").WithLocation(23, 38) ); CreateCompilation(source1, options: TestOptions.DebugExe).VerifyDiagnostics( ); } [Fact, WorkItem(1081302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081302"), WorkItem(371, "Devdiv")] public void Bug1081302_0() { string source1 = @" using System; namespace ConsoleApplication2 { public static class Goo { public static U IfNotNull<T, U>(this T value, Func<T, U> selector, U defaultValue = default(U)) { System.Console.WriteLine(""IfNotNull<T, U>(this T value, Func<T, U> selector, U defaultValue = default(U))""); return value != null ? selector(value) : defaultValue; } public static U IfNotNull<T, U>(this T? source, Func<T, U> selector) where T : struct { System.Console.WriteLine(""IfNotNull<T, U>(this T? source, Func<T, U> selector)""); return source.HasValue ? selector(source.Value) : default(U); } } class Program { static void Main(string[] args) { double? val = null; var d1 = val.IfNotNull(v => v / 100); var d2 = Goo.IfNotNull(val, v => v / 100); } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"IfNotNull<T, U>(this T? source, Func<T, U> selector) IfNotNull<T, U>(this T? source, Func<T, U> selector)"); } [Fact, WorkItem(1081302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081302"), WorkItem(371, "Devdiv")] public void Bug1081302_1() { string source1 = @" using System; namespace ConsoleApplication2 { public static class Goo { public static U IfNotNull<T, U>(this T value, Func<T, U> selector, params U[] defaultValue) { System.Console.WriteLine(""IfNotNull<T, U>(this T value, Func<T, U> selector, params U[] defaultValue)""); return value != null ? selector(value) : defaultValue[0]; } public static U IfNotNull<T, U>(this T? source, Func<T, U> selector) where T : struct { System.Console.WriteLine(""IfNotNull<T, U>(this T? source, Func<T, U> selector)""); return source.HasValue ? selector(source.Value) : default(U); } } class Program { static void Main(string[] args) { double? val = null; var d1 = val.IfNotNull(v => v / 100); var d2 = Goo.IfNotNull(val, v => v / 100); } } } "; var compilation = CreateCompilationWithMscorlib40(source1, new[] { TestMetadata.Net40.SystemCore }, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); } [Fact, WorkItem(1081302, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1081302"), WorkItem(371, "Devdiv")] public void Bug1081302_2() { string source1 = @" using System; namespace ConsoleApplication2 { public static class Goo { public static U IfNotNull<T, U>(this T? source, Func<T, U> selector) where T : struct { System.Console.WriteLine(""IfNotNull<T, U>(this T? source, Func<T, U> selector)""); return source.HasValue ? selector(source.Value) : default(U); } public static U IfNotNull<T, U>(this T value, Func<T, U> selector, params U[] defaultValue) { System.Console.WriteLine(""IfNotNull<T, U>(this T value, Func<T, U> selector, params U[] defaultValue)""); return value != null ? selector(value) : defaultValue[0]; } } class Program { static void Main(string[] args) { double? val = null; var d1 = val.IfNotNull(v => v / 100); var d2 = Goo.IfNotNull(val, v => v / 100); } } } "; var compilation = CreateCompilationWithMscorlib40(source1, new[] { TestMetadata.Net40.SystemCore }, options: TestOptions.DebugExe); compilation.VerifyDiagnostics(); } [Fact] public void ExactParameterMatchAndOptionals() { string source1 = @" class CTest { static void Main() { M1(0); } static void M1(int x) { System.Console.WriteLine(""M1(int x)""); } static void M1(int x, int y = 0) { System.Console.WriteLine(""M1(int x, int y = 0)""); } static void M1(int x, params int [] y) { System.Console.WriteLine(""M1(int x, params int [] y)""); } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"M1(int x)"); } [Fact] [WorkItem(1034429, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1034429")] public void TestBug1034429() { string source = @" using System.Security.Permissions; class Program { [A(SecurityAction.Assert)] [B(p2: SecurityAction.Assert, p1: 0)] [C(p3: ""again"", p2: SecurityAction.Assert, p1: 0)] static void Main() { } } public class A : CodeAccessSecurityAttribute { public A(params SecurityAction) { } } public class B : CodeAccessSecurityAttribute { public B(int p1, params SecurityAction p2) { } } public class C : CodeAccessSecurityAttribute { public C(int p1, params SecurityAction p2, string p3) { } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (16,35): error CS1001: Identifier expected // public A(params SecurityAction) Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(16, 35), // (30,22): error CS0231: A params parameter must be the last parameter in a formal parameter list // public C(int p1, params SecurityAction p2, string p3) Diagnostic(ErrorCode.ERR_ParamsLast, "params SecurityAction p2").WithLocation(30, 22), // (14,14): error CS0534: 'A' does not implement inherited abstract member 'SecurityAttribute.CreatePermission()' // public class A : CodeAccessSecurityAttribute Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "A").WithArguments("A", "System.Security.Permissions.SecurityAttribute.CreatePermission()").WithLocation(14, 14), // (28,14): error CS0534: 'C' does not implement inherited abstract member 'SecurityAttribute.CreatePermission()' // public class C : CodeAccessSecurityAttribute Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "C").WithArguments("C", "System.Security.Permissions.SecurityAttribute.CreatePermission()").WithLocation(28, 14), // (21,14): error CS0534: 'B' does not implement inherited abstract member 'SecurityAttribute.CreatePermission()' // public class B : CodeAccessSecurityAttribute Diagnostic(ErrorCode.ERR_UnimplementedAbstractMethod, "B").WithArguments("B", "System.Security.Permissions.SecurityAttribute.CreatePermission()").WithLocation(21, 14), // (16,14): error CS0225: The params parameter must be a single dimensional array // public A(params SecurityAction) Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(16, 14), // (23,22): error CS0225: The params parameter must be a single dimensional array // public B(int p1, params SecurityAction p2) Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(23, 22), // (30,22): error CS0225: The params parameter must be a single dimensional array // public C(int p1, params SecurityAction p2, string p3) Diagnostic(ErrorCode.ERR_ParamsMustBeArray, "params").WithLocation(30, 22), // (7,6): error CS7048: First argument to a security attribute must be a valid SecurityAction // [B(p2: SecurityAction.Assert, p1: 0)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "B").WithLocation(7, 6), // (8,6): error CS7048: First argument to a security attribute must be a valid SecurityAction // [C(p3: "again", p2: SecurityAction.Assert, p1: 0)] Diagnostic(ErrorCode.ERR_SecurityAttributeMissingAction, "C").WithLocation(8, 6), // (16,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'CodeAccessSecurityAttribute.CodeAccessSecurityAttribute(SecurityAction)' // public A(params SecurityAction) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "A").WithArguments("action", "System.Security.Permissions.CodeAccessSecurityAttribute.CodeAccessSecurityAttribute(System.Security.Permissions.SecurityAction)").WithLocation(16, 12), // (23,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'CodeAccessSecurityAttribute.CodeAccessSecurityAttribute(SecurityAction)' // public B(int p1, params SecurityAction p2) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "B").WithArguments("action", "System.Security.Permissions.CodeAccessSecurityAttribute.CodeAccessSecurityAttribute(System.Security.Permissions.SecurityAction)").WithLocation(23, 12), // (30,12): error CS7036: There is no argument given that corresponds to the required formal parameter 'action' of 'CodeAccessSecurityAttribute.CodeAccessSecurityAttribute(SecurityAction)' // public C(int p1, params SecurityAction p2, string p3) Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "C").WithArguments("action", "System.Security.Permissions.CodeAccessSecurityAttribute.CodeAccessSecurityAttribute(System.Security.Permissions.SecurityAction)").WithLocation(30, 12)); } [WorkItem(18875, "https://github.com/dotnet/roslyn/issues/18875")] [Fact] public void InvalidParamsPositionCSharp() { const string source = @" public class A { public static void Goo(params int[] vals, bool truth) { } public static void Bar() { // 1 shouldn't show CS1503 Argument 1: cannot convert from 'int' to 'int' Goo(1, true); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (4,28): error CS0231: A params parameter must be the last parameter in a formal parameter list // public static void Goo(params int[] vals, bool truth) Diagnostic(ErrorCode.ERR_ParamsLast, "params int[] vals"), // (12,13): error CS1503: Argument 1: cannot convert from 'int' to 'params int[]' // Goo(1, true); Diagnostic(ErrorCode.ERR_BadArgType, "1").WithArguments("1", "int", "params int[]").WithLocation(12, 13)); } [WorkItem(2249, "https://github.com/dotnet/roslyn/issues/2249")] [Fact] public void TestRefMethodGroup() { var source = @"using System; class Program { static void M() { Console.WriteLine(""pass""); } public static void Main(string[] args) { Action a1 = new Action(ref M); a1(); Action a2 = new Action(out a1); a2(); } }"; CompileAndVerify(source, expectedOutput: @"pass pass").VerifyDiagnostics(); CreateCompilation(source, options: TestOptions.ReleaseDll, parseOptions: TestOptions.Regular.WithStrictFeature()).VerifyDiagnostics( // (12,36): error CS1657: Cannot use 'M' as a ref or out value because it is a 'method group' // Action a1 = new Action(ref M); Diagnostic(ErrorCode.ERR_RefReadonlyLocalCause, "M").WithArguments("M", "method group").WithLocation(12, 36), // (14,36): error CS0149: Method name expected // Action a2 = new Action(out a1); Diagnostic(ErrorCode.ERR_MethodNameExpected, "a1").WithLocation(14, 36) ); } [Fact, WorkItem(1157097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1157097"), WorkItem(2298, "https://github.com/dotnet/roslyn/issues/2298")] public void ParamsAndOptionals() { string source1 = @" using System; using System.Collections.Generic; using VS2015CompilerBug; public static class Extensions { //extension with params keyword public static int Properties(this IFirstInterface source, params int[] x) { System.Console.WriteLine(""int Properties(this IFirstInterface source, params int[] x)""); return 0; } public static bool Properties(this ISecondInterface source, int x = 0, params int[] y) { System.Console.WriteLine(""bool Properties(this ISecondInterface source, int x = 0, params int[] y)""); return true; } //extension without params keyword public static int Properties2(this IFirstInterface source) { System.Console.WriteLine(""int Properties2(this IFirstInterface source)""); return 0; } public static bool Properties2(this ISecondInterface source, int x = 0) { System.Console.WriteLine(""bool Properties2(this ISecondInterface source, int x = 0)""); return true; } } namespace VS2015CompilerBug { public interface IFirstInterface { } public interface ISecondInterface { } public interface IFinalInterface : ISecondInterface, IFirstInterface { } public class VS2015CompilerBug { public static void Main() { IFinalInterface x = default(IFinalInterface); var properties = x.Properties(); var properties2 = x.Properties2(); (new VS2015CompilerBug()).Test2(); } private void Test2(int x = 5, params int[] y) { System.Console.WriteLine(""void Test2(int x = 5, params int[] y)""); } private void Test2(params int[] x) { System.Console.WriteLine(""void Test2(params int[] x)""); } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"int Properties(this IFirstInterface source, params int[] x) int Properties2(this IFirstInterface source) void Test2(params int[] x)"); } [Fact, WorkItem(1157097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1157097"), WorkItem(2298, "https://github.com/dotnet/roslyn/issues/2298")] public void TieBreakOnNumberOfDeclaredParameters_01() { string source1 = @" namespace VS2015CompilerBug { public class VS2015CompilerBug { public static void Main() { (new VS2015CompilerBug()).Test2(1); (new VS2015CompilerBug()).Test2(1, 2); (new VS2015CompilerBug()).Test2(1, 2, 3); (new VS2015CompilerBug()).Test3(1, 2); (new VS2015CompilerBug()).Test3(1, 2, 3); (new VS2015CompilerBug()).Test3(1, 2, 3, 4); } private void Test2(int x, params int[] y) { System.Console.WriteLine(""void Test2(int x, params int[] y)""); } private void Test2(params int[] x) { System.Console.WriteLine(""void Test2(params int[] x)""); } private void Test3(int x, int y, params int[] z) { System.Console.WriteLine(""void Test3(int x, int y, params int[] z)""); } private void Test3(int x, params int[] y) { System.Console.WriteLine(""void Test3(int x, params int[] y)""); } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"void Test2(int x, params int[] y) void Test2(int x, params int[] y) void Test2(int x, params int[] y) void Test3(int x, int y, params int[] z) void Test3(int x, int y, params int[] z) void Test3(int x, int y, params int[] z)"); } [Fact, WorkItem(1157097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1157097"), WorkItem(2298, "https://github.com/dotnet/roslyn/issues/2298")] public void TieBreakOnNumberOfDeclaredParameters_02() { string source1 = @" namespace VS2015CompilerBug { public class VS2015CompilerBug { public static void Main() { (new VS2015CompilerBug()).Test2(1, 2); (new VS2015CompilerBug()).Test3(1, 2, 3); } private void Test2(int x = 0, int y = 0) { System.Console.WriteLine(""void Test2(int x = 0, int y = 0)""); } private void Test2(int x, int y = 0, int z = 0) { System.Console.WriteLine(""void Test2(int x, int y = 0, int z = 0)""); } private void Test3(int x, int y, int z = 0, int u = 0) { System.Console.WriteLine(""void Test3(int x, int y, int z = 0, int u = 0)""); } private void Test3(int x, int y = 0, int z = 0) { System.Console.WriteLine(""void Test3(int x, int y = 0, int z = 0)""); } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"void Test2(int x = 0, int y = 0) void Test3(int x, int y = 0, int z = 0)"); } [Fact, WorkItem(1157097, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1157097"), WorkItem(2298, "https://github.com/dotnet/roslyn/issues/2298")] public void TieBreakOnNumberOfDeclaredParameters_03() { string source1 = @" namespace VS2015CompilerBug { public class VS2015CompilerBug { public static void Main() { (new VS2015CompilerBug()).Test2(1); (new VS2015CompilerBug()).Test3(1, 2); } private void Test2(int x = 0, int y = 0) { } private void Test2(int x, int y = 0, int z = 0) { } private void Test3(int x, int y, int z = 0, int u = 0) { } private void Test3(int x, int y = 0, int z = 0) { } } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (9,39): error CS0121: The call is ambiguous between the following methods or properties: 'VS2015CompilerBug.Test2(int, int)' and 'VS2015CompilerBug.Test2(int, int, int)' // (new VS2015CompilerBug()).Test2(1); Diagnostic(ErrorCode.ERR_AmbigCall, "Test2").WithArguments("VS2015CompilerBug.VS2015CompilerBug.Test2(int, int)", "VS2015CompilerBug.VS2015CompilerBug.Test2(int, int, int)").WithLocation(9, 39), // (10,39): error CS0121: The call is ambiguous between the following methods or properties: 'VS2015CompilerBug.Test3(int, int, int, int)' and 'VS2015CompilerBug.Test3(int, int, int)' // (new VS2015CompilerBug()).Test3(1, 2); Diagnostic(ErrorCode.ERR_AmbigCall, "Test3").WithArguments("VS2015CompilerBug.VS2015CompilerBug.Test3(int, int, int, int)", "VS2015CompilerBug.VS2015CompilerBug.Test3(int, int, int)").WithLocation(10, 39) ); } [Fact, WorkItem(2533, "https://github.com/dotnet/roslyn/issues/2533")] public void TieBreakOnNumberOfDeclaredParameters_04() { string source1 = @" public class Test { static void M1(object o, object o1, string s, object o2 = null) { System.Console.WriteLine(""void M1(object o, object o1, string s, object o2 = null) ""); } static void M1(string s, object o1, object o2) { System.Console.WriteLine(""void M1(string s, object o1, object o2)""); } public static void Main() { M1(""M"", null, null); } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"void M1(string s, object o1, object o2)"); } [Fact, WorkItem(2533, "https://github.com/dotnet/roslyn/issues/2533")] public void TieBreakOnNumberOfDeclaredParameters_05() { string source1 = @" public class Test { static void M1(object o, object o1, string s) { } static void M1(string s, object o1, object o2) { } public static void Main() { M1(""M"", null, null); } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); compilation.VerifyDiagnostics( // (14,9): error CS0121: The call is ambiguous between the following methods or properties: 'Test.M1(object, object, string)' and 'Test.M1(string, object, object)' // M1("M", null, null); Diagnostic(ErrorCode.ERR_AmbigCall, "M1").WithArguments("Test.M1(object, object, string)", "Test.M1(string, object, object)").WithLocation(14, 9) ); } [Fact, WorkItem(4424, "https://github.com/dotnet/roslyn/issues/4424")] public void TieBreakOnNumberOfDeclaredParameters_06() { string source1 = @" class Test { static void Fn(string x = """", string y = """", params object[] p) { System.Console.WriteLine(1); } static void Fn(string x, params object[] p) { System.Console.WriteLine(2); } static void Main() { Fn(""Hello"", p: ""World""); } } "; var compilation = CreateCompilation(source1, options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @"2"); } [Fact, WorkItem(1099752, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1099752"), WorkItem(2291, "https://github.com/dotnet/roslyn/issues/2291")] public void BetterErrorMessage_01() { string source1 = @" class C { static void F1(object x, object y) { } static void F1(object x, object w, object z) { } static void F2(object x, object w, object z) { } static void F2(object x, object y) { } static void Main() { F1(x: 1, y: 2, z: 3); F2(x: 1, y: 2, z: 3); M1(0, x: 1); M2(0, x: 1); M3(0, x: 1); M4(0, x: 1); M5(0, x: 1); M6(0, x: 1); M7(0, x: 1); M9(0, x: 1); M8(0, x: 1); M10(0, x: 1); M11(x: 1, y: 2, z: 3); M12(1, 2, 3, 4); M13(1, 2, 3, 4); M14(1, 2, 3); M15(1, z: 0); M16(1, z: 0); M17(1, x: 2, y: 3); M18(1, x: 2, y: 3); M19(1, x: 2, y: 3); } static void M1() { } static void M2() { } static void M2(int u, int w) { } static void M3(int u, int w) { } static void M3() { } static void M4() { } static void M4(int u, int w) { } static void M4(int x) { } static void M5() { } static void M5(int x) { } static void M5(int u, int w) { } static void M6(int x) { } static void M6() { } static void M6(int u, int w) { } static void M7() { } static void M7(int u, int w) { } static void M7(int x) { } static void M7(int u, int x, int w) { } static void M8() { } static void M8(int u, int w) { } static void M8(int u, int x, int w) { } static void M8(int x) { } static void M9() { } static void M9(int u, int x, int w) { } static void M9(int u, int w) { } static void M9(int x) { } static void M10(int u, int x, int w) { } static void M10() { } static void M10(int u, int w) { } static void M10(int x) { } static void M11(object x, int y) { } static void M11(object x, short y) { } static void M12(object x, object y) { } static void M12(object x, object y, object z) { } static void M13(object x, object y, object z) { } static void M13(object x, object y) { } static void M14(object x, int y) { } static void M14(object x, short y) { } static void M15(object x, int y, object z = null) { } static void M15(object x, short y, object z = null) { } static void M16(object x, int y, object z = null) { } static void M16(object x, short y, object z = null) { } static void M17(object x, int y, int z) { } static void M17(object y, short x, int z) { } static void M18(object y, int x, int z) { } static void M18(object x, short y, int z) { } static void M19(object x, int y, int z) { } static void M19(object x, short y, int z) { } } "; var compilation = CreateCompilation(source1); compilation.VerifyDiagnostics( // (12,24): error CS1739: The best overload for 'F1' does not have a parameter named 'z' // F1(x: 1, y: 2, z: 3); Diagnostic(ErrorCode.ERR_BadNamedArgument, "z").WithArguments("F1", "z").WithLocation(12, 24), // (13,24): error CS1739: The best overload for 'F2' does not have a parameter named 'z' // F2(x: 1, y: 2, z: 3); Diagnostic(ErrorCode.ERR_BadNamedArgument, "z").WithArguments("F2", "z").WithLocation(13, 24), // (15,9): error CS1501: No overload for method 'M1' takes 2 arguments // M1(0, x: 1); Diagnostic(ErrorCode.ERR_BadArgCount, "M1").WithArguments("M1", "2").WithLocation(15, 9), // (17,15): error CS1739: The best overload for 'M2' does not have a parameter named 'x' // M2(0, x: 1); Diagnostic(ErrorCode.ERR_BadNamedArgument, "x").WithArguments("M2", "x").WithLocation(17, 15), // (18,15): error CS1739: The best overload for 'M3' does not have a parameter named 'x' // M3(0, x: 1); Diagnostic(ErrorCode.ERR_BadNamedArgument, "x").WithArguments("M3", "x").WithLocation(18, 15), // (20,15): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // M4(0, x: 1); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(20, 15), // (21,15): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // M5(0, x: 1); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(21, 15), // (22,15): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // M6(0, x: 1); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(22, 15), // (24,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'w' of 'C.M7(int, int, int)' // M7(0, x: 1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M7").WithArguments("w", "C.M7(int, int, int)").WithLocation(24, 9), // (25,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'w' of 'C.M9(int, int, int)' // M9(0, x: 1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M9").WithArguments("w", "C.M9(int, int, int)").WithLocation(25, 9), // (26,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'w' of 'C.M8(int, int, int)' // M8(0, x: 1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M8").WithArguments("w", "C.M8(int, int, int)").WithLocation(26, 9), // (27,9): error CS7036: There is no argument given that corresponds to the required formal parameter 'w' of 'C.M10(int, int, int)' // M10(0, x: 1); Diagnostic(ErrorCode.ERR_NoCorrespondingArgument, "M10").WithArguments("w", "C.M10(int, int, int)").WithLocation(27, 9), // (29,25): error CS1739: The best overload for 'M11' does not have a parameter named 'z' // M11(x: 1, y: 2, z: 3); Diagnostic(ErrorCode.ERR_BadNamedArgument, "z").WithArguments("M11", "z").WithLocation(29, 25), // (31,9): error CS1501: No overload for method 'M12' takes 4 arguments // M12(1, 2, 3, 4); Diagnostic(ErrorCode.ERR_BadArgCount, "M12").WithArguments("M12", "4").WithLocation(31, 9), // (32,9): error CS1501: No overload for method 'M13' takes 4 arguments // M13(1, 2, 3, 4); Diagnostic(ErrorCode.ERR_BadArgCount, "M13").WithArguments("M13", "4").WithLocation(32, 9), // (34,9): error CS1501: No overload for method 'M14' takes 3 arguments // M14(1, 2, 3); Diagnostic(ErrorCode.ERR_BadArgCount, "M14").WithArguments("M14", "3").WithLocation(34, 9), // (36,9): error CS1501: No overload for method 'M15' takes 2 arguments // M15(1, z: 0); Diagnostic(ErrorCode.ERR_BadArgCount, "M15").WithArguments("M15", "2").WithLocation(36, 9), // (37,9): error CS1501: No overload for method 'M16' takes 2 arguments // M16(1, z: 0); Diagnostic(ErrorCode.ERR_BadArgCount, "M16").WithArguments("M16", "2").WithLocation(37, 9), // (39,22): error CS1744: Named argument 'y' specifies a parameter for which a positional argument has already been given // M17(1, x: 2, y: 3); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "y").WithArguments("y").WithLocation(39, 22), // (40,22): error CS1744: Named argument 'y' specifies a parameter for which a positional argument has already been given // M18(1, x: 2, y: 3); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "y").WithArguments("y").WithLocation(40, 22), // (41,16): error CS1744: Named argument 'x' specifies a parameter for which a positional argument has already been given // M19(1, x: 2, y: 3); Diagnostic(ErrorCode.ERR_NamedArgumentUsedInPositional, "x").WithArguments("x").WithLocation(41, 16) ); } [Fact, WorkItem(2631, "https://github.com/dotnet/roslyn/issues/2631")] public void ArglistCompilerCrash() { var source = @"class Program { static void M(object x) { } static void M(object x, object y) { } static void M(object x, object y, object z) { } static void M(object x, object y, object z, __arglist) { } static void M(object x, params object[] args) { } static void Main(string[] args) { M(x: 1, y: 2, z: 3); } }"; var compilation = CreateCompilation(source); compilation.VerifyDiagnostics(); } [Fact, WorkItem(1171723, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1171723"), WorkItem(2985, "https://github.com/dotnet/roslyn/issues/2985")] public void BetterErrorMessage_02() { string source1 = @" using FluentAssertions; using Extensions; using System; using System.Collections.Generic; using System.Collections; namespace FluentAssertions { public static class AssertionExtensions { public static object Should(this object actualValue) { throw null; } public static object Should(this IEnumerable actualValue) { throw null; } public static object Should<T>(this IEnumerable<T> actualValue) { throw null; } public static object Should<TKey, TValue>(this IDictionary<TKey, TValue> actualValue) { throw null; } } } namespace Extensions { public static class TestExtensions { public static object Should<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> actualValue) { throw null; } } } namespace ClassLibraryOverloadResolution { public class Class1 { void goo() { Dictionary<String, String> dict = null; dict.Should(); } } }"; var compilation = CreateCompilationWithMscorlib45(source1); compilation.VerifyDiagnostics( // (34,18): error CS0121: The call is ambiguous between the following methods or properties: 'FluentAssertions.AssertionExtensions.Should<TKey, TValue>(System.Collections.Generic.IDictionary<TKey, TValue>)' and 'Extensions.TestExtensions.Should<TKey, TValue>(System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>)' // dict.Should(); Diagnostic(ErrorCode.ERR_AmbigCall, "Should").WithArguments("FluentAssertions.AssertionExtensions.Should<TKey, TValue>(System.Collections.Generic.IDictionary<TKey, TValue>)", "Extensions.TestExtensions.Should<TKey, TValue>(System.Collections.Generic.IReadOnlyDictionary<TKey, TValue>)").WithLocation(34, 18) ); } [Fact, WorkItem(4970, "https://github.com/dotnet/roslyn/issues/4970")] public void GenericExtensionMethodWithConstraintsAsADelegate() { var source = @" using System; public interface IDetail<T> { } public interface IMain<T> { } public class MyClass { static void Main() { Principal aPrincipal = new Principal(); Test(aPrincipal.RemoveDetail); Test(aPrincipal.RemoveDetail<Principal,Permission>); Action<Permission> a; a = aPrincipal.RemoveDetail; a(null); a = aPrincipal.RemoveDetail<Principal,Permission>; a(null); } static void Test(Action<Permission> a) { a(null); } } public class Permission : IDetail<Principal> { } public class Principal : IMain<Permission> { } public static class Class { public static void RemoveDetail<TMain, TChild>(this TMain main, TChild child) where TMain : class, IMain<TChild> where TChild : class, IDetail<TMain> { System.Console.WriteLine(""RemoveDetail""); } }"; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @"RemoveDetail RemoveDetail RemoveDetail RemoveDetail"); } [Fact, WorkItem(2544, "https://github.com/dotnet/roslyn/issues/2544")] public void GetSymbolInfo_Inaccessible() { var source = @" class C { private void M(D d) { d.M(1); } } class D { private void M(int i) { } private void M(double d) { } } "; var compilation = CreateCompilation(source, options: TestOptions.ReleaseDll); compilation.VerifyDiagnostics( // (6,11): error CS0122: 'D.M(int)' is inaccessible due to its protection level // d.M(1); Diagnostic(ErrorCode.ERR_BadAccess, "M").WithArguments("D.M(int)").WithLocation(6, 11) ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var callSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(callSyntax); Assert.Equal(CandidateReason.Inaccessible, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(2, candidates.Length); Assert.Equal("void D.M(System.Int32 i)", candidates[0].ToTestDisplayString()); Assert.Equal("void D.M(System.Double d)", candidates[1].ToTestDisplayString()); } [Fact, WorkItem(12061, "https://github.com/dotnet/roslyn/issues/12061")] public void RecursiveBetterBetterness01() { string source = @" delegate Del1 Del1(); delegate Del2 Del2(); class Program { static void Method(Del1 del1) { } static void Method(Del2 del2) { } static void Main() { Method(() => null); } } "; CreateCompilation(source).VerifyDiagnostics( // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(Del1)' and 'Program.Method(Del2)' // Method(() => null); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(Del1)", "Program.Method(Del2)").WithLocation(11, 9) ); } [Fact, WorkItem(12061, "https://github.com/dotnet/roslyn/issues/12061")] public void RecursiveBetterBetterness02() { string source = @" delegate Del2 Del1(); delegate Del1 Del2(); class Program { static void Method(Del1 del1) { } static void Method(Del2 del2) { } static void Main() { Method(() => null); } } "; CreateCompilation(source).VerifyDiagnostics( // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(Del1)' and 'Program.Method(Del2)' // Method(() => null); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(Del1)", "Program.Method(Del2)").WithLocation(11, 9) ); } [Fact, WorkItem(12061, "https://github.com/dotnet/roslyn/issues/12061")] public void RecursiveBetterBetterness03() { string source = @" delegate Del2<Del1<T>> Del1<T>(); delegate Del1<Del2<T>> Del2<T>(); class Program { static void Method(Del1<string> del1) { } static void Method(Del2<string> del2) { } static void Main() { Method(() => null); } } "; CreateCompilation(source).VerifyDiagnostics( // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(Del1<string>)' and 'Program.Method(Del2<string>)' // Method(() => null); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(Del1<string>)", "Program.Method(Del2<string>)").WithLocation(11, 9) ); } [Fact, WorkItem(12061, "https://github.com/dotnet/roslyn/issues/12061")] public void RecursiveBetterBetterness04() { string source = @" using System.Threading.Tasks; delegate Task<Del2> Del1(); delegate Task<Del1> Del2(); class Program { static void Method(Del1 del1) { } static void Method(Del2 del2) { } static void Main() { Method(() => null); } } "; CreateCompilationWithMscorlib40AndSystemCore(source).VerifyDiagnostics( // (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(Del1)' and 'Program.Method(Del2)' // Method(() => null); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(Del1)", "Program.Method(Del2)").WithLocation(12, 9) ); } [Fact, WorkItem(13380, "https://github.com/dotnet/roslyn/issues/13380")] public void ImplicitNullableOperatorInEquality() { string source = @"public class Class1 { public static void Main(string[] args) { var a = default(Registration<Something>); var x = (a == Something.Bad); //this line fails in VS2015.3 System.Console.WriteLine(x); } } public struct Registration<T> where T : struct { public static implicit operator T? (Registration<T> registration) { return null; } } public enum Something { Good, Bad }"; // should be NO errors. CompileAndVerify(source, expectedOutput: @"False"); } [Fact, WorkItem(16478, "https://github.com/dotnet/roslyn/issues/16478")] public void AmbiguousInference_01() { string source = @" using System; using System.Collections.Generic; public class Test { public static void Assert<T>(T a, T b) { Console.WriteLine(""Non collection""); } public static void Assert<T>(IEnumerable<T> a, IEnumerable<T> b) { Console.WriteLine(""Collection""); } public static void Main() { string[] a = new[] { ""A"" }; StringValues b = new StringValues(); Assert(a, b); Assert(b, a); } private class StringValues : List<string> { public static implicit operator StringValues(string[] values) { return new StringValues(); } public static implicit operator string[] (StringValues value) { return new string[0]; } } }"; CompileAndVerify(source, expectedOutput: @"Collection Collection"); } [Fact, WorkItem(16478, "https://github.com/dotnet/roslyn/issues/16478")] public void AmbiguousInference_02() { string source = @" using System; using System.Collections.Generic; public class Test { public static void Assert<T>(T a, T b) { Console.WriteLine(""Non collection""); } public static void Main() { string[] a = new[] { ""A"" }; StringValues b = new StringValues(); Assert(a, b); Assert(b, a); } private class StringValues : List<string> { public static implicit operator StringValues(string[] values) { return new StringValues(); } public static implicit operator string[] (StringValues value) { return new string[0]; } } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (17,9): error CS0411: The type arguments for method 'Test.Assert<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Assert(a, b); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Assert").WithArguments("Test.Assert<T>(T, T)").WithLocation(17, 9), // (18,9): error CS0411: The type arguments for method 'Test.Assert<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Assert(b, a); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Assert").WithArguments("Test.Assert<T>(T, T)").WithLocation(18, 9) ); } /// <summary> /// Inapplicable extension methods with bad arguments, with overloads where /// the instance argument can be converted to 'this' before overloads where the /// instance argument cannot be converted. Overload resolution should choose /// a method with convertible 'this', as with the native compiler. /// </summary> [Fact] public void InapplicableExtensionMethods_1() { string source = @"using System; class A { } class B { } class C { static void Main() { var a = new A(); a.F(o => {}, a); } } static class E { internal static void F(this A x, Action<object> y) { } internal static void F(this A x, Action<object> y, B z) { } internal static void F(this B x, Action<object> y) { } internal static void F(this B x, Action<object> y, A z) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (9,22): error CS1503: Argument 3: cannot convert from 'A' to 'B' // a.F(o => {}, a); Diagnostic(ErrorCode.ERR_BadArgType, "a").WithArguments("3", "A", "B").WithLocation(9, 22)); } /// <summary> /// Inapplicable extension methods with bad arguments, with overloads where /// the instance argument can be converted to 'this' after overloads where the /// instance argument cannot be converted. Overload resolution should choose /// a method where non-convertible 'this', as with the native compiler. /// </summary> [Fact] public void InapplicableExtensionMethods_2() { string source = @"using System; class A { } class B { } class C { static void Main() { var a = new A(); a.F(o => {}, a); } } static class E { internal static void F(this B x, Action<object> y) { } internal static void F(this B x, Action<object> y, A z) { } internal static void F(this A x, Action<object> y) { } internal static void F(this A x, Action<object> y, B z) { } }"; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (9,9): error CS1929: 'A' does not contain a definition for 'F' and the best extension method overload 'E.F(B, Action<object>, A)' requires a receiver of type 'B' // a.F(o => {}, a); Diagnostic(ErrorCode.ERR_BadInstanceArgType, "a").WithArguments("A", "F", "E.F(B, System.Action<object>, A)", "B").WithLocation(9, 9)); } [Fact] public void CircularImplicitConversions() { string source = @" class A { public static implicit operator B(A a) => null; } class B { public static implicit operator C(B b) => null; } class C { public static implicit operator A(C c) => null; } class D { public static implicit operator A(D d) => null; public static implicit operator B(D d) => null; public static implicit operator C(D d) => null; } class E { public static void F(A a) {} public static void F(B b) {} public static void F(C c) {} } public class Program { public static void Main() => E.F(new D()); } "; var comp = CreateCompilationWithMscorlib40AndSystemCore(source); comp.VerifyDiagnostics( // (28,36): error CS0121: The call is ambiguous between the following methods or properties: 'E.F(A)' and 'E.F(B)' // public static void Main() => E.F(new D()); Diagnostic(ErrorCode.ERR_AmbigCall, "F").WithArguments("E.F(A)", "E.F(B)").WithLocation(28, 36) ); var tree = comp.SyntaxTrees.Single(); var model = comp.GetSemanticModel(tree); var callSyntax = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbolInfo = model.GetSymbolInfo(callSyntax); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); var candidates = symbolInfo.CandidateSymbols; Assert.Equal(3, candidates.Length); Assert.Equal("void E.F(A a)", candidates[0].ToTestDisplayString()); Assert.Equal("void E.F(B b)", candidates[1].ToTestDisplayString()); Assert.Equal("void E.F(C c)", candidates[2].ToTestDisplayString()); } [Fact] public void PassingArgumentsToInParameters_RefKind_None() { var code = @" public static class Program { public static void Method(in int p) { System.Console.WriteLine(p); } public static void Main() { int x = 5; Method(x); } }"; CompileAndVerify(code, expectedOutput: "5"); } [Fact] public void PassingArgumentsToInParameters_RefKind_Ref() { var code = @" public static class Program { public static void Method(in int p) { System.Console.WriteLine(p); } public static void Main() { int x = 5; Method(ref x); } }"; CreateCompilation(code).VerifyDiagnostics( // (11,20): error CS1615: Argument 1 may not be passed with the 'ref' keyword // Method(ref x); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "x").WithArguments("1", "ref").WithLocation(11, 20)); } [Fact] public void PassingArgumentsToInParameters_RefKind_Out() { var code = @" public static class Program { public static void Method(in int p) { System.Console.WriteLine(p); } public static void Main() { int x; Method(out x); } }"; CreateCompilation(code).VerifyDiagnostics( // (11,20): error CS1615: Argument 1 may not be passed with the 'out' keyword // Method(out x); Diagnostic(ErrorCode.ERR_BadArgExtraRef, "x").WithArguments("1", "out").WithLocation(11, 20)); } [Fact] public void PassingArgumentsToInParameters_RefKind_In() { var code = @" public static class Program { public static void Method(in int p) { System.Console.WriteLine(p); } public static void Main() { int x = 5; Method(in x); } }"; CompileAndVerify(code, expectedOutput: "5"); } [WorkItem(20799, "https://github.com/dotnet/roslyn/issues/20799")] [Fact] public void PassingArgumentsToInParameters_RefKind_None_WrongType() { var code = @" public static class Program { public static void Method(in int p) { System.Console.WriteLine(p); } public static void Main() { System.Exception x = null; Method(x); } }"; CreateCompilation(code).VerifyDiagnostics( // (11,16): error CS1503: Argument 1: cannot convert from 'System.Exception' to 'in int' // Method(x); Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "System.Exception", "in int").WithLocation(11, 16) ); } [WorkItem(20799, "https://github.com/dotnet/roslyn/issues/20799")] [Fact] public void PassingArgumentsToRefParameters_RefKind_None_WrongType() { var code = @" public static class Program { public static void Method(ref int p) { System.Console.WriteLine(p); } public static void Main() { System.Exception x = null; Method(x); } }"; CreateCompilation(code).VerifyDiagnostics( // (11,16): error CS1620: Argument 1 must be passed with the 'ref' keyword // Method(x); Diagnostic(ErrorCode.ERR_BadArgRef, "x").WithArguments("1", "ref").WithLocation(11, 16) ); } [Fact] public void PassingInArgumentsOverloadedOnIn() { var code = @" public static class Program { public static void Method(in int x) { System.Console.WriteLine(""in: "" + x); } public static void Method(int x) { System.Console.WriteLine(""val: "" + x); } public static void Main() { int x = 5; Method(in x); Method(x); Method(5); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 5 val: 5 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_Inverse() { var code = @" public static class Program { public static void Method(int x) { System.Console.WriteLine(""val: "" + x); } public static void Method(in int x) { System.Console.WriteLine(""in: "" + x); } public static void Main() { int x = 5; Method(in x); Method(x); Method(5); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 5 val: 5 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_BinaryOperators() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(Test a, Test b) => ""val""; public static string operator +(in Test a, in Test b) => ""in""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_BinaryOperators_Inverse() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(in Test a, in Test b) => ""in""; public static string operator +(Test a, Test b) => ""val""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_UnaryOperators() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator !(Test a) => ""val""; public static string operator !(in Test a) => ""in""; } class Program { static void Main() { var a = new Test { Value = 1 }; Console.WriteLine(!a); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_UnaryOperators_Inverse() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator !(in Test a) => ""in""; public static string operator !(Test a) => ""val""; } class Program { static void Main() { var a = new Test { Value = 1 }; Console.WriteLine(!a); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_FirstArgument() { var code = @" public static class Program { public static void Method(in int x, int ignore) { System.Console.WriteLine(""in: "" + x); } public static void Method(int x, int ignore) { System.Console.WriteLine(""val: "" + x); } public static void Main() { int x = 5; Method(in x, 0); Method(x, 0); Method(5, 0); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 5 val: 5 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_FirstArgument_Inverse() { var code = @" public static class Program { public static void Method(int x, int ignore) { System.Console.WriteLine(""val: "" + x); } public static void Method(in int x, int ignore) { System.Console.WriteLine(""in: "" + x); } public static void Main() { int x = 5; Method(in x, 0); Method(x, 0); Method(5, 0); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 5 val: 5 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_FirstArgument_BinaryOperators() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(Test a, Test b) => ""val""; public static string operator +(in Test a, Test b) => ""in""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_FirstArgument_BinaryOperators_Inverse() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(in Test a, Test b) => ""in""; public static string operator +(Test a, Test b) => ""val""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_SecondArgument() { var code = @" public static class Program { public static void Method(int ignore, in int x) { System.Console.WriteLine(""in: "" + x); } public static void Method(int ignore, int x) { System.Console.WriteLine(""val: "" + x); } public static void Main() { int x = 5; Method(0, in x); Method(0, x); Method(0, 5); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 5 val: 5 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_SecondArgument_Inverse() { var code = @" public static class Program { public static void Method(int ignore, int x) { System.Console.WriteLine(""val: "" + x); } public static void Method(int ignore, in int x) { System.Console.WriteLine(""in: "" + x); } public static void Main() { int x = 5; Method(0, in x); Method(0, x); Method(0, 5); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 5 val: 5 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_SecondArgument_BinaryOperators() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(Test a, Test b) => ""val""; public static string operator +(Test a, in Test b) => ""in""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_SecondArgument_BinaryOperators_Inverse() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(Test a, in Test b) => ""in""; public static string operator +(Test a, Test b) => ""val""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }", expectedOutput: "val"); } [Fact] public void PassingInArgumentsOverloadedOnIn_ConflictingParameters() { var code = @" public static class Program { public static void Method(in int x, int y) { System.Console.WriteLine($""in {x} | val {y}""); } public static void Method(int x, in int y) { System.Console.WriteLine($""val {x} | in {y}""); } public static void Main() { int x = 1, y = 2; Method(x, in y); Method(in x, y); } }"; CompileAndVerify(code, expectedOutput: @" val 1 | in 2 in 1 | val 2 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_ConflictingParameters_Inverse() { var code = @" public static class Program { public static void Method(int x, in int y) { System.Console.WriteLine($""val {x} | in {y}""); } public static void Method(in int x, int y) { System.Console.WriteLine($""in {x} | val {y}""); } public static void Main() { int x = 1, y = 2; Method(x, in y); Method(in x, y); } }"; CompileAndVerify(code, expectedOutput: @" val 1 | in 2 in 1 | val 2 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_ConflictingParameters_Error() { var code = @" public static class Program { public static void Method(in int x, int y) { System.Console.WriteLine($""in {x} val {y}""); } public static void Method(int x, in int y) { System.Console.WriteLine($""val {x} in {y}""); } public static void Main() { int x = 1, y = 2; Method(x, y); Method(3, 4); } }"; CreateCompilation(code).VerifyDiagnostics( // (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(in int, int)' and 'Program.Method(int, in int)' // Method(x, y); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(in int, int)", "Program.Method(int, in int)").WithLocation(18, 9), // (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(in int, int)' and 'Program.Method(int, in int)' // Method(3, 4); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(in int, int)", "Program.Method(int, in int)").WithLocation(19, 9)); } [Fact] public void PassingInArgumentsOverloadedOnIn_ConflictingParameters_Error_Inverse() { var code = @" public static class Program { public static void Method(int x, in int y) { System.Console.WriteLine($""val {x} in {y}""); } public static void Method(in int x, int y) { System.Console.WriteLine($""in {x} val {y}""); } public static void Main() { int x = 1, y = 2; Method(x, y); Method(3, 4); } }"; CreateCompilation(code).VerifyDiagnostics( // (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(int, in int)' and 'Program.Method(in int, int)' // Method(x, y); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(int, in int)", "Program.Method(in int, int)").WithLocation(18, 9), // (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(int, in int)' and 'Program.Method(in int, int)' // Method(3, 4); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(int, in int)", "Program.Method(in int, int)").WithLocation(19, 9)); } [Fact] public void PassingInArgumentsOverloadedOnIn_ThreeConflictingParameters_Error() { var code = @" public static class Program { public static void Method(in int x, int y, in int z) { System.Console.WriteLine($""in {x} val {y} in {z}""); } public static void Method(int x, in int y, int z) { System.Console.WriteLine($""val {x} in {y} val {z}""); } public static void Main() { int x = 1, y = 2, z = 3; Method(x, y, z); Method(4, 5, 6); } }"; CreateCompilation(code).VerifyDiagnostics( // (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(in int, int, in int)' and 'Program.Method(int, in int, int)' // Method(x, y, z); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(in int, int, in int)", "Program.Method(int, in int, int)").WithLocation(18, 9), // (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(in int, int, in int)' and 'Program.Method(int, in int, int)' // Method(4, 5, 6); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(in int, int, in int)", "Program.Method(int, in int, int)").WithLocation(19, 9)); } [Fact] public void PassingInArgumentsOverloadedOnIn_ThreeConflictingParameters_Error_Inverse() { var code = @" public static class Program { public static void Method(int x, in int y, int z) { System.Console.WriteLine($""val {x} in {y} val {z}""); } public static void Method(in int x, int y, in int z) { System.Console.WriteLine($""in {x} val {y} in {z}""); } public static void Main() { int x = 1, y = 2, z = 3; Method(x, y, z); Method(4, 5, 6); } }"; CreateCompilation(code).VerifyDiagnostics( // (18,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(int, in int, int)' and 'Program.Method(in int, int, in int)' // Method(x, y, z); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(int, in int, int)", "Program.Method(in int, int, in int)").WithLocation(18, 9), // (19,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.Method(int, in int, int)' and 'Program.Method(in int, int, in int)' // Method(4, 5, 6); Diagnostic(ErrorCode.ERR_AmbigCall, "Method").WithArguments("Program.Method(int, in int, int)", "Program.Method(in int, int, in int)").WithLocation(19, 9)); } [Fact] public void PassingInArgumentsOverloadedOnIn_ConflictingParameters_Error_BinaryOperators() { CreateCompilation(@" using System; class Test { public int Value { get; set; } public static string operator +(in Test a, Test b) => ""left""; public static string operator +(Test a, in Test b) => ""right""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }").VerifyDiagnostics( // (15,27): error CS0034: Operator '+' is ambiguous on operands of type 'Test' and 'Test' // Console.WriteLine(a + b); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "a + b").WithArguments("+", "Test", "Test").WithLocation(15, 27)); } [Fact] public void PassingInArgumentsOverloadedOnIn_ConflictingParameters_Error_BinaryOperators_Inverse() { CreateCompilation(@" using System; class Test { public int Value { get; set; } public static string operator +(Test a, in Test b) => ""right""; public static string operator +(in Test a, Test b) => ""left""; } class Program { static void Main() { var a = new Test { Value = 1 }; var b = new Test { Value = 2 }; Console.WriteLine(a + b); } }").VerifyDiagnostics( // (15,27): error CS0034: Operator '+' is ambiguous on operands of type 'Test' and 'Test' // Console.WriteLine(a + b); Diagnostic(ErrorCode.ERR_AmbigBinaryOps, "a + b").WithArguments("+", "Test", "Test").WithLocation(15, 27)); } [Fact] public void PassingInArgumentsOverloadedOnIn_UnusedConflictingParameters() { var code = @" public static class Program { public static void Method(in int x, int y = 0) { System.Console.WriteLine($""in: {x}""); } public static void Method(int x, in int y = 0) { System.Console.WriteLine($""val: {x}""); } public static void Main() { int x = 1; Method(x); Method(in x); Method(2); } }"; CompileAndVerify(code, expectedOutput: @" val: 1 in: 1 val: 2"); } [Fact] public void PassingInArgumentsOverloadedOnIn_UnorderedNamedParameters() { var code = @" public static class Program { public static void Method(int a, int b) { System.Console.WriteLine($""val a: {a} | val b: {b}""); } public static void Method(in int b, int a) { System.Console.WriteLine($""in b: {b} | val a: {a}""); } public static void Main() { int a = 1, b = 2; Method(b: b, a: a); Method(a: a, b: in b); } }"; CompileAndVerify(code, expectedOutput: @" val a: 1 | val b: 2 in b: 2 | val a: 1"); } [Fact] public void PassingInArgumentsOverloadedOnIn_OptionalParameters() { var code = @" public static class Program { public static void Method(in int x, int op1 = 0, int op2 = 0) { System.Console.WriteLine(""in: "" + x); } public static void Method(int x, int op1 = 0, int op2 = 0, int op3 = 0) { System.Console.WriteLine(""val: "" + x); } public static void Main() { int x = 1; Method(x); Method(in x); Method(1); x = 2; Method(x, 0); Method(in x, 0); Method(2, 0); x = 3; Method(x, op3: 0); } }"; CompileAndVerify(code, expectedOutput: @" val: 1 in: 1 val: 1 val: 2 in: 2 val: 2 val: 3 "); } [Fact] public void PassingInArgumentsOverloadedOnIn_OptionalParameters_Error() { var code = @" public static class Program { public static void Method(in int x, int op1 = 0, int op2 = 0) { System.Console.WriteLine(""in: "" + x); } public static void Method(int x, int op1 = 0, int op2 = 0, int op3 = 0) { System.Console.WriteLine(""val: "" + x); } public static void Main() { int x = 1; Method(in x, op3: 0); // ERROR } }"; CreateCompilation(code).VerifyDiagnostics( // (17,19): error CS1615: Argument 1 may not be passed with the 'in' keyword // Method(in x, op3: 0); // ERROR Diagnostic(ErrorCode.ERR_BadArgExtraRef, "x").WithArguments("1", "in").WithLocation(17, 19)); } [Fact] public void PassingInArgumentsOverloadedOnIn_Named() { var code = @" public static class Program { public static void Method(in int inP) { System.Console.WriteLine(""in: "" + inP); } public static void Method(int valP) { System.Console.WriteLine(""val: "" + valP); } public static void Main() { int x = 5; Method(in x); Method(valP: 3); Method(inP: 2); } }"; CompileAndVerify(code, expectedOutput: @" in: 5 val: 3 in: 2 "); } [Fact] public void PassingInArgumentsOverloadedOnInErr() { var code = @" public static class Program { public static void Method(in int inP) { System.Console.WriteLine(""in: "" + inP); } public static void Method(int valP) { System.Console.WriteLine(""val: "" + valP); } public static void Main() { byte x = 5; Method(in x); Method('Q'); Method(3); Method(valP: out 2); Method(valP: in 2); } }"; CreateCompilation(code).VerifyDiagnostics( // (17,19): error CS1503: Argument 1: cannot convert from 'in byte' to 'in int' // Method(in x); Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "in byte", "in int").WithLocation(17, 19), // (20,26): error CS1510: A ref or out value must be an assignable variable // Method(valP: out 2); Diagnostic(ErrorCode.ERR_RefLvalueExpected, "2").WithLocation(20, 26), // (21,25): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // Method(valP: in 2); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "2").WithLocation(21, 25) ); } [Fact] public void PassingInArgumentsOverloadedOnInIndexer() { var code = @" public class Program { public int this[in int inP] { get { System.Console.WriteLine(""in: "" + inP); return 1; } } public int this[int valP] { get { System.Console.WriteLine(""val: "" + valP); return 1; } } public static void Main() { var p = new Program(); int x = 5; _ = p[0]; _ = p[x]; _ = p[in x]; _ = p[valP: 3]; _ = p[inP: 2]; } } "; CompileAndVerify(code, expectedOutput: @" val: 0 val: 5 in: 5 val: 3 in: 2 "); } [Fact] public void PassingInArgumentsOverloadedOnInIndexerErr() { var code = @" public class Program { public int this[in int inP] { get { System.Console.WriteLine(""in: "" + inP); return 1; } } public int this[int valP] { get { System.Console.WriteLine(""val: "" + valP); return 1; } } public static void Main() { var p = new Program(); byte x = 5; _ = p[in x]; _ = p['Q']; _ = p[3]; _ = p[valP: out 2]; _ = p[inP: in 2]; } }"; CreateCompilation(code).VerifyDiagnostics( // (27,18): error CS1503: Argument 1: cannot convert from 'in byte' to 'in int' // _ = p[in x]; Diagnostic(ErrorCode.ERR_BadArgType, "x").WithArguments("1", "in byte", "in int").WithLocation(27, 18), // (30,25): error CS1510: A ref or out value must be an assignable variable // _ = p[valP: out 2]; Diagnostic(ErrorCode.ERR_RefLvalueExpected, "2").WithLocation(30, 25), // (31,23): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // _ = p[inP: in 2]; Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "2").WithLocation(31, 23)); } [Fact] public void PassingInArgumentsOverloadedOnInOptionalParameters() { var code = @" public static class Program { public static void Method(in int inP = 0) { System.Console.WriteLine(""in: "" + inP); } public static void Method(int valP = 0) { System.Console.WriteLine(""val: "" + valP); } public static void Main() { Method(valP: 1); Method(inP: 2); int x = 3; Method(in x); } }"; CompileAndVerify(code, expectedOutput: @" val: 1 in: 2 in: 3 "); } [Fact] public void PassingInArgumentsOverloadedOnInParams() { var code = @" using System; class Program { void M(in int x) { Console.WriteLine(""in: "" + x); } void M(params int[] p) { Console.WriteLine(""params: "" + p.Length); } static void Main() { var p = new Program(); p.M(); p.M(1); p.M(1, 2); int x = 3; p.M(in x); } }"; CompileAndVerify(code, expectedOutput: @"params: 0 in: 1 params: 2 in: 3"); } [Fact] public void PassingInArgumentsOverloadedOnInParams_Array() { var code = @" using System; class Program { void M(in int[] p) { Console.WriteLine(""in: "" + p.Length); } void M(params int[] p) { Console.WriteLine(""params: "" + p.Length); } static void Main() { var p = new Program(); p.M(); p.M(1); p.M(1, 2); var x = new int[] { }; p.M(x); p.M(in x); p.M(new int[] { }); x = new int[] { 1 }; p.M(x); p.M(in x); p.M(new int[] { 1 }); } }"; CompileAndVerify(code, expectedOutput: @"params: 0 params: 1 params: 2 params: 0 in: 0 params: 0 params: 1 in: 1 params: 1"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_ExtensionMethods() { CompileAndVerify(@" using System; static class Extensions { public static void M(this Program instance, in int x) { Console.WriteLine(""in: "" + x); } } class Program { void M(int x) { Console.WriteLine(""val: "" + x); } static void Main() { var instance = new Program(); int x = 1; instance.M(x); x = 2; instance.M(in x); instance.M(3); } }", expectedOutput: @"val: 1 in: 2 val: 3"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_Indexers() { CompileAndVerify(@" using System; class Program { public string this[int x] => ""val: "" + x; public string this[in int x] => ""in: "" + x; static void Main() { var instance = new Program(); int x = 1; Console.WriteLine(instance[x]); x = 2; Console.WriteLine(instance[in x]); Console.WriteLine(instance[3]); } }", expectedOutput: @"val: 1 in: 2 val: 3"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_TypeConversions_In() { CompileAndVerify(@" using System; class Program { static void M(in byte x) { Console.WriteLine(""in: "" + x); } static void M(int x) { Console.WriteLine(""val: "" + x); } static void Main() { M(0); int intX = 1; byte byteX = 1; M(intX); M(byteX); M((int)2); M((byte)2); } }", expectedOutput: @" val: 0 val: 1 in: 1 val: 2 in: 2"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_TypeConversions_Val() { CompileAndVerify(@" using System; class Program { static void M(byte x) { Console.WriteLine(""val: "" + x); } static void M(in int x) { Console.WriteLine(""in: "" + x); } static void Main() { M(0); int intX = 1; byte byteX = 1; M(intX); M(byteX); M((int)2); M((byte)2); } }", expectedOutput: @" in: 0 in: 1 val: 1 in: 2 val: 2"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_TypeConversions_BinaryOperators() { CompileAndVerify(@" using System; class Test { public int Value { get; set; } public static string operator +(int a, Test b) => ""val""; public static string operator +(in byte a, Test b) => ""in""; } class Program { static void Main() { int intX = 1; byte byteX = 1; var b = new Test { Value = 2 }; Console.WriteLine(intX + b); Console.WriteLine(byteX + b); Console.WriteLine(1 + b); Console.WriteLine(((byte)1) + b); } }", expectedOutput: @" val in val in"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_TypeConversions_NonConvertible() { CompileAndVerify(@" using System; using System.Text; class Program { static void M(string x) { Console.WriteLine(""val""); } static void M(in StringBuilder x) { Console.WriteLine(""in""); } static void Main() { M(null); } }", expectedOutput: "val"); } [Fact] public void PassingArgumentsToOverloadsOfByValAndInParameters_TypeConversions_NonConvertible_Error() { CreateCompilation(@" using System; using System.Text; class Program { static void M(string x) { Console.WriteLine(""val""); } static void M(StringBuilder x) { Console.WriteLine(""in""); } static void Main() { M(null); } }").VerifyDiagnostics( // (11,9): error CS0121: The call is ambiguous between the following methods or properties: 'Program.M(string)' and 'Program.M(StringBuilder)' // M(null); Diagnostic(ErrorCode.ERR_AmbigCall, "M").WithArguments("Program.M(string)", "Program.M(System.Text.StringBuilder)").WithLocation(11, 9)); } [Fact] public void GenericInferenceOnIn() { var code = @" using System; class Program { public static void M1<T>(in T arg1, in T arg2) { System.Console.WriteLine(typeof(T).ToString()); } static void Main() { int x = 1; byte y = 2; M1(null, (string)null); M1(default, 1); M1(new Object(), new Exception()); M1(new Object(), 1); M1(in x, in x); // valid, same type M1(y, in x); // valid, byval x sets lower bound, byte converts to int } } "; CompileAndVerify(code, expectedOutput: @" System.String System.Int32 System.Object System.Object System.Int32 System.Int32 "); } [Fact] public void GenericInferenceOnInErr() { var code = @" class Program { public static void M1<T>(in T arg1, in T arg2) { System.Console.WriteLine(typeof(T).ToString()); } static void Main() { int x = 1; byte y = 2; var rl = default(RefLike); M1(null, null); M1(null, 1); M1(new object(), default(RefLike)); M1(rl, rl); M1(in rl, in rl); M1(in y, in x); M1(in y, x); } ref struct RefLike{} } "; CreateCompilation(code).VerifyDiagnostics( // (15,9): error CS0411: The type arguments for method 'Program.M1<T>(in T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1(null, null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(in T, in T)").WithLocation(15, 9), // (16,12): error CS1503: Argument 1: cannot convert from '<null>' to 'in int' // M1(null, 1); Diagnostic(ErrorCode.ERR_BadArgType, "null").WithArguments("1", "<null>", "in int").WithLocation(16, 12), // (17,9): error CS0411: The type arguments for method 'Program.M1<T>(in T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1(new object(), default(RefLike)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(in T, in T)").WithLocation(17, 9), // (19,9): error CS0306: The type 'Program.RefLike' may not be used as a type argument // M1(rl, rl); Diagnostic(ErrorCode.ERR_BadTypeArgument, "M1").WithArguments("Program.RefLike").WithLocation(19, 9), // (20,9): error CS0306: The type 'Program.RefLike' may not be used as a type argument // M1(in rl, in rl); Diagnostic(ErrorCode.ERR_BadTypeArgument, "M1").WithArguments("Program.RefLike").WithLocation(20, 9), // (22,9): error CS0411: The type arguments for method 'Program.M1<T>(in T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1(in y, in x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(in T, in T)").WithLocation(22, 9), // (23,9): error CS0411: The type arguments for method 'Program.M1<T>(in T, in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1(in y, x); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(in T, in T)").WithLocation(23, 9) ); } [Fact] public void GenericInferenceOnInTuples() { var code = @" using System; class Program { public static void Method<T>(in (T arg1, T arg2) p) { System.Console.WriteLine(typeof(T).ToString()); } static void Main() { int x = 1; byte y = 2; Method((null, (string)null)); Method((default, x)); Method((new Object(), new Exception())); Method((new Object(), x)); Method((x, x)); // valid, same type Method((y, x)); // valid, byval x sets lower bound, byte converts to int } } "; CompileAndVerifyWithMscorlib40(code, references: new[] { SystemRuntimeFacadeRef, ValueTupleRef }, expectedOutput: @" System.String System.Int32 System.Object System.Object System.Int32 System.Int32 "); } [Fact] public void GenericInferenceOnInErrTuples() { var code = @" class Program { public static void Method<T>(in (T arg1, T arg2) p) { System.Console.WriteLine(typeof(T).ToString()); } static void Main() { int x = 1; byte y = 2; var rl = default(RefLike); Method((null, null)); Method((null, 1)); Method((new object(), default(RefLike))); Method((rl, rl)); Method(in (rl, rl)); Method(in (y, x)); } ref struct RefLike{} } "; CreateCompilationWithMscorlib40(code, references: new[] { SystemRuntimeFacadeRef, ValueTupleRef }).VerifyDiagnostics( // (15,9): error CS0411: The type arguments for method 'Program.Method<T>(in (T arg1, T arg2))' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Method((null, null)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Method").WithArguments("Program.Method<T>(in (T arg1, T arg2))").WithLocation(15, 9), // (16,16): error CS1503: Argument 1: cannot convert from '(<null>, int)' to 'in (int arg1, int arg2)' // Method((null, 1)); Diagnostic(ErrorCode.ERR_BadArgType, "(null, 1)").WithArguments("1", "(<null>, int)", "in (int arg1, int arg2)").WithLocation(16, 16), // (17,31): error CS0306: The type 'Program.RefLike' may not be used as a type argument // Method((new object(), default(RefLike))); Diagnostic(ErrorCode.ERR_BadTypeArgument, "default(RefLike)").WithArguments("Program.RefLike").WithLocation(17, 31), // (17,9): error CS0411: The type arguments for method 'Program.Method<T>(in (T arg1, T arg2))' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Method((new object(), default(RefLike))); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Method").WithArguments("Program.Method<T>(in (T arg1, T arg2))").WithLocation(17, 9), // (19,17): error CS0306: The type 'Program.RefLike' may not be used as a type argument // Method((rl, rl)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "rl").WithArguments("Program.RefLike").WithLocation(19, 17), // (19,21): error CS0306: The type 'Program.RefLike' may not be used as a type argument // Method((rl, rl)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "rl").WithArguments("Program.RefLike").WithLocation(19, 21), // (19,9): error CS0306: The type 'Program.RefLike' may not be used as a type argument // Method((rl, rl)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "Method").WithArguments("Program.RefLike").WithLocation(19, 9), // (20,20): error CS0306: The type 'Program.RefLike' may not be used as a type argument // Method(in (rl, rl)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "rl").WithArguments("Program.RefLike").WithLocation(20, 20), // (20,24): error CS0306: The type 'Program.RefLike' may not be used as a type argument // Method(in (rl, rl)); Diagnostic(ErrorCode.ERR_BadTypeArgument, "rl").WithArguments("Program.RefLike").WithLocation(20, 24), // (20,19): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // Method(in (rl, rl)); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "(rl, rl)").WithLocation(20, 19), // (22,19): error CS8156: An expression cannot be used in this context because it may not be passed or returned by reference // Method(in (y, x)); Diagnostic(ErrorCode.ERR_RefReturnLvalueExpected, "(y, x)").WithLocation(22, 19)); } [Fact] public void GenericInferenceErrorRecovery() { var code = @" class Program { public static void Method<T>(in T p) { System.Console.WriteLine(typeof(T).ToString()); } static void Main() { Method((null, 1)); } } "; var comp = CreateCompilation(code); comp.VerifyDiagnostics( // (11,9): error CS0411: The type arguments for method 'Program.Method<T>(in T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // Method((null, 1)); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "Method").WithArguments("Program.Method<T>(in T)").WithLocation(11, 9)); } [Fact] public void GenericInferenceLambdaVariance() { var code = @" class Program { public delegate void D1<T>(in T arg1, in T arg2); public static void M1<T>(T arg1, T arg2) { System.Console.WriteLine(typeof(T).ToString()); } static void Main() { M1((in int arg1, in int arg2) => throw null, (in int arg1, in int arg2) => throw null); } } "; CreateCompilation(code).VerifyDiagnostics( // (13,9): error CS0411: The type arguments for method 'Program.M1<T>(T, T)' cannot be inferred from the usage. Try specifying the type arguments explicitly. // M1((in int arg1, in int arg2) => throw null, (in int arg1, in int arg2) => throw null); Diagnostic(ErrorCode.ERR_CantInferMethTypeArgs, "M1").WithArguments("Program.M1<T>(T, T)").WithLocation(13, 9) ); } [Fact] public void DelegateConversions() { var librarySrc = @" public class C { public void RR_input(in int x) => throw null; public ref readonly int RR_output() => throw null; public ref readonly int P => throw null; public ref readonly int this[in int i] => throw null; public delegate ref readonly int Delegate(in int i); } public static class Extensions { public static void RR_extension(in this int x) => throw null; public static void R_extension(ref this int x) => throw null; } "; var libComp = CreateCompilationWithMscorlib40(librarySrc, references: new[] { TestMetadata.Net40.SystemCore }).VerifyDiagnostics(); var code = @" class D { void M(C c, in int y) { c.RR_input(y); VerifyRR(c.RR_output()); VerifyRR(c.P); VerifyRR(c[y]); C.Delegate x = VerifyDelegate; y.RR_extension(); 1.RR_extension(); y.R_extension(); // error 1 1.R_extension(); // error 2 } void VerifyRR(in int y) => throw null; ref readonly int VerifyDelegate(in int y) => throw null; } "; CreateCompilation(code, references: new[] { libComp.EmitToImageReference() }).VerifyDiagnostics( // (13,10): error CS8329: Cannot use variable 'in int' as a ref or out value because it is a readonly variable // y.R_extension(); // error 1 Diagnostic(ErrorCode.ERR_RefReadonlyNotField, "y").WithArguments("variable", "in int").WithLocation(13, 10), // (14,10): error CS1510: A ref or out value must be an assignable variable // 1.R_extension(); // error 2 Diagnostic(ErrorCode.ERR_RefLvalueExpected, "1").WithLocation(14, 10) ); CreateCompilation(code, references: new[] { libComp.ToMetadataReference() }).VerifyDiagnostics( // (13,10): error CS8329: Cannot use variable 'in int' as a ref or out value because it is a readonly variable // y.R_extension(); // error 1 Diagnostic(ErrorCode.ERR_RefReadonlyNotField, "y").WithArguments("variable", "in int").WithLocation(13, 10), // (14,10): error CS1510: A ref or out value must be an assignable variable // 1.R_extension(); // error 2 Diagnostic(ErrorCode.ERR_RefLvalueExpected, "1").WithLocation(14, 10) ); } [Fact] public void MethodGroupConversionVal2In() { var code = @" using System; class Program { static void F(in DateTime x) { Console.WriteLine(x); } static void Main() { Action<DateTime> a = F; a(DateTime.MaxValue); } } "; CreateCompilation(code).VerifyDiagnostics( // (13,30): error CS0123: No overload for 'F' matches delegate 'Action<DateTime>' // Action<DateTime> a = F; Diagnostic(ErrorCode.ERR_MethDelegateMismatch, "F").WithArguments("F", "System.Action<System.DateTime>").WithLocation(13, 30) ); } [Fact] public void MethodGroupConversionVal2Overloaded() { var code = @" using System; class Program { static void F(in DateTime x) { Console.WriteLine('1'); } static void F(DateTime x) { Console.WriteLine('2'); } static void Main() { Action<DateTime> a = F; a(DateTime.MaxValue); } } "; CompileAndVerify(code, expectedOutput: @"2"); } [Fact] public void MethodGroupConversionIn2Overloaded() { var code = @" using System; class Program { delegate void D(in DateTime d); static void F(in DateTime x) { Console.WriteLine('1'); } static void F(DateTime x) { Console.WriteLine('2'); } static void Main() { D a = F; a(DateTime.MaxValue); } } "; CompileAndVerify(code, expectedOutput: @"1", verify: Verification.Fails); } [Fact] public void MethodGroupConversionRoReadonlyReturn() { var code = @" using System; class Program { delegate int D(in DateTime d); static ref readonly int F(in DateTime x) { Console.WriteLine('1'); return ref (new int[1])[0]; } static void Main() { D a = F; a(DateTime.MaxValue); } } "; CreateCompilation(code).VerifyDiagnostics ( // (16,15): error CS8189: Ref mismatch between 'Program.F(in DateTime)' and delegate 'Program.D' // D a = F; Diagnostic(ErrorCode.ERR_DelegateRefMismatch, "F").WithArguments("Program.F(in System.DateTime)", "Program.D").WithLocation(16, 15) ); } [Fact] public void MethodGroupConversionRoReadonlyReturnType() { var code = @" using System; class Program { delegate ref readonly object D(in DateTime d); static ref readonly string F(in DateTime x) { Console.WriteLine('1'); return ref (new string[1])[0]; } static void Main() { D a = F; a(DateTime.MaxValue); } } "; CreateCompilation(code).VerifyDiagnostics ( // (16,15): error CS0407: 'string Program.F(in DateTime)' has the wrong return type // D a = F; Diagnostic(ErrorCode.ERR_BadRetType, "F").WithArguments("Program.F(in System.DateTime)", "string").WithLocation(16, 15) ); } [Fact, WorkItem(25813, "https://github.com/dotnet/roslyn/issues/25813")] public void InaccessibleExtensionMethod() { var code = @" using System; using System.Collections.Generic; using System.Linq; public class Program { static void Main(string[] args) { var a = new[] { 0, 1, 3 }; var b = new[] { 1, 2, 3, 4, 5 }; Console.WriteLine(b.Count(a.Contains)); } } public static class Extensions { // NOTE: private access modifier simulates internal class public method in referenced assembly. private static bool Contains<T>(this System.Collections.Generic.IEnumerable<T> a, T value) => throw new NotImplementedException(); }"; CompileAndVerify(code, expectedOutput: @"2"); } [Fact] public void GenericTypeOverriddenMethod() { var source0 = @"public class Base<TKey, TValue> where TKey : class where TValue : class { public virtual TValue F(TKey key) => throw null; }"; var source1 = @"public class A { } public class Derived<TValue> : Base<A, TValue> where TValue : class { public override TValue F(A key) => throw null; }"; var source2 = @"class B { } class Program { static void M(Derived<B> d, A a) { _ = d.F(a); } }"; var comp = CreateCompilation(new[] { source0, source1, source2 }); comp.VerifyEmitDiagnostics(); verify(comp, comp.SyntaxTrees[2]); var ref0 = CreateCompilation(source0).EmitToImageReference(); var ref1 = CreateCompilation(source1, references: new[] { ref0 }).EmitToImageReference(); comp = CreateCompilation(source2, references: new[] { ref0, ref1 }); comp.VerifyEmitDiagnostics(); verify(comp, comp.SyntaxTrees[0]); static void verify(CSharpCompilation comp, SyntaxTree tree) { var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(expr).Symbol.GetSymbol<MethodSymbol>(); Assert.Equal("B Derived<B>.F(A key)", symbol.ToTestDisplayString()); symbol = symbol.GetLeastOverriddenMethod(accessingTypeOpt: null); Assert.Equal("B Base<A, B>.F(A key)", symbol.ToTestDisplayString()); } } [Fact] [WorkItem(46549, "https://github.com/dotnet/roslyn/issues/46549")] public void GenericTypeOverriddenProperty() { var source0 = @"public class Base<TKey, TValue> where TKey : class where TValue : class { public virtual TValue this[TKey key] => throw null; }"; var source1 = @"public class A { } public class Derived<TValue> : Base<A, TValue> where TValue : class { public override TValue this[A key] => throw null; }"; var source2 = @"class B { } class Program { static void M(Derived<B> d, A a) { _ = d[a]; } }"; var comp = CreateCompilation(new[] { source0, source1, source2 }); comp.VerifyEmitDiagnostics(); verify(comp, comp.SyntaxTrees[2]); var ref0 = CreateCompilation(source0).EmitToImageReference(); var ref1 = CreateCompilation(source1, references: new[] { ref0 }).EmitToImageReference(); comp = CreateCompilation(source2, references: new[] { ref0, ref1 }); comp.VerifyEmitDiagnostics(); verify(comp, comp.SyntaxTrees[0]); static void verify(CSharpCompilation comp, SyntaxTree tree) { var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<ElementAccessExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(expr).Symbol.GetSymbol<PropertySymbol>(); Assert.Equal("B Derived<B>.this[A key] { get; }", symbol.ToTestDisplayString()); symbol = symbol.GetLeastOverriddenProperty(accessingTypeOpt: null); Assert.Equal("B Base<A, B>.this[A key] { get; }", symbol.ToTestDisplayString()); } } [Fact] [WorkItem(46549, "https://github.com/dotnet/roslyn/issues/46549")] public void GenericTypeOverriddenEvent() { var source0 = @"public delegate TValue D<TKey, TValue>(TKey key); public abstract class Base<TKey, TValue> where TKey : class where TValue : class { public abstract event D<TKey, TValue> E; }"; var source1 = @"public class A { } public class Derived<TValue> : Base<A, TValue> where TValue : class { public override event D<A, TValue> E { add { } remove { } } }"; var source2 = @"class B { } class Program { static void M(Derived<B> d, A a) { d.E += (A a) => default(B); } }"; var comp = CreateCompilation(new[] { source0, source1, source2 }); comp.VerifyEmitDiagnostics(); verify(comp, comp.SyntaxTrees[2]); var ref0 = CreateCompilation(source0).EmitToImageReference(); var ref1 = CreateCompilation(source1, references: new[] { ref0 }).EmitToImageReference(); comp = CreateCompilation(source2, references: new[] { ref0, ref1 }); comp.VerifyEmitDiagnostics(); verify(comp, comp.SyntaxTrees[0]); static void verify(CSharpCompilation comp, SyntaxTree tree) { var model = comp.GetSemanticModel(tree); var expr = tree.GetRoot().DescendantNodes().OfType<MemberAccessExpressionSyntax>().Single(); var symbol = model.GetSymbolInfo(expr).Symbol.GetSymbol<EventSymbol>(); Assert.Equal("event D<A, B> Derived<B>.E", symbol.ToTestDisplayString()); symbol = symbol.GetLeastOverriddenEvent(accessingTypeOpt: null); Assert.Equal("event D<A, B> Base<A, B>.E", symbol.ToTestDisplayString()); } } [Fact] [WorkItem(52701, "https://github.com/dotnet/roslyn/issues/52701")] public void Issue52701_01() { var source = @" class A { internal void F<T>(T t) where T : class {} } class B : A { internal new void F<T>(T t) where T : struct { } void M() { System.Action<object> d = F<object>; } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,35): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // System.Action<object> d = F<object>; Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(11, 35) ); } [Fact] [WorkItem(52701, "https://github.com/dotnet/roslyn/issues/52701")] public void Issue52701_02() { var source = @" class A { internal void F<T>(T t) where T : class {} } class B : A { internal new void F<T>(T t) where T : struct { } void M() { F<object>(default); } } "; var comp = CreateCompilation(source); comp.VerifyDiagnostics( // (11,9): error CS0453: The type 'object' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'B.F<T>(T)' // F<object>(default); Diagnostic(ErrorCode.ERR_ValConstraintNotSatisfied, "F<object>").WithArguments("B.F<T>(T)", "T", "object").WithLocation(11, 9) ); } } }
1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayFormat.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Describes the formatting rules that should be used when displaying symbols. /// </summary> public class SymbolDisplayFormat { /// <summary> /// Formats a symbol description as in a C# compiler error message. /// </summary> public static SymbolDisplayFormat CSharpErrorMessageFormat { get; } = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, // Not showing the name is important because we visit parameters to display their // types. If we visited their types directly, we wouldn't get ref/out/params. miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); /// <summary> /// Formats a symbol description as in a C# compiler short error message. /// </summary> public static SymbolDisplayFormat CSharpShortErrorMessageFormat { get; } = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, // Not showing the name is important because we visit parameters to display their // types. If we visited their types directly, we wouldn't get ref/out/params. miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); /// <summary> /// Formats a symbol description as in a Visual Basic compiler error message. /// </summary> public static SymbolDisplayFormat VisualBasicErrorMessageFormat { get; } = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef | SymbolDisplayMemberOptions.IncludeModifiers, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeOptionalBrackets | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); /// <summary> /// Formats a symbol description as in a Visual Basic compiler short error message. /// </summary> public static SymbolDisplayFormat VisualBasicShortErrorMessageFormat { get; } = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef | SymbolDisplayMemberOptions.IncludeModifiers, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeOptionalBrackets | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); /// <summary> /// Formats the names of all types and namespaces in a fully qualified style (including the global alias). /// </summary> public static SymbolDisplayFormat FullyQualifiedFormat { get; } = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); /// <summary> /// Formats a symbol description in a form that suits <see cref="ISymbol.ToMinimalDisplayString"/>. /// </summary> public static SymbolDisplayFormat MinimallyQualifiedFormat { get; } = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef | SymbolDisplayMemberOptions.IncludeContainingType, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeDefaultValue, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); /// <summary> /// A verbose format for displaying symbols (useful for testing). /// </summary> internal static readonly SymbolDisplayFormat TestFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, localOptions: SymbolDisplayLocalOptions.IncludeType, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef | SymbolDisplayMemberOptions.IncludeExplicitInterface, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions: SymbolDisplayParameterOptions.IncludeOptionalBrackets | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeScriptType | SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames | SymbolDisplayCompilerInternalOptions.FlagMissingMetadataTypes | SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers); /// <summary> /// A verbose format for displaying symbols (useful for testing). /// </summary> internal static readonly SymbolDisplayFormat TestFormatWithConstraints = TestFormat.WithGenericsOptions(TestFormat.GenericsOptions | SymbolDisplayGenericsOptions.IncludeTypeConstraints). AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier). WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None); /// <summary> /// this.QualifiedNameOnly = containingSymbol.QualifiedNameOnly + "." + this.Name /// </summary> internal static readonly SymbolDisplayFormat QualifiedNameOnlyFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); /// <summary> /// this.QualifiedNameArity = containingSymbol.QualifiedNameArity + "." + this.Name + "`" + this.Arity /// </summary> internal static readonly SymbolDisplayFormat QualifiedNameArityFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes | SymbolDisplayCompilerInternalOptions.UseValueTuple); /// <summary> /// A succinct format for displaying symbols. /// </summary> internal static readonly SymbolDisplayFormat ShortFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, parameterOptions: SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); /// <summary> /// The format used for displaying symbols when visualizing IL. /// </summary> internal static readonly SymbolDisplayFormat ILVisualizationFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames | SymbolDisplayCompilerInternalOptions.UseValueTuple); /// <summary> /// Used to normalize explicit interface implementation member names. /// Only expected to be applied to interface types (and their type arguments). /// </summary> internal static readonly SymbolDisplayFormat ExplicitInterfaceImplementationFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.ReverseArrayRankSpecifiers); /// <summary> /// Determines how the global namespace is displayed. /// </summary> public SymbolDisplayGlobalNamespaceStyle GlobalNamespaceStyle { get; } /// <summary> /// Determines how types are qualified (e.g. Nested vs Containing.Nested vs Namespace.Containing.Nested). /// </summary> public SymbolDisplayTypeQualificationStyle TypeQualificationStyle { get; } /// <summary> /// Determines how generics (on types and methods) should be described (i.e. the level of detail). /// </summary> public SymbolDisplayGenericsOptions GenericsOptions { get; } /// <summary> /// Determines how fields, properties, events, and methods are displayed. /// </summary> public SymbolDisplayMemberOptions MemberOptions { get; } /// <summary> /// Determines how parameters (of methods, properties/indexers, and delegates) are displayed. /// </summary> public SymbolDisplayParameterOptions ParameterOptions { get; } /// <summary> /// Determines how delegates are displayed (e.g. name vs full signature). /// </summary> public SymbolDisplayDelegateStyle DelegateStyle { get; } /// <summary> /// Determines how extension methods are displayed. /// </summary> public SymbolDisplayExtensionMethodStyle ExtensionMethodStyle { get; } /// <summary> /// Determines how properties are displayed. /// For example, "Prop" vs "Prop { get; set; }" in C# or "Prop" vs. "ReadOnly Prop" in Visual Basic. /// </summary> public SymbolDisplayPropertyStyle PropertyStyle { get; } /// <summary> /// Determines how local variables are displayed. /// </summary> public SymbolDisplayLocalOptions LocalOptions { get; } /// <summary> /// Determines which kind keywords should be included when displaying symbols. /// </summary> public SymbolDisplayKindOptions KindOptions { get; } /// <summary> /// Determines other characteristics of how symbols are displayed. /// </summary> public SymbolDisplayMiscellaneousOptions MiscellaneousOptions { get; } /// <summary> /// Flags that can only be set within the compiler. /// </summary> internal SymbolDisplayCompilerInternalOptions CompilerInternalOptions { get; } /// <summary> /// Constructs a new instance of <see cref="SymbolDisplayFormat"/> accepting a variety of optional parameters. /// </summary> /// <param name="globalNamespaceStyle"> /// The settings that determine how the global namespace is displayed. /// </param> /// <param name="typeQualificationStyle"> /// The settings that determine how types are qualified (e.g. Nested vs Containing.Nested vs Namespace.Containing.Nested). /// </param> /// <param name="genericsOptions"> /// The settings that determine how generics (on types and methods) should be described (i.e. the level of detail). /// </param> /// <param name="memberOptions"> /// The settings that determine how fields, properties, events, and methods are displayed. /// </param> /// <param name="delegateStyle"> /// The settings that determine how delegates are displayed (e.g. name vs full signature). /// </param> /// <param name="extensionMethodStyle"> /// The settings that determine how extension methods are displayed. /// </param> /// <param name="parameterOptions"> /// The settings that determine how parameters (of methods, properties/indexers, and delegates) are displayed. /// </param> /// <param name="propertyStyle"> /// The settings that determine how properties are displayed. /// For example, "Prop" vs "Prop { get; set; }" in C# or "Prop" vs. "ReadOnly Prop" in Visual Basic. /// </param> /// <param name="localOptions"> /// The settings that determine how local variables are displayed. /// </param> /// <param name="kindOptions"> /// The settings that determine which kind keywords should be included when displaying symbols. /// </param> /// <param name="miscellaneousOptions"> /// The settings that determine other characteristics of how symbols are displayed. /// </param> public SymbolDisplayFormat( SymbolDisplayGlobalNamespaceStyle globalNamespaceStyle = default(SymbolDisplayGlobalNamespaceStyle), SymbolDisplayTypeQualificationStyle typeQualificationStyle = default(SymbolDisplayTypeQualificationStyle), SymbolDisplayGenericsOptions genericsOptions = default(SymbolDisplayGenericsOptions), SymbolDisplayMemberOptions memberOptions = default(SymbolDisplayMemberOptions), SymbolDisplayDelegateStyle delegateStyle = default(SymbolDisplayDelegateStyle), SymbolDisplayExtensionMethodStyle extensionMethodStyle = default(SymbolDisplayExtensionMethodStyle), SymbolDisplayParameterOptions parameterOptions = default(SymbolDisplayParameterOptions), SymbolDisplayPropertyStyle propertyStyle = default(SymbolDisplayPropertyStyle), SymbolDisplayLocalOptions localOptions = default(SymbolDisplayLocalOptions), SymbolDisplayKindOptions kindOptions = default(SymbolDisplayKindOptions), SymbolDisplayMiscellaneousOptions miscellaneousOptions = default(SymbolDisplayMiscellaneousOptions)) : this( compilerInternalOptions: default, globalNamespaceStyle, typeQualificationStyle, genericsOptions, memberOptions, parameterOptions, delegateStyle, extensionMethodStyle, propertyStyle, localOptions, kindOptions, miscellaneousOptions) { } /// <summary> /// This version also accepts <see cref="SymbolDisplayCompilerInternalOptions"/>. /// </summary> internal SymbolDisplayFormat( SymbolDisplayCompilerInternalOptions compilerInternalOptions, SymbolDisplayGlobalNamespaceStyle globalNamespaceStyle = default(SymbolDisplayGlobalNamespaceStyle), SymbolDisplayTypeQualificationStyle typeQualificationStyle = default(SymbolDisplayTypeQualificationStyle), SymbolDisplayGenericsOptions genericsOptions = default(SymbolDisplayGenericsOptions), SymbolDisplayMemberOptions memberOptions = default(SymbolDisplayMemberOptions), SymbolDisplayParameterOptions parameterOptions = default(SymbolDisplayParameterOptions), SymbolDisplayDelegateStyle delegateStyle = default(SymbolDisplayDelegateStyle), SymbolDisplayExtensionMethodStyle extensionMethodStyle = default(SymbolDisplayExtensionMethodStyle), SymbolDisplayPropertyStyle propertyStyle = default(SymbolDisplayPropertyStyle), SymbolDisplayLocalOptions localOptions = default(SymbolDisplayLocalOptions), SymbolDisplayKindOptions kindOptions = default(SymbolDisplayKindOptions), SymbolDisplayMiscellaneousOptions miscellaneousOptions = default(SymbolDisplayMiscellaneousOptions)) { this.GlobalNamespaceStyle = globalNamespaceStyle; this.TypeQualificationStyle = typeQualificationStyle; this.GenericsOptions = genericsOptions; this.MemberOptions = memberOptions; this.ParameterOptions = parameterOptions; this.DelegateStyle = delegateStyle; this.ExtensionMethodStyle = extensionMethodStyle; this.PropertyStyle = propertyStyle; this.LocalOptions = localOptions; this.KindOptions = kindOptions; this.MiscellaneousOptions = miscellaneousOptions; this.CompilerInternalOptions = compilerInternalOptions; } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayMiscellaneousOptions"/>. /// </summary> /// <param name="options"> /// An object representing how miscellaneous symbols will be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayMiscellaneousOptions"/>.</returns> public SymbolDisplayFormat WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions options) { return new SymbolDisplayFormat( this.CompilerInternalOptions, this.GlobalNamespaceStyle, this.TypeQualificationStyle, this.GenericsOptions, this.MemberOptions, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, this.KindOptions, options ); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with an additional set of <seealso cref="SymbolDisplayMiscellaneousOptions"/>. /// </summary> /// <param name="options"> /// An object specifying additional parameters for how miscellaneous symbols will be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with an additional set of <seealso cref="SymbolDisplayMiscellaneousOptions"/>.</returns> public SymbolDisplayFormat AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions options) { return this.WithMiscellaneousOptions(this.MiscellaneousOptions | options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat without the specified <seealso cref="SymbolDisplayMiscellaneousOptions"/>. /// </summary> /// <param name="options"> /// An object specifying which parameters should not be applied to how miscellaneous symbols will be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, without the specified <seealso cref="SymbolDisplayMiscellaneousOptions"/>.</returns> public SymbolDisplayFormat RemoveMiscellaneousOptions(SymbolDisplayMiscellaneousOptions options) { return this.WithMiscellaneousOptions(this.MiscellaneousOptions & ~options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayGenericsOptions"/>. /// </summary> /// <param name="options"> /// An object specifying how generic symbols will be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayGenericsOptions"/>.</returns> public SymbolDisplayFormat WithGenericsOptions(SymbolDisplayGenericsOptions options) { return new SymbolDisplayFormat( this.CompilerInternalOptions, this.GlobalNamespaceStyle, this.TypeQualificationStyle, options, this.MemberOptions, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, this.KindOptions, this.MiscellaneousOptions); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with an additional set of <seealso cref="SymbolDisplayGenericsOptions"/>. /// </summary> /// <param name="options"> /// An object specifying additional parameters for how generic symbols will be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with an additional set of <seealso cref="SymbolDisplayGenericsOptions"/>.</returns> public SymbolDisplayFormat AddGenericsOptions(SymbolDisplayGenericsOptions options) { return this.WithGenericsOptions(this.GenericsOptions | options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with a set of <seealso cref="SymbolDisplayGenericsOptions"/> stripped away from the original object. /// </summary> /// <param name="options"> /// An object specifying which parameters should not be applied to how generic symbols will be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with a set of <seealso cref="SymbolDisplayGenericsOptions"/> stripped away from the original object. /// </returns> public SymbolDisplayFormat RemoveGenericsOptions(SymbolDisplayGenericsOptions options) { return this.WithGenericsOptions(this.GenericsOptions & ~options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayMemberOptions"/>. /// </summary> /// <param name="options"> /// An object specifying how members will be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayMemberOptions"/>.</returns> public SymbolDisplayFormat WithMemberOptions(SymbolDisplayMemberOptions options) { return new SymbolDisplayFormat( this.CompilerInternalOptions, this.GlobalNamespaceStyle, this.TypeQualificationStyle, this.GenericsOptions, options, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, this.KindOptions, this.MiscellaneousOptions); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with an additional set of <seealso cref="SymbolDisplayMemberOptions"/>. /// </summary> /// <param name="options"> /// An object specifying additional parameters for how members will be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with an additional set of <seealso cref="SymbolDisplayMemberOptions"/>. /// </returns> public SymbolDisplayFormat AddMemberOptions(SymbolDisplayMemberOptions options) { return this.WithMemberOptions(this.MemberOptions | options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with a set of <seealso cref="SymbolDisplayMemberOptions"/> stripped away from the original object. /// </summary> /// <param name="options"> /// An object specifying which parameters should not be applied to how members will be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with a set of <seealso cref="SymbolDisplayMemberOptions"/> stripped away from the original object. /// </returns> public SymbolDisplayFormat RemoveMemberOptions(SymbolDisplayMemberOptions options) { return this.WithMemberOptions(this.MemberOptions & ~options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayKindOptions"/>. /// </summary> /// <param name="options"> /// An object specifying parameters with which symbols belonging to kind keywords should be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayKindOptions"/>. /// </returns> public SymbolDisplayFormat WithKindOptions(SymbolDisplayKindOptions options) { return new SymbolDisplayFormat( this.CompilerInternalOptions, this.GlobalNamespaceStyle, this.TypeQualificationStyle, this.GenericsOptions, this.MemberOptions, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, options, this.MiscellaneousOptions); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with an additional set of <seealso cref="SymbolDisplayKindOptions"/>. /// </summary> /// <param name="options"> /// An object specifying additional parameters with which symbols belonging to kind keywords should be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with an additional set of <seealso cref="SymbolDisplayKindOptions"/>. /// </returns> public SymbolDisplayFormat AddKindOptions(SymbolDisplayKindOptions options) { return this.WithKindOptions(this.KindOptions | options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with a set of <seealso cref="SymbolDisplayKindOptions"/> stripped away from the original object. /// </summary> /// <param name="options"> /// The settings that determine other characteristics of how symbols are displayed. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with a set of <seealso cref="SymbolDisplayKindOptions"/> stripped away from the original object. /// </returns> public SymbolDisplayFormat RemoveKindOptions(SymbolDisplayKindOptions options) { return this.WithKindOptions(this.KindOptions & ~options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayParameterOptions"/>. /// </summary> /// <param name="options"> /// An object specifying how parameters should be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayParameterOptions"/>.</returns> public SymbolDisplayFormat WithParameterOptions(SymbolDisplayParameterOptions options) { return new SymbolDisplayFormat( this.CompilerInternalOptions, this.GlobalNamespaceStyle, this.TypeQualificationStyle, this.GenericsOptions, this.MemberOptions, options, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, this.KindOptions, this.MiscellaneousOptions); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with an additional set of <seealso cref="SymbolDisplayParameterOptions"/>. /// </summary> /// <param name="options"> /// An object specifying additional parameters on how parameters should be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with an additional set of <seealso cref="SymbolDisplayParameterOptions"/>. /// </returns> public SymbolDisplayFormat AddParameterOptions(SymbolDisplayParameterOptions options) { return this.WithParameterOptions(this.ParameterOptions | options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with a set of <seealso cref="SymbolDisplayParameterOptions"/> stripped away from the original object. /// </summary> /// <param name="options"> /// An object specifying parameters that should not be applied when formatting parameters. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with a set of <seealso cref="SymbolDisplayParameterOptions"/> stripped away from the original object. /// </returns> public SymbolDisplayFormat RemoveParameterOptions(SymbolDisplayParameterOptions options) { return this.WithParameterOptions(this.ParameterOptions & ~options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced <seealso cref="SymbolDisplayGlobalNamespaceStyle"/>. /// </summary> /// <param name="style"> /// An object specifying parameters on how namespace symbols should be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayGlobalNamespaceStyle"/>.</returns> public SymbolDisplayFormat WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle style) { return new SymbolDisplayFormat( this.CompilerInternalOptions, style, this.TypeQualificationStyle, this.GenericsOptions, this.MemberOptions, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, this.KindOptions, this.MiscellaneousOptions); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayLocalOptions"/>. /// </summary> /// <param name="options"> /// An object specifying parameters on how symbols belonging to locals should be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayLocalOptions"/>.</returns> public SymbolDisplayFormat WithLocalOptions(SymbolDisplayLocalOptions options) { return new SymbolDisplayFormat( this.CompilerInternalOptions, this.GlobalNamespaceStyle, this.TypeQualificationStyle, this.GenericsOptions, this.MemberOptions, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, options, this.KindOptions, this.MiscellaneousOptions); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with an additional set of <seealso cref="SymbolDisplayLocalOptions"/>. /// </summary> /// <param name="options"> /// An object specifying additional parameters on how symbols belonging to locals should be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with an additional set of <seealso cref="SymbolDisplayLocalOptions"/>. /// </returns> public SymbolDisplayFormat AddLocalOptions(SymbolDisplayLocalOptions options) { return this.WithLocalOptions(this.LocalOptions | options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with a set of <seealso cref="SymbolDisplayLocalOptions"/> stripped away from the original object. /// </summary> /// <param name="options"> /// An object specifying parameters that should not be applied when formatting symbols belonging to locals. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with a set of <seealso cref="SymbolDisplayLocalOptions"/> stripped away from the original object. /// </returns> public SymbolDisplayFormat RemoveLocalOptions(SymbolDisplayLocalOptions options) { return this.WithLocalOptions(this.LocalOptions & ~options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayCompilerInternalOptions"/>. /// </summary> internal SymbolDisplayFormat WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions options) { return new SymbolDisplayFormat( options, this.GlobalNamespaceStyle, this.TypeQualificationStyle, this.GenericsOptions, this.MemberOptions, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, this.KindOptions, this.MiscellaneousOptions); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Describes the formatting rules that should be used when displaying symbols. /// </summary> public class SymbolDisplayFormat { /// <summary> /// Formats a symbol description as in a C# compiler error message. /// </summary> public static SymbolDisplayFormat CSharpErrorMessageFormat { get; } = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, // Not showing the name is important because we visit parameters to display their // types. If we visited their types directly, we wouldn't get ref/out/params. miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); /// <summary> /// Formats a symbol description as in a C# compiler short error message. /// </summary> public static SymbolDisplayFormat CSharpShortErrorMessageFormat { get; } = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeExplicitInterface, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, // Not showing the name is important because we visit parameters to display their // types. If we visited their types directly, we wouldn't get ref/out/params. miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); /// <summary> /// Formats a symbol description as in a Visual Basic compiler error message. /// </summary> public static SymbolDisplayFormat VisualBasicErrorMessageFormat { get; } = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef | SymbolDisplayMemberOptions.IncludeModifiers, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeOptionalBrackets | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); /// <summary> /// Formats a symbol description as in a Visual Basic compiler short error message. /// </summary> public static SymbolDisplayFormat VisualBasicShortErrorMessageFormat { get; } = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypes, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeAccessibility | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef | SymbolDisplayMemberOptions.IncludeModifiers, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeOptionalBrackets | SymbolDisplayParameterOptions.IncludeDefaultValue, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseAsterisksInMultiDimensionalArrays | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); /// <summary> /// Formats the names of all types and namespaces in a fully qualified style (including the global alias). /// </summary> public static SymbolDisplayFormat FullyQualifiedFormat { get; } = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes); /// <summary> /// Formats a symbol description in a form that suits <see cref="ISymbol.ToMinimalDisplayString"/>. /// </summary> public static SymbolDisplayFormat MinimallyQualifiedFormat { get; } = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef | SymbolDisplayMemberOptions.IncludeContainingType, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeDefaultValue, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); /// <summary> /// A verbose format for displaying symbols (useful for testing). /// </summary> internal static readonly SymbolDisplayFormat TestFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, localOptions: SymbolDisplayLocalOptions.IncludeType, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef | SymbolDisplayMemberOptions.IncludeExplicitInterface, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, parameterOptions: SymbolDisplayParameterOptions.IncludeOptionalBrackets | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.IncludeScriptType | SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames | SymbolDisplayCompilerInternalOptions.FlagMissingMetadataTypes | SymbolDisplayCompilerInternalOptions.IncludeCustomModifiers); /// <summary> /// A verbose format for displaying symbols (useful for testing). /// </summary> internal static readonly SymbolDisplayFormat TestFormatWithConstraints = TestFormat.WithGenericsOptions(TestFormat.GenericsOptions | SymbolDisplayGenericsOptions.IncludeTypeConstraints). AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier). WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None); /// <summary> /// this.QualifiedNameOnly = containingSymbol.QualifiedNameOnly + "." + this.Name /// </summary> internal static readonly SymbolDisplayFormat QualifiedNameOnlyFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); /// <summary> /// this.QualifiedNameArity = containingSymbol.QualifiedNameArity + "." + this.Name + "`" + this.Arity /// </summary> internal static readonly SymbolDisplayFormat QualifiedNameArityFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.UseArityForGenericTypes | SymbolDisplayCompilerInternalOptions.UseValueTuple); /// <summary> /// A succinct format for displaying symbols. /// </summary> internal static readonly SymbolDisplayFormat ShortFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly, propertyStyle: SymbolDisplayPropertyStyle.NameOnly, parameterOptions: SymbolDisplayParameterOptions.IncludeName, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier); /// <summary> /// The format used for displaying symbols when visualizing IL. /// </summary> internal static readonly SymbolDisplayFormat ILVisualizationFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType | SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeRef, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, parameterOptions: SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.UseMetadataMethodNames | SymbolDisplayCompilerInternalOptions.UseValueTuple); /// <summary> /// Used to normalize explicit interface implementation member names. /// Only expected to be applied to interface types (and their type arguments). /// </summary> internal static readonly SymbolDisplayFormat ExplicitInterfaceImplementationFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers, compilerInternalOptions: SymbolDisplayCompilerInternalOptions.ReverseArrayRankSpecifiers); /// <summary> /// Determines how the global namespace is displayed. /// </summary> public SymbolDisplayGlobalNamespaceStyle GlobalNamespaceStyle { get; } /// <summary> /// Determines how types are qualified (e.g. Nested vs Containing.Nested vs Namespace.Containing.Nested). /// </summary> public SymbolDisplayTypeQualificationStyle TypeQualificationStyle { get; } /// <summary> /// Determines how generics (on types and methods) should be described (i.e. the level of detail). /// </summary> public SymbolDisplayGenericsOptions GenericsOptions { get; } /// <summary> /// Determines how fields, properties, events, and methods are displayed. /// </summary> public SymbolDisplayMemberOptions MemberOptions { get; } /// <summary> /// Determines how parameters (of methods, properties/indexers, and delegates) are displayed. /// </summary> public SymbolDisplayParameterOptions ParameterOptions { get; } /// <summary> /// Determines how delegates are displayed (e.g. name vs full signature). /// </summary> public SymbolDisplayDelegateStyle DelegateStyle { get; } /// <summary> /// Determines how extension methods are displayed. /// </summary> public SymbolDisplayExtensionMethodStyle ExtensionMethodStyle { get; } /// <summary> /// Determines how properties are displayed. /// For example, "Prop" vs "Prop { get; set; }" in C# or "Prop" vs. "ReadOnly Prop" in Visual Basic. /// </summary> public SymbolDisplayPropertyStyle PropertyStyle { get; } /// <summary> /// Determines how local variables are displayed. /// </summary> public SymbolDisplayLocalOptions LocalOptions { get; } /// <summary> /// Determines which kind keywords should be included when displaying symbols. /// </summary> public SymbolDisplayKindOptions KindOptions { get; } /// <summary> /// Determines other characteristics of how symbols are displayed. /// </summary> public SymbolDisplayMiscellaneousOptions MiscellaneousOptions { get; } /// <summary> /// Flags that can only be set within the compiler. /// </summary> internal SymbolDisplayCompilerInternalOptions CompilerInternalOptions { get; } /// <summary> /// Constructs a new instance of <see cref="SymbolDisplayFormat"/> accepting a variety of optional parameters. /// </summary> /// <param name="globalNamespaceStyle"> /// The settings that determine how the global namespace is displayed. /// </param> /// <param name="typeQualificationStyle"> /// The settings that determine how types are qualified (e.g. Nested vs Containing.Nested vs Namespace.Containing.Nested). /// </param> /// <param name="genericsOptions"> /// The settings that determine how generics (on types and methods) should be described (i.e. the level of detail). /// </param> /// <param name="memberOptions"> /// The settings that determine how fields, properties, events, and methods are displayed. /// </param> /// <param name="delegateStyle"> /// The settings that determine how delegates are displayed (e.g. name vs full signature). /// </param> /// <param name="extensionMethodStyle"> /// The settings that determine how extension methods are displayed. /// </param> /// <param name="parameterOptions"> /// The settings that determine how parameters (of methods, properties/indexers, and delegates) are displayed. /// </param> /// <param name="propertyStyle"> /// The settings that determine how properties are displayed. /// For example, "Prop" vs "Prop { get; set; }" in C# or "Prop" vs. "ReadOnly Prop" in Visual Basic. /// </param> /// <param name="localOptions"> /// The settings that determine how local variables are displayed. /// </param> /// <param name="kindOptions"> /// The settings that determine which kind keywords should be included when displaying symbols. /// </param> /// <param name="miscellaneousOptions"> /// The settings that determine other characteristics of how symbols are displayed. /// </param> public SymbolDisplayFormat( SymbolDisplayGlobalNamespaceStyle globalNamespaceStyle = default(SymbolDisplayGlobalNamespaceStyle), SymbolDisplayTypeQualificationStyle typeQualificationStyle = default(SymbolDisplayTypeQualificationStyle), SymbolDisplayGenericsOptions genericsOptions = default(SymbolDisplayGenericsOptions), SymbolDisplayMemberOptions memberOptions = default(SymbolDisplayMemberOptions), SymbolDisplayDelegateStyle delegateStyle = default(SymbolDisplayDelegateStyle), SymbolDisplayExtensionMethodStyle extensionMethodStyle = default(SymbolDisplayExtensionMethodStyle), SymbolDisplayParameterOptions parameterOptions = default(SymbolDisplayParameterOptions), SymbolDisplayPropertyStyle propertyStyle = default(SymbolDisplayPropertyStyle), SymbolDisplayLocalOptions localOptions = default(SymbolDisplayLocalOptions), SymbolDisplayKindOptions kindOptions = default(SymbolDisplayKindOptions), SymbolDisplayMiscellaneousOptions miscellaneousOptions = default(SymbolDisplayMiscellaneousOptions)) : this( compilerInternalOptions: default, globalNamespaceStyle, typeQualificationStyle, genericsOptions, memberOptions, parameterOptions, delegateStyle, extensionMethodStyle, propertyStyle, localOptions, kindOptions, miscellaneousOptions) { } /// <summary> /// This version also accepts <see cref="SymbolDisplayCompilerInternalOptions"/>. /// </summary> internal SymbolDisplayFormat( SymbolDisplayCompilerInternalOptions compilerInternalOptions, SymbolDisplayGlobalNamespaceStyle globalNamespaceStyle = default(SymbolDisplayGlobalNamespaceStyle), SymbolDisplayTypeQualificationStyle typeQualificationStyle = default(SymbolDisplayTypeQualificationStyle), SymbolDisplayGenericsOptions genericsOptions = default(SymbolDisplayGenericsOptions), SymbolDisplayMemberOptions memberOptions = default(SymbolDisplayMemberOptions), SymbolDisplayParameterOptions parameterOptions = default(SymbolDisplayParameterOptions), SymbolDisplayDelegateStyle delegateStyle = default(SymbolDisplayDelegateStyle), SymbolDisplayExtensionMethodStyle extensionMethodStyle = default(SymbolDisplayExtensionMethodStyle), SymbolDisplayPropertyStyle propertyStyle = default(SymbolDisplayPropertyStyle), SymbolDisplayLocalOptions localOptions = default(SymbolDisplayLocalOptions), SymbolDisplayKindOptions kindOptions = default(SymbolDisplayKindOptions), SymbolDisplayMiscellaneousOptions miscellaneousOptions = default(SymbolDisplayMiscellaneousOptions)) { this.GlobalNamespaceStyle = globalNamespaceStyle; this.TypeQualificationStyle = typeQualificationStyle; this.GenericsOptions = genericsOptions; this.MemberOptions = memberOptions; this.ParameterOptions = parameterOptions; this.DelegateStyle = delegateStyle; this.ExtensionMethodStyle = extensionMethodStyle; this.PropertyStyle = propertyStyle; this.LocalOptions = localOptions; this.KindOptions = kindOptions; this.MiscellaneousOptions = miscellaneousOptions; this.CompilerInternalOptions = compilerInternalOptions; } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayMiscellaneousOptions"/>. /// </summary> /// <param name="options"> /// An object representing how miscellaneous symbols will be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayMiscellaneousOptions"/>.</returns> public SymbolDisplayFormat WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions options) { return new SymbolDisplayFormat( this.CompilerInternalOptions, this.GlobalNamespaceStyle, this.TypeQualificationStyle, this.GenericsOptions, this.MemberOptions, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, this.KindOptions, options ); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with an additional set of <seealso cref="SymbolDisplayMiscellaneousOptions"/>. /// </summary> /// <param name="options"> /// An object specifying additional parameters for how miscellaneous symbols will be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with an additional set of <seealso cref="SymbolDisplayMiscellaneousOptions"/>.</returns> public SymbolDisplayFormat AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions options) { return this.WithMiscellaneousOptions(this.MiscellaneousOptions | options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat without the specified <seealso cref="SymbolDisplayMiscellaneousOptions"/>. /// </summary> /// <param name="options"> /// An object specifying which parameters should not be applied to how miscellaneous symbols will be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, without the specified <seealso cref="SymbolDisplayMiscellaneousOptions"/>.</returns> public SymbolDisplayFormat RemoveMiscellaneousOptions(SymbolDisplayMiscellaneousOptions options) { return this.WithMiscellaneousOptions(this.MiscellaneousOptions & ~options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayGenericsOptions"/>. /// </summary> /// <param name="options"> /// An object specifying how generic symbols will be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayGenericsOptions"/>.</returns> public SymbolDisplayFormat WithGenericsOptions(SymbolDisplayGenericsOptions options) { return new SymbolDisplayFormat( this.CompilerInternalOptions, this.GlobalNamespaceStyle, this.TypeQualificationStyle, options, this.MemberOptions, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, this.KindOptions, this.MiscellaneousOptions); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with an additional set of <seealso cref="SymbolDisplayGenericsOptions"/>. /// </summary> /// <param name="options"> /// An object specifying additional parameters for how generic symbols will be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with an additional set of <seealso cref="SymbolDisplayGenericsOptions"/>.</returns> public SymbolDisplayFormat AddGenericsOptions(SymbolDisplayGenericsOptions options) { return this.WithGenericsOptions(this.GenericsOptions | options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with a set of <seealso cref="SymbolDisplayGenericsOptions"/> stripped away from the original object. /// </summary> /// <param name="options"> /// An object specifying which parameters should not be applied to how generic symbols will be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with a set of <seealso cref="SymbolDisplayGenericsOptions"/> stripped away from the original object. /// </returns> public SymbolDisplayFormat RemoveGenericsOptions(SymbolDisplayGenericsOptions options) { return this.WithGenericsOptions(this.GenericsOptions & ~options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayMemberOptions"/>. /// </summary> /// <param name="options"> /// An object specifying how members will be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayMemberOptions"/>.</returns> public SymbolDisplayFormat WithMemberOptions(SymbolDisplayMemberOptions options) { return new SymbolDisplayFormat( this.CompilerInternalOptions, this.GlobalNamespaceStyle, this.TypeQualificationStyle, this.GenericsOptions, options, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, this.KindOptions, this.MiscellaneousOptions); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with an additional set of <seealso cref="SymbolDisplayMemberOptions"/>. /// </summary> /// <param name="options"> /// An object specifying additional parameters for how members will be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with an additional set of <seealso cref="SymbolDisplayMemberOptions"/>. /// </returns> public SymbolDisplayFormat AddMemberOptions(SymbolDisplayMemberOptions options) { return this.WithMemberOptions(this.MemberOptions | options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with a set of <seealso cref="SymbolDisplayMemberOptions"/> stripped away from the original object. /// </summary> /// <param name="options"> /// An object specifying which parameters should not be applied to how members will be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with a set of <seealso cref="SymbolDisplayMemberOptions"/> stripped away from the original object. /// </returns> public SymbolDisplayFormat RemoveMemberOptions(SymbolDisplayMemberOptions options) { return this.WithMemberOptions(this.MemberOptions & ~options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayKindOptions"/>. /// </summary> /// <param name="options"> /// An object specifying parameters with which symbols belonging to kind keywords should be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayKindOptions"/>. /// </returns> public SymbolDisplayFormat WithKindOptions(SymbolDisplayKindOptions options) { return new SymbolDisplayFormat( this.CompilerInternalOptions, this.GlobalNamespaceStyle, this.TypeQualificationStyle, this.GenericsOptions, this.MemberOptions, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, options, this.MiscellaneousOptions); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with an additional set of <seealso cref="SymbolDisplayKindOptions"/>. /// </summary> /// <param name="options"> /// An object specifying additional parameters with which symbols belonging to kind keywords should be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with an additional set of <seealso cref="SymbolDisplayKindOptions"/>. /// </returns> public SymbolDisplayFormat AddKindOptions(SymbolDisplayKindOptions options) { return this.WithKindOptions(this.KindOptions | options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with a set of <seealso cref="SymbolDisplayKindOptions"/> stripped away from the original object. /// </summary> /// <param name="options"> /// The settings that determine other characteristics of how symbols are displayed. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with a set of <seealso cref="SymbolDisplayKindOptions"/> stripped away from the original object. /// </returns> public SymbolDisplayFormat RemoveKindOptions(SymbolDisplayKindOptions options) { return this.WithKindOptions(this.KindOptions & ~options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayParameterOptions"/>. /// </summary> /// <param name="options"> /// An object specifying how parameters should be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayParameterOptions"/>.</returns> public SymbolDisplayFormat WithParameterOptions(SymbolDisplayParameterOptions options) { return new SymbolDisplayFormat( this.CompilerInternalOptions, this.GlobalNamespaceStyle, this.TypeQualificationStyle, this.GenericsOptions, this.MemberOptions, options, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, this.KindOptions, this.MiscellaneousOptions); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with an additional set of <seealso cref="SymbolDisplayParameterOptions"/>. /// </summary> /// <param name="options"> /// An object specifying additional parameters on how parameters should be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with an additional set of <seealso cref="SymbolDisplayParameterOptions"/>. /// </returns> public SymbolDisplayFormat AddParameterOptions(SymbolDisplayParameterOptions options) { return this.WithParameterOptions(this.ParameterOptions | options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with a set of <seealso cref="SymbolDisplayParameterOptions"/> stripped away from the original object. /// </summary> /// <param name="options"> /// An object specifying parameters that should not be applied when formatting parameters. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with a set of <seealso cref="SymbolDisplayParameterOptions"/> stripped away from the original object. /// </returns> public SymbolDisplayFormat RemoveParameterOptions(SymbolDisplayParameterOptions options) { return this.WithParameterOptions(this.ParameterOptions & ~options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced <seealso cref="SymbolDisplayGlobalNamespaceStyle"/>. /// </summary> /// <param name="style"> /// An object specifying parameters on how namespace symbols should be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayGlobalNamespaceStyle"/>.</returns> public SymbolDisplayFormat WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle style) { return new SymbolDisplayFormat( this.CompilerInternalOptions, style, this.TypeQualificationStyle, this.GenericsOptions, this.MemberOptions, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, this.KindOptions, this.MiscellaneousOptions); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayLocalOptions"/>. /// </summary> /// <param name="options"> /// An object specifying parameters on how symbols belonging to locals should be formatted. /// </param> /// <returns>A duplicate of the SymbolDisplayFormat, with a replaced set of <seealso cref="SymbolDisplayLocalOptions"/>.</returns> public SymbolDisplayFormat WithLocalOptions(SymbolDisplayLocalOptions options) { return new SymbolDisplayFormat( this.CompilerInternalOptions, this.GlobalNamespaceStyle, this.TypeQualificationStyle, this.GenericsOptions, this.MemberOptions, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, options, this.KindOptions, this.MiscellaneousOptions); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with an additional set of <seealso cref="SymbolDisplayLocalOptions"/>. /// </summary> /// <param name="options"> /// An object specifying additional parameters on how symbols belonging to locals should be formatted. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with an additional set of <seealso cref="SymbolDisplayLocalOptions"/>. /// </returns> public SymbolDisplayFormat AddLocalOptions(SymbolDisplayLocalOptions options) { return this.WithLocalOptions(this.LocalOptions | options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with a set of <seealso cref="SymbolDisplayLocalOptions"/> stripped away from the original object. /// </summary> /// <param name="options"> /// An object specifying parameters that should not be applied when formatting symbols belonging to locals. /// </param> /// <returns> /// A duplicate of the SymbolDisplayFormat, with a set of <seealso cref="SymbolDisplayLocalOptions"/> stripped away from the original object. /// </returns> public SymbolDisplayFormat RemoveLocalOptions(SymbolDisplayLocalOptions options) { return this.WithLocalOptions(this.LocalOptions & ~options); } /// <summary> /// Creates a copy of the SymbolDisplayFormat but with replaced set of <seealso cref="SymbolDisplayCompilerInternalOptions"/>. /// </summary> internal SymbolDisplayFormat WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions options) { return new SymbolDisplayFormat( options, this.GlobalNamespaceStyle, this.TypeQualificationStyle, this.GenericsOptions, this.MemberOptions, this.ParameterOptions, this.DelegateStyle, this.ExtensionMethodStyle, this.PropertyStyle, this.LocalOptions, this.KindOptions, this.MiscellaneousOptions); } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/VisualStudio/Core/Impl/CodeModel/InternalElements/CodeFunctionDeclareDecl.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using EnvDTE; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { public sealed class CodeFunctionDeclareDecl : CodeFunction { internal static new EnvDTE.CodeFunction Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeFunctionDeclareDecl(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static new EnvDTE.CodeFunction CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeFunctionDeclareDecl(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(element); } private CodeFunctionDeclareDecl( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeFunctionDeclareDecl( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } public override vsCMElement Kind { get { return vsCMElement.vsCMElementDeclareDecl; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using EnvDTE; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.TextManager.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements { public sealed class CodeFunctionDeclareDecl : CodeFunction { internal static new EnvDTE.CodeFunction Create( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) { var element = new CodeFunctionDeclareDecl(state, fileCodeModel, nodeKey, nodeKind); var result = (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(element); fileCodeModel.OnCodeElementCreated(nodeKey, (EnvDTE.CodeElement)result); return result; } internal static new EnvDTE.CodeFunction CreateUnknown( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) { var element = new CodeFunctionDeclareDecl(state, fileCodeModel, nodeKind, name); return (EnvDTE.CodeFunction)ComAggregate.CreateAggregatedObject(element); } private CodeFunctionDeclareDecl( CodeModelState state, FileCodeModel fileCodeModel, SyntaxNodeKey nodeKey, int? nodeKind) : base(state, fileCodeModel, nodeKey, nodeKind) { } private CodeFunctionDeclareDecl( CodeModelState state, FileCodeModel fileCodeModel, int nodeKind, string name) : base(state, fileCodeModel, nodeKind, name) { } public override vsCMElement Kind { get { return vsCMElement.vsCMElementDeclareDecl; } } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Analyzers/CSharp/CodeFixes/ConvertNamespace/ConvertNamespaceTransform.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.CSharp.ConvertNamespace { internal static class ConvertNamespaceTransform { public static async Task<Document> ConvertAsync( Document document, BaseNamespaceDeclarationSyntax baseNamespace, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(root.ReplaceNode(baseNamespace, Convert(baseNamespace))); } public static BaseNamespaceDeclarationSyntax Convert(BaseNamespaceDeclarationSyntax baseNamespace) { return baseNamespace switch { FileScopedNamespaceDeclarationSyntax fileScopedNamespace => ConvertFileScopedNamespace(fileScopedNamespace), NamespaceDeclarationSyntax namespaceDeclaration => ConvertNamespaceDeclaration(namespaceDeclaration), _ => throw ExceptionUtilities.UnexpectedValue(baseNamespace.Kind()), }; } private static bool HasLeadingBlankLine( SyntaxToken token, out SyntaxToken withoutBlankLine) { var leadingTrivia = token.LeadingTrivia; if (leadingTrivia.Count >= 1 && leadingTrivia[0].Kind() == SyntaxKind.EndOfLineTrivia) { withoutBlankLine = token.WithLeadingTrivia(leadingTrivia.RemoveAt(0)); return true; } if (leadingTrivia.Count >= 2 && leadingTrivia[0].IsKind(SyntaxKind.WhitespaceTrivia) && leadingTrivia[1].IsKind(SyntaxKind.EndOfLineTrivia)) { withoutBlankLine = token.WithLeadingTrivia(leadingTrivia.Skip(2)); return true; } withoutBlankLine = default; return false; } private static FileScopedNamespaceDeclarationSyntax ConvertNamespaceDeclaration(NamespaceDeclarationSyntax namespaceDeclaration) { var fileScopedNamespace = SyntaxFactory.FileScopedNamespaceDeclaration( namespaceDeclaration.AttributeLists, namespaceDeclaration.Modifiers, namespaceDeclaration.NamespaceKeyword, namespaceDeclaration.Name, SyntaxFactory.Token(SyntaxKind.SemicolonToken).WithTrailingTrivia(namespaceDeclaration.OpenBraceToken.TrailingTrivia), namespaceDeclaration.Externs, namespaceDeclaration.Usings, namespaceDeclaration.Members).WithAdditionalAnnotations(Formatter.Annotation); // Ensure there's a blank line between the namespace line and the first body member. var firstBodyToken = fileScopedNamespace.SemicolonToken.GetNextToken(); if (firstBodyToken.Kind() != SyntaxKind.EndOfFileToken && !HasLeadingBlankLine(firstBodyToken, out _)) { fileScopedNamespace = fileScopedNamespace.ReplaceToken( firstBodyToken, firstBodyToken.WithPrependedLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)); } return fileScopedNamespace; } private static NamespaceDeclarationSyntax ConvertFileScopedNamespace(FileScopedNamespaceDeclarationSyntax fileScopedNamespace) { var namespaceDeclaration = SyntaxFactory.NamespaceDeclaration( fileScopedNamespace.AttributeLists, fileScopedNamespace.Modifiers, fileScopedNamespace.NamespaceKeyword, fileScopedNamespace.Name, SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithTrailingTrivia(fileScopedNamespace.SemicolonToken.TrailingTrivia), fileScopedNamespace.Externs, fileScopedNamespace.Usings, fileScopedNamespace.Members, SyntaxFactory.Token(SyntaxKind.CloseBraceToken), semicolonToken: default).WithAdditionalAnnotations(Formatter.Annotation); // Ensure there is no errant blank line between the open curly and the first body element. var firstBodyToken = namespaceDeclaration.OpenBraceToken.GetNextToken(); if (firstBodyToken != namespaceDeclaration.CloseBraceToken && firstBodyToken.Kind() != SyntaxKind.EndOfFileToken && HasLeadingBlankLine(firstBodyToken, out var firstBodyTokenWithoutBlankLine)) { namespaceDeclaration = namespaceDeclaration.ReplaceToken(firstBodyToken, firstBodyTokenWithoutBlankLine); } return namespaceDeclaration; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; #if CODE_STYLE using OptionSet = Microsoft.CodeAnalysis.Diagnostics.AnalyzerConfigOptions; #endif namespace Microsoft.CodeAnalysis.CSharp.ConvertNamespace { internal static class ConvertNamespaceTransform { public static async Task<Document> ConvertAsync( Document document, BaseNamespaceDeclarationSyntax baseNamespace, CancellationToken cancellationToken) { var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(root.ReplaceNode(baseNamespace, Convert(baseNamespace))); } public static BaseNamespaceDeclarationSyntax Convert(BaseNamespaceDeclarationSyntax baseNamespace) { return baseNamespace switch { FileScopedNamespaceDeclarationSyntax fileScopedNamespace => ConvertFileScopedNamespace(fileScopedNamespace), NamespaceDeclarationSyntax namespaceDeclaration => ConvertNamespaceDeclaration(namespaceDeclaration), _ => throw ExceptionUtilities.UnexpectedValue(baseNamespace.Kind()), }; } private static bool HasLeadingBlankLine( SyntaxToken token, out SyntaxToken withoutBlankLine) { var leadingTrivia = token.LeadingTrivia; if (leadingTrivia.Count >= 1 && leadingTrivia[0].Kind() == SyntaxKind.EndOfLineTrivia) { withoutBlankLine = token.WithLeadingTrivia(leadingTrivia.RemoveAt(0)); return true; } if (leadingTrivia.Count >= 2 && leadingTrivia[0].IsKind(SyntaxKind.WhitespaceTrivia) && leadingTrivia[1].IsKind(SyntaxKind.EndOfLineTrivia)) { withoutBlankLine = token.WithLeadingTrivia(leadingTrivia.Skip(2)); return true; } withoutBlankLine = default; return false; } private static FileScopedNamespaceDeclarationSyntax ConvertNamespaceDeclaration(NamespaceDeclarationSyntax namespaceDeclaration) { var fileScopedNamespace = SyntaxFactory.FileScopedNamespaceDeclaration( namespaceDeclaration.AttributeLists, namespaceDeclaration.Modifiers, namespaceDeclaration.NamespaceKeyword, namespaceDeclaration.Name, SyntaxFactory.Token(SyntaxKind.SemicolonToken).WithTrailingTrivia(namespaceDeclaration.OpenBraceToken.TrailingTrivia), namespaceDeclaration.Externs, namespaceDeclaration.Usings, namespaceDeclaration.Members).WithAdditionalAnnotations(Formatter.Annotation); // Ensure there's a blank line between the namespace line and the first body member. var firstBodyToken = fileScopedNamespace.SemicolonToken.GetNextToken(); if (firstBodyToken.Kind() != SyntaxKind.EndOfFileToken && !HasLeadingBlankLine(firstBodyToken, out _)) { fileScopedNamespace = fileScopedNamespace.ReplaceToken( firstBodyToken, firstBodyToken.WithPrependedLeadingTrivia(SyntaxFactory.ElasticCarriageReturnLineFeed)); } return fileScopedNamespace; } private static NamespaceDeclarationSyntax ConvertFileScopedNamespace(FileScopedNamespaceDeclarationSyntax fileScopedNamespace) { var namespaceDeclaration = SyntaxFactory.NamespaceDeclaration( fileScopedNamespace.AttributeLists, fileScopedNamespace.Modifiers, fileScopedNamespace.NamespaceKeyword, fileScopedNamespace.Name, SyntaxFactory.Token(SyntaxKind.OpenBraceToken).WithTrailingTrivia(fileScopedNamespace.SemicolonToken.TrailingTrivia), fileScopedNamespace.Externs, fileScopedNamespace.Usings, fileScopedNamespace.Members, SyntaxFactory.Token(SyntaxKind.CloseBraceToken), semicolonToken: default).WithAdditionalAnnotations(Formatter.Annotation); // Ensure there is no errant blank line between the open curly and the first body element. var firstBodyToken = namespaceDeclaration.OpenBraceToken.GetNextToken(); if (firstBodyToken != namespaceDeclaration.CloseBraceToken && firstBodyToken.Kind() != SyntaxKind.EndOfFileToken && HasLeadingBlankLine(firstBodyToken, out var firstBodyTokenWithoutBlankLine)) { namespaceDeclaration = namespaceDeclaration.ReplaceToken(firstBodyToken, firstBodyTokenWithoutBlankLine); } return namespaceDeclaration; } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/EditorFeatures/Core/Shared/Extensions/IEditorOptionsFactoryServiceExtensions.cs
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class IEditorOptionsFactoryServiceExtensions { public static IEditorOptions GetEditorOptions(this IEditorOptionsFactoryService editorOptionsFactory, SourceText text) { var textBuffer = text.Container.TryGetTextBuffer(); if (textBuffer != null) { return editorOptionsFactory.GetOptions(textBuffer); } return editorOptionsFactory.GlobalOptions; } public static IEditorOptions GetEditorOptions(this IEditorOptionsFactoryService editorOptionsFactory, Document document) { if (document.TryGetText(out var text)) { return editorOptionsFactory.GetEditorOptions(text); } return editorOptionsFactory.GlobalOptions; } // This particular section is commented for future reference if there arises a need to implement a option serializer in the editor layer // public static IOptionService GetFormattingOptions(this IEditorOptionsFactoryService editorOptionsFactory, Document document) // { // return CreateOptions(editorOptionsFactory.GetEditorOptions(document)); // } // private static IOptionService CreateOptions(IEditorOptions editorOptions) // { // return new FormattingOptions( // !editorOptions.IsConvertTabsToSpacesEnabled(), // editorOptions.GetTabSize(), // editorOptions.GetIndentSize()); // } } }
// Licensed to the .NET Foundation under one or more agreements. // 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; using Microsoft.VisualStudio.Text.Editor; namespace Microsoft.CodeAnalysis.Editor.Shared.Extensions { internal static class IEditorOptionsFactoryServiceExtensions { public static IEditorOptions GetEditorOptions(this IEditorOptionsFactoryService editorOptionsFactory, SourceText text) { var textBuffer = text.Container.TryGetTextBuffer(); if (textBuffer != null) { return editorOptionsFactory.GetOptions(textBuffer); } return editorOptionsFactory.GlobalOptions; } public static IEditorOptions GetEditorOptions(this IEditorOptionsFactoryService editorOptionsFactory, Document document) { if (document.TryGetText(out var text)) { return editorOptionsFactory.GetEditorOptions(text); } return editorOptionsFactory.GlobalOptions; } // This particular section is commented for future reference if there arises a need to implement a option serializer in the editor layer // public static IOptionService GetFormattingOptions(this IEditorOptionsFactoryService editorOptionsFactory, Document document) // { // return CreateOptions(editorOptionsFactory.GetEditorOptions(document)); // } // private static IOptionService CreateOptions(IEditorOptions editorOptions) // { // return new FormattingOptions( // !editorOptions.IsConvertTabsToSpacesEnabled(), // editorOptions.GetTabSize(), // editorOptions.GetIndentSize()); // } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/EditorFeatures/Core/IOptionPageService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Editor { internal interface IOptionPageService : ILanguageService { void ShowFormattingOptionPage(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.Editor { internal interface IOptionPageService : ILanguageService { void ShowFormattingOptionPage(); } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/Core/Portable/CommandLine/CommandLineSourceFile.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Describes a source file specification stored on command line arguments. /// </summary> [DebuggerDisplay("{Path,nq}")] public struct CommandLineSourceFile { public CommandLineSourceFile(string path, bool isScript) : this(path, isScript, false) { } public CommandLineSourceFile(string path, bool isScript, bool isInputRedirected) { Debug.Assert(!string.IsNullOrEmpty(path)); Path = path; IsScript = isScript; IsInputRedirected = isInputRedirected; } /// <summary> /// Resolved absolute path of the source file (does not contain wildcards). /// </summary> /// <remarks> /// Although this path is absolute it may not be normalized. That is, it may contain ".." and "." in the middle. /// </remarks> public string Path { get; } /// <summary> /// True if the input has been redirected from the standard input stream. /// </summary> public bool IsInputRedirected { get; } /// <summary> /// True if the file should be treated as a script file. /// </summary> public bool IsScript { get; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace Microsoft.CodeAnalysis { /// <summary> /// Describes a source file specification stored on command line arguments. /// </summary> [DebuggerDisplay("{Path,nq}")] public struct CommandLineSourceFile { public CommandLineSourceFile(string path, bool isScript) : this(path, isScript, false) { } public CommandLineSourceFile(string path, bool isScript, bool isInputRedirected) { Debug.Assert(!string.IsNullOrEmpty(path)); Path = path; IsScript = isScript; IsInputRedirected = isInputRedirected; } /// <summary> /// Resolved absolute path of the source file (does not contain wildcards). /// </summary> /// <remarks> /// Although this path is absolute it may not be normalized. That is, it may contain ".." and "." in the middle. /// </remarks> public string Path { get; } /// <summary> /// True if the input has been redirected from the standard input stream. /// </summary> public bool IsInputRedirected { get; } /// <summary> /// True if the file should be treated as a script file. /// </summary> public bool IsScript { get; } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/CSharp/Test/Semantic/Diagnostics/DiagnosticAnalyzerTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.CSharp; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class DiagnosticAnalyzerTests : CompilingTestBase { private class ComplainAboutX : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor s_CA9999_UseOfVariableThatStartsWithX = new DiagnosticDescriptor(id: "CA9999_UseOfVariableThatStartsWithX", title: "CA9999_UseOfVariableThatStartsWithX", messageFormat: "Use of variable whose name starts with 'x': '{0}'", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_CA9999_UseOfVariableThatStartsWithX); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.IdentifierName); } private static void AnalyzeNode(SyntaxNodeAnalysisContext context) { var id = (IdentifierNameSyntax)context.Node; if (id.Identifier.ValueText.StartsWith("x", StringComparison.Ordinal)) { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(s_CA9999_UseOfVariableThatStartsWithX, id.Location, id.Identifier.ValueText)); } } } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void SimplestDiagnosticAnalyzerTest() { string source = @"public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics( // (1,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound") ) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (5,18): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1"), // (5,21): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2"), // (6,16): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x3' // return x3 + 1; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x3").WithArguments("x3") ); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void SimplestDiagnosticAnalyzerTestInInitializer() { string source = @"delegate int D(out int x); public class C : NotFound { static int x1 = 2; static int x2 = 3; int x3 = x1 + x2; D d1 = (out int x4) => (x4 = 1) + @x4; }"; // TODO: Compilation create doesn't accept analyzers anymore. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound") ) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (6,14): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1 + x2; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1"), // (6,19): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1 + x2; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2"), // (7,29): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x4' // D d1 = (out int x4) => (x4 = 1) + @x4; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x4").WithArguments("x4"), // (7,39): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x4' // D d1 = (out int x4) => (x4 = 1) + @x4; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "@x4").WithArguments("x4") ); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void DiagnosticAnalyzerSuppressDiagnostic() { string source = @" public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; // TODO: Compilation create doesn't accept analyzers anymore. var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions( new[] { KeyValuePairUtil.Create("CA9999_UseOfVariableThatStartsWithX", ReportDiagnostic.Suppress) }); CreateCompilationWithMscorlib45(source, options: options/*, analyzers: new IDiagnosticAnalyzerFactory[] { new ComplainAboutX() }*/).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound")); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void DiagnosticAnalyzerWarnAsError() { string source = @" public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; // TODO: Compilation create doesn't accept analyzers anymore. var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions( new[] { KeyValuePairUtil.Create("CA9999_UseOfVariableThatStartsWithX", ReportDiagnostic.Error) }); CreateCompilationWithMscorlib45(source, options: options).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound")) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (6,18): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1").WithWarningAsError(true), // (6,21): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2").WithWarningAsError(true), // (7,16): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x3' // return x3 + 1; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x3").WithArguments("x3").WithWarningAsError(true) ); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void DiagnosticAnalyzerWarnAsErrorGlobal() { string source = @" public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; var options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); CreateCompilationWithMscorlib45(source, options: options).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound") ) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (6,18): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1").WithWarningAsError(true), // (6,21): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2").WithWarningAsError(true), // (7,16): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x3' // return x3 + 1; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x3").WithArguments("x3").WithWarningAsError(true)); } [Fact, WorkItem(1038025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1038025")] public void TestImplicitlyDeclaredSymbolsNotAnalyzed() { string source = @" using System; public class C { public event EventHandler e; }"; CreateCompilationWithMscorlib45(source) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ImplicitlyDeclaredSymbolAnalyzer() }); } private class SyntaxAndSymbolAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor("XX0001", "My Syntax/Symbol Diagnostic", "My Syntax/Symbol Diagnostic for '{0}'", "Compiler", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_descriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.Attribute, SyntaxKind.ClassDeclaration, SyntaxKind.UsingDirective); context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType); } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { switch (context.Node.Kind()) { case SyntaxKind.Attribute: var diag1 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Node.GetLocation(), "Attribute"); context.ReportDiagnostic(diag1); break; case SyntaxKind.ClassDeclaration: var diag2 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Node.GetLocation(), "ClassDeclaration"); context.ReportDiagnostic(diag2); break; case SyntaxKind.UsingDirective: var diag3 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Node.GetLocation(), "UsingDirective"); context.ReportDiagnostic(diag3); break; } } private void AnalyzeSymbol(SymbolAnalysisContext context) { var diag1 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Symbol.Locations[0], "NamedType"); context.ReportDiagnostic(diag1); } } [WorkItem(914236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/914236")] [Fact] public void DiagnosticAnalyzerSyntaxNodeAndSymbolAnalysis() { string source = @" using System; [Obsolete] public class C { }"; var options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); CreateCompilationWithMscorlib45(source, options: options) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new SyntaxAndSymbolAnalyzer() }, null, null, // Symbol diagnostics Diagnostic("XX0001", "C").WithArguments("NamedType").WithWarningAsError(true), // Syntax diagnostics Diagnostic("XX0001", "using System;").WithArguments("UsingDirective").WithWarningAsError(true), // using directive Diagnostic("XX0001", "Obsolete").WithArguments("Attribute").WithWarningAsError(true), // attribute syntax Diagnostic("XX0001", @"[Obsolete] public class C { }").WithArguments("ClassDeclaration").WithWarningAsError(true)); // class declaration } [Fact] public void TestGetEffectiveDiagnostics() { var noneDiagDescriptor = new DiagnosticDescriptor("XX0001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Hidden, isEnabledByDefault: true); var infoDiagDescriptor = new DiagnosticDescriptor("XX0002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Info, isEnabledByDefault: true); var warningDiagDescriptor = new DiagnosticDescriptor("XX0003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); var errorDiagDescriptor = new DiagnosticDescriptor("XX0004", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Error, isEnabledByDefault: true); var noneDiag = CodeAnalysis.Diagnostic.Create(noneDiagDescriptor, Location.None); var infoDiag = CodeAnalysis.Diagnostic.Create(infoDiagDescriptor, Location.None); var warningDiag = CodeAnalysis.Diagnostic.Create(warningDiagDescriptor, Location.None); var errorDiag = CodeAnalysis.Diagnostic.Create(errorDiagDescriptor, Location.None); var diags = new[] { noneDiag, infoDiag, warningDiag, errorDiag }; // Escalate all diagnostics to error. var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(noneDiagDescriptor.Id, ReportDiagnostic.Error); specificDiagOptions.Add(infoDiagDescriptor.Id, ReportDiagnostic.Error); specificDiagOptions.Add(warningDiagDescriptor.Id, ReportDiagnostic.Error); var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); var comp = CreateCompilationWithMscorlib45("", options: options); var effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(diags.Length, effectiveDiags.Length); foreach (var effectiveDiag in effectiveDiags) { Assert.True(effectiveDiag.Severity == DiagnosticSeverity.Error); } // Suppress all diagnostics. specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(noneDiagDescriptor.Id, ReportDiagnostic.Suppress); specificDiagOptions.Add(infoDiagDescriptor.Id, ReportDiagnostic.Suppress); specificDiagOptions.Add(warningDiagDescriptor.Id, ReportDiagnostic.Suppress); specificDiagOptions.Add(errorDiagDescriptor.Id, ReportDiagnostic.Suppress); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(0, effectiveDiags.Length); // Shuffle diagnostic severity. specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(noneDiagDescriptor.Id, ReportDiagnostic.Info); specificDiagOptions.Add(infoDiagDescriptor.Id, ReportDiagnostic.Hidden); specificDiagOptions.Add(warningDiagDescriptor.Id, ReportDiagnostic.Error); specificDiagOptions.Add(errorDiagDescriptor.Id, ReportDiagnostic.Warn); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(diags.Length, effectiveDiags.Length); var diagIds = new HashSet<string>(diags.Select(d => d.Id)); foreach (var effectiveDiag in effectiveDiags) { Assert.True(diagIds.Remove(effectiveDiag.Id)); switch (effectiveDiag.Severity) { case DiagnosticSeverity.Hidden: Assert.Equal(infoDiagDescriptor.Id, effectiveDiag.Id); break; case DiagnosticSeverity.Info: Assert.Equal(noneDiagDescriptor.Id, effectiveDiag.Id); break; case DiagnosticSeverity.Warning: Assert.Equal(errorDiagDescriptor.Id, effectiveDiag.Id); break; case DiagnosticSeverity.Error: Assert.Equal(warningDiagDescriptor.Id, effectiveDiag.Id); break; default: throw ExceptionUtilities.Unreachable; } } Assert.Empty(diagIds); } [Fact] public void TestGetEffectiveDiagnosticsGlobal() { var noneDiagDescriptor = new DiagnosticDescriptor("XX0001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Hidden, isEnabledByDefault: true); var infoDiagDescriptor = new DiagnosticDescriptor("XX0002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Info, isEnabledByDefault: true); var warningDiagDescriptor = new DiagnosticDescriptor("XX0003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); var errorDiagDescriptor = new DiagnosticDescriptor("XX0004", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Error, isEnabledByDefault: true); var noneDiag = Microsoft.CodeAnalysis.Diagnostic.Create(noneDiagDescriptor, Location.None); var infoDiag = Microsoft.CodeAnalysis.Diagnostic.Create(infoDiagDescriptor, Location.None); var warningDiag = Microsoft.CodeAnalysis.Diagnostic.Create(warningDiagDescriptor, Location.None); var errorDiag = Microsoft.CodeAnalysis.Diagnostic.Create(errorDiagDescriptor, Location.None); var diags = new[] { noneDiag, infoDiag, warningDiag, errorDiag }; var options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Default); var comp = CreateCompilationWithMscorlib45("", options: options); var effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.IsWarningAsError)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Warn); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Warning)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Info); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Info)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Hidden); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Hidden)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Suppress); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(2, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Hidden)); } [Fact] public void TestDisabledDiagnostics() { var disabledDiagDescriptor = new DiagnosticDescriptor("XX001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); var enabledDiagDescriptor = new DiagnosticDescriptor("XX002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); var disabledDiag = CodeAnalysis.Diagnostic.Create(disabledDiagDescriptor, Location.None); var enabledDiag = CodeAnalysis.Diagnostic.Create(enabledDiagDescriptor, Location.None); var diags = new[] { disabledDiag, enabledDiag }; // Verify that only the enabled diag shows up after filtering. var options = TestOptions.ReleaseDll; var comp = CreateCompilationWithMscorlib45("", options: options); var effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(1, effectiveDiags.Length); Assert.Contains(enabledDiag, effectiveDiags); // If the disabled diag was enabled through options, then it should show up. var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(disabledDiagDescriptor.Id, ReportDiagnostic.Warn); specificDiagOptions.Add(enabledDiagDescriptor.Id, ReportDiagnostic.Suppress); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(1, effectiveDiags.Length); Assert.Contains(disabledDiag, effectiveDiags); } internal class FullyDisabledAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor desc1 = new DiagnosticDescriptor("XX001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public static DiagnosticDescriptor desc2 = new DiagnosticDescriptor("XX002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public static DiagnosticDescriptor desc3 = new DiagnosticDescriptor("XX003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false, customTags: WellKnownDiagnosticTags.NotConfigurable); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(desc1, desc2, desc3); } } public override void Initialize(AnalysisContext context) { } } internal class PartiallyDisabledAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor desc1 = new DiagnosticDescriptor("XX003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public static DiagnosticDescriptor desc2 = new DiagnosticDescriptor("XX004", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(desc1, desc2); } } public override void Initialize(AnalysisContext context) { } } internal class ImplicitlyDeclaredSymbolAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor desc1 = new DiagnosticDescriptor("DummyId", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(desc1); } } public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction( (c) => { Assert.False(c.Symbol.IsImplicitlyDeclared); }, SymbolKind.Namespace, SymbolKind.NamedType, SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.Property); } } [Fact] public void TestDisabledAnalyzers() { var fullyDisabledAnalyzer = new FullyDisabledAnalyzer(); var partiallyDisabledAnalyzer = new PartiallyDisabledAnalyzer(); var options = TestOptions.ReleaseDll; Assert.True(fullyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); Assert.False(partiallyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(FullyDisabledAnalyzer.desc1.Id, ReportDiagnostic.Warn); specificDiagOptions.Add(PartiallyDisabledAnalyzer.desc2.Id, ReportDiagnostic.Suppress); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); Assert.False(fullyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); Assert.True(partiallyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); // Verify not configurable disabled diagnostic cannot be enabled, and hence cannot affect IsDiagnosticAnalyzerSuppressed computation. specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(FullyDisabledAnalyzer.desc3.Id, ReportDiagnostic.Warn); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); Assert.True(fullyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); } [Fact, WorkItem(1008059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1008059")] public void TestCodeBlockAnalyzersForNoExecutableCode() { string noExecutableCodeSource = @" public abstract class C { public int P { get; set; } public int field; public abstract int Method(); }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: true) }; CreateCompilationWithMscorlib45(noExecutableCodeSource) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers); } [Fact, WorkItem(1008059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1008059")] public void TestCodeBlockAnalyzersForBaseConstructorInitializer() { string baseCtorSource = @" public class B { public B(int x) {} } public class C : B { public C() : base(x: 10) {} }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: true) }; CreateCompilationWithMscorlib45(baseCtorSource) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ConstructorInitializerDiagnostic"), Diagnostic("CodeBlockDiagnostic"), Diagnostic("CodeBlockDiagnostic")); } [Fact, WorkItem(1067286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067286")] public void TestCodeBlockAnalyzersForExpressionBody() { string source = @" public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: true) }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("CodeBlockDiagnostic"), Diagnostic("CodeBlockDiagnostic"), Diagnostic("CodeBlockDiagnostic"), Diagnostic("PropertyExpressionBodyDiagnostic"), Diagnostic("IndexerExpressionBodyDiagnostic"), Diagnostic("MethodExpressionBodyDiagnostic")); } [Fact, WorkItem(592, "https://github.com/dotnet/roslyn/issues/592")] public void TestSyntaxNodeAnalyzersForExpressionBody() { string source = @" public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: false) }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("PropertyExpressionBodyDiagnostic"), Diagnostic("IndexerExpressionBodyDiagnostic"), Diagnostic("MethodExpressionBodyDiagnostic")); } [Fact, WorkItem(592, "https://github.com/dotnet/roslyn/issues/592")] public void TestMethodSymbolAnalyzersForExpressionBody() { string source = @" public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; }"; var analyzers = new DiagnosticAnalyzer[] { new MethodSymbolAnalyzer() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("MethodSymbolDiagnostic", "0").WithArguments("B.Property.get").WithLocation(4, 28), Diagnostic("MethodSymbolDiagnostic", "Method").WithArguments("B.Method()").WithLocation(5, 16), Diagnostic("MethodSymbolDiagnostic", "0").WithArguments("B.this[int].get").WithLocation(6, 31)); } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class FieldDeclarationAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "MyFieldDiagnostic"; internal const string Title = "MyFieldDiagnostic"; internal const string MessageFormat = "MyFieldDiagnostic"; internal const string Category = "Naming"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration); } private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) { var fieldDeclaration = (FieldDeclarationSyntax)context.Node; var diagnostic = CodeAnalysis.Diagnostic.Create(Rule, fieldDeclaration.GetLocation()); context.ReportDiagnostic(diagnostic); } } [Fact] public void TestNoDuplicateCallbacksForFieldDeclaration() { string source = @" public class B { public string field = ""field""; }"; var analyzers = new DiagnosticAnalyzer[] { new FieldDeclarationAnalyzer() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("MyFieldDiagnostic", @"public string field = ""field"";").WithLocation(4, 5)); } [Fact, WorkItem(565, "https://github.com/dotnet/roslyn/issues/565")] public void TestCallbacksForFieldDeclarationWithMultipleVariables() { string source = @" public class B { public string field1, field2; public int field3 = 0, field4 = 1; public int field5, field6 = 1; }"; var analyzers = new DiagnosticAnalyzer[] { new FieldDeclarationAnalyzer() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("MyFieldDiagnostic", @"public string field1, field2;").WithLocation(4, 5), Diagnostic("MyFieldDiagnostic", @"public int field3 = 0, field4 = 1;").WithLocation(5, 5), Diagnostic("MyFieldDiagnostic", @"public int field5, field6 = 1;").WithLocation(6, 5)); } [Fact, WorkItem(1096600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1096600")] public void TestDescriptorForConfigurableCompilerDiagnostics() { // Verify that all configurable compiler diagnostics, i.e. all non-error diagnostics, // have a non-null and non-empty Title and Category. // These diagnostic descriptor fields show up in the ruleset editor and hence must have a valid value. var analyzer = new CSharpCompilerDiagnosticAnalyzer(); foreach (var descriptor in analyzer.SupportedDiagnostics) { Assert.True(descriptor.IsEnabledByDefault); if (descriptor.IsNotConfigurable()) { continue; } var title = descriptor.Title.ToString(); if (string.IsNullOrEmpty(title)) { var id = Int32.Parse(descriptor.Id.Substring(2)); var missingResource = Enum.GetName(typeof(ErrorCode), id) + "_Title"; var message = string.Format("Add resource string named '{0}' for Title of '{1}' to '{2}'", missingResource, descriptor.Id, nameof(CSharpResources)); // This assert will fire if you are adding a new compiler diagnostic (non-error severity), // but did not add a title resource string for the diagnostic. Assert.True(false, message); } var category = descriptor.Category; if (string.IsNullOrEmpty(title)) { var message = string.Format("'{0}' must have a non-null non-empty 'Category'", descriptor.Id); Assert.True(false, message); } } } public class CodeBlockOrSyntaxNodeAnalyzer : DiagnosticAnalyzer { private readonly bool _isCodeBlockAnalyzer; public static DiagnosticDescriptor Descriptor1 = DescriptorFactory.CreateSimpleDescriptor("CodeBlockDiagnostic"); public static DiagnosticDescriptor Descriptor2 = DescriptorFactory.CreateSimpleDescriptor("EqualsValueDiagnostic"); public static DiagnosticDescriptor Descriptor3 = DescriptorFactory.CreateSimpleDescriptor("ConstructorInitializerDiagnostic"); public static DiagnosticDescriptor Descriptor4 = DescriptorFactory.CreateSimpleDescriptor("PropertyExpressionBodyDiagnostic"); public static DiagnosticDescriptor Descriptor5 = DescriptorFactory.CreateSimpleDescriptor("IndexerExpressionBodyDiagnostic"); public static DiagnosticDescriptor Descriptor6 = DescriptorFactory.CreateSimpleDescriptor("MethodExpressionBodyDiagnostic"); public CodeBlockOrSyntaxNodeAnalyzer(bool isCodeBlockAnalyzer) { _isCodeBlockAnalyzer = isCodeBlockAnalyzer; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor1, Descriptor2, Descriptor3, Descriptor4, Descriptor5, Descriptor6); } } public override void Initialize(AnalysisContext context) { if (_isCodeBlockAnalyzer) { context.RegisterCodeBlockStartAction<SyntaxKind>(OnCodeBlockStarted); context.RegisterCodeBlockAction(OnCodeBlockEnded); } else { Action<Action<SyntaxNodeAnalysisContext>, ImmutableArray<SyntaxKind>> registerMethod = (action, Kinds) => context.RegisterSyntaxNodeAction(action, Kinds); var analyzer = new NodeAnalyzer(); analyzer.Initialize(registerMethod); } } public static void OnCodeBlockEnded(CodeBlockAnalysisContext context) { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor1, Location.None)); } public static void OnCodeBlockStarted(CodeBlockStartAnalysisContext<SyntaxKind> context) { Action<Action<SyntaxNodeAnalysisContext>, ImmutableArray<SyntaxKind>> registerMethod = (action, Kinds) => context.RegisterSyntaxNodeAction(action, Kinds); var analyzer = new NodeAnalyzer(); analyzer.Initialize(registerMethod); } protected class NodeAnalyzer { public void Initialize(Action<Action<SyntaxNodeAnalysisContext>, ImmutableArray<SyntaxKind>> registerSyntaxNodeAction) { registerSyntaxNodeAction(context => { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor2, Location.None)); }, ImmutableArray.Create(SyntaxKind.EqualsValueClause)); registerSyntaxNodeAction(context => { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor3, Location.None)); }, ImmutableArray.Create(SyntaxKind.BaseConstructorInitializer)); registerSyntaxNodeAction(context => { var descriptor = (DiagnosticDescriptor)null; switch (CSharpExtensions.Kind(context.Node.Parent)) { case SyntaxKind.PropertyDeclaration: descriptor = Descriptor4; break; case SyntaxKind.IndexerDeclaration: descriptor = Descriptor5; break; default: descriptor = Descriptor6; break; } context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(descriptor, Location.None)); }, ImmutableArray.Create(SyntaxKind.ArrowExpressionClause)); } } } public class MethodSymbolAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor Descriptor1 = new DiagnosticDescriptor("MethodSymbolDiagnostic", "MethodSymbolDiagnostic", "{0}", "MethodSymbolDiagnostic", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor1); } } public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(ctxt => { var method = ((IMethodSymbol)ctxt.Symbol); ctxt.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor1, method.Locations[0], method.ToDisplayString())); }, SymbolKind.Method); } } [Fact, WorkItem(252, "https://github.com/dotnet/roslyn/issues/252"), WorkItem(1392, "https://github.com/dotnet/roslyn/issues/1392")] public void TestReportingUnsupportedDiagnostic() { string source = @""; CSharpCompilation compilation = CreateCompilationWithMscorlib45(source); var analyzer = new AnalyzerReportingUnsupportedDiagnostic(); var analyzers = new DiagnosticAnalyzer[] { analyzer }; string message = new ArgumentException(string.Format(CodeAnalysisResources.UnsupportedDiagnosticReported, AnalyzerReportingUnsupportedDiagnostic.UnsupportedDescriptor.Id), "diagnostic").Message; IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: {compilation.AssemblyName}")} {new LazyToString(() => analyzer.ThrownException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ID_1")}"; compilation .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CSharp.UnitTests.DiagnosticAnalyzerTests+AnalyzerReportingUnsupportedDiagnostic", "System.ArgumentException", message, context) .WithLocation(1, 1)); } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class AnalyzerReportingUnsupportedDiagnostic : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor SupportedDescriptor = new DiagnosticDescriptor("ID_1", "DummyTitle", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor UnsupportedDescriptor = new DiagnosticDescriptor("ID_2", "DummyTitle", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public Exception ThrownException { get; set; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(SupportedDescriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => { try { ThrownException = null; compilationContext.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(UnsupportedDescriptor, Location.None)); } catch (Exception e) { ThrownException = e; throw; } }); } } [Fact, WorkItem(4376, "https://github.com/dotnet/roslyn/issues/4376")] public void TestReportingDiagnosticWithInvalidId() { string source = @""; CSharpCompilation compilation = CreateCompilationWithMscorlib45(source); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithInvalidDiagnosticId() }; string message = new ArgumentException(string.Format(CodeAnalysisResources.InvalidDiagnosticIdReported, AnalyzerWithInvalidDiagnosticId.Descriptor.Id), "diagnostic").Message; Exception analyzerException = null; IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: {compilation.AssemblyName}")} {new LazyToString(() => analyzerException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "Invalid ID")}"; EventHandler<FirstChanceExceptionEventArgs> firstChanceException = (sender, e) => { if (e.Exception is ArgumentException && e.Exception.Message == message) { analyzerException = e.Exception; } }; try { AppDomain.CurrentDomain.FirstChanceException += firstChanceException; compilation .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithInvalidDiagnosticId", "System.ArgumentException", message, context) .WithLocation(1, 1)); } finally { AppDomain.CurrentDomain.FirstChanceException -= firstChanceException; } } [Fact, WorkItem(30453, "https://github.com/dotnet/roslyn/issues/30453")] public void TestAnalyzerWithNullDescriptor() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithNullDescriptor() }; var analyzerFullName = "Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithNullDescriptor"; string message = new ArgumentException(string.Format(CodeAnalysisResources.SupportedDiagnosticsHasNullDescriptor, analyzerFullName), "SupportedDiagnostics").Message; Exception analyzerException = null; IFormattable context = $@"{new LazyToString(() => analyzerException)} -----"; EventHandler<FirstChanceExceptionEventArgs> firstChanceException = (sender, e) => { if (e.Exception is ArgumentException && e.Exception.Message == message) { analyzerException = e.Exception; } }; try { AppDomain.CurrentDomain.FirstChanceException += firstChanceException; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments(analyzerFullName, "System.ArgumentException", message, context) .WithLocation(1, 1)); } finally { AppDomain.CurrentDomain.FirstChanceException -= firstChanceException; } } [Fact, WorkItem(25748, "https://github.com/dotnet/roslyn/issues/25748")] public void TestReportingDiagnosticWithCSharpCompilerId() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithCSharpCompilerDiagnosticId() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("CS101").WithLocation(1, 1)); } [Fact, WorkItem(25748, "https://github.com/dotnet/roslyn/issues/25748")] public void TestReportingDiagnosticWithBasicCompilerId() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithBasicCompilerDiagnosticId() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("BC101").WithLocation(1, 1)); } [Theory, WorkItem(7173, "https://github.com/dotnet/roslyn/issues/7173")] [CombinatorialData] public void TestReportingDiagnosticWithInvalidLocation(AnalyzerWithInvalidDiagnosticLocation.ActionKind actionKind) { var source1 = @"class C1 { void M() { int i = 0; i++; } }"; var source2 = @"class C2 { void M() { int i = 0; i++; } }"; var compilation = CreateCompilationWithMscorlib45(source1); var anotherCompilation = CreateCompilationWithMscorlib45(source2); var treeInAnotherCompilation = anotherCompilation.SyntaxTrees.Single(); string message = new ArgumentException( string.Format(CodeAnalysisResources.InvalidDiagnosticLocationReported, AnalyzerWithInvalidDiagnosticLocation.Descriptor.Id, treeInAnotherCompilation.FilePath), "diagnostic").Message; compilation.VerifyDiagnostics(); var analyzer = new AnalyzerWithInvalidDiagnosticLocation(treeInAnotherCompilation, actionKind); var analyzers = new DiagnosticAnalyzer[] { analyzer }; Exception analyzerException = null; string contextDetail; switch (actionKind) { case AnalyzerWithInvalidDiagnosticLocation.ActionKind.Symbol: contextDetail = $@"Compilation: {compilation.AssemblyName} ISymbol: C1 (NamedType)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.CodeBlock: contextDetail = $@"Compilation: {compilation.AssemblyName} ISymbol: M (Method) SyntaxTree: SyntaxNode: void M() {{ int i = 0; i++; }} [MethodDeclarationSyntax]@[11..39) (0,11)-(0,39)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.Operation: contextDetail = $@"Compilation: {compilation.AssemblyName} IOperation: VariableDeclarationGroup SyntaxTree: SyntaxNode: int i = 0; [LocalDeclarationStatementSyntax]@[22..32) (0,22)-(0,32)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.OperationBlockEnd: contextDetail = $@"Compilation: {compilation.AssemblyName} ISymbol: M (Method)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.Compilation: case AnalyzerWithInvalidDiagnosticLocation.ActionKind.CompilationEnd: contextDetail = $@"Compilation: {compilation.AssemblyName}"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.SyntaxTree: contextDetail = $@"Compilation: {compilation.AssemblyName} SyntaxTree: "; break; default: throw ExceptionUtilities.Unreachable; } IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, contextDetail)} {new LazyToString(() => analyzerException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ID")}"; EventHandler<FirstChanceExceptionEventArgs> firstChanceException = (sender, e) => { if (e.Exception is ArgumentException && e.Exception.Message == message) { analyzerException = e.Exception; } }; try { AppDomain.CurrentDomain.FirstChanceException += firstChanceException; compilation .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithInvalidDiagnosticLocation", "System.ArgumentException", message, context) .WithLocation(1, 1) ); } finally { AppDomain.CurrentDomain.FirstChanceException -= firstChanceException; } } [Fact] public void TestReportingDiagnosticWithInvalidSpan() { var source1 = @"class C1 { void M() { int i = 0; i++; } }"; var compilation = CreateCompilationWithMscorlib45(source1); var treeInAnotherCompilation = compilation.SyntaxTrees.Single(); var badSpan = new Text.TextSpan(100000, 10000); var analyzer = new AnalyzerWithInvalidDiagnosticSpan(badSpan); string message = new ArgumentException( string.Format(CodeAnalysisResources.InvalidDiagnosticSpanReported, AnalyzerWithInvalidDiagnosticSpan.Descriptor.Id, badSpan, treeInAnotherCompilation.FilePath), "diagnostic").Message; IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: {compilation.AssemblyName} SyntaxTree: ")} {new LazyToString(() => analyzer.ThrownException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ID")}"; compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { analyzer }; compilation .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithInvalidDiagnosticSpan", "System.ArgumentException", message, context) .WithLocation(1, 1) ); } [Fact, WorkItem(1473, "https://github.com/dotnet/roslyn/issues/1473")] public void TestReportingNotConfigurableDiagnostic() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new NotConfigurableDiagnosticAnalyzer() }; // Verify, not configurable enabled diagnostic is always reported and disabled diagnostic is never reported.. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id)); // Verify not configurable enabled diagnostic cannot be suppressed. var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id, ReportDiagnostic.Suppress); var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); CreateCompilationWithMscorlib45(source, options: options) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id)); // Verify not configurable disabled diagnostic cannot be enabled. specificDiagOptions.Clear(); specificDiagOptions.Add(NotConfigurableDiagnosticAnalyzer.DisabledRule.Id, ReportDiagnostic.Warn); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); CreateCompilationWithMscorlib45(source, options: options) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id)); } [Fact, WorkItem(1709, "https://github.com/dotnet/roslyn/issues/1709")] public void TestCodeBlockAction() { string source = @" class C { public void M() {} }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockActionAnalyzer() }; // Verify, code block action diagnostics. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: new[] { Diagnostic(CodeBlockActionAnalyzer.CodeBlockTopLevelRule.Id, "M").WithArguments("M").WithLocation(4, 17), Diagnostic(CodeBlockActionAnalyzer.CodeBlockPerCompilationRule.Id, "M").WithArguments("M").WithLocation(4, 17) }); } [Fact, WorkItem(1709, "https://github.com/dotnet/roslyn/issues/1709")] public void TestCodeBlockAction_OnlyStatelessAction() { string source = @" class C { public void M() {} }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockActionAnalyzer(onlyStatelessAction: true) }; // Verify, code block action diagnostics. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(CodeBlockActionAnalyzer.CodeBlockTopLevelRule.Id, "M").WithArguments("M").WithLocation(4, 17)); } [Fact, WorkItem(2614, "https://github.com/dotnet/roslyn/issues/2614")] public void TestGenericName() { var source = @" using System; using System.Text; namespace ConsoleApplication1 { class MyClass { private Nullable<int> myVar = 5; void Method() { } } }"; TestGenericNameCore(source, new CSharpGenericNameAnalyzer()); } private void TestGenericNameCore(string source, params DiagnosticAnalyzer[] analyzers) { // Verify, no duplicate diagnostics on generic name. CreateCompilationWithMscorlib45(source) .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic(CSharpGenericNameAnalyzer.DiagnosticId, @"Nullable<int>").WithLocation(9, 17)); } [Fact, WorkItem(4745, "https://github.com/dotnet/roslyn/issues/4745")] public void TestNamespaceDeclarationAnalyzer() { var source = @" namespace Goo.Bar.GooBar { } "; var analyzers = new DiagnosticAnalyzer[] { new CSharpNamespaceDeclarationAnalyzer() }; // Verify, no duplicate diagnostics on qualified name. CreateCompilationWithMscorlib45(source) .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic(CSharpNamespaceDeclarationAnalyzer.DiagnosticId, @"namespace Goo.Bar.GooBar { }").WithLocation(2, 1)); } [Fact, WorkItem(2980, "https://github.com/dotnet/roslyn/issues/2980")] public void TestAnalyzerWithNoActions() { var source = @" using System; using System.Text; namespace ConsoleApplication1 { class MyClass { private Nullable<int> myVar = 5; void Method() { } } }"; // Ensure that adding a dummy analyzer with no actions doesn't bring down entire analysis. // See https://github.com/dotnet/roslyn/issues/2980 for details. TestGenericNameCore(source, new AnalyzerWithNoActions(), new CSharpGenericNameAnalyzer()); } [Fact, WorkItem(4055, "https://github.com/dotnet/roslyn/issues/4055")] public void TestAnalyzerWithNoSupportedDiagnostics() { var source = @" class MyClass { }"; // Ensure that adding a dummy analyzer with no supported diagnostics doesn't bring down entire analysis. var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithNoSupportedDiagnostics() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers); } private static void TestEffectiveSeverity( DiagnosticSeverity defaultSeverity, ReportDiagnostic expectedEffectiveSeverity, Dictionary<string, ReportDiagnostic> specificOptions = null, ReportDiagnostic generalOption = ReportDiagnostic.Default, bool isEnabledByDefault = true) { specificOptions = specificOptions ?? new Dictionary<string, ReportDiagnostic>(); var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication, generalDiagnosticOption: generalOption, specificDiagnosticOptions: specificOptions); var descriptor = new DiagnosticDescriptor(id: "Test0001", title: "Test0001", messageFormat: "Test0001", category: "Test0001", defaultSeverity: defaultSeverity, isEnabledByDefault: isEnabledByDefault); var effectiveSeverity = descriptor.GetEffectiveSeverity(options); Assert.Equal(expectedEffectiveSeverity, effectiveSeverity); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_DiagnosticDefault1() { TestEffectiveSeverity(DiagnosticSeverity.Warning, ReportDiagnostic.Warn); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_DiagnosticDefault2() { var specificOptions = new Dictionary<string, ReportDiagnostic>() { { "Test0001", ReportDiagnostic.Default } }; var generalOption = ReportDiagnostic.Error; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: ReportDiagnostic.Warn, specificOptions: specificOptions, generalOption: generalOption); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_GeneralOption() { var generalOption = ReportDiagnostic.Error; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: generalOption, generalOption: generalOption); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_SpecificOption() { var specificOption = ReportDiagnostic.Suppress; var specificOptions = new Dictionary<string, ReportDiagnostic>() { { "Test0001", specificOption } }; var generalOption = ReportDiagnostic.Error; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: specificOption, specificOptions: specificOptions, generalOption: generalOption); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_GeneralOptionDoesNotEnableDisabledDiagnostic() { var generalOption = ReportDiagnostic.Error; var enabledByDefault = false; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: ReportDiagnostic.Suppress, generalOption: generalOption, isEnabledByDefault: enabledByDefault); } [Fact()] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_SpecificOptionEnablesDisabledDiagnostic() { var specificOption = ReportDiagnostic.Warn; var specificOptions = new Dictionary<string, ReportDiagnostic>() { { "Test0001", specificOption } }; var generalOption = ReportDiagnostic.Error; var enabledByDefault = false; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: specificOption, specificOptions: specificOptions, generalOption: generalOption, isEnabledByDefault: enabledByDefault); } [Fact, WorkItem(5463, "https://github.com/dotnet/roslyn/issues/5463")] public void TestObjectCreationInCodeBlockAnalyzer() { string source = @" class C { } class D { public C x = new C(); }"; var analyzers = new DiagnosticAnalyzer[] { new CSharpCodeBlockObjectCreationAnalyzer() }; // Verify, code block action diagnostics. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: new[] { Diagnostic(CSharpCodeBlockObjectCreationAnalyzer.DiagnosticDescriptor.Id, "new C()").WithLocation(5, 18) }); } private static Compilation GetCompilationWithConcurrentBuildEnabled(string source) { var compilation = CreateCompilationWithMscorlib45(source); // NOTE: We set the concurrentBuild option to true after creating the compilation as CreateCompilationWithMscorlib // always sets concurrentBuild to false if debugger is attached, even if we had passed options with concurrentBuild = true to that API. // We want the tests using GetCompilationWithConcurrentBuildEnabled to have identical behavior with and without debugger being attached. var options = compilation.Options.WithConcurrentBuild(true); return compilation.WithOptions(options); } [Fact, WorkItem(6737, "https://github.com/dotnet/roslyn/issues/6737")] public void TestNonConcurrentAnalyzer() { var builder = new StringBuilder(); var typeCount = 100; for (int i = 1; i <= typeCount; i++) { var typeName = $"C{i}"; builder.Append($"\r\nclass {typeName} {{ }}"); } var source = builder.ToString(); var analyzers = new DiagnosticAnalyzer[] { new NonConcurrentAnalyzer() }; // Verify no diagnostics. var compilation = GetCompilationWithConcurrentBuildEnabled(source); compilation.VerifyDiagnostics(); compilation.VerifyAnalyzerDiagnostics(analyzers); } [Fact, WorkItem(6737, "https://github.com/dotnet/roslyn/issues/6737")] public void TestConcurrentAnalyzer() { if (Environment.ProcessorCount <= 1) { // Don't test for non-concurrent environment. return; } var builder = new StringBuilder(); var typeCount = 100; var typeNames = new string[typeCount]; for (int i = 1; i <= typeCount; i++) { var typeName = $"C{i}"; typeNames[i - 1] = typeName; builder.Append($"\r\nclass {typeName} {{ }}"); } var source = builder.ToString(); var compilation = GetCompilationWithConcurrentBuildEnabled(source); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics for Concurrent analyzer only. var analyzers = new DiagnosticAnalyzer[] { new ConcurrentAnalyzer(typeNames) }; var expected = new DiagnosticDescription[typeCount]; for (int i = 0; i < typeCount; i++) { var typeName = $"C{i + 1}"; expected[i] = Diagnostic(ConcurrentAnalyzer.Descriptor.Id, typeName) .WithArguments(typeName) .WithLocation(i + 2, 7); } compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); // Verify analyzer diagnostics for Concurrent and NonConcurrent analyzer together (latter reports diagnostics only for error cases). analyzers = new DiagnosticAnalyzer[] { new ConcurrentAnalyzer(typeNames), new NonConcurrentAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(6998, "https://github.com/dotnet/roslyn/issues/6998")] public void TestGeneratedCodeAnalyzer() { string source = @" [System.CodeDom.Compiler.GeneratedCodeAttribute(""tool"", ""version"")] class GeneratedCode{0} {{ private class Nested{0} {{ }} }} class NonGeneratedCode{0} {{ [System.CodeDom.Compiler.GeneratedCodeAttribute(""tool"", ""version"")] private class NestedGeneratedCode{0} {{ }} }} "; var generatedFileNames = new List<string> { "TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs", "Test.designer.cs", "Test.Designer.cs", "Test.generated.cs", "Test.g.cs", "Test.g.i.cs" }; var builder = ImmutableArray.CreateBuilder<SyntaxTree>(); int treeNum = 0; // Trees with non-generated code file names var tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "SourceFileRegular.cs"); builder.Add(tree); tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "AssemblyInfo.cs"); builder.Add(tree); // Trees with generated code file names foreach (var fileName in generatedFileNames) { tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: fileName); builder.Add(tree); } var autoGeneratedPrefixes = new[] { @"// <auto-generated>", @"// <autogenerated>", @"/* <auto-generated> */" }; for (var i = 0; i < autoGeneratedPrefixes.Length; i++) { // Tree with '<auto-generated>' comment var autoGeneratedPrefix = autoGeneratedPrefixes[i]; tree = CSharpSyntaxTree.ParseText(string.Format(autoGeneratedPrefix + source, treeNum++), path: $"SourceFileWithAutoGeneratedComment{i++}.cs"); builder.Add(tree); } // Files with editorconfig based "generated_code" configuration var analyzerConfigOptionsPerTreeBuilder = ImmutableDictionary.CreateBuilder<object, AnalyzerConfigOptions>(); // (1) "generated_code = true" const string myGeneratedFileTrueName = "MyGeneratedFileTrue.cs"; generatedFileNames.Add(myGeneratedFileTrueName); tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: myGeneratedFileTrueName); builder.Add(tree); var analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "true")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); // (2) "generated_code = TRUE" (case insensitive) const string myGeneratedFileCaseInsensitiveTrueName = "MyGeneratedFileCaseInsensitiveTrue.cs"; generatedFileNames.Add(myGeneratedFileCaseInsensitiveTrueName); tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: myGeneratedFileCaseInsensitiveTrueName); builder.Add(tree); analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "TRUE")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); // (3) "generated_code = false" tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "MyGeneratedFileFalse.cs"); builder.Add(tree); analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "false")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); // (4) "generated_code = auto" tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "MyGeneratedFileAuto.cs"); builder.Add(tree); analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "auto")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); var analyzerConfigOptionsProvider = new CompilerAnalyzerConfigOptionsProvider(analyzerConfigOptionsPerTreeBuilder.ToImmutable(), CompilerAnalyzerConfigOptions.Empty); var analyzerOptions = new AnalyzerOptions(additionalFiles: ImmutableArray<AdditionalText>.Empty, analyzerConfigOptionsProvider); // Verify no compiler diagnostics. var trees = builder.ToImmutable(); var compilation = CreateCompilationWithMscorlib45(trees, new MetadataReference[] { SystemRef }); compilation.VerifyDiagnostics(); Func<string, bool> isGeneratedFile = fileName => fileName.Contains("SourceFileWithAutoGeneratedComment") || generatedFileNames.Contains(fileName); // (1) Verify default mode of analysis when there is no generated code configuration. VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, generatedCodeAnalysisFlagsOpt: null); // (2) Verify ConfigureGeneratedCodeAnalysis with different combinations of GeneratedCodeAnalysisFlags. VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.None); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.Analyze); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.ReportDiagnostics); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); // (4) Ensure warnaserror doesn't produce noise in generated files. var options = compilation.Options.WithGeneralDiagnosticOption(ReportDiagnostic.Error); var warnAsErrorCompilation = compilation.WithOptions(options); VerifyGeneratedCodeAnalyzerDiagnostics(warnAsErrorCompilation, analyzerOptions, isGeneratedFile, generatedCodeAnalysisFlagsOpt: null); } [Fact, WorkItem(6998, "https://github.com/dotnet/roslyn/issues/6998")] public void TestGeneratedCodeAnalyzerPartialType() { string source = @" [System.CodeDom.Compiler.GeneratedCodeAttribute(""tool"", ""version"")] partial class PartialType { } partial class PartialType { } "; var tree = CSharpSyntaxTree.ParseText(source, path: "SourceFileRegular.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }, new MetadataReference[] { SystemRef }); compilation.VerifyDiagnostics(); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); // Expected symbol diagnostics var squiggledText = "PartialType"; var diagnosticArgument = squiggledText; var line = 3; var column = 15; AddExpectedLocalDiagnostics(builder, false, squiggledText, line, column, GeneratedCodeAnalysisFlags.ReportDiagnostics, diagnosticArgument); // Expected tree diagnostics squiggledText = "}"; diagnosticArgument = tree.FilePath; line = 9; column = 1; AddExpectedLocalDiagnostics(builder, false, squiggledText, line, column, GeneratedCodeAnalysisFlags.ReportDiagnostics, diagnosticArgument); // Expected compilation diagnostics AddExpectedNonLocalDiagnostic(builder, "PartialType", compilation.SyntaxTrees[0].FilePath); var expected = builder.ToArrayAndFree(); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, generatedCodeAnalysisFlagsOpt: null); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.None); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.Analyze); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.ReportDiagnostics); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); } [Fact, WorkItem(11217, "https://github.com/dotnet/roslyn/issues/11217")] public void TestGeneratedCodeAnalyzerNoReportDiagnostics() { string source1 = @" class TypeInUserFile { } "; string source2 = @" class TypeInGeneratedFile { } "; var tree1 = CSharpSyntaxTree.ParseText(source1, path: "SourceFileRegular.cs"); var tree2 = CSharpSyntaxTree.ParseText(source2, path: "SourceFileRegular.Designer.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }, new MetadataReference[] { SystemRef }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer2() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("GeneratedCodeAnalyzer2Warning", "TypeInUserFile").WithArguments("TypeInUserFile", "2").WithLocation(2, 7)); } internal class OwningSymbolTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor ExpressionDescriptor = new DiagnosticDescriptor( "Expression", "Expression", "Expression found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(ExpressionDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction( (nodeContext) => { if (nodeContext.ContainingSymbol.Name.StartsWith("Funky") && nodeContext.Compilation.Language == "C#") { nodeContext.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(ExpressionDescriptor, nodeContext.Node.GetLocation())); } }, SyntaxKind.IdentifierName, SyntaxKind.NumericLiteralExpression); } } [Fact] public void OwningSymbolTest() { const string source = @" class C { public void UnFunkyMethod() { int x = 0; int y = x; } public void FunkyMethod() { int x = 0; int y = x; } public int FunkyField = 12; public int UnFunkyField = 12; } "; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new OwningSymbolTestAnalyzer() }, null, null, Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "0").WithLocation(12, 17), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "x").WithLocation(13, 17), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "12").WithLocation(16, 29)); } private static void VerifyGeneratedCodeAnalyzerDiagnostics(Compilation compilation, AnalyzerOptions analyzerOptions, Func<string, bool> isGeneratedFileName, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt) { var expected = GetExpectedGeneratedCodeAnalyzerDiagnostics(compilation, isGeneratedFileName, generatedCodeAnalysisFlagsOpt); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, generatedCodeAnalysisFlagsOpt, analyzerOptions); } private static void VerifyGeneratedCodeAnalyzerDiagnostics(Compilation compilation, DiagnosticDescription[] expected, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt, AnalyzerOptions analyzerOptions = null) { var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(generatedCodeAnalysisFlagsOpt) }; compilation.VerifyAnalyzerDiagnostics(analyzers, analyzerOptions, null, expected: expected); } private static DiagnosticDescription[] GetExpectedGeneratedCodeAnalyzerDiagnostics(Compilation compilation, Func<string, bool> isGeneratedFileName, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt) { var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(generatedCodeAnalysisFlagsOpt) }; var files = compilation.SyntaxTrees.Select(t => t.FilePath).ToImmutableArray(); var sortedCallbackSymbolNames = new SortedSet<string>(); var sortedCallbackTreePaths = new SortedSet<string>(); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); for (int i = 0; i < compilation.SyntaxTrees.Count(); i++) { var file = files[i]; var isGeneratedFile = isGeneratedFileName(file); // Type "GeneratedCode{0}" var squiggledText = string.Format("GeneratedCode{0}", i); var diagnosticArgument = squiggledText; var line = 3; var column = 7; var isGeneratedCode = true; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Type "Nested{0}" squiggledText = string.Format("Nested{0}", i); diagnosticArgument = squiggledText; line = 5; column = 19; isGeneratedCode = true; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Type "NonGeneratedCode{0}" squiggledText = string.Format("NonGeneratedCode{0}", i); diagnosticArgument = squiggledText; line = 8; column = 7; isGeneratedCode = isGeneratedFile; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Type "NestedGeneratedCode{0}" squiggledText = string.Format("NestedGeneratedCode{0}", i); diagnosticArgument = squiggledText; line = 11; column = 19; isGeneratedCode = true; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // File diagnostic squiggledText = "}"; // last token in file. diagnosticArgument = file; line = 12; column = 1; isGeneratedCode = isGeneratedFile; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Compilation end summary diagnostic (verify callbacks into analyzer) // Analyzer always called for generated code, unless generated code analysis is explicitly disabled. if (generatedCodeAnalysisFlagsOpt == null || (generatedCodeAnalysisFlagsOpt & GeneratedCodeAnalysisFlags.Analyze) != 0) { sortedCallbackSymbolNames.Add(string.Format("GeneratedCode{0}", i)); sortedCallbackSymbolNames.Add(string.Format("Nested{0}", i)); sortedCallbackSymbolNames.Add(string.Format("NonGeneratedCode{0}", i)); sortedCallbackSymbolNames.Add(string.Format("NestedGeneratedCode{0}", i)); sortedCallbackTreePaths.Add(file); } else if (!isGeneratedFile) { // Analyzer always called for non-generated code. sortedCallbackSymbolNames.Add(string.Format("NonGeneratedCode{0}", i)); sortedCallbackTreePaths.Add(file); } } // Compilation end summary diagnostic (verify callbacks into analyzer) var arg1 = sortedCallbackSymbolNames.Join(","); var arg2 = sortedCallbackTreePaths.Join(","); AddExpectedNonLocalDiagnostic(builder, arguments: new[] { arg1, arg2 }); if (compilation.Options.GeneralDiagnosticOption == ReportDiagnostic.Error) { for (int i = 0; i < builder.Count; i++) { if (((string)builder[i].Code) != GeneratedCodeAnalyzer.Error.Id) { builder[i] = builder[i].WithWarningAsError(true); } } } return builder.ToArrayAndFree(); } private static void AddExpectedLocalDiagnostics( ArrayBuilder<DiagnosticDescription> builder, bool isGeneratedCode, string squiggledText, int line, int column, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt, params string[] arguments) { // Always report diagnostics in generated code, unless explicitly suppressed or we are not even analyzing generated code. var reportInGeneratedCode = generatedCodeAnalysisFlagsOpt == null || ((generatedCodeAnalysisFlagsOpt & GeneratedCodeAnalysisFlags.ReportDiagnostics) != 0 && (generatedCodeAnalysisFlagsOpt & GeneratedCodeAnalysisFlags.Analyze) != 0); if (!isGeneratedCode || reportInGeneratedCode) { var diagnostic = Diagnostic(GeneratedCodeAnalyzer.Warning.Id, squiggledText).WithArguments(arguments).WithLocation(line, column); builder.Add(diagnostic); diagnostic = Diagnostic(GeneratedCodeAnalyzer.Error.Id, squiggledText).WithArguments(arguments).WithLocation(line, column); builder.Add(diagnostic); } } private static void AddExpectedNonLocalDiagnostic(ArrayBuilder<DiagnosticDescription> builder, params string[] arguments) { AddExpectedDiagnostic(builder, GeneratedCodeAnalyzer.Summary.Id, squiggledText: null, line: 1, column: 1, arguments: arguments); } private static void AddExpectedDiagnostic(ArrayBuilder<DiagnosticDescription> builder, string diagnosticId, string squiggledText, int line, int column, params string[] arguments) { var diagnostic = Diagnostic(diagnosticId, squiggledText).WithArguments(arguments).WithLocation(line, column); builder.Add(diagnostic); } [Fact] public void TestEnsureNoMergedNamespaceSymbolAnalyzer() { var source = @"namespace N1.N2 { }"; var metadataReference = CreateCompilation(source).ToMetadataReference(); var compilation = CreateCompilation(source, new[] { metadataReference }); compilation.VerifyDiagnostics(); // Analyzer reports a diagnostic if it receives a merged namespace symbol across assemblies in compilation. var analyzers = new DiagnosticAnalyzer[] { new EnsureNoMergedNamespaceSymbolAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers); } [Fact, WorkItem(6324, "https://github.com/dotnet/roslyn/issues/6324")] public void TestSharedStateAnalyzer() { string source1 = @" public partial class C { } "; string source2 = @" public partial class C2 { } "; string source3 = @" public partial class C33 { } "; var tree1 = CSharpSyntaxTree.ParseText(source1, path: "Source1_File1.cs"); var tree2 = CSharpSyntaxTree.ParseText(source1, path: "Source1_File2.cs"); var tree3 = CSharpSyntaxTree.ParseText(source2, path: "Source2_File3.cs"); var tree4 = CSharpSyntaxTree.ParseText(source3, path: "Source3_File4.generated.cs"); var tree5 = CSharpSyntaxTree.ParseText(source3, path: "Source3_File5.designer.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2, tree3, tree4, tree5 }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new SharedStateAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("UserCodeDiagnostic").WithArguments("Source1_File1.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source1_File1.cs").WithLocation(1, 1), Diagnostic("GeneratedCodeDiagnostic", "C33").WithArguments("C33").WithLocation(2, 22), Diagnostic("UserCodeDiagnostic", "C2").WithArguments("C2").WithLocation(2, 22), Diagnostic("UserCodeDiagnostic", "C").WithArguments("C").WithLocation(2, 22), Diagnostic("UserCodeDiagnostic").WithArguments("Source1_File2.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source1_File2.cs").WithLocation(1, 1), Diagnostic("UserCodeDiagnostic").WithArguments("Source2_File3.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source2_File3.cs").WithLocation(1, 1), Diagnostic("GeneratedCodeDiagnostic").WithArguments("Source3_File4.generated.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source3_File4.generated.cs").WithLocation(1, 1), Diagnostic("GeneratedCodeDiagnostic").WithArguments("Source3_File5.designer.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source3_File5.designer.cs").WithLocation(1, 1), Diagnostic("NumberOfUniqueTextFileDescriptor").WithArguments("3").WithLocation(1, 1)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InConstructor() { string source = @" public class C { public C(int a, int b) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(4, 18), Diagnostic("Parameter_ID", "b").WithLocation(4, 25)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InRegularMethod() { string source = @" public class C { void M1(string a, string b) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(4, 20), Diagnostic("Parameter_ID", "b").WithLocation(4, 30)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InIndexers() { string source = @" public class C { public int this[int index] { get { return 0; } set { } } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "index").WithLocation(4, 25)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14061"), WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_Lambdas() { string source = @" public class C { void M2() { System.Func<int, int, int> x = (int a, int b) => b; } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Local_ID", "x").WithLocation(6, 36), Diagnostic("Parameter_ID", "a").WithLocation(6, 45), Diagnostic("Parameter_ID", "b").WithLocation(6, 52)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14061"), WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InAnonymousMethods() { string source = @" public class C { void M3() { M4(delegate (int x, int y) { }); } void M4(System.Action<int, int> a) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(9, 37), Diagnostic("Parameter_ID", "x").WithLocation(6, 26), Diagnostic("Parameter_ID", "y").WithLocation(6, 33)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InDelegateTypes() { string source = @" public class C { delegate void D(int x, string y); } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "x").WithLocation(4, 25), Diagnostic("Parameter_ID", "y").WithLocation(4, 35)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InOperators() { string source = @" public class C { public static implicit operator int (C c) { return 0; } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "c").WithLocation(4, 44)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InExplicitInterfaceImplementations() { string source = @" interface I { void M(int a, int b); } public class C : I { void I.M(int c, int d) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "c").WithLocation(9, 18), Diagnostic("Parameter_ID", "d").WithLocation(9, 25), Diagnostic("Parameter_ID", "a").WithLocation(4, 16), Diagnostic("Parameter_ID", "b").WithLocation(4, 23)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InExtensionMethods() { string source = @" public static class C { static void M(this int x, int y) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "x").WithLocation(4, 28), Diagnostic("Parameter_ID", "y").WithLocation(4, 35)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14061"), WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InLocalFunctions() { string source = @" public class C { void M1() { M2(1, 2); void M2(int a, int b) { } } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(4, 18), // ctor Diagnostic("Parameter_ID", "b").WithLocation(4, 25), Diagnostic("Local_ID", "c").WithLocation(6, 13), Diagnostic("Local_ID", "d").WithLocation(6, 20), Diagnostic("Parameter_ID", "a").WithLocation(10, 20), // M1 Diagnostic("Parameter_ID", "b").WithLocation(10, 30), Diagnostic("Local_ID", "c").WithLocation(12, 11), Diagnostic("Local_ID", "x").WithLocation(18, 36), // M2 Diagnostic("Parameter_ID", "a").WithLocation(26, 37), // M4 Diagnostic("Parameter_ID", "index").WithLocation(28, 25)); // indexer } [Fact, WorkItem(15903, "https://github.com/dotnet/roslyn/issues/15903")] public void TestSymbolAnalyzer_HiddenRegions() { string source = @" #line hidden public class HiddenClass { } #line default public class RegularClass { } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags.None) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerError", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerWarning", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerError", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("RegularClass", "Source.cs").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags.Analyze) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerError", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerWarning", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerError", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("HiddenClass,RegularClass", "Source.cs").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerError", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerWarning", "HiddenClass").WithArguments("HiddenClass").WithLocation(4, 14), Diagnostic("GeneratedCodeAnalyzerError", "HiddenClass").WithArguments("HiddenClass").WithLocation(4, 14), Diagnostic("GeneratedCodeAnalyzerWarning", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerError", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("HiddenClass,RegularClass", "Source.cs").WithLocation(1, 1)); } [Fact, WorkItem(15903, "https://github.com/dotnet/roslyn/issues/15903")] public void TestSyntaxAndOperationAnalyzer_HiddenRegions() { string source = @" public class Class { void DummyMethod(int i) { } #line hidden void HiddenMethod() { var hiddenVar = 0; DummyMethod(hiddenVar); } #line default void NonHiddenMethod() { var userVar = 0; DummyMethod(userVar); } void MixMethod() { #line hidden var mixMethodHiddenVar = 0; #line default var mixMethodUserVar = 0; DummyMethod(mixMethodHiddenVar + mixMethodUserVar); } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var syntaxKinds = ImmutableArray.Create(SyntaxKind.VariableDeclaration); var operationKinds = ImmutableArray.Create(OperationKind.VariableDeclarator); var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags.None, syntaxKinds, operationKinds) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "var userVar = 0").WithArguments("Node: var userVar = 0").WithLocation(17, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodUserVar = 0").WithArguments("Node: var mixMethodUserVar = 0").WithLocation(26, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "userVar = 0").WithArguments("Operation: NonHiddenMethod").WithLocation(17, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodUserVar = 0").WithArguments("Operation: MixMethod").WithLocation(26, 13), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("Node: var mixMethodUserVar = 0,Node: var userVar = 0,Operation: MixMethod,Operation: NonHiddenMethod").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags.Analyze, syntaxKinds, operationKinds) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "var userVar = 0").WithArguments("Node: var userVar = 0").WithLocation(17, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "userVar = 0").WithArguments("Operation: NonHiddenMethod").WithLocation(17, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodUserVar = 0").WithArguments("Node: var mixMethodUserVar = 0").WithLocation(26, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodUserVar = 0").WithArguments("Operation: MixMethod").WithLocation(26, 13), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("Node: var hiddenVar = 0,Node: var mixMethodHiddenVar = 0,Node: var mixMethodUserVar = 0,Node: var userVar = 0,Operation: HiddenMethod,Operation: MixMethod,Operation: NonHiddenMethod").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics, syntaxKinds, operationKinds) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "var hiddenVar = 0").WithArguments("Node: var hiddenVar = 0").WithLocation(10, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "hiddenVar = 0").WithArguments("Operation: HiddenMethod").WithLocation(10, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "var userVar = 0").WithArguments("Node: var userVar = 0").WithLocation(17, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "userVar = 0").WithArguments("Operation: NonHiddenMethod").WithLocation(17, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodHiddenVar = 0").WithArguments("Node: var mixMethodHiddenVar = 0").WithLocation(24, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodUserVar = 0").WithArguments("Node: var mixMethodUserVar = 0").WithLocation(26, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodHiddenVar = 0").WithArguments("Operation: MixMethod").WithLocation(24, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodUserVar = 0").WithArguments("Operation: MixMethod").WithLocation(26, 13), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("Node: var hiddenVar = 0,Node: var mixMethodHiddenVar = 0,Node: var mixMethodUserVar = 0,Node: var userVar = 0,Operation: HiddenMethod,Operation: MixMethod,Operation: NonHiddenMethod").WithLocation(1, 1)); } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class GeneratedCodeSyntaxAndOperationAnalyzer : DiagnosticAnalyzer { private readonly GeneratedCodeAnalysisFlags? _generatedCodeAnalysisFlagsOpt; private readonly ImmutableArray<SyntaxKind> _syntaxKinds; private readonly ImmutableArray<OperationKind> _operationKinds; public static readonly DiagnosticDescriptor Warning = new DiagnosticDescriptor( "GeneratedCodeAnalyzerWarning", "Title", "GeneratedCodeAnalyzerMessage for '{0}'", "Category", DiagnosticSeverity.Warning, true); public static readonly DiagnosticDescriptor Summary = new DiagnosticDescriptor( "GeneratedCodeAnalyzerSummary", "Title2", "GeneratedCodeAnalyzer received callbacks for: '{0}' entities", "Category", DiagnosticSeverity.Warning, true); public GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt, ImmutableArray<SyntaxKind> syntaxKinds, ImmutableArray<OperationKind> operationKinds) { _generatedCodeAnalysisFlagsOpt = generatedCodeAnalysisFlagsOpt; _syntaxKinds = syntaxKinds; _operationKinds = operationKinds; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Warning, Summary); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(this.OnCompilationStart); if (_generatedCodeAnalysisFlagsOpt.HasValue) { // Configure analysis on generated code. context.ConfigureGeneratedCodeAnalysis(_generatedCodeAnalysisFlagsOpt.Value); } } private void OnCompilationStart(CompilationStartAnalysisContext context) { var sortedCallbackEntityNames = new SortedSet<string>(); context.RegisterSyntaxNodeAction(syntaxContext => { sortedCallbackEntityNames.Add($"Node: {syntaxContext.Node.ToString()}"); ReportNodeDiagnostics(syntaxContext.Node, syntaxContext.ReportDiagnostic); }, _syntaxKinds); context.RegisterOperationAction(operationContext => { sortedCallbackEntityNames.Add($"Operation: {operationContext.ContainingSymbol.Name}"); ReportOperationDiagnostics(operationContext.Operation, operationContext.ContainingSymbol.Name, operationContext.ReportDiagnostic); }, _operationKinds); context.RegisterCompilationEndAction(endContext => { // Summary diagnostic about received callbacks. var diagnostic = CodeAnalysis.Diagnostic.Create(Summary, Location.None, sortedCallbackEntityNames.Join(",")); endContext.ReportDiagnostic(diagnostic); }); } private void ReportNodeDiagnostics(SyntaxNode node, Action<Diagnostic> addDiagnostic) { ReportDiagnosticsCore(addDiagnostic, node.Location, $"Node: {node.ToString()}"); } private void ReportOperationDiagnostics(IOperation operation, string name, Action<Diagnostic> addDiagnostic) { ReportDiagnosticsCore(addDiagnostic, operation.Syntax.Location, $"Operation: {name}"); } private void ReportDiagnosticsCore(Action<Diagnostic> addDiagnostic, Location location, params object[] messageArguments) { // warning diagnostic var diagnostic = CodeAnalysis.Diagnostic.Create(Warning, location, messageArguments); addDiagnostic(diagnostic); } } [Fact, WorkItem(23309, "https://github.com/dotnet/roslyn/issues/23309")] public void TestFieldReferenceAnalyzer_InAttributes() { string source = @" using System; [assembly: MyAttribute(C.FieldForAssembly)] [module: MyAttribute(C.FieldForModule)] internal class MyAttribute : Attribute { public MyAttribute(int f) { } } internal interface MyInterface { event EventHandler MyEvent; } [MyAttribute(FieldForClass)] internal class C : MyInterface { internal const int FieldForClass = 1, FieldForStruct = 2, FieldForInterface = 3, FieldForField = 4, FieldForMethod = 5, FieldForEnum = 6, FieldForEnumMember = 7, FieldForDelegate = 8, FieldForEventField = 9, FieldForEvent = 10, FieldForAddHandler = 11, FieldForRemoveHandler = 12, FieldForProperty = 13, FieldForPropertyGetter = 14, FieldForPropertySetter = 15, FieldForIndexer = 16, FieldForIndexerGetter = 17, FieldForIndexerSetter = 18, FieldForExpressionBodiedMethod = 19, FieldForExpressionBodiedProperty = 20, FieldForMethodParameter = 21, FieldForDelegateParameter = 22, FieldForIndexerParameter = 23, FieldForMethodTypeParameter = 24, FieldForTypeTypeParameter = 25, FieldForDelegateTypeParameter = 26, FieldForMethodReturnType = 27, FieldForAssembly = 28, FieldForModule = 29, FieldForPropertyInitSetter = 30; [MyAttribute(FieldForStruct)] private struct S<[MyAttribute(FieldForTypeTypeParameter)] T> { } [MyAttribute(FieldForInterface)] private interface I { } [MyAttribute(FieldForField)] private int field2 = 0, field3 = 0; [return: MyAttribute(FieldForMethodReturnType)] [MyAttribute(FieldForMethod)] private void M1<[MyAttribute(FieldForMethodTypeParameter)]T>([MyAttribute(FieldForMethodParameter)]int p1) { } [MyAttribute(FieldForEnum)] private enum E { [MyAttribute(FieldForEnumMember)] F = 0 } [MyAttribute(FieldForDelegate)] public delegate void Delegate<[MyAttribute(FieldForDelegateTypeParameter)]T>([MyAttribute(FieldForDelegateParameter)]int p1); [MyAttribute(FieldForEventField)] public event Delegate<int> MyEvent; [MyAttribute(FieldForEvent)] event EventHandler MyInterface.MyEvent { [MyAttribute(FieldForAddHandler)] add { } [MyAttribute(FieldForRemoveHandler)] remove { } } [MyAttribute(FieldForProperty)] private int P1 { [MyAttribute(FieldForPropertyGetter)] get; [MyAttribute(FieldForPropertySetter)] set; } [MyAttribute(FieldForIndexer)] private int this[[MyAttribute(FieldForIndexerParameter)]int index] { [MyAttribute(FieldForIndexerGetter)] get { return 0; } [MyAttribute(FieldForIndexerSetter)] set { } } [MyAttribute(FieldForExpressionBodiedMethod)] private int M2 => 0; [MyAttribute(FieldForExpressionBodiedProperty)] private int P2 => 0; private int P3 { [MyAttribute(FieldForPropertyInitSetter)] init { } } } "; var compilation = CreateCompilationWithMscorlib45(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (51,32): warning CS0067: The event 'C.MyEvent' is never used // public event Delegate<int> MyEvent; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("C.MyEvent").WithLocation(51, 32), // (34,17): warning CS0414: The field 'C.field2' is assigned but its value is never used // private int field2 = 0, field3 = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field2").WithArguments("C.field2").WithLocation(34, 17), // (34,29): warning CS0414: The field 'C.field3' is assigned but its value is never used // private int field2 = 0, field3 = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field3").WithArguments("C.field3").WithLocation(34, 29)); // Test RegisterOperationBlockAction testFieldReferenceAnalyzer_InAttributes_Core(compilation, doOperationBlockAnalysis: true); // Test RegisterOperationAction testFieldReferenceAnalyzer_InAttributes_Core(compilation, doOperationBlockAnalysis: false); static void testFieldReferenceAnalyzer_InAttributes_Core(Compilation compilation, bool doOperationBlockAnalysis) { var analyzers = new DiagnosticAnalyzer[] { new FieldReferenceOperationAnalyzer(doOperationBlockAnalysis) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ID", "FieldForPropertyInitSetter").WithArguments("FieldForPropertyInitSetter", "30").WithLocation(92, 22), Diagnostic("ID", "FieldForClass").WithArguments("FieldForClass", "1").WithLocation(17, 14), Diagnostic("ID", "FieldForStruct").WithArguments("FieldForStruct", "2").WithLocation(27, 18), Diagnostic("ID", "FieldForInterface").WithArguments("FieldForInterface", "3").WithLocation(30, 18), Diagnostic("ID", "FieldForField").WithArguments("FieldForField", "4").WithLocation(33, 18), Diagnostic("ID", "FieldForField").WithArguments("FieldForField", "4").WithLocation(33, 18), Diagnostic("ID", "FieldForMethod").WithArguments("FieldForMethod", "5").WithLocation(37, 18), Diagnostic("ID", "FieldForEnum").WithArguments("FieldForEnum", "6").WithLocation(40, 18), Diagnostic("ID", "FieldForEnumMember").WithArguments("FieldForEnumMember", "7").WithLocation(43, 22), Diagnostic("ID", "FieldForDelegate").WithArguments("FieldForDelegate", "8").WithLocation(47, 18), Diagnostic("ID", "FieldForEventField").WithArguments("FieldForEventField", "9").WithLocation(50, 18), Diagnostic("ID", "FieldForEvent").WithArguments("FieldForEvent", "10").WithLocation(53, 18), Diagnostic("ID", "FieldForAddHandler").WithArguments("FieldForAddHandler", "11").WithLocation(56, 22), Diagnostic("ID", "FieldForRemoveHandler").WithArguments("FieldForRemoveHandler", "12").WithLocation(60, 22), Diagnostic("ID", "FieldForProperty").WithArguments("FieldForProperty", "13").WithLocation(66, 18), Diagnostic("ID", "FieldForPropertyGetter").WithArguments("FieldForPropertyGetter", "14").WithLocation(69, 22), Diagnostic("ID", "FieldForPropertySetter").WithArguments("FieldForPropertySetter", "15").WithLocation(71, 22), Diagnostic("ID", "FieldForIndexer").WithArguments("FieldForIndexer", "16").WithLocation(75, 18), Diagnostic("ID", "FieldForIndexerGetter").WithArguments("FieldForIndexerGetter", "17").WithLocation(78, 22), Diagnostic("ID", "FieldForIndexerSetter").WithArguments("FieldForIndexerSetter", "18").WithLocation(80, 22), Diagnostic("ID", "FieldForExpressionBodiedMethod").WithArguments("FieldForExpressionBodiedMethod", "19").WithLocation(84, 18), Diagnostic("ID", "FieldForExpressionBodiedProperty").WithArguments("FieldForExpressionBodiedProperty", "20").WithLocation(87, 18), Diagnostic("ID", "FieldForMethodParameter").WithArguments("FieldForMethodParameter", "21").WithLocation(38, 79), Diagnostic("ID", "FieldForDelegateParameter").WithArguments("FieldForDelegateParameter", "22").WithLocation(48, 95), Diagnostic("ID", "FieldForIndexerParameter").WithArguments("FieldForIndexerParameter", "23").WithLocation(76, 35), Diagnostic("ID", "FieldForMethodTypeParameter").WithArguments("FieldForMethodTypeParameter", "24").WithLocation(38, 34), Diagnostic("ID", "FieldForTypeTypeParameter").WithArguments("FieldForTypeTypeParameter", "25").WithLocation(28, 35), Diagnostic("ID", "FieldForDelegateTypeParameter").WithArguments("FieldForDelegateTypeParameter", "26").WithLocation(48, 48), Diagnostic("ID", "FieldForMethodReturnType").WithArguments("FieldForMethodReturnType", "27").WithLocation(36, 26), Diagnostic("ID", "C.FieldForAssembly").WithArguments("FieldForAssembly", "28").WithLocation(4, 24), Diagnostic("ID", "C.FieldForModule").WithArguments("FieldForModule", "29").WithLocation(5, 22)); } } [Fact, WorkItem(23309, "https://github.com/dotnet/roslyn/issues/23309")] public void TestFieldReferenceAnalyzer_InConstructorInitializer() { string source = @" internal class Base { protected Base(int i) { } } internal class Derived : Base { private const int Field = 0; public Derived() : base(Field) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); // Test RegisterOperationBlockAction TestFieldReferenceAnalyzer_InConstructorInitializer_Core(compilation, doOperationBlockAnalysis: true); // Test RegisterOperationAction TestFieldReferenceAnalyzer_InConstructorInitializer_Core(compilation, doOperationBlockAnalysis: false); } private static void TestFieldReferenceAnalyzer_InConstructorInitializer_Core(Compilation compilation, bool doOperationBlockAnalysis) { var analyzers = new DiagnosticAnalyzer[] { new FieldReferenceOperationAnalyzer(doOperationBlockAnalysis) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ID", "Field").WithArguments("Field", "0").WithLocation(11, 29)); } [Fact, WorkItem(26520, "https://github.com/dotnet/roslyn/issues/26520")] public void TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody() { string source = @" internal class C { public bool Flag; public C() => Flag = true; ~C() => Flag = false; }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); // Test RegisterOperationBlockAction TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody_Core(compilation, doOperationBlockAnalysis: true); // Test RegisterOperationAction TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody_Core(compilation, doOperationBlockAnalysis: false); } private static void TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody_Core(Compilation compilation, bool doOperationBlockAnalysis) { var analyzers = new DiagnosticAnalyzer[] { new FieldReferenceOperationAnalyzer(doOperationBlockAnalysis) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ID", "Flag").WithArguments("Flag", "").WithLocation(5, 19), Diagnostic("ID", "Flag").WithArguments("Flag", "").WithLocation(6, 13)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestMethodBodyOperationAnalyzer() { string source = @" internal class A { public void M() { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID", squiggledText: "public void M() { }").WithArguments("M").WithLocation(4, 5)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestMethodBodyOperationAnalyzer_WithParameterInitializers() { string source = @" internal class A { public void M(int p = 0) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID", squiggledText: "public void M(int p = 0) { }").WithArguments("M").WithLocation(4, 5)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestMethodBodyOperationAnalyzer_WithExpressionAndMethodBody() { string source = @" internal class A { public int M() { return 0; } => 0; }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public int M() { return 0; } => 0; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "public int M() { return 0; } => 0;").WithLocation(4, 5)); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID", squiggledText: "public int M() { return 0; } => 0;").WithArguments("M").WithLocation(4, 5)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestConstructorBodyOperationAnalyzer() { string source = @" internal class Base { protected Base(int i) { } } internal class Derived : Base { private const int Field = 0; public Derived() : base(Field) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: new[] { Diagnostic("ID", squiggledText: "protected Base(int i) { }").WithArguments(".ctor").WithLocation(4, 5), Diagnostic("ID", squiggledText: "public Derived() : base(Field) { }").WithArguments(".ctor").WithLocation(11, 5) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TestGetControlFlowGraphInOperationAnalyzers() { string source = @"class C { void M(int p = 0) { int x = 1 + 2; } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.VerifyDiagnostics( // (1,35): warning CS0219: The variable 'x' is assigned but its value is never used // class C { void M(int p = 0) { int x = 1 + 2; } } Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(1, 35)); var expectedFlowGraphs = new[] { // Method body @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1 + 2') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 1 + 2') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, Constant: 3) (Syntax: '1 + 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0)", // Parameter initializer @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 0') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: '= 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0)" }; // Verify analyzer diagnostics and flow graphs for different kind of operation analyzers. var analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.Operation, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "0").WithArguments("Operation").WithLocation(1, 26), Diagnostic("ID", "1").WithArguments("Operation").WithLocation(1, 39), Diagnostic("ID", "2").WithArguments("Operation").WithLocation(1, 43) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.OperationInOperationBlockStart, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "0").WithArguments("OperationInOperationBlockStart").WithLocation(1, 26), Diagnostic("ID", "1").WithArguments("OperationInOperationBlockStart").WithLocation(1, 39), Diagnostic("ID", "2").WithArguments("OperationInOperationBlockStart").WithLocation(1, 43) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.OperationBlock, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "M").WithArguments("OperationBlock").WithLocation(1, 16) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.OperationBlockEnd, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "M").WithArguments("OperationBlockEnd").WithLocation(1, 16) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); void verifyFlowGraphs(ImmutableArray<(ControlFlowGraph Graph, ISymbol AssociatedSymbol)> flowGraphs) { for (int i = 0; i < expectedFlowGraphs.Length; i++) { string expectedFlowGraph = expectedFlowGraphs[i]; (ControlFlowGraph actualFlowGraph, ISymbol associatedSymbol) = flowGraphs[i]; ControlFlowGraphVerifier.VerifyGraph(compilation, expectedFlowGraph, actualFlowGraph, associatedSymbol); } } } private static void TestSymbolStartAnalyzerCore(SymbolStartAnalyzer analyzer, params DiagnosticDescription[] diagnostics) { TestSymbolStartAnalyzerCore(new DiagnosticAnalyzer[] { analyzer }, diagnostics); } private static void TestSymbolStartAnalyzerCore(DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics) { var source = @" #pragma warning disable CS0219 // unused local #pragma warning disable CS0067 // unused event class C1 { void M1() { int localInTypeInGlobalNamespace = 0; } } class C2 { class NestedType { void M2() { int localInNestedType = 0; } } } namespace N1 { } namespace N2 { namespace N3 { class C3 { void M3(int p) { int localInTypeInNamespace = 0; } void M4() { } } } } namespace N2.N3 { class C4 { public int f1 = 0; } } namespace N4 { class C5 { void M5() { } } class C6 { void M6() { } void M7() { } } } namespace N5 { partial class C7 { void M8() { } int P1 { get; set; } public event System.EventHandler e1; } partial class C7 { void M9() { } void M10() { } } } "; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); compilation.VerifyAnalyzerDiagnostics(analyzers, expected: diagnostics); } [Fact] public void TestSymbolStartAnalyzer_NamedType() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType), Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Namespace() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Namespace), Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Method() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Method), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Field() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Field), Diagnostic("SymbolStartRuleId").WithArguments("f1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Property() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Property), Diagnostic("SymbolStartRuleId").WithArguments("P1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Event() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Event), Diagnostic("SymbolStartRuleId").WithArguments("e1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Parameter() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Parameter)); } [Fact] public void TestSymbolStartAnalyzer_MultipleAnalyzers_NamespaceAndMethods() { var analyzer1 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Namespace, analyzerId: 1); var analyzer2 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Method, analyzerId: 2); TestSymbolStartAnalyzerCore(new DiagnosticAnalyzer[] { analyzer1, analyzer2 }, Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer2").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_MultipleAnalyzers_NamedTypeAndMethods() { var analyzer1 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType, analyzerId: 1); var analyzer2 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Method, analyzerId: 2); TestSymbolStartAnalyzerCore(new DiagnosticAnalyzer[] { analyzer1, analyzer2 }, Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer2").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_MultipleAnalyzers_AllSymbolKinds() { testCore("SymbolStartTopLevelRuleId", topLevel: true); testCore("SymbolStartRuleId", topLevel: false); void testCore(string ruleId, bool topLevel) { var symbolKinds = new[] { SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event, SymbolKind.Field, SymbolKind.Parameter }; var analyzers = new DiagnosticAnalyzer[symbolKinds.Length]; for (int i = 0; i < symbolKinds.Length; i++) { analyzers[i] = new SymbolStartAnalyzer(topLevel, symbolKinds[i], analyzerId: i + 1); } TestSymbolStartAnalyzerCore(analyzers, Diagnostic(ruleId).WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N1", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N2", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N3", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N4", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N5", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M1", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M2", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M3", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M4", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M5", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M6", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M7", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M8", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M9", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M10", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("get_P1", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("set_P1", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("P1", "Analyzer4").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("e1", "Analyzer5").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("f1", "Analyzer6").WithLocation(1, 1)); } } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_Namespace() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Namespace, OperationKind.VariableDeclarationGroup), Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("N3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_NamedType() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType, OperationKind.VariableDeclarationGroup), Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("NestedType", "M2", "int localInNestedType = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_Method() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.Method, OperationKind.VariableDeclarationGroup), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M7", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M8", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M9", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M10", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("get_P1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("set_P1", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M2", "M2", "int localInNestedType = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_AllSymbolKinds() { var symbolKinds = new[] { SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event, SymbolKind.Field, SymbolKind.Parameter }; var analyzers = new DiagnosticAnalyzer[symbolKinds.Length]; for (int i = 0; i < symbolKinds.Length; i++) { analyzers[i] = new SymbolStartAnalyzer(topLevelAction: false, symbolKinds[i], OperationKind.VariableDeclarationGroup, analyzerId: i + 1); } TestSymbolStartAnalyzerCore(analyzers, Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("NestedType", "M2", "int localInNestedType = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer2").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("N3", "M3", "int localInTypeInNamespace = 0;", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer3").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M2", "M2", "int localInNestedType = 0;", "Analyzer3").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M3", "M3", "int localInTypeInNamespace = 0;", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("P1", "Analyzer4").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("e1", "Analyzer5").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("f1", "Analyzer6").WithLocation(1, 1)); } [Fact] public void TestInitOnlyProperty() { string source1 = @" class C { int P1 { get; init; } int P2 { get; set; } }"; var compilation = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics(); var symbolKinds = new[] { SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event, SymbolKind.Field, SymbolKind.Parameter }; var analyzers = new DiagnosticAnalyzer[symbolKinds.Length]; for (int i = 0; i < symbolKinds.Length; i++) { analyzers[i] = new SymbolStartAnalyzer(topLevelAction: false, symbolKinds[i], OperationKind.VariableDeclarationGroup, analyzerId: i + 1); } var expected = new[] { Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("IsExternalInit", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("P2", "Analyzer4").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("P1", "Analyzer4").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P2", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P2", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("CompilerServices", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("Runtime", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("System", "Analyzer2").WithLocation(1, 1) }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(32702, "https://github.com/dotnet/roslyn/issues/32702")] public void TestInvocationInPartialMethod() { string source1 = @" static partial class B { static partial void PartialMethod(); }"; string source2 = @" static partial class B { static partial void PartialMethod() { M(); } private static void M() { } }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2 }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType, OperationKind.Invocation) }; var expected = new[] { Diagnostic("OperationRuleId").WithArguments("B", "PartialMethod", "M()", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("B", "Analyzer1").WithLocation(1, 1) }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(32702, "https://github.com/dotnet/roslyn/issues/32702")] public void TestFieldReferenceInPartialMethod() { string source1 = @" static partial class B { static partial void PartialMethod(); }"; string source2 = @" static partial class B { static partial void PartialMethod() { var x = _field; } private static int _field = 0; }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2 }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.NamedType, OperationKind.FieldReference) }; var expected = new[] { Diagnostic("OperationRuleId").WithArguments("B", "PartialMethod", "_field", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("B", "Analyzer1").WithLocation(1, 1) }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(922802, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/922802")] public async Task TestAnalysisScopeForGetAnalyzerSemanticDiagnosticsAsync() { string source1 = @" partial class B { private int _field1 = 1; }"; string source2 = @" partial class B { private int _field2 = 2; }"; string source3 = @" class C { private int _field3 = 3; }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2, source3 }); var tree1 = compilation.SyntaxTrees[0]; var semanticModel1 = compilation.GetSemanticModel(tree1); var analyzer1 = new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.Field, analyzerId: 1); var analyzer2 = new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.Field, analyzerId: 2); var compilationWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1, analyzer2)); // Invoke "GetAnalyzerSemanticDiagnosticsAsync" for a single analyzer on a single tree and // ensure that the API respects the requested analysis scope: // 1. It should never force analyze the non-requested analyzer. // 2. It should only analyze the requested tree. If the requested tree has partial type declaration(s), // then it should also analyze additional trees with other partial declarations for partial types in the original tree, // but not other tree. var tree1SemanticDiagnostics = await compilationWithAnalyzers.GetAnalyzerSemanticDiagnosticsAsync(semanticModel1, filterSpan: null, ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1), CancellationToken.None); Assert.Equal(2, analyzer1.SymbolsStarted.Count); var sortedSymbolNames = analyzer1.SymbolsStarted.Select(s => s.Name).ToImmutableSortedSet(); Assert.Equal("_field1", sortedSymbolNames[0]); Assert.Equal("_field2", sortedSymbolNames[1]); Assert.Empty(analyzer2.SymbolsStarted); Assert.Empty(tree1SemanticDiagnostics); } [Fact] public void TestAnalyzerCallbacksWithSuppressedFile_SymbolAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic and callback with suppression on second file. var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider(tree2, (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress))); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostic even suppression on second file. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestAnalyzerCallbacksWithSuppressedFile_SymbolStartEndAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify same callbacks even with suppression on second file when using GeneratedCodeAnalysisFlags.Analyze. var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider(tree2, (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress)) ); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd, GeneratedCodeAnalysisFlags.Analyze); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic and callback with suppression on second file when not using GeneratedCodeAnalysisFlags.Analyze. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd, GeneratedCodeAnalysisFlags.None); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostics even with suppression on second file when not using GeneratedCodeAnalysisFlags.Analyze. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestAnalyzerCallbacksWithSuppressedFile_CompilationStartEndAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A, B").WithLocation(1, 1) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify same diagnostics and callbacks even with suppression on second file when using GeneratedCodeAnalysisFlags.Analyze. var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider(tree2, (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress)) ); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd, GeneratedCodeAnalysisFlags.Analyze); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A, B").WithLocation(1, 1) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic and callback with suppression on second file when not using GeneratedCodeAnalysisFlags.Analyze. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd, GeneratedCodeAnalysisFlags.None); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A").WithLocation(1, 1) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostics even with suppression on second file. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A, B").WithLocation(1, 1) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestAnalyzerCallbacksWithGloballySuppressedFile_SymbolAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic for both files when specified globally var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress))); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }); Assert.Equal("", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostic even suppression on second file. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for a single file when suppressed globally and un-suppressed for a single file options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress), (tree1, new[] { (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Default) }))); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestConcurrentAnalyzerActions() { var first = AnalyzerActions.Empty; var second = AnalyzerActions.Empty; first.EnableConcurrentExecution(); Assert.True(first.Concurrent); Assert.False(second.Concurrent); Assert.True(first.Append(second).Concurrent); Assert.True(first.Concurrent); Assert.False(second.Concurrent); Assert.True(second.Append(first).Concurrent); } [Fact, WorkItem(41402, "https://github.com/dotnet/roslyn/issues/41402")] public async Task TestRegisterOperationBlockAndOperationActionOnSameContext() { string source = @" internal class A { public void M() { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); // Verify analyzer execution from command line // 'VerifyAnalyzerDiagnostics' helper executes the analyzers on the entire compilation without any state-based analysis. var analyzers = new DiagnosticAnalyzer[] { new RegisterOperationBlockAndOperationActionAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID0001", "M").WithLocation(4, 17)); // Now verify analyzer execution for a single file. // 'GetAnalyzerSemanticDiagnosticsAsync' executes the analyzers on the given file with state-based analysis. var model = compilation.GetSemanticModel(tree); var compWithAnalyzers = new CompilationWithAnalyzers( compilation, analyzers.ToImmutableArray(), new AnalyzerOptions(ImmutableArray<AdditionalText>.Empty), CancellationToken.None); var diagnostics = await compWithAnalyzers.GetAnalyzerSemanticDiagnosticsAsync(model, filterSpan: null, CancellationToken.None); diagnostics.Verify(Diagnostic("ID0001", "M").WithLocation(4, 17)); } [Fact, WorkItem(26217, "https://github.com/dotnet/roslyn/issues/26217")] public void TestConstructorInitializerWithExpressionBody() { string source = @" class C { C() : base() => _ = 0; }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new RegisterOperationBlockAndOperationActionAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID0001", "C").WithLocation(4, 5)); } [Fact, WorkItem(43106, "https://github.com/dotnet/roslyn/issues/43106")] public void TestConstructorInitializerWithoutBody() { string source = @" class B { // Haven't typed { } on the next line yet public B() : this(1) public B(int a) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics( // (5,12): error CS0501: 'B.B()' must declare a body because it is not marked abstract, extern, or partial // public B() : this(1) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "B").WithArguments("B.B()").WithLocation(5, 12), // (5,25): error CS1002: ; expected // public B() : this(1) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 25)); var analyzers = new DiagnosticAnalyzer[] { new RegisterOperationBlockAndOperationActionAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: new[] { Diagnostic("ID0001", "B").WithLocation(5, 12), Diagnostic("ID0001", "B").WithLocation(7, 12) }); } [Theory, CombinatorialData] public async Task TestGetAnalysisResultAsync(bool syntax, bool singleAnalyzer) { string source1 = @" partial class B { private int _field1 = 1; }"; string source2 = @" partial class B { private int _field2 = 2; }"; string source3 = @" class C { private int _field3 = 3; }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2, source3 }); var tree1 = compilation.SyntaxTrees[0]; var field1 = tree1.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Single().Declaration.Variables.Single().Identifier; var semanticModel1 = compilation.GetSemanticModel(tree1); var analyzer1 = new FieldAnalyzer("ID0001", syntax); var analyzer2 = new FieldAnalyzer("ID0002", syntax); var allAnalyzers = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1, analyzer2); var compilationWithAnalyzers = compilation.WithAnalyzers(allAnalyzers); // Invoke "GetAnalysisResultAsync" for a single analyzer on a single tree and // ensure that the API respects the requested analysis scope: // 1. It only reports diagnostics for the requested analyzer. // 2. It only reports diagnostics for the requested tree. var analyzersToQuery = singleAnalyzer ? ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1) : allAnalyzers; AnalysisResult analysisResult; if (singleAnalyzer) { analysisResult = syntax ? await compilationWithAnalyzers.GetAnalysisResultAsync(tree1, analyzersToQuery, CancellationToken.None) : await compilationWithAnalyzers.GetAnalysisResultAsync(semanticModel1, filterSpan: null, analyzersToQuery, CancellationToken.None); } else { analysisResult = syntax ? await compilationWithAnalyzers.GetAnalysisResultAsync(tree1, CancellationToken.None) : await compilationWithAnalyzers.GetAnalysisResultAsync(semanticModel1, filterSpan: null, CancellationToken.None); } var diagnosticsMap = syntax ? analysisResult.SyntaxDiagnostics : analysisResult.SemanticDiagnostics; var diagnostics = diagnosticsMap.TryGetValue(tree1, out var value) ? value : ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>.Empty; foreach (var analyzer in allAnalyzers) { if (analyzersToQuery.Contains(analyzer)) { Assert.True(diagnostics.ContainsKey(analyzer)); var diagnostic = Assert.Single(diagnostics[analyzer]); Assert.Equal(((FieldAnalyzer)analyzer).Descriptor.Id, diagnostic.Id); Assert.Equal(field1.GetLocation(), diagnostic.Location); } else { Assert.False(diagnostics.ContainsKey(analyzer)); } } } [Theory, CombinatorialData] public async Task TestAdditionalFileAnalyzer(bool registerFromInitialize) { var tree = CSharpSyntaxTree.ParseText(string.Empty); var compilation = CreateCompilation(new[] { tree }); compilation.VerifyDiagnostics(); AdditionalText additionalFile = new TestAdditionalText("Additional File Text"); var options = new AnalyzerOptions(ImmutableArray.Create(additionalFile)); var diagnosticSpan = new TextSpan(2, 2); var analyzer = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan); var analyzers = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer); var diagnostics = await compilation.WithAnalyzers(analyzers, options).GetAnalyzerDiagnosticsAsync(CancellationToken.None); verifyDiagnostics(diagnostics); var analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile, CancellationToken.None); verifyDiagnostics(analysisResult.GetAllDiagnostics()); verifyDiagnostics(analysisResult.AdditionalFileDiagnostics[additionalFile][analyzer]); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(CancellationToken.None); verifyDiagnostics(analysisResult.GetAllDiagnostics()); verifyDiagnostics(analysisResult.AdditionalFileDiagnostics[additionalFile][analyzer]); void verifyDiagnostics(ImmutableArray<Diagnostic> diagnostics) { var diagnostic = Assert.Single(diagnostics); Assert.Equal(analyzer.Descriptor.Id, diagnostic.Id); Assert.Equal(LocationKind.ExternalFile, diagnostic.Location.Kind); var location = (ExternalFileLocation)diagnostic.Location; Assert.Equal(additionalFile.Path, location.FilePath); Assert.Equal(diagnosticSpan, location.SourceSpan); } } [Theory, CombinatorialData] public async Task TestMultipleAdditionalFileAnalyzers(bool registerFromInitialize, bool additionalFilesHaveSamePaths, bool firstAdditionalFileHasNullPath) { var tree = CSharpSyntaxTree.ParseText(string.Empty); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var path1 = firstAdditionalFileHasNullPath ? null : @"c:\file.txt"; var path2 = additionalFilesHaveSamePaths ? path1 : @"file2.txt"; AdditionalText additionalFile1 = new TestAdditionalText("Additional File1 Text", path: path1); AdditionalText additionalFile2 = new TestAdditionalText("Additional File2 Text", path: path2); var additionalFiles = ImmutableArray.Create(additionalFile1, additionalFile2); var options = new AnalyzerOptions(additionalFiles); var diagnosticSpan = new TextSpan(2, 2); var analyzer1 = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan, id: "ID0001"); var analyzer2 = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan, id: "ID0002"); var analyzers = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1, analyzer2); var diagnostics = await compilation.WithAnalyzers(analyzers, options).GetAnalyzerDiagnosticsAsync(CancellationToken.None); verifyDiagnostics(diagnostics, analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths); var analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile1, CancellationToken.None); verifyAnalysisResult(analysisResult, analyzers, ImmutableArray.Create(additionalFile1), diagnosticSpan, additionalFilesHaveSamePaths); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile2, CancellationToken.None); verifyAnalysisResult(analysisResult, analyzers, ImmutableArray.Create(additionalFile2), diagnosticSpan, additionalFilesHaveSamePaths); var singleAnalyzerArray = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile1, singleAnalyzerArray, CancellationToken.None); verifyAnalysisResult(analysisResult, singleAnalyzerArray, ImmutableArray.Create(additionalFile1), diagnosticSpan, additionalFilesHaveSamePaths); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile2, singleAnalyzerArray, CancellationToken.None); verifyAnalysisResult(analysisResult, singleAnalyzerArray, ImmutableArray.Create(additionalFile2), diagnosticSpan, additionalFilesHaveSamePaths); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(CancellationToken.None); verifyDiagnostics(analysisResult.GetAllDiagnostics(), analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths); if (!additionalFilesHaveSamePaths) { verifyAnalysisResult(analysisResult, analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths, verifyGetAllDiagnostics: false); } return; static void verifyDiagnostics( ImmutableArray<Diagnostic> diagnostics, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<AdditionalText> additionalFiles, TextSpan diagnosticSpan, bool additionalFilesHaveSamePaths) { foreach (AdditionalFileAnalyzer analyzer in analyzers) { var fileIndex = 0; foreach (var additionalFile in additionalFiles) { var applicableDiagnostics = diagnostics.WhereAsArray( d => d.Id == analyzer.Descriptor.Id && PathUtilities.Comparer.Equals(d.Location.GetLineSpan().Path, additionalFile.Path)); if (additionalFile.Path == null) { Assert.Empty(applicableDiagnostics); continue; } var expectedCount = additionalFilesHaveSamePaths ? additionalFiles.Length : 1; Assert.Equal(expectedCount, applicableDiagnostics.Length); foreach (var diagnostic in applicableDiagnostics) { Assert.Equal(LocationKind.ExternalFile, diagnostic.Location.Kind); var location = (ExternalFileLocation)diagnostic.Location; Assert.Equal(diagnosticSpan, location.SourceSpan); } fileIndex++; if (!additionalFilesHaveSamePaths || fileIndex == additionalFiles.Length) { diagnostics = diagnostics.RemoveRange(applicableDiagnostics); } } } Assert.Empty(diagnostics); } static void verifyAnalysisResult( AnalysisResult analysisResult, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<AdditionalText> additionalFiles, TextSpan diagnosticSpan, bool additionalFilesHaveSamePaths, bool verifyGetAllDiagnostics = true) { if (verifyGetAllDiagnostics) { verifyDiagnostics(analysisResult.GetAllDiagnostics(), analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths); } foreach (var analyzer in analyzers) { var singleAnalyzerArray = ImmutableArray.Create(analyzer); foreach (var additionalFile in additionalFiles) { var reportedDiagnostics = getReportedDiagnostics(analysisResult, analyzer, additionalFile); verifyDiagnostics(reportedDiagnostics, singleAnalyzerArray, ImmutableArray.Create(additionalFile), diagnosticSpan, additionalFilesHaveSamePaths); } } return; static ImmutableArray<Diagnostic> getReportedDiagnostics(AnalysisResult analysisResult, DiagnosticAnalyzer analyzer, AdditionalText additionalFile) { if (analysisResult.AdditionalFileDiagnostics.TryGetValue(additionalFile, out var diagnosticsMap) && diagnosticsMap.TryGetValue(analyzer, out var diagnostics)) { return diagnostics; } return ImmutableArray<Diagnostic>.Empty; } } } [Fact] public void TestSemanticModelProvider() { var tree = CSharpSyntaxTree.ParseText(@"class C { }"); Compilation compilation = CreateCompilation(new[] { tree }); var semanticModelProvider = new MySemanticModelProvider(); compilation = compilation.WithSemanticModelProvider(semanticModelProvider); // Verify semantic model provider is used by Compilation.GetSemanticModel API var model = compilation.GetSemanticModel(tree); semanticModelProvider.VerifyCachedModel(tree, model); // Verify semantic model provider is used by CSharpCompilation.GetSemanticModel API model = ((CSharpCompilation)compilation).GetSemanticModel(tree, ignoreAccessibility: false); semanticModelProvider.VerifyCachedModel(tree, model); } private sealed class MySemanticModelProvider : SemanticModelProvider { private readonly ConcurrentDictionary<SyntaxTree, SemanticModel> _cache = new ConcurrentDictionary<SyntaxTree, SemanticModel>(); public override SemanticModel GetSemanticModel(SyntaxTree tree, Compilation compilation, bool ignoreAccessibility = false) { return _cache.GetOrAdd(tree, compilation.CreateSemanticModel(tree, ignoreAccessibility)); } public void VerifyCachedModel(SyntaxTree tree, SemanticModel model) { Assert.Same(model, _cache[tree]); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Runtime.ExceptionServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Diagnostics.CSharp; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using static Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class DiagnosticAnalyzerTests : CompilingTestBase { private class ComplainAboutX : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor s_CA9999_UseOfVariableThatStartsWithX = new DiagnosticDescriptor(id: "CA9999_UseOfVariableThatStartsWithX", title: "CA9999_UseOfVariableThatStartsWithX", messageFormat: "Use of variable whose name starts with 'x': '{0}'", category: "Test", defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_CA9999_UseOfVariableThatStartsWithX); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.IdentifierName); } private static void AnalyzeNode(SyntaxNodeAnalysisContext context) { var id = (IdentifierNameSyntax)context.Node; if (id.Identifier.ValueText.StartsWith("x", StringComparison.Ordinal)) { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(s_CA9999_UseOfVariableThatStartsWithX, id.Location, id.Identifier.ValueText)); } } } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void SimplestDiagnosticAnalyzerTest() { string source = @"public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics( // (1,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound") ) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (5,18): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1"), // (5,21): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2"), // (6,16): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x3' // return x3 + 1; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x3").WithArguments("x3") ); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void SimplestDiagnosticAnalyzerTestInInitializer() { string source = @"delegate int D(out int x); public class C : NotFound { static int x1 = 2; static int x2 = 3; int x3 = x1 + x2; D d1 = (out int x4) => (x4 = 1) + @x4; }"; // TODO: Compilation create doesn't accept analyzers anymore. CreateCompilationWithMscorlib45(source).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound") ) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (6,14): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1 + x2; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1"), // (6,19): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1 + x2; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2"), // (7,29): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x4' // D d1 = (out int x4) => (x4 = 1) + @x4; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x4").WithArguments("x4"), // (7,39): warning CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x4' // D d1 = (out int x4) => (x4 = 1) + @x4; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "@x4").WithArguments("x4") ); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void DiagnosticAnalyzerSuppressDiagnostic() { string source = @" public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; // TODO: Compilation create doesn't accept analyzers anymore. var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions( new[] { KeyValuePairUtil.Create("CA9999_UseOfVariableThatStartsWithX", ReportDiagnostic.Suppress) }); CreateCompilationWithMscorlib45(source, options: options/*, analyzers: new IDiagnosticAnalyzerFactory[] { new ComplainAboutX() }*/).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound")); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void DiagnosticAnalyzerWarnAsError() { string source = @" public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; // TODO: Compilation create doesn't accept analyzers anymore. var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions( new[] { KeyValuePairUtil.Create("CA9999_UseOfVariableThatStartsWithX", ReportDiagnostic.Error) }); CreateCompilationWithMscorlib45(source, options: options).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound")) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (6,18): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1").WithWarningAsError(true), // (6,21): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2").WithWarningAsError(true), // (7,16): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x3' // return x3 + 1; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x3").WithArguments("x3").WithWarningAsError(true) ); } [WorkItem(892467, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/892467")] [Fact] public void DiagnosticAnalyzerWarnAsErrorGlobal() { string source = @" public class C : NotFound { int x1(int x2) { int x3 = x1(x2); return x3 + 1; } }"; var options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); CreateCompilationWithMscorlib45(source, options: options).VerifyDiagnostics( // (2,18): error CS0246: The type or namespace name 'NotFound' could not be found (are you missing a using directive or an assembly reference?) // public class C : NotFound Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "NotFound").WithArguments("NotFound") ) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ComplainAboutX() }, null, null, // (6,18): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x1' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x1").WithArguments("x1").WithWarningAsError(true), // (6,21): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x2' // int x3 = x1(x2); Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x2").WithArguments("x2").WithWarningAsError(true), // (7,16): error CA9999_UseOfVariableThatStartsWithX: Use of variable whose name starts with 'x': 'x3' // return x3 + 1; Diagnostic("CA9999_UseOfVariableThatStartsWithX", "x3").WithArguments("x3").WithWarningAsError(true)); } [Fact, WorkItem(1038025, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1038025")] public void TestImplicitlyDeclaredSymbolsNotAnalyzed() { string source = @" using System; public class C { public event EventHandler e; }"; CreateCompilationWithMscorlib45(source) .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new ImplicitlyDeclaredSymbolAnalyzer() }); } private class SyntaxAndSymbolAnalyzer : DiagnosticAnalyzer { private static readonly DiagnosticDescriptor s_descriptor = new DiagnosticDescriptor("XX0001", "My Syntax/Symbol Diagnostic", "My Syntax/Symbol Diagnostic for '{0}'", "Compiler", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(s_descriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.Attribute, SyntaxKind.ClassDeclaration, SyntaxKind.UsingDirective); context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType); } private void AnalyzeNode(SyntaxNodeAnalysisContext context) { switch (context.Node.Kind()) { case SyntaxKind.Attribute: var diag1 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Node.GetLocation(), "Attribute"); context.ReportDiagnostic(diag1); break; case SyntaxKind.ClassDeclaration: var diag2 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Node.GetLocation(), "ClassDeclaration"); context.ReportDiagnostic(diag2); break; case SyntaxKind.UsingDirective: var diag3 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Node.GetLocation(), "UsingDirective"); context.ReportDiagnostic(diag3); break; } } private void AnalyzeSymbol(SymbolAnalysisContext context) { var diag1 = CodeAnalysis.Diagnostic.Create(s_descriptor, context.Symbol.Locations[0], "NamedType"); context.ReportDiagnostic(diag1); } } [WorkItem(914236, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/914236")] [Fact] public void DiagnosticAnalyzerSyntaxNodeAndSymbolAnalysis() { string source = @" using System; [Obsolete] public class C { }"; var options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); CreateCompilationWithMscorlib45(source, options: options) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new SyntaxAndSymbolAnalyzer() }, null, null, // Symbol diagnostics Diagnostic("XX0001", "C").WithArguments("NamedType").WithWarningAsError(true), // Syntax diagnostics Diagnostic("XX0001", "using System;").WithArguments("UsingDirective").WithWarningAsError(true), // using directive Diagnostic("XX0001", "Obsolete").WithArguments("Attribute").WithWarningAsError(true), // attribute syntax Diagnostic("XX0001", @"[Obsolete] public class C { }").WithArguments("ClassDeclaration").WithWarningAsError(true)); // class declaration } [Fact] public void TestGetEffectiveDiagnostics() { var noneDiagDescriptor = new DiagnosticDescriptor("XX0001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Hidden, isEnabledByDefault: true); var infoDiagDescriptor = new DiagnosticDescriptor("XX0002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Info, isEnabledByDefault: true); var warningDiagDescriptor = new DiagnosticDescriptor("XX0003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); var errorDiagDescriptor = new DiagnosticDescriptor("XX0004", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Error, isEnabledByDefault: true); var noneDiag = CodeAnalysis.Diagnostic.Create(noneDiagDescriptor, Location.None); var infoDiag = CodeAnalysis.Diagnostic.Create(infoDiagDescriptor, Location.None); var warningDiag = CodeAnalysis.Diagnostic.Create(warningDiagDescriptor, Location.None); var errorDiag = CodeAnalysis.Diagnostic.Create(errorDiagDescriptor, Location.None); var diags = new[] { noneDiag, infoDiag, warningDiag, errorDiag }; // Escalate all diagnostics to error. var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(noneDiagDescriptor.Id, ReportDiagnostic.Error); specificDiagOptions.Add(infoDiagDescriptor.Id, ReportDiagnostic.Error); specificDiagOptions.Add(warningDiagDescriptor.Id, ReportDiagnostic.Error); var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); var comp = CreateCompilationWithMscorlib45("", options: options); var effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(diags.Length, effectiveDiags.Length); foreach (var effectiveDiag in effectiveDiags) { Assert.True(effectiveDiag.Severity == DiagnosticSeverity.Error); } // Suppress all diagnostics. specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(noneDiagDescriptor.Id, ReportDiagnostic.Suppress); specificDiagOptions.Add(infoDiagDescriptor.Id, ReportDiagnostic.Suppress); specificDiagOptions.Add(warningDiagDescriptor.Id, ReportDiagnostic.Suppress); specificDiagOptions.Add(errorDiagDescriptor.Id, ReportDiagnostic.Suppress); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(0, effectiveDiags.Length); // Shuffle diagnostic severity. specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(noneDiagDescriptor.Id, ReportDiagnostic.Info); specificDiagOptions.Add(infoDiagDescriptor.Id, ReportDiagnostic.Hidden); specificDiagOptions.Add(warningDiagDescriptor.Id, ReportDiagnostic.Error); specificDiagOptions.Add(errorDiagDescriptor.Id, ReportDiagnostic.Warn); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(diags.Length, effectiveDiags.Length); var diagIds = new HashSet<string>(diags.Select(d => d.Id)); foreach (var effectiveDiag in effectiveDiags) { Assert.True(diagIds.Remove(effectiveDiag.Id)); switch (effectiveDiag.Severity) { case DiagnosticSeverity.Hidden: Assert.Equal(infoDiagDescriptor.Id, effectiveDiag.Id); break; case DiagnosticSeverity.Info: Assert.Equal(noneDiagDescriptor.Id, effectiveDiag.Id); break; case DiagnosticSeverity.Warning: Assert.Equal(errorDiagDescriptor.Id, effectiveDiag.Id); break; case DiagnosticSeverity.Error: Assert.Equal(warningDiagDescriptor.Id, effectiveDiag.Id); break; default: throw ExceptionUtilities.Unreachable; } } Assert.Empty(diagIds); } [Fact] public void TestGetEffectiveDiagnosticsGlobal() { var noneDiagDescriptor = new DiagnosticDescriptor("XX0001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Hidden, isEnabledByDefault: true); var infoDiagDescriptor = new DiagnosticDescriptor("XX0002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Info, isEnabledByDefault: true); var warningDiagDescriptor = new DiagnosticDescriptor("XX0003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); var errorDiagDescriptor = new DiagnosticDescriptor("XX0004", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Error, isEnabledByDefault: true); var noneDiag = Microsoft.CodeAnalysis.Diagnostic.Create(noneDiagDescriptor, Location.None); var infoDiag = Microsoft.CodeAnalysis.Diagnostic.Create(infoDiagDescriptor, Location.None); var warningDiag = Microsoft.CodeAnalysis.Diagnostic.Create(warningDiagDescriptor, Location.None); var errorDiag = Microsoft.CodeAnalysis.Diagnostic.Create(errorDiagDescriptor, Location.None); var diags = new[] { noneDiag, infoDiag, warningDiag, errorDiag }; var options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Default); var comp = CreateCompilationWithMscorlib45("", options: options); var effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Error); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.IsWarningAsError)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Warn); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Warning)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Info); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Info)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Hidden); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(4, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Hidden)); options = TestOptions.ReleaseDll.WithGeneralDiagnosticOption(ReportDiagnostic.Suppress); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(2, effectiveDiags.Length); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Error)); Assert.Equal(1, effectiveDiags.Count(d => d.Severity == DiagnosticSeverity.Hidden)); } [Fact] public void TestDisabledDiagnostics() { var disabledDiagDescriptor = new DiagnosticDescriptor("XX001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); var enabledDiagDescriptor = new DiagnosticDescriptor("XX002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); var disabledDiag = CodeAnalysis.Diagnostic.Create(disabledDiagDescriptor, Location.None); var enabledDiag = CodeAnalysis.Diagnostic.Create(enabledDiagDescriptor, Location.None); var diags = new[] { disabledDiag, enabledDiag }; // Verify that only the enabled diag shows up after filtering. var options = TestOptions.ReleaseDll; var comp = CreateCompilationWithMscorlib45("", options: options); var effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(1, effectiveDiags.Length); Assert.Contains(enabledDiag, effectiveDiags); // If the disabled diag was enabled through options, then it should show up. var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(disabledDiagDescriptor.Id, ReportDiagnostic.Warn); specificDiagOptions.Add(enabledDiagDescriptor.Id, ReportDiagnostic.Suppress); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); comp = CreateCompilationWithMscorlib45("", options: options); effectiveDiags = comp.GetEffectiveDiagnostics(diags).ToArray(); Assert.Equal(1, effectiveDiags.Length); Assert.Contains(disabledDiag, effectiveDiags); } internal class FullyDisabledAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor desc1 = new DiagnosticDescriptor("XX001", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public static DiagnosticDescriptor desc2 = new DiagnosticDescriptor("XX002", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public static DiagnosticDescriptor desc3 = new DiagnosticDescriptor("XX003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false, customTags: WellKnownDiagnosticTags.NotConfigurable); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(desc1, desc2, desc3); } } public override void Initialize(AnalysisContext context) { } } internal class PartiallyDisabledAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor desc1 = new DiagnosticDescriptor("XX003", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public static DiagnosticDescriptor desc2 = new DiagnosticDescriptor("XX004", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(desc1, desc2); } } public override void Initialize(AnalysisContext context) { } } internal class ImplicitlyDeclaredSymbolAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor desc1 = new DiagnosticDescriptor("DummyId", "DummyDescription", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: false); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(desc1); } } public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction( (c) => { Assert.False(c.Symbol.IsImplicitlyDeclared); }, SymbolKind.Namespace, SymbolKind.NamedType, SymbolKind.Event, SymbolKind.Field, SymbolKind.Method, SymbolKind.Property); } } [Fact] public void TestDisabledAnalyzers() { var fullyDisabledAnalyzer = new FullyDisabledAnalyzer(); var partiallyDisabledAnalyzer = new PartiallyDisabledAnalyzer(); var options = TestOptions.ReleaseDll; Assert.True(fullyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); Assert.False(partiallyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(FullyDisabledAnalyzer.desc1.Id, ReportDiagnostic.Warn); specificDiagOptions.Add(PartiallyDisabledAnalyzer.desc2.Id, ReportDiagnostic.Suppress); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); Assert.False(fullyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); Assert.True(partiallyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); // Verify not configurable disabled diagnostic cannot be enabled, and hence cannot affect IsDiagnosticAnalyzerSuppressed computation. specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(FullyDisabledAnalyzer.desc3.Id, ReportDiagnostic.Warn); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); Assert.True(fullyDisabledAnalyzer.IsDiagnosticAnalyzerSuppressed(options)); } [Fact, WorkItem(1008059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1008059")] public void TestCodeBlockAnalyzersForNoExecutableCode() { string noExecutableCodeSource = @" public abstract class C { public int P { get; set; } public int field; public abstract int Method(); }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: true) }; CreateCompilationWithMscorlib45(noExecutableCodeSource) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers); } [Fact, WorkItem(1008059, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1008059")] public void TestCodeBlockAnalyzersForBaseConstructorInitializer() { string baseCtorSource = @" public class B { public B(int x) {} } public class C : B { public C() : base(x: 10) {} }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: true) }; CreateCompilationWithMscorlib45(baseCtorSource) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ConstructorInitializerDiagnostic"), Diagnostic("CodeBlockDiagnostic"), Diagnostic("CodeBlockDiagnostic")); } [Fact, WorkItem(1067286, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1067286")] public void TestCodeBlockAnalyzersForExpressionBody() { string source = @" public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: true) }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("CodeBlockDiagnostic"), Diagnostic("CodeBlockDiagnostic"), Diagnostic("CodeBlockDiagnostic"), Diagnostic("PropertyExpressionBodyDiagnostic"), Diagnostic("IndexerExpressionBodyDiagnostic"), Diagnostic("MethodExpressionBodyDiagnostic")); } [Fact, WorkItem(592, "https://github.com/dotnet/roslyn/issues/592")] public void TestSyntaxNodeAnalyzersForExpressionBody() { string source = @" public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockOrSyntaxNodeAnalyzer(isCodeBlockAnalyzer: false) }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("PropertyExpressionBodyDiagnostic"), Diagnostic("IndexerExpressionBodyDiagnostic"), Diagnostic("MethodExpressionBodyDiagnostic")); } [Fact, WorkItem(592, "https://github.com/dotnet/roslyn/issues/592")] public void TestMethodSymbolAnalyzersForExpressionBody() { string source = @" public class B { public int Property => 0; public int Method() => 0; public int this[int i] => 0; }"; var analyzers = new DiagnosticAnalyzer[] { new MethodSymbolAnalyzer() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("MethodSymbolDiagnostic", "0").WithArguments("B.Property.get").WithLocation(4, 28), Diagnostic("MethodSymbolDiagnostic", "Method").WithArguments("B.Method()").WithLocation(5, 16), Diagnostic("MethodSymbolDiagnostic", "0").WithArguments("B.this[int].get").WithLocation(6, 31)); } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class FieldDeclarationAnalyzer : DiagnosticAnalyzer { public const string DiagnosticId = "MyFieldDiagnostic"; internal const string Title = "MyFieldDiagnostic"; internal const string MessageFormat = "MyFieldDiagnostic"; internal const string Category = "Naming"; internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Rule); } } public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeFieldDeclaration, SyntaxKind.FieldDeclaration); } private static void AnalyzeFieldDeclaration(SyntaxNodeAnalysisContext context) { var fieldDeclaration = (FieldDeclarationSyntax)context.Node; var diagnostic = CodeAnalysis.Diagnostic.Create(Rule, fieldDeclaration.GetLocation()); context.ReportDiagnostic(diagnostic); } } [Fact] public void TestNoDuplicateCallbacksForFieldDeclaration() { string source = @" public class B { public string field = ""field""; }"; var analyzers = new DiagnosticAnalyzer[] { new FieldDeclarationAnalyzer() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("MyFieldDiagnostic", @"public string field = ""field"";").WithLocation(4, 5)); } [Fact, WorkItem(565, "https://github.com/dotnet/roslyn/issues/565")] public void TestCallbacksForFieldDeclarationWithMultipleVariables() { string source = @" public class B { public string field1, field2; public int field3 = 0, field4 = 1; public int field5, field6 = 1; }"; var analyzers = new DiagnosticAnalyzer[] { new FieldDeclarationAnalyzer() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("MyFieldDiagnostic", @"public string field1, field2;").WithLocation(4, 5), Diagnostic("MyFieldDiagnostic", @"public int field3 = 0, field4 = 1;").WithLocation(5, 5), Diagnostic("MyFieldDiagnostic", @"public int field5, field6 = 1;").WithLocation(6, 5)); } [Fact, WorkItem(1096600, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1096600")] public void TestDescriptorForConfigurableCompilerDiagnostics() { // Verify that all configurable compiler diagnostics, i.e. all non-error diagnostics, // have a non-null and non-empty Title and Category. // These diagnostic descriptor fields show up in the ruleset editor and hence must have a valid value. var analyzer = new CSharpCompilerDiagnosticAnalyzer(); foreach (var descriptor in analyzer.SupportedDiagnostics) { Assert.True(descriptor.IsEnabledByDefault); if (descriptor.IsNotConfigurable()) { continue; } var title = descriptor.Title.ToString(); if (string.IsNullOrEmpty(title)) { var id = Int32.Parse(descriptor.Id.Substring(2)); var missingResource = Enum.GetName(typeof(ErrorCode), id) + "_Title"; var message = string.Format("Add resource string named '{0}' for Title of '{1}' to '{2}'", missingResource, descriptor.Id, nameof(CSharpResources)); // This assert will fire if you are adding a new compiler diagnostic (non-error severity), // but did not add a title resource string for the diagnostic. Assert.True(false, message); } var category = descriptor.Category; if (string.IsNullOrEmpty(title)) { var message = string.Format("'{0}' must have a non-null non-empty 'Category'", descriptor.Id); Assert.True(false, message); } } } public class CodeBlockOrSyntaxNodeAnalyzer : DiagnosticAnalyzer { private readonly bool _isCodeBlockAnalyzer; public static DiagnosticDescriptor Descriptor1 = DescriptorFactory.CreateSimpleDescriptor("CodeBlockDiagnostic"); public static DiagnosticDescriptor Descriptor2 = DescriptorFactory.CreateSimpleDescriptor("EqualsValueDiagnostic"); public static DiagnosticDescriptor Descriptor3 = DescriptorFactory.CreateSimpleDescriptor("ConstructorInitializerDiagnostic"); public static DiagnosticDescriptor Descriptor4 = DescriptorFactory.CreateSimpleDescriptor("PropertyExpressionBodyDiagnostic"); public static DiagnosticDescriptor Descriptor5 = DescriptorFactory.CreateSimpleDescriptor("IndexerExpressionBodyDiagnostic"); public static DiagnosticDescriptor Descriptor6 = DescriptorFactory.CreateSimpleDescriptor("MethodExpressionBodyDiagnostic"); public CodeBlockOrSyntaxNodeAnalyzer(bool isCodeBlockAnalyzer) { _isCodeBlockAnalyzer = isCodeBlockAnalyzer; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor1, Descriptor2, Descriptor3, Descriptor4, Descriptor5, Descriptor6); } } public override void Initialize(AnalysisContext context) { if (_isCodeBlockAnalyzer) { context.RegisterCodeBlockStartAction<SyntaxKind>(OnCodeBlockStarted); context.RegisterCodeBlockAction(OnCodeBlockEnded); } else { Action<Action<SyntaxNodeAnalysisContext>, ImmutableArray<SyntaxKind>> registerMethod = (action, Kinds) => context.RegisterSyntaxNodeAction(action, Kinds); var analyzer = new NodeAnalyzer(); analyzer.Initialize(registerMethod); } } public static void OnCodeBlockEnded(CodeBlockAnalysisContext context) { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor1, Location.None)); } public static void OnCodeBlockStarted(CodeBlockStartAnalysisContext<SyntaxKind> context) { Action<Action<SyntaxNodeAnalysisContext>, ImmutableArray<SyntaxKind>> registerMethod = (action, Kinds) => context.RegisterSyntaxNodeAction(action, Kinds); var analyzer = new NodeAnalyzer(); analyzer.Initialize(registerMethod); } protected class NodeAnalyzer { public void Initialize(Action<Action<SyntaxNodeAnalysisContext>, ImmutableArray<SyntaxKind>> registerSyntaxNodeAction) { registerSyntaxNodeAction(context => { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor2, Location.None)); }, ImmutableArray.Create(SyntaxKind.EqualsValueClause)); registerSyntaxNodeAction(context => { context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor3, Location.None)); }, ImmutableArray.Create(SyntaxKind.BaseConstructorInitializer)); registerSyntaxNodeAction(context => { var descriptor = (DiagnosticDescriptor)null; switch (CSharpExtensions.Kind(context.Node.Parent)) { case SyntaxKind.PropertyDeclaration: descriptor = Descriptor4; break; case SyntaxKind.IndexerDeclaration: descriptor = Descriptor5; break; default: descriptor = Descriptor6; break; } context.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(descriptor, Location.None)); }, ImmutableArray.Create(SyntaxKind.ArrowExpressionClause)); } } } public class MethodSymbolAnalyzer : DiagnosticAnalyzer { public static DiagnosticDescriptor Descriptor1 = new DiagnosticDescriptor("MethodSymbolDiagnostic", "MethodSymbolDiagnostic", "{0}", "MethodSymbolDiagnostic", DiagnosticSeverity.Warning, isEnabledByDefault: true); public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(Descriptor1); } } public override void Initialize(AnalysisContext context) { context.RegisterSymbolAction(ctxt => { var method = ((IMethodSymbol)ctxt.Symbol); ctxt.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(Descriptor1, method.Locations[0], method.ToDisplayString())); }, SymbolKind.Method); } } [Fact, WorkItem(252, "https://github.com/dotnet/roslyn/issues/252"), WorkItem(1392, "https://github.com/dotnet/roslyn/issues/1392")] public void TestReportingUnsupportedDiagnostic() { string source = @""; CSharpCompilation compilation = CreateCompilationWithMscorlib45(source); var analyzer = new AnalyzerReportingUnsupportedDiagnostic(); var analyzers = new DiagnosticAnalyzer[] { analyzer }; string message = new ArgumentException(string.Format(CodeAnalysisResources.UnsupportedDiagnosticReported, AnalyzerReportingUnsupportedDiagnostic.UnsupportedDescriptor.Id), "diagnostic").Message; IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: {compilation.AssemblyName}")} {new LazyToString(() => analyzer.ThrownException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ID_1")}"; compilation .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CSharp.UnitTests.DiagnosticAnalyzerTests+AnalyzerReportingUnsupportedDiagnostic", "System.ArgumentException", message, context) .WithLocation(1, 1)); } [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] public class AnalyzerReportingUnsupportedDiagnostic : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor SupportedDescriptor = new DiagnosticDescriptor("ID_1", "DummyTitle", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public static readonly DiagnosticDescriptor UnsupportedDescriptor = new DiagnosticDescriptor("ID_2", "DummyTitle", "DummyMessage", "DummyCategory", DiagnosticSeverity.Warning, isEnabledByDefault: true); public Exception ThrownException { get; set; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(SupportedDescriptor); } } public override void Initialize(AnalysisContext context) { context.RegisterCompilationAction(compilationContext => { try { ThrownException = null; compilationContext.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(UnsupportedDescriptor, Location.None)); } catch (Exception e) { ThrownException = e; throw; } }); } } [Fact, WorkItem(4376, "https://github.com/dotnet/roslyn/issues/4376")] public void TestReportingDiagnosticWithInvalidId() { string source = @""; CSharpCompilation compilation = CreateCompilationWithMscorlib45(source); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithInvalidDiagnosticId() }; string message = new ArgumentException(string.Format(CodeAnalysisResources.InvalidDiagnosticIdReported, AnalyzerWithInvalidDiagnosticId.Descriptor.Id), "diagnostic").Message; Exception analyzerException = null; IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: {compilation.AssemblyName}")} {new LazyToString(() => analyzerException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "Invalid ID")}"; EventHandler<FirstChanceExceptionEventArgs> firstChanceException = (sender, e) => { if (e.Exception is ArgumentException && e.Exception.Message == message) { analyzerException = e.Exception; } }; try { AppDomain.CurrentDomain.FirstChanceException += firstChanceException; compilation .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithInvalidDiagnosticId", "System.ArgumentException", message, context) .WithLocation(1, 1)); } finally { AppDomain.CurrentDomain.FirstChanceException -= firstChanceException; } } [Fact, WorkItem(30453, "https://github.com/dotnet/roslyn/issues/30453")] public void TestAnalyzerWithNullDescriptor() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithNullDescriptor() }; var analyzerFullName = "Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithNullDescriptor"; string message = new ArgumentException(string.Format(CodeAnalysisResources.SupportedDiagnosticsHasNullDescriptor, analyzerFullName), "SupportedDiagnostics").Message; Exception analyzerException = null; IFormattable context = $@"{new LazyToString(() => analyzerException)} -----"; EventHandler<FirstChanceExceptionEventArgs> firstChanceException = (sender, e) => { if (e.Exception is ArgumentException && e.Exception.Message == message) { analyzerException = e.Exception; } }; try { AppDomain.CurrentDomain.FirstChanceException += firstChanceException; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments(analyzerFullName, "System.ArgumentException", message, context) .WithLocation(1, 1)); } finally { AppDomain.CurrentDomain.FirstChanceException -= firstChanceException; } } [Fact, WorkItem(25748, "https://github.com/dotnet/roslyn/issues/25748")] public void TestReportingDiagnosticWithCSharpCompilerId() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithCSharpCompilerDiagnosticId() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("CS101").WithLocation(1, 1)); } [Fact, WorkItem(25748, "https://github.com/dotnet/roslyn/issues/25748")] public void TestReportingDiagnosticWithBasicCompilerId() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithBasicCompilerDiagnosticId() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("BC101").WithLocation(1, 1)); } [Theory, WorkItem(7173, "https://github.com/dotnet/roslyn/issues/7173")] [CombinatorialData] public void TestReportingDiagnosticWithInvalidLocation(AnalyzerWithInvalidDiagnosticLocation.ActionKind actionKind) { var source1 = @"class C1 { void M() { int i = 0; i++; } }"; var source2 = @"class C2 { void M() { int i = 0; i++; } }"; var compilation = CreateCompilationWithMscorlib45(source1); var anotherCompilation = CreateCompilationWithMscorlib45(source2); var treeInAnotherCompilation = anotherCompilation.SyntaxTrees.Single(); string message = new ArgumentException( string.Format(CodeAnalysisResources.InvalidDiagnosticLocationReported, AnalyzerWithInvalidDiagnosticLocation.Descriptor.Id, treeInAnotherCompilation.FilePath), "diagnostic").Message; compilation.VerifyDiagnostics(); var analyzer = new AnalyzerWithInvalidDiagnosticLocation(treeInAnotherCompilation, actionKind); var analyzers = new DiagnosticAnalyzer[] { analyzer }; Exception analyzerException = null; string contextDetail; switch (actionKind) { case AnalyzerWithInvalidDiagnosticLocation.ActionKind.Symbol: contextDetail = $@"Compilation: {compilation.AssemblyName} ISymbol: C1 (NamedType)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.CodeBlock: contextDetail = $@"Compilation: {compilation.AssemblyName} ISymbol: M (Method) SyntaxTree: SyntaxNode: void M() {{ int i = 0; i++; }} [MethodDeclarationSyntax]@[11..39) (0,11)-(0,39)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.Operation: contextDetail = $@"Compilation: {compilation.AssemblyName} IOperation: VariableDeclarationGroup SyntaxTree: SyntaxNode: int i = 0; [LocalDeclarationStatementSyntax]@[22..32) (0,22)-(0,32)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.OperationBlockEnd: contextDetail = $@"Compilation: {compilation.AssemblyName} ISymbol: M (Method)"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.Compilation: case AnalyzerWithInvalidDiagnosticLocation.ActionKind.CompilationEnd: contextDetail = $@"Compilation: {compilation.AssemblyName}"; break; case AnalyzerWithInvalidDiagnosticLocation.ActionKind.SyntaxTree: contextDetail = $@"Compilation: {compilation.AssemblyName} SyntaxTree: "; break; default: throw ExceptionUtilities.Unreachable; } IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, contextDetail)} {new LazyToString(() => analyzerException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ID")}"; EventHandler<FirstChanceExceptionEventArgs> firstChanceException = (sender, e) => { if (e.Exception is ArgumentException && e.Exception.Message == message) { analyzerException = e.Exception; } }; try { AppDomain.CurrentDomain.FirstChanceException += firstChanceException; compilation .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithInvalidDiagnosticLocation", "System.ArgumentException", message, context) .WithLocation(1, 1) ); } finally { AppDomain.CurrentDomain.FirstChanceException -= firstChanceException; } } [Fact] public void TestReportingDiagnosticWithInvalidSpan() { var source1 = @"class C1 { void M() { int i = 0; i++; } }"; var compilation = CreateCompilationWithMscorlib45(source1); var treeInAnotherCompilation = compilation.SyntaxTrees.Single(); var badSpan = new Text.TextSpan(100000, 10000); var analyzer = new AnalyzerWithInvalidDiagnosticSpan(badSpan); string message = new ArgumentException( string.Format(CodeAnalysisResources.InvalidDiagnosticSpanReported, AnalyzerWithInvalidDiagnosticSpan.Descriptor.Id, badSpan, treeInAnotherCompilation.FilePath), "diagnostic").Message; IFormattable context = $@"{string.Format(CodeAnalysisResources.ExceptionContext, $@"Compilation: {compilation.AssemblyName} SyntaxTree: ")} {new LazyToString(() => analyzer.ThrownException)} ----- {string.Format(CodeAnalysisResources.DisableAnalyzerDiagnosticsMessage, "ID")}"; compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { analyzer }; compilation .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic("AD0001") .WithArguments("Microsoft.CodeAnalysis.CommonDiagnosticAnalyzers+AnalyzerWithInvalidDiagnosticSpan", "System.ArgumentException", message, context) .WithLocation(1, 1) ); } [Fact, WorkItem(1473, "https://github.com/dotnet/roslyn/issues/1473")] public void TestReportingNotConfigurableDiagnostic() { string source = @""; var analyzers = new DiagnosticAnalyzer[] { new NotConfigurableDiagnosticAnalyzer() }; // Verify, not configurable enabled diagnostic is always reported and disabled diagnostic is never reported.. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id)); // Verify not configurable enabled diagnostic cannot be suppressed. var specificDiagOptions = new Dictionary<string, ReportDiagnostic>(); specificDiagOptions.Add(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id, ReportDiagnostic.Suppress); var options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); CreateCompilationWithMscorlib45(source, options: options) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id)); // Verify not configurable disabled diagnostic cannot be enabled. specificDiagOptions.Clear(); specificDiagOptions.Add(NotConfigurableDiagnosticAnalyzer.DisabledRule.Id, ReportDiagnostic.Warn); options = TestOptions.ReleaseDll.WithSpecificDiagnosticOptions(specificDiagOptions); CreateCompilationWithMscorlib45(source, options: options) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(NotConfigurableDiagnosticAnalyzer.EnabledRule.Id)); } [Fact, WorkItem(1709, "https://github.com/dotnet/roslyn/issues/1709")] public void TestCodeBlockAction() { string source = @" class C { public void M() {} }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockActionAnalyzer() }; // Verify, code block action diagnostics. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: new[] { Diagnostic(CodeBlockActionAnalyzer.CodeBlockTopLevelRule.Id, "M").WithArguments("M").WithLocation(4, 17), Diagnostic(CodeBlockActionAnalyzer.CodeBlockPerCompilationRule.Id, "M").WithArguments("M").WithLocation(4, 17) }); } [Fact, WorkItem(1709, "https://github.com/dotnet/roslyn/issues/1709")] public void TestCodeBlockAction_OnlyStatelessAction() { string source = @" class C { public void M() {} }"; var analyzers = new DiagnosticAnalyzer[] { new CodeBlockActionAnalyzer(onlyStatelessAction: true) }; // Verify, code block action diagnostics. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: Diagnostic(CodeBlockActionAnalyzer.CodeBlockTopLevelRule.Id, "M").WithArguments("M").WithLocation(4, 17)); } [Fact, WorkItem(2614, "https://github.com/dotnet/roslyn/issues/2614")] public void TestGenericName() { var source = @" using System; using System.Text; namespace ConsoleApplication1 { class MyClass { private Nullable<int> myVar = 5; void Method() { } } }"; TestGenericNameCore(source, new CSharpGenericNameAnalyzer()); } private void TestGenericNameCore(string source, params DiagnosticAnalyzer[] analyzers) { // Verify, no duplicate diagnostics on generic name. CreateCompilationWithMscorlib45(source) .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic(CSharpGenericNameAnalyzer.DiagnosticId, @"Nullable<int>").WithLocation(9, 17)); } [Fact, WorkItem(4745, "https://github.com/dotnet/roslyn/issues/4745")] public void TestNamespaceDeclarationAnalyzer() { var source = @" namespace Goo.Bar.GooBar { } "; var analyzers = new DiagnosticAnalyzer[] { new CSharpNamespaceDeclarationAnalyzer() }; // Verify, no duplicate diagnostics on qualified name. CreateCompilationWithMscorlib45(source) .VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic(CSharpNamespaceDeclarationAnalyzer.DiagnosticId, @"namespace Goo.Bar.GooBar { }").WithLocation(2, 1)); } [Fact, WorkItem(2980, "https://github.com/dotnet/roslyn/issues/2980")] public void TestAnalyzerWithNoActions() { var source = @" using System; using System.Text; namespace ConsoleApplication1 { class MyClass { private Nullable<int> myVar = 5; void Method() { } } }"; // Ensure that adding a dummy analyzer with no actions doesn't bring down entire analysis. // See https://github.com/dotnet/roslyn/issues/2980 for details. TestGenericNameCore(source, new AnalyzerWithNoActions(), new CSharpGenericNameAnalyzer()); } [Fact, WorkItem(4055, "https://github.com/dotnet/roslyn/issues/4055")] public void TestAnalyzerWithNoSupportedDiagnostics() { var source = @" class MyClass { }"; // Ensure that adding a dummy analyzer with no supported diagnostics doesn't bring down entire analysis. var analyzers = new DiagnosticAnalyzer[] { new AnalyzerWithNoSupportedDiagnostics() }; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers); } private static void TestEffectiveSeverity( DiagnosticSeverity defaultSeverity, ReportDiagnostic expectedEffectiveSeverity, Dictionary<string, ReportDiagnostic> specificOptions = null, ReportDiagnostic generalOption = ReportDiagnostic.Default, bool isEnabledByDefault = true) { specificOptions = specificOptions ?? new Dictionary<string, ReportDiagnostic>(); var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication, generalDiagnosticOption: generalOption, specificDiagnosticOptions: specificOptions); var descriptor = new DiagnosticDescriptor(id: "Test0001", title: "Test0001", messageFormat: "Test0001", category: "Test0001", defaultSeverity: defaultSeverity, isEnabledByDefault: isEnabledByDefault); var effectiveSeverity = descriptor.GetEffectiveSeverity(options); Assert.Equal(expectedEffectiveSeverity, effectiveSeverity); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_DiagnosticDefault1() { TestEffectiveSeverity(DiagnosticSeverity.Warning, ReportDiagnostic.Warn); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_DiagnosticDefault2() { var specificOptions = new Dictionary<string, ReportDiagnostic>() { { "Test0001", ReportDiagnostic.Default } }; var generalOption = ReportDiagnostic.Error; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: ReportDiagnostic.Warn, specificOptions: specificOptions, generalOption: generalOption); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_GeneralOption() { var generalOption = ReportDiagnostic.Error; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: generalOption, generalOption: generalOption); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_SpecificOption() { var specificOption = ReportDiagnostic.Suppress; var specificOptions = new Dictionary<string, ReportDiagnostic>() { { "Test0001", specificOption } }; var generalOption = ReportDiagnostic.Error; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: specificOption, specificOptions: specificOptions, generalOption: generalOption); } [Fact] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_GeneralOptionDoesNotEnableDisabledDiagnostic() { var generalOption = ReportDiagnostic.Error; var enabledByDefault = false; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: ReportDiagnostic.Suppress, generalOption: generalOption, isEnabledByDefault: enabledByDefault); } [Fact()] [WorkItem(1107500, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1107500")] [WorkItem(2598, "https://github.com/dotnet/roslyn/issues/2598")] public void EffectiveSeverity_SpecificOptionEnablesDisabledDiagnostic() { var specificOption = ReportDiagnostic.Warn; var specificOptions = new Dictionary<string, ReportDiagnostic>() { { "Test0001", specificOption } }; var generalOption = ReportDiagnostic.Error; var enabledByDefault = false; TestEffectiveSeverity(DiagnosticSeverity.Warning, expectedEffectiveSeverity: specificOption, specificOptions: specificOptions, generalOption: generalOption, isEnabledByDefault: enabledByDefault); } [Fact, WorkItem(5463, "https://github.com/dotnet/roslyn/issues/5463")] public void TestObjectCreationInCodeBlockAnalyzer() { string source = @" class C { } class D { public C x = new C(); }"; var analyzers = new DiagnosticAnalyzer[] { new CSharpCodeBlockObjectCreationAnalyzer() }; // Verify, code block action diagnostics. CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(analyzers, null, null, expected: new[] { Diagnostic(CSharpCodeBlockObjectCreationAnalyzer.DiagnosticDescriptor.Id, "new C()").WithLocation(5, 18) }); } private static Compilation GetCompilationWithConcurrentBuildEnabled(string source) { var compilation = CreateCompilationWithMscorlib45(source); // NOTE: We set the concurrentBuild option to true after creating the compilation as CreateCompilationWithMscorlib // always sets concurrentBuild to false if debugger is attached, even if we had passed options with concurrentBuild = true to that API. // We want the tests using GetCompilationWithConcurrentBuildEnabled to have identical behavior with and without debugger being attached. var options = compilation.Options.WithConcurrentBuild(true); return compilation.WithOptions(options); } [Fact, WorkItem(6737, "https://github.com/dotnet/roslyn/issues/6737")] public void TestNonConcurrentAnalyzer() { var builder = new StringBuilder(); var typeCount = 100; for (int i = 1; i <= typeCount; i++) { var typeName = $"C{i}"; builder.Append($"\r\nclass {typeName} {{ }}"); } var source = builder.ToString(); var analyzers = new DiagnosticAnalyzer[] { new NonConcurrentAnalyzer() }; // Verify no diagnostics. var compilation = GetCompilationWithConcurrentBuildEnabled(source); compilation.VerifyDiagnostics(); compilation.VerifyAnalyzerDiagnostics(analyzers); } [Fact, WorkItem(6737, "https://github.com/dotnet/roslyn/issues/6737")] public void TestConcurrentAnalyzer() { if (Environment.ProcessorCount <= 1) { // Don't test for non-concurrent environment. return; } var builder = new StringBuilder(); var typeCount = 100; var typeNames = new string[typeCount]; for (int i = 1; i <= typeCount; i++) { var typeName = $"C{i}"; typeNames[i - 1] = typeName; builder.Append($"\r\nclass {typeName} {{ }}"); } var source = builder.ToString(); var compilation = GetCompilationWithConcurrentBuildEnabled(source); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics for Concurrent analyzer only. var analyzers = new DiagnosticAnalyzer[] { new ConcurrentAnalyzer(typeNames) }; var expected = new DiagnosticDescription[typeCount]; for (int i = 0; i < typeCount; i++) { var typeName = $"C{i + 1}"; expected[i] = Diagnostic(ConcurrentAnalyzer.Descriptor.Id, typeName) .WithArguments(typeName) .WithLocation(i + 2, 7); } compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); // Verify analyzer diagnostics for Concurrent and NonConcurrent analyzer together (latter reports diagnostics only for error cases). analyzers = new DiagnosticAnalyzer[] { new ConcurrentAnalyzer(typeNames), new NonConcurrentAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(6998, "https://github.com/dotnet/roslyn/issues/6998")] public void TestGeneratedCodeAnalyzer() { string source = @" [System.CodeDom.Compiler.GeneratedCodeAttribute(""tool"", ""version"")] class GeneratedCode{0} {{ private class Nested{0} {{ }} }} class NonGeneratedCode{0} {{ [System.CodeDom.Compiler.GeneratedCodeAttribute(""tool"", ""version"")] private class NestedGeneratedCode{0} {{ }} }} "; var generatedFileNames = new List<string> { "TemporaryGeneratedFile_036C0B5B-1481-4323-8D20-8F5ADCB23D92.cs", "Test.designer.cs", "Test.Designer.cs", "Test.generated.cs", "Test.g.cs", "Test.g.i.cs" }; var builder = ImmutableArray.CreateBuilder<SyntaxTree>(); int treeNum = 0; // Trees with non-generated code file names var tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "SourceFileRegular.cs"); builder.Add(tree); tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "AssemblyInfo.cs"); builder.Add(tree); // Trees with generated code file names foreach (var fileName in generatedFileNames) { tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: fileName); builder.Add(tree); } var autoGeneratedPrefixes = new[] { @"// <auto-generated>", @"// <autogenerated>", @"/* <auto-generated> */" }; for (var i = 0; i < autoGeneratedPrefixes.Length; i++) { // Tree with '<auto-generated>' comment var autoGeneratedPrefix = autoGeneratedPrefixes[i]; tree = CSharpSyntaxTree.ParseText(string.Format(autoGeneratedPrefix + source, treeNum++), path: $"SourceFileWithAutoGeneratedComment{i++}.cs"); builder.Add(tree); } // Files with editorconfig based "generated_code" configuration var analyzerConfigOptionsPerTreeBuilder = ImmutableDictionary.CreateBuilder<object, AnalyzerConfigOptions>(); // (1) "generated_code = true" const string myGeneratedFileTrueName = "MyGeneratedFileTrue.cs"; generatedFileNames.Add(myGeneratedFileTrueName); tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: myGeneratedFileTrueName); builder.Add(tree); var analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "true")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); // (2) "generated_code = TRUE" (case insensitive) const string myGeneratedFileCaseInsensitiveTrueName = "MyGeneratedFileCaseInsensitiveTrue.cs"; generatedFileNames.Add(myGeneratedFileCaseInsensitiveTrueName); tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: myGeneratedFileCaseInsensitiveTrueName); builder.Add(tree); analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "TRUE")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); // (3) "generated_code = false" tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "MyGeneratedFileFalse.cs"); builder.Add(tree); analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "false")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); // (4) "generated_code = auto" tree = CSharpSyntaxTree.ParseText(string.Format(source, treeNum++), path: "MyGeneratedFileAuto.cs"); builder.Add(tree); analyzerConfigOptions = new CompilerAnalyzerConfigOptions(ImmutableDictionary<string, string>.Empty.Add("generated_code", "auto")); analyzerConfigOptionsPerTreeBuilder.Add(tree, analyzerConfigOptions); var analyzerConfigOptionsProvider = new CompilerAnalyzerConfigOptionsProvider(analyzerConfigOptionsPerTreeBuilder.ToImmutable(), CompilerAnalyzerConfigOptions.Empty); var analyzerOptions = new AnalyzerOptions(additionalFiles: ImmutableArray<AdditionalText>.Empty, analyzerConfigOptionsProvider); // Verify no compiler diagnostics. var trees = builder.ToImmutable(); var compilation = CreateCompilationWithMscorlib45(trees, new MetadataReference[] { SystemRef }); compilation.VerifyDiagnostics(); Func<string, bool> isGeneratedFile = fileName => fileName.Contains("SourceFileWithAutoGeneratedComment") || generatedFileNames.Contains(fileName); // (1) Verify default mode of analysis when there is no generated code configuration. VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, generatedCodeAnalysisFlagsOpt: null); // (2) Verify ConfigureGeneratedCodeAnalysis with different combinations of GeneratedCodeAnalysisFlags. VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.None); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.Analyze); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.ReportDiagnostics); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, analyzerOptions, isGeneratedFile, GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); // (4) Ensure warnaserror doesn't produce noise in generated files. var options = compilation.Options.WithGeneralDiagnosticOption(ReportDiagnostic.Error); var warnAsErrorCompilation = compilation.WithOptions(options); VerifyGeneratedCodeAnalyzerDiagnostics(warnAsErrorCompilation, analyzerOptions, isGeneratedFile, generatedCodeAnalysisFlagsOpt: null); } [Fact, WorkItem(6998, "https://github.com/dotnet/roslyn/issues/6998")] public void TestGeneratedCodeAnalyzerPartialType() { string source = @" [System.CodeDom.Compiler.GeneratedCodeAttribute(""tool"", ""version"")] partial class PartialType { } partial class PartialType { } "; var tree = CSharpSyntaxTree.ParseText(source, path: "SourceFileRegular.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }, new MetadataReference[] { SystemRef }); compilation.VerifyDiagnostics(); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); // Expected symbol diagnostics var squiggledText = "PartialType"; var diagnosticArgument = squiggledText; var line = 3; var column = 15; AddExpectedLocalDiagnostics(builder, false, squiggledText, line, column, GeneratedCodeAnalysisFlags.ReportDiagnostics, diagnosticArgument); // Expected tree diagnostics squiggledText = "}"; diagnosticArgument = tree.FilePath; line = 9; column = 1; AddExpectedLocalDiagnostics(builder, false, squiggledText, line, column, GeneratedCodeAnalysisFlags.ReportDiagnostics, diagnosticArgument); // Expected compilation diagnostics AddExpectedNonLocalDiagnostic(builder, "PartialType", compilation.SyntaxTrees[0].FilePath); var expected = builder.ToArrayAndFree(); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, generatedCodeAnalysisFlagsOpt: null); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.None); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.Analyze); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.ReportDiagnostics); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); } [Fact, WorkItem(11217, "https://github.com/dotnet/roslyn/issues/11217")] public void TestGeneratedCodeAnalyzerNoReportDiagnostics() { string source1 = @" class TypeInUserFile { } "; string source2 = @" class TypeInGeneratedFile { } "; var tree1 = CSharpSyntaxTree.ParseText(source1, path: "SourceFileRegular.cs"); var tree2 = CSharpSyntaxTree.ParseText(source2, path: "SourceFileRegular.Designer.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }, new MetadataReference[] { SystemRef }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer2() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("GeneratedCodeAnalyzer2Warning", "TypeInUserFile").WithArguments("TypeInUserFile", "2").WithLocation(2, 7)); } internal class OwningSymbolTestAnalyzer : DiagnosticAnalyzer { public static readonly DiagnosticDescriptor ExpressionDescriptor = new DiagnosticDescriptor( "Expression", "Expression", "Expression found.", "Testing", DiagnosticSeverity.Warning, isEnabledByDefault: true); public sealed override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get { return ImmutableArray.Create(ExpressionDescriptor); } } public sealed override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction( (nodeContext) => { if (nodeContext.ContainingSymbol.Name.StartsWith("Funky") && nodeContext.Compilation.Language == "C#") { nodeContext.ReportDiagnostic(CodeAnalysis.Diagnostic.Create(ExpressionDescriptor, nodeContext.Node.GetLocation())); } }, SyntaxKind.IdentifierName, SyntaxKind.NumericLiteralExpression); } } [Fact] public void OwningSymbolTest() { const string source = @" class C { public void UnFunkyMethod() { int x = 0; int y = x; } public void FunkyMethod() { int x = 0; int y = x; } public int FunkyField = 12; public int UnFunkyField = 12; } "; CreateCompilationWithMscorlib45(source) .VerifyDiagnostics() .VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { new OwningSymbolTestAnalyzer() }, null, null, Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "0").WithLocation(12, 17), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "x").WithLocation(13, 17), Diagnostic(OwningSymbolTestAnalyzer.ExpressionDescriptor.Id, "12").WithLocation(16, 29)); } private static void VerifyGeneratedCodeAnalyzerDiagnostics(Compilation compilation, AnalyzerOptions analyzerOptions, Func<string, bool> isGeneratedFileName, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt) { var expected = GetExpectedGeneratedCodeAnalyzerDiagnostics(compilation, isGeneratedFileName, generatedCodeAnalysisFlagsOpt); VerifyGeneratedCodeAnalyzerDiagnostics(compilation, expected, generatedCodeAnalysisFlagsOpt, analyzerOptions); } private static void VerifyGeneratedCodeAnalyzerDiagnostics(Compilation compilation, DiagnosticDescription[] expected, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt, AnalyzerOptions analyzerOptions = null) { var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(generatedCodeAnalysisFlagsOpt) }; compilation.VerifyAnalyzerDiagnostics(analyzers, analyzerOptions, null, expected: expected); } private static DiagnosticDescription[] GetExpectedGeneratedCodeAnalyzerDiagnostics(Compilation compilation, Func<string, bool> isGeneratedFileName, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt) { var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(generatedCodeAnalysisFlagsOpt) }; var files = compilation.SyntaxTrees.Select(t => t.FilePath).ToImmutableArray(); var sortedCallbackSymbolNames = new SortedSet<string>(); var sortedCallbackTreePaths = new SortedSet<string>(); var builder = ArrayBuilder<DiagnosticDescription>.GetInstance(); for (int i = 0; i < compilation.SyntaxTrees.Count(); i++) { var file = files[i]; var isGeneratedFile = isGeneratedFileName(file); // Type "GeneratedCode{0}" var squiggledText = string.Format("GeneratedCode{0}", i); var diagnosticArgument = squiggledText; var line = 3; var column = 7; var isGeneratedCode = true; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Type "Nested{0}" squiggledText = string.Format("Nested{0}", i); diagnosticArgument = squiggledText; line = 5; column = 19; isGeneratedCode = true; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Type "NonGeneratedCode{0}" squiggledText = string.Format("NonGeneratedCode{0}", i); diagnosticArgument = squiggledText; line = 8; column = 7; isGeneratedCode = isGeneratedFile; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Type "NestedGeneratedCode{0}" squiggledText = string.Format("NestedGeneratedCode{0}", i); diagnosticArgument = squiggledText; line = 11; column = 19; isGeneratedCode = true; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // File diagnostic squiggledText = "}"; // last token in file. diagnosticArgument = file; line = 12; column = 1; isGeneratedCode = isGeneratedFile; AddExpectedLocalDiagnostics(builder, isGeneratedCode, squiggledText, line, column, generatedCodeAnalysisFlagsOpt, diagnosticArgument); // Compilation end summary diagnostic (verify callbacks into analyzer) // Analyzer always called for generated code, unless generated code analysis is explicitly disabled. if (generatedCodeAnalysisFlagsOpt == null || (generatedCodeAnalysisFlagsOpt & GeneratedCodeAnalysisFlags.Analyze) != 0) { sortedCallbackSymbolNames.Add(string.Format("GeneratedCode{0}", i)); sortedCallbackSymbolNames.Add(string.Format("Nested{0}", i)); sortedCallbackSymbolNames.Add(string.Format("NonGeneratedCode{0}", i)); sortedCallbackSymbolNames.Add(string.Format("NestedGeneratedCode{0}", i)); sortedCallbackTreePaths.Add(file); } else if (!isGeneratedFile) { // Analyzer always called for non-generated code. sortedCallbackSymbolNames.Add(string.Format("NonGeneratedCode{0}", i)); sortedCallbackTreePaths.Add(file); } } // Compilation end summary diagnostic (verify callbacks into analyzer) var arg1 = sortedCallbackSymbolNames.Join(","); var arg2 = sortedCallbackTreePaths.Join(","); AddExpectedNonLocalDiagnostic(builder, arguments: new[] { arg1, arg2 }); if (compilation.Options.GeneralDiagnosticOption == ReportDiagnostic.Error) { for (int i = 0; i < builder.Count; i++) { if (((string)builder[i].Code) != GeneratedCodeAnalyzer.Error.Id) { builder[i] = builder[i].WithWarningAsError(true); } } } return builder.ToArrayAndFree(); } private static void AddExpectedLocalDiagnostics( ArrayBuilder<DiagnosticDescription> builder, bool isGeneratedCode, string squiggledText, int line, int column, GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt, params string[] arguments) { // Always report diagnostics in generated code, unless explicitly suppressed or we are not even analyzing generated code. var reportInGeneratedCode = generatedCodeAnalysisFlagsOpt == null || ((generatedCodeAnalysisFlagsOpt & GeneratedCodeAnalysisFlags.ReportDiagnostics) != 0 && (generatedCodeAnalysisFlagsOpt & GeneratedCodeAnalysisFlags.Analyze) != 0); if (!isGeneratedCode || reportInGeneratedCode) { var diagnostic = Diagnostic(GeneratedCodeAnalyzer.Warning.Id, squiggledText).WithArguments(arguments).WithLocation(line, column); builder.Add(diagnostic); diagnostic = Diagnostic(GeneratedCodeAnalyzer.Error.Id, squiggledText).WithArguments(arguments).WithLocation(line, column); builder.Add(diagnostic); } } private static void AddExpectedNonLocalDiagnostic(ArrayBuilder<DiagnosticDescription> builder, params string[] arguments) { AddExpectedDiagnostic(builder, GeneratedCodeAnalyzer.Summary.Id, squiggledText: null, line: 1, column: 1, arguments: arguments); } private static void AddExpectedDiagnostic(ArrayBuilder<DiagnosticDescription> builder, string diagnosticId, string squiggledText, int line, int column, params string[] arguments) { var diagnostic = Diagnostic(diagnosticId, squiggledText).WithArguments(arguments).WithLocation(line, column); builder.Add(diagnostic); } [Fact] public void TestEnsureNoMergedNamespaceSymbolAnalyzer() { var source = @"namespace N1.N2 { }"; var metadataReference = CreateCompilation(source).ToMetadataReference(); var compilation = CreateCompilation(source, new[] { metadataReference }); compilation.VerifyDiagnostics(); // Analyzer reports a diagnostic if it receives a merged namespace symbol across assemblies in compilation. var analyzers = new DiagnosticAnalyzer[] { new EnsureNoMergedNamespaceSymbolAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers); } [Fact, WorkItem(6324, "https://github.com/dotnet/roslyn/issues/6324")] public void TestSharedStateAnalyzer() { string source1 = @" public partial class C { } "; string source2 = @" public partial class C2 { } "; string source3 = @" public partial class C33 { } "; var tree1 = CSharpSyntaxTree.ParseText(source1, path: "Source1_File1.cs"); var tree2 = CSharpSyntaxTree.ParseText(source1, path: "Source1_File2.cs"); var tree3 = CSharpSyntaxTree.ParseText(source2, path: "Source2_File3.cs"); var tree4 = CSharpSyntaxTree.ParseText(source3, path: "Source3_File4.generated.cs"); var tree5 = CSharpSyntaxTree.ParseText(source3, path: "Source3_File5.designer.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2, tree3, tree4, tree5 }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new SharedStateAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("UserCodeDiagnostic").WithArguments("Source1_File1.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source1_File1.cs").WithLocation(1, 1), Diagnostic("GeneratedCodeDiagnostic", "C33").WithArguments("C33").WithLocation(2, 22), Diagnostic("UserCodeDiagnostic", "C2").WithArguments("C2").WithLocation(2, 22), Diagnostic("UserCodeDiagnostic", "C").WithArguments("C").WithLocation(2, 22), Diagnostic("UserCodeDiagnostic").WithArguments("Source1_File2.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source1_File2.cs").WithLocation(1, 1), Diagnostic("UserCodeDiagnostic").WithArguments("Source2_File3.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source2_File3.cs").WithLocation(1, 1), Diagnostic("GeneratedCodeDiagnostic").WithArguments("Source3_File4.generated.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source3_File4.generated.cs").WithLocation(1, 1), Diagnostic("GeneratedCodeDiagnostic").WithArguments("Source3_File5.designer.cs").WithLocation(1, 1), Diagnostic("UniqueTextFileDiagnostic").WithArguments("Source3_File5.designer.cs").WithLocation(1, 1), Diagnostic("NumberOfUniqueTextFileDescriptor").WithArguments("3").WithLocation(1, 1)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InConstructor() { string source = @" public class C { public C(int a, int b) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(4, 18), Diagnostic("Parameter_ID", "b").WithLocation(4, 25)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InRegularMethod() { string source = @" public class C { void M1(string a, string b) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(4, 20), Diagnostic("Parameter_ID", "b").WithLocation(4, 30)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InIndexers() { string source = @" public class C { public int this[int index] { get { return 0; } set { } } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "index").WithLocation(4, 25)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14061"), WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_Lambdas() { string source = @" public class C { void M2() { System.Func<int, int, int> x = (int a, int b) => b; } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Local_ID", "x").WithLocation(6, 36), Diagnostic("Parameter_ID", "a").WithLocation(6, 45), Diagnostic("Parameter_ID", "b").WithLocation(6, 52)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14061"), WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InAnonymousMethods() { string source = @" public class C { void M3() { M4(delegate (int x, int y) { }); } void M4(System.Action<int, int> a) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(9, 37), Diagnostic("Parameter_ID", "x").WithLocation(6, 26), Diagnostic("Parameter_ID", "y").WithLocation(6, 33)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InDelegateTypes() { string source = @" public class C { delegate void D(int x, string y); } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "x").WithLocation(4, 25), Diagnostic("Parameter_ID", "y").WithLocation(4, 35)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InOperators() { string source = @" public class C { public static implicit operator int (C c) { return 0; } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "c").WithLocation(4, 44)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InExplicitInterfaceImplementations() { string source = @" interface I { void M(int a, int b); } public class C : I { void I.M(int c, int d) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "c").WithLocation(9, 18), Diagnostic("Parameter_ID", "d").WithLocation(9, 25), Diagnostic("Parameter_ID", "a").WithLocation(4, 16), Diagnostic("Parameter_ID", "b").WithLocation(4, 23)); } [Fact, WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InExtensionMethods() { string source = @" public static class C { static void M(this int x, int y) { } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "x").WithLocation(4, 28), Diagnostic("Parameter_ID", "y").WithLocation(4, 35)); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/14061"), WorkItem(8753, "https://github.com/dotnet/roslyn/issues/8753")] public void TestParametersAnalyzer_InLocalFunctions() { string source = @" public class C { void M1() { M2(1, 2); void M2(int a, int b) { } } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new AnalyzerForParameters() }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("Parameter_ID", "a").WithLocation(4, 18), // ctor Diagnostic("Parameter_ID", "b").WithLocation(4, 25), Diagnostic("Local_ID", "c").WithLocation(6, 13), Diagnostic("Local_ID", "d").WithLocation(6, 20), Diagnostic("Parameter_ID", "a").WithLocation(10, 20), // M1 Diagnostic("Parameter_ID", "b").WithLocation(10, 30), Diagnostic("Local_ID", "c").WithLocation(12, 11), Diagnostic("Local_ID", "x").WithLocation(18, 36), // M2 Diagnostic("Parameter_ID", "a").WithLocation(26, 37), // M4 Diagnostic("Parameter_ID", "index").WithLocation(28, 25)); // indexer } [Fact, WorkItem(15903, "https://github.com/dotnet/roslyn/issues/15903")] public void TestSymbolAnalyzer_HiddenRegions() { string source = @" #line hidden public class HiddenClass { } #line default public class RegularClass { } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags.None) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerError", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerWarning", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerError", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("RegularClass", "Source.cs").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags.Analyze) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerError", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerWarning", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerError", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("HiddenClass,RegularClass", "Source.cs").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeAnalyzer(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerError", "}").WithArguments("Source.cs").WithLocation(11, 1), Diagnostic("GeneratedCodeAnalyzerWarning", "HiddenClass").WithArguments("HiddenClass").WithLocation(4, 14), Diagnostic("GeneratedCodeAnalyzerError", "HiddenClass").WithArguments("HiddenClass").WithLocation(4, 14), Diagnostic("GeneratedCodeAnalyzerWarning", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerError", "RegularClass").WithArguments("RegularClass").WithLocation(9, 14), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("HiddenClass,RegularClass", "Source.cs").WithLocation(1, 1)); } [Fact, WorkItem(15903, "https://github.com/dotnet/roslyn/issues/15903")] public void TestSyntaxAndOperationAnalyzer_HiddenRegions() { string source = @" public class Class { void DummyMethod(int i) { } #line hidden void HiddenMethod() { var hiddenVar = 0; DummyMethod(hiddenVar); } #line default void NonHiddenMethod() { var userVar = 0; DummyMethod(userVar); } void MixMethod() { #line hidden var mixMethodHiddenVar = 0; #line default var mixMethodUserVar = 0; DummyMethod(mixMethodHiddenVar + mixMethodUserVar); } } "; var tree = CSharpSyntaxTree.ParseText(source, path: "Source.cs"); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var syntaxKinds = ImmutableArray.Create(SyntaxKind.VariableDeclaration); var operationKinds = ImmutableArray.Create(OperationKind.VariableDeclarator); var analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags.None, syntaxKinds, operationKinds) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "var userVar = 0").WithArguments("Node: var userVar = 0").WithLocation(17, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodUserVar = 0").WithArguments("Node: var mixMethodUserVar = 0").WithLocation(26, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "userVar = 0").WithArguments("Operation: NonHiddenMethod").WithLocation(17, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodUserVar = 0").WithArguments("Operation: MixMethod").WithLocation(26, 13), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("Node: var mixMethodUserVar = 0,Node: var userVar = 0,Operation: MixMethod,Operation: NonHiddenMethod").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags.Analyze, syntaxKinds, operationKinds) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "var userVar = 0").WithArguments("Node: var userVar = 0").WithLocation(17, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "userVar = 0").WithArguments("Operation: NonHiddenMethod").WithLocation(17, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodUserVar = 0").WithArguments("Node: var mixMethodUserVar = 0").WithLocation(26, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodUserVar = 0").WithArguments("Operation: MixMethod").WithLocation(26, 13), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("Node: var hiddenVar = 0,Node: var mixMethodHiddenVar = 0,Node: var mixMethodUserVar = 0,Node: var userVar = 0,Operation: HiddenMethod,Operation: MixMethod,Operation: NonHiddenMethod").WithLocation(1, 1)); analyzers = new DiagnosticAnalyzer[] { new GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics, syntaxKinds, operationKinds) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("GeneratedCodeAnalyzerWarning", "var hiddenVar = 0").WithArguments("Node: var hiddenVar = 0").WithLocation(10, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "hiddenVar = 0").WithArguments("Operation: HiddenMethod").WithLocation(10, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "var userVar = 0").WithArguments("Node: var userVar = 0").WithLocation(17, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "userVar = 0").WithArguments("Operation: NonHiddenMethod").WithLocation(17, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodHiddenVar = 0").WithArguments("Node: var mixMethodHiddenVar = 0").WithLocation(24, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "var mixMethodUserVar = 0").WithArguments("Node: var mixMethodUserVar = 0").WithLocation(26, 9), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodHiddenVar = 0").WithArguments("Operation: MixMethod").WithLocation(24, 13), Diagnostic("GeneratedCodeAnalyzerWarning", "mixMethodUserVar = 0").WithArguments("Operation: MixMethod").WithLocation(26, 13), Diagnostic("GeneratedCodeAnalyzerSummary").WithArguments("Node: var hiddenVar = 0,Node: var mixMethodHiddenVar = 0,Node: var mixMethodUserVar = 0,Node: var userVar = 0,Operation: HiddenMethod,Operation: MixMethod,Operation: NonHiddenMethod").WithLocation(1, 1)); } [DiagnosticAnalyzer(LanguageNames.CSharp)] public class GeneratedCodeSyntaxAndOperationAnalyzer : DiagnosticAnalyzer { private readonly GeneratedCodeAnalysisFlags? _generatedCodeAnalysisFlagsOpt; private readonly ImmutableArray<SyntaxKind> _syntaxKinds; private readonly ImmutableArray<OperationKind> _operationKinds; public static readonly DiagnosticDescriptor Warning = new DiagnosticDescriptor( "GeneratedCodeAnalyzerWarning", "Title", "GeneratedCodeAnalyzerMessage for '{0}'", "Category", DiagnosticSeverity.Warning, true); public static readonly DiagnosticDescriptor Summary = new DiagnosticDescriptor( "GeneratedCodeAnalyzerSummary", "Title2", "GeneratedCodeAnalyzer received callbacks for: '{0}' entities", "Category", DiagnosticSeverity.Warning, true); public GeneratedCodeSyntaxAndOperationAnalyzer(GeneratedCodeAnalysisFlags? generatedCodeAnalysisFlagsOpt, ImmutableArray<SyntaxKind> syntaxKinds, ImmutableArray<OperationKind> operationKinds) { _generatedCodeAnalysisFlagsOpt = generatedCodeAnalysisFlagsOpt; _syntaxKinds = syntaxKinds; _operationKinds = operationKinds; } public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Warning, Summary); public override void Initialize(AnalysisContext context) { context.RegisterCompilationStartAction(this.OnCompilationStart); if (_generatedCodeAnalysisFlagsOpt.HasValue) { // Configure analysis on generated code. context.ConfigureGeneratedCodeAnalysis(_generatedCodeAnalysisFlagsOpt.Value); } } private void OnCompilationStart(CompilationStartAnalysisContext context) { var sortedCallbackEntityNames = new SortedSet<string>(); context.RegisterSyntaxNodeAction(syntaxContext => { sortedCallbackEntityNames.Add($"Node: {syntaxContext.Node.ToString()}"); ReportNodeDiagnostics(syntaxContext.Node, syntaxContext.ReportDiagnostic); }, _syntaxKinds); context.RegisterOperationAction(operationContext => { sortedCallbackEntityNames.Add($"Operation: {operationContext.ContainingSymbol.Name}"); ReportOperationDiagnostics(operationContext.Operation, operationContext.ContainingSymbol.Name, operationContext.ReportDiagnostic); }, _operationKinds); context.RegisterCompilationEndAction(endContext => { // Summary diagnostic about received callbacks. var diagnostic = CodeAnalysis.Diagnostic.Create(Summary, Location.None, sortedCallbackEntityNames.Join(",")); endContext.ReportDiagnostic(diagnostic); }); } private void ReportNodeDiagnostics(SyntaxNode node, Action<Diagnostic> addDiagnostic) { ReportDiagnosticsCore(addDiagnostic, node.Location, $"Node: {node.ToString()}"); } private void ReportOperationDiagnostics(IOperation operation, string name, Action<Diagnostic> addDiagnostic) { ReportDiagnosticsCore(addDiagnostic, operation.Syntax.Location, $"Operation: {name}"); } private void ReportDiagnosticsCore(Action<Diagnostic> addDiagnostic, Location location, params object[] messageArguments) { // warning diagnostic var diagnostic = CodeAnalysis.Diagnostic.Create(Warning, location, messageArguments); addDiagnostic(diagnostic); } } [Fact, WorkItem(23309, "https://github.com/dotnet/roslyn/issues/23309")] public void TestFieldReferenceAnalyzer_InAttributes() { string source = @" using System; [assembly: MyAttribute(C.FieldForAssembly)] [module: MyAttribute(C.FieldForModule)] internal class MyAttribute : Attribute { public MyAttribute(int f) { } } internal interface MyInterface { event EventHandler MyEvent; } [MyAttribute(FieldForClass)] internal class C : MyInterface { internal const int FieldForClass = 1, FieldForStruct = 2, FieldForInterface = 3, FieldForField = 4, FieldForMethod = 5, FieldForEnum = 6, FieldForEnumMember = 7, FieldForDelegate = 8, FieldForEventField = 9, FieldForEvent = 10, FieldForAddHandler = 11, FieldForRemoveHandler = 12, FieldForProperty = 13, FieldForPropertyGetter = 14, FieldForPropertySetter = 15, FieldForIndexer = 16, FieldForIndexerGetter = 17, FieldForIndexerSetter = 18, FieldForExpressionBodiedMethod = 19, FieldForExpressionBodiedProperty = 20, FieldForMethodParameter = 21, FieldForDelegateParameter = 22, FieldForIndexerParameter = 23, FieldForMethodTypeParameter = 24, FieldForTypeTypeParameter = 25, FieldForDelegateTypeParameter = 26, FieldForMethodReturnType = 27, FieldForAssembly = 28, FieldForModule = 29, FieldForPropertyInitSetter = 30; [MyAttribute(FieldForStruct)] private struct S<[MyAttribute(FieldForTypeTypeParameter)] T> { } [MyAttribute(FieldForInterface)] private interface I { } [MyAttribute(FieldForField)] private int field2 = 0, field3 = 0; [return: MyAttribute(FieldForMethodReturnType)] [MyAttribute(FieldForMethod)] private void M1<[MyAttribute(FieldForMethodTypeParameter)]T>([MyAttribute(FieldForMethodParameter)]int p1) { } [MyAttribute(FieldForEnum)] private enum E { [MyAttribute(FieldForEnumMember)] F = 0 } [MyAttribute(FieldForDelegate)] public delegate void Delegate<[MyAttribute(FieldForDelegateTypeParameter)]T>([MyAttribute(FieldForDelegateParameter)]int p1); [MyAttribute(FieldForEventField)] public event Delegate<int> MyEvent; [MyAttribute(FieldForEvent)] event EventHandler MyInterface.MyEvent { [MyAttribute(FieldForAddHandler)] add { } [MyAttribute(FieldForRemoveHandler)] remove { } } [MyAttribute(FieldForProperty)] private int P1 { [MyAttribute(FieldForPropertyGetter)] get; [MyAttribute(FieldForPropertySetter)] set; } [MyAttribute(FieldForIndexer)] private int this[[MyAttribute(FieldForIndexerParameter)]int index] { [MyAttribute(FieldForIndexerGetter)] get { return 0; } [MyAttribute(FieldForIndexerSetter)] set { } } [MyAttribute(FieldForExpressionBodiedMethod)] private int M2 => 0; [MyAttribute(FieldForExpressionBodiedProperty)] private int P2 => 0; private int P3 { [MyAttribute(FieldForPropertyInitSetter)] init { } } } "; var compilation = CreateCompilationWithMscorlib45(new[] { source, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics( // (51,32): warning CS0067: The event 'C.MyEvent' is never used // public event Delegate<int> MyEvent; Diagnostic(ErrorCode.WRN_UnreferencedEvent, "MyEvent").WithArguments("C.MyEvent").WithLocation(51, 32), // (34,17): warning CS0414: The field 'C.field2' is assigned but its value is never used // private int field2 = 0, field3 = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field2").WithArguments("C.field2").WithLocation(34, 17), // (34,29): warning CS0414: The field 'C.field3' is assigned but its value is never used // private int field2 = 0, field3 = 0; Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "field3").WithArguments("C.field3").WithLocation(34, 29)); // Test RegisterOperationBlockAction testFieldReferenceAnalyzer_InAttributes_Core(compilation, doOperationBlockAnalysis: true); // Test RegisterOperationAction testFieldReferenceAnalyzer_InAttributes_Core(compilation, doOperationBlockAnalysis: false); static void testFieldReferenceAnalyzer_InAttributes_Core(Compilation compilation, bool doOperationBlockAnalysis) { var analyzers = new DiagnosticAnalyzer[] { new FieldReferenceOperationAnalyzer(doOperationBlockAnalysis) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ID", "FieldForPropertyInitSetter").WithArguments("FieldForPropertyInitSetter", "30").WithLocation(92, 22), Diagnostic("ID", "FieldForClass").WithArguments("FieldForClass", "1").WithLocation(17, 14), Diagnostic("ID", "FieldForStruct").WithArguments("FieldForStruct", "2").WithLocation(27, 18), Diagnostic("ID", "FieldForInterface").WithArguments("FieldForInterface", "3").WithLocation(30, 18), Diagnostic("ID", "FieldForField").WithArguments("FieldForField", "4").WithLocation(33, 18), Diagnostic("ID", "FieldForField").WithArguments("FieldForField", "4").WithLocation(33, 18), Diagnostic("ID", "FieldForMethod").WithArguments("FieldForMethod", "5").WithLocation(37, 18), Diagnostic("ID", "FieldForEnum").WithArguments("FieldForEnum", "6").WithLocation(40, 18), Diagnostic("ID", "FieldForEnumMember").WithArguments("FieldForEnumMember", "7").WithLocation(43, 22), Diagnostic("ID", "FieldForDelegate").WithArguments("FieldForDelegate", "8").WithLocation(47, 18), Diagnostic("ID", "FieldForEventField").WithArguments("FieldForEventField", "9").WithLocation(50, 18), Diagnostic("ID", "FieldForEvent").WithArguments("FieldForEvent", "10").WithLocation(53, 18), Diagnostic("ID", "FieldForAddHandler").WithArguments("FieldForAddHandler", "11").WithLocation(56, 22), Diagnostic("ID", "FieldForRemoveHandler").WithArguments("FieldForRemoveHandler", "12").WithLocation(60, 22), Diagnostic("ID", "FieldForProperty").WithArguments("FieldForProperty", "13").WithLocation(66, 18), Diagnostic("ID", "FieldForPropertyGetter").WithArguments("FieldForPropertyGetter", "14").WithLocation(69, 22), Diagnostic("ID", "FieldForPropertySetter").WithArguments("FieldForPropertySetter", "15").WithLocation(71, 22), Diagnostic("ID", "FieldForIndexer").WithArguments("FieldForIndexer", "16").WithLocation(75, 18), Diagnostic("ID", "FieldForIndexerGetter").WithArguments("FieldForIndexerGetter", "17").WithLocation(78, 22), Diagnostic("ID", "FieldForIndexerSetter").WithArguments("FieldForIndexerSetter", "18").WithLocation(80, 22), Diagnostic("ID", "FieldForExpressionBodiedMethod").WithArguments("FieldForExpressionBodiedMethod", "19").WithLocation(84, 18), Diagnostic("ID", "FieldForExpressionBodiedProperty").WithArguments("FieldForExpressionBodiedProperty", "20").WithLocation(87, 18), Diagnostic("ID", "FieldForMethodParameter").WithArguments("FieldForMethodParameter", "21").WithLocation(38, 79), Diagnostic("ID", "FieldForDelegateParameter").WithArguments("FieldForDelegateParameter", "22").WithLocation(48, 95), Diagnostic("ID", "FieldForIndexerParameter").WithArguments("FieldForIndexerParameter", "23").WithLocation(76, 35), Diagnostic("ID", "FieldForMethodTypeParameter").WithArguments("FieldForMethodTypeParameter", "24").WithLocation(38, 34), Diagnostic("ID", "FieldForTypeTypeParameter").WithArguments("FieldForTypeTypeParameter", "25").WithLocation(28, 35), Diagnostic("ID", "FieldForDelegateTypeParameter").WithArguments("FieldForDelegateTypeParameter", "26").WithLocation(48, 48), Diagnostic("ID", "FieldForMethodReturnType").WithArguments("FieldForMethodReturnType", "27").WithLocation(36, 26), Diagnostic("ID", "C.FieldForAssembly").WithArguments("FieldForAssembly", "28").WithLocation(4, 24), Diagnostic("ID", "C.FieldForModule").WithArguments("FieldForModule", "29").WithLocation(5, 22)); } } [Fact, WorkItem(23309, "https://github.com/dotnet/roslyn/issues/23309")] public void TestFieldReferenceAnalyzer_InConstructorInitializer() { string source = @" internal class Base { protected Base(int i) { } } internal class Derived : Base { private const int Field = 0; public Derived() : base(Field) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); // Test RegisterOperationBlockAction TestFieldReferenceAnalyzer_InConstructorInitializer_Core(compilation, doOperationBlockAnalysis: true); // Test RegisterOperationAction TestFieldReferenceAnalyzer_InConstructorInitializer_Core(compilation, doOperationBlockAnalysis: false); } private static void TestFieldReferenceAnalyzer_InConstructorInitializer_Core(Compilation compilation, bool doOperationBlockAnalysis) { var analyzers = new DiagnosticAnalyzer[] { new FieldReferenceOperationAnalyzer(doOperationBlockAnalysis) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ID", "Field").WithArguments("Field", "0").WithLocation(11, 29)); } [Fact, WorkItem(26520, "https://github.com/dotnet/roslyn/issues/26520")] public void TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody() { string source = @" internal class C { public bool Flag; public C() => Flag = true; ~C() => Flag = false; }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); // Test RegisterOperationBlockAction TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody_Core(compilation, doOperationBlockAnalysis: true); // Test RegisterOperationAction TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody_Core(compilation, doOperationBlockAnalysis: false); } private static void TestFieldReferenceAnalyzer_InConstructorDestructorExpressionBody_Core(Compilation compilation, bool doOperationBlockAnalysis) { var analyzers = new DiagnosticAnalyzer[] { new FieldReferenceOperationAnalyzer(doOperationBlockAnalysis) }; compilation.VerifyAnalyzerDiagnostics(analyzers, null, null, Diagnostic("ID", "Flag").WithArguments("Flag", "").WithLocation(5, 19), Diagnostic("ID", "Flag").WithArguments("Flag", "").WithLocation(6, 13)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestMethodBodyOperationAnalyzer() { string source = @" internal class A { public void M() { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID", squiggledText: "public void M() { }").WithArguments("M").WithLocation(4, 5)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestMethodBodyOperationAnalyzer_WithParameterInitializers() { string source = @" internal class A { public void M(int p = 0) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID", squiggledText: "public void M(int p = 0) { }").WithArguments("M").WithLocation(4, 5)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestMethodBodyOperationAnalyzer_WithExpressionAndMethodBody() { string source = @" internal class A { public int M() { return 0; } => 0; }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics( // (4,5): error CS8057: Block bodies and expression bodies cannot both be provided. // public int M() { return 0; } => 0; Diagnostic(ErrorCode.ERR_BlockBodyAndExpressionBody, "public int M() { return 0; } => 0;").WithLocation(4, 5)); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID", squiggledText: "public int M() { return 0; } => 0;").WithArguments("M").WithLocation(4, 5)); } [Fact, WorkItem(25167, "https://github.com/dotnet/roslyn/issues/25167")] public void TestConstructorBodyOperationAnalyzer() { string source = @" internal class Base { protected Base(int i) { } } internal class Derived : Base { private const int Field = 0; public Derived() : base(Field) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new MethodOrConstructorBodyOperationAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: new[] { Diagnostic("ID", squiggledText: "protected Base(int i) { }").WithArguments(".ctor").WithLocation(4, 5), Diagnostic("ID", squiggledText: "public Derived() : base(Field) { }").WithArguments(".ctor").WithLocation(11, 5) }); } [CompilerTrait(CompilerFeature.IOperation, CompilerFeature.Dataflow)] [Fact] public void TestGetControlFlowGraphInOperationAnalyzers() { string source = @"class C { void M(int p = 0) { int x = 1 + 2; } }"; var compilation = CreateCompilationWithMscorlib45(source); compilation.VerifyDiagnostics( // (1,35): warning CS0219: The variable 'x' is assigned but its value is never used // class C { void M(int p = 0) { int x = 1 + 2; } } Diagnostic(ErrorCode.WRN_UnreferencedVarAssg, "x").WithArguments("x").WithLocation(1, 35)); var expectedFlowGraphs = new[] { // Method body @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Entering: {R1} .locals {R1} { Locals: [System.Int32 x] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'x = 1 + 2') Left: ILocalReferenceOperation: x (IsDeclaration: True) (OperationKind.LocalReference, Type: System.Int32, IsImplicit) (Syntax: 'x = 1 + 2') Right: IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32, Constant: 3) (Syntax: '1 + 2') Left: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2') Next (Regular) Block[B2] Leaving: {R1} } Block[B2] - Exit Predecessors: [B1] Statements (0)", // Parameter initializer @" Block[B0] - Entry Statements (0) Next (Regular) Block[B1] Block[B1] - Block Predecessors: [B0] Statements (1) ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: '= 0') Left: IParameterReferenceOperation: p (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: '= 0') Right: ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 0) (Syntax: '0') Next (Regular) Block[B2] Block[B2] - Exit Predecessors: [B1] Statements (0)" }; // Verify analyzer diagnostics and flow graphs for different kind of operation analyzers. var analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.Operation, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "0").WithArguments("Operation").WithLocation(1, 26), Diagnostic("ID", "1").WithArguments("Operation").WithLocation(1, 39), Diagnostic("ID", "2").WithArguments("Operation").WithLocation(1, 43) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.OperationInOperationBlockStart, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "0").WithArguments("OperationInOperationBlockStart").WithLocation(1, 26), Diagnostic("ID", "1").WithArguments("OperationInOperationBlockStart").WithLocation(1, 39), Diagnostic("ID", "2").WithArguments("OperationInOperationBlockStart").WithLocation(1, 43) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.OperationBlock, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "M").WithArguments("OperationBlock").WithLocation(1, 16) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); analyzer = new OperationAnalyzer(OperationAnalyzer.ActionKind.OperationBlockEnd, verifyGetControlFlowGraph: true); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { analyzer }, expected: new[] { Diagnostic("ID", "M").WithArguments("OperationBlockEnd").WithLocation(1, 16) }); verifyFlowGraphs(analyzer.GetControlFlowGraphs()); void verifyFlowGraphs(ImmutableArray<(ControlFlowGraph Graph, ISymbol AssociatedSymbol)> flowGraphs) { for (int i = 0; i < expectedFlowGraphs.Length; i++) { string expectedFlowGraph = expectedFlowGraphs[i]; (ControlFlowGraph actualFlowGraph, ISymbol associatedSymbol) = flowGraphs[i]; ControlFlowGraphVerifier.VerifyGraph(compilation, expectedFlowGraph, actualFlowGraph, associatedSymbol); } } } private static void TestSymbolStartAnalyzerCore(SymbolStartAnalyzer analyzer, params DiagnosticDescription[] diagnostics) { TestSymbolStartAnalyzerCore(new DiagnosticAnalyzer[] { analyzer }, diagnostics); } private static void TestSymbolStartAnalyzerCore(DiagnosticAnalyzer[] analyzers, params DiagnosticDescription[] diagnostics) { var source = @" #pragma warning disable CS0219 // unused local #pragma warning disable CS0067 // unused event class C1 { void M1() { int localInTypeInGlobalNamespace = 0; } } class C2 { class NestedType { void M2() { int localInNestedType = 0; } } } namespace N1 { } namespace N2 { namespace N3 { class C3 { void M3(int p) { int localInTypeInNamespace = 0; } void M4() { } } } } namespace N2.N3 { class C4 { public int f1 = 0; } } namespace N4 { class C5 { void M5() { } } class C6 { void M6() { } void M7() { } } } namespace N5 { partial class C7 { void M8() { } int P1 { get; set; } public event System.EventHandler e1; } partial class C7 { void M9() { } void M10() { } } } "; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); compilation.VerifyAnalyzerDiagnostics(analyzers, expected: diagnostics); } [Fact] public void TestSymbolStartAnalyzer_NamedType() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType), Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Namespace() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Namespace), Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Method() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Method), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Field() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Field), Diagnostic("SymbolStartRuleId").WithArguments("f1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Property() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Property), Diagnostic("SymbolStartRuleId").WithArguments("P1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Event() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Event), Diagnostic("SymbolStartRuleId").WithArguments("e1", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_Parameter() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Parameter)); } [Fact] public void TestSymbolStartAnalyzer_MultipleAnalyzers_NamespaceAndMethods() { var analyzer1 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Namespace, analyzerId: 1); var analyzer2 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Method, analyzerId: 2); TestSymbolStartAnalyzerCore(new DiagnosticAnalyzer[] { analyzer1, analyzer2 }, Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer2").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_MultipleAnalyzers_NamedTypeAndMethods() { var analyzer1 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType, analyzerId: 1); var analyzer2 = new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Method, analyzerId: 2); TestSymbolStartAnalyzerCore(new DiagnosticAnalyzer[] { analyzer1, analyzer2 }, Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer2").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_MultipleAnalyzers_AllSymbolKinds() { testCore("SymbolStartTopLevelRuleId", topLevel: true); testCore("SymbolStartRuleId", topLevel: false); void testCore(string ruleId, bool topLevel) { var symbolKinds = new[] { SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event, SymbolKind.Field, SymbolKind.Parameter }; var analyzers = new DiagnosticAnalyzer[symbolKinds.Length]; for (int i = 0; i < symbolKinds.Length; i++) { analyzers[i] = new SymbolStartAnalyzer(topLevel, symbolKinds[i], analyzerId: i + 1); } TestSymbolStartAnalyzerCore(analyzers, Diagnostic(ruleId).WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N1", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N2", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N3", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N4", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("N5", "Analyzer2").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M1", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M2", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M3", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M4", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M5", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M6", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M7", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M8", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M9", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("M10", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("get_P1", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("set_P1", "Analyzer3").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("P1", "Analyzer4").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("e1", "Analyzer5").WithLocation(1, 1), Diagnostic(ruleId).WithArguments("f1", "Analyzer6").WithLocation(1, 1)); } } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_Namespace() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.Namespace, OperationKind.VariableDeclarationGroup), Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("N3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_NamedType() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType, OperationKind.VariableDeclarationGroup), Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("NestedType", "M2", "int localInNestedType = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_Method() { TestSymbolStartAnalyzerCore(new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.Method, OperationKind.VariableDeclarationGroup), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M7", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M8", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M9", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("M10", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("get_P1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("set_P1", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M2", "M2", "int localInNestedType = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1)); } [Fact] public void TestSymbolStartAnalyzer_NestedOperationAction_Inside_AllSymbolKinds() { var symbolKinds = new[] { SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event, SymbolKind.Field, SymbolKind.Parameter }; var analyzers = new DiagnosticAnalyzer[symbolKinds.Length]; for (int i = 0; i < symbolKinds.Length; i++) { analyzers[i] = new SymbolStartAnalyzer(topLevelAction: false, symbolKinds[i], OperationKind.VariableDeclarationGroup, analyzerId: i + 1); } TestSymbolStartAnalyzerCore(analyzers, Diagnostic("SymbolStartRuleId").WithArguments("NestedType", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C1", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C2", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C3", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C4", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C5", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C6", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C7", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("NestedType", "M2", "int localInNestedType = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("C3", "M3", "int localInTypeInNamespace = 0;", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N1", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N2", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N3", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N4", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("N5", "Analyzer2").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("N3", "M3", "int localInTypeInNamespace = 0;", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M2", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M3", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M4", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M5", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M6", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M7", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M8", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M9", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("M10", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M1", "M1", "int localInTypeInGlobalNamespace = 0;", "Analyzer3").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M2", "M2", "int localInNestedType = 0;", "Analyzer3").WithLocation(1, 1), Diagnostic("OperationRuleId").WithArguments("M3", "M3", "int localInTypeInNamespace = 0;", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("P1", "Analyzer4").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("e1", "Analyzer5").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("f1", "Analyzer6").WithLocation(1, 1)); } [Fact] public void TestInitOnlyProperty() { string source1 = @" class C { int P1 { get; init; } int P2 { get; set; } }"; var compilation = CreateCompilation(new[] { source1, IsExternalInitTypeDefinition }, parseOptions: TestOptions.Regular9); compilation.VerifyDiagnostics(); var symbolKinds = new[] { SymbolKind.NamedType, SymbolKind.Namespace, SymbolKind.Method, SymbolKind.Property, SymbolKind.Event, SymbolKind.Field, SymbolKind.Parameter }; var analyzers = new DiagnosticAnalyzer[symbolKinds.Length]; for (int i = 0; i < symbolKinds.Length; i++) { analyzers[i] = new SymbolStartAnalyzer(topLevelAction: false, symbolKinds[i], OperationKind.VariableDeclarationGroup, analyzerId: i + 1); } var expected = new[] { Diagnostic("SymbolStartRuleId").WithArguments("get_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("IsExternalInit", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("P2", "Analyzer4").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("P1", "Analyzer4").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("get_P2", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P1", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("set_P2", "Analyzer3").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("C", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("CompilerServices", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("Runtime", "Analyzer2").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("System", "Analyzer2").WithLocation(1, 1) }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(32702, "https://github.com/dotnet/roslyn/issues/32702")] public void TestInvocationInPartialMethod() { string source1 = @" static partial class B { static partial void PartialMethod(); }"; string source2 = @" static partial class B { static partial void PartialMethod() { M(); } private static void M() { } }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2 }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new SymbolStartAnalyzer(topLevelAction: false, SymbolKind.NamedType, OperationKind.Invocation) }; var expected = new[] { Diagnostic("OperationRuleId").WithArguments("B", "PartialMethod", "M()", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartRuleId").WithArguments("B", "Analyzer1").WithLocation(1, 1) }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(32702, "https://github.com/dotnet/roslyn/issues/32702")] public void TestFieldReferenceInPartialMethod() { string source1 = @" static partial class B { static partial void PartialMethod(); }"; string source2 = @" static partial class B { static partial void PartialMethod() { var x = _field; } private static int _field = 0; }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2 }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.NamedType, OperationKind.FieldReference) }; var expected = new[] { Diagnostic("OperationRuleId").WithArguments("B", "PartialMethod", "_field", "Analyzer1").WithLocation(1, 1), Diagnostic("SymbolStartTopLevelRuleId").WithArguments("B", "Analyzer1").WithLocation(1, 1) }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: expected); } [Fact, WorkItem(922802, "https://dev.azure.com/devdiv/DevDiv/_workitems/edit/922802")] public async Task TestAnalysisScopeForGetAnalyzerSemanticDiagnosticsAsync() { string source1 = @" partial class B { private int _field1 = 1; }"; string source2 = @" partial class B { private int _field2 = 2; }"; string source3 = @" class C { private int _field3 = 3; }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2, source3 }); var tree1 = compilation.SyntaxTrees[0]; var semanticModel1 = compilation.GetSemanticModel(tree1); var analyzer1 = new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.Field, analyzerId: 1); var analyzer2 = new SymbolStartAnalyzer(topLevelAction: true, SymbolKind.Field, analyzerId: 2); var compilationWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1, analyzer2)); // Invoke "GetAnalyzerSemanticDiagnosticsAsync" for a single analyzer on a single tree and // ensure that the API respects the requested analysis scope: // 1. It should never force analyze the non-requested analyzer. // 2. It should only analyze the requested tree. If the requested tree has partial type declaration(s), // then it should also analyze additional trees with other partial declarations for partial types in the original tree, // but not other tree. var tree1SemanticDiagnostics = await compilationWithAnalyzers.GetAnalyzerSemanticDiagnosticsAsync(semanticModel1, filterSpan: null, ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1), CancellationToken.None); Assert.Equal(2, analyzer1.SymbolsStarted.Count); var sortedSymbolNames = analyzer1.SymbolsStarted.Select(s => s.Name).ToImmutableSortedSet(); Assert.Equal("_field1", sortedSymbolNames[0]); Assert.Equal("_field2", sortedSymbolNames[1]); Assert.Empty(analyzer2.SymbolsStarted); Assert.Empty(tree1SemanticDiagnostics); } [Fact] public void TestAnalyzerCallbacksWithSuppressedFile_SymbolAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic and callback with suppression on second file. var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider(tree2, (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress))); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostic even suppression on second file. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestAnalyzerCallbacksWithSuppressedFile_SymbolStartEndAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify same callbacks even with suppression on second file when using GeneratedCodeAnalysisFlags.Analyze. var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider(tree2, (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress)) ); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd, GeneratedCodeAnalysisFlags.Analyze); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic and callback with suppression on second file when not using GeneratedCodeAnalysisFlags.Analyze. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd, GeneratedCodeAnalysisFlags.None); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostics even with suppression on second file when not using GeneratedCodeAnalysisFlags.Analyze. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.SymbolStartEnd, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestAnalyzerCallbacksWithSuppressedFile_CompilationStartEndAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A, B").WithLocation(1, 1) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify same diagnostics and callbacks even with suppression on second file when using GeneratedCodeAnalysisFlags.Analyze. var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider(tree2, (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress)) ); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd, GeneratedCodeAnalysisFlags.Analyze); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A, B").WithLocation(1, 1) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic and callback with suppression on second file when not using GeneratedCodeAnalysisFlags.Analyze. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd, GeneratedCodeAnalysisFlags.None); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A").WithLocation(1, 1) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostics even with suppression on second file. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.CompilationStartEnd, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId).WithArguments("A, B").WithLocation(1, 1) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestAnalyzerCallbacksWithGloballySuppressedFile_SymbolAction() { var tree1 = Parse("partial class A { }"); var tree2 = Parse("partial class A { private class B { } }"); var compilation = CreateCompilationWithMscorlib45(new[] { tree1, tree2 }); compilation.VerifyDiagnostics(); // Verify analyzer diagnostics and callbacks without suppression. var namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify suppressed analyzer diagnostic for both files when specified globally var options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress))); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }); Assert.Equal("", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for non-configurable diagnostic even suppression on second file. namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol, configurable: false); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15), Diagnostic(NamedTypeAnalyzer.RuleId, "B").WithArguments("B").WithLocation(1, 33) }); Assert.Equal("A, B", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); // Verify analyzer diagnostics and callbacks for a single file when suppressed globally and un-suppressed for a single file options = TestOptions.DebugDll.WithSyntaxTreeOptionsProvider( new TestSyntaxTreeOptionsProvider((NamedTypeAnalyzer.RuleId, ReportDiagnostic.Suppress), (tree1, new[] { (NamedTypeAnalyzer.RuleId, ReportDiagnostic.Default) }))); compilation = CreateCompilation(new[] { tree1, tree2 }, options: options); compilation.VerifyDiagnostics(); namedTypeAnalyzer = new NamedTypeAnalyzer(NamedTypeAnalyzer.AnalysisKind.Symbol); compilation.VerifyAnalyzerDiagnostics(new DiagnosticAnalyzer[] { namedTypeAnalyzer }, expected: new[] { Diagnostic(NamedTypeAnalyzer.RuleId, "A").WithArguments("A").WithLocation(1, 15) }); Assert.Equal("A", namedTypeAnalyzer.GetSortedSymbolCallbacksString()); } [Fact] public void TestConcurrentAnalyzerActions() { var first = AnalyzerActions.Empty; var second = AnalyzerActions.Empty; first.EnableConcurrentExecution(); Assert.True(first.Concurrent); Assert.False(second.Concurrent); Assert.True(first.Append(second).Concurrent); Assert.True(first.Concurrent); Assert.False(second.Concurrent); Assert.True(second.Append(first).Concurrent); } [Fact, WorkItem(41402, "https://github.com/dotnet/roslyn/issues/41402")] public async Task TestRegisterOperationBlockAndOperationActionOnSameContext() { string source = @" internal class A { public void M() { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); // Verify analyzer execution from command line // 'VerifyAnalyzerDiagnostics' helper executes the analyzers on the entire compilation without any state-based analysis. var analyzers = new DiagnosticAnalyzer[] { new RegisterOperationBlockAndOperationActionAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID0001", "M").WithLocation(4, 17)); // Now verify analyzer execution for a single file. // 'GetAnalyzerSemanticDiagnosticsAsync' executes the analyzers on the given file with state-based analysis. var model = compilation.GetSemanticModel(tree); var compWithAnalyzers = new CompilationWithAnalyzers( compilation, analyzers.ToImmutableArray(), new AnalyzerOptions(ImmutableArray<AdditionalText>.Empty), CancellationToken.None); var diagnostics = await compWithAnalyzers.GetAnalyzerSemanticDiagnosticsAsync(model, filterSpan: null, CancellationToken.None); diagnostics.Verify(Diagnostic("ID0001", "M").WithLocation(4, 17)); } [Fact, WorkItem(26217, "https://github.com/dotnet/roslyn/issues/26217")] public void TestConstructorInitializerWithExpressionBody() { string source = @" class C { C() : base() => _ = 0; }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var analyzers = new DiagnosticAnalyzer[] { new RegisterOperationBlockAndOperationActionAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: Diagnostic("ID0001", "C").WithLocation(4, 5)); } [Fact, WorkItem(43106, "https://github.com/dotnet/roslyn/issues/43106")] public void TestConstructorInitializerWithoutBody() { string source = @" class B { // Haven't typed { } on the next line yet public B() : this(1) public B(int a) { } }"; var tree = CSharpSyntaxTree.ParseText(source); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics( // (5,12): error CS0501: 'B.B()' must declare a body because it is not marked abstract, extern, or partial // public B() : this(1) Diagnostic(ErrorCode.ERR_ConcreteMissingBody, "B").WithArguments("B.B()").WithLocation(5, 12), // (5,25): error CS1002: ; expected // public B() : this(1) Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(5, 25)); var analyzers = new DiagnosticAnalyzer[] { new RegisterOperationBlockAndOperationActionAnalyzer() }; compilation.VerifyAnalyzerDiagnostics(analyzers, expected: new[] { Diagnostic("ID0001", "B").WithLocation(5, 12), Diagnostic("ID0001", "B").WithLocation(7, 12) }); } [Theory, CombinatorialData] public async Task TestGetAnalysisResultAsync(bool syntax, bool singleAnalyzer) { string source1 = @" partial class B { private int _field1 = 1; }"; string source2 = @" partial class B { private int _field2 = 2; }"; string source3 = @" class C { private int _field3 = 3; }"; var compilation = CreateCompilationWithMscorlib45(new[] { source1, source2, source3 }); var tree1 = compilation.SyntaxTrees[0]; var field1 = tree1.GetRoot().DescendantNodes().OfType<FieldDeclarationSyntax>().Single().Declaration.Variables.Single().Identifier; var semanticModel1 = compilation.GetSemanticModel(tree1); var analyzer1 = new FieldAnalyzer("ID0001", syntax); var analyzer2 = new FieldAnalyzer("ID0002", syntax); var allAnalyzers = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1, analyzer2); var compilationWithAnalyzers = compilation.WithAnalyzers(allAnalyzers); // Invoke "GetAnalysisResultAsync" for a single analyzer on a single tree and // ensure that the API respects the requested analysis scope: // 1. It only reports diagnostics for the requested analyzer. // 2. It only reports diagnostics for the requested tree. var analyzersToQuery = singleAnalyzer ? ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1) : allAnalyzers; AnalysisResult analysisResult; if (singleAnalyzer) { analysisResult = syntax ? await compilationWithAnalyzers.GetAnalysisResultAsync(tree1, analyzersToQuery, CancellationToken.None) : await compilationWithAnalyzers.GetAnalysisResultAsync(semanticModel1, filterSpan: null, analyzersToQuery, CancellationToken.None); } else { analysisResult = syntax ? await compilationWithAnalyzers.GetAnalysisResultAsync(tree1, CancellationToken.None) : await compilationWithAnalyzers.GetAnalysisResultAsync(semanticModel1, filterSpan: null, CancellationToken.None); } var diagnosticsMap = syntax ? analysisResult.SyntaxDiagnostics : analysisResult.SemanticDiagnostics; var diagnostics = diagnosticsMap.TryGetValue(tree1, out var value) ? value : ImmutableDictionary<DiagnosticAnalyzer, ImmutableArray<Diagnostic>>.Empty; foreach (var analyzer in allAnalyzers) { if (analyzersToQuery.Contains(analyzer)) { Assert.True(diagnostics.ContainsKey(analyzer)); var diagnostic = Assert.Single(diagnostics[analyzer]); Assert.Equal(((FieldAnalyzer)analyzer).Descriptor.Id, diagnostic.Id); Assert.Equal(field1.GetLocation(), diagnostic.Location); } else { Assert.False(diagnostics.ContainsKey(analyzer)); } } } [Theory, CombinatorialData] public async Task TestAdditionalFileAnalyzer(bool registerFromInitialize) { var tree = CSharpSyntaxTree.ParseText(string.Empty); var compilation = CreateCompilation(new[] { tree }); compilation.VerifyDiagnostics(); AdditionalText additionalFile = new TestAdditionalText("Additional File Text"); var options = new AnalyzerOptions(ImmutableArray.Create(additionalFile)); var diagnosticSpan = new TextSpan(2, 2); var analyzer = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan); var analyzers = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer); var diagnostics = await compilation.WithAnalyzers(analyzers, options).GetAnalyzerDiagnosticsAsync(CancellationToken.None); verifyDiagnostics(diagnostics); var analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile, CancellationToken.None); verifyDiagnostics(analysisResult.GetAllDiagnostics()); verifyDiagnostics(analysisResult.AdditionalFileDiagnostics[additionalFile][analyzer]); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(CancellationToken.None); verifyDiagnostics(analysisResult.GetAllDiagnostics()); verifyDiagnostics(analysisResult.AdditionalFileDiagnostics[additionalFile][analyzer]); void verifyDiagnostics(ImmutableArray<Diagnostic> diagnostics) { var diagnostic = Assert.Single(diagnostics); Assert.Equal(analyzer.Descriptor.Id, diagnostic.Id); Assert.Equal(LocationKind.ExternalFile, diagnostic.Location.Kind); var location = (ExternalFileLocation)diagnostic.Location; Assert.Equal(additionalFile.Path, location.FilePath); Assert.Equal(diagnosticSpan, location.SourceSpan); } } [Theory, CombinatorialData] public async Task TestMultipleAdditionalFileAnalyzers(bool registerFromInitialize, bool additionalFilesHaveSamePaths, bool firstAdditionalFileHasNullPath) { var tree = CSharpSyntaxTree.ParseText(string.Empty); var compilation = CreateCompilationWithMscorlib45(new[] { tree }); compilation.VerifyDiagnostics(); var path1 = firstAdditionalFileHasNullPath ? null : @"c:\file.txt"; var path2 = additionalFilesHaveSamePaths ? path1 : @"file2.txt"; AdditionalText additionalFile1 = new TestAdditionalText("Additional File1 Text", path: path1); AdditionalText additionalFile2 = new TestAdditionalText("Additional File2 Text", path: path2); var additionalFiles = ImmutableArray.Create(additionalFile1, additionalFile2); var options = new AnalyzerOptions(additionalFiles); var diagnosticSpan = new TextSpan(2, 2); var analyzer1 = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan, id: "ID0001"); var analyzer2 = new AdditionalFileAnalyzer(registerFromInitialize, diagnosticSpan, id: "ID0002"); var analyzers = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1, analyzer2); var diagnostics = await compilation.WithAnalyzers(analyzers, options).GetAnalyzerDiagnosticsAsync(CancellationToken.None); verifyDiagnostics(diagnostics, analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths); var analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile1, CancellationToken.None); verifyAnalysisResult(analysisResult, analyzers, ImmutableArray.Create(additionalFile1), diagnosticSpan, additionalFilesHaveSamePaths); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile2, CancellationToken.None); verifyAnalysisResult(analysisResult, analyzers, ImmutableArray.Create(additionalFile2), diagnosticSpan, additionalFilesHaveSamePaths); var singleAnalyzerArray = ImmutableArray.Create<DiagnosticAnalyzer>(analyzer1); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile1, singleAnalyzerArray, CancellationToken.None); verifyAnalysisResult(analysisResult, singleAnalyzerArray, ImmutableArray.Create(additionalFile1), diagnosticSpan, additionalFilesHaveSamePaths); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(additionalFile2, singleAnalyzerArray, CancellationToken.None); verifyAnalysisResult(analysisResult, singleAnalyzerArray, ImmutableArray.Create(additionalFile2), diagnosticSpan, additionalFilesHaveSamePaths); analysisResult = await compilation.WithAnalyzers(analyzers, options).GetAnalysisResultAsync(CancellationToken.None); verifyDiagnostics(analysisResult.GetAllDiagnostics(), analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths); if (!additionalFilesHaveSamePaths) { verifyAnalysisResult(analysisResult, analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths, verifyGetAllDiagnostics: false); } return; static void verifyDiagnostics( ImmutableArray<Diagnostic> diagnostics, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<AdditionalText> additionalFiles, TextSpan diagnosticSpan, bool additionalFilesHaveSamePaths) { foreach (AdditionalFileAnalyzer analyzer in analyzers) { var fileIndex = 0; foreach (var additionalFile in additionalFiles) { var applicableDiagnostics = diagnostics.WhereAsArray( d => d.Id == analyzer.Descriptor.Id && PathUtilities.Comparer.Equals(d.Location.GetLineSpan().Path, additionalFile.Path)); if (additionalFile.Path == null) { Assert.Empty(applicableDiagnostics); continue; } var expectedCount = additionalFilesHaveSamePaths ? additionalFiles.Length : 1; Assert.Equal(expectedCount, applicableDiagnostics.Length); foreach (var diagnostic in applicableDiagnostics) { Assert.Equal(LocationKind.ExternalFile, diagnostic.Location.Kind); var location = (ExternalFileLocation)diagnostic.Location; Assert.Equal(diagnosticSpan, location.SourceSpan); } fileIndex++; if (!additionalFilesHaveSamePaths || fileIndex == additionalFiles.Length) { diagnostics = diagnostics.RemoveRange(applicableDiagnostics); } } } Assert.Empty(diagnostics); } static void verifyAnalysisResult( AnalysisResult analysisResult, ImmutableArray<DiagnosticAnalyzer> analyzers, ImmutableArray<AdditionalText> additionalFiles, TextSpan diagnosticSpan, bool additionalFilesHaveSamePaths, bool verifyGetAllDiagnostics = true) { if (verifyGetAllDiagnostics) { verifyDiagnostics(analysisResult.GetAllDiagnostics(), analyzers, additionalFiles, diagnosticSpan, additionalFilesHaveSamePaths); } foreach (var analyzer in analyzers) { var singleAnalyzerArray = ImmutableArray.Create(analyzer); foreach (var additionalFile in additionalFiles) { var reportedDiagnostics = getReportedDiagnostics(analysisResult, analyzer, additionalFile); verifyDiagnostics(reportedDiagnostics, singleAnalyzerArray, ImmutableArray.Create(additionalFile), diagnosticSpan, additionalFilesHaveSamePaths); } } return; static ImmutableArray<Diagnostic> getReportedDiagnostics(AnalysisResult analysisResult, DiagnosticAnalyzer analyzer, AdditionalText additionalFile) { if (analysisResult.AdditionalFileDiagnostics.TryGetValue(additionalFile, out var diagnosticsMap) && diagnosticsMap.TryGetValue(analyzer, out var diagnostics)) { return diagnostics; } return ImmutableArray<Diagnostic>.Empty; } } } [Fact] public void TestSemanticModelProvider() { var tree = CSharpSyntaxTree.ParseText(@"class C { }"); Compilation compilation = CreateCompilation(new[] { tree }); var semanticModelProvider = new MySemanticModelProvider(); compilation = compilation.WithSemanticModelProvider(semanticModelProvider); // Verify semantic model provider is used by Compilation.GetSemanticModel API var model = compilation.GetSemanticModel(tree); semanticModelProvider.VerifyCachedModel(tree, model); // Verify semantic model provider is used by CSharpCompilation.GetSemanticModel API model = ((CSharpCompilation)compilation).GetSemanticModel(tree, ignoreAccessibility: false); semanticModelProvider.VerifyCachedModel(tree, model); } private sealed class MySemanticModelProvider : SemanticModelProvider { private readonly ConcurrentDictionary<SyntaxTree, SemanticModel> _cache = new ConcurrentDictionary<SyntaxTree, SemanticModel>(); public override SemanticModel GetSemanticModel(SyntaxTree tree, Compilation compilation, bool ignoreAccessibility = false) { return _cache.GetOrAdd(tree, compilation.CreateSemanticModel(tree, ignoreAccessibility)); } public void VerifyCachedModel(SyntaxTree tree, SemanticModel model) { Assert.Same(model, _cache[tree]); } } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Workspaces/Remote/Core/IRemoteHostService.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Remote { internal interface IRemoteHostService { void InitializeGlobalState(int uiCultureLCID, int cultureLCID, CancellationToken cancellationToken); void InitializeTelemetrySession(int hostProcessId, string serializedSession, CancellationToken cancellationToken); /// <summary> /// This is only for debugging /// /// this lets remote side to set same logging options as VS side /// </summary> void SetLoggingFunctionIds(List<string> loggerTypes, List<string> functionIds, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Remote { internal interface IRemoteHostService { void InitializeGlobalState(int uiCultureLCID, int cultureLCID, CancellationToken cancellationToken); void InitializeTelemetrySession(int hostProcessId, string serializedSession, CancellationToken cancellationToken); /// <summary> /// This is only for debugging /// /// this lets remote side to set same logging options as VS side /// </summary> void SetLoggingFunctionIds(List<string> loggerTypes, List<string> functionIds, CancellationToken cancellationToken); } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Workspaces/Core/Portable/Storage/SQLite/Interop/SafeSqliteBlobHandle.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Runtime.InteropServices; using Microsoft.CodeAnalysis.Shared.Extensions; using SQLitePCL; namespace Microsoft.CodeAnalysis.SQLite.Interop { internal sealed class SafeSqliteBlobHandle : SafeHandle { private readonly sqlite3_blob? _wrapper; private readonly SafeHandleLease _lease; private readonly SafeHandleLease _sqliteLease; public SafeSqliteBlobHandle(SafeSqliteHandle sqliteHandle, sqlite3_blob? wrapper) : base(invalidHandleValue: IntPtr.Zero, ownsHandle: true) { _wrapper = wrapper; if (wrapper is not null) { _lease = wrapper.Lease(); SetHandle(wrapper.DangerousGetHandle()); } else { _lease = default; SetHandle(IntPtr.Zero); } _sqliteLease = sqliteHandle.Lease(); } public override bool IsInvalid => handle == IntPtr.Zero; public sqlite3_blob DangerousGetWrapper() => _wrapper!; protected override bool ReleaseHandle() { try { using var _ = _wrapper; _lease.Dispose(); SetHandle(IntPtr.Zero); return true; } finally { _sqliteLease.Dispose(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Runtime.InteropServices; using Microsoft.CodeAnalysis.Shared.Extensions; using SQLitePCL; namespace Microsoft.CodeAnalysis.SQLite.Interop { internal sealed class SafeSqliteBlobHandle : SafeHandle { private readonly sqlite3_blob? _wrapper; private readonly SafeHandleLease _lease; private readonly SafeHandleLease _sqliteLease; public SafeSqliteBlobHandle(SafeSqliteHandle sqliteHandle, sqlite3_blob? wrapper) : base(invalidHandleValue: IntPtr.Zero, ownsHandle: true) { _wrapper = wrapper; if (wrapper is not null) { _lease = wrapper.Lease(); SetHandle(wrapper.DangerousGetHandle()); } else { _lease = default; SetHandle(IntPtr.Zero); } _sqliteLease = sqliteHandle.Lease(); } public override bool IsInvalid => handle == IntPtr.Zero; public sqlite3_blob DangerousGetWrapper() => _wrapper!; protected override bool ReleaseHandle() { try { using var _ = _wrapper; _lease.Dispose(); SetHandle(IntPtr.Zero); return true; } finally { _sqliteLease.Dispose(); } } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/CSharp/Test/Emit/CodeGen/IndexAndRangeTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class IndexAndRangeTests : CSharpTestBase { private CompilationVerifier CompileAndVerifyWithIndexAndRange(string s, string expectedOutput = null) { var comp = CreateCompilationWithIndexAndRange( new[] { s, TestSources.GetSubArray, }, expectedOutput is null ? TestOptions.ReleaseDll : TestOptions.ReleaseExe); return CompileAndVerify(comp, expectedOutput: expectedOutput); } private static (SemanticModel model, List<ElementAccessExpressionSyntax> accesses) GetModelAndAccesses(CSharpCompilation comp) { var syntaxTree = comp.SyntaxTrees[0]; var root = syntaxTree.GetRoot(); var model = comp.GetSemanticModel(syntaxTree); return (model, root.DescendantNodes().OfType<ElementAccessExpressionSyntax>().ToList()); } private static void VerifyIndexCall(IMethodSymbol symbol, string methodName, string containingTypeName) { Assert.NotNull(symbol); Assert.Equal(methodName, symbol.Name); Assert.Equal(2, symbol.Parameters.Length); Assert.Equal(containingTypeName, symbol.ContainingType.Name); } [Fact] public void ExpressionTreePatternIndexAndRange() { var src = @" using System; using System.Collections.Generic; using System.Linq.Expressions; struct S { public int Length => 0; public S Slice(int start, int length) => default; } class Program { static void Main() { Expression<Func<int[], int>> e = (int[] a) => a[new Index(0, true)]; // 1 Expression<Func<List<int>, int>> e2 = (List<int> a) => a[new Index(0, true)]; // 2 Expression<Func<int[], int[]>> e3 = (int[] a) => a[new Range(0, 1)]; // 3 Expression<Func<S, S>> e4 = (S s) => s[new Range(0, 1)]; // 4 } }"; var comp = CreateCompilationWithIndexAndRange( new[] { src, TestSources.GetSubArray, }); comp.VerifyEmitDiagnostics( // (16,55): error CS8790: An expression tree may not contain a pattern System.Index or System.Range indexer access // Expression<Func<int[], int>> e = (int[] a) => a[new Index(0, true)]; // 1 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, "a[new Index(0, true)]").WithLocation(16, 55), // (17,64): error CS8790: An expression tree may not contain a pattern System.Index or System.Range indexer access // Expression<Func<List<int>, int>> e2 = (List<int> a) => a[new Index(0, true)]; // 2 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, "a[new Index(0, true)]").WithLocation(17, 64), // (19,58): error CS8790: An expression tree may not contain a pattern System.Index or System.Range indexer access // Expression<Func<int[], int[]>> e3 = (int[] a) => a[new Range(0, 1)]; // 3 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, "a[new Range(0, 1)]").WithLocation(19, 58), // (20,46): error CS8790: An expression tree may not contain a pattern System.Index or System.Range indexer access // Expression<Func<S, S>> e4 = (S s) => s[new Range(0, 1)]; // 4 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, "s[new Range(0, 1)]").WithLocation(20, 46) ); } [Fact] public void ExpressionTreeFromEndIndexAndRange() { var src = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<Index>> e = () => ^1; Expression<Func<Range>> e2 = () => 1..2; } }"; var comp = CreateCompilationWithIndexAndRange(src); comp.VerifyEmitDiagnostics( // (10,43): error CS8791: An expression tree may not contain a from-end index ('^') expression. // Expression<Func<Index>> e = () => ^1; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsFromEndIndexExpression, "^1").WithLocation(10, 43), // (11,44): error CS8792: An expression tree may not contain a range ('..') expression. // Expression<Func<Range>> e2 = () => 1..2; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsRangeExpression, "1..2").WithLocation(11, 44) ); } [Fact] public void PatternIndexArray() { var src = @" class C { static int M1(int[] arr) => arr[^1]; static char M2(string s) => s[^1]; } "; var verifier = CompileAndVerifyWithIndexAndRange(src); // Code gen for the following two should look basically // the same, except that string will use Length/indexer // and array will use ldlen/ldelem, and string may have // more temporaries verifier.VerifyIL("C.M1", @" { // Code size 8 (0x8) .maxstack 3 IL_0000: ldarg.0 IL_0001: dup IL_0002: ldlen IL_0003: conv.i4 IL_0004: ldc.i4.1 IL_0005: sub IL_0006: ldelem.i4 IL_0007: ret }"); verifier.VerifyIL("C.M2", @" { // Code size 17 (0x11) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: dup IL_0002: callvirt ""int string.Length.get"" IL_0007: ldc.i4.1 IL_0008: sub IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: callvirt ""char string.this[int].get"" IL_0010: ret }"); } [Fact] [WorkItem(37789, "https://github.com/dotnet/roslyn/issues/37789")] public void PatternIndexAndRangeCompoundOperatorRefIndexer() { var src = @" using System; class C { static void Main(string[] args) { var span = new Span<byte>(new byte[2]); Console.WriteLine(span[1]); span[^1] += 1; Console.WriteLine(span[1]); } } "; var comp = CreateCompilationWithIndexAndRangeAndSpan(src, TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"0 1"); verifier.VerifyIL("C.Main", @" { // Code size 65 (0x41) .maxstack 3 .locals init (System.Span<byte> V_0, //span int V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.2 IL_0003: newarr ""byte"" IL_0008: call ""System.Span<byte>..ctor(byte[])"" IL_000d: ldloca.s V_0 IL_000f: ldc.i4.1 IL_0010: call ""ref byte System.Span<byte>.this[int].get"" IL_0015: ldind.u1 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: ldloca.s V_0 IL_001d: dup IL_001e: call ""int System.Span<byte>.Length.get"" IL_0023: ldc.i4.1 IL_0024: sub IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: call ""ref byte System.Span<byte>.this[int].get"" IL_002c: dup IL_002d: ldind.u1 IL_002e: ldc.i4.1 IL_002f: add IL_0030: conv.u1 IL_0031: stind.i1 IL_0032: ldloca.s V_0 IL_0034: ldc.i4.1 IL_0035: call ""ref byte System.Span<byte>.this[int].get"" IL_003a: ldind.u1 IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret }"); } [Fact] [WorkItem(37789, "https://github.com/dotnet/roslyn/issues/37789")] public void PatternIndexCompoundOperator() { var src = @" using System; struct S { private readonly int[] _array; private int _counter; public S(int[] a) { _array = a; _counter = 0; } public int Length { get { Console.WriteLine(""Length "" + _counter++); return _array.Length; } } public int this[int index] { get { Console.WriteLine(""Get "" + _counter++); return _array[index]; } set { Console.WriteLine(""Set "" + _counter++); _array[index] = value; } } } class C { static void Main(string[] args) { var array = new int[2]; Console.WriteLine(array[1]); var s = new S(array); s[^1] += 5; Console.WriteLine(array[1]); } } "; var comp = CreateCompilationWithIndexAndRangeAndSpan(src, TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"0 Length 0 Get 1 Set 2 5"); verifier.VerifyIL("C.Main", @" { // Code size 65 (0x41) .maxstack 4 .locals init (int[] V_0, //array S V_1, //s S& V_2, S& V_3, int V_4) IL_0000: ldc.i4.2 IL_0001: newarr ""int"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: ldelem.i4 IL_000a: call ""void System.Console.WriteLine(int)"" IL_000f: ldloca.s V_1 IL_0011: ldloc.0 IL_0012: call ""S..ctor(int[])"" IL_0017: ldloca.s V_1 IL_0019: stloc.2 IL_001a: ldloc.2 IL_001b: call ""int S.Length.get"" IL_0020: ldc.i4.1 IL_0021: sub IL_0022: ldloc.2 IL_0023: stloc.3 IL_0024: stloc.s V_4 IL_0026: ldloc.3 IL_0027: ldloc.s V_4 IL_0029: ldloc.3 IL_002a: ldloc.s V_4 IL_002c: call ""int S.this[int].get"" IL_0031: ldc.i4.5 IL_0032: add IL_0033: call ""void S.this[int].set"" IL_0038: ldloc.0 IL_0039: ldc.i4.1 IL_003a: ldelem.i4 IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret }"); } [Fact] [WorkItem(37789, "https://github.com/dotnet/roslyn/issues/37789")] public void PatternRangeCompoundOperator() { var src = @" using System; struct S { private readonly int[] _array; private int _counter; public S(int[] a) { _array = a; _counter = 0; } public int Length { get { Console.WriteLine(""Length "" + _counter++); return _array.Length; } } public ref int Slice(int start, int length) { Console.WriteLine(""Slice "" + _counter++); return ref _array[start]; } } class C { static void Main(string[] args) { var array = new int[2]; Console.WriteLine(array[1]); var s = new S(array); s[1..] += 5; Console.WriteLine(array[1]); } } "; var comp = CreateCompilationWithIndexAndRangeAndSpan(src, TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"0 Length 0 Slice 1 5"); verifier.VerifyIL("C.Main", @" { // Code size 57 (0x39) .maxstack 3 .locals init (int[] V_0, //array S V_1, int V_2, int V_3) IL_0000: ldc.i4.2 IL_0001: newarr ""int"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: ldelem.i4 IL_000a: call ""void System.Console.WriteLine(int)"" IL_000f: ldloc.0 IL_0010: newobj ""S..ctor(int[])"" IL_0015: stloc.1 IL_0016: ldloca.s V_1 IL_0018: call ""int S.Length.get"" IL_001d: ldc.i4.1 IL_001e: stloc.2 IL_001f: ldloc.2 IL_0020: sub IL_0021: stloc.3 IL_0022: ldloca.s V_1 IL_0024: ldloc.2 IL_0025: ldloc.3 IL_0026: call ""ref int S.Slice(int, int)"" IL_002b: dup IL_002c: ldind.i4 IL_002d: ldc.i4.5 IL_002e: add IL_002f: stind.i4 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldelem.i4 IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret }"); } [Fact] [WorkItem(37789, "https://github.com/dotnet/roslyn/issues/37789")] public void PatternindexNullableCoalescingAssignmentClass() { var src = @" using System; struct S { private readonly string[] _array; private int _counter; public S(string[] a) { _array = a; _counter = 0; } public int Length { get { Console.WriteLine(""Length "" + _counter++); return _array.Length; } } public string this[int index] { get { Console.WriteLine(""Get "" + _counter++); return _array[index]; } set { Console.WriteLine(""Set "" + _counter++); _array[index] = value; } } } class C { static void Main(string[] args) { var array = new string[2]; array[0] = ""abc""; Console.WriteLine(array[1] is null); var s = new S(array); s[^1] ??= s[^2]; s[^1] ??= s[^2]; Console.WriteLine(s[^1] ??= ""def""); Console.WriteLine(array[1]); } }"; var comp = CreateCompilationWithIndex(src, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @" True Length 0 Get 1 Length 2 Get 3 Set 4 Length 5 Get 6 Length 7 Get 8 abc abc"); verifier.VerifyIL("C.Main", @" { // Code size 203 (0xcb) .maxstack 5 .locals init (string[] V_0, //array S V_1, //s S& V_2, S& V_3, int V_4, string V_5, int V_6) IL_0000: ldc.i4.2 IL_0001: newarr ""string"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ldstr ""abc"" IL_000e: stelem.ref IL_000f: ldloc.0 IL_0010: ldc.i4.1 IL_0011: ldelem.ref IL_0012: ldnull IL_0013: ceq IL_0015: call ""void System.Console.WriteLine(bool)"" IL_001a: ldloca.s V_1 IL_001c: ldloc.0 IL_001d: call ""S..ctor(string[])"" IL_0022: ldloca.s V_1 IL_0024: stloc.2 IL_0025: ldloc.2 IL_0026: call ""int S.Length.get"" IL_002b: ldc.i4.1 IL_002c: sub IL_002d: ldloc.2 IL_002e: stloc.3 IL_002f: stloc.s V_4 IL_0031: ldloc.3 IL_0032: ldloc.s V_4 IL_0034: call ""string S.this[int].get"" IL_0039: brtrue.s IL_0059 IL_003b: ldloc.3 IL_003c: ldloc.s V_4 IL_003e: ldloca.s V_1 IL_0040: dup IL_0041: call ""int S.Length.get"" IL_0046: ldc.i4.2 IL_0047: sub IL_0048: stloc.s V_6 IL_004a: ldloc.s V_6 IL_004c: call ""string S.this[int].get"" IL_0051: dup IL_0052: stloc.s V_5 IL_0054: call ""void S.this[int].set"" IL_0059: ldloca.s V_1 IL_005b: stloc.3 IL_005c: ldloc.3 IL_005d: call ""int S.Length.get"" IL_0062: ldc.i4.1 IL_0063: sub IL_0064: ldloc.3 IL_0065: stloc.2 IL_0066: stloc.s V_4 IL_0068: ldloc.2 IL_0069: ldloc.s V_4 IL_006b: call ""string S.this[int].get"" IL_0070: brtrue.s IL_0090 IL_0072: ldloc.2 IL_0073: ldloc.s V_4 IL_0075: ldloca.s V_1 IL_0077: dup IL_0078: call ""int S.Length.get"" IL_007d: ldc.i4.2 IL_007e: sub IL_007f: stloc.s V_6 IL_0081: ldloc.s V_6 IL_0083: call ""string S.this[int].get"" IL_0088: dup IL_0089: stloc.s V_5 IL_008b: call ""void S.this[int].set"" IL_0090: ldloca.s V_1 IL_0092: stloc.2 IL_0093: ldloc.2 IL_0094: call ""int S.Length.get"" IL_0099: ldc.i4.1 IL_009a: sub IL_009b: ldloc.2 IL_009c: stloc.3 IL_009d: stloc.s V_4 IL_009f: ldloc.3 IL_00a0: ldloc.s V_4 IL_00a2: call ""string S.this[int].get"" IL_00a7: dup IL_00a8: brtrue.s IL_00bd IL_00aa: pop IL_00ab: ldloc.3 IL_00ac: ldloc.s V_4 IL_00ae: ldstr ""def"" IL_00b3: dup IL_00b4: stloc.s V_5 IL_00b6: call ""void S.this[int].set"" IL_00bb: ldloc.s V_5 IL_00bd: call ""void System.Console.WriteLine(string)"" IL_00c2: ldloc.0 IL_00c3: ldc.i4.1 IL_00c4: ldelem.ref IL_00c5: call ""void System.Console.WriteLine(string)"" IL_00ca: ret }"); } [Fact] [WorkItem(37789, "https://github.com/dotnet/roslyn/issues/37789")] public void PatternindexNullableCoalescingAssignmentStruct() { var src = @" using System; struct S { private readonly int?[] _array; private int _counter; public S(int?[] a) { _array = a; _counter = 0; } public int Length { get { Console.WriteLine(""Length "" + _counter++); return _array.Length; } } public int? this[int index] { get { Console.WriteLine(""Get "" + _counter++); return _array[index]; } set { Console.WriteLine(""Set "" + _counter++); _array[index] = value; } } } class C { static void Main(string[] args) { var array = new int?[2]; array[0] = 1; Console.WriteLine(array[1] is null); var s = new S(array); s[^1] ??= s[^2]; s[^1] ??= s[^2]; Console.WriteLine(s[^1] ??= 0); Console.WriteLine(array[1]); } }"; var comp = CreateCompilationWithIndex(src, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @" True Length 0 Get 1 Length 2 Get 3 Set 4 Length 5 Get 6 Length 7 Get 8 1 1"); verifier.VerifyIL("C.Main", @" { // Code size 279 (0x117) .maxstack 5 .locals init (int?[] V_0, //array S V_1, //s int? V_2, S& V_3, S& V_4, int V_5, int? V_6, int V_7) IL_0000: ldc.i4.2 IL_0001: newarr ""int?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: newobj ""int?..ctor(int)"" IL_000f: stelem ""int?"" IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem ""int?"" IL_001b: stloc.2 IL_001c: ldloca.s V_2 IL_001e: call ""bool int?.HasValue.get"" IL_0023: ldc.i4.0 IL_0024: ceq IL_0026: call ""void System.Console.WriteLine(bool)"" IL_002b: ldloca.s V_1 IL_002d: ldloc.0 IL_002e: call ""S..ctor(int?[])"" IL_0033: ldloca.s V_1 IL_0035: stloc.3 IL_0036: ldloc.3 IL_0037: call ""int S.Length.get"" IL_003c: ldc.i4.1 IL_003d: sub IL_003e: ldloc.3 IL_003f: stloc.s V_4 IL_0041: stloc.s V_5 IL_0043: ldloc.s V_4 IL_0045: ldloc.s V_5 IL_0047: call ""int? S.this[int].get"" IL_004c: stloc.2 IL_004d: ldloca.s V_2 IL_004f: call ""bool int?.HasValue.get"" IL_0054: brtrue.s IL_0075 IL_0056: ldloc.s V_4 IL_0058: ldloc.s V_5 IL_005a: ldloca.s V_1 IL_005c: dup IL_005d: call ""int S.Length.get"" IL_0062: ldc.i4.2 IL_0063: sub IL_0064: stloc.s V_7 IL_0066: ldloc.s V_7 IL_0068: call ""int? S.this[int].get"" IL_006d: dup IL_006e: stloc.s V_6 IL_0070: call ""void S.this[int].set"" IL_0075: ldloca.s V_1 IL_0077: stloc.s V_4 IL_0079: ldloc.s V_4 IL_007b: call ""int S.Length.get"" IL_0080: ldc.i4.1 IL_0081: sub IL_0082: ldloc.s V_4 IL_0084: stloc.3 IL_0085: stloc.s V_5 IL_0087: ldloc.3 IL_0088: ldloc.s V_5 IL_008a: call ""int? S.this[int].get"" IL_008f: stloc.2 IL_0090: ldloca.s V_2 IL_0092: call ""bool int?.HasValue.get"" IL_0097: brtrue.s IL_00b7 IL_0099: ldloc.3 IL_009a: ldloc.s V_5 IL_009c: ldloca.s V_1 IL_009e: dup IL_009f: call ""int S.Length.get"" IL_00a4: ldc.i4.2 IL_00a5: sub IL_00a6: stloc.s V_7 IL_00a8: ldloc.s V_7 IL_00aa: call ""int? S.this[int].get"" IL_00af: dup IL_00b0: stloc.s V_6 IL_00b2: call ""void S.this[int].set"" IL_00b7: ldloca.s V_1 IL_00b9: stloc.3 IL_00ba: ldloc.3 IL_00bb: call ""int S.Length.get"" IL_00c0: ldc.i4.1 IL_00c1: sub IL_00c2: ldloc.3 IL_00c3: stloc.s V_4 IL_00c5: stloc.s V_5 IL_00c7: ldloc.s V_4 IL_00c9: ldloc.s V_5 IL_00cb: call ""int? S.this[int].get"" IL_00d0: stloc.2 IL_00d1: ldloca.s V_2 IL_00d3: call ""int int?.GetValueOrDefault()"" IL_00d8: stloc.s V_7 IL_00da: ldloca.s V_2 IL_00dc: call ""bool int?.HasValue.get"" IL_00e1: brtrue.s IL_00fe IL_00e3: ldc.i4.0 IL_00e4: stloc.s V_7 IL_00e6: ldloc.s V_4 IL_00e8: ldloc.s V_5 IL_00ea: ldloca.s V_6 IL_00ec: ldloc.s V_7 IL_00ee: call ""int?..ctor(int)"" IL_00f3: ldloc.s V_6 IL_00f5: call ""void S.this[int].set"" IL_00fa: ldloc.s V_7 IL_00fc: br.s IL_0100 IL_00fe: ldloc.s V_7 IL_0100: call ""void System.Console.WriteLine(int)"" IL_0105: ldloc.0 IL_0106: ldc.i4.1 IL_0107: ldelem ""int?"" IL_010c: box ""int?"" IL_0111: call ""void System.Console.WriteLine(object)"" IL_0116: ret }"); } [Fact] public void StringAndSpanPatternRangeOpenEnd() { var src = @" using System; class C { public static void Main() { string s = ""abcd""; Console.WriteLine(s[..]); ReadOnlySpan<char> span = s; foreach (var c in span[..]) { Console.Write(c); } } }"; var comp = CreateCompilationWithIndexAndRangeAndSpan(src, TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @" abcd abcd"); verifier.VerifyIL("C.Main", @" { // Code size 86 (0x56) .maxstack 4 .locals init (int V_0, System.ReadOnlySpan<char> V_1, System.ReadOnlySpan<char> V_2, int V_3) IL_0000: ldstr ""abcd"" IL_0005: dup IL_0006: dup IL_0007: callvirt ""int string.Length.get"" IL_000c: ldc.i4.0 IL_000d: sub IL_000e: stloc.0 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: callvirt ""string string.Substring(int, int)"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(string)"" IL_0020: stloc.2 IL_0021: ldloca.s V_2 IL_0023: call ""int System.ReadOnlySpan<char>.Length.get"" IL_0028: ldc.i4.0 IL_0029: sub IL_002a: stloc.3 IL_002b: ldloca.s V_2 IL_002d: ldc.i4.0 IL_002e: ldloc.3 IL_002f: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.Slice(int, int)"" IL_0034: stloc.1 IL_0035: ldc.i4.0 IL_0036: stloc.0 IL_0037: br.s IL_004b IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: call ""ref readonly char System.ReadOnlySpan<char>.this[int].get"" IL_0041: ldind.u2 IL_0042: call ""void System.Console.Write(char)"" IL_0047: ldloc.0 IL_0048: ldc.i4.1 IL_0049: add IL_004a: stloc.0 IL_004b: ldloc.0 IL_004c: ldloca.s V_1 IL_004e: call ""int System.ReadOnlySpan<char>.Length.get"" IL_0053: blt.s IL_0039 IL_0055: ret }"); var (model, elementAccesses) = GetModelAndAccesses(comp); var info = model.GetSymbolInfo(elementAccesses[0]); var substringCall = (IMethodSymbol)info.Symbol; info = model.GetSymbolInfo(elementAccesses[1]); var sliceCall = (IMethodSymbol)info.Symbol; VerifyIndexCall(substringCall, "Substring", "String"); VerifyIndexCall(sliceCall, "Slice", "ReadOnlySpan"); } [Fact] public void SpanTaskReturn() { var src = @" using System; using System.Threading.Tasks; class C { static void Throws(Action a) { try { a(); } catch { Console.WriteLine(""throws""); } } public static void Main() { string s = ""abcd""; Throws(() => { var span = new Span<char>(s.ToCharArray())[0..10]; }); } }"; var comp = CreateCompilationWithIndexAndRangeAndSpan(src, TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "throws"); var (model, accesses) = GetModelAndAccesses(comp); VerifyIndexCall((IMethodSymbol)model.GetSymbolInfo(accesses[0]).Symbol, "Slice", "Span"); } [Fact] public void PatternIndexSetter() { var src = @" using System; struct S { public int F; public int Length => 1; public int this[int i] { get => F; set { F = value; } } } class C { static void Main() { S s = new S(); s.F = 0; Console.WriteLine(s[^1]); s[^1] = 2; Console.WriteLine(s[^1]); Console.WriteLine(s.F); } }"; var comp = CreateCompilationWithIndexAndRange(src, TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"0 2 2"); verifier.VerifyIL("C.Main", @" { // Code size 90 (0x5a) .maxstack 3 .locals init (S V_0, //s int V_1) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.0 IL_000b: stfld ""int S.F"" IL_0010: ldloca.s V_0 IL_0012: dup IL_0013: call ""int S.Length.get"" IL_0018: ldc.i4.1 IL_0019: sub IL_001a: stloc.1 IL_001b: ldloc.1 IL_001c: call ""int S.this[int].get"" IL_0021: call ""void System.Console.WriteLine(int)"" IL_0026: ldloca.s V_0 IL_0028: dup IL_0029: call ""int S.Length.get"" IL_002e: ldc.i4.1 IL_002f: sub IL_0030: stloc.1 IL_0031: ldloc.1 IL_0032: ldc.i4.2 IL_0033: call ""void S.this[int].set"" IL_0038: ldloca.s V_0 IL_003a: dup IL_003b: call ""int S.Length.get"" IL_0040: ldc.i4.1 IL_0041: sub IL_0042: stloc.1 IL_0043: ldloc.1 IL_0044: call ""int S.this[int].get"" IL_0049: call ""void System.Console.WriteLine(int)"" IL_004e: ldloc.0 IL_004f: ldfld ""int S.F"" IL_0054: call ""void System.Console.WriteLine(int)"" IL_0059: ret }"); var (model, accesses) = GetModelAndAccesses(comp); foreach (var access in accesses) { var info = model.GetSymbolInfo(access); var property = (IPropertySymbol)info.Symbol; Assert.NotNull(property); Assert.True(property.IsIndexer); Assert.Equal(SpecialType.System_Int32, property.Parameters[0].Type.SpecialType); Assert.Equal("S", property.ContainingType.Name); } } [Fact] public void PatternIndexerRefReturn() { var comp = CreateCompilationWithIndexAndRangeAndSpan(@" using System; class C { static void Main() { Span<int> s = new int[] { 2, 4, 5, 6 }; Console.WriteLine(s[^2]); ref int x = ref s[^2]; Console.WriteLine(x); s[^2] = 9; Console.WriteLine(s[^2]); Console.WriteLine(x); } }", TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"5 5 9 9"); verifier.VerifyIL("C.Main", @" { // Code size 120 (0x78) .maxstack 4 .locals init (System.Span<int> V_0, //s int V_1, int V_2) IL_0000: ldc.i4.4 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=16 <PrivateImplementationDetails>.B35A10C764778866E34111165FC69660C6171DF0CB0141E39FA0217EF7A97646"" IL_000c: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0011: call ""System.Span<int> System.Span<int>.op_Implicit(int[])"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: dup IL_001a: call ""int System.Span<int>.Length.get"" IL_001f: ldc.i4.2 IL_0020: sub IL_0021: stloc.1 IL_0022: ldloc.1 IL_0023: call ""ref int System.Span<int>.this[int].get"" IL_0028: ldind.i4 IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: ldloca.s V_0 IL_0030: dup IL_0031: call ""int System.Span<int>.Length.get"" IL_0036: ldc.i4.2 IL_0037: sub IL_0038: stloc.1 IL_0039: ldloc.1 IL_003a: call ""ref int System.Span<int>.this[int].get"" IL_003f: dup IL_0040: ldind.i4 IL_0041: call ""void System.Console.WriteLine(int)"" IL_0046: ldloca.s V_0 IL_0048: dup IL_0049: call ""int System.Span<int>.Length.get"" IL_004e: ldc.i4.2 IL_004f: sub IL_0050: stloc.2 IL_0051: ldloc.2 IL_0052: call ""ref int System.Span<int>.this[int].get"" IL_0057: ldc.i4.s 9 IL_0059: stind.i4 IL_005a: ldloca.s V_0 IL_005c: dup IL_005d: call ""int System.Span<int>.Length.get"" IL_0062: ldc.i4.2 IL_0063: sub IL_0064: stloc.2 IL_0065: ldloc.2 IL_0066: call ""ref int System.Span<int>.this[int].get"" IL_006b: ldind.i4 IL_006c: call ""void System.Console.WriteLine(int)"" IL_0071: ldind.i4 IL_0072: call ""void System.Console.WriteLine(int)"" IL_0077: ret }"); } [Fact] public void PatternIndexAndRangeSpanChar() { var comp = CreateCompilationWithIndexAndRangeAndSpan(@" using System; class C { static void Main() { ReadOnlySpan<char> s = ""abcdefg""; Console.WriteLine(s[^2]); var index = ^1; Console.WriteLine(s[index]); s = s[^2..]; Console.WriteLine(s[0]); Console.WriteLine(s[1]); } }", TestOptions.ReleaseExe); ; var verifier = CompileAndVerify(comp, expectedOutput: @"f g f g"); verifier.VerifyIL(@"C.Main", @" { // Code size 129 (0x81) .maxstack 3 .locals init (System.ReadOnlySpan<char> V_0, //s System.Index V_1, //index int V_2, int V_3, System.ReadOnlySpan<char> V_4) IL_0000: ldstr ""abcdefg"" IL_0005: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_0 IL_000d: dup IL_000e: call ""int System.ReadOnlySpan<char>.Length.get"" IL_0013: ldc.i4.2 IL_0014: sub IL_0015: stloc.2 IL_0016: ldloc.2 IL_0017: call ""ref readonly char System.ReadOnlySpan<char>.this[int].get"" IL_001c: ldind.u2 IL_001d: call ""void System.Console.WriteLine(char)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: ldc.i4.1 IL_0026: call ""System.Index..ctor(int, bool)"" IL_002b: ldloca.s V_0 IL_002d: dup IL_002e: call ""int System.ReadOnlySpan<char>.Length.get"" IL_0033: stloc.2 IL_0034: ldloca.s V_1 IL_0036: ldloc.2 IL_0037: call ""int System.Index.GetOffset(int)"" IL_003c: stloc.3 IL_003d: ldloc.3 IL_003e: call ""ref readonly char System.ReadOnlySpan<char>.this[int].get"" IL_0043: ldind.u2 IL_0044: call ""void System.Console.WriteLine(char)"" IL_0049: ldloc.0 IL_004a: stloc.s V_4 IL_004c: ldloca.s V_4 IL_004e: call ""int System.ReadOnlySpan<char>.Length.get"" IL_0053: dup IL_0054: ldc.i4.2 IL_0055: sub IL_0056: stloc.3 IL_0057: ldloc.3 IL_0058: sub IL_0059: stloc.2 IL_005a: ldloca.s V_4 IL_005c: ldloc.3 IL_005d: ldloc.2 IL_005e: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.Slice(int, int)"" IL_0063: stloc.0 IL_0064: ldloca.s V_0 IL_0066: ldc.i4.0 IL_0067: call ""ref readonly char System.ReadOnlySpan<char>.this[int].get"" IL_006c: ldind.u2 IL_006d: call ""void System.Console.WriteLine(char)"" IL_0072: ldloca.s V_0 IL_0074: ldc.i4.1 IL_0075: call ""ref readonly char System.ReadOnlySpan<char>.this[int].get"" IL_007a: ldind.u2 IL_007b: call ""void System.Console.WriteLine(char)"" IL_0080: ret }"); } [Fact] public void PatternIndexAndRangeSpanInt() { var comp = CreateCompilationWithIndexAndRangeAndSpan(@" using System; class C { static void Main() { Span<int> s = new int[] { 2, 4, 5, 6 }; Console.WriteLine(s[^2]); var index = ^1; Console.WriteLine(s[index]); s = s[^2..]; Console.WriteLine(s[0]); Console.WriteLine(s[1]); } }", TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"5 6 5 6"); verifier.VerifyIL("C.Main", @" { // Code size 141 (0x8d) .maxstack 3 .locals init (System.Span<int> V_0, //s System.Index V_1, //index int V_2, int V_3, System.Span<int> V_4) IL_0000: ldc.i4.4 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=16 <PrivateImplementationDetails>.B35A10C764778866E34111165FC69660C6171DF0CB0141E39FA0217EF7A97646"" IL_000c: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0011: call ""System.Span<int> System.Span<int>.op_Implicit(int[])"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: dup IL_001a: call ""int System.Span<int>.Length.get"" IL_001f: ldc.i4.2 IL_0020: sub IL_0021: stloc.2 IL_0022: ldloc.2 IL_0023: call ""ref int System.Span<int>.this[int].get"" IL_0028: ldind.i4 IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: ldloca.s V_1 IL_0030: ldc.i4.1 IL_0031: ldc.i4.1 IL_0032: call ""System.Index..ctor(int, bool)"" IL_0037: ldloca.s V_0 IL_0039: dup IL_003a: call ""int System.Span<int>.Length.get"" IL_003f: stloc.2 IL_0040: ldloca.s V_1 IL_0042: ldloc.2 IL_0043: call ""int System.Index.GetOffset(int)"" IL_0048: stloc.3 IL_0049: ldloc.3 IL_004a: call ""ref int System.Span<int>.this[int].get"" IL_004f: ldind.i4 IL_0050: call ""void System.Console.WriteLine(int)"" IL_0055: ldloc.0 IL_0056: stloc.s V_4 IL_0058: ldloca.s V_4 IL_005a: call ""int System.Span<int>.Length.get"" IL_005f: dup IL_0060: ldc.i4.2 IL_0061: sub IL_0062: stloc.3 IL_0063: ldloc.3 IL_0064: sub IL_0065: stloc.2 IL_0066: ldloca.s V_4 IL_0068: ldloc.3 IL_0069: ldloc.2 IL_006a: call ""System.Span<int> System.Span<int>.Slice(int, int)"" IL_006f: stloc.0 IL_0070: ldloca.s V_0 IL_0072: ldc.i4.0 IL_0073: call ""ref int System.Span<int>.this[int].get"" IL_0078: ldind.i4 IL_0079: call ""void System.Console.WriteLine(int)"" IL_007e: ldloca.s V_0 IL_0080: ldc.i4.1 IL_0081: call ""ref int System.Span<int>.this[int].get"" IL_0086: ldind.i4 IL_0087: call ""void System.Console.WriteLine(int)"" IL_008c: ret }"); } [Fact] public void RealIndexersPreferredToPattern() { var src = @" using System; class C { public int Length => throw null; public int this[Index i, int j = 0] { get { Console.WriteLine(""Index""); return 0; } } public int this[int i] { get { Console.WriteLine(""int""); return 0; } } public int Slice(int i, int j) => throw null; public int this[Range r, int j = 0] { get { Console.WriteLine(""Range""); return 0; } } static void Main() { var c = new C(); _ = c[0]; _ = c[^0]; _ = c[0..]; } }"; var verifier = CompileAndVerifyWithIndexAndRange(src, expectedOutput: @" int Index Range"); } [Fact] public void PatternIndexList() { var src = @" using System; using System.Collections.Generic; class C { private static List<int> list = new List<int>() { 2, 4, 5, 6 }; static void Main() { Console.WriteLine(list[^2]); var index = ^1; Console.WriteLine(list[index]); } }"; var verifier = CompileAndVerifyWithIndexAndRange(src, expectedOutput: @"5 6"); verifier.VerifyIL("C.Main", @" { // Code size 67 (0x43) .maxstack 3 .locals init (System.Index V_0, //index int V_1, int V_2) IL_0000: ldsfld ""System.Collections.Generic.List<int> C.list"" IL_0005: dup IL_0006: callvirt ""int System.Collections.Generic.List<int>.Count.get"" IL_000b: ldc.i4.2 IL_000c: sub IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: callvirt ""int System.Collections.Generic.List<int>.this[int].get"" IL_0014: call ""void System.Console.WriteLine(int)"" IL_0019: ldloca.s V_0 IL_001b: ldc.i4.1 IL_001c: ldc.i4.1 IL_001d: call ""System.Index..ctor(int, bool)"" IL_0022: ldsfld ""System.Collections.Generic.List<int> C.list"" IL_0027: dup IL_0028: callvirt ""int System.Collections.Generic.List<int>.Count.get"" IL_002d: stloc.1 IL_002e: ldloca.s V_0 IL_0030: ldloc.1 IL_0031: call ""int System.Index.GetOffset(int)"" IL_0036: stloc.2 IL_0037: ldloc.2 IL_0038: callvirt ""int System.Collections.Generic.List<int>.this[int].get"" IL_003d: call ""void System.Console.WriteLine(int)"" IL_0042: ret }"); } [Theory] [InlineData("Length")] [InlineData("Count")] public void PatternRangeIndexers(string propertyName) { var src = @" using System; class C { private int[] _f = { 2, 4, 5, 6 }; public int " + propertyName + @" => _f.Length; public int[] Slice(int start, int length) => _f[start..length]; static void Main() { var c = new C(); foreach (var x in c[1..]) { Console.WriteLine(x); } foreach (var x in c[..^2]) { Console.WriteLine(x); } } }"; var verifier = CompileAndVerifyWithIndexAndRange(src, @" 4 5 2 4"); verifier.VerifyIL("C.Main", @" { // Code size 95 (0x5f) .maxstack 3 .locals init (C V_0, //c int[] V_1, int V_2, int V_3, int V_4) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: dup IL_0008: callvirt ""int C." + propertyName + @".get"" IL_000d: ldc.i4.1 IL_000e: stloc.3 IL_000f: ldloc.3 IL_0010: sub IL_0011: stloc.s V_4 IL_0013: ldloc.3 IL_0014: ldloc.s V_4 IL_0016: callvirt ""int[] C.Slice(int, int)"" IL_001b: stloc.1 IL_001c: ldc.i4.0 IL_001d: stloc.2 IL_001e: br.s IL_002c IL_0020: ldloc.1 IL_0021: ldloc.2 IL_0022: ldelem.i4 IL_0023: call ""void System.Console.WriteLine(int)"" IL_0028: ldloc.2 IL_0029: ldc.i4.1 IL_002a: add IL_002b: stloc.2 IL_002c: ldloc.2 IL_002d: ldloc.1 IL_002e: ldlen IL_002f: conv.i4 IL_0030: blt.s IL_0020 IL_0032: ldloc.0 IL_0033: dup IL_0034: callvirt ""int C." + propertyName + @".get"" IL_0039: ldc.i4.2 IL_003a: sub IL_003b: ldc.i4.0 IL_003c: sub IL_003d: stloc.s V_4 IL_003f: ldc.i4.0 IL_0040: ldloc.s V_4 IL_0042: callvirt ""int[] C.Slice(int, int)"" IL_0047: stloc.1 IL_0048: ldc.i4.0 IL_0049: stloc.2 IL_004a: br.s IL_0058 IL_004c: ldloc.1 IL_004d: ldloc.2 IL_004e: ldelem.i4 IL_004f: call ""void System.Console.WriteLine(int)"" IL_0054: ldloc.2 IL_0055: ldc.i4.1 IL_0056: add IL_0057: stloc.2 IL_0058: ldloc.2 IL_0059: ldloc.1 IL_005a: ldlen IL_005b: conv.i4 IL_005c: blt.s IL_004c IL_005e: ret } "); } [Theory] [InlineData("Length")] [InlineData("Count")] public void PatternIndexIndexers(string propertyName) { var src = @" using System; class C { private int[] _f = { 2, 4, 5, 6 }; public int " + propertyName + @" => _f.Length; public int this[int x] => _f[x]; static void Main() { var c = new C(); Console.WriteLine(c[0]); Console.WriteLine(c[^1]); } }"; var verifier = CompileAndVerifyWithIndexAndRange(src, @" 2 6"); verifier.VerifyIL("C.Main", @" { // Code size 38 (0x26) .maxstack 3 .locals init (int V_0) IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldc.i4.0 IL_0007: callvirt ""int C.this[int].get"" IL_000c: call ""void System.Console.WriteLine(int)"" IL_0011: dup IL_0012: callvirt ""int C." + propertyName + @".get"" IL_0017: ldc.i4.1 IL_0018: sub IL_0019: stloc.0 IL_001a: ldloc.0 IL_001b: callvirt ""int C.this[int].get"" IL_0020: call ""void System.Console.WriteLine(int)"" IL_0025: ret }"); } [Fact] public void RefToArrayIndexIndexer() { var verifier = CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { int[] x = { 0, 1, 2, 3 }; M(x); } static void M(int[] x) { ref int r1 = ref x[2]; Console.WriteLine(r1); ref int r2 = ref x[^2]; Console.WriteLine(r2); r2 = 7; Console.WriteLine(r1); Console.WriteLine(r2); r1 = 5; Console.WriteLine(r1); Console.WriteLine(r2); } }", expectedOutput: @"2 2 7 7 5 5"); verifier.VerifyIL("C.M", @" { // Code size 67 (0x43) .maxstack 4 .locals init (int& V_0) //r2 IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: ldelema ""int"" IL_0007: dup IL_0008: ldind.i4 IL_0009: call ""void System.Console.WriteLine(int)"" IL_000e: ldarg.0 IL_000f: dup IL_0010: ldlen IL_0011: conv.i4 IL_0012: ldc.i4.2 IL_0013: sub IL_0014: ldelema ""int"" IL_0019: stloc.0 IL_001a: ldloc.0 IL_001b: ldind.i4 IL_001c: call ""void System.Console.WriteLine(int)"" IL_0021: ldloc.0 IL_0022: ldc.i4.7 IL_0023: stind.i4 IL_0024: dup IL_0025: ldind.i4 IL_0026: call ""void System.Console.WriteLine(int)"" IL_002b: ldloc.0 IL_002c: ldind.i4 IL_002d: call ""void System.Console.WriteLine(int)"" IL_0032: dup IL_0033: ldc.i4.5 IL_0034: stind.i4 IL_0035: ldind.i4 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: ldloc.0 IL_003c: ldind.i4 IL_003d: call ""void System.Console.WriteLine(int)"" IL_0042: ret }"); } [Fact] public void RangeIndexerStringIsFromEndStart() { CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { string s = ""abcdef""; Console.WriteLine(s[^2..]); } }", expectedOutput: "ef"); } [Fact] public void FakeRangeIndexerStringBothIsFromEnd() { CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { string s = ""abcdef""; Console.WriteLine(s[^4..^1]); } }", expectedOutput: "cde"); } [Fact] public void IndexIndexerStringTwoArgs() { var comp = CreateCompilationWithIndexAndRange(@" using System; class C { public static void Main() { var s = ""abcdef""; M(s); } public static void M(string s) { Console.WriteLine(s[new Index(1, false)]); Console.WriteLine(s[new Index(1, false), ^1]); } }"); comp.VerifyDiagnostics( // (13,27): error CS1501: No overload for method 'this' takes 2 arguments // Console.WriteLine(s[new Index(1, false), ^1]); Diagnostic(ErrorCode.ERR_BadArgCount, "s[new Index(1, false), ^1]").WithArguments("this", "2").WithLocation(13, 27)); } [Fact] public void IndexIndexerArrayTwoArgs() { var comp = CreateCompilationWithIndex(@" using System; class C { public static void Main() { var x = new int[1,1]; M(x); } public static void M(int[,] s) { Console.WriteLine(s[new Index(1, false), ^1]); } }"); comp.VerifyDiagnostics( // (12,27): error CS0029: Cannot implicitly convert type 'System.Index' to 'int' // Console.WriteLine(s[new Index(1, false), ^1]); Diagnostic(ErrorCode.ERR_NoImplicitConv, "new Index(1, false)").WithArguments("System.Index", "int").WithLocation(12, 29), // (12,27): error CS0029: Cannot implicitly convert type 'System.Index' to 'int' // Console.WriteLine(s[new Index(1, false), ^1]); Diagnostic(ErrorCode.ERR_NoImplicitConv, "^1").WithArguments("System.Index", "int").WithLocation(12, 50)); } [Fact] public void FakeIndexIndexerString() { var verifier = CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var s = ""abcdef""; Console.WriteLine(s[new Index(1, false)]); Console.WriteLine(s[(Index)2]); Console.WriteLine(s[^1]); } }", expectedOutput: @"b c f"); verifier.VerifyIL("C.Main", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (int V_0, int V_1, System.Index V_2) IL_0000: ldstr ""abcdef"" IL_0005: dup IL_0006: dup IL_0007: callvirt ""int string.Length.get"" IL_000c: stloc.0 IL_000d: ldc.i4.1 IL_000e: ldc.i4.0 IL_000f: newobj ""System.Index..ctor(int, bool)"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: ldloc.0 IL_0018: call ""int System.Index.GetOffset(int)"" IL_001d: stloc.1 IL_001e: ldloc.1 IL_001f: callvirt ""char string.this[int].get"" IL_0024: call ""void System.Console.WriteLine(char)"" IL_0029: dup IL_002a: ldc.i4.2 IL_002b: stloc.1 IL_002c: ldloc.1 IL_002d: callvirt ""char string.this[int].get"" IL_0032: call ""void System.Console.WriteLine(char)"" IL_0037: dup IL_0038: callvirt ""int string.Length.get"" IL_003d: ldc.i4.1 IL_003e: sub IL_003f: stloc.1 IL_0040: ldloc.1 IL_0041: callvirt ""char string.this[int].get"" IL_0046: call ""void System.Console.WriteLine(char)"" IL_004b: ret }"); } [Fact] public void FakeRangeIndexerString() { var verifier = CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var s = ""abcdef""; Console.WriteLine(s[1..3]); } }", expectedOutput: "bc"); verifier.VerifyIL("C.Main", @" { // Code size 24 (0x18) .maxstack 3 .locals init (int V_0, int V_1) IL_0000: ldstr ""abcdef"" IL_0005: ldc.i4.1 IL_0006: stloc.0 IL_0007: ldc.i4.3 IL_0008: ldloc.0 IL_0009: sub IL_000a: stloc.1 IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: callvirt ""string string.Substring(int, int)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret }"); } [Fact, WorkItem(40776, "https://github.com/dotnet/roslyn/issues/40776")] public void FakeIndexIndexerOnDefaultStruct() { var verifier = CompileAndVerifyWithIndexAndRange(@" using System; struct NotASpan { public int Length => 1; public int this[int index] => 0; } class C { static int Repro() => default(NotASpan)[^0]; static void Main() => Repro(); }"); verifier.VerifyIL("C.Repro", @" { // Code size 25 (0x19) .maxstack 3 .locals init (int V_0, NotASpan V_1) IL_0000: ldloca.s V_1 IL_0002: dup IL_0003: initobj ""NotASpan"" IL_0009: dup IL_000a: call ""int NotASpan.Length.get"" IL_000f: ldc.i4.0 IL_0010: sub IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: call ""int NotASpan.this[int].get"" IL_0018: ret }"); } [Fact, WorkItem(40776, "https://github.com/dotnet/roslyn/issues/40776")] public void FakeIndexIndexerOnStructConstructor() { var comp = CreateCompilationWithIndexAndRangeAndSpan(@" using System; class C { static byte Repro() => new Span<byte>(new byte[] { })[^1]; }"); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.Repro", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, System.Span<byte> V_1) IL_0000: ldc.i4.0 IL_0001: newarr ""byte"" IL_0006: newobj ""System.Span<byte>..ctor(byte[])"" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: dup IL_000f: call ""int System.Span<byte>.Length.get"" IL_0014: ldc.i4.1 IL_0015: sub IL_0016: stloc.0 IL_0017: ldloc.0 IL_0018: call ""ref byte System.Span<byte>.this[int].get"" IL_001d: ldind.u1 IL_001e: ret }"); } [Fact] public void FakeRangeIndexerStringOpenEnd() { CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var s = ""abcdef""; var result = M(s); Console.WriteLine(result); } public static string M(string s) => s[1..]; }", expectedOutput: "bcdef"); } [Fact] public void FakeRangeIndexerStringOpenStart() { CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var s = ""abcdef""; var result = M(s); Console.WriteLine(result); } public static string M(string s) => s[..^2]; }", expectedOutput: "abcd"); } [Fact] public void FakeIndexIndexerArray() { var comp = CreateCompilationWithIndex(@" using System; class C { public static void Main() { var x = new[] { 1, 2, 3, 11 }; M(x); } public static void M(int[] array) { Console.WriteLine(array[new Index(1, false)]); Console.WriteLine(array[^1]); } }", TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"2 11"); verifier.VerifyIL("C.M", @" { // Code size 40 (0x28) .maxstack 3 .locals init (int[] V_0, System.Index V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.0 IL_0005: newobj ""System.Index..ctor(int, bool)"" IL_000a: stloc.1 IL_000b: ldloca.s V_1 IL_000d: ldloc.0 IL_000e: ldlen IL_000f: conv.i4 IL_0010: call ""int System.Index.GetOffset(int)"" IL_0015: ldelem.i4 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: ldarg.0 IL_001c: dup IL_001d: ldlen IL_001e: conv.i4 IL_001f: ldc.i4.1 IL_0020: sub IL_0021: ldelem.i4 IL_0022: call ""void System.Console.WriteLine(int)"" IL_0027: ret }"); } [Fact] public void SuppressNullableWarning_FakeIndexIndexerArray() { string source = @" using System; class C { public static void Main() { var x = new[] { 1, 2, 3, 11 }; M(x); } public static void M(int[] array) { Console.Write(array[new Index(1, false)!]); Console.Write(array[(^1)!]); } }"; // cover case in ConvertToArrayIndex var comp = CreateCompilationWithIndex(source, WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "211"); } [Fact] public void FakeRangeIndexerArray() { var verifier = CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var arr = new[] { 1, 2, 3, 11 }; var result = M(arr); Console.WriteLine(result.Length); foreach (var x in result) { Console.WriteLine(x); } } public static int[] M(int[] array) => array[1..3]; }", expectedOutput: @"2 2 3"); verifier.VerifyIL("C.M", @" { // Code size 24 (0x18) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: call ""System.Index System.Index.op_Implicit(int)"" IL_0007: ldc.i4.3 IL_0008: call ""System.Index System.Index.op_Implicit(int)"" IL_000d: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0012: call ""int[] System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray<int>(int[], System.Range)"" IL_0017: ret } "); } [Fact] public void FakeRangeStartIsFromEndIndexerArray() { CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var arr = new[] { 1, 2, 3, 11 }; var result = M(arr); Console.WriteLine(result.Length); foreach (var x in result) { Console.WriteLine(x); } } public static int[] M(int[] array) => array[^2..]; }", expectedOutput: @"2 3 11"); } [Fact] public void FakeRangeBothIsFromEndIndexerArray() { CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var arr = new[] { 1, 2, 3, 11 }; var result = M(arr); Console.WriteLine(result.Length); foreach (var x in result) { Console.WriteLine(x); } } public static int[] M(int[] array) => array[^3..^1]; }", expectedOutput: @"2 2 3"); } [Fact] public void FakeRangeToEndIndexerArray() { var verifier = CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var arr = new[] { 1, 2, 3, 11 }; var result = M(arr); Console.WriteLine(result.Length); foreach (var x in result) { Console.WriteLine(x); } } public static int[] M(int[] array) => array[1..]; }", expectedOutput: @"3 2 3 11"); verifier.VerifyIL("C.M", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: call ""System.Index System.Index.op_Implicit(int)"" IL_0007: call ""System.Range System.Range.StartAt(System.Index)"" IL_000c: call ""int[] System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray<int>(int[], System.Range)"" IL_0011: ret } "); } [Fact] public void FakeRangeFromStartIndexerArray() { var comp = CreateCompilationWithIndexAndRange(@" using System; class C { public static void Main() { var arr = new[] { 1, 2, 3, 11 }; var result = M(arr); Console.WriteLine(result.Length); foreach (var x in result) { Console.WriteLine(x); } } public static int[] M(int[] array) => array[..3]; }" + TestSources.GetSubArray, TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, verify: Verification.Passes, expectedOutput: @"3 1 2 3"); verifier.VerifyIL("C.M", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.3 IL_0002: call ""System.Index System.Index.op_Implicit(int)"" IL_0007: call ""System.Range System.Range.EndAt(System.Index)"" IL_000c: call ""int[] System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray<int>(int[], System.Range)"" IL_0011: ret }"); } [Fact] public void LowerIndex_Int() { var compilation = CreateCompilationWithIndex(@" using System; public static class Util { public static Index Convert(int a) => ^a; }"); CompileAndVerify(compilation).VerifyIL("Util.Convert", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: newobj ""System.Index..ctor(int, bool)"" IL_0007: ret }"); } [Fact] public void LowerIndex_NullableInt() { var compilation = CreateCompilationWithIndex(@" using System; public static class Util { public static Index? Convert(int? a) => ^a; }"); CompileAndVerify(compilation).VerifyIL("Util.Convert", @" { // Code size 40 (0x28) .maxstack 2 .locals init (int? V_0, System.Index? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool int?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""System.Index?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""int int?.GetValueOrDefault()"" IL_001c: ldc.i4.1 IL_001d: newobj ""System.Index..ctor(int, bool)"" IL_0022: newobj ""System.Index?..ctor(System.Index)"" IL_0027: ret }"); } [Fact] public void PrintIndexExpressions() { var compilation = CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { int nonNullable = 1; int? nullableValue = 2; int? nullableDefault = default; Index a = nonNullable; Console.WriteLine(""a: "" + Print(a)); Index b = ^nonNullable; Console.WriteLine(""b: "" + Print(b)); // -------------------------------------------------------- Index? c = nullableValue; Console.WriteLine(""c: "" + Print(c)); Index? d = ^nullableValue; Console.WriteLine(""d: "" + Print(d)); // -------------------------------------------------------- Index? e = nullableDefault; Console.WriteLine(""e: "" + Print(e)); Index? f = ^nullableDefault; Console.WriteLine(""f: "" + Print(f)); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @" a: value: '1', fromEnd: 'False' b: value: '1', fromEnd: 'True' c: value: '2', fromEnd: 'False' d: value: '2', fromEnd: 'True' e: default f: default"); } [Fact] public void LowerRange_Create_Index_Index() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range Create(Index start, Index end) => start..end; }"); CompileAndVerify(compilation).VerifyIL("Util.Create", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0007: ret }"); } [Fact] public void LowerRange_Create_Index_NullableIndex() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range? Create(Index start, Index? end) => start..end; }"); CompileAndVerify(compilation).VerifyIL("Util.Create", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (System.Index V_0, System.Index? V_1, System.Range? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_1 IL_0006: call ""bool System.Index?.HasValue.get"" IL_000b: brtrue.s IL_0017 IL_000d: ldloca.s V_2 IL_000f: initobj ""System.Range?"" IL_0015: ldloc.2 IL_0016: ret IL_0017: ldloc.0 IL_0018: ldloca.s V_1 IL_001a: call ""System.Index System.Index?.GetValueOrDefault()"" IL_001f: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0024: newobj ""System.Range?..ctor(System.Range)"" IL_0029: ret }"); } [Fact] public void LowerRange_Create_NullableIndex_Index() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range? Create(Index? start, Index end) => start..end; }"); CompileAndVerify(compilation).VerifyIL("Util.Create", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (System.Index? V_0, System.Index V_1, System.Range? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""bool System.Index?.HasValue.get"" IL_000b: brtrue.s IL_0017 IL_000d: ldloca.s V_2 IL_000f: initobj ""System.Range?"" IL_0015: ldloc.2 IL_0016: ret IL_0017: ldloca.s V_0 IL_0019: call ""System.Index System.Index?.GetValueOrDefault()"" IL_001e: ldloc.1 IL_001f: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0024: newobj ""System.Range?..ctor(System.Range)"" IL_0029: ret }"); } [Fact] public void LowerRange_Create_NullableIndex_NullableIndex() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range? Create(Index? start, Index? end) => start..end; }"); CompileAndVerify(compilation).VerifyIL("Util.Create", @" { // Code size 56 (0x38) .maxstack 2 .locals init (System.Index? V_0, System.Index? V_1, System.Range? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""bool System.Index?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""bool System.Index?.HasValue.get"" IL_0012: and IL_0013: brtrue.s IL_001f IL_0015: ldloca.s V_2 IL_0017: initobj ""System.Range?"" IL_001d: ldloc.2 IL_001e: ret IL_001f: ldloca.s V_0 IL_0021: call ""System.Index System.Index?.GetValueOrDefault()"" IL_0026: ldloca.s V_1 IL_0028: call ""System.Index System.Index?.GetValueOrDefault()"" IL_002d: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0032: newobj ""System.Range?..ctor(System.Range)"" IL_0037: ret }"); } [Fact] public void LowerRange_ToEnd_Index() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range ToEnd(Index end) => ..end; }"); CompileAndVerify(compilation).VerifyIL("Util.ToEnd", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""System.Range System.Range.EndAt(System.Index)"" IL_0006: ret }"); } [Fact] public void LowerRange_ToEnd_NullableIndex() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range? ToEnd(Index? end) => ..end; }"); CompileAndVerify(compilation).VerifyIL("Util.ToEnd", @" { // Code size 39 (0x27) .maxstack 1 .locals init (System.Index? V_0, System.Range? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.Index?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""System.Range?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""System.Index System.Index?.GetValueOrDefault()"" IL_001c: call ""System.Range System.Range.EndAt(System.Index)"" IL_0021: newobj ""System.Range?..ctor(System.Range)"" IL_0026: ret }"); } [Fact] public void LowerRange_FromStart_Index() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range FromStart(Index start) => start..; }"); CompileAndVerify(compilation).VerifyIL("Util.FromStart", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""System.Range System.Range.StartAt(System.Index)"" IL_0006: ret }"); } [Fact] public void LowerRange_FromStart_NullableIndex() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range? FromStart(Index? start) => start..; }"); CompileAndVerify(compilation).VerifyIL("Util.FromStart", @" { // Code size 39 (0x27) .maxstack 1 .locals init (System.Index? V_0, System.Range? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.Index?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""System.Range?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""System.Index System.Index?.GetValueOrDefault()"" IL_001c: call ""System.Range System.Range.StartAt(System.Index)"" IL_0021: newobj ""System.Range?..ctor(System.Range)"" IL_0026: ret }"); } [Fact] public void LowerRange_All() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range All() => ..; }"); CompileAndVerify(compilation).VerifyIL("Util.All", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""System.Range System.Range.All.get"" IL_0005: ret }"); } [Fact] public void PrintRangeExpressions() { var compilation = CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Index nonNullable = 1; Index? nullableValue = 2; Index? nullableDefault = default; Range a = nonNullable..nonNullable; Console.WriteLine(""a: "" + Print(a)); Range? b = nonNullable..nullableValue; Console.WriteLine(""b: "" + Print(b)); Range? c = nonNullable..nullableDefault; Console.WriteLine(""c: "" + Print(c)); // -------------------------------------------------------- Range? d = nullableValue..nonNullable; Console.WriteLine(""d: "" + Print(d)); Range? e = nullableValue..nullableValue; Console.WriteLine(""e: "" + Print(e)); Range? f = nullableValue..nullableDefault; Console.WriteLine(""f: "" + Print(f)); // -------------------------------------------------------- Range? g = nullableDefault..nonNullable; Console.WriteLine(""g: "" + Print(g)); Range? h = nullableDefault..nullableValue; Console.WriteLine(""h: "" + Print(h)); Range? i = nullableDefault..nullableDefault; Console.WriteLine(""i: "" + Print(i)); // -------------------------------------------------------- Range? j = ..nonNullable; Console.WriteLine(""j: "" + Print(j)); Range? k = ..nullableValue; Console.WriteLine(""k: "" + Print(k)); Range? l = ..nullableDefault; Console.WriteLine(""l: "" + Print(l)); // -------------------------------------------------------- Range? m = nonNullable..; Console.WriteLine(""m: "" + Print(m)); Range? n = nullableValue..; Console.WriteLine(""n: "" + Print(n)); Range? o = nullableDefault..; Console.WriteLine(""o: "" + Print(o)); // -------------------------------------------------------- Range? p = ..; Console.WriteLine(""p: "" + Print(p)); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @" a: value: 'value: '1', fromEnd: 'False'', fromEnd: 'value: '1', fromEnd: 'False'' b: value: 'value: '1', fromEnd: 'False'', fromEnd: 'value: '2', fromEnd: 'False'' c: default d: value: 'value: '2', fromEnd: 'False'', fromEnd: 'value: '1', fromEnd: 'False'' e: value: 'value: '2', fromEnd: 'False'', fromEnd: 'value: '2', fromEnd: 'False'' f: default g: default h: default i: default j: value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '1', fromEnd: 'False'' k: value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '2', fromEnd: 'False'' l: default m: value: 'value: '1', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'True'' n: value: 'value: '2', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'True'' o: default p: value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'True''"); } [Fact] public void PassingAsArguments() { var compilation = CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(^1)); Console.WriteLine(Print(..)); Console.WriteLine(Print(2..)); Console.WriteLine(Print(..3)); Console.WriteLine(Print(4..5)); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @" value: '1', fromEnd: 'True' value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'True'' value: 'value: '2', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'True'' value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '3', fromEnd: 'False'' value: 'value: '4', fromEnd: 'False'', fromEnd: 'value: '5', fromEnd: 'False''"); } [Fact] public void LowerRange_OrderOfEvaluation_Index_NullableIndex() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { static void Main() { var x = Create(); } public static Range? Create() { return GetIndex1() .. GetIndex2(); } static Index GetIndex1() { System.Console.WriteLine(""1""); return default; } static Index? GetIndex2() { System.Console.WriteLine(""2""); return new Index(1, true); } }", options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @" 1 2").VerifyIL("Util.Create", @" { // Code size 56 (0x38) .maxstack 2 .locals init (System.Index V_0, System.Index? V_1, System.Range? V_2, System.Range? V_3) IL_0000: nop IL_0001: call ""System.Index Util.GetIndex1()"" IL_0006: stloc.0 IL_0007: call ""System.Index? Util.GetIndex2()"" IL_000c: stloc.1 IL_000d: ldloca.s V_1 IL_000f: call ""bool System.Index?.HasValue.get"" IL_0014: brtrue.s IL_0021 IL_0016: ldloca.s V_2 IL_0018: initobj ""System.Range?"" IL_001e: ldloc.2 IL_001f: br.s IL_0033 IL_0021: ldloc.0 IL_0022: ldloca.s V_1 IL_0024: call ""System.Index System.Index?.GetValueOrDefault()"" IL_0029: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_002e: newobj ""System.Range?..ctor(System.Range)"" IL_0033: stloc.3 IL_0034: br.s IL_0036 IL_0036: ldloc.3 IL_0037: ret }"); } [Fact] public void LowerRange_OrderOfEvaluation_Index_Null() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { static void Main() { var x = Create(); } public static Range? Create() { return GetIndex1() .. GetIndex2(); } static Index GetIndex1() { System.Console.WriteLine(""1""); return default; } static Index? GetIndex2() { System.Console.WriteLine(""2""); return null; } }", options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @" 1 2").VerifyIL("Util.Create", @" { // Code size 56 (0x38) .maxstack 2 .locals init (System.Index V_0, System.Index? V_1, System.Range? V_2, System.Range? V_3) IL_0000: nop IL_0001: call ""System.Index Util.GetIndex1()"" IL_0006: stloc.0 IL_0007: call ""System.Index? Util.GetIndex2()"" IL_000c: stloc.1 IL_000d: ldloca.s V_1 IL_000f: call ""bool System.Index?.HasValue.get"" IL_0014: brtrue.s IL_0021 IL_0016: ldloca.s V_2 IL_0018: initobj ""System.Range?"" IL_001e: ldloc.2 IL_001f: br.s IL_0033 IL_0021: ldloc.0 IL_0022: ldloca.s V_1 IL_0024: call ""System.Index System.Index?.GetValueOrDefault()"" IL_0029: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_002e: newobj ""System.Range?..ctor(System.Range)"" IL_0033: stloc.3 IL_0034: br.s IL_0036 IL_0036: ldloc.3 IL_0037: ret }"); } [Fact] public void Index_OperandConvertibleToInt() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { byte a = 3; Index b = ^a; Console.WriteLine(Print(b)); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: '3', fromEnd: 'True'"); } [Fact] public void Index_NullableAlwaysHasValue() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create())); } static Index? Create() { // should be lowered into: new Nullable<Index>(new Index(5, fromEnd: true)) return ^new Nullable<int>(5); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: '5', fromEnd: 'True'") .VerifyIL("Program.Create", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.5 IL_0001: ldc.i4.1 IL_0002: newobj ""System.Index..ctor(int, bool)"" IL_0007: newobj ""System.Index?..ctor(System.Index)"" IL_000c: ret }"); } [Fact] public void Range_NullableAlwaysHasValue_Left() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create(^1))); } static Range? Create(Index arg) { // should be lowered into: new Nullable<Range>(Range.FromStart(arg)) return new Nullable<Index>(arg)..; } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '1', fromEnd: 'True'', fromEnd: 'value: '0', fromEnd: 'True''") .VerifyIL("Program.Create", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""System.Range System.Range.StartAt(System.Index)"" IL_0006: newobj ""System.Range?..ctor(System.Range)"" IL_000b: ret }"); } [Fact] public void Range_NullableAlwaysHasValue_Right() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create(^1))); } static Range? Create(Index arg) { // should be lowered into: new Nullable<Range>(Range.ToEnd(arg)) return ..new Nullable<Index>(arg); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '1', fromEnd: 'True''") .VerifyIL("Program.Create", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""System.Range System.Range.EndAt(System.Index)"" IL_0006: newobj ""System.Range?..ctor(System.Range)"" IL_000b: ret }"); } [Fact] public void Range_NullableAlwaysHasValue_Both() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create(^2, ^1))); } static Range? Create(Index arg1, Index arg2) { // should be lowered into: new Nullable<Range>(Range.Create(arg1, arg2)) return new Nullable<Index>(arg1)..new Nullable<Index>(arg2); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '2', fromEnd: 'True'', fromEnd: 'value: '1', fromEnd: 'True''") .VerifyIL("Program.Create", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0007: newobj ""System.Range?..ctor(System.Range)"" IL_000c: ret }"); } [Fact] public void Index_NullableNeverHasValue() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create())); } static Index? Create() { // should be lowered into: new Nullable<Index>(new Index(default, fromEnd: true)) return ^new Nullable<int>(); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: '0', fromEnd: 'True'") .VerifyIL("Program.Create", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""System.Index..ctor(int, bool)"" IL_0007: newobj ""System.Index?..ctor(System.Index)"" IL_000c: ret }"); } [Fact] public void Range_NullableNeverhasValue_Left() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create())); } static Range? Create() { // should be lowered into: new Nullable<Range>(Range.FromStart(default)) return new Nullable<Index>()..; } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'True''") .VerifyIL("Program.Create", @" { // Code size 20 (0x14) .maxstack 1 .locals init (System.Index V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""System.Index"" IL_0008: ldloc.0 IL_0009: call ""System.Range System.Range.StartAt(System.Index)"" IL_000e: newobj ""System.Range?..ctor(System.Range)"" IL_0013: ret }"); } [Fact] public void Range_NullableNeverHasValue_Right() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create())); } static Range? Create() { // should be lowered into: new Nullable<Range>(Range.ToEnd(default)) return ..new Nullable<Index>(); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'False''") .VerifyIL("Program.Create", @" { // Code size 20 (0x14) .maxstack 1 .locals init (System.Index V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""System.Index"" IL_0008: ldloc.0 IL_0009: call ""System.Range System.Range.EndAt(System.Index)"" IL_000e: newobj ""System.Range?..ctor(System.Range)"" IL_0013: ret }"); } [Fact] public void Range_NullableNeverHasValue_Both() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create())); } static Range? Create() { // should be lowered into: new Nullable<Range>(Range.Create(default, default)) return new Nullable<Index>()..new Nullable<Index>(); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'False''") .VerifyIL("Program.Create", @" { // Code size 29 (0x1d) .maxstack 2 .locals init (System.Index V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""System.Index"" IL_0008: ldloc.0 IL_0009: ldloca.s V_0 IL_000b: initobj ""System.Index"" IL_0011: ldloc.0 IL_0012: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0017: newobj ""System.Range?..ctor(System.Range)"" IL_001c: ret }"); } [Fact] public void Index_OnFunctionCall() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(^Create(5))); } static int Create(int x) => x; }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: '5', fromEnd: 'True'"); } [Fact] public void Range_OnFunctionCall() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create(1)..Create(2))); } static Index Create(int x) => ^x; }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '1', fromEnd: 'True'', fromEnd: 'value: '2', fromEnd: 'True''"); } [Fact] public void Index_OnAssignment() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { int x = default; Console.WriteLine(Print(^(x = Create(5)))); Console.WriteLine(x); } static int Create(int x) => x; }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: @" value: '5', fromEnd: 'True' 5"); } [Fact] public void Range_OnAssignment() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Index x = default, y = default; Console.WriteLine(Print((x = Create(1))..(y = Create(2)))); Console.WriteLine(Print(x)); Console.WriteLine(Print(y)); } static Index Create(int x) => ^x; }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: @" value: 'value: '1', fromEnd: 'True'', fromEnd: 'value: '2', fromEnd: 'True'' value: '1', fromEnd: 'True' value: '2', fromEnd: 'True'"); } [Fact] public void Range_OnVarOut() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create(1, out Index y)..y)); } static Index Create(int x, out Index y) { y = ^2; return ^x; } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '1', fromEnd: 'True'', fromEnd: 'value: '2', fromEnd: 'True''"); } [Fact] public void Range_EvaluationInCondition() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { if ((Create(1, out int a)..Create(2, out int b)).Start.IsFromEnd && a < b) { Console.WriteLine(""YES""); } if ((Create(4, out int c)..Create(3, out int d)).Start.IsFromEnd && c < d) { Console.WriteLine(""NO""); } } static Index Create(int x, out int y) { y = x; return ^x; } }", options: TestOptions.ReleaseExe), expectedOutput: "YES"); } private const string PrintIndexesAndRangesCode = @" partial class Program { static string Print(Index arg) { return $""value: '{arg.Value}', fromEnd: '{arg.IsFromEnd}'""; } static string Print(Range arg) { return $""value: '{Print(arg.Start)}', fromEnd: '{Print(arg.End)}'""; } static string Print(Index? arg) { if (arg.HasValue) { return Print(arg.Value); } else { return ""default""; } } static string Print(Range? arg) { if (arg.HasValue) { return Print(arg.Value); } else { return ""default""; } } }"; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; 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 IndexAndRangeTests : CSharpTestBase { private CompilationVerifier CompileAndVerifyWithIndexAndRange(string s, string expectedOutput = null) { var comp = CreateCompilationWithIndexAndRange( new[] { s, TestSources.GetSubArray, }, expectedOutput is null ? TestOptions.ReleaseDll : TestOptions.ReleaseExe); return CompileAndVerify(comp, expectedOutput: expectedOutput); } private static (SemanticModel model, List<ElementAccessExpressionSyntax> accesses) GetModelAndAccesses(CSharpCompilation comp) { var syntaxTree = comp.SyntaxTrees[0]; var root = syntaxTree.GetRoot(); var model = comp.GetSemanticModel(syntaxTree); return (model, root.DescendantNodes().OfType<ElementAccessExpressionSyntax>().ToList()); } private static void VerifyIndexCall(IMethodSymbol symbol, string methodName, string containingTypeName) { Assert.NotNull(symbol); Assert.Equal(methodName, symbol.Name); Assert.Equal(2, symbol.Parameters.Length); Assert.Equal(containingTypeName, symbol.ContainingType.Name); } [Fact] public void ExpressionTreePatternIndexAndRange() { var src = @" using System; using System.Collections.Generic; using System.Linq.Expressions; struct S { public int Length => 0; public S Slice(int start, int length) => default; } class Program { static void Main() { Expression<Func<int[], int>> e = (int[] a) => a[new Index(0, true)]; // 1 Expression<Func<List<int>, int>> e2 = (List<int> a) => a[new Index(0, true)]; // 2 Expression<Func<int[], int[]>> e3 = (int[] a) => a[new Range(0, 1)]; // 3 Expression<Func<S, S>> e4 = (S s) => s[new Range(0, 1)]; // 4 } }"; var comp = CreateCompilationWithIndexAndRange( new[] { src, TestSources.GetSubArray, }); comp.VerifyEmitDiagnostics( // (16,55): error CS8790: An expression tree may not contain a pattern System.Index or System.Range indexer access // Expression<Func<int[], int>> e = (int[] a) => a[new Index(0, true)]; // 1 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, "a[new Index(0, true)]").WithLocation(16, 55), // (17,64): error CS8790: An expression tree may not contain a pattern System.Index or System.Range indexer access // Expression<Func<List<int>, int>> e2 = (List<int> a) => a[new Index(0, true)]; // 2 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, "a[new Index(0, true)]").WithLocation(17, 64), // (19,58): error CS8790: An expression tree may not contain a pattern System.Index or System.Range indexer access // Expression<Func<int[], int[]>> e3 = (int[] a) => a[new Range(0, 1)]; // 3 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, "a[new Range(0, 1)]").WithLocation(19, 58), // (20,46): error CS8790: An expression tree may not contain a pattern System.Index or System.Range indexer access // Expression<Func<S, S>> e4 = (S s) => s[new Range(0, 1)]; // 4 Diagnostic(ErrorCode.ERR_ExpressionTreeContainsPatternIndexOrRangeIndexer, "s[new Range(0, 1)]").WithLocation(20, 46) ); } [Fact] public void ExpressionTreeFromEndIndexAndRange() { var src = @" using System; using System.Collections.Generic; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<Index>> e = () => ^1; Expression<Func<Range>> e2 = () => 1..2; } }"; var comp = CreateCompilationWithIndexAndRange(src); comp.VerifyEmitDiagnostics( // (10,43): error CS8791: An expression tree may not contain a from-end index ('^') expression. // Expression<Func<Index>> e = () => ^1; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsFromEndIndexExpression, "^1").WithLocation(10, 43), // (11,44): error CS8792: An expression tree may not contain a range ('..') expression. // Expression<Func<Range>> e2 = () => 1..2; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsRangeExpression, "1..2").WithLocation(11, 44) ); } [Fact] public void PatternIndexArray() { var src = @" class C { static int M1(int[] arr) => arr[^1]; static char M2(string s) => s[^1]; } "; var verifier = CompileAndVerifyWithIndexAndRange(src); // Code gen for the following two should look basically // the same, except that string will use Length/indexer // and array will use ldlen/ldelem, and string may have // more temporaries verifier.VerifyIL("C.M1", @" { // Code size 8 (0x8) .maxstack 3 IL_0000: ldarg.0 IL_0001: dup IL_0002: ldlen IL_0003: conv.i4 IL_0004: ldc.i4.1 IL_0005: sub IL_0006: ldelem.i4 IL_0007: ret }"); verifier.VerifyIL("C.M2", @" { // Code size 17 (0x11) .maxstack 3 .locals init (int V_0) IL_0000: ldarg.0 IL_0001: dup IL_0002: callvirt ""int string.Length.get"" IL_0007: ldc.i4.1 IL_0008: sub IL_0009: stloc.0 IL_000a: ldloc.0 IL_000b: callvirt ""char string.this[int].get"" IL_0010: ret }"); } [Fact] [WorkItem(37789, "https://github.com/dotnet/roslyn/issues/37789")] public void PatternIndexAndRangeCompoundOperatorRefIndexer() { var src = @" using System; class C { static void Main(string[] args) { var span = new Span<byte>(new byte[2]); Console.WriteLine(span[1]); span[^1] += 1; Console.WriteLine(span[1]); } } "; var comp = CreateCompilationWithIndexAndRangeAndSpan(src, TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"0 1"); verifier.VerifyIL("C.Main", @" { // Code size 65 (0x41) .maxstack 3 .locals init (System.Span<byte> V_0, //span int V_1) IL_0000: ldloca.s V_0 IL_0002: ldc.i4.2 IL_0003: newarr ""byte"" IL_0008: call ""System.Span<byte>..ctor(byte[])"" IL_000d: ldloca.s V_0 IL_000f: ldc.i4.1 IL_0010: call ""ref byte System.Span<byte>.this[int].get"" IL_0015: ldind.u1 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: ldloca.s V_0 IL_001d: dup IL_001e: call ""int System.Span<byte>.Length.get"" IL_0023: ldc.i4.1 IL_0024: sub IL_0025: stloc.1 IL_0026: ldloc.1 IL_0027: call ""ref byte System.Span<byte>.this[int].get"" IL_002c: dup IL_002d: ldind.u1 IL_002e: ldc.i4.1 IL_002f: add IL_0030: conv.u1 IL_0031: stind.i1 IL_0032: ldloca.s V_0 IL_0034: ldc.i4.1 IL_0035: call ""ref byte System.Span<byte>.this[int].get"" IL_003a: ldind.u1 IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret }"); } [Fact] [WorkItem(37789, "https://github.com/dotnet/roslyn/issues/37789")] public void PatternIndexCompoundOperator() { var src = @" using System; struct S { private readonly int[] _array; private int _counter; public S(int[] a) { _array = a; _counter = 0; } public int Length { get { Console.WriteLine(""Length "" + _counter++); return _array.Length; } } public int this[int index] { get { Console.WriteLine(""Get "" + _counter++); return _array[index]; } set { Console.WriteLine(""Set "" + _counter++); _array[index] = value; } } } class C { static void Main(string[] args) { var array = new int[2]; Console.WriteLine(array[1]); var s = new S(array); s[^1] += 5; Console.WriteLine(array[1]); } } "; var comp = CreateCompilationWithIndexAndRangeAndSpan(src, TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"0 Length 0 Get 1 Set 2 5"); verifier.VerifyIL("C.Main", @" { // Code size 65 (0x41) .maxstack 4 .locals init (int[] V_0, //array S V_1, //s S& V_2, S& V_3, int V_4) IL_0000: ldc.i4.2 IL_0001: newarr ""int"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: ldelem.i4 IL_000a: call ""void System.Console.WriteLine(int)"" IL_000f: ldloca.s V_1 IL_0011: ldloc.0 IL_0012: call ""S..ctor(int[])"" IL_0017: ldloca.s V_1 IL_0019: stloc.2 IL_001a: ldloc.2 IL_001b: call ""int S.Length.get"" IL_0020: ldc.i4.1 IL_0021: sub IL_0022: ldloc.2 IL_0023: stloc.3 IL_0024: stloc.s V_4 IL_0026: ldloc.3 IL_0027: ldloc.s V_4 IL_0029: ldloc.3 IL_002a: ldloc.s V_4 IL_002c: call ""int S.this[int].get"" IL_0031: ldc.i4.5 IL_0032: add IL_0033: call ""void S.this[int].set"" IL_0038: ldloc.0 IL_0039: ldc.i4.1 IL_003a: ldelem.i4 IL_003b: call ""void System.Console.WriteLine(int)"" IL_0040: ret }"); } [Fact] [WorkItem(37789, "https://github.com/dotnet/roslyn/issues/37789")] public void PatternRangeCompoundOperator() { var src = @" using System; struct S { private readonly int[] _array; private int _counter; public S(int[] a) { _array = a; _counter = 0; } public int Length { get { Console.WriteLine(""Length "" + _counter++); return _array.Length; } } public ref int Slice(int start, int length) { Console.WriteLine(""Slice "" + _counter++); return ref _array[start]; } } class C { static void Main(string[] args) { var array = new int[2]; Console.WriteLine(array[1]); var s = new S(array); s[1..] += 5; Console.WriteLine(array[1]); } } "; var comp = CreateCompilationWithIndexAndRangeAndSpan(src, TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"0 Length 0 Slice 1 5"); verifier.VerifyIL("C.Main", @" { // Code size 57 (0x39) .maxstack 3 .locals init (int[] V_0, //array S V_1, int V_2, int V_3) IL_0000: ldc.i4.2 IL_0001: newarr ""int"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.1 IL_0009: ldelem.i4 IL_000a: call ""void System.Console.WriteLine(int)"" IL_000f: ldloc.0 IL_0010: newobj ""S..ctor(int[])"" IL_0015: stloc.1 IL_0016: ldloca.s V_1 IL_0018: call ""int S.Length.get"" IL_001d: ldc.i4.1 IL_001e: stloc.2 IL_001f: ldloc.2 IL_0020: sub IL_0021: stloc.3 IL_0022: ldloca.s V_1 IL_0024: ldloc.2 IL_0025: ldloc.3 IL_0026: call ""ref int S.Slice(int, int)"" IL_002b: dup IL_002c: ldind.i4 IL_002d: ldc.i4.5 IL_002e: add IL_002f: stind.i4 IL_0030: ldloc.0 IL_0031: ldc.i4.1 IL_0032: ldelem.i4 IL_0033: call ""void System.Console.WriteLine(int)"" IL_0038: ret }"); } [Fact] [WorkItem(37789, "https://github.com/dotnet/roslyn/issues/37789")] public void PatternindexNullableCoalescingAssignmentClass() { var src = @" using System; struct S { private readonly string[] _array; private int _counter; public S(string[] a) { _array = a; _counter = 0; } public int Length { get { Console.WriteLine(""Length "" + _counter++); return _array.Length; } } public string this[int index] { get { Console.WriteLine(""Get "" + _counter++); return _array[index]; } set { Console.WriteLine(""Set "" + _counter++); _array[index] = value; } } } class C { static void Main(string[] args) { var array = new string[2]; array[0] = ""abc""; Console.WriteLine(array[1] is null); var s = new S(array); s[^1] ??= s[^2]; s[^1] ??= s[^2]; Console.WriteLine(s[^1] ??= ""def""); Console.WriteLine(array[1]); } }"; var comp = CreateCompilationWithIndex(src, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @" True Length 0 Get 1 Length 2 Get 3 Set 4 Length 5 Get 6 Length 7 Get 8 abc abc"); verifier.VerifyIL("C.Main", @" { // Code size 203 (0xcb) .maxstack 5 .locals init (string[] V_0, //array S V_1, //s S& V_2, S& V_3, int V_4, string V_5, int V_6) IL_0000: ldc.i4.2 IL_0001: newarr ""string"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ldstr ""abc"" IL_000e: stelem.ref IL_000f: ldloc.0 IL_0010: ldc.i4.1 IL_0011: ldelem.ref IL_0012: ldnull IL_0013: ceq IL_0015: call ""void System.Console.WriteLine(bool)"" IL_001a: ldloca.s V_1 IL_001c: ldloc.0 IL_001d: call ""S..ctor(string[])"" IL_0022: ldloca.s V_1 IL_0024: stloc.2 IL_0025: ldloc.2 IL_0026: call ""int S.Length.get"" IL_002b: ldc.i4.1 IL_002c: sub IL_002d: ldloc.2 IL_002e: stloc.3 IL_002f: stloc.s V_4 IL_0031: ldloc.3 IL_0032: ldloc.s V_4 IL_0034: call ""string S.this[int].get"" IL_0039: brtrue.s IL_0059 IL_003b: ldloc.3 IL_003c: ldloc.s V_4 IL_003e: ldloca.s V_1 IL_0040: dup IL_0041: call ""int S.Length.get"" IL_0046: ldc.i4.2 IL_0047: sub IL_0048: stloc.s V_6 IL_004a: ldloc.s V_6 IL_004c: call ""string S.this[int].get"" IL_0051: dup IL_0052: stloc.s V_5 IL_0054: call ""void S.this[int].set"" IL_0059: ldloca.s V_1 IL_005b: stloc.3 IL_005c: ldloc.3 IL_005d: call ""int S.Length.get"" IL_0062: ldc.i4.1 IL_0063: sub IL_0064: ldloc.3 IL_0065: stloc.2 IL_0066: stloc.s V_4 IL_0068: ldloc.2 IL_0069: ldloc.s V_4 IL_006b: call ""string S.this[int].get"" IL_0070: brtrue.s IL_0090 IL_0072: ldloc.2 IL_0073: ldloc.s V_4 IL_0075: ldloca.s V_1 IL_0077: dup IL_0078: call ""int S.Length.get"" IL_007d: ldc.i4.2 IL_007e: sub IL_007f: stloc.s V_6 IL_0081: ldloc.s V_6 IL_0083: call ""string S.this[int].get"" IL_0088: dup IL_0089: stloc.s V_5 IL_008b: call ""void S.this[int].set"" IL_0090: ldloca.s V_1 IL_0092: stloc.2 IL_0093: ldloc.2 IL_0094: call ""int S.Length.get"" IL_0099: ldc.i4.1 IL_009a: sub IL_009b: ldloc.2 IL_009c: stloc.3 IL_009d: stloc.s V_4 IL_009f: ldloc.3 IL_00a0: ldloc.s V_4 IL_00a2: call ""string S.this[int].get"" IL_00a7: dup IL_00a8: brtrue.s IL_00bd IL_00aa: pop IL_00ab: ldloc.3 IL_00ac: ldloc.s V_4 IL_00ae: ldstr ""def"" IL_00b3: dup IL_00b4: stloc.s V_5 IL_00b6: call ""void S.this[int].set"" IL_00bb: ldloc.s V_5 IL_00bd: call ""void System.Console.WriteLine(string)"" IL_00c2: ldloc.0 IL_00c3: ldc.i4.1 IL_00c4: ldelem.ref IL_00c5: call ""void System.Console.WriteLine(string)"" IL_00ca: ret }"); } [Fact] [WorkItem(37789, "https://github.com/dotnet/roslyn/issues/37789")] public void PatternindexNullableCoalescingAssignmentStruct() { var src = @" using System; struct S { private readonly int?[] _array; private int _counter; public S(int?[] a) { _array = a; _counter = 0; } public int Length { get { Console.WriteLine(""Length "" + _counter++); return _array.Length; } } public int? this[int index] { get { Console.WriteLine(""Get "" + _counter++); return _array[index]; } set { Console.WriteLine(""Set "" + _counter++); _array[index] = value; } } } class C { static void Main(string[] args) { var array = new int?[2]; array[0] = 1; Console.WriteLine(array[1] is null); var s = new S(array); s[^1] ??= s[^2]; s[^1] ??= s[^2]; Console.WriteLine(s[^1] ??= 0); Console.WriteLine(array[1]); } }"; var comp = CreateCompilationWithIndex(src, options: TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @" True Length 0 Get 1 Length 2 Get 3 Set 4 Length 5 Get 6 Length 7 Get 8 1 1"); verifier.VerifyIL("C.Main", @" { // Code size 279 (0x117) .maxstack 5 .locals init (int?[] V_0, //array S V_1, //s int? V_2, S& V_3, S& V_4, int V_5, int? V_6, int V_7) IL_0000: ldc.i4.2 IL_0001: newarr ""int?"" IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.0 IL_0009: ldc.i4.1 IL_000a: newobj ""int?..ctor(int)"" IL_000f: stelem ""int?"" IL_0014: ldloc.0 IL_0015: ldc.i4.1 IL_0016: ldelem ""int?"" IL_001b: stloc.2 IL_001c: ldloca.s V_2 IL_001e: call ""bool int?.HasValue.get"" IL_0023: ldc.i4.0 IL_0024: ceq IL_0026: call ""void System.Console.WriteLine(bool)"" IL_002b: ldloca.s V_1 IL_002d: ldloc.0 IL_002e: call ""S..ctor(int?[])"" IL_0033: ldloca.s V_1 IL_0035: stloc.3 IL_0036: ldloc.3 IL_0037: call ""int S.Length.get"" IL_003c: ldc.i4.1 IL_003d: sub IL_003e: ldloc.3 IL_003f: stloc.s V_4 IL_0041: stloc.s V_5 IL_0043: ldloc.s V_4 IL_0045: ldloc.s V_5 IL_0047: call ""int? S.this[int].get"" IL_004c: stloc.2 IL_004d: ldloca.s V_2 IL_004f: call ""bool int?.HasValue.get"" IL_0054: brtrue.s IL_0075 IL_0056: ldloc.s V_4 IL_0058: ldloc.s V_5 IL_005a: ldloca.s V_1 IL_005c: dup IL_005d: call ""int S.Length.get"" IL_0062: ldc.i4.2 IL_0063: sub IL_0064: stloc.s V_7 IL_0066: ldloc.s V_7 IL_0068: call ""int? S.this[int].get"" IL_006d: dup IL_006e: stloc.s V_6 IL_0070: call ""void S.this[int].set"" IL_0075: ldloca.s V_1 IL_0077: stloc.s V_4 IL_0079: ldloc.s V_4 IL_007b: call ""int S.Length.get"" IL_0080: ldc.i4.1 IL_0081: sub IL_0082: ldloc.s V_4 IL_0084: stloc.3 IL_0085: stloc.s V_5 IL_0087: ldloc.3 IL_0088: ldloc.s V_5 IL_008a: call ""int? S.this[int].get"" IL_008f: stloc.2 IL_0090: ldloca.s V_2 IL_0092: call ""bool int?.HasValue.get"" IL_0097: brtrue.s IL_00b7 IL_0099: ldloc.3 IL_009a: ldloc.s V_5 IL_009c: ldloca.s V_1 IL_009e: dup IL_009f: call ""int S.Length.get"" IL_00a4: ldc.i4.2 IL_00a5: sub IL_00a6: stloc.s V_7 IL_00a8: ldloc.s V_7 IL_00aa: call ""int? S.this[int].get"" IL_00af: dup IL_00b0: stloc.s V_6 IL_00b2: call ""void S.this[int].set"" IL_00b7: ldloca.s V_1 IL_00b9: stloc.3 IL_00ba: ldloc.3 IL_00bb: call ""int S.Length.get"" IL_00c0: ldc.i4.1 IL_00c1: sub IL_00c2: ldloc.3 IL_00c3: stloc.s V_4 IL_00c5: stloc.s V_5 IL_00c7: ldloc.s V_4 IL_00c9: ldloc.s V_5 IL_00cb: call ""int? S.this[int].get"" IL_00d0: stloc.2 IL_00d1: ldloca.s V_2 IL_00d3: call ""int int?.GetValueOrDefault()"" IL_00d8: stloc.s V_7 IL_00da: ldloca.s V_2 IL_00dc: call ""bool int?.HasValue.get"" IL_00e1: brtrue.s IL_00fe IL_00e3: ldc.i4.0 IL_00e4: stloc.s V_7 IL_00e6: ldloc.s V_4 IL_00e8: ldloc.s V_5 IL_00ea: ldloca.s V_6 IL_00ec: ldloc.s V_7 IL_00ee: call ""int?..ctor(int)"" IL_00f3: ldloc.s V_6 IL_00f5: call ""void S.this[int].set"" IL_00fa: ldloc.s V_7 IL_00fc: br.s IL_0100 IL_00fe: ldloc.s V_7 IL_0100: call ""void System.Console.WriteLine(int)"" IL_0105: ldloc.0 IL_0106: ldc.i4.1 IL_0107: ldelem ""int?"" IL_010c: box ""int?"" IL_0111: call ""void System.Console.WriteLine(object)"" IL_0116: ret }"); } [Fact] public void StringAndSpanPatternRangeOpenEnd() { var src = @" using System; class C { public static void Main() { string s = ""abcd""; Console.WriteLine(s[..]); ReadOnlySpan<char> span = s; foreach (var c in span[..]) { Console.Write(c); } } }"; var comp = CreateCompilationWithIndexAndRangeAndSpan(src, TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @" abcd abcd"); verifier.VerifyIL("C.Main", @" { // Code size 86 (0x56) .maxstack 4 .locals init (int V_0, System.ReadOnlySpan<char> V_1, System.ReadOnlySpan<char> V_2, int V_3) IL_0000: ldstr ""abcd"" IL_0005: dup IL_0006: dup IL_0007: callvirt ""int string.Length.get"" IL_000c: ldc.i4.0 IL_000d: sub IL_000e: stloc.0 IL_000f: ldc.i4.0 IL_0010: ldloc.0 IL_0011: callvirt ""string string.Substring(int, int)"" IL_0016: call ""void System.Console.WriteLine(string)"" IL_001b: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(string)"" IL_0020: stloc.2 IL_0021: ldloca.s V_2 IL_0023: call ""int System.ReadOnlySpan<char>.Length.get"" IL_0028: ldc.i4.0 IL_0029: sub IL_002a: stloc.3 IL_002b: ldloca.s V_2 IL_002d: ldc.i4.0 IL_002e: ldloc.3 IL_002f: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.Slice(int, int)"" IL_0034: stloc.1 IL_0035: ldc.i4.0 IL_0036: stloc.0 IL_0037: br.s IL_004b IL_0039: ldloca.s V_1 IL_003b: ldloc.0 IL_003c: call ""ref readonly char System.ReadOnlySpan<char>.this[int].get"" IL_0041: ldind.u2 IL_0042: call ""void System.Console.Write(char)"" IL_0047: ldloc.0 IL_0048: ldc.i4.1 IL_0049: add IL_004a: stloc.0 IL_004b: ldloc.0 IL_004c: ldloca.s V_1 IL_004e: call ""int System.ReadOnlySpan<char>.Length.get"" IL_0053: blt.s IL_0039 IL_0055: ret }"); var (model, elementAccesses) = GetModelAndAccesses(comp); var info = model.GetSymbolInfo(elementAccesses[0]); var substringCall = (IMethodSymbol)info.Symbol; info = model.GetSymbolInfo(elementAccesses[1]); var sliceCall = (IMethodSymbol)info.Symbol; VerifyIndexCall(substringCall, "Substring", "String"); VerifyIndexCall(sliceCall, "Slice", "ReadOnlySpan"); } [Fact] public void SpanTaskReturn() { var src = @" using System; using System.Threading.Tasks; class C { static void Throws(Action a) { try { a(); } catch { Console.WriteLine(""throws""); } } public static void Main() { string s = ""abcd""; Throws(() => { var span = new Span<char>(s.ToCharArray())[0..10]; }); } }"; var comp = CreateCompilationWithIndexAndRangeAndSpan(src, TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "throws"); var (model, accesses) = GetModelAndAccesses(comp); VerifyIndexCall((IMethodSymbol)model.GetSymbolInfo(accesses[0]).Symbol, "Slice", "Span"); } [Fact] public void PatternIndexSetter() { var src = @" using System; struct S { public int F; public int Length => 1; public int this[int i] { get => F; set { F = value; } } } class C { static void Main() { S s = new S(); s.F = 0; Console.WriteLine(s[^1]); s[^1] = 2; Console.WriteLine(s[^1]); Console.WriteLine(s.F); } }"; var comp = CreateCompilationWithIndexAndRange(src, TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"0 2 2"); verifier.VerifyIL("C.Main", @" { // Code size 90 (0x5a) .maxstack 3 .locals init (S V_0, //s int V_1) IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: ldc.i4.0 IL_000b: stfld ""int S.F"" IL_0010: ldloca.s V_0 IL_0012: dup IL_0013: call ""int S.Length.get"" IL_0018: ldc.i4.1 IL_0019: sub IL_001a: stloc.1 IL_001b: ldloc.1 IL_001c: call ""int S.this[int].get"" IL_0021: call ""void System.Console.WriteLine(int)"" IL_0026: ldloca.s V_0 IL_0028: dup IL_0029: call ""int S.Length.get"" IL_002e: ldc.i4.1 IL_002f: sub IL_0030: stloc.1 IL_0031: ldloc.1 IL_0032: ldc.i4.2 IL_0033: call ""void S.this[int].set"" IL_0038: ldloca.s V_0 IL_003a: dup IL_003b: call ""int S.Length.get"" IL_0040: ldc.i4.1 IL_0041: sub IL_0042: stloc.1 IL_0043: ldloc.1 IL_0044: call ""int S.this[int].get"" IL_0049: call ""void System.Console.WriteLine(int)"" IL_004e: ldloc.0 IL_004f: ldfld ""int S.F"" IL_0054: call ""void System.Console.WriteLine(int)"" IL_0059: ret }"); var (model, accesses) = GetModelAndAccesses(comp); foreach (var access in accesses) { var info = model.GetSymbolInfo(access); var property = (IPropertySymbol)info.Symbol; Assert.NotNull(property); Assert.True(property.IsIndexer); Assert.Equal(SpecialType.System_Int32, property.Parameters[0].Type.SpecialType); Assert.Equal("S", property.ContainingType.Name); } } [Fact] public void PatternIndexerRefReturn() { var comp = CreateCompilationWithIndexAndRangeAndSpan(@" using System; class C { static void Main() { Span<int> s = new int[] { 2, 4, 5, 6 }; Console.WriteLine(s[^2]); ref int x = ref s[^2]; Console.WriteLine(x); s[^2] = 9; Console.WriteLine(s[^2]); Console.WriteLine(x); } }", TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"5 5 9 9"); verifier.VerifyIL("C.Main", @" { // Code size 120 (0x78) .maxstack 4 .locals init (System.Span<int> V_0, //s int V_1, int V_2) IL_0000: ldc.i4.4 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=16 <PrivateImplementationDetails>.B35A10C764778866E34111165FC69660C6171DF0CB0141E39FA0217EF7A97646"" IL_000c: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0011: call ""System.Span<int> System.Span<int>.op_Implicit(int[])"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: dup IL_001a: call ""int System.Span<int>.Length.get"" IL_001f: ldc.i4.2 IL_0020: sub IL_0021: stloc.1 IL_0022: ldloc.1 IL_0023: call ""ref int System.Span<int>.this[int].get"" IL_0028: ldind.i4 IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: ldloca.s V_0 IL_0030: dup IL_0031: call ""int System.Span<int>.Length.get"" IL_0036: ldc.i4.2 IL_0037: sub IL_0038: stloc.1 IL_0039: ldloc.1 IL_003a: call ""ref int System.Span<int>.this[int].get"" IL_003f: dup IL_0040: ldind.i4 IL_0041: call ""void System.Console.WriteLine(int)"" IL_0046: ldloca.s V_0 IL_0048: dup IL_0049: call ""int System.Span<int>.Length.get"" IL_004e: ldc.i4.2 IL_004f: sub IL_0050: stloc.2 IL_0051: ldloc.2 IL_0052: call ""ref int System.Span<int>.this[int].get"" IL_0057: ldc.i4.s 9 IL_0059: stind.i4 IL_005a: ldloca.s V_0 IL_005c: dup IL_005d: call ""int System.Span<int>.Length.get"" IL_0062: ldc.i4.2 IL_0063: sub IL_0064: stloc.2 IL_0065: ldloc.2 IL_0066: call ""ref int System.Span<int>.this[int].get"" IL_006b: ldind.i4 IL_006c: call ""void System.Console.WriteLine(int)"" IL_0071: ldind.i4 IL_0072: call ""void System.Console.WriteLine(int)"" IL_0077: ret }"); } [Fact] public void PatternIndexAndRangeSpanChar() { var comp = CreateCompilationWithIndexAndRangeAndSpan(@" using System; class C { static void Main() { ReadOnlySpan<char> s = ""abcdefg""; Console.WriteLine(s[^2]); var index = ^1; Console.WriteLine(s[index]); s = s[^2..]; Console.WriteLine(s[0]); Console.WriteLine(s[1]); } }", TestOptions.ReleaseExe); ; var verifier = CompileAndVerify(comp, expectedOutput: @"f g f g"); verifier.VerifyIL(@"C.Main", @" { // Code size 129 (0x81) .maxstack 3 .locals init (System.ReadOnlySpan<char> V_0, //s System.Index V_1, //index int V_2, int V_3, System.ReadOnlySpan<char> V_4) IL_0000: ldstr ""abcdefg"" IL_0005: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.op_Implicit(string)"" IL_000a: stloc.0 IL_000b: ldloca.s V_0 IL_000d: dup IL_000e: call ""int System.ReadOnlySpan<char>.Length.get"" IL_0013: ldc.i4.2 IL_0014: sub IL_0015: stloc.2 IL_0016: ldloc.2 IL_0017: call ""ref readonly char System.ReadOnlySpan<char>.this[int].get"" IL_001c: ldind.u2 IL_001d: call ""void System.Console.WriteLine(char)"" IL_0022: ldloca.s V_1 IL_0024: ldc.i4.1 IL_0025: ldc.i4.1 IL_0026: call ""System.Index..ctor(int, bool)"" IL_002b: ldloca.s V_0 IL_002d: dup IL_002e: call ""int System.ReadOnlySpan<char>.Length.get"" IL_0033: stloc.2 IL_0034: ldloca.s V_1 IL_0036: ldloc.2 IL_0037: call ""int System.Index.GetOffset(int)"" IL_003c: stloc.3 IL_003d: ldloc.3 IL_003e: call ""ref readonly char System.ReadOnlySpan<char>.this[int].get"" IL_0043: ldind.u2 IL_0044: call ""void System.Console.WriteLine(char)"" IL_0049: ldloc.0 IL_004a: stloc.s V_4 IL_004c: ldloca.s V_4 IL_004e: call ""int System.ReadOnlySpan<char>.Length.get"" IL_0053: dup IL_0054: ldc.i4.2 IL_0055: sub IL_0056: stloc.3 IL_0057: ldloc.3 IL_0058: sub IL_0059: stloc.2 IL_005a: ldloca.s V_4 IL_005c: ldloc.3 IL_005d: ldloc.2 IL_005e: call ""System.ReadOnlySpan<char> System.ReadOnlySpan<char>.Slice(int, int)"" IL_0063: stloc.0 IL_0064: ldloca.s V_0 IL_0066: ldc.i4.0 IL_0067: call ""ref readonly char System.ReadOnlySpan<char>.this[int].get"" IL_006c: ldind.u2 IL_006d: call ""void System.Console.WriteLine(char)"" IL_0072: ldloca.s V_0 IL_0074: ldc.i4.1 IL_0075: call ""ref readonly char System.ReadOnlySpan<char>.this[int].get"" IL_007a: ldind.u2 IL_007b: call ""void System.Console.WriteLine(char)"" IL_0080: ret }"); } [Fact] public void PatternIndexAndRangeSpanInt() { var comp = CreateCompilationWithIndexAndRangeAndSpan(@" using System; class C { static void Main() { Span<int> s = new int[] { 2, 4, 5, 6 }; Console.WriteLine(s[^2]); var index = ^1; Console.WriteLine(s[index]); s = s[^2..]; Console.WriteLine(s[0]); Console.WriteLine(s[1]); } }", TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"5 6 5 6"); verifier.VerifyIL("C.Main", @" { // Code size 141 (0x8d) .maxstack 3 .locals init (System.Span<int> V_0, //s System.Index V_1, //index int V_2, int V_3, System.Span<int> V_4) IL_0000: ldc.i4.4 IL_0001: newarr ""int"" IL_0006: dup IL_0007: ldtoken ""<PrivateImplementationDetails>.__StaticArrayInitTypeSize=16 <PrivateImplementationDetails>.B35A10C764778866E34111165FC69660C6171DF0CB0141E39FA0217EF7A97646"" IL_000c: call ""void System.Runtime.CompilerServices.RuntimeHelpers.InitializeArray(System.Array, System.RuntimeFieldHandle)"" IL_0011: call ""System.Span<int> System.Span<int>.op_Implicit(int[])"" IL_0016: stloc.0 IL_0017: ldloca.s V_0 IL_0019: dup IL_001a: call ""int System.Span<int>.Length.get"" IL_001f: ldc.i4.2 IL_0020: sub IL_0021: stloc.2 IL_0022: ldloc.2 IL_0023: call ""ref int System.Span<int>.this[int].get"" IL_0028: ldind.i4 IL_0029: call ""void System.Console.WriteLine(int)"" IL_002e: ldloca.s V_1 IL_0030: ldc.i4.1 IL_0031: ldc.i4.1 IL_0032: call ""System.Index..ctor(int, bool)"" IL_0037: ldloca.s V_0 IL_0039: dup IL_003a: call ""int System.Span<int>.Length.get"" IL_003f: stloc.2 IL_0040: ldloca.s V_1 IL_0042: ldloc.2 IL_0043: call ""int System.Index.GetOffset(int)"" IL_0048: stloc.3 IL_0049: ldloc.3 IL_004a: call ""ref int System.Span<int>.this[int].get"" IL_004f: ldind.i4 IL_0050: call ""void System.Console.WriteLine(int)"" IL_0055: ldloc.0 IL_0056: stloc.s V_4 IL_0058: ldloca.s V_4 IL_005a: call ""int System.Span<int>.Length.get"" IL_005f: dup IL_0060: ldc.i4.2 IL_0061: sub IL_0062: stloc.3 IL_0063: ldloc.3 IL_0064: sub IL_0065: stloc.2 IL_0066: ldloca.s V_4 IL_0068: ldloc.3 IL_0069: ldloc.2 IL_006a: call ""System.Span<int> System.Span<int>.Slice(int, int)"" IL_006f: stloc.0 IL_0070: ldloca.s V_0 IL_0072: ldc.i4.0 IL_0073: call ""ref int System.Span<int>.this[int].get"" IL_0078: ldind.i4 IL_0079: call ""void System.Console.WriteLine(int)"" IL_007e: ldloca.s V_0 IL_0080: ldc.i4.1 IL_0081: call ""ref int System.Span<int>.this[int].get"" IL_0086: ldind.i4 IL_0087: call ""void System.Console.WriteLine(int)"" IL_008c: ret }"); } [Fact] public void RealIndexersPreferredToPattern() { var src = @" using System; class C { public int Length => throw null; public int this[Index i, int j = 0] { get { Console.WriteLine(""Index""); return 0; } } public int this[int i] { get { Console.WriteLine(""int""); return 0; } } public int Slice(int i, int j) => throw null; public int this[Range r, int j = 0] { get { Console.WriteLine(""Range""); return 0; } } static void Main() { var c = new C(); _ = c[0]; _ = c[^0]; _ = c[0..]; } }"; var verifier = CompileAndVerifyWithIndexAndRange(src, expectedOutput: @" int Index Range"); } [Fact] public void PatternIndexList() { var src = @" using System; using System.Collections.Generic; class C { private static List<int> list = new List<int>() { 2, 4, 5, 6 }; static void Main() { Console.WriteLine(list[^2]); var index = ^1; Console.WriteLine(list[index]); } }"; var verifier = CompileAndVerifyWithIndexAndRange(src, expectedOutput: @"5 6"); verifier.VerifyIL("C.Main", @" { // Code size 67 (0x43) .maxstack 3 .locals init (System.Index V_0, //index int V_1, int V_2) IL_0000: ldsfld ""System.Collections.Generic.List<int> C.list"" IL_0005: dup IL_0006: callvirt ""int System.Collections.Generic.List<int>.Count.get"" IL_000b: ldc.i4.2 IL_000c: sub IL_000d: stloc.1 IL_000e: ldloc.1 IL_000f: callvirt ""int System.Collections.Generic.List<int>.this[int].get"" IL_0014: call ""void System.Console.WriteLine(int)"" IL_0019: ldloca.s V_0 IL_001b: ldc.i4.1 IL_001c: ldc.i4.1 IL_001d: call ""System.Index..ctor(int, bool)"" IL_0022: ldsfld ""System.Collections.Generic.List<int> C.list"" IL_0027: dup IL_0028: callvirt ""int System.Collections.Generic.List<int>.Count.get"" IL_002d: stloc.1 IL_002e: ldloca.s V_0 IL_0030: ldloc.1 IL_0031: call ""int System.Index.GetOffset(int)"" IL_0036: stloc.2 IL_0037: ldloc.2 IL_0038: callvirt ""int System.Collections.Generic.List<int>.this[int].get"" IL_003d: call ""void System.Console.WriteLine(int)"" IL_0042: ret }"); } [Theory] [InlineData("Length")] [InlineData("Count")] public void PatternRangeIndexers(string propertyName) { var src = @" using System; class C { private int[] _f = { 2, 4, 5, 6 }; public int " + propertyName + @" => _f.Length; public int[] Slice(int start, int length) => _f[start..length]; static void Main() { var c = new C(); foreach (var x in c[1..]) { Console.WriteLine(x); } foreach (var x in c[..^2]) { Console.WriteLine(x); } } }"; var verifier = CompileAndVerifyWithIndexAndRange(src, @" 4 5 2 4"); verifier.VerifyIL("C.Main", @" { // Code size 95 (0x5f) .maxstack 3 .locals init (C V_0, //c int[] V_1, int V_2, int V_3, int V_4) IL_0000: newobj ""C..ctor()"" IL_0005: stloc.0 IL_0006: ldloc.0 IL_0007: dup IL_0008: callvirt ""int C." + propertyName + @".get"" IL_000d: ldc.i4.1 IL_000e: stloc.3 IL_000f: ldloc.3 IL_0010: sub IL_0011: stloc.s V_4 IL_0013: ldloc.3 IL_0014: ldloc.s V_4 IL_0016: callvirt ""int[] C.Slice(int, int)"" IL_001b: stloc.1 IL_001c: ldc.i4.0 IL_001d: stloc.2 IL_001e: br.s IL_002c IL_0020: ldloc.1 IL_0021: ldloc.2 IL_0022: ldelem.i4 IL_0023: call ""void System.Console.WriteLine(int)"" IL_0028: ldloc.2 IL_0029: ldc.i4.1 IL_002a: add IL_002b: stloc.2 IL_002c: ldloc.2 IL_002d: ldloc.1 IL_002e: ldlen IL_002f: conv.i4 IL_0030: blt.s IL_0020 IL_0032: ldloc.0 IL_0033: dup IL_0034: callvirt ""int C." + propertyName + @".get"" IL_0039: ldc.i4.2 IL_003a: sub IL_003b: ldc.i4.0 IL_003c: sub IL_003d: stloc.s V_4 IL_003f: ldc.i4.0 IL_0040: ldloc.s V_4 IL_0042: callvirt ""int[] C.Slice(int, int)"" IL_0047: stloc.1 IL_0048: ldc.i4.0 IL_0049: stloc.2 IL_004a: br.s IL_0058 IL_004c: ldloc.1 IL_004d: ldloc.2 IL_004e: ldelem.i4 IL_004f: call ""void System.Console.WriteLine(int)"" IL_0054: ldloc.2 IL_0055: ldc.i4.1 IL_0056: add IL_0057: stloc.2 IL_0058: ldloc.2 IL_0059: ldloc.1 IL_005a: ldlen IL_005b: conv.i4 IL_005c: blt.s IL_004c IL_005e: ret } "); } [Theory] [InlineData("Length")] [InlineData("Count")] public void PatternIndexIndexers(string propertyName) { var src = @" using System; class C { private int[] _f = { 2, 4, 5, 6 }; public int " + propertyName + @" => _f.Length; public int this[int x] => _f[x]; static void Main() { var c = new C(); Console.WriteLine(c[0]); Console.WriteLine(c[^1]); } }"; var verifier = CompileAndVerifyWithIndexAndRange(src, @" 2 6"); verifier.VerifyIL("C.Main", @" { // Code size 38 (0x26) .maxstack 3 .locals init (int V_0) IL_0000: newobj ""C..ctor()"" IL_0005: dup IL_0006: ldc.i4.0 IL_0007: callvirt ""int C.this[int].get"" IL_000c: call ""void System.Console.WriteLine(int)"" IL_0011: dup IL_0012: callvirt ""int C." + propertyName + @".get"" IL_0017: ldc.i4.1 IL_0018: sub IL_0019: stloc.0 IL_001a: ldloc.0 IL_001b: callvirt ""int C.this[int].get"" IL_0020: call ""void System.Console.WriteLine(int)"" IL_0025: ret }"); } [Fact] public void RefToArrayIndexIndexer() { var verifier = CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { int[] x = { 0, 1, 2, 3 }; M(x); } static void M(int[] x) { ref int r1 = ref x[2]; Console.WriteLine(r1); ref int r2 = ref x[^2]; Console.WriteLine(r2); r2 = 7; Console.WriteLine(r1); Console.WriteLine(r2); r1 = 5; Console.WriteLine(r1); Console.WriteLine(r2); } }", expectedOutput: @"2 2 7 7 5 5"); verifier.VerifyIL("C.M", @" { // Code size 67 (0x43) .maxstack 4 .locals init (int& V_0) //r2 IL_0000: ldarg.0 IL_0001: ldc.i4.2 IL_0002: ldelema ""int"" IL_0007: dup IL_0008: ldind.i4 IL_0009: call ""void System.Console.WriteLine(int)"" IL_000e: ldarg.0 IL_000f: dup IL_0010: ldlen IL_0011: conv.i4 IL_0012: ldc.i4.2 IL_0013: sub IL_0014: ldelema ""int"" IL_0019: stloc.0 IL_001a: ldloc.0 IL_001b: ldind.i4 IL_001c: call ""void System.Console.WriteLine(int)"" IL_0021: ldloc.0 IL_0022: ldc.i4.7 IL_0023: stind.i4 IL_0024: dup IL_0025: ldind.i4 IL_0026: call ""void System.Console.WriteLine(int)"" IL_002b: ldloc.0 IL_002c: ldind.i4 IL_002d: call ""void System.Console.WriteLine(int)"" IL_0032: dup IL_0033: ldc.i4.5 IL_0034: stind.i4 IL_0035: ldind.i4 IL_0036: call ""void System.Console.WriteLine(int)"" IL_003b: ldloc.0 IL_003c: ldind.i4 IL_003d: call ""void System.Console.WriteLine(int)"" IL_0042: ret }"); } [Fact] public void RangeIndexerStringIsFromEndStart() { CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { string s = ""abcdef""; Console.WriteLine(s[^2..]); } }", expectedOutput: "ef"); } [Fact] public void FakeRangeIndexerStringBothIsFromEnd() { CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { string s = ""abcdef""; Console.WriteLine(s[^4..^1]); } }", expectedOutput: "cde"); } [Fact] public void IndexIndexerStringTwoArgs() { var comp = CreateCompilationWithIndexAndRange(@" using System; class C { public static void Main() { var s = ""abcdef""; M(s); } public static void M(string s) { Console.WriteLine(s[new Index(1, false)]); Console.WriteLine(s[new Index(1, false), ^1]); } }"); comp.VerifyDiagnostics( // (13,27): error CS1501: No overload for method 'this' takes 2 arguments // Console.WriteLine(s[new Index(1, false), ^1]); Diagnostic(ErrorCode.ERR_BadArgCount, "s[new Index(1, false), ^1]").WithArguments("this", "2").WithLocation(13, 27)); } [Fact] public void IndexIndexerArrayTwoArgs() { var comp = CreateCompilationWithIndex(@" using System; class C { public static void Main() { var x = new int[1,1]; M(x); } public static void M(int[,] s) { Console.WriteLine(s[new Index(1, false), ^1]); } }"); comp.VerifyDiagnostics( // (12,27): error CS0029: Cannot implicitly convert type 'System.Index' to 'int' // Console.WriteLine(s[new Index(1, false), ^1]); Diagnostic(ErrorCode.ERR_NoImplicitConv, "new Index(1, false)").WithArguments("System.Index", "int").WithLocation(12, 29), // (12,27): error CS0029: Cannot implicitly convert type 'System.Index' to 'int' // Console.WriteLine(s[new Index(1, false), ^1]); Diagnostic(ErrorCode.ERR_NoImplicitConv, "^1").WithArguments("System.Index", "int").WithLocation(12, 50)); } [Fact] public void FakeIndexIndexerString() { var verifier = CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var s = ""abcdef""; Console.WriteLine(s[new Index(1, false)]); Console.WriteLine(s[(Index)2]); Console.WriteLine(s[^1]); } }", expectedOutput: @"b c f"); verifier.VerifyIL("C.Main", @" { // Code size 76 (0x4c) .maxstack 4 .locals init (int V_0, int V_1, System.Index V_2) IL_0000: ldstr ""abcdef"" IL_0005: dup IL_0006: dup IL_0007: callvirt ""int string.Length.get"" IL_000c: stloc.0 IL_000d: ldc.i4.1 IL_000e: ldc.i4.0 IL_000f: newobj ""System.Index..ctor(int, bool)"" IL_0014: stloc.2 IL_0015: ldloca.s V_2 IL_0017: ldloc.0 IL_0018: call ""int System.Index.GetOffset(int)"" IL_001d: stloc.1 IL_001e: ldloc.1 IL_001f: callvirt ""char string.this[int].get"" IL_0024: call ""void System.Console.WriteLine(char)"" IL_0029: dup IL_002a: ldc.i4.2 IL_002b: stloc.1 IL_002c: ldloc.1 IL_002d: callvirt ""char string.this[int].get"" IL_0032: call ""void System.Console.WriteLine(char)"" IL_0037: dup IL_0038: callvirt ""int string.Length.get"" IL_003d: ldc.i4.1 IL_003e: sub IL_003f: stloc.1 IL_0040: ldloc.1 IL_0041: callvirt ""char string.this[int].get"" IL_0046: call ""void System.Console.WriteLine(char)"" IL_004b: ret }"); } [Fact] public void FakeRangeIndexerString() { var verifier = CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var s = ""abcdef""; Console.WriteLine(s[1..3]); } }", expectedOutput: "bc"); verifier.VerifyIL("C.Main", @" { // Code size 24 (0x18) .maxstack 3 .locals init (int V_0, int V_1) IL_0000: ldstr ""abcdef"" IL_0005: ldc.i4.1 IL_0006: stloc.0 IL_0007: ldc.i4.3 IL_0008: ldloc.0 IL_0009: sub IL_000a: stloc.1 IL_000b: ldloc.0 IL_000c: ldloc.1 IL_000d: callvirt ""string string.Substring(int, int)"" IL_0012: call ""void System.Console.WriteLine(string)"" IL_0017: ret }"); } [Fact, WorkItem(40776, "https://github.com/dotnet/roslyn/issues/40776")] public void FakeIndexIndexerOnDefaultStruct() { var verifier = CompileAndVerifyWithIndexAndRange(@" using System; struct NotASpan { public int Length => 1; public int this[int index] => 0; } class C { static int Repro() => default(NotASpan)[^0]; static void Main() => Repro(); }"); verifier.VerifyIL("C.Repro", @" { // Code size 25 (0x19) .maxstack 3 .locals init (int V_0, NotASpan V_1) IL_0000: ldloca.s V_1 IL_0002: dup IL_0003: initobj ""NotASpan"" IL_0009: dup IL_000a: call ""int NotASpan.Length.get"" IL_000f: ldc.i4.0 IL_0010: sub IL_0011: stloc.0 IL_0012: ldloc.0 IL_0013: call ""int NotASpan.this[int].get"" IL_0018: ret }"); } [Fact, WorkItem(40776, "https://github.com/dotnet/roslyn/issues/40776")] public void FakeIndexIndexerOnStructConstructor() { var comp = CreateCompilationWithIndexAndRangeAndSpan(@" using System; class C { static byte Repro() => new Span<byte>(new byte[] { })[^1]; }"); var verifier = CompileAndVerify(comp); verifier.VerifyIL("C.Repro", @" { // Code size 31 (0x1f) .maxstack 3 .locals init (int V_0, System.Span<byte> V_1) IL_0000: ldc.i4.0 IL_0001: newarr ""byte"" IL_0006: newobj ""System.Span<byte>..ctor(byte[])"" IL_000b: stloc.1 IL_000c: ldloca.s V_1 IL_000e: dup IL_000f: call ""int System.Span<byte>.Length.get"" IL_0014: ldc.i4.1 IL_0015: sub IL_0016: stloc.0 IL_0017: ldloc.0 IL_0018: call ""ref byte System.Span<byte>.this[int].get"" IL_001d: ldind.u1 IL_001e: ret }"); } [Fact] public void FakeRangeIndexerStringOpenEnd() { CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var s = ""abcdef""; var result = M(s); Console.WriteLine(result); } public static string M(string s) => s[1..]; }", expectedOutput: "bcdef"); } [Fact] public void FakeRangeIndexerStringOpenStart() { CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var s = ""abcdef""; var result = M(s); Console.WriteLine(result); } public static string M(string s) => s[..^2]; }", expectedOutput: "abcd"); } [Fact] public void FakeIndexIndexerArray() { var comp = CreateCompilationWithIndex(@" using System; class C { public static void Main() { var x = new[] { 1, 2, 3, 11 }; M(x); } public static void M(int[] array) { Console.WriteLine(array[new Index(1, false)]); Console.WriteLine(array[^1]); } }", TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, expectedOutput: @"2 11"); verifier.VerifyIL("C.M", @" { // Code size 40 (0x28) .maxstack 3 .locals init (int[] V_0, System.Index V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: ldc.i4.1 IL_0004: ldc.i4.0 IL_0005: newobj ""System.Index..ctor(int, bool)"" IL_000a: stloc.1 IL_000b: ldloca.s V_1 IL_000d: ldloc.0 IL_000e: ldlen IL_000f: conv.i4 IL_0010: call ""int System.Index.GetOffset(int)"" IL_0015: ldelem.i4 IL_0016: call ""void System.Console.WriteLine(int)"" IL_001b: ldarg.0 IL_001c: dup IL_001d: ldlen IL_001e: conv.i4 IL_001f: ldc.i4.1 IL_0020: sub IL_0021: ldelem.i4 IL_0022: call ""void System.Console.WriteLine(int)"" IL_0027: ret }"); } [Fact] public void SuppressNullableWarning_FakeIndexIndexerArray() { string source = @" using System; class C { public static void Main() { var x = new[] { 1, 2, 3, 11 }; M(x); } public static void M(int[] array) { Console.Write(array[new Index(1, false)!]); Console.Write(array[(^1)!]); } }"; // cover case in ConvertToArrayIndex var comp = CreateCompilationWithIndex(source, WithNullableEnable(TestOptions.DebugExe)); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "211"); } [Fact] public void FakeRangeIndexerArray() { var verifier = CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var arr = new[] { 1, 2, 3, 11 }; var result = M(arr); Console.WriteLine(result.Length); foreach (var x in result) { Console.WriteLine(x); } } public static int[] M(int[] array) => array[1..3]; }", expectedOutput: @"2 2 3"); verifier.VerifyIL("C.M", @" { // Code size 24 (0x18) .maxstack 3 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: call ""System.Index System.Index.op_Implicit(int)"" IL_0007: ldc.i4.3 IL_0008: call ""System.Index System.Index.op_Implicit(int)"" IL_000d: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0012: call ""int[] System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray<int>(int[], System.Range)"" IL_0017: ret } "); } [Fact] public void FakeRangeStartIsFromEndIndexerArray() { CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var arr = new[] { 1, 2, 3, 11 }; var result = M(arr); Console.WriteLine(result.Length); foreach (var x in result) { Console.WriteLine(x); } } public static int[] M(int[] array) => array[^2..]; }", expectedOutput: @"2 3 11"); } [Fact] public void FakeRangeBothIsFromEndIndexerArray() { CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var arr = new[] { 1, 2, 3, 11 }; var result = M(arr); Console.WriteLine(result.Length); foreach (var x in result) { Console.WriteLine(x); } } public static int[] M(int[] array) => array[^3..^1]; }", expectedOutput: @"2 2 3"); } [Fact] public void FakeRangeToEndIndexerArray() { var verifier = CompileAndVerifyWithIndexAndRange(@" using System; class C { public static void Main() { var arr = new[] { 1, 2, 3, 11 }; var result = M(arr); Console.WriteLine(result.Length); foreach (var x in result) { Console.WriteLine(x); } } public static int[] M(int[] array) => array[1..]; }", expectedOutput: @"3 2 3 11"); verifier.VerifyIL("C.M", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: call ""System.Index System.Index.op_Implicit(int)"" IL_0007: call ""System.Range System.Range.StartAt(System.Index)"" IL_000c: call ""int[] System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray<int>(int[], System.Range)"" IL_0011: ret } "); } [Fact] public void FakeRangeFromStartIndexerArray() { var comp = CreateCompilationWithIndexAndRange(@" using System; class C { public static void Main() { var arr = new[] { 1, 2, 3, 11 }; var result = M(arr); Console.WriteLine(result.Length); foreach (var x in result) { Console.WriteLine(x); } } public static int[] M(int[] array) => array[..3]; }" + TestSources.GetSubArray, TestOptions.ReleaseExe); var verifier = CompileAndVerify(comp, verify: Verification.Passes, expectedOutput: @"3 1 2 3"); verifier.VerifyIL("C.M", @" { // Code size 18 (0x12) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.3 IL_0002: call ""System.Index System.Index.op_Implicit(int)"" IL_0007: call ""System.Range System.Range.EndAt(System.Index)"" IL_000c: call ""int[] System.Runtime.CompilerServices.RuntimeHelpers.GetSubArray<int>(int[], System.Range)"" IL_0011: ret }"); } [Fact] public void LowerIndex_Int() { var compilation = CreateCompilationWithIndex(@" using System; public static class Util { public static Index Convert(int a) => ^a; }"); CompileAndVerify(compilation).VerifyIL("Util.Convert", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldc.i4.1 IL_0002: newobj ""System.Index..ctor(int, bool)"" IL_0007: ret }"); } [Fact] public void LowerIndex_NullableInt() { var compilation = CreateCompilationWithIndex(@" using System; public static class Util { public static Index? Convert(int? a) => ^a; }"); CompileAndVerify(compilation).VerifyIL("Util.Convert", @" { // Code size 40 (0x28) .maxstack 2 .locals init (int? V_0, System.Index? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool int?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""System.Index?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""int int?.GetValueOrDefault()"" IL_001c: ldc.i4.1 IL_001d: newobj ""System.Index..ctor(int, bool)"" IL_0022: newobj ""System.Index?..ctor(System.Index)"" IL_0027: ret }"); } [Fact] public void PrintIndexExpressions() { var compilation = CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { int nonNullable = 1; int? nullableValue = 2; int? nullableDefault = default; Index a = nonNullable; Console.WriteLine(""a: "" + Print(a)); Index b = ^nonNullable; Console.WriteLine(""b: "" + Print(b)); // -------------------------------------------------------- Index? c = nullableValue; Console.WriteLine(""c: "" + Print(c)); Index? d = ^nullableValue; Console.WriteLine(""d: "" + Print(d)); // -------------------------------------------------------- Index? e = nullableDefault; Console.WriteLine(""e: "" + Print(e)); Index? f = ^nullableDefault; Console.WriteLine(""f: "" + Print(f)); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @" a: value: '1', fromEnd: 'False' b: value: '1', fromEnd: 'True' c: value: '2', fromEnd: 'False' d: value: '2', fromEnd: 'True' e: default f: default"); } [Fact] public void LowerRange_Create_Index_Index() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range Create(Index start, Index end) => start..end; }"); CompileAndVerify(compilation).VerifyIL("Util.Create", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0007: ret }"); } [Fact] public void LowerRange_Create_Index_NullableIndex() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range? Create(Index start, Index? end) => start..end; }"); CompileAndVerify(compilation).VerifyIL("Util.Create", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (System.Index V_0, System.Index? V_1, System.Range? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_1 IL_0006: call ""bool System.Index?.HasValue.get"" IL_000b: brtrue.s IL_0017 IL_000d: ldloca.s V_2 IL_000f: initobj ""System.Range?"" IL_0015: ldloc.2 IL_0016: ret IL_0017: ldloc.0 IL_0018: ldloca.s V_1 IL_001a: call ""System.Index System.Index?.GetValueOrDefault()"" IL_001f: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0024: newobj ""System.Range?..ctor(System.Range)"" IL_0029: ret }"); } [Fact] public void LowerRange_Create_NullableIndex_Index() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range? Create(Index? start, Index end) => start..end; }"); CompileAndVerify(compilation).VerifyIL("Util.Create", @" { // Code size 42 (0x2a) .maxstack 2 .locals init (System.Index? V_0, System.Index V_1, System.Range? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""bool System.Index?.HasValue.get"" IL_000b: brtrue.s IL_0017 IL_000d: ldloca.s V_2 IL_000f: initobj ""System.Range?"" IL_0015: ldloc.2 IL_0016: ret IL_0017: ldloca.s V_0 IL_0019: call ""System.Index System.Index?.GetValueOrDefault()"" IL_001e: ldloc.1 IL_001f: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0024: newobj ""System.Range?..ctor(System.Range)"" IL_0029: ret }"); } [Fact] public void LowerRange_Create_NullableIndex_NullableIndex() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range? Create(Index? start, Index? end) => start..end; }"); CompileAndVerify(compilation).VerifyIL("Util.Create", @" { // Code size 56 (0x38) .maxstack 2 .locals init (System.Index? V_0, System.Index? V_1, System.Range? V_2) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldarg.1 IL_0003: stloc.1 IL_0004: ldloca.s V_0 IL_0006: call ""bool System.Index?.HasValue.get"" IL_000b: ldloca.s V_1 IL_000d: call ""bool System.Index?.HasValue.get"" IL_0012: and IL_0013: brtrue.s IL_001f IL_0015: ldloca.s V_2 IL_0017: initobj ""System.Range?"" IL_001d: ldloc.2 IL_001e: ret IL_001f: ldloca.s V_0 IL_0021: call ""System.Index System.Index?.GetValueOrDefault()"" IL_0026: ldloca.s V_1 IL_0028: call ""System.Index System.Index?.GetValueOrDefault()"" IL_002d: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0032: newobj ""System.Range?..ctor(System.Range)"" IL_0037: ret }"); } [Fact] public void LowerRange_ToEnd_Index() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range ToEnd(Index end) => ..end; }"); CompileAndVerify(compilation).VerifyIL("Util.ToEnd", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""System.Range System.Range.EndAt(System.Index)"" IL_0006: ret }"); } [Fact] public void LowerRange_ToEnd_NullableIndex() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range? ToEnd(Index? end) => ..end; }"); CompileAndVerify(compilation).VerifyIL("Util.ToEnd", @" { // Code size 39 (0x27) .maxstack 1 .locals init (System.Index? V_0, System.Range? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.Index?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""System.Range?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""System.Index System.Index?.GetValueOrDefault()"" IL_001c: call ""System.Range System.Range.EndAt(System.Index)"" IL_0021: newobj ""System.Range?..ctor(System.Range)"" IL_0026: ret }"); } [Fact] public void LowerRange_FromStart_Index() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range FromStart(Index start) => start..; }"); CompileAndVerify(compilation).VerifyIL("Util.FromStart", @" { // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""System.Range System.Range.StartAt(System.Index)"" IL_0006: ret }"); } [Fact] public void LowerRange_FromStart_NullableIndex() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range? FromStart(Index? start) => start..; }"); CompileAndVerify(compilation).VerifyIL("Util.FromStart", @" { // Code size 39 (0x27) .maxstack 1 .locals init (System.Index? V_0, System.Range? V_1) IL_0000: ldarg.0 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: call ""bool System.Index?.HasValue.get"" IL_0009: brtrue.s IL_0015 IL_000b: ldloca.s V_1 IL_000d: initobj ""System.Range?"" IL_0013: ldloc.1 IL_0014: ret IL_0015: ldloca.s V_0 IL_0017: call ""System.Index System.Index?.GetValueOrDefault()"" IL_001c: call ""System.Range System.Range.StartAt(System.Index)"" IL_0021: newobj ""System.Range?..ctor(System.Range)"" IL_0026: ret }"); } [Fact] public void LowerRange_All() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { public static Range All() => ..; }"); CompileAndVerify(compilation).VerifyIL("Util.All", @" { // Code size 6 (0x6) .maxstack 1 IL_0000: call ""System.Range System.Range.All.get"" IL_0005: ret }"); } [Fact] public void PrintRangeExpressions() { var compilation = CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Index nonNullable = 1; Index? nullableValue = 2; Index? nullableDefault = default; Range a = nonNullable..nonNullable; Console.WriteLine(""a: "" + Print(a)); Range? b = nonNullable..nullableValue; Console.WriteLine(""b: "" + Print(b)); Range? c = nonNullable..nullableDefault; Console.WriteLine(""c: "" + Print(c)); // -------------------------------------------------------- Range? d = nullableValue..nonNullable; Console.WriteLine(""d: "" + Print(d)); Range? e = nullableValue..nullableValue; Console.WriteLine(""e: "" + Print(e)); Range? f = nullableValue..nullableDefault; Console.WriteLine(""f: "" + Print(f)); // -------------------------------------------------------- Range? g = nullableDefault..nonNullable; Console.WriteLine(""g: "" + Print(g)); Range? h = nullableDefault..nullableValue; Console.WriteLine(""h: "" + Print(h)); Range? i = nullableDefault..nullableDefault; Console.WriteLine(""i: "" + Print(i)); // -------------------------------------------------------- Range? j = ..nonNullable; Console.WriteLine(""j: "" + Print(j)); Range? k = ..nullableValue; Console.WriteLine(""k: "" + Print(k)); Range? l = ..nullableDefault; Console.WriteLine(""l: "" + Print(l)); // -------------------------------------------------------- Range? m = nonNullable..; Console.WriteLine(""m: "" + Print(m)); Range? n = nullableValue..; Console.WriteLine(""n: "" + Print(n)); Range? o = nullableDefault..; Console.WriteLine(""o: "" + Print(o)); // -------------------------------------------------------- Range? p = ..; Console.WriteLine(""p: "" + Print(p)); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: @" a: value: 'value: '1', fromEnd: 'False'', fromEnd: 'value: '1', fromEnd: 'False'' b: value: 'value: '1', fromEnd: 'False'', fromEnd: 'value: '2', fromEnd: 'False'' c: default d: value: 'value: '2', fromEnd: 'False'', fromEnd: 'value: '1', fromEnd: 'False'' e: value: 'value: '2', fromEnd: 'False'', fromEnd: 'value: '2', fromEnd: 'False'' f: default g: default h: default i: default j: value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '1', fromEnd: 'False'' k: value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '2', fromEnd: 'False'' l: default m: value: 'value: '1', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'True'' n: value: 'value: '2', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'True'' o: default p: value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'True''"); } [Fact] public void PassingAsArguments() { var compilation = CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(^1)); Console.WriteLine(Print(..)); Console.WriteLine(Print(2..)); Console.WriteLine(Print(..3)); Console.WriteLine(Print(4..5)); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe).VerifyDiagnostics(); CompileAndVerify(compilation, expectedOutput: @" value: '1', fromEnd: 'True' value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'True'' value: 'value: '2', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'True'' value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '3', fromEnd: 'False'' value: 'value: '4', fromEnd: 'False'', fromEnd: 'value: '5', fromEnd: 'False''"); } [Fact] public void LowerRange_OrderOfEvaluation_Index_NullableIndex() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { static void Main() { var x = Create(); } public static Range? Create() { return GetIndex1() .. GetIndex2(); } static Index GetIndex1() { System.Console.WriteLine(""1""); return default; } static Index? GetIndex2() { System.Console.WriteLine(""2""); return new Index(1, true); } }", options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @" 1 2").VerifyIL("Util.Create", @" { // Code size 56 (0x38) .maxstack 2 .locals init (System.Index V_0, System.Index? V_1, System.Range? V_2, System.Range? V_3) IL_0000: nop IL_0001: call ""System.Index Util.GetIndex1()"" IL_0006: stloc.0 IL_0007: call ""System.Index? Util.GetIndex2()"" IL_000c: stloc.1 IL_000d: ldloca.s V_1 IL_000f: call ""bool System.Index?.HasValue.get"" IL_0014: brtrue.s IL_0021 IL_0016: ldloca.s V_2 IL_0018: initobj ""System.Range?"" IL_001e: ldloc.2 IL_001f: br.s IL_0033 IL_0021: ldloc.0 IL_0022: ldloca.s V_1 IL_0024: call ""System.Index System.Index?.GetValueOrDefault()"" IL_0029: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_002e: newobj ""System.Range?..ctor(System.Range)"" IL_0033: stloc.3 IL_0034: br.s IL_0036 IL_0036: ldloc.3 IL_0037: ret }"); } [Fact] public void LowerRange_OrderOfEvaluation_Index_Null() { var compilation = CreateCompilationWithIndexAndRange(@" using System; public static class Util { static void Main() { var x = Create(); } public static Range? Create() { return GetIndex1() .. GetIndex2(); } static Index GetIndex1() { System.Console.WriteLine(""1""); return default; } static Index? GetIndex2() { System.Console.WriteLine(""2""); return null; } }", options: TestOptions.DebugExe); CompileAndVerify(compilation, expectedOutput: @" 1 2").VerifyIL("Util.Create", @" { // Code size 56 (0x38) .maxstack 2 .locals init (System.Index V_0, System.Index? V_1, System.Range? V_2, System.Range? V_3) IL_0000: nop IL_0001: call ""System.Index Util.GetIndex1()"" IL_0006: stloc.0 IL_0007: call ""System.Index? Util.GetIndex2()"" IL_000c: stloc.1 IL_000d: ldloca.s V_1 IL_000f: call ""bool System.Index?.HasValue.get"" IL_0014: brtrue.s IL_0021 IL_0016: ldloca.s V_2 IL_0018: initobj ""System.Range?"" IL_001e: ldloc.2 IL_001f: br.s IL_0033 IL_0021: ldloc.0 IL_0022: ldloca.s V_1 IL_0024: call ""System.Index System.Index?.GetValueOrDefault()"" IL_0029: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_002e: newobj ""System.Range?..ctor(System.Range)"" IL_0033: stloc.3 IL_0034: br.s IL_0036 IL_0036: ldloc.3 IL_0037: ret }"); } [Fact] public void Index_OperandConvertibleToInt() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { byte a = 3; Index b = ^a; Console.WriteLine(Print(b)); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: '3', fromEnd: 'True'"); } [Fact] public void Index_NullableAlwaysHasValue() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create())); } static Index? Create() { // should be lowered into: new Nullable<Index>(new Index(5, fromEnd: true)) return ^new Nullable<int>(5); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: '5', fromEnd: 'True'") .VerifyIL("Program.Create", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.5 IL_0001: ldc.i4.1 IL_0002: newobj ""System.Index..ctor(int, bool)"" IL_0007: newobj ""System.Index?..ctor(System.Index)"" IL_000c: ret }"); } [Fact] public void Range_NullableAlwaysHasValue_Left() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create(^1))); } static Range? Create(Index arg) { // should be lowered into: new Nullable<Range>(Range.FromStart(arg)) return new Nullable<Index>(arg)..; } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '1', fromEnd: 'True'', fromEnd: 'value: '0', fromEnd: 'True''") .VerifyIL("Program.Create", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""System.Range System.Range.StartAt(System.Index)"" IL_0006: newobj ""System.Range?..ctor(System.Range)"" IL_000b: ret }"); } [Fact] public void Range_NullableAlwaysHasValue_Right() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create(^1))); } static Range? Create(Index arg) { // should be lowered into: new Nullable<Range>(Range.ToEnd(arg)) return ..new Nullable<Index>(arg); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '1', fromEnd: 'True''") .VerifyIL("Program.Create", @" { // Code size 12 (0xc) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""System.Range System.Range.EndAt(System.Index)"" IL_0006: newobj ""System.Range?..ctor(System.Range)"" IL_000b: ret }"); } [Fact] public void Range_NullableAlwaysHasValue_Both() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create(^2, ^1))); } static Range? Create(Index arg1, Index arg2) { // should be lowered into: new Nullable<Range>(Range.Create(arg1, arg2)) return new Nullable<Index>(arg1)..new Nullable<Index>(arg2); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '2', fromEnd: 'True'', fromEnd: 'value: '1', fromEnd: 'True''") .VerifyIL("Program.Create", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0007: newobj ""System.Range?..ctor(System.Range)"" IL_000c: ret }"); } [Fact] public void Index_NullableNeverHasValue() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create())); } static Index? Create() { // should be lowered into: new Nullable<Index>(new Index(default, fromEnd: true)) return ^new Nullable<int>(); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: '0', fromEnd: 'True'") .VerifyIL("Program.Create", @" { // Code size 13 (0xd) .maxstack 2 IL_0000: ldc.i4.0 IL_0001: ldc.i4.1 IL_0002: newobj ""System.Index..ctor(int, bool)"" IL_0007: newobj ""System.Index?..ctor(System.Index)"" IL_000c: ret }"); } [Fact] public void Range_NullableNeverhasValue_Left() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create())); } static Range? Create() { // should be lowered into: new Nullable<Range>(Range.FromStart(default)) return new Nullable<Index>()..; } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'True''") .VerifyIL("Program.Create", @" { // Code size 20 (0x14) .maxstack 1 .locals init (System.Index V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""System.Index"" IL_0008: ldloc.0 IL_0009: call ""System.Range System.Range.StartAt(System.Index)"" IL_000e: newobj ""System.Range?..ctor(System.Range)"" IL_0013: ret }"); } [Fact] public void Range_NullableNeverHasValue_Right() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create())); } static Range? Create() { // should be lowered into: new Nullable<Range>(Range.ToEnd(default)) return ..new Nullable<Index>(); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'False''") .VerifyIL("Program.Create", @" { // Code size 20 (0x14) .maxstack 1 .locals init (System.Index V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""System.Index"" IL_0008: ldloc.0 IL_0009: call ""System.Range System.Range.EndAt(System.Index)"" IL_000e: newobj ""System.Range?..ctor(System.Range)"" IL_0013: ret }"); } [Fact] public void Range_NullableNeverHasValue_Both() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create())); } static Range? Create() { // should be lowered into: new Nullable<Range>(Range.Create(default, default)) return new Nullable<Index>()..new Nullable<Index>(); } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '0', fromEnd: 'False'', fromEnd: 'value: '0', fromEnd: 'False''") .VerifyIL("Program.Create", @" { // Code size 29 (0x1d) .maxstack 2 .locals init (System.Index V_0) IL_0000: ldloca.s V_0 IL_0002: initobj ""System.Index"" IL_0008: ldloc.0 IL_0009: ldloca.s V_0 IL_000b: initobj ""System.Index"" IL_0011: ldloc.0 IL_0012: newobj ""System.Range..ctor(System.Index, System.Index)"" IL_0017: newobj ""System.Range?..ctor(System.Range)"" IL_001c: ret }"); } [Fact] public void Index_OnFunctionCall() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(^Create(5))); } static int Create(int x) => x; }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: '5', fromEnd: 'True'"); } [Fact] public void Range_OnFunctionCall() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create(1)..Create(2))); } static Index Create(int x) => ^x; }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '1', fromEnd: 'True'', fromEnd: 'value: '2', fromEnd: 'True''"); } [Fact] public void Index_OnAssignment() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { int x = default; Console.WriteLine(Print(^(x = Create(5)))); Console.WriteLine(x); } static int Create(int x) => x; }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: @" value: '5', fromEnd: 'True' 5"); } [Fact] public void Range_OnAssignment() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Index x = default, y = default; Console.WriteLine(Print((x = Create(1))..(y = Create(2)))); Console.WriteLine(Print(x)); Console.WriteLine(Print(y)); } static Index Create(int x) => ^x; }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: @" value: 'value: '1', fromEnd: 'True'', fromEnd: 'value: '2', fromEnd: 'True'' value: '1', fromEnd: 'True' value: '2', fromEnd: 'True'"); } [Fact] public void Range_OnVarOut() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { Console.WriteLine(Print(Create(1, out Index y)..y)); } static Index Create(int x, out Index y) { y = ^2; return ^x; } }" + PrintIndexesAndRangesCode, options: TestOptions.ReleaseExe), expectedOutput: "value: 'value: '1', fromEnd: 'True'', fromEnd: 'value: '2', fromEnd: 'True''"); } [Fact] public void Range_EvaluationInCondition() { CompileAndVerify(CreateCompilationWithIndexAndRange(@" using System; partial class Program { static void Main() { if ((Create(1, out int a)..Create(2, out int b)).Start.IsFromEnd && a < b) { Console.WriteLine(""YES""); } if ((Create(4, out int c)..Create(3, out int d)).Start.IsFromEnd && c < d) { Console.WriteLine(""NO""); } } static Index Create(int x, out int y) { y = x; return ^x; } }", options: TestOptions.ReleaseExe), expectedOutput: "YES"); } private const string PrintIndexesAndRangesCode = @" partial class Program { static string Print(Index arg) { return $""value: '{arg.Value}', fromEnd: '{arg.IsFromEnd}'""; } static string Print(Range arg) { return $""value: '{Print(arg.Start)}', fromEnd: '{Print(arg.End)}'""; } static string Print(Index? arg) { if (arg.HasValue) { return Print(arg.Value); } else { return ""default""; } } static string Print(Range? arg) { if (arg.HasValue) { return Print(arg.Value); } else { return ""default""; } } }"; } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/VisualStudio/CSharp/Impl/Options/Formatting/IndentationViewModel.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Windows.Controls; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// Interaction logic for FormattingIndentationOptionControl.xaml /// </summary> internal class IndentationViewModel : AbstractOptionPreviewViewModel { private const string BlockContentPreview = @" class C { //[ int Method() { int x; int y; } //] }"; private const string IndentBracePreview = @" class C { //[ int Method() { return 0; } //] }"; private const string SwitchCasePreview = @" class MyClass { int Method(int goo){ //[ switch (goo){ case 2: break; } //] } }"; private const string SwitchCaseWhenBlockPreview = @" class MyClass { int Method(int goo){ //[ switch (goo){ case 2: { break; } } //] } }"; private const string GotoLabelPreview = @" class MyClass { int Method(int goo){ //[ MyLabel: goto MyLabel; return 0; //] } }"; public IndentationViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentBlock, CSharpVSResources.Indent_block_contents, BlockContentPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentBraces, CSharpVSResources.Indent_open_and_close_braces, IndentBracePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentSwitchCaseSection, CSharpVSResources.Indent_case_contents, SwitchCasePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentSwitchCaseSectionWhenBlock, CSharpVSResources.Indent_case_contents_when_block, SwitchCaseWhenBlockPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentSwitchSection, CSharpVSResources.Indent_case_labels, SwitchCasePreview, this, optionStore)); Items.Add(new TextBlock() { Text = CSharpVSResources.Label_Indentation }); Items.Add(new RadioButtonViewModel<LabelPositionOptions>(CSharpVSResources.Place_goto_labels_in_leftmost_column, GotoLabelPreview, "goto", LabelPositionOptions.LeftMost, CSharpFormattingOptions.LabelPositioning, this, optionStore)); Items.Add(new RadioButtonViewModel<LabelPositionOptions>(CSharpVSResources.Indent_labels_normally, GotoLabelPreview, "goto", LabelPositionOptions.NoIndent, CSharpFormattingOptions.LabelPositioning, this, optionStore)); Items.Add(new RadioButtonViewModel<LabelPositionOptions>(CSharpVSResources.Place_goto_labels_one_indent_less_than_current, GotoLabelPreview, "goto", LabelPositionOptions.OneLess, CSharpFormattingOptions.LabelPositioning, this, optionStore)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Windows.Controls; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.VisualStudio.LanguageServices.Implementation.Options; namespace Microsoft.VisualStudio.LanguageServices.CSharp.Options.Formatting { /// <summary> /// Interaction logic for FormattingIndentationOptionControl.xaml /// </summary> internal class IndentationViewModel : AbstractOptionPreviewViewModel { private const string BlockContentPreview = @" class C { //[ int Method() { int x; int y; } //] }"; private const string IndentBracePreview = @" class C { //[ int Method() { return 0; } //] }"; private const string SwitchCasePreview = @" class MyClass { int Method(int goo){ //[ switch (goo){ case 2: break; } //] } }"; private const string SwitchCaseWhenBlockPreview = @" class MyClass { int Method(int goo){ //[ switch (goo){ case 2: { break; } } //] } }"; private const string GotoLabelPreview = @" class MyClass { int Method(int goo){ //[ MyLabel: goto MyLabel; return 0; //] } }"; public IndentationViewModel(OptionStore optionStore, IServiceProvider serviceProvider) : base(optionStore, serviceProvider, LanguageNames.CSharp) { Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentBlock, CSharpVSResources.Indent_block_contents, BlockContentPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentBraces, CSharpVSResources.Indent_open_and_close_braces, IndentBracePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentSwitchCaseSection, CSharpVSResources.Indent_case_contents, SwitchCasePreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentSwitchCaseSectionWhenBlock, CSharpVSResources.Indent_case_contents_when_block, SwitchCaseWhenBlockPreview, this, optionStore)); Items.Add(new CheckBoxOptionViewModel(CSharpFormattingOptions.IndentSwitchSection, CSharpVSResources.Indent_case_labels, SwitchCasePreview, this, optionStore)); Items.Add(new TextBlock() { Text = CSharpVSResources.Label_Indentation }); Items.Add(new RadioButtonViewModel<LabelPositionOptions>(CSharpVSResources.Place_goto_labels_in_leftmost_column, GotoLabelPreview, "goto", LabelPositionOptions.LeftMost, CSharpFormattingOptions.LabelPositioning, this, optionStore)); Items.Add(new RadioButtonViewModel<LabelPositionOptions>(CSharpVSResources.Indent_labels_normally, GotoLabelPreview, "goto", LabelPositionOptions.NoIndent, CSharpFormattingOptions.LabelPositioning, this, optionStore)); Items.Add(new RadioButtonViewModel<LabelPositionOptions>(CSharpVSResources.Place_goto_labels_one_indent_less_than_current, GotoLabelPreview, "goto", LabelPositionOptions.OneLess, CSharpFormattingOptions.LabelPositioning, this, optionStore)); } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/Test/Resources/Core/SymbolsTests/Interface/MDInterfaceMapping.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // csc /t:library using System; using System.Collections.Generic; using System.Linq; using System.Text; public interface IGoo { void Goo(); } public class A { public void Goo() { Console.WriteLine("A.Goo"); } } public class B : A, IGoo { } public class C : B { public new void Goo() { Console.WriteLine("C.Goo"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // csc /t:library using System; using System.Collections.Generic; using System.Linq; using System.Text; public interface IGoo { void Goo(); } public class A { public void Goo() { Console.WriteLine("A.Goo"); } } public class B : A, IGoo { } public class C : B { public new void Goo() { Console.WriteLine("C.Goo"); } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/VisualStudio/Core/Def/SymbolSearch/VisualStudioSymbolSearchService.LogService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.SymbolSearch { internal partial class VisualStudioSymbolSearchService { private class LogService : ForegroundThreadAffinitizedObject, ISymbolSearchLogService { private static readonly LinkedList<string> s_log = new(); private readonly IVsActivityLog _activityLog; public LogService(IThreadingContext threadingContext, IVsActivityLog activityLog) : base(threadingContext) { _activityLog = activityLog; } public ValueTask LogInfoAsync(string text, CancellationToken cancellationToken) => LogAsync(text, __ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION); public ValueTask LogExceptionAsync(string exception, string text, CancellationToken cancellationToken) => LogAsync(text + ". " + exception, __ACTIVITYLOG_ENTRYTYPE.ALE_ERROR); private ValueTask LogAsync(string text, __ACTIVITYLOG_ENTRYTYPE type) { Log(text, type); return default; } private void Log(string text, __ACTIVITYLOG_ENTRYTYPE type) { if (!IsForeground()) { InvokeBelowInputPriorityAsync(() => Log(text, type)); return; } AssertIsForeground(); _activityLog?.LogEntry((uint)type, SymbolSearchUpdateEngine.HostId, text); // Keep a running in memory log as well for debugging purposes. s_log.AddLast(text); while (s_log.Count > 100) { s_log.RemoveFirst(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.SymbolSearch; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.SymbolSearch { internal partial class VisualStudioSymbolSearchService { private class LogService : ForegroundThreadAffinitizedObject, ISymbolSearchLogService { private static readonly LinkedList<string> s_log = new(); private readonly IVsActivityLog _activityLog; public LogService(IThreadingContext threadingContext, IVsActivityLog activityLog) : base(threadingContext) { _activityLog = activityLog; } public ValueTask LogInfoAsync(string text, CancellationToken cancellationToken) => LogAsync(text, __ACTIVITYLOG_ENTRYTYPE.ALE_INFORMATION); public ValueTask LogExceptionAsync(string exception, string text, CancellationToken cancellationToken) => LogAsync(text + ". " + exception, __ACTIVITYLOG_ENTRYTYPE.ALE_ERROR); private ValueTask LogAsync(string text, __ACTIVITYLOG_ENTRYTYPE type) { Log(text, type); return default; } private void Log(string text, __ACTIVITYLOG_ENTRYTYPE type) { if (!IsForeground()) { InvokeBelowInputPriorityAsync(() => Log(text, type)); return; } AssertIsForeground(); _activityLog?.LogEntry((uint)type, SymbolSearchUpdateEngine.HostId, text); // Keep a running in memory log as well for debugging purposes. s_log.AddLast(text); while (s_log.Count > 100) { s_log.RemoveFirst(); } } } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Features/Core/Portable/GenerateMember/GenerateConstructor/AbstractGenerateConstructorService.State.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> { protected internal class State { private readonly TService _service; private readonly SemanticDocument _document; private readonly NamingRule _fieldNamingRule; private readonly NamingRule _propertyNamingRule; private readonly NamingRule _parameterNamingRule; private ImmutableArray<Argument> _arguments; // The type we're creating a constructor for. Will be a class or struct type. public INamedTypeSymbol? TypeToGenerateIn { get; private set; } private ImmutableArray<RefKind> _parameterRefKinds; public ImmutableArray<ITypeSymbol> ParameterTypes; public SyntaxToken Token { get; private set; } public bool IsConstructorInitializerGeneration { get; private set; } private IMethodSymbol? _delegatedConstructor; private ImmutableArray<IParameterSymbol> _parameters; private ImmutableDictionary<string, ISymbol>? _parameterToExistingMemberMap; public ImmutableDictionary<string, string> ParameterToNewFieldMap { get; private set; } public ImmutableDictionary<string, string> ParameterToNewPropertyMap { get; private set; } public bool IsContainedInUnsafeType { get; private set; } private State(TService service, SemanticDocument document, NamingRule fieldNamingRule, NamingRule propertyNamingRule, NamingRule parameterNamingRule) { _service = service; _document = document; _fieldNamingRule = fieldNamingRule; _propertyNamingRule = propertyNamingRule; _parameterNamingRule = parameterNamingRule; ParameterToNewFieldMap = ImmutableDictionary<string, string>.Empty; ParameterToNewPropertyMap = ImmutableDictionary<string, string>.Empty; } public static async Task<State?> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var fieldNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, cancellationToken).ConfigureAwait(false); var propertyNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Property, Accessibility.Public, cancellationToken).ConfigureAwait(false); var parameterNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Parameter, Accessibility.NotApplicable, cancellationToken).ConfigureAwait(false); var state = new State(service, document, fieldNamingRule, propertyNamingRule, parameterNamingRule); if (!await state.TryInitializeAsync(node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( SyntaxNode node, CancellationToken cancellationToken) { if (_service.IsConstructorInitializerGeneration(_document, node, cancellationToken)) { if (!await TryInitializeConstructorInitializerGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsSimpleNameGeneration(_document, node, cancellationToken)) { if (!await TryInitializeSimpleNameGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsImplicitObjectCreation(_document, node, cancellationToken)) { if (!await TryInitializeImplicitObjectCreationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else { return false; } Contract.ThrowIfNull(TypeToGenerateIn); if (!CodeGenerator.CanAdd(_document.Project.Solution, TypeToGenerateIn, cancellationToken)) return false; ParameterTypes = ParameterTypes.IsDefault ? GetParameterTypes(cancellationToken) : ParameterTypes; _parameterRefKinds = _arguments.SelectAsArray(a => a.RefKind); if (ClashesWithExistingConstructor()) return false; if (!TryInitializeDelegatedConstructor(cancellationToken)) InitializeNonDelegatedConstructor(cancellationToken); IsContainedInUnsafeType = _service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); return true; } private void InitializeNonDelegatedConstructor(CancellationToken cancellationToken) { var typeParametersNames = TypeToGenerateIn.GetAllTypeParameters().Select(t => t.Name).ToImmutableArray(); var parameterNames = GetParameterNames(_arguments, typeParametersNames, cancellationToken); GetParameters(_arguments, ParameterTypes, parameterNames, cancellationToken); } private ImmutableArray<ParameterName> GetParameterNames( ImmutableArray<Argument> arguments, ImmutableArray<string> typeParametersNames, CancellationToken cancellationToken) { return _service.GenerateParameterNames(_document, arguments, typeParametersNames, _parameterNamingRule, cancellationToken); } private bool TryInitializeDelegatedConstructor(CancellationToken cancellationToken) { var parameters = ParameterTypes.Zip(_parameterRefKinds, (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray(); var expressions = _arguments.SelectAsArray(a => a.Expression); var delegatedConstructor = FindConstructorToDelegateTo(parameters, expressions, cancellationToken); if (delegatedConstructor == null) return false; // Map the first N parameters to the other constructor in this type. Then // try to map any further parameters to existing fields. Finally, generate // new fields if no such parameters exist. // Find the names of the parameters that will follow the parameters we're // delegating. var argumentCount = delegatedConstructor.Parameters.Length; var remainingArguments = _arguments.Skip(argumentCount).ToImmutableArray(); var remainingParameterNames = _service.GenerateParameterNames( _document, remainingArguments, delegatedConstructor.Parameters.Select(p => p.Name).ToList(), _parameterNamingRule, cancellationToken); // Can't generate the constructor if the parameter names we're copying over forcibly // conflict with any names we generated. if (delegatedConstructor.Parameters.Select(p => p.Name).Intersect(remainingParameterNames.Select(n => n.BestNameForParameter)).Any()) return false; var remainingParameterTypes = ParameterTypes.Skip(argumentCount).ToImmutableArray(); _delegatedConstructor = delegatedConstructor; GetParameters(remainingArguments, remainingParameterTypes, remainingParameterNames, cancellationToken); return true; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> allParameters, ImmutableArray<TExpressionSyntax?> allExpressions, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); Contract.ThrowIfNull(TypeToGenerateIn.BaseType); for (var i = allParameters.Length; i > 0; i--) { var parameters = allParameters.TakeAsArray(i); var expressions = allExpressions.TakeAsArray(i); var result = FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.InstanceConstructors, cancellationToken) ?? FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.BaseType.InstanceConstructors, cancellationToken); if (result != null) return result; } return null; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, ImmutableArray<IMethodSymbol> constructors, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); foreach (var constructor in constructors) { // Don't bother delegating to an implicit constructor. We don't want to add `: base()` as that's just // redundant for subclasses and `: this()` won't even work as we won't have an implicit constructor once // we add this new constructor. if (constructor.IsImplicitlyDeclared) continue; // Don't delegate to another constructor in this type if it's got the same parameter types as the // one we're generating. This can happen if we're generating the new constructor because parameter // names don't match (when a user explicitly provides named parameters). if (TypeToGenerateIn.Equals(constructor.ContainingType) && constructor.Parameters.Select(p => p.Type).SequenceEqual(ParameterTypes)) { continue; } if (GenerateConstructorHelpers.CanDelegateTo(_document, parameters, expressions, constructor) && !_service.WillCauseConstructorCycle(this, _document, constructor, cancellationToken)) { return constructor; } } return null; } private bool ClashesWithExistingConstructor() { Contract.ThrowIfNull(TypeToGenerateIn); var destinationProvider = _document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var syntaxFacts = destinationProvider.GetRequiredService<ISyntaxFactsService>(); return TypeToGenerateIn.InstanceConstructors.Any(c => Matches(c, syntaxFacts)); } private bool Matches(IMethodSymbol ctor, ISyntaxFactsService service) { if (ctor.Parameters.Length != ParameterTypes.Length) return false; for (var i = 0; i < ParameterTypes.Length; i++) { var ctorParameter = ctor.Parameters[i]; var result = SymbolEquivalenceComparer.Instance.Equals(ctorParameter.Type, ParameterTypes[i]) && ctorParameter.RefKind == _parameterRefKinds[i]; var parameterName = GetParameterName(i); if (!string.IsNullOrEmpty(parameterName)) { result &= service.IsCaseSensitive ? ctorParameter.Name == parameterName : string.Equals(ctorParameter.Name, parameterName, StringComparison.OrdinalIgnoreCase); } if (result == false) return false; } return true; } private string GetParameterName(int index) => _arguments.IsDefault || index >= _arguments.Length ? string.Empty : _arguments[index].Name; internal ImmutableArray<ITypeSymbol> GetParameterTypes(CancellationToken cancellationToken) { var allTypeParameters = TypeToGenerateIn.GetAllTypeParameters(); var semanticModel = _document.SemanticModel; var allTypes = _arguments.Select(a => _service.GetArgumentType(_document.SemanticModel, a, cancellationToken)); return allTypes.Select(t => FixType(t, semanticModel, allTypeParameters)).ToImmutableArray(); } private static ITypeSymbol FixType(ITypeSymbol typeSymbol, SemanticModel semanticModel, IEnumerable<ITypeParameterSymbol> allTypeParameters) { var compilation = semanticModel.Compilation; return typeSymbol.RemoveAnonymousTypes(compilation) .RemoveUnavailableTypeParameters(compilation, allTypeParameters) .RemoveUnnamedErrorTypes(compilation); } private async Task<bool> TryInitializeConstructorInitializerGenerationAsync( SyntaxNode constructorInitializer, CancellationToken cancellationToken) { if (_service.TryInitializeConstructorInitializerGeneration( _document, constructorInitializer, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; IsConstructorInitializerGeneration = true; var semanticInfo = _document.SemanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeImplicitObjectCreationAsync(SyntaxNode implicitObjectCreation, CancellationToken cancellationToken) { if (_service.TryInitializeImplicitObjectCreation( _document, implicitObjectCreation, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; var semanticInfo = _document.SemanticModel.GetSymbolInfo(implicitObjectCreation, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeSimpleNameGenerationAsync( SyntaxNode simpleName, CancellationToken cancellationToken) { if (_service.TryInitializeSimpleNameGenerationState( _document, simpleName, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; } else if (_service.TryInitializeSimpleAttributeNameGenerationState( _document, simpleName, cancellationToken, out token, out arguments, out typeToGenerateIn)) { Token = token; _arguments = arguments; //// Attribute parameters are restricted to be constant values (simple types or string, etc). if (GetParameterTypes(cancellationToken).Any(t => !IsValidAttributeParameterType(t))) return false; } else { return false; } cancellationToken.ThrowIfCancellationRequested(); return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } private static bool IsValidAttributeParameterType(ITypeSymbol type) { if (type.Kind == SymbolKind.ArrayType) { var arrayType = (IArrayTypeSymbol)type; if (arrayType.Rank != 1) { return false; } type = arrayType.ElementType; } if (type.IsEnumType()) { return true; } switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_String: return true; default: return false; } } private async Task<bool> TryDetermineTypeToGenerateInAsync( INamedTypeSymbol original, CancellationToken cancellationToken) { var definition = await SymbolFinder.FindSourceDefinitionAsync(original, _document.Project.Solution, cancellationToken).ConfigureAwait(false); TypeToGenerateIn = definition as INamedTypeSymbol; return TypeToGenerateIn?.TypeKind is (TypeKind?)TypeKind.Class or (TypeKind?)TypeKind.Struct; } private void GetParameters( ImmutableArray<Argument> arguments, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<ParameterName> parameterNames, CancellationToken cancellationToken) { var parameterToExistingMemberMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>(); var parameterToNewPropertyMap = ImmutableDictionary.CreateBuilder<string, string>(); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters); for (var i = 0; i < parameterNames.Length; i++) { var parameterName = parameterNames[i]; var parameterType = parameterTypes[i]; var argument = arguments[i]; // See if there's a matching field or property we can use, or create a new member otherwise. FindExistingOrCreateNewMember( ref parameterName, parameterType, argument, parameterToExistingMemberMap, parameterToNewFieldMap, parameterToNewPropertyMap, cancellationToken); parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: argument.RefKind, isParams: false, type: parameterType, name: parameterName.BestNameForParameter)); } _parameters = parameters.ToImmutable(); _parameterToExistingMemberMap = parameterToExistingMemberMap.ToImmutable(); ParameterToNewFieldMap = parameterToNewFieldMap.ToImmutable(); ParameterToNewPropertyMap = parameterToNewPropertyMap.ToImmutable(); } private void FindExistingOrCreateNewMember( ref ParameterName parameterName, ITypeSymbol parameterType, Argument argument, ImmutableDictionary<string, ISymbol>.Builder parameterToExistingMemberMap, ImmutableDictionary<string, string>.Builder parameterToNewFieldMap, ImmutableDictionary<string, string>.Builder parameterToNewPropertyMap, CancellationToken cancellationToken) { var expectedFieldName = _fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var expectedPropertyName = _propertyNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var isFixed = argument.IsNamed; // For non-out parameters, see if there's already a field there with the same name. // If so, and it has a compatible type, then we can just assign to that field. // Otherwise, we'll need to choose a different name for this member so that it // doesn't conflict with something already in the type. First check the current type // for a matching field. If so, defer to it. var unavailableMemberNames = GetUnavailableMemberNames().ToImmutableArray(); var members = from t in TypeToGenerateIn.GetBaseTypesAndThis() let ignoreAccessibility = t.Equals(TypeToGenerateIn) from m in t.GetMembers() where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase) where ignoreAccessibility || IsSymbolAccessible(m, _document) select m; var membersArray = members.ToImmutableArray(); var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault(); if (symbol != null) { if (IsViableFieldOrProperty(parameterType, symbol)) { // Ok! We can just the existing field. parameterToExistingMemberMap[parameterName.BestNameForParameter] = symbol; } else { // Uh-oh. Now we have a problem. We can't assign this parameter to // this field. So we need to create a new field. Find a name not in // use so we can assign to that. var baseName = _service.GenerateNameForArgument(_document.SemanticModel, argument, cancellationToken); var baseFieldWithNamingStyle = _fieldNamingRule.NamingStyle.MakeCompliant(baseName).First(); var basePropertyWithNamingStyle = _propertyNamingRule.NamingStyle.MakeCompliant(baseName).First(); var newFieldName = NameGenerator.EnsureUniqueness(baseFieldWithNamingStyle, unavailableMemberNames.Concat(parameterToNewFieldMap.Values)); var newPropertyName = NameGenerator.EnsureUniqueness(basePropertyWithNamingStyle, unavailableMemberNames.Concat(parameterToNewPropertyMap.Values)); if (isFixed) { // Can't change the parameter name, so map the existing parameter // name to the new field name. parameterToNewFieldMap[parameterName.NameBasedOnArgument] = newFieldName; parameterToNewPropertyMap[parameterName.NameBasedOnArgument] = newPropertyName; } else { // Can change the parameter name, so do so. // But first remove any prefix added due to field naming styles var fieldNameMinusPrefix = newFieldName[_fieldNamingRule.NamingStyle.Prefix.Length..]; var newParameterName = new ParameterName(fieldNameMinusPrefix, isFixed: false, _parameterNamingRule); parameterName = newParameterName; parameterToNewFieldMap[newParameterName.BestNameForParameter] = newFieldName; parameterToNewPropertyMap[newParameterName.BestNameForParameter] = newPropertyName; } } return; } // If no matching field was found, use the fieldNamingRule to create suitable name var bestNameForParameter = parameterName.BestNameForParameter; var nameBasedOnArgument = parameterName.NameBasedOnArgument; parameterToNewFieldMap[bestNameForParameter] = _fieldNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); parameterToNewPropertyMap[bestNameForParameter] = _propertyNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); } private IEnumerable<string> GetUnavailableMemberNames() { Contract.ThrowIfNull(TypeToGenerateIn); return TypeToGenerateIn.MemberNames.Concat( from type in TypeToGenerateIn.GetBaseTypes() from member in type.GetMembers() select member.Name); } private bool IsViableFieldOrProperty( ITypeSymbol parameterType, ISymbol symbol) { if (parameterType.Language != symbol.Language) return false; if (symbol != null && !symbol.IsStatic) { if (symbol is IFieldSymbol field) { return !field.IsConst && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, field.Type); } else if (symbol is IPropertySymbol property) { return property.Parameters.Length == 0 && property.IsWritableInConstructor() && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, property.Type); } } return false; } public async Task<Document> GetChangedDocumentAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { // See if there's an accessible base constructor that would accept these // types, then just call into that instead of generating fields. // // then, see if there are any constructors that would take the first 'n' arguments // we've provided. If so, delegate to those, and then create a field for any // remaining arguments. Try to match from largest to smallest. // // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. return await GenerateThisOrBaseDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false) ?? await GenerateMemberDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); } private async Task<Document?> GenerateThisOrBaseDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { if (_delegatedConstructor == null) return null; Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var (members, assignments) = await GenerateMembersAndAssignmentsAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); var isThis = _delegatedConstructor.ContainingType.OriginalDefinition.Equals(TypeToGenerateIn.OriginalDefinition); var delegatingArguments = provider.GetService<SyntaxGenerator>().CreateArguments(_delegatedConstructor.Parameters); var newParameters = _delegatedConstructor.Parameters.Concat(_parameters); var generateUnsafe = !IsContainedInUnsafeType && newParameters.Any(p => p.RequiresUnsafeModifier()); var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isUnsafe: generateUnsafe), typeName: TypeToGenerateIn.Name, parameters: newParameters, statements: assignments, baseConstructorArguments: isThis ? default : delegatingArguments, thisConstructorArguments: isThis ? delegatingArguments : default); return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, members.Concat(constructor), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } private async Task<(ImmutableArray<ISymbol>, ImmutableArray<SyntaxNode>)> GenerateMembersAndAssignmentsAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var members = withFields ? SyntaxGeneratorExtensions.CreateFieldsForParameters(_parameters, ParameterToNewFieldMap, IsContainedInUnsafeType) : withProperties ? SyntaxGeneratorExtensions.CreatePropertiesForParameters(_parameters, ParameterToNewPropertyMap, IsContainedInUnsafeType) : ImmutableArray<ISymbol>.Empty; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var assignments = !withFields && !withProperties ? ImmutableArray<SyntaxNode>.Empty : provider.GetService<SyntaxGenerator>().CreateAssignmentStatements( semanticModel, _parameters, _parameterToExistingMemberMap, withFields ? ParameterToNewFieldMap : ParameterToNewPropertyMap, addNullChecks: false, preferThrowExpression: false); return (members, assignments); } private async Task<Document> GenerateMemberDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newMemberMap = withFields ? ParameterToNewFieldMap : withProperties ? ParameterToNewPropertyMap : ImmutableDictionary<string, string>.Empty; return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, provider.GetService<SyntaxGenerator>().CreateMemberDelegatingConstructor( semanticModel, TypeToGenerateIn.Name, TypeToGenerateIn, _parameters, _parameterToExistingMemberMap, newMemberMap, addNullChecks: false, preferThrowExpression: false, generateProperties: withProperties, IsContainedInUnsafeType), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Diagnostics.Analyzers.NamingStyles; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Utilities; using Microsoft.CodeAnalysis.Utilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.GenerateMember.GenerateConstructor { internal abstract partial class AbstractGenerateConstructorService<TService, TExpressionSyntax> { protected internal class State { private readonly TService _service; private readonly SemanticDocument _document; private readonly NamingRule _fieldNamingRule; private readonly NamingRule _propertyNamingRule; private readonly NamingRule _parameterNamingRule; private ImmutableArray<Argument> _arguments; // The type we're creating a constructor for. Will be a class or struct type. public INamedTypeSymbol? TypeToGenerateIn { get; private set; } private ImmutableArray<RefKind> _parameterRefKinds; public ImmutableArray<ITypeSymbol> ParameterTypes; public SyntaxToken Token { get; private set; } public bool IsConstructorInitializerGeneration { get; private set; } private IMethodSymbol? _delegatedConstructor; private ImmutableArray<IParameterSymbol> _parameters; private ImmutableDictionary<string, ISymbol>? _parameterToExistingMemberMap; public ImmutableDictionary<string, string> ParameterToNewFieldMap { get; private set; } public ImmutableDictionary<string, string> ParameterToNewPropertyMap { get; private set; } public bool IsContainedInUnsafeType { get; private set; } private State(TService service, SemanticDocument document, NamingRule fieldNamingRule, NamingRule propertyNamingRule, NamingRule parameterNamingRule) { _service = service; _document = document; _fieldNamingRule = fieldNamingRule; _propertyNamingRule = propertyNamingRule; _parameterNamingRule = parameterNamingRule; ParameterToNewFieldMap = ImmutableDictionary<string, string>.Empty; ParameterToNewPropertyMap = ImmutableDictionary<string, string>.Empty; } public static async Task<State?> GenerateAsync( TService service, SemanticDocument document, SyntaxNode node, CancellationToken cancellationToken) { var fieldNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Field, Accessibility.Private, cancellationToken).ConfigureAwait(false); var propertyNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Property, Accessibility.Public, cancellationToken).ConfigureAwait(false); var parameterNamingRule = await document.Document.GetApplicableNamingRuleAsync(SymbolKind.Parameter, Accessibility.NotApplicable, cancellationToken).ConfigureAwait(false); var state = new State(service, document, fieldNamingRule, propertyNamingRule, parameterNamingRule); if (!await state.TryInitializeAsync(node, cancellationToken).ConfigureAwait(false)) { return null; } return state; } private async Task<bool> TryInitializeAsync( SyntaxNode node, CancellationToken cancellationToken) { if (_service.IsConstructorInitializerGeneration(_document, node, cancellationToken)) { if (!await TryInitializeConstructorInitializerGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsSimpleNameGeneration(_document, node, cancellationToken)) { if (!await TryInitializeSimpleNameGenerationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else if (_service.IsImplicitObjectCreation(_document, node, cancellationToken)) { if (!await TryInitializeImplicitObjectCreationAsync(node, cancellationToken).ConfigureAwait(false)) return false; } else { return false; } Contract.ThrowIfNull(TypeToGenerateIn); if (!CodeGenerator.CanAdd(_document.Project.Solution, TypeToGenerateIn, cancellationToken)) return false; ParameterTypes = ParameterTypes.IsDefault ? GetParameterTypes(cancellationToken) : ParameterTypes; _parameterRefKinds = _arguments.SelectAsArray(a => a.RefKind); if (ClashesWithExistingConstructor()) return false; if (!TryInitializeDelegatedConstructor(cancellationToken)) InitializeNonDelegatedConstructor(cancellationToken); IsContainedInUnsafeType = _service.ContainingTypesOrSelfHasUnsafeKeyword(TypeToGenerateIn); return true; } private void InitializeNonDelegatedConstructor(CancellationToken cancellationToken) { var typeParametersNames = TypeToGenerateIn.GetAllTypeParameters().Select(t => t.Name).ToImmutableArray(); var parameterNames = GetParameterNames(_arguments, typeParametersNames, cancellationToken); GetParameters(_arguments, ParameterTypes, parameterNames, cancellationToken); } private ImmutableArray<ParameterName> GetParameterNames( ImmutableArray<Argument> arguments, ImmutableArray<string> typeParametersNames, CancellationToken cancellationToken) { return _service.GenerateParameterNames(_document, arguments, typeParametersNames, _parameterNamingRule, cancellationToken); } private bool TryInitializeDelegatedConstructor(CancellationToken cancellationToken) { var parameters = ParameterTypes.Zip(_parameterRefKinds, (t, r) => CodeGenerationSymbolFactory.CreateParameterSymbol(r, t, name: "")).ToImmutableArray(); var expressions = _arguments.SelectAsArray(a => a.Expression); var delegatedConstructor = FindConstructorToDelegateTo(parameters, expressions, cancellationToken); if (delegatedConstructor == null) return false; // Map the first N parameters to the other constructor in this type. Then // try to map any further parameters to existing fields. Finally, generate // new fields if no such parameters exist. // Find the names of the parameters that will follow the parameters we're // delegating. var argumentCount = delegatedConstructor.Parameters.Length; var remainingArguments = _arguments.Skip(argumentCount).ToImmutableArray(); var remainingParameterNames = _service.GenerateParameterNames( _document, remainingArguments, delegatedConstructor.Parameters.Select(p => p.Name).ToList(), _parameterNamingRule, cancellationToken); // Can't generate the constructor if the parameter names we're copying over forcibly // conflict with any names we generated. if (delegatedConstructor.Parameters.Select(p => p.Name).Intersect(remainingParameterNames.Select(n => n.BestNameForParameter)).Any()) return false; var remainingParameterTypes = ParameterTypes.Skip(argumentCount).ToImmutableArray(); _delegatedConstructor = delegatedConstructor; GetParameters(remainingArguments, remainingParameterTypes, remainingParameterNames, cancellationToken); return true; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> allParameters, ImmutableArray<TExpressionSyntax?> allExpressions, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); Contract.ThrowIfNull(TypeToGenerateIn.BaseType); for (var i = allParameters.Length; i > 0; i--) { var parameters = allParameters.TakeAsArray(i); var expressions = allExpressions.TakeAsArray(i); var result = FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.InstanceConstructors, cancellationToken) ?? FindConstructorToDelegateTo(parameters, expressions, TypeToGenerateIn.BaseType.InstanceConstructors, cancellationToken); if (result != null) return result; } return null; } private IMethodSymbol? FindConstructorToDelegateTo( ImmutableArray<IParameterSymbol> parameters, ImmutableArray<TExpressionSyntax?> expressions, ImmutableArray<IMethodSymbol> constructors, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); foreach (var constructor in constructors) { // Don't bother delegating to an implicit constructor. We don't want to add `: base()` as that's just // redundant for subclasses and `: this()` won't even work as we won't have an implicit constructor once // we add this new constructor. if (constructor.IsImplicitlyDeclared) continue; // Don't delegate to another constructor in this type if it's got the same parameter types as the // one we're generating. This can happen if we're generating the new constructor because parameter // names don't match (when a user explicitly provides named parameters). if (TypeToGenerateIn.Equals(constructor.ContainingType) && constructor.Parameters.Select(p => p.Type).SequenceEqual(ParameterTypes)) { continue; } if (GenerateConstructorHelpers.CanDelegateTo(_document, parameters, expressions, constructor) && !_service.WillCauseConstructorCycle(this, _document, constructor, cancellationToken)) { return constructor; } } return null; } private bool ClashesWithExistingConstructor() { Contract.ThrowIfNull(TypeToGenerateIn); var destinationProvider = _document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var syntaxFacts = destinationProvider.GetRequiredService<ISyntaxFactsService>(); return TypeToGenerateIn.InstanceConstructors.Any(c => Matches(c, syntaxFacts)); } private bool Matches(IMethodSymbol ctor, ISyntaxFactsService service) { if (ctor.Parameters.Length != ParameterTypes.Length) return false; for (var i = 0; i < ParameterTypes.Length; i++) { var ctorParameter = ctor.Parameters[i]; var result = SymbolEquivalenceComparer.Instance.Equals(ctorParameter.Type, ParameterTypes[i]) && ctorParameter.RefKind == _parameterRefKinds[i]; var parameterName = GetParameterName(i); if (!string.IsNullOrEmpty(parameterName)) { result &= service.IsCaseSensitive ? ctorParameter.Name == parameterName : string.Equals(ctorParameter.Name, parameterName, StringComparison.OrdinalIgnoreCase); } if (result == false) return false; } return true; } private string GetParameterName(int index) => _arguments.IsDefault || index >= _arguments.Length ? string.Empty : _arguments[index].Name; internal ImmutableArray<ITypeSymbol> GetParameterTypes(CancellationToken cancellationToken) { var allTypeParameters = TypeToGenerateIn.GetAllTypeParameters(); var semanticModel = _document.SemanticModel; var allTypes = _arguments.Select(a => _service.GetArgumentType(_document.SemanticModel, a, cancellationToken)); return allTypes.Select(t => FixType(t, semanticModel, allTypeParameters)).ToImmutableArray(); } private static ITypeSymbol FixType(ITypeSymbol typeSymbol, SemanticModel semanticModel, IEnumerable<ITypeParameterSymbol> allTypeParameters) { var compilation = semanticModel.Compilation; return typeSymbol.RemoveAnonymousTypes(compilation) .RemoveUnavailableTypeParameters(compilation, allTypeParameters) .RemoveUnnamedErrorTypes(compilation); } private async Task<bool> TryInitializeConstructorInitializerGenerationAsync( SyntaxNode constructorInitializer, CancellationToken cancellationToken) { if (_service.TryInitializeConstructorInitializerGeneration( _document, constructorInitializer, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; IsConstructorInitializerGeneration = true; var semanticInfo = _document.SemanticModel.GetSymbolInfo(constructorInitializer, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeImplicitObjectCreationAsync(SyntaxNode implicitObjectCreation, CancellationToken cancellationToken) { if (_service.TryInitializeImplicitObjectCreation( _document, implicitObjectCreation, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; var semanticInfo = _document.SemanticModel.GetSymbolInfo(implicitObjectCreation, cancellationToken); if (semanticInfo.Symbol == null) return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } return false; } private async Task<bool> TryInitializeSimpleNameGenerationAsync( SyntaxNode simpleName, CancellationToken cancellationToken) { if (_service.TryInitializeSimpleNameGenerationState( _document, simpleName, cancellationToken, out var token, out var arguments, out var typeToGenerateIn)) { Token = token; _arguments = arguments; } else if (_service.TryInitializeSimpleAttributeNameGenerationState( _document, simpleName, cancellationToken, out token, out arguments, out typeToGenerateIn)) { Token = token; _arguments = arguments; //// Attribute parameters are restricted to be constant values (simple types or string, etc). if (GetParameterTypes(cancellationToken).Any(t => !IsValidAttributeParameterType(t))) return false; } else { return false; } cancellationToken.ThrowIfCancellationRequested(); return await TryDetermineTypeToGenerateInAsync(typeToGenerateIn, cancellationToken).ConfigureAwait(false); } private static bool IsValidAttributeParameterType(ITypeSymbol type) { if (type.Kind == SymbolKind.ArrayType) { var arrayType = (IArrayTypeSymbol)type; if (arrayType.Rank != 1) { return false; } type = arrayType.ElementType; } if (type.IsEnumType()) { return true; } switch (type.SpecialType) { case SpecialType.System_Boolean: case SpecialType.System_Byte: case SpecialType.System_Char: case SpecialType.System_Int16: case SpecialType.System_Int32: case SpecialType.System_Int64: case SpecialType.System_Double: case SpecialType.System_Single: case SpecialType.System_String: return true; default: return false; } } private async Task<bool> TryDetermineTypeToGenerateInAsync( INamedTypeSymbol original, CancellationToken cancellationToken) { var definition = await SymbolFinder.FindSourceDefinitionAsync(original, _document.Project.Solution, cancellationToken).ConfigureAwait(false); TypeToGenerateIn = definition as INamedTypeSymbol; return TypeToGenerateIn?.TypeKind is (TypeKind?)TypeKind.Class or (TypeKind?)TypeKind.Struct; } private void GetParameters( ImmutableArray<Argument> arguments, ImmutableArray<ITypeSymbol> parameterTypes, ImmutableArray<ParameterName> parameterNames, CancellationToken cancellationToken) { var parameterToExistingMemberMap = ImmutableDictionary.CreateBuilder<string, ISymbol>(); var parameterToNewFieldMap = ImmutableDictionary.CreateBuilder<string, string>(); var parameterToNewPropertyMap = ImmutableDictionary.CreateBuilder<string, string>(); using var _ = ArrayBuilder<IParameterSymbol>.GetInstance(out var parameters); for (var i = 0; i < parameterNames.Length; i++) { var parameterName = parameterNames[i]; var parameterType = parameterTypes[i]; var argument = arguments[i]; // See if there's a matching field or property we can use, or create a new member otherwise. FindExistingOrCreateNewMember( ref parameterName, parameterType, argument, parameterToExistingMemberMap, parameterToNewFieldMap, parameterToNewPropertyMap, cancellationToken); parameters.Add(CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, refKind: argument.RefKind, isParams: false, type: parameterType, name: parameterName.BestNameForParameter)); } _parameters = parameters.ToImmutable(); _parameterToExistingMemberMap = parameterToExistingMemberMap.ToImmutable(); ParameterToNewFieldMap = parameterToNewFieldMap.ToImmutable(); ParameterToNewPropertyMap = parameterToNewPropertyMap.ToImmutable(); } private void FindExistingOrCreateNewMember( ref ParameterName parameterName, ITypeSymbol parameterType, Argument argument, ImmutableDictionary<string, ISymbol>.Builder parameterToExistingMemberMap, ImmutableDictionary<string, string>.Builder parameterToNewFieldMap, ImmutableDictionary<string, string>.Builder parameterToNewPropertyMap, CancellationToken cancellationToken) { var expectedFieldName = _fieldNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var expectedPropertyName = _propertyNamingRule.NamingStyle.MakeCompliant(parameterName.NameBasedOnArgument).First(); var isFixed = argument.IsNamed; // For non-out parameters, see if there's already a field there with the same name. // If so, and it has a compatible type, then we can just assign to that field. // Otherwise, we'll need to choose a different name for this member so that it // doesn't conflict with something already in the type. First check the current type // for a matching field. If so, defer to it. var unavailableMemberNames = GetUnavailableMemberNames().ToImmutableArray(); var members = from t in TypeToGenerateIn.GetBaseTypesAndThis() let ignoreAccessibility = t.Equals(TypeToGenerateIn) from m in t.GetMembers() where m.Name.Equals(expectedFieldName, StringComparison.OrdinalIgnoreCase) where ignoreAccessibility || IsSymbolAccessible(m, _document) select m; var membersArray = members.ToImmutableArray(); var symbol = membersArray.FirstOrDefault(m => m.Name.Equals(expectedFieldName, StringComparison.Ordinal)) ?? membersArray.FirstOrDefault(); if (symbol != null) { if (IsViableFieldOrProperty(parameterType, symbol)) { // Ok! We can just the existing field. parameterToExistingMemberMap[parameterName.BestNameForParameter] = symbol; } else { // Uh-oh. Now we have a problem. We can't assign this parameter to // this field. So we need to create a new field. Find a name not in // use so we can assign to that. var baseName = _service.GenerateNameForArgument(_document.SemanticModel, argument, cancellationToken); var baseFieldWithNamingStyle = _fieldNamingRule.NamingStyle.MakeCompliant(baseName).First(); var basePropertyWithNamingStyle = _propertyNamingRule.NamingStyle.MakeCompliant(baseName).First(); var newFieldName = NameGenerator.EnsureUniqueness(baseFieldWithNamingStyle, unavailableMemberNames.Concat(parameterToNewFieldMap.Values)); var newPropertyName = NameGenerator.EnsureUniqueness(basePropertyWithNamingStyle, unavailableMemberNames.Concat(parameterToNewPropertyMap.Values)); if (isFixed) { // Can't change the parameter name, so map the existing parameter // name to the new field name. parameterToNewFieldMap[parameterName.NameBasedOnArgument] = newFieldName; parameterToNewPropertyMap[parameterName.NameBasedOnArgument] = newPropertyName; } else { // Can change the parameter name, so do so. // But first remove any prefix added due to field naming styles var fieldNameMinusPrefix = newFieldName[_fieldNamingRule.NamingStyle.Prefix.Length..]; var newParameterName = new ParameterName(fieldNameMinusPrefix, isFixed: false, _parameterNamingRule); parameterName = newParameterName; parameterToNewFieldMap[newParameterName.BestNameForParameter] = newFieldName; parameterToNewPropertyMap[newParameterName.BestNameForParameter] = newPropertyName; } } return; } // If no matching field was found, use the fieldNamingRule to create suitable name var bestNameForParameter = parameterName.BestNameForParameter; var nameBasedOnArgument = parameterName.NameBasedOnArgument; parameterToNewFieldMap[bestNameForParameter] = _fieldNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); parameterToNewPropertyMap[bestNameForParameter] = _propertyNamingRule.NamingStyle.MakeCompliant(nameBasedOnArgument).First(); } private IEnumerable<string> GetUnavailableMemberNames() { Contract.ThrowIfNull(TypeToGenerateIn); return TypeToGenerateIn.MemberNames.Concat( from type in TypeToGenerateIn.GetBaseTypes() from member in type.GetMembers() select member.Name); } private bool IsViableFieldOrProperty( ITypeSymbol parameterType, ISymbol symbol) { if (parameterType.Language != symbol.Language) return false; if (symbol != null && !symbol.IsStatic) { if (symbol is IFieldSymbol field) { return !field.IsConst && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, field.Type); } else if (symbol is IPropertySymbol property) { return property.Parameters.Length == 0 && property.IsWritableInConstructor() && _service.IsConversionImplicit(_document.SemanticModel.Compilation, parameterType, property.Type); } } return false; } public async Task<Document> GetChangedDocumentAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { // See if there's an accessible base constructor that would accept these // types, then just call into that instead of generating fields. // // then, see if there are any constructors that would take the first 'n' arguments // we've provided. If so, delegate to those, and then create a field for any // remaining arguments. Try to match from largest to smallest. // // Otherwise, just generate a normal constructor that assigns any provided // parameters into fields. return await GenerateThisOrBaseDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false) ?? await GenerateMemberDelegatingConstructorAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); } private async Task<Document?> GenerateThisOrBaseDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { if (_delegatedConstructor == null) return null; Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var (members, assignments) = await GenerateMembersAndAssignmentsAsync(document, withFields, withProperties, cancellationToken).ConfigureAwait(false); var isThis = _delegatedConstructor.ContainingType.OriginalDefinition.Equals(TypeToGenerateIn.OriginalDefinition); var delegatingArguments = provider.GetService<SyntaxGenerator>().CreateArguments(_delegatedConstructor.Parameters); var newParameters = _delegatedConstructor.Parameters.Concat(_parameters); var generateUnsafe = !IsContainedInUnsafeType && newParameters.Any(p => p.RequiresUnsafeModifier()); var constructor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility: Accessibility.Public, modifiers: new DeclarationModifiers(isUnsafe: generateUnsafe), typeName: TypeToGenerateIn.Name, parameters: newParameters, statements: assignments, baseConstructorArguments: isThis ? default : delegatingArguments, thisConstructorArguments: isThis ? delegatingArguments : default); return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, members.Concat(constructor), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } private async Task<(ImmutableArray<ISymbol>, ImmutableArray<SyntaxNode>)> GenerateMembersAndAssignmentsAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var members = withFields ? SyntaxGeneratorExtensions.CreateFieldsForParameters(_parameters, ParameterToNewFieldMap, IsContainedInUnsafeType) : withProperties ? SyntaxGeneratorExtensions.CreatePropertiesForParameters(_parameters, ParameterToNewPropertyMap, IsContainedInUnsafeType) : ImmutableArray<ISymbol>.Empty; var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false); var assignments = !withFields && !withProperties ? ImmutableArray<SyntaxNode>.Empty : provider.GetService<SyntaxGenerator>().CreateAssignmentStatements( semanticModel, _parameters, _parameterToExistingMemberMap, withFields ? ParameterToNewFieldMap : ParameterToNewPropertyMap, addNullChecks: false, preferThrowExpression: false); return (members, assignments); } private async Task<Document> GenerateMemberDelegatingConstructorAsync( Document document, bool withFields, bool withProperties, CancellationToken cancellationToken) { Contract.ThrowIfNull(TypeToGenerateIn); var provider = document.Project.Solution.Workspace.Services.GetLanguageServices(TypeToGenerateIn.Language); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var newMemberMap = withFields ? ParameterToNewFieldMap : withProperties ? ParameterToNewPropertyMap : ImmutableDictionary<string, string>.Empty; return await provider.GetRequiredService<ICodeGenerationService>().AddMembersAsync( document.Project.Solution, TypeToGenerateIn, provider.GetService<SyntaxGenerator>().CreateMemberDelegatingConstructor( semanticModel, TypeToGenerateIn.Name, TypeToGenerateIn, _parameters, _parameterToExistingMemberMap, newMemberMap, addNullChecks: false, preferThrowExpression: false, generateProperties: withProperties, IsContainedInUnsafeType), new CodeGenerationOptions( Token.GetLocation(), options: await document.GetOptionsAsync(cancellationToken).ConfigureAwait(false)), cancellationToken).ConfigureAwait(false); } } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/CSharp/Portable/Symbols/Attributes/WellKnownAttributeData/PropertyEarlyWellKnownAttributeData.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Information decoded from early well-known custom attributes applied on a property. /// </summary> internal sealed class PropertyEarlyWellKnownAttributeData : CommonPropertyEarlyWellKnownAttributeData { #region IndexerNameAttribute private string _indexerName; public string IndexerName { get { VerifySealed(expected: true); return _indexerName; } set { VerifySealed(expected: false); Debug.Assert(value != null); // This can be false if there are duplicate IndexerNameAttributes. // Just ignore the second one and let a later pass report an // appropriate diagnostic. if (_indexerName == null) { _indexerName = value; SetDataStored(); } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Symbols { /// <summary> /// Information decoded from early well-known custom attributes applied on a property. /// </summary> internal sealed class PropertyEarlyWellKnownAttributeData : CommonPropertyEarlyWellKnownAttributeData { #region IndexerNameAttribute private string _indexerName; public string IndexerName { get { VerifySealed(expected: true); return _indexerName; } set { VerifySealed(expected: false); Debug.Assert(value != null); // This can be false if there are duplicate IndexerNameAttributes. // Just ignore the second one and let a later pass report an // appropriate diagnostic. if (_indexerName == null) { _indexerName = value; SetDataStored(); } } } #endregion } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/EditorFeatures/CSharpTest/Diagnostics/Configuration/ConfigureSeverity/CodeStyleOptionBasedSeverityConfigurationTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity; using Microsoft.CodeAnalysis.CSharp.UseObjectInitializer; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureSeverity { public abstract partial class CodeStyleOptionBasedSeverityConfigurationTests : AbstractSuppressionDiagnosticTest { protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CSharpUseObjectInitializerDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider()); } public class NoneConfigurationTests : CodeStyleOptionBasedSeverityConfigurationTests { protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_style_object_initializer = true:suggestion ; Comment2 dotnet_diagnostic.IDE0017.severity = suggestion ;; Comment3 </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_style_object_initializer = true:none ; Comment2 dotnet_diagnostic.IDE0017.severity = none ;; Comment3 </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.IDE0017.severity = suggestion [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainOption_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_object_initializer = true:suggestion dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_object_initializer = true:none dotnet_diagnostic.IDE0017.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = true:suggestion dotnet_diagnostic.IDE0017.severityyy = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = true:suggestion dotnet_diagnostic.IDE0017.severityyy = suggestion # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } public class SilentConfigurationTests : CodeStyleOptionBasedSeverityConfigurationTests { protected override int CodeActionIndex => 1; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_Silent() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_Silent() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } public class SuggestionConfigurationTests : CodeStyleOptionBasedSeverityConfigurationTests { protected override int CodeActionIndex => 2; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_Suggestion() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_Suggestion() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:suggestion dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } public class WarningConfigurationTests : CodeStyleOptionBasedSeverityConfigurationTests { protected override int CodeActionIndex => 3; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_Warning() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_Warning() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } public class ErrorConfigurationTests : CodeStyleOptionBasedSeverityConfigurationTests { protected override int CodeActionIndex => 4; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_CodeStyleBased_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:error # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_SeverityBased_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_CodeStyleAndSeverityBased_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:suggestion dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.IDE0017.severity = suggestion [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = true:warning dotnet_diagnostic.IDE0017.severityyy = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = true:warning dotnet_diagnostic.IDE0017.severityyy = suggestion # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ConcreteHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_NestedDirectory_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_NestedDirectoryNestedHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[ParentFolder/File.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[ParentFolder/File.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_NestedDirectoryIncorrectHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[ParentFolderr/File.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[ParentFolderr/File.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = warning [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_IncorrectExtension_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.vb] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.vb] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_HeaderRegex_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[Parent*r/Fil*.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[Parent*r/Fil*.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_HeaderAllFiles_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MultipleHeaders_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.vb] dotnet_diagnostic.IDE0017.severity = warning [File.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning [cs.vb] dotnet_diagnostic.IDE0017.severity = warning [test.test] dotnet_diagnostic.IDE0017.severity = warning [WrongName.cs] dotnet_diagnostic.IDE0017.severity = warning [WrongName2.cs] dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.vb] dotnet_diagnostic.IDE0017.severity = warning [File.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error [cs.vb] dotnet_diagnostic.IDE0017.severity = warning [test.test] dotnet_diagnostic.IDE0017.severity = warning [WrongName.cs] dotnet_diagnostic.IDE0017.severity = warning [WrongName2.cs] dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexPartialMatch_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[gram.cs] dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[gram.cs] dotnet_diagnostic.IDE0017.severity = warning [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_VerifyCaseInsensitive_Warning() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\PARENTfoldeR/ProGRAM.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[PROgram.cs] dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\PARENTfoldeR/ProGRAM.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[PROgram.cs] dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_DuplicateRule_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning [Program.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning [Program.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ChooseBestHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] dotnet_style_qualification_for_field = false:silent [*.cs] csharp_style_expression_bodied_methods = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] dotnet_style_qualification_for_field = false:silent # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error [*.cs] csharp_style_expression_bodied_methods = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ChooseBestHeaderReversed_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = false:silent [*.{cs,vb}] dotnet_style_qualification_for_field = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = false:silent [*.{cs,vb}] dotnet_style_qualification_for_field = false:silent # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_DotFileName_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/Test.file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[Test.file.cs] # IDE0017: Simplify object initialization dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/Test.file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[Test.file.cs] # IDE0017: Simplify object initialization dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Configuration.ConfigureSeverity; using Microsoft.CodeAnalysis.CSharp.UseObjectInitializer; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.Configuration.ConfigureSeverity { public abstract partial class CodeStyleOptionBasedSeverityConfigurationTests : AbstractSuppressionDiagnosticTest { protected internal override string GetLanguage() => LanguageNames.CSharp; protected override ParseOptions GetScriptOptions() => Options.Script; internal override Tuple<DiagnosticAnalyzer, IConfigurationFixProvider> CreateDiagnosticProviderAndFixer(Workspace workspace) { return new Tuple<DiagnosticAnalyzer, IConfigurationFixProvider>( new CSharpUseObjectInitializerDiagnosticAnalyzer(), new ConfigureSeverityLevelCodeFixProvider()); } public class NoneConfigurationTests : CodeStyleOptionBasedSeverityConfigurationTests { protected override int CodeActionIndex => 0; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_style_object_initializer = true:suggestion ; Comment2 dotnet_diagnostic.IDE0017.severity = suggestion ;; Comment3 </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] # Comment1 dotnet_style_object_initializer = true:none ; Comment2 dotnet_diagnostic.IDE0017.severity = none ;; Comment3 </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.IDE0017.severity = suggestion [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MaintainOption_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_object_initializer = true:suggestion dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{vb,cs}] dotnet_style_object_initializer = true:none dotnet_diagnostic.IDE0017.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_None() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = true:suggestion dotnet_diagnostic.IDE0017.severityyy = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = true:suggestion dotnet_diagnostic.IDE0017.severityyy = suggestion # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = none </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } public class SilentConfigurationTests : CodeStyleOptionBasedSeverityConfigurationTests { protected override int CodeActionIndex => 1; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_Silent() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_Silent() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } public class SuggestionConfigurationTests : CodeStyleOptionBasedSeverityConfigurationTests { protected override int CodeActionIndex => 2; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_Suggestion() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_Suggestion() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:suggestion dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } public class WarningConfigurationTests : CodeStyleOptionBasedSeverityConfigurationTests { protected override int CodeActionIndex => 3; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_Warning() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_Warning() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } public class ErrorConfigurationTests : CodeStyleOptionBasedSeverityConfigurationTests { protected override int CodeActionIndex => 4; [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_Empty_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig""></AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_CodeStyleBased_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:error # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_SeverityBased_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RuleExists_CodeStyleAndSeverityBased_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:suggestion dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = new Customer(); obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.vb] dotnet_diagnostic.IDE0017.severity = suggestion [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_InvalidRule_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = true:warning dotnet_diagnostic.IDE0017.severityyy = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializerr = true:warning dotnet_diagnostic.IDE0017.severityyy = suggestion # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ConcreteHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_NestedDirectory_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_NestedDirectoryNestedHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[ParentFolder/File.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[ParentFolder/File.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_NestedDirectoryIncorrectHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[ParentFolderr/File.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[ParentFolderr/File.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = warning [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_IncorrectExtension_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.vb] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.vb] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_HeaderRegex_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[Parent*r/Fil*.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[Parent*r/Fil*.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_HeaderAllFiles_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = suggestion </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_MultipleHeaders_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.vb] dotnet_diagnostic.IDE0017.severity = warning [File.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning [cs.vb] dotnet_diagnostic.IDE0017.severity = warning [test.test] dotnet_diagnostic.IDE0017.severity = warning [WrongName.cs] dotnet_diagnostic.IDE0017.severity = warning [WrongName2.cs] dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/File.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[File.vb] dotnet_diagnostic.IDE0017.severity = warning [File.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error [cs.vb] dotnet_diagnostic.IDE0017.severity = warning [test.test] dotnet_diagnostic.IDE0017.severity = warning [WrongName.cs] dotnet_diagnostic.IDE0017.severity = warning [WrongName2.cs] dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_RegexPartialMatch_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[gram.cs] dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\ParentFolder/Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[gram.cs] dotnet_diagnostic.IDE0017.severity = warning [*.{cs,vb}] # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_VerifyCaseInsensitive_Warning() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\PARENTfoldeR/ProGRAM.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[PROgram.cs] dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\PARENTfoldeR/ProGRAM.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[PROgram.cs] dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_DuplicateRule_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning [Program.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning [Program.cs] dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ChooseBestHeader_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] dotnet_style_qualification_for_field = false:silent [*.cs] csharp_style_expression_bodied_methods = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.{cs,vb}] dotnet_style_qualification_for_field = false:silent # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error [*.cs] csharp_style_expression_bodied_methods = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_ChooseBestHeaderReversed_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = false:silent [*.{cs,vb}] dotnet_style_qualification_for_field = false:silent </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[*.cs] csharp_style_expression_bodied_methods = false:silent [*.{cs,vb}] dotnet_style_qualification_for_field = false:silent # IDE0017: Simplify object initialization dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } [ConditionalFact(typeof(IsEnglishLocal)), Trait(Traits.Feature, Traits.Features.CodeActionsConfiguration)] public async Task ConfigureEditorconfig_DotFileName_Error() { var input = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/Test.file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[Test.file.cs] # IDE0017: Simplify object initialization dotnet_style_object_initializer = true:warning dotnet_diagnostic.IDE0017.severity = warning </AnalyzerConfigDocument> </Project> </Workspace>"; var expected = @" <Workspace> <Project Language=""C#"" AssemblyName=""Assembly1"" CommonReferences=""true""> <Document FilePath=""z:\\Program/Test.file.cs""> class Program1 { static void Main() { // dotnet_style_object_initializer = true var obj = new Customer() { _age = 21 }; // dotnet_style_object_initializer = false Customer obj2 = [|new Customer()|]; obj2._age = 21; } internal class Customer { public int _age; public Customer() { } } } </Document> <AnalyzerConfigDocument FilePath=""z:\\.editorconfig"">[Test.file.cs] # IDE0017: Simplify object initialization dotnet_style_object_initializer = true:error dotnet_diagnostic.IDE0017.severity = error </AnalyzerConfigDocument> </Project> </Workspace>"; await TestInRegularAndScriptAsync(input, expected, CodeActionIndex); } } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/EditorFeatures/CSharp/Highlighting/KeywordHighlighters/UnsafeStatementHighlighter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp)] internal class UnsafeStatementHighlighter : AbstractKeywordHighlighter<UnsafeStatementSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UnsafeStatementHighlighter() { } protected override void AddHighlights(UnsafeStatementSyntax unsafeStatement, List<TextSpan> highlights, CancellationToken cancellationToken) => highlights.Add(unsafeStatement.UnsafeKeyword.Span); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.ComponentModel.Composition; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.Implementation.Highlighting; using Microsoft.CodeAnalysis.Host.Mef; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Editor.CSharp.KeywordHighlighting.KeywordHighlighters { [ExportHighlighter(LanguageNames.CSharp)] internal class UnsafeStatementHighlighter : AbstractKeywordHighlighter<UnsafeStatementSyntax> { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public UnsafeStatementHighlighter() { } protected override void AddHighlights(UnsafeStatementSyntax unsafeStatement, List<TextSpan> highlights, CancellationToken cancellationToken) => highlights.Add(unsafeStatement.UnsafeKeyword.Span); } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/Core/CodeAnalysisTest/Collections/CachingFactoryTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public class CachingFactoryTests { private sealed class CacheKey { public CacheKey(int value) { this.Value = value; } public readonly int Value; public static int GetHashCode(CacheKey key) { return key.Value; } } private sealed class CacheValue { public CacheValue(int value) { this.Value = value; } public readonly int Value; } [WorkItem(620704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620704")] [Fact] public void ZeroHash() { var cache = new CachingFactory<CacheKey, CacheValue>(512, k => new CacheValue(k.Value + 1), k => k.Value, (k, v) => k.Value == v.Value); var key = new CacheKey(0); Assert.Equal(0, CacheKey.GetHashCode(key)); CacheValue value; bool found = cache.TryGetValue(key, out value); Assert.False(found); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.Collections { public class CachingFactoryTests { private sealed class CacheKey { public CacheKey(int value) { this.Value = value; } public readonly int Value; public static int GetHashCode(CacheKey key) { return key.Value; } } private sealed class CacheValue { public CacheValue(int value) { this.Value = value; } public readonly int Value; } [WorkItem(620704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/620704")] [Fact] public void ZeroHash() { var cache = new CachingFactory<CacheKey, CacheValue>(512, k => new CacheValue(k.Value + 1), k => k.Value, (k, v) => k.Value == v.Value); var key = new CacheKey(0); Assert.Equal(0, CacheKey.GetHashCode(key)); CacheValue value; bool found = cache.TryGetValue(key, out value); Assert.False(found); } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ITypeSymbolExtensions.TypeSyntaxGeneratorVisitor.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal partial class ITypeSymbolExtensions { private class TypeSyntaxGeneratorVisitor : SymbolVisitor<TypeSyntax> { private readonly bool _nameOnly; private static readonly TypeSyntaxGeneratorVisitor NameOnlyInstance = new(nameOnly: true); private static readonly TypeSyntaxGeneratorVisitor NotNameOnlyInstance = new(nameOnly: false); private TypeSyntaxGeneratorVisitor(bool nameOnly) => _nameOnly = nameOnly; public static TypeSyntaxGeneratorVisitor Create(bool nameOnly = false) => nameOnly ? NameOnlyInstance : NotNameOnlyInstance; public override TypeSyntax DefaultVisit(ISymbol node) => throw new NotImplementedException(); private static TTypeSyntax AddInformationTo<TTypeSyntax>(TTypeSyntax syntax, ISymbol symbol) where TTypeSyntax : TypeSyntax { syntax = syntax.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker); syntax = syntax.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol)); return syntax; } public override TypeSyntax VisitAlias(IAliasSymbol symbol) => AddInformationTo(symbol.Name.ToIdentifierName(), symbol); private void ThrowIfNameOnly() { if (_nameOnly) { throw new InvalidOperationException("This symbol cannot be converted into a NameSyntax"); } } public override TypeSyntax VisitArrayType(IArrayTypeSymbol symbol) { ThrowIfNameOnly(); ITypeSymbol underlyingType = symbol; while (underlyingType is IArrayTypeSymbol innerArray) { underlyingType = innerArray.ElementType; if (underlyingType.NullableAnnotation == NullableAnnotation.Annotated) { // If the inner array we just moved to is also nullable, then // we must terminate the digging now so we produce the syntax for that, // and then append the ranks we passed through at the end. This is because // nullability annotations acts as a "barrier" where we won't reorder array // through. So whereas: // // string[][,] // // is really an array of rank 1 that has an element of rank 2, // // string[]?[,] // // is really an array of rank 2 that has nullable elements of rank 1. break; } } var elementTypeSyntax = underlyingType.GenerateTypeSyntax(); using var _ = ArrayBuilder<ArrayRankSpecifierSyntax>.GetInstance(out var ranks); var arrayType = symbol; while (arrayType != null && !arrayType.Equals(underlyingType)) { ranks.Add(SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.SeparatedList(Enumerable.Repeat<ExpressionSyntax>(SyntaxFactory.OmittedArraySizeExpression(), arrayType.Rank)))); arrayType = arrayType.ElementType as IArrayTypeSymbol; } TypeSyntax arrayTypeSyntax = SyntaxFactory.ArrayType(elementTypeSyntax, ranks.ToSyntaxList()); if (symbol.NullableAnnotation == NullableAnnotation.Annotated) { arrayTypeSyntax = SyntaxFactory.NullableType(arrayTypeSyntax); } return AddInformationTo(arrayTypeSyntax, symbol); } public override TypeSyntax VisitDynamicType(IDynamicTypeSymbol symbol) => AddInformationTo(SyntaxFactory.IdentifierName("dynamic"), symbol); public static bool TryCreateNativeIntegerType(INamedTypeSymbol symbol, [NotNullWhen(true)] out TypeSyntax? syntax) { if (symbol.IsNativeIntegerType) { syntax = SyntaxFactory.IdentifierName(symbol.SpecialType == SpecialType.System_IntPtr ? "nint" : "nuint"); return true; } syntax = null; return false; } public override TypeSyntax VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { FunctionPointerCallingConventionSyntax? callingConventionSyntax = null; // For varargs there is no C# syntax. You get a use-site diagnostic if you attempt to use it, and just // making a default-convention symbol is likely good enough. This is only observable through metadata // that always be uncompilable in C# anyway. if (symbol.Signature.CallingConvention != System.Reflection.Metadata.SignatureCallingConvention.Default && symbol.Signature.CallingConvention != System.Reflection.Metadata.SignatureCallingConvention.VarArgs) { var conventionsList = symbol.Signature.CallingConvention switch { System.Reflection.Metadata.SignatureCallingConvention.CDecl => new[] { GetConventionForString("Cdecl") }, System.Reflection.Metadata.SignatureCallingConvention.StdCall => new[] { GetConventionForString("Stdcall") }, System.Reflection.Metadata.SignatureCallingConvention.ThisCall => new[] { GetConventionForString("Thiscall") }, System.Reflection.Metadata.SignatureCallingConvention.FastCall => new[] { GetConventionForString("Fastcall") }, System.Reflection.Metadata.SignatureCallingConvention.Unmanaged => // All types that come from CallingConventionTypes start with "CallConv". We don't want the prefix for the actual // syntax, so strip it off symbol.Signature.UnmanagedCallingConventionTypes.IsEmpty ? null : symbol.Signature.UnmanagedCallingConventionTypes.Select(type => GetConventionForString(type.Name["CallConv".Length..])), _ => throw ExceptionUtilities.UnexpectedValue(symbol.Signature.CallingConvention), }; callingConventionSyntax = SyntaxFactory.FunctionPointerCallingConvention( SyntaxFactory.Token(SyntaxKind.UnmanagedKeyword), conventionsList is object ? SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(SyntaxFactory.SeparatedList(conventionsList)) : null); static FunctionPointerUnmanagedCallingConventionSyntax GetConventionForString(string identifier) => SyntaxFactory.FunctionPointerUnmanagedCallingConvention(SyntaxFactory.Identifier(identifier)); } var parameters = symbol.Signature.Parameters.Select(p => (p.Type, RefKindModifiers: CSharpSyntaxGeneratorInternal.GetParameterModifiers(p.RefKind))) .Concat(SpecializedCollections.SingletonEnumerable(( Type: symbol.Signature.ReturnType, RefKindModifiers: CSharpSyntaxGeneratorInternal.GetParameterModifiers(symbol.Signature.RefKind, forFunctionPointerReturnParameter: true)))) .SelectAsArray(t => SyntaxFactory.FunctionPointerParameter(t.Type.GenerateTypeSyntax()).WithModifiers(t.RefKindModifiers)); return AddInformationTo( SyntaxFactory.FunctionPointerType(callingConventionSyntax, SyntaxFactory.FunctionPointerParameterList(SyntaxFactory.SeparatedList(parameters))), symbol); } public TypeSyntax CreateSimpleTypeSyntax(INamedTypeSymbol symbol) { if (!_nameOnly) { var syntax = TryCreateSpecializedNamedTypeSyntax(symbol); if (syntax != null) return syntax; } if (symbol.IsTupleType && symbol.TupleUnderlyingType != null && !symbol.Equals(symbol.TupleUnderlyingType)) { return CreateSimpleTypeSyntax(symbol.TupleUnderlyingType); } if (symbol.Name == string.Empty || symbol.IsAnonymousType) { return CreateSystemObject(); } if (symbol.TypeParameters.Length == 0) { if (symbol.TypeKind == TypeKind.Error && symbol.Name == "var") { return CreateSystemObject(); } return symbol.Name.ToIdentifierName(); } var typeArguments = symbol.IsUnboundGenericType ? Enumerable.Repeat((TypeSyntax)SyntaxFactory.OmittedTypeArgument(), symbol.TypeArguments.Length) : symbol.TypeArguments.SelectAsArray(t => t.GenerateTypeSyntax()); return SyntaxFactory.GenericName( symbol.Name.ToIdentifierToken(), SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments))); } private static QualifiedNameSyntax CreateSystemObject() { return SyntaxFactory.QualifiedName( SyntaxFactory.AliasQualifiedName( CreateGlobalIdentifier(), SyntaxFactory.IdentifierName("System")), SyntaxFactory.IdentifierName("Object")); } private static IdentifierNameSyntax CreateGlobalIdentifier() => SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); private static TypeSyntax? TryCreateSpecializedNamedTypeSyntax(INamedTypeSymbol symbol) { if (symbol.SpecialType == SpecialType.System_Void) { return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)); } if (symbol.IsTupleType && symbol.TupleElements.Length >= 2) { return CreateTupleTypeSyntax(symbol); } if (symbol.IsNullable()) { // Can't have a nullable of a pointer type. i.e. "int*?" is illegal. var innerType = symbol.TypeArguments.First(); if (innerType.TypeKind != TypeKind.Pointer) { return AddInformationTo( SyntaxFactory.NullableType(innerType.GenerateTypeSyntax()), symbol); } } return null; } private static TupleTypeSyntax CreateTupleTypeSyntax(INamedTypeSymbol symbol) { var list = new SeparatedSyntaxList<TupleElementSyntax>(); foreach (var element in symbol.TupleElements) { var name = element.IsImplicitlyDeclared ? default : SyntaxFactory.Identifier(element.Name); list = list.Add(SyntaxFactory.TupleElement(element.Type.GenerateTypeSyntax(), name)); } return AddInformationTo(SyntaxFactory.TupleType(list), symbol); } public override TypeSyntax VisitNamedType(INamedTypeSymbol symbol) { if (TryCreateNativeIntegerType(symbol, out var typeSyntax)) return typeSyntax; typeSyntax = CreateSimpleTypeSyntax(symbol); if (!(typeSyntax is SimpleNameSyntax)) return typeSyntax; var simpleNameSyntax = (SimpleNameSyntax)typeSyntax; if (symbol.ContainingType != null) { if (symbol.ContainingType.TypeKind != TypeKind.Submission) { var containingTypeSyntax = symbol.ContainingType.Accept(this); if (containingTypeSyntax is NameSyntax name) { typeSyntax = AddInformationTo( SyntaxFactory.QualifiedName(name, simpleNameSyntax), symbol); } else { typeSyntax = AddInformationTo(simpleNameSyntax, symbol); } } } else if (symbol.ContainingNamespace != null) { if (symbol.ContainingNamespace.IsGlobalNamespace) { if (symbol.TypeKind != TypeKind.Error) { typeSyntax = AddGlobalAlias(symbol, simpleNameSyntax); } } else { var container = symbol.ContainingNamespace.Accept(this)!; typeSyntax = AddInformationTo(SyntaxFactory.QualifiedName( (NameSyntax)container, simpleNameSyntax), symbol); } } if (symbol is { IsValueType: false, NullableAnnotation: NullableAnnotation.Annotated }) { // value type with nullable annotation may be composed from unconstrained nullable generic // doesn't mean nullable value type in this case typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol); } return typeSyntax; } public override TypeSyntax VisitNamespace(INamespaceSymbol symbol) { var syntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol); if (symbol.ContainingNamespace == null) { return syntax; } if (symbol.ContainingNamespace.IsGlobalNamespace) { return AddGlobalAlias(symbol, syntax); } else { var container = symbol.ContainingNamespace.Accept(this)!; return AddInformationTo(SyntaxFactory.QualifiedName( (NameSyntax)container, syntax), symbol); } } /// <summary> /// We always unilaterally add "global::" to all named types/namespaces. This /// will then be trimmed off if possible by calls to /// <see cref="Simplifier.ReduceAsync(Document, OptionSet, CancellationToken)"/> /// </summary> private static TypeSyntax AddGlobalAlias(INamespaceOrTypeSymbol symbol, SimpleNameSyntax syntax) { return AddInformationTo( SyntaxFactory.AliasQualifiedName( CreateGlobalIdentifier(), syntax), symbol); } public override TypeSyntax VisitPointerType(IPointerTypeSymbol symbol) { ThrowIfNameOnly(); return AddInformationTo( SyntaxFactory.PointerType(symbol.PointedAtType.GenerateTypeSyntax()), symbol); } public override TypeSyntax VisitTypeParameter(ITypeParameterSymbol symbol) { TypeSyntax typeSyntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol); if (symbol is { IsValueType: false, NullableAnnotation: NullableAnnotation.Annotated }) { // value type with nullable annotation may be composed from unconstrained nullable generic // doesn't mean nullable value type in this case typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol); } return typeSyntax; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.CSharp.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.Extensions { internal partial class ITypeSymbolExtensions { private class TypeSyntaxGeneratorVisitor : SymbolVisitor<TypeSyntax> { private readonly bool _nameOnly; private static readonly TypeSyntaxGeneratorVisitor NameOnlyInstance = new(nameOnly: true); private static readonly TypeSyntaxGeneratorVisitor NotNameOnlyInstance = new(nameOnly: false); private TypeSyntaxGeneratorVisitor(bool nameOnly) => _nameOnly = nameOnly; public static TypeSyntaxGeneratorVisitor Create(bool nameOnly = false) => nameOnly ? NameOnlyInstance : NotNameOnlyInstance; public override TypeSyntax DefaultVisit(ISymbol node) => throw new NotImplementedException(); private static TTypeSyntax AddInformationTo<TTypeSyntax>(TTypeSyntax syntax, ISymbol symbol) where TTypeSyntax : TypeSyntax { syntax = syntax.WithPrependedLeadingTrivia(SyntaxFactory.ElasticMarker).WithAppendedTrailingTrivia(SyntaxFactory.ElasticMarker); syntax = syntax.WithAdditionalAnnotations(SymbolAnnotation.Create(symbol)); return syntax; } public override TypeSyntax VisitAlias(IAliasSymbol symbol) => AddInformationTo(symbol.Name.ToIdentifierName(), symbol); private void ThrowIfNameOnly() { if (_nameOnly) { throw new InvalidOperationException("This symbol cannot be converted into a NameSyntax"); } } public override TypeSyntax VisitArrayType(IArrayTypeSymbol symbol) { ThrowIfNameOnly(); ITypeSymbol underlyingType = symbol; while (underlyingType is IArrayTypeSymbol innerArray) { underlyingType = innerArray.ElementType; if (underlyingType.NullableAnnotation == NullableAnnotation.Annotated) { // If the inner array we just moved to is also nullable, then // we must terminate the digging now so we produce the syntax for that, // and then append the ranks we passed through at the end. This is because // nullability annotations acts as a "barrier" where we won't reorder array // through. So whereas: // // string[][,] // // is really an array of rank 1 that has an element of rank 2, // // string[]?[,] // // is really an array of rank 2 that has nullable elements of rank 1. break; } } var elementTypeSyntax = underlyingType.GenerateTypeSyntax(); using var _ = ArrayBuilder<ArrayRankSpecifierSyntax>.GetInstance(out var ranks); var arrayType = symbol; while (arrayType != null && !arrayType.Equals(underlyingType)) { ranks.Add(SyntaxFactory.ArrayRankSpecifier( SyntaxFactory.SeparatedList(Enumerable.Repeat<ExpressionSyntax>(SyntaxFactory.OmittedArraySizeExpression(), arrayType.Rank)))); arrayType = arrayType.ElementType as IArrayTypeSymbol; } TypeSyntax arrayTypeSyntax = SyntaxFactory.ArrayType(elementTypeSyntax, ranks.ToSyntaxList()); if (symbol.NullableAnnotation == NullableAnnotation.Annotated) { arrayTypeSyntax = SyntaxFactory.NullableType(arrayTypeSyntax); } return AddInformationTo(arrayTypeSyntax, symbol); } public override TypeSyntax VisitDynamicType(IDynamicTypeSymbol symbol) => AddInformationTo(SyntaxFactory.IdentifierName("dynamic"), symbol); public static bool TryCreateNativeIntegerType(INamedTypeSymbol symbol, [NotNullWhen(true)] out TypeSyntax? syntax) { if (symbol.IsNativeIntegerType) { syntax = SyntaxFactory.IdentifierName(symbol.SpecialType == SpecialType.System_IntPtr ? "nint" : "nuint"); return true; } syntax = null; return false; } public override TypeSyntax VisitFunctionPointerType(IFunctionPointerTypeSymbol symbol) { FunctionPointerCallingConventionSyntax? callingConventionSyntax = null; // For varargs there is no C# syntax. You get a use-site diagnostic if you attempt to use it, and just // making a default-convention symbol is likely good enough. This is only observable through metadata // that always be uncompilable in C# anyway. if (symbol.Signature.CallingConvention != System.Reflection.Metadata.SignatureCallingConvention.Default && symbol.Signature.CallingConvention != System.Reflection.Metadata.SignatureCallingConvention.VarArgs) { var conventionsList = symbol.Signature.CallingConvention switch { System.Reflection.Metadata.SignatureCallingConvention.CDecl => new[] { GetConventionForString("Cdecl") }, System.Reflection.Metadata.SignatureCallingConvention.StdCall => new[] { GetConventionForString("Stdcall") }, System.Reflection.Metadata.SignatureCallingConvention.ThisCall => new[] { GetConventionForString("Thiscall") }, System.Reflection.Metadata.SignatureCallingConvention.FastCall => new[] { GetConventionForString("Fastcall") }, System.Reflection.Metadata.SignatureCallingConvention.Unmanaged => // All types that come from CallingConventionTypes start with "CallConv". We don't want the prefix for the actual // syntax, so strip it off symbol.Signature.UnmanagedCallingConventionTypes.IsEmpty ? null : symbol.Signature.UnmanagedCallingConventionTypes.Select(type => GetConventionForString(type.Name["CallConv".Length..])), _ => throw ExceptionUtilities.UnexpectedValue(symbol.Signature.CallingConvention), }; callingConventionSyntax = SyntaxFactory.FunctionPointerCallingConvention( SyntaxFactory.Token(SyntaxKind.UnmanagedKeyword), conventionsList is object ? SyntaxFactory.FunctionPointerUnmanagedCallingConventionList(SyntaxFactory.SeparatedList(conventionsList)) : null); static FunctionPointerUnmanagedCallingConventionSyntax GetConventionForString(string identifier) => SyntaxFactory.FunctionPointerUnmanagedCallingConvention(SyntaxFactory.Identifier(identifier)); } var parameters = symbol.Signature.Parameters.Select(p => (p.Type, RefKindModifiers: CSharpSyntaxGeneratorInternal.GetParameterModifiers(p.RefKind))) .Concat(SpecializedCollections.SingletonEnumerable(( Type: symbol.Signature.ReturnType, RefKindModifiers: CSharpSyntaxGeneratorInternal.GetParameterModifiers(symbol.Signature.RefKind, forFunctionPointerReturnParameter: true)))) .SelectAsArray(t => SyntaxFactory.FunctionPointerParameter(t.Type.GenerateTypeSyntax()).WithModifiers(t.RefKindModifiers)); return AddInformationTo( SyntaxFactory.FunctionPointerType(callingConventionSyntax, SyntaxFactory.FunctionPointerParameterList(SyntaxFactory.SeparatedList(parameters))), symbol); } public TypeSyntax CreateSimpleTypeSyntax(INamedTypeSymbol symbol) { if (!_nameOnly) { var syntax = TryCreateSpecializedNamedTypeSyntax(symbol); if (syntax != null) return syntax; } if (symbol.IsTupleType && symbol.TupleUnderlyingType != null && !symbol.Equals(symbol.TupleUnderlyingType)) { return CreateSimpleTypeSyntax(symbol.TupleUnderlyingType); } if (symbol.Name == string.Empty || symbol.IsAnonymousType) { return CreateSystemObject(); } if (symbol.TypeParameters.Length == 0) { if (symbol.TypeKind == TypeKind.Error && symbol.Name == "var") { return CreateSystemObject(); } return symbol.Name.ToIdentifierName(); } var typeArguments = symbol.IsUnboundGenericType ? Enumerable.Repeat((TypeSyntax)SyntaxFactory.OmittedTypeArgument(), symbol.TypeArguments.Length) : symbol.TypeArguments.SelectAsArray(t => t.GenerateTypeSyntax()); return SyntaxFactory.GenericName( symbol.Name.ToIdentifierToken(), SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(typeArguments))); } private static QualifiedNameSyntax CreateSystemObject() { return SyntaxFactory.QualifiedName( SyntaxFactory.AliasQualifiedName( CreateGlobalIdentifier(), SyntaxFactory.IdentifierName("System")), SyntaxFactory.IdentifierName("Object")); } private static IdentifierNameSyntax CreateGlobalIdentifier() => SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)); private static TypeSyntax? TryCreateSpecializedNamedTypeSyntax(INamedTypeSymbol symbol) { if (symbol.SpecialType == SpecialType.System_Void) { return SyntaxFactory.PredefinedType(SyntaxFactory.Token(SyntaxKind.VoidKeyword)); } if (symbol.IsTupleType && symbol.TupleElements.Length >= 2) { return CreateTupleTypeSyntax(symbol); } if (symbol.IsNullable()) { // Can't have a nullable of a pointer type. i.e. "int*?" is illegal. var innerType = symbol.TypeArguments.First(); if (innerType.TypeKind != TypeKind.Pointer) { return AddInformationTo( SyntaxFactory.NullableType(innerType.GenerateTypeSyntax()), symbol); } } return null; } private static TupleTypeSyntax CreateTupleTypeSyntax(INamedTypeSymbol symbol) { var list = new SeparatedSyntaxList<TupleElementSyntax>(); foreach (var element in symbol.TupleElements) { var name = element.IsImplicitlyDeclared ? default : SyntaxFactory.Identifier(element.Name); list = list.Add(SyntaxFactory.TupleElement(element.Type.GenerateTypeSyntax(), name)); } return AddInformationTo(SyntaxFactory.TupleType(list), symbol); } public override TypeSyntax VisitNamedType(INamedTypeSymbol symbol) { if (TryCreateNativeIntegerType(symbol, out var typeSyntax)) return typeSyntax; typeSyntax = CreateSimpleTypeSyntax(symbol); if (!(typeSyntax is SimpleNameSyntax)) return typeSyntax; var simpleNameSyntax = (SimpleNameSyntax)typeSyntax; if (symbol.ContainingType != null) { if (symbol.ContainingType.TypeKind != TypeKind.Submission) { var containingTypeSyntax = symbol.ContainingType.Accept(this); if (containingTypeSyntax is NameSyntax name) { typeSyntax = AddInformationTo( SyntaxFactory.QualifiedName(name, simpleNameSyntax), symbol); } else { typeSyntax = AddInformationTo(simpleNameSyntax, symbol); } } } else if (symbol.ContainingNamespace != null) { if (symbol.ContainingNamespace.IsGlobalNamespace) { if (symbol.TypeKind != TypeKind.Error) { typeSyntax = AddGlobalAlias(symbol, simpleNameSyntax); } } else { var container = symbol.ContainingNamespace.Accept(this)!; typeSyntax = AddInformationTo(SyntaxFactory.QualifiedName( (NameSyntax)container, simpleNameSyntax), symbol); } } if (symbol is { IsValueType: false, NullableAnnotation: NullableAnnotation.Annotated }) { // value type with nullable annotation may be composed from unconstrained nullable generic // doesn't mean nullable value type in this case typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol); } return typeSyntax; } public override TypeSyntax VisitNamespace(INamespaceSymbol symbol) { var syntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol); if (symbol.ContainingNamespace == null) { return syntax; } if (symbol.ContainingNamespace.IsGlobalNamespace) { return AddGlobalAlias(symbol, syntax); } else { var container = symbol.ContainingNamespace.Accept(this)!; return AddInformationTo(SyntaxFactory.QualifiedName( (NameSyntax)container, syntax), symbol); } } /// <summary> /// We always unilaterally add "global::" to all named types/namespaces. This /// will then be trimmed off if possible by calls to /// <see cref="Simplifier.ReduceAsync(Document, OptionSet, CancellationToken)"/> /// </summary> private static TypeSyntax AddGlobalAlias(INamespaceOrTypeSymbol symbol, SimpleNameSyntax syntax) { return AddInformationTo( SyntaxFactory.AliasQualifiedName( CreateGlobalIdentifier(), syntax), symbol); } public override TypeSyntax VisitPointerType(IPointerTypeSymbol symbol) { ThrowIfNameOnly(); return AddInformationTo( SyntaxFactory.PointerType(symbol.PointedAtType.GenerateTypeSyntax()), symbol); } public override TypeSyntax VisitTypeParameter(ITypeParameterSymbol symbol) { TypeSyntax typeSyntax = AddInformationTo(symbol.Name.ToIdentifierName(), symbol); if (symbol is { IsValueType: false, NullableAnnotation: NullableAnnotation.Annotated }) { // value type with nullable annotation may be composed from unconstrained nullable generic // doesn't mean nullable value type in this case typeSyntax = AddInformationTo(SyntaxFactory.NullableType(typeSyntax), symbol); } return typeSyntax; } } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Workspaces/CSharp/Portable/CodeGeneration/ConversionGenerator.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class ConversionGenerator { internal static TypeDeclarationSyntax AddConversionTo( TypeDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var methodDeclaration = GenerateConversionDeclaration( method, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, methodDeclaration, options, availableIndices, after: LastOperator); return AddMembersTo(destination, members); } internal static ConversionOperatorDeclarationSyntax GenerateConversionDeclaration( IMethodSymbol method, CodeGenerationOptions options, ParseOptions parseOptions) { var declaration = GenerateConversionDeclarationWorker(method, options, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options))); } private static ConversionOperatorDeclarationSyntax GenerateConversionDeclarationWorker( IMethodSymbol method, CodeGenerationOptions options, ParseOptions parseOptions) { var hasNoBody = !options.GenerateMethodBodies || method.IsExtern; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ConversionOperatorDeclarationSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var keyword = method.MetadataName == WellKnownMemberNames.ImplicitConversionName ? SyntaxFactory.Token(SyntaxKind.ImplicitKeyword) : SyntaxFactory.Token(SyntaxKind.ExplicitKeyword); var declaration = SyntaxFactory.ConversionOperatorDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options), modifiers: GenerateModifiers(), implicitOrExplicitKeyword: keyword, operatorKeyword: SyntaxFactory.Token(SyntaxKind.OperatorKeyword), type: method.ReturnType.GenerateTypeSyntax(), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options: options), body: hasNoBody ? null : StatementGenerator.GenerateBlock(method), semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken()); declaration = UseExpressionBodyIfDesired(options, declaration, parseOptions); return declaration; } private static ConversionOperatorDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, ConversionOperatorDeclarationSyntax declaration, ParseOptions parseOptions) { if (declaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedOperators).Value; if (declaration.Body.TryConvertToArrowExpressionBody( declaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return declaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return declaration; } private static SyntaxTokenList GenerateModifiers() { return SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Generic; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using static Microsoft.CodeAnalysis.CodeGeneration.CodeGenerationHelpers; using static Microsoft.CodeAnalysis.CSharp.CodeGeneration.CSharpCodeGenerationHelpers; namespace Microsoft.CodeAnalysis.CSharp.CodeGeneration { internal static class ConversionGenerator { internal static TypeDeclarationSyntax AddConversionTo( TypeDeclarationSyntax destination, IMethodSymbol method, CodeGenerationOptions options, IList<bool> availableIndices) { var methodDeclaration = GenerateConversionDeclaration( method, options, destination?.SyntaxTree.Options ?? options.ParseOptions); var members = Insert(destination.Members, methodDeclaration, options, availableIndices, after: LastOperator); return AddMembersTo(destination, members); } internal static ConversionOperatorDeclarationSyntax GenerateConversionDeclaration( IMethodSymbol method, CodeGenerationOptions options, ParseOptions parseOptions) { var declaration = GenerateConversionDeclarationWorker(method, options, parseOptions); return AddFormatterAndCodeGeneratorAnnotationsTo(AddAnnotationsTo(method, ConditionallyAddDocumentationCommentTo(declaration, method, options))); } private static ConversionOperatorDeclarationSyntax GenerateConversionDeclarationWorker( IMethodSymbol method, CodeGenerationOptions options, ParseOptions parseOptions) { var hasNoBody = !options.GenerateMethodBodies || method.IsExtern; var reusableSyntax = GetReuseableSyntaxNodeForSymbol<ConversionOperatorDeclarationSyntax>(method, options); if (reusableSyntax != null) { return reusableSyntax; } var keyword = method.MetadataName == WellKnownMemberNames.ImplicitConversionName ? SyntaxFactory.Token(SyntaxKind.ImplicitKeyword) : SyntaxFactory.Token(SyntaxKind.ExplicitKeyword); var declaration = SyntaxFactory.ConversionOperatorDeclaration( attributeLists: AttributeGenerator.GenerateAttributeLists(method.GetAttributes(), options), modifiers: GenerateModifiers(), implicitOrExplicitKeyword: keyword, operatorKeyword: SyntaxFactory.Token(SyntaxKind.OperatorKeyword), type: method.ReturnType.GenerateTypeSyntax(), parameterList: ParameterGenerator.GenerateParameterList(method.Parameters, isExplicit: false, options: options), body: hasNoBody ? null : StatementGenerator.GenerateBlock(method), semicolonToken: hasNoBody ? SyntaxFactory.Token(SyntaxKind.SemicolonToken) : new SyntaxToken()); declaration = UseExpressionBodyIfDesired(options, declaration, parseOptions); return declaration; } private static ConversionOperatorDeclarationSyntax UseExpressionBodyIfDesired( CodeGenerationOptions options, ConversionOperatorDeclarationSyntax declaration, ParseOptions parseOptions) { if (declaration.ExpressionBody == null) { var expressionBodyPreference = options.Options.GetOption(CSharpCodeStyleOptions.PreferExpressionBodiedOperators).Value; if (declaration.Body.TryConvertToArrowExpressionBody( declaration.Kind(), parseOptions, expressionBodyPreference, out var expressionBody, out var semicolonToken)) { return declaration.WithBody(null) .WithExpressionBody(expressionBody) .WithSemicolonToken(semicolonToken); } } return declaration; } private static SyntaxTokenList GenerateModifiers() { return SyntaxFactory.TokenList( SyntaxFactory.Token(SyntaxKind.PublicKeyword), SyntaxFactory.Token(SyntaxKind.StaticKeyword)); } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Features/CSharp/Portable/Structure/Providers/InitializerExpressionStructureProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class InitializerExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<InitializerExpressionSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, InitializerExpressionSyntax node, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { if (node.Parent is InitializerExpressionSyntax) { // We have something like: // // new Dictionary<int, string> // { // ... // { // ... // }, // ... // } // // In this case, we want to collapse the "{ ... }," (including the comma). var nextToken = node.CloseBraceToken.GetNextToken(); var end = nextToken.Kind() == SyntaxKind.CommaToken ? nextToken.Span.End : node.Span.End; spans.Add(new BlockSpan( isCollapsible: true, textSpan: TextSpan.FromBounds(node.SpanStart, end), hintSpan: TextSpan.FromBounds(node.SpanStart, end), type: BlockTypes.Expression)); } else { // Parent is something like: // // new Dictionary<int, string> { // ... // } // // The collapsed textspan should be from the > to the } // // However, the hint span should be the entire object creation. spans.Add(new BlockSpan( isCollapsible: true, textSpan: TextSpan.FromBounds(previousToken.Span.End, node.Span.End), hintSpan: node.Parent.Span, type: BlockTypes.Expression)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Shared.Collections; using Microsoft.CodeAnalysis.Structure; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class InitializerExpressionStructureProvider : AbstractSyntaxNodeStructureProvider<InitializerExpressionSyntax> { protected override void CollectBlockSpans( SyntaxToken previousToken, InitializerExpressionSyntax node, ref TemporaryArray<BlockSpan> spans, BlockStructureOptionProvider optionProvider, CancellationToken cancellationToken) { if (node.Parent is InitializerExpressionSyntax) { // We have something like: // // new Dictionary<int, string> // { // ... // { // ... // }, // ... // } // // In this case, we want to collapse the "{ ... }," (including the comma). var nextToken = node.CloseBraceToken.GetNextToken(); var end = nextToken.Kind() == SyntaxKind.CommaToken ? nextToken.Span.End : node.Span.End; spans.Add(new BlockSpan( isCollapsible: true, textSpan: TextSpan.FromBounds(node.SpanStart, end), hintSpan: TextSpan.FromBounds(node.SpanStart, end), type: BlockTypes.Expression)); } else { // Parent is something like: // // new Dictionary<int, string> { // ... // } // // The collapsed textspan should be from the > to the } // // However, the hint span should be the entire object creation. spans.Add(new BlockSpan( isCollapsible: true, textSpan: TextSpan.FromBounds(previousToken.Span.End, node.Span.End), hintSpan: node.Parent.Span, type: BlockTypes.Expression)); } } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/VisualStudio/Core/Def/Implementation/Progression/GraphQueries/InheritedByGraphQuery.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.VisualStudio.GraphModel; using Microsoft.VisualStudio.GraphModel.Schemas; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class InheritedByGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (!(symbol is INamedTypeSymbol namedType)) continue; if (namedType.TypeKind == TypeKind.Class) { var derivedTypes = await SymbolFinder.FindDerivedClassesArrayAsync( namedType, solution, transitive: false, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var derivedType in derivedTypes) { var symbolNode = await graphBuilder.AddNodeAsync( derivedType, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(symbolNode, CodeLinkCategories.InheritsFrom, node, cancellationToken); } } else if (namedType.TypeKind == TypeKind.Interface) { var implementingClassesAndStructs = await SymbolFinder.FindImplementationsArrayAsync( namedType, solution, transitive: false, cancellationToken: cancellationToken).ConfigureAwait(false); var derivedInterfaces = await SymbolFinder.FindDerivedInterfacesArrayAsync( namedType, solution, transitive: false, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var derivedType in implementingClassesAndStructs.Concat(derivedInterfaces)) { var symbolNode = await graphBuilder.AddNodeAsync( derivedType, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(symbolNode, CodeLinkCategories.InheritsFrom, node, cancellationToken); } } } return graphBuilder; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.FindSymbols; using Microsoft.VisualStudio.GraphModel; using Microsoft.VisualStudio.GraphModel.Schemas; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Progression { internal sealed class InheritedByGraphQuery : IGraphQuery { public async Task<GraphBuilder> GetGraphAsync(Solution solution, IGraphContext context, CancellationToken cancellationToken) { var graphBuilder = await GraphBuilder.CreateForInputNodesAsync(solution, context.InputNodes, cancellationToken).ConfigureAwait(false); foreach (var node in context.InputNodes) { var symbol = graphBuilder.GetSymbol(node, cancellationToken); if (!(symbol is INamedTypeSymbol namedType)) continue; if (namedType.TypeKind == TypeKind.Class) { var derivedTypes = await SymbolFinder.FindDerivedClassesArrayAsync( namedType, solution, transitive: false, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var derivedType in derivedTypes) { var symbolNode = await graphBuilder.AddNodeAsync( derivedType, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(symbolNode, CodeLinkCategories.InheritsFrom, node, cancellationToken); } } else if (namedType.TypeKind == TypeKind.Interface) { var implementingClassesAndStructs = await SymbolFinder.FindImplementationsArrayAsync( namedType, solution, transitive: false, cancellationToken: cancellationToken).ConfigureAwait(false); var derivedInterfaces = await SymbolFinder.FindDerivedInterfacesArrayAsync( namedType, solution, transitive: false, cancellationToken: cancellationToken).ConfigureAwait(false); foreach (var derivedType in implementingClassesAndStructs.Concat(derivedInterfaces)) { var symbolNode = await graphBuilder.AddNodeAsync( derivedType, relatedNode: node, cancellationToken).ConfigureAwait(false); graphBuilder.AddLink(symbolNode, CodeLinkCategories.InheritsFrom, node, cancellationToken); } } } return graphBuilder; } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Features/CSharp/Portable/RemoveAsyncModifier/CSharpRemoveAsyncModifierCodeFixProvider.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.MakeMethodSynchronous; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.RemoveAsyncModifier; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.RemoveAsyncModifier { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveAsyncModifier), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.MakeMethodSynchronous)] internal partial class CSharpRemoveAsyncModifierCodeFixProvider : AbstractRemoveAsyncModifierCodeFixProvider<ReturnStatementSyntax, ExpressionSyntax> { private const string CS1998 = nameof(CS1998); // This async method lacks 'await' operators and will run synchronously. [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpRemoveAsyncModifierCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(CS1998); protected override bool IsAsyncSupportingFunctionSyntax(SyntaxNode node) => node.IsAsyncSupportingFunctionSyntax(); protected override SyntaxNode? ConvertToBlockBody(SyntaxNode node, ExpressionSyntax expressionBody) { var semicolonToken = SyntaxFactory.Token(SyntaxKind.SemicolonToken); if (expressionBody.TryConvertToStatement(semicolonToken, createReturnStatementForExpression: false, out var statement)) { var block = SyntaxFactory.Block(statement); return node switch { MethodDeclarationSyntax method => method.WithBody(block).WithExpressionBody(null).WithSemicolonToken(default), LocalFunctionStatementSyntax localFunction => localFunction.WithBody(block).WithExpressionBody(null).WithSemicolonToken(default), AnonymousFunctionExpressionSyntax anonymousFunction => anonymousFunction.WithBody(block).WithExpressionBody(null), _ => throw ExceptionUtilities.Unreachable }; } return null; } protected override SyntaxNode RemoveAsyncModifier(SyntaxGenerator generator, SyntaxNode methodLikeNode) => methodLikeNode switch { MethodDeclarationSyntax method => RemoveAsyncModifierHelpers.WithoutAsyncModifier(method, method.ReturnType), LocalFunctionStatementSyntax localFunction => RemoveAsyncModifierHelpers.WithoutAsyncModifier(localFunction, localFunction.ReturnType), AnonymousMethodExpressionSyntax method => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(method)), ParenthesizedLambdaExpressionSyntax lambda => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda)), SimpleLambdaExpressionSyntax lambda => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda)), _ => methodLikeNode, }; // Block bodied lambdas and anonymous methods need to be formatted after changing their modifiers, or their indentation is broken private static SyntaxNode AnnotateBlock(SyntaxGenerator generator, SyntaxNode node) => generator.GetExpression(node) == null ? node.WithAdditionalAnnotations(Formatter.Annotation) : node; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.Composition; using System.Diagnostics.CodeAnalysis; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.MakeMethodSynchronous; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.RemoveAsyncModifier; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.RemoveAsyncModifier { [ExportCodeFixProvider(LanguageNames.CSharp, Name = PredefinedCodeFixProviderNames.RemoveAsyncModifier), Shared] [ExtensionOrder(After = PredefinedCodeFixProviderNames.MakeMethodSynchronous)] internal partial class CSharpRemoveAsyncModifierCodeFixProvider : AbstractRemoveAsyncModifierCodeFixProvider<ReturnStatementSyntax, ExpressionSyntax> { private const string CS1998 = nameof(CS1998); // This async method lacks 'await' operators and will run synchronously. [ImportingConstructor] [SuppressMessage("RoslynDiagnosticsReliability", "RS0033:Importing constructor should be [Obsolete]", Justification = "Used in test code: https://github.com/dotnet/roslyn/issues/42814")] public CSharpRemoveAsyncModifierCodeFixProvider() { } public override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(CS1998); protected override bool IsAsyncSupportingFunctionSyntax(SyntaxNode node) => node.IsAsyncSupportingFunctionSyntax(); protected override SyntaxNode? ConvertToBlockBody(SyntaxNode node, ExpressionSyntax expressionBody) { var semicolonToken = SyntaxFactory.Token(SyntaxKind.SemicolonToken); if (expressionBody.TryConvertToStatement(semicolonToken, createReturnStatementForExpression: false, out var statement)) { var block = SyntaxFactory.Block(statement); return node switch { MethodDeclarationSyntax method => method.WithBody(block).WithExpressionBody(null).WithSemicolonToken(default), LocalFunctionStatementSyntax localFunction => localFunction.WithBody(block).WithExpressionBody(null).WithSemicolonToken(default), AnonymousFunctionExpressionSyntax anonymousFunction => anonymousFunction.WithBody(block).WithExpressionBody(null), _ => throw ExceptionUtilities.Unreachable }; } return null; } protected override SyntaxNode RemoveAsyncModifier(SyntaxGenerator generator, SyntaxNode methodLikeNode) => methodLikeNode switch { MethodDeclarationSyntax method => RemoveAsyncModifierHelpers.WithoutAsyncModifier(method, method.ReturnType), LocalFunctionStatementSyntax localFunction => RemoveAsyncModifierHelpers.WithoutAsyncModifier(localFunction, localFunction.ReturnType), AnonymousMethodExpressionSyntax method => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(method)), ParenthesizedLambdaExpressionSyntax lambda => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda)), SimpleLambdaExpressionSyntax lambda => AnnotateBlock(generator, RemoveAsyncModifierHelpers.WithoutAsyncModifier(lambda)), _ => methodLikeNode, }; // Block bodied lambdas and anonymous methods need to be formatted after changing their modifiers, or their indentation is broken private static SyntaxNode AnnotateBlock(SyntaxGenerator generator, SyntaxNode node) => generator.GetExpression(node) == null ? node.WithAdditionalAnnotations(Formatter.Annotation) : node; } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/VisualStudio/Xaml/Impl/XamlStaticTypeDefinitions.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.ComponentModel.Composition; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Xaml { public static class XamlStaticTypeDefinitions { /// <summary> /// Definition of the XAML content type. /// </summary> [Export] [Name(ContentTypeNames.XamlContentType)] [BaseDefinition("code")] internal static readonly ContentTypeDefinition XamlContentType; // Associate .xaml as the Xaml content type. [Export] [FileExtension(StringConstants.XamlFileExtension)] [ContentType(ContentTypeNames.XamlContentType)] internal static readonly FileExtensionToContentTypeDefinition XamlFileExtension; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.ComponentModel.Composition; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.Utilities; namespace Microsoft.CodeAnalysis.Editor.Xaml { public static class XamlStaticTypeDefinitions { /// <summary> /// Definition of the XAML content type. /// </summary> [Export] [Name(ContentTypeNames.XamlContentType)] [BaseDefinition("code")] internal static readonly ContentTypeDefinition XamlContentType; // Associate .xaml as the Xaml content type. [Export] [FileExtension(StringConstants.XamlFileExtension)] [ContentType(ContentTypeNames.XamlContentType)] internal static readonly FileExtensionToContentTypeDefinition XamlFileExtension; } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/EditorFeatures/DiagnosticsTestUtilities/Microsoft.CodeAnalysis.EditorFeatures.DiagnosticsTests.Utilities.csproj
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.Test.Utilities</RootNamespace> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj"> <Aliases>global,WORKSPACES</Aliases> </ProjectReference> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServer.Protocol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> </ItemGroup> <ItemGroup> <!-- TODO: Remove the below IVTs to CodeStyle Unit test projects once all analyzer/code fix tests are switched to Microsoft.CodeAnalysis.Testing --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" /> </ItemGroup> </Project>
<?xml version="1.0" encoding="utf-8"?> <!-- Licensed to the .NET Foundation under one or more agreements. The .NET Foundation licenses this file to you under the MIT license. See the LICENSE file in the project root for more information. --> <Project Sdk="Microsoft.NET.Sdk.WindowsDesktop"> <PropertyGroup> <OutputType>Library</OutputType> <RootNamespace>Microsoft.CodeAnalysis.Test.Utilities</RootNamespace> <TargetFramework>net472</TargetFramework> <UseWpf>true</UseWpf> <AllowUnsafeBlocks>true</AllowUnsafeBlocks> <IsShipping>false</IsShipping> </PropertyGroup> <ItemGroup> <ProjectReference Include="..\..\Compilers\Core\Portable\Microsoft.CodeAnalysis.csproj" /> <ProjectReference Include="..\..\Compilers\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.csproj" /> <ProjectReference Include="..\..\Compilers\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.vbproj" /> <ProjectReference Include="..\..\Features\Core\Portable\Microsoft.CodeAnalysis.Features.csproj" /> <ProjectReference Include="..\..\Features\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Features.csproj" /> <ProjectReference Include="..\..\Features\LanguageServer\Protocol\Microsoft.CodeAnalysis.LanguageServer.Protocol.csproj" /> <ProjectReference Include="..\..\Features\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Features.vbproj" /> <ProjectReference Include="..\..\Compilers\Test\Core\Microsoft.CodeAnalysis.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\CoreTestUtilities\Microsoft.CodeAnalysis.Workspaces.Test.Utilities.csproj" /> <ProjectReference Include="..\TestUtilities\Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities.csproj" /> <ProjectReference Include="..\..\Workspaces\Core\Portable\Microsoft.CodeAnalysis.Workspaces.csproj"> <Aliases>global,WORKSPACES</Aliases> </ProjectReference> <ProjectReference Include="..\..\Workspaces\CSharp\Portable\Microsoft.CodeAnalysis.CSharp.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\Core\Microsoft.CodeAnalysis.Remote.Workspaces.csproj" /> <ProjectReference Include="..\..\Workspaces\Remote\ServiceHub\Microsoft.CodeAnalysis.Remote.ServiceHub.csproj" /> <ProjectReference Include="..\..\Workspaces\VisualBasic\Portable\Microsoft.CodeAnalysis.VisualBasic.Workspaces.vbproj" /> <ProjectReference Include="..\Core\Microsoft.CodeAnalysis.EditorFeatures.csproj" /> <ProjectReference Include="..\Core.Wpf\Microsoft.CodeAnalysis.EditorFeatures.Wpf.csproj" /> <ProjectReference Include="..\CSharp\Microsoft.CodeAnalysis.CSharp.EditorFeatures.csproj" /> <ProjectReference Include="..\Text\Microsoft.CodeAnalysis.EditorFeatures.Text.csproj" /> <ProjectReference Include="..\VisualBasic\Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.vbproj" /> </ItemGroup> <ItemGroup> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.LanguageServer.Protocol.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures2.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.EditorFeatures.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.EditorFeatures.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.CSharp.UnitTests" /> <InternalsVisibleTo Include="Roslyn.VisualStudio.Next.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.LiveShare.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.UnitTests" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.IntegrationTest.Utilities" /> <InternalsVisibleTo Include="Microsoft.VisualStudio.LanguageServices.Test.Utilities2" /> </ItemGroup> <ItemGroup> <!-- TODO: Remove the below IVTs to CodeStyle Unit test projects once all analyzer/code fix tests are switched to Microsoft.CodeAnalysis.Testing --> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CodeStyle.LegacyTestFramework.UnitTestUtilities" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.CSharp.CodeStyle.UnitTests" /> <InternalsVisibleTo Include="Microsoft.CodeAnalysis.VisualBasic.CodeStyle.UnitTests" /> </ItemGroup> </Project>
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Workspaces/Core/Portable/CodeFixes/FixAllOccurrences/DefaultFixAllProviderHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { using FixAllContexts = Func<FixAllContext, ImmutableArray<FixAllContext>, Task<Solution?>>; /// <summary> /// Default implementation of a <see cref="FixAllProvider"/> that efficiently handles the dispatch logic for fixing /// entire solutions. Used by <see cref="BatchFixAllProvider"/> and <see cref="DocumentBasedFixAllProvider"/>. /// </summary> internal static class DefaultFixAllProviderHelpers { public static async Task<CodeAction?> GetFixAsync( string title, FixAllContext fixAllContext, FixAllContexts fixAllContextsAsync) { Contract.ThrowIfFalse(fixAllContext.Scope is FixAllScope.Document or FixAllScope.Project or FixAllScope.Solution); var solution = fixAllContext.Scope switch { FixAllScope.Document => await GetDocumentFixesAsync(fixAllContext, fixAllContextsAsync).ConfigureAwait(false), FixAllScope.Project => await GetProjectFixesAsync(fixAllContext, fixAllContextsAsync).ConfigureAwait(false), FixAllScope.Solution => await GetSolutionFixesAsync(fixAllContext, fixAllContextsAsync).ConfigureAwait(false), _ => throw ExceptionUtilities.UnexpectedValue(fixAllContext.Scope), }; if (solution == null) return null; #pragma warning disable RS0005 // Do not use generic 'CodeAction.Create' to create 'CodeAction' return CodeAction.Create( title, c => Task.FromResult(solution)); #pragma warning disable RS0005 // Do not use generic 'CodeAction.Create' to create 'CodeAction' } private static Task<Solution?> GetDocumentFixesAsync(FixAllContext fixAllContext, FixAllContexts fixAllContextsAsync) => fixAllContextsAsync(fixAllContext, ImmutableArray.Create(fixAllContext)); private static Task<Solution?> GetProjectFixesAsync(FixAllContext fixAllContext, FixAllContexts fixAllContextsAsync) => fixAllContextsAsync(fixAllContext, ImmutableArray.Create(fixAllContext.WithDocument(null))); private static Task<Solution?> GetSolutionFixesAsync(FixAllContext fixAllContext, FixAllContexts fixAllContextsAsync) { var solution = fixAllContext.Solution; var dependencyGraph = solution.GetProjectDependencyGraph(); // Walk through each project in topological order, determining and applying the diagnostics for each // project. We do this in topological order so that the compilations for successive projects are readily // available as we just computed them for dependent projects. If we were to do it out of order, we might // start with a project that has a ton of dependencies, and we'd spend an inordinate amount of time just // building the compilations for it before we could proceed. // // By processing one project at a time, we can also let go of a project once done with it, allowing us to // reclaim lots of the memory so we don't overload the system while processing a large solution. // // Note: we have to filter down to projects of the same language as the FixAllContext points at a // CodeFixProvider, and we can't call into providers of different languages with diagnostics from a // different language. var sortedProjects = dependencyGraph.GetTopologicallySortedProjects() .Select(id => solution.GetRequiredProject(id)) .Where(p => p.Language == fixAllContext.Project.Language); return fixAllContextsAsync( fixAllContext, sortedProjects.SelectAsArray(p => fixAllContext.WithScope(FixAllScope.Project).WithProject(p).WithDocument(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.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeFixes { using FixAllContexts = Func<FixAllContext, ImmutableArray<FixAllContext>, Task<Solution?>>; /// <summary> /// Default implementation of a <see cref="FixAllProvider"/> that efficiently handles the dispatch logic for fixing /// entire solutions. Used by <see cref="BatchFixAllProvider"/> and <see cref="DocumentBasedFixAllProvider"/>. /// </summary> internal static class DefaultFixAllProviderHelpers { public static async Task<CodeAction?> GetFixAsync( string title, FixAllContext fixAllContext, FixAllContexts fixAllContextsAsync) { Contract.ThrowIfFalse(fixAllContext.Scope is FixAllScope.Document or FixAllScope.Project or FixAllScope.Solution); var solution = fixAllContext.Scope switch { FixAllScope.Document => await GetDocumentFixesAsync(fixAllContext, fixAllContextsAsync).ConfigureAwait(false), FixAllScope.Project => await GetProjectFixesAsync(fixAllContext, fixAllContextsAsync).ConfigureAwait(false), FixAllScope.Solution => await GetSolutionFixesAsync(fixAllContext, fixAllContextsAsync).ConfigureAwait(false), _ => throw ExceptionUtilities.UnexpectedValue(fixAllContext.Scope), }; if (solution == null) return null; #pragma warning disable RS0005 // Do not use generic 'CodeAction.Create' to create 'CodeAction' return CodeAction.Create( title, c => Task.FromResult(solution)); #pragma warning disable RS0005 // Do not use generic 'CodeAction.Create' to create 'CodeAction' } private static Task<Solution?> GetDocumentFixesAsync(FixAllContext fixAllContext, FixAllContexts fixAllContextsAsync) => fixAllContextsAsync(fixAllContext, ImmutableArray.Create(fixAllContext)); private static Task<Solution?> GetProjectFixesAsync(FixAllContext fixAllContext, FixAllContexts fixAllContextsAsync) => fixAllContextsAsync(fixAllContext, ImmutableArray.Create(fixAllContext.WithDocument(null))); private static Task<Solution?> GetSolutionFixesAsync(FixAllContext fixAllContext, FixAllContexts fixAllContextsAsync) { var solution = fixAllContext.Solution; var dependencyGraph = solution.GetProjectDependencyGraph(); // Walk through each project in topological order, determining and applying the diagnostics for each // project. We do this in topological order so that the compilations for successive projects are readily // available as we just computed them for dependent projects. If we were to do it out of order, we might // start with a project that has a ton of dependencies, and we'd spend an inordinate amount of time just // building the compilations for it before we could proceed. // // By processing one project at a time, we can also let go of a project once done with it, allowing us to // reclaim lots of the memory so we don't overload the system while processing a large solution. // // Note: we have to filter down to projects of the same language as the FixAllContext points at a // CodeFixProvider, and we can't call into providers of different languages with diagnostics from a // different language. var sortedProjects = dependencyGraph.GetTopologicallySortedProjects() .Select(id => solution.GetRequiredProject(id)) .Where(p => p.Language == fixAllContext.Project.Language); return fixAllContextsAsync( fixAllContext, sortedProjects.SelectAsArray(p => fixAllContext.WithScope(FixAllScope.Project).WithProject(p).WithDocument(null))); } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Tools/Source/CompilerGeneratorTools/Source/VisualBasicSyntaxGenerator/Util/WriteDumper.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. '----------------------------------------------------------------------------------------------------------- 'Code the generate a dumper class for a given parse tree. Reads the parse tree and outputs 'a dumper utility class. '----------------------------------------------------------------------------------------------------------- Imports System.IO Friend Class WriteDumper Inherits WriteUtils Private ReadOnly _checksum As String Private _writer As TextWriter 'output is sent here. Public Sub New(parseTree As ParseTree, checksum As String) MyBase.New(parseTree) _checksum = checksum End Sub ' Write the dumper utility function to the given file. Public Sub WriteDumper(filename As String) _writer = New StreamWriter(New FileStream(filename, FileMode.Create, FileAccess.Write)) Using _writer GenerateFile() End Using End Sub ' Write the whole contents of the file. Private Sub GenerateFile() _writer.WriteLine("' Definition of parse trees dumper.") _writer.WriteLine("' DO NOT HAND EDIT") _writer.WriteLine() GenerateNamespace() End Sub ' Create imports and the namespace declaration around the whole file Private Sub GenerateNamespace() _writer.WriteLine("Imports System.Collections.Generic") _writer.WriteLine("Imports System.IO") _writer.WriteLine() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("Namespace {0}", _parseTree.NamespaceName) _writer.WriteLine() End If GenerateDumperClass() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("End Namespace") End If End Sub ' Generate the partial part of the utilities class with the DumpTree function in it. Private Sub GenerateDumperClass() _writer.WriteLine(" Public Partial Class NodeInfo") _writer.WriteLine() ' Create the nested visitor class that does all the real work. GenerateDumpVisitor() _writer.WriteLine(" End Class") End Sub Private Sub GenerateDumpVisitor() ' Write out the first boilerplate part of the visitor _writer.WriteLine(" Private Class Visitor") _writer.WriteLine(" Inherits VisualBasicSyntaxVisitor(Of NodeInfo)") _writer.WriteLine() GenerateDumpVisitorMethods() _writer.WriteLine(" End Class") End Sub ' Generate the Visitor class definition Private Sub GenerateDumpVisitorMethods() For Each nodeStructure In _parseTree.NodeStructures.Values GenerateDumpVisitorMethod(nodeStructure) Next End Sub ' Generate a method in the Visitor class that dumps the given node type. Private Sub GenerateDumpVisitorMethod(nodeStructure As ParseNodeStructure) _writer.WriteLine(" Public Overrides Function {0}(ByVal node As {1}) As NodeInfo", VisitorMethodName(nodeStructure), StructureTypeName(nodeStructure)) ' Node, and name of the node structure _writer.WriteLine(" Return New NodeInfo(") _writer.WriteLine(" ""{0}"",", StructureTypeName(nodeStructure)) ' Fields of the node structure Dim fieldList = GetAllFieldsOfStructure(nodeStructure) If fieldList.Count > 0 Then _writer.WriteLine(" { ") For i = 0 To fieldList.Count - 1 GenerateFieldInfo(fieldList(i), i = fieldList.Count - 1) Next _writer.WriteLine(" },") Else _writer.WriteLine(" Nothing,") End If ' Children (including child lists) Dim childList = GetAllChildrenOfStructure(nodeStructure) _writer.WriteLine(" { ") For i = 0 To childList.Count - 1 GenerateChildInfo(childList(i), i = childList.Count - 1) Next _writer.WriteLine(" })") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Write out the code to create info about a simple field; just a primitive Private Sub GenerateFieldInfo(field As ParseNodeField, last As Boolean) _writer.Write(" New NodeInfo.FieldInfo(""{0}"", GetType({1}), node.{0})", FieldPropertyName(field), FieldTypeRef(field)) If last Then _writer.WriteLine() Else _writer.WriteLine(",") End If End Sub ' Write out the code to create info about a child or child list Private Sub GenerateChildInfo(child As ParseNodeChild, last As Boolean) If child.IsList Then If child.IsSeparated Then _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.SeparatedNodeList, GetType({1}), node.{0}, node.{0}.Separators)", ChildPropertyName(child), BaseTypeReference(child)) Else _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.NodeList, GetType({1}), node.{0}, Nothing)", ChildPropertyName(child), BaseTypeReference(child)) End If Else _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.SingleNode, GetType({1}), node.{0}, Nothing)", ChildPropertyName(child), BaseTypeReference(child)) End If If last Then _writer.WriteLine() Else _writer.WriteLine(",") End If 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. '----------------------------------------------------------------------------------------------------------- 'Code the generate a dumper class for a given parse tree. Reads the parse tree and outputs 'a dumper utility class. '----------------------------------------------------------------------------------------------------------- Imports System.IO Friend Class WriteDumper Inherits WriteUtils Private ReadOnly _checksum As String Private _writer As TextWriter 'output is sent here. Public Sub New(parseTree As ParseTree, checksum As String) MyBase.New(parseTree) _checksum = checksum End Sub ' Write the dumper utility function to the given file. Public Sub WriteDumper(filename As String) _writer = New StreamWriter(New FileStream(filename, FileMode.Create, FileAccess.Write)) Using _writer GenerateFile() End Using End Sub ' Write the whole contents of the file. Private Sub GenerateFile() _writer.WriteLine("' Definition of parse trees dumper.") _writer.WriteLine("' DO NOT HAND EDIT") _writer.WriteLine() GenerateNamespace() End Sub ' Create imports and the namespace declaration around the whole file Private Sub GenerateNamespace() _writer.WriteLine("Imports System.Collections.Generic") _writer.WriteLine("Imports System.IO") _writer.WriteLine() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("Namespace {0}", _parseTree.NamespaceName) _writer.WriteLine() End If GenerateDumperClass() If Not String.IsNullOrEmpty(_parseTree.NamespaceName) Then _writer.WriteLine("End Namespace") End If End Sub ' Generate the partial part of the utilities class with the DumpTree function in it. Private Sub GenerateDumperClass() _writer.WriteLine(" Public Partial Class NodeInfo") _writer.WriteLine() ' Create the nested visitor class that does all the real work. GenerateDumpVisitor() _writer.WriteLine(" End Class") End Sub Private Sub GenerateDumpVisitor() ' Write out the first boilerplate part of the visitor _writer.WriteLine(" Private Class Visitor") _writer.WriteLine(" Inherits VisualBasicSyntaxVisitor(Of NodeInfo)") _writer.WriteLine() GenerateDumpVisitorMethods() _writer.WriteLine(" End Class") End Sub ' Generate the Visitor class definition Private Sub GenerateDumpVisitorMethods() For Each nodeStructure In _parseTree.NodeStructures.Values GenerateDumpVisitorMethod(nodeStructure) Next End Sub ' Generate a method in the Visitor class that dumps the given node type. Private Sub GenerateDumpVisitorMethod(nodeStructure As ParseNodeStructure) _writer.WriteLine(" Public Overrides Function {0}(ByVal node As {1}) As NodeInfo", VisitorMethodName(nodeStructure), StructureTypeName(nodeStructure)) ' Node, and name of the node structure _writer.WriteLine(" Return New NodeInfo(") _writer.WriteLine(" ""{0}"",", StructureTypeName(nodeStructure)) ' Fields of the node structure Dim fieldList = GetAllFieldsOfStructure(nodeStructure) If fieldList.Count > 0 Then _writer.WriteLine(" { ") For i = 0 To fieldList.Count - 1 GenerateFieldInfo(fieldList(i), i = fieldList.Count - 1) Next _writer.WriteLine(" },") Else _writer.WriteLine(" Nothing,") End If ' Children (including child lists) Dim childList = GetAllChildrenOfStructure(nodeStructure) _writer.WriteLine(" { ") For i = 0 To childList.Count - 1 GenerateChildInfo(childList(i), i = childList.Count - 1) Next _writer.WriteLine(" })") _writer.WriteLine(" End Function") _writer.WriteLine() End Sub ' Write out the code to create info about a simple field; just a primitive Private Sub GenerateFieldInfo(field As ParseNodeField, last As Boolean) _writer.Write(" New NodeInfo.FieldInfo(""{0}"", GetType({1}), node.{0})", FieldPropertyName(field), FieldTypeRef(field)) If last Then _writer.WriteLine() Else _writer.WriteLine(",") End If End Sub ' Write out the code to create info about a child or child list Private Sub GenerateChildInfo(child As ParseNodeChild, last As Boolean) If child.IsList Then If child.IsSeparated Then _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.SeparatedNodeList, GetType({1}), node.{0}, node.{0}.Separators)", ChildPropertyName(child), BaseTypeReference(child)) Else _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.NodeList, GetType({1}), node.{0}, Nothing)", ChildPropertyName(child), BaseTypeReference(child)) End If Else _writer.Write(" New NodeInfo.ChildInfo(""{0}"", NodeInfo.ChildKind.SingleNode, GetType({1}), node.{0}, Nothing)", ChildPropertyName(child), BaseTypeReference(child)) End If If last Then _writer.WriteLine() Else _writer.WriteLine(",") End If End Sub End Class
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Workspaces/Core/Portable/Classification/ClassificationTypeNames.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Classification { public static class ClassificationTypeNames { /// <summary> /// Additive classifications types supply additional context to other classifications. /// </summary> /// <remarks> /// NOTE: Any updates to this class should also be reflected in LSP - see /// Features/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHelpers.cs /// </remarks> public static ImmutableArray<string> AdditiveTypeNames { get; } = ImmutableArray.Create(StaticSymbol); public const string Comment = "comment"; public const string ExcludedCode = "excluded code"; public const string Identifier = "identifier"; public const string Keyword = "keyword"; public const string ControlKeyword = "keyword - control"; public const string NumericLiteral = "number"; public const string Operator = "operator"; public const string OperatorOverloaded = "operator - overloaded"; public const string PreprocessorKeyword = "preprocessor keyword"; public const string StringLiteral = "string"; public const string WhiteSpace = "whitespace"; public const string Text = "text"; internal const string ReassignedVariable = "reassigned variable"; public const string StaticSymbol = "static symbol"; public const string PreprocessorText = "preprocessor text"; public const string Punctuation = "punctuation"; public const string VerbatimStringLiteral = "string - verbatim"; public const string StringEscapeCharacter = "string - escape character"; public const string ClassName = "class name"; public const string RecordClassName = "record class name"; public const string DelegateName = "delegate name"; public const string EnumName = "enum name"; public const string InterfaceName = "interface name"; public const string ModuleName = "module name"; public const string StructName = "struct name"; public const string RecordStructName = "record struct name"; public const string TypeParameterName = "type parameter name"; public const string FieldName = "field name"; public const string EnumMemberName = "enum member name"; public const string ConstantName = "constant name"; public const string LocalName = "local name"; public const string ParameterName = "parameter name"; public const string MethodName = "method name"; public const string ExtensionMethodName = "extension method name"; public const string PropertyName = "property name"; public const string EventName = "event name"; public const string NamespaceName = "namespace name"; public const string LabelName = "label name"; public const string XmlDocCommentAttributeName = "xml doc comment - attribute name"; public const string XmlDocCommentAttributeQuotes = "xml doc comment - attribute quotes"; public const string XmlDocCommentAttributeValue = "xml doc comment - attribute value"; public const string XmlDocCommentCDataSection = "xml doc comment - cdata section"; public const string XmlDocCommentComment = "xml doc comment - comment"; public const string XmlDocCommentDelimiter = "xml doc comment - delimiter"; public const string XmlDocCommentEntityReference = "xml doc comment - entity reference"; public const string XmlDocCommentName = "xml doc comment - name"; public const string XmlDocCommentProcessingInstruction = "xml doc comment - processing instruction"; public const string XmlDocCommentText = "xml doc comment - text"; public const string XmlLiteralAttributeName = "xml literal - attribute name"; public const string XmlLiteralAttributeQuotes = "xml literal - attribute quotes"; public const string XmlLiteralAttributeValue = "xml literal - attribute value"; public const string XmlLiteralCDataSection = "xml literal - cdata section"; public const string XmlLiteralComment = "xml literal - comment"; public const string XmlLiteralDelimiter = "xml literal - delimiter"; public const string XmlLiteralEmbeddedExpression = "xml literal - embedded expression"; public const string XmlLiteralEntityReference = "xml literal - entity reference"; public const string XmlLiteralName = "xml literal - name"; public const string XmlLiteralProcessingInstruction = "xml literal - processing instruction"; public const string XmlLiteralText = "xml literal - text"; public const string RegexComment = "regex - comment"; public const string RegexCharacterClass = "regex - character class"; public const string RegexAnchor = "regex - anchor"; public const string RegexQuantifier = "regex - quantifier"; public const string RegexGrouping = "regex - grouping"; public const string RegexAlternation = "regex - alternation"; public const string RegexText = "regex - text"; public const string RegexSelfEscapedCharacter = "regex - self escaped character"; public const string RegexOtherEscape = "regex - other escape"; } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Classification { public static class ClassificationTypeNames { /// <summary> /// Additive classifications types supply additional context to other classifications. /// </summary> /// <remarks> /// NOTE: Any updates to this class should also be reflected in LSP - see /// Features/LanguageServer/Protocol/Handler/SemanticTokens/SemanticTokensHelpers.cs /// </remarks> public static ImmutableArray<string> AdditiveTypeNames { get; } = ImmutableArray.Create(StaticSymbol); public const string Comment = "comment"; public const string ExcludedCode = "excluded code"; public const string Identifier = "identifier"; public const string Keyword = "keyword"; public const string ControlKeyword = "keyword - control"; public const string NumericLiteral = "number"; public const string Operator = "operator"; public const string OperatorOverloaded = "operator - overloaded"; public const string PreprocessorKeyword = "preprocessor keyword"; public const string StringLiteral = "string"; public const string WhiteSpace = "whitespace"; public const string Text = "text"; internal const string ReassignedVariable = "reassigned variable"; public const string StaticSymbol = "static symbol"; public const string PreprocessorText = "preprocessor text"; public const string Punctuation = "punctuation"; public const string VerbatimStringLiteral = "string - verbatim"; public const string StringEscapeCharacter = "string - escape character"; public const string ClassName = "class name"; public const string RecordClassName = "record class name"; public const string DelegateName = "delegate name"; public const string EnumName = "enum name"; public const string InterfaceName = "interface name"; public const string ModuleName = "module name"; public const string StructName = "struct name"; public const string RecordStructName = "record struct name"; public const string TypeParameterName = "type parameter name"; public const string FieldName = "field name"; public const string EnumMemberName = "enum member name"; public const string ConstantName = "constant name"; public const string LocalName = "local name"; public const string ParameterName = "parameter name"; public const string MethodName = "method name"; public const string ExtensionMethodName = "extension method name"; public const string PropertyName = "property name"; public const string EventName = "event name"; public const string NamespaceName = "namespace name"; public const string LabelName = "label name"; public const string XmlDocCommentAttributeName = "xml doc comment - attribute name"; public const string XmlDocCommentAttributeQuotes = "xml doc comment - attribute quotes"; public const string XmlDocCommentAttributeValue = "xml doc comment - attribute value"; public const string XmlDocCommentCDataSection = "xml doc comment - cdata section"; public const string XmlDocCommentComment = "xml doc comment - comment"; public const string XmlDocCommentDelimiter = "xml doc comment - delimiter"; public const string XmlDocCommentEntityReference = "xml doc comment - entity reference"; public const string XmlDocCommentName = "xml doc comment - name"; public const string XmlDocCommentProcessingInstruction = "xml doc comment - processing instruction"; public const string XmlDocCommentText = "xml doc comment - text"; public const string XmlLiteralAttributeName = "xml literal - attribute name"; public const string XmlLiteralAttributeQuotes = "xml literal - attribute quotes"; public const string XmlLiteralAttributeValue = "xml literal - attribute value"; public const string XmlLiteralCDataSection = "xml literal - cdata section"; public const string XmlLiteralComment = "xml literal - comment"; public const string XmlLiteralDelimiter = "xml literal - delimiter"; public const string XmlLiteralEmbeddedExpression = "xml literal - embedded expression"; public const string XmlLiteralEntityReference = "xml literal - entity reference"; public const string XmlLiteralName = "xml literal - name"; public const string XmlLiteralProcessingInstruction = "xml literal - processing instruction"; public const string XmlLiteralText = "xml literal - text"; public const string RegexComment = "regex - comment"; public const string RegexCharacterClass = "regex - character class"; public const string RegexAnchor = "regex - anchor"; public const string RegexQuantifier = "regex - quantifier"; public const string RegexGrouping = "regex - grouping"; public const string RegexAlternation = "regex - alternation"; public const string RegexText = "regex - text"; public const string RegexSelfEscapedCharacter = "regex - self escaped character"; public const string RegexOtherEscape = "regex - other escape"; } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/VisualBasic/Portable/BoundTree/BoundPseudoVariable.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundPseudoVariable Protected Overrides Function MakeRValueImpl() As BoundExpression If Not _IsLValue Then Return Me End If Return Update(_LocalSymbol, isLValue:=False, emitExpressions:=_EmitExpressions, type:=Type) 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. Namespace Microsoft.CodeAnalysis.VisualBasic Partial Friend Class BoundPseudoVariable Protected Overrides Function MakeRValueImpl() As BoundExpression If Not _IsLValue Then Return Me End If Return Update(_LocalSymbol, isLValue:=False, emitExpressions:=_EmitExpressions, type:=Type) End Function End Class End Namespace
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/VisualStudio/Core/Impl/CodeModel/Collections/ExternalParameterCollection.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections.Immutable; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class ExternalParameterCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, AbstractExternalCodeMember parent, ProjectId projectId) { var collection = new ExternalParameterCollection(state, parent, projectId); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ProjectId _projectId; private ExternalParameterCollection( CodeModelState state, AbstractExternalCodeMember parent, ProjectId projectId) : base(state, parent) { _projectId = projectId; } private AbstractExternalCodeMember ParentElement { get { return (AbstractExternalCodeMember)this.Parent; } } private ImmutableArray<IParameterSymbol> GetParameters() { var symbol = this.ParentElement.LookupSymbol(); return symbol.GetParameters(); } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var parameters = GetParameters(); if (index < parameters.Length) { element = (EnvDTE.CodeElement)ExternalCodeParameter.Create(this.State, _projectId, parameters[index], this.ParentElement); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var parameters = GetParameters(); var index = parameters.IndexOf(p => p.Name == name); if (index >= 0 && index < parameters.Length) { element = (EnvDTE.CodeElement)ExternalCodeParameter.Create(this.State, _projectId, parameters[index], this.ParentElement); return true; } element = null; return false; } public override int Count { get { var parameters = GetParameters(); return parameters.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.Collections.Immutable; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.ExternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections { [ComVisible(true)] [ComDefaultInterface(typeof(ICodeElements))] public sealed class ExternalParameterCollection : AbstractCodeElementCollection { internal static EnvDTE.CodeElements Create( CodeModelState state, AbstractExternalCodeMember parent, ProjectId projectId) { var collection = new ExternalParameterCollection(state, parent, projectId); return (EnvDTE.CodeElements)ComAggregate.CreateAggregatedObject(collection); } private readonly ProjectId _projectId; private ExternalParameterCollection( CodeModelState state, AbstractExternalCodeMember parent, ProjectId projectId) : base(state, parent) { _projectId = projectId; } private AbstractExternalCodeMember ParentElement { get { return (AbstractExternalCodeMember)this.Parent; } } private ImmutableArray<IParameterSymbol> GetParameters() { var symbol = this.ParentElement.LookupSymbol(); return symbol.GetParameters(); } protected override bool TryGetItemByIndex(int index, out EnvDTE.CodeElement element) { var parameters = GetParameters(); if (index < parameters.Length) { element = (EnvDTE.CodeElement)ExternalCodeParameter.Create(this.State, _projectId, parameters[index], this.ParentElement); return true; } element = null; return false; } protected override bool TryGetItemByName(string name, out EnvDTE.CodeElement element) { var parameters = GetParameters(); var index = parameters.IndexOf(p => p.Name == name); if (index >= 0 && index < parameters.Length) { element = (EnvDTE.CodeElement)ExternalCodeParameter.Create(this.State, _projectId, parameters[index], this.ParentElement); return true; } element = null; return false; } public override int Count { get { var parameters = GetParameters(); return parameters.Length; } } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/VisualStudio/Core/Def/Implementation/ColorSchemes/ColorSchemeApplier.ClassificationVerifier.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Security.Permissions; using System.Windows; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.ColorSchemes; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ColorSchemes { internal partial class ColorSchemeApplier { private sealed class ClassificationVerifier : ForegroundThreadAffinitizedObject { private readonly IServiceProvider _serviceProvider; private readonly ImmutableDictionary<SchemeName, ImmutableDictionary<Guid, ImmutableDictionary<string, uint>>> _colorSchemes; private static readonly Guid TextEditorMEFItemsColorCategory = new("75a05685-00a8-4ded-bae5-e7a50bfa929a"); // These classification colors (0x00BBGGRR) should match the VS\EditorColors.xml file. // They are not in the scheme files because they are core classifications. private const uint DarkThemePlainText = 0x00DCDCDCu; private const uint DarkThemeIdentifier = DarkThemePlainText; private const uint DarkThemeOperator = 0x00B4B4B4u; private const uint DarkThemeKeyword = 0x00D69C56u; private const uint LightThemePlainText = 0x00000000u; private const uint LightThemeIdentifier = LightThemePlainText; private const uint LightThemeOperator = LightThemePlainText; private const uint LightThemeKeyword = 0x00FF0000u; private const string PlainTextClassificationTypeName = "plain text"; // Dark Theme Core Classifications private static ImmutableDictionary<string, uint> DarkThemeForeground => new Dictionary<string, uint>() { [PlainTextClassificationTypeName] = DarkThemePlainText, [ClassificationTypeNames.Identifier] = DarkThemeIdentifier, [ClassificationTypeNames.Keyword] = DarkThemeKeyword, [ClassificationTypeNames.Operator] = DarkThemeOperator, }.ToImmutableDictionary(); // Light, Blue, or AdditionalContrast Theme Core Classifications private static ImmutableDictionary<string, uint> BlueLightThemeForeground => new Dictionary<string, uint>() { [PlainTextClassificationTypeName] = LightThemePlainText, [ClassificationTypeNames.Identifier] = LightThemeIdentifier, [ClassificationTypeNames.Keyword] = LightThemeKeyword, [ClassificationTypeNames.Operator] = LightThemeOperator, }.ToImmutableDictionary(); // The High Contrast theme is not included because we do not want to make changes when the user is in High Contrast mode. private IVsFontAndColorStorage? _fontAndColorStorage; private IVsFontAndColorUtilities? _fontAndColorUtilities; private ImmutableArray<string> Classifications { get; } public ClassificationVerifier(IThreadingContext threadingContext, IServiceProvider serviceProvider, ImmutableDictionary<SchemeName, ColorScheme> colorSchemes) : base(threadingContext) { _serviceProvider = serviceProvider; _colorSchemes = colorSchemes.ToImmutableDictionary( nameAndScheme => nameAndScheme.Key, nameAndScheme => nameAndScheme.Value.Themes.ToImmutableDictionary( theme => theme.Guid, theme => theme.Category.Colors .Where(color => color.Foreground.HasValue) .ToImmutableDictionary(color => color.Name, color => color.Foreground!.Value))); // Gather all the classifications from the core and scheme dictionaries. var coreClassifications = DarkThemeForeground.Keys.Concat(BlueLightThemeForeground.Keys).Distinct(); var colorSchemeClassifications = _colorSchemes.Values.SelectMany(scheme => scheme.Values.SelectMany(theme => theme.Keys)).Distinct(); Classifications = coreClassifications.Concat(colorSchemeClassifications).ToImmutableArray(); } /// <summary> /// Determines if any Classification foreground colors have been customized in Fonts and Colors. /// </summary> public bool AreForegroundColorsCustomized(SchemeName schemeName, Guid themeId) { AssertIsForeground(); // Ensure we are initialized if (_fontAndColorStorage is null) { _fontAndColorStorage = _serviceProvider.GetService<SVsFontAndColorStorage, IVsFontAndColorStorage>(); _fontAndColorUtilities = (IVsFontAndColorUtilities)_fontAndColorStorage!; } // Make no changes when in high contast mode or in unknown theme. if (SystemParameters.HighContrast || !_colorSchemes.TryGetValue(schemeName, out var colorScheme) || !colorScheme.TryGetValue(themeId, out var colorSchemeTheme)) { return false; } var coreThemeColors = (themeId == KnownColorThemes.Dark) ? DarkThemeForeground : BlueLightThemeForeground; // Open Text Editor category for readonly access and do not load items if they are defaulted. if (_fontAndColorStorage.OpenCategory(TextEditorMEFItemsColorCategory, (uint)__FCSTORAGEFLAGS.FCSF_READONLY) != VSConstants.S_OK) { // We were unable to access color information. return false; } try { foreach (var classification in Classifications) { var colorItems = new ColorableItemInfo[1]; if (_fontAndColorStorage.GetItem(classification, colorItems) != VSConstants.S_OK) { // Classifications that are still defaulted will not have entries. continue; } var colorItem = colorItems[0]; if (IsClassificationCustomized(coreThemeColors, colorSchemeTheme, colorItem, classification)) { return true; } } } finally { _fontAndColorStorage.CloseCategory(); } return false; } /// <summary> /// Determines if the ColorableItemInfo's Foreground has been customized to a color that doesn't match the /// selected scheme. /// </summary> private bool IsClassificationCustomized( ImmutableDictionary<string, uint> coreThemeColors, ImmutableDictionary<string, uint> schemeThemeColors, ColorableItemInfo colorItem, string classification) { AssertIsForeground(); Contract.ThrowIfNull(_fontAndColorUtilities); var foregroundColorRef = colorItem.crForeground; if (_fontAndColorUtilities.GetColorType(foregroundColorRef, out var foregroundColorType) != VSConstants.S_OK) { // Without being able to check color type, we cannot make a determination. return false; } // If the color is defaulted then it isn't customized. if (foregroundColorType == (int)__VSCOLORTYPE.CT_AUTOMATIC) { return false; } // Since the color type isn't default then it has been customized, we will // perform an additional check for RGB colors to see if the customized color // matches the color scheme color. if (foregroundColorType != (int)__VSCOLORTYPE.CT_RAW) { return true; } if (coreThemeColors.TryGetValue(classification, out var coreColor)) { return foregroundColorRef != coreColor; } if (schemeThemeColors.TryGetValue(classification, out var schemeColor)) { return foregroundColorRef != schemeColor; } // Since Classification inheritance isn't represented in the scheme files, // this switch case will handle the 3 cases we expect. var fallbackColor = classification switch { ClassificationTypeNames.OperatorOverloaded => coreThemeColors[ClassificationTypeNames.Operator], ClassificationTypeNames.ControlKeyword => coreThemeColors[ClassificationTypeNames.Keyword], _ => coreThemeColors[ClassificationTypeNames.Identifier] }; return foregroundColorRef != fallbackColor; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Security.Permissions; using System.Windows; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.Editor.ColorSchemes; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TextManager.Interop; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.ColorSchemes { internal partial class ColorSchemeApplier { private sealed class ClassificationVerifier : ForegroundThreadAffinitizedObject { private readonly IServiceProvider _serviceProvider; private readonly ImmutableDictionary<SchemeName, ImmutableDictionary<Guid, ImmutableDictionary<string, uint>>> _colorSchemes; private static readonly Guid TextEditorMEFItemsColorCategory = new("75a05685-00a8-4ded-bae5-e7a50bfa929a"); // These classification colors (0x00BBGGRR) should match the VS\EditorColors.xml file. // They are not in the scheme files because they are core classifications. private const uint DarkThemePlainText = 0x00DCDCDCu; private const uint DarkThemeIdentifier = DarkThemePlainText; private const uint DarkThemeOperator = 0x00B4B4B4u; private const uint DarkThemeKeyword = 0x00D69C56u; private const uint LightThemePlainText = 0x00000000u; private const uint LightThemeIdentifier = LightThemePlainText; private const uint LightThemeOperator = LightThemePlainText; private const uint LightThemeKeyword = 0x00FF0000u; private const string PlainTextClassificationTypeName = "plain text"; // Dark Theme Core Classifications private static ImmutableDictionary<string, uint> DarkThemeForeground => new Dictionary<string, uint>() { [PlainTextClassificationTypeName] = DarkThemePlainText, [ClassificationTypeNames.Identifier] = DarkThemeIdentifier, [ClassificationTypeNames.Keyword] = DarkThemeKeyword, [ClassificationTypeNames.Operator] = DarkThemeOperator, }.ToImmutableDictionary(); // Light, Blue, or AdditionalContrast Theme Core Classifications private static ImmutableDictionary<string, uint> BlueLightThemeForeground => new Dictionary<string, uint>() { [PlainTextClassificationTypeName] = LightThemePlainText, [ClassificationTypeNames.Identifier] = LightThemeIdentifier, [ClassificationTypeNames.Keyword] = LightThemeKeyword, [ClassificationTypeNames.Operator] = LightThemeOperator, }.ToImmutableDictionary(); // The High Contrast theme is not included because we do not want to make changes when the user is in High Contrast mode. private IVsFontAndColorStorage? _fontAndColorStorage; private IVsFontAndColorUtilities? _fontAndColorUtilities; private ImmutableArray<string> Classifications { get; } public ClassificationVerifier(IThreadingContext threadingContext, IServiceProvider serviceProvider, ImmutableDictionary<SchemeName, ColorScheme> colorSchemes) : base(threadingContext) { _serviceProvider = serviceProvider; _colorSchemes = colorSchemes.ToImmutableDictionary( nameAndScheme => nameAndScheme.Key, nameAndScheme => nameAndScheme.Value.Themes.ToImmutableDictionary( theme => theme.Guid, theme => theme.Category.Colors .Where(color => color.Foreground.HasValue) .ToImmutableDictionary(color => color.Name, color => color.Foreground!.Value))); // Gather all the classifications from the core and scheme dictionaries. var coreClassifications = DarkThemeForeground.Keys.Concat(BlueLightThemeForeground.Keys).Distinct(); var colorSchemeClassifications = _colorSchemes.Values.SelectMany(scheme => scheme.Values.SelectMany(theme => theme.Keys)).Distinct(); Classifications = coreClassifications.Concat(colorSchemeClassifications).ToImmutableArray(); } /// <summary> /// Determines if any Classification foreground colors have been customized in Fonts and Colors. /// </summary> public bool AreForegroundColorsCustomized(SchemeName schemeName, Guid themeId) { AssertIsForeground(); // Ensure we are initialized if (_fontAndColorStorage is null) { _fontAndColorStorage = _serviceProvider.GetService<SVsFontAndColorStorage, IVsFontAndColorStorage>(); _fontAndColorUtilities = (IVsFontAndColorUtilities)_fontAndColorStorage!; } // Make no changes when in high contast mode or in unknown theme. if (SystemParameters.HighContrast || !_colorSchemes.TryGetValue(schemeName, out var colorScheme) || !colorScheme.TryGetValue(themeId, out var colorSchemeTheme)) { return false; } var coreThemeColors = (themeId == KnownColorThemes.Dark) ? DarkThemeForeground : BlueLightThemeForeground; // Open Text Editor category for readonly access and do not load items if they are defaulted. if (_fontAndColorStorage.OpenCategory(TextEditorMEFItemsColorCategory, (uint)__FCSTORAGEFLAGS.FCSF_READONLY) != VSConstants.S_OK) { // We were unable to access color information. return false; } try { foreach (var classification in Classifications) { var colorItems = new ColorableItemInfo[1]; if (_fontAndColorStorage.GetItem(classification, colorItems) != VSConstants.S_OK) { // Classifications that are still defaulted will not have entries. continue; } var colorItem = colorItems[0]; if (IsClassificationCustomized(coreThemeColors, colorSchemeTheme, colorItem, classification)) { return true; } } } finally { _fontAndColorStorage.CloseCategory(); } return false; } /// <summary> /// Determines if the ColorableItemInfo's Foreground has been customized to a color that doesn't match the /// selected scheme. /// </summary> private bool IsClassificationCustomized( ImmutableDictionary<string, uint> coreThemeColors, ImmutableDictionary<string, uint> schemeThemeColors, ColorableItemInfo colorItem, string classification) { AssertIsForeground(); Contract.ThrowIfNull(_fontAndColorUtilities); var foregroundColorRef = colorItem.crForeground; if (_fontAndColorUtilities.GetColorType(foregroundColorRef, out var foregroundColorType) != VSConstants.S_OK) { // Without being able to check color type, we cannot make a determination. return false; } // If the color is defaulted then it isn't customized. if (foregroundColorType == (int)__VSCOLORTYPE.CT_AUTOMATIC) { return false; } // Since the color type isn't default then it has been customized, we will // perform an additional check for RGB colors to see if the customized color // matches the color scheme color. if (foregroundColorType != (int)__VSCOLORTYPE.CT_RAW) { return true; } if (coreThemeColors.TryGetValue(classification, out var coreColor)) { return foregroundColorRef != coreColor; } if (schemeThemeColors.TryGetValue(classification, out var schemeColor)) { return foregroundColorRef != schemeColor; } // Since Classification inheritance isn't represented in the scheme files, // this switch case will handle the 3 cases we expect. var fallbackColor = classification switch { ClassificationTypeNames.OperatorOverloaded => coreThemeColors[ClassificationTypeNames.Operator], ClassificationTypeNames.ControlKeyword => coreThemeColors[ClassificationTypeNames.Keyword], _ => coreThemeColors[ClassificationTypeNames.Identifier] }; return foregroundColorRef != fallbackColor; } } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/EditorFeatures/VisualBasic/EndConstructGeneration/EndConstructStatementVisitor_IfStatement.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.Shared.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration Partial Friend Class EndConstructStatementVisitor Public Overrides Function VisitIfStatement(node As IfStatementSyntax) As AbstractEndConstructResult Dim needsEnd = node.GetAncestorsOrThis(Of MultiLineIfBlockSyntax)().Any(Function(block) block.EndIfStatement.IsMissing) If needsEnd Then Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(node.SpanStart) Return New SpitLinesResult({"", aligningWhitespace & "End If"}) Else Return Nothing End If End Function Public Overrides Function VisitSingleLineIfStatement(node As SingleLineIfStatementSyntax) As AbstractEndConstructResult Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(node.SpanStart) Dim indentedWhitespace = aligningWhitespace & " " Dim whitespaceTrivia = {SyntaxFactory.WhitespaceTrivia(aligningWhitespace)}.ToSyntaxTriviaList() Dim endOfLine = SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter) Dim elseBlock As ElseBlockSyntax = Nothing If node.ElseClause IsNot Nothing Then Dim trailingTrivia = If(node.ElseClause.ElseKeyword.HasTrailingTrivia AndAlso node.ElseClause.ElseKeyword.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia), node.ElseClause.ElseKeyword.TrailingTrivia, {endOfLine}.ToSyntaxTriviaList()) elseBlock = SyntaxFactory.ElseBlock(SyntaxFactory.ElseStatement(SyntaxFactory.Token(whitespaceTrivia, SyntaxKind.ElseKeyword, trailingTrivia)), ConvertSingleLineStatementsToMultiLineStatements(node.ElseClause.Statements, indentedWhitespace)) End If Dim ifBlock = SyntaxFactory.MultiLineIfBlock( SyntaxFactory.IfStatement(node.IfKeyword, node.Condition, node.ThenKeyword).WithTrailingTrivia(endOfLine), ConvertSingleLineStatementsToMultiLineStatements(node.Statements, indentedWhitespace), New SyntaxList(Of ElseIfBlockSyntax), elseBlock, SyntaxFactory.EndIfStatement( SyntaxFactory.Token(whitespaceTrivia, SyntaxKind.EndKeyword, {SyntaxFactory.WhitespaceTrivia(" ")}.ToSyntaxTriviaList(), "End"), SyntaxFactory.Token(Nothing, SyntaxKind.IfKeyword, {endOfLine}.ToSyntaxTriviaList(), "If"))) Dim position = If(ifBlock.Statements.Any(), ifBlock.Statements(0).SpanStart, ifBlock.IfStatement.Span.End + _state.NewLineCharacter.Length) Dim ifNodeToken As SyntaxNodeOrToken = ifBlock Return New ReplaceSpanResult(node.FullSpan.ToSnapshotSpan(_subjectBuffer.CurrentSnapshot), ifNodeToken.ToFullString(), position) End Function ''' <summary> ''' Given a separatedSyntaxList of statements separated by colons, converts them to a ''' separate syntax list of statements separated by newlines ''' </summary> ''' <param name="statements">The list of statements to convert.</param> ''' <param name="indentedWhitespace">The whitespace to indent with.</param> Private Function ConvertSingleLineStatementsToMultiLineStatements(statements As SyntaxList(Of StatementSyntax), indentedWhitespace As String) As SyntaxList(Of StatementSyntax) If statements = Nothing OrElse statements.Count = 0 Then ' Return an empty statement with a newline Return SyntaxFactory.List({DirectCast(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.EmptyToken, SyntaxFactory.TriviaList(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)))), StatementSyntax)}) End If Dim indentedWhitespaceTrivia = SpecializedCollections.SingletonEnumerable(SyntaxFactory.WhitespaceTrivia(indentedWhitespace)) Dim newList As New List(Of StatementSyntax)(capacity:=statements.Count) Dim triviaLeftForNextStatement As IEnumerable(Of SyntaxTrivia) = New List(Of SyntaxTrivia) ' If the last statement itself is an End If statement, we should skip it Dim lastStatementToProcess = statements.Count - 1 If statements.LastOrDefault().IsKind(SyntaxKind.EndIfStatement) Then lastStatementToProcess = statements.Count - 2 End If For i = 0 To lastStatementToProcess Dim statement = statements(i) ' Add the new whitespace on the start of the statement If statement.Kind <> SyntaxKind.EmptyStatement OrElse statement.HasTrailingTrivia Then Dim leadingTrivia = indentedWhitespaceTrivia.Concat(triviaLeftForNextStatement.Concat(statement.GetLeadingTrivia()).WithoutLeadingWhitespaceOrEndOfLine()) statement = statement.WithLeadingTrivia(leadingTrivia) End If ' We want to drop any whitespace trivia from the ' end Dim trailingTrivia = New List(Of SyntaxTrivia) Dim separator As SyntaxTrivia = Nothing Dim lastToken = statement.GetLastToken(includeZeroWidth:=True) For Each trivia In lastToken.TrailingTrivia If trivia.Kind = SyntaxKind.ColonTrivia Then separator = trivia Exit For End If trailingTrivia.Add(trivia) Next Do While trailingTrivia.Count > 0 AndAlso trailingTrivia.Last().Kind = SyntaxKind.WhitespaceTrivia trailingTrivia.RemoveAt(trailingTrivia.Count - 1) Loop If separator.Kind <> SyntaxKind.None OrElse Not trailingTrivia.Any Then trailingTrivia.Add(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)) End If statement = statement.WithTrailingTrivia(trailingTrivia) newList.Add(statement) triviaLeftForNextStatement = lastToken.TrailingTrivia.SkipWhile(Function(t) t <> separator).Where(Function(t) t.Kind <> SyntaxKind.ColonTrivia) Next Return SyntaxFactory.List(newList) 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.Shared.Extensions Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.EndConstructGeneration Partial Friend Class EndConstructStatementVisitor Public Overrides Function VisitIfStatement(node As IfStatementSyntax) As AbstractEndConstructResult Dim needsEnd = node.GetAncestorsOrThis(Of MultiLineIfBlockSyntax)().Any(Function(block) block.EndIfStatement.IsMissing) If needsEnd Then Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(node.SpanStart) Return New SpitLinesResult({"", aligningWhitespace & "End If"}) Else Return Nothing End If End Function Public Overrides Function VisitSingleLineIfStatement(node As SingleLineIfStatementSyntax) As AbstractEndConstructResult Dim aligningWhitespace = _subjectBuffer.CurrentSnapshot.GetAligningWhitespace(node.SpanStart) Dim indentedWhitespace = aligningWhitespace & " " Dim whitespaceTrivia = {SyntaxFactory.WhitespaceTrivia(aligningWhitespace)}.ToSyntaxTriviaList() Dim endOfLine = SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter) Dim elseBlock As ElseBlockSyntax = Nothing If node.ElseClause IsNot Nothing Then Dim trailingTrivia = If(node.ElseClause.ElseKeyword.HasTrailingTrivia AndAlso node.ElseClause.ElseKeyword.TrailingTrivia.Any(SyntaxKind.EndOfLineTrivia), node.ElseClause.ElseKeyword.TrailingTrivia, {endOfLine}.ToSyntaxTriviaList()) elseBlock = SyntaxFactory.ElseBlock(SyntaxFactory.ElseStatement(SyntaxFactory.Token(whitespaceTrivia, SyntaxKind.ElseKeyword, trailingTrivia)), ConvertSingleLineStatementsToMultiLineStatements(node.ElseClause.Statements, indentedWhitespace)) End If Dim ifBlock = SyntaxFactory.MultiLineIfBlock( SyntaxFactory.IfStatement(node.IfKeyword, node.Condition, node.ThenKeyword).WithTrailingTrivia(endOfLine), ConvertSingleLineStatementsToMultiLineStatements(node.Statements, indentedWhitespace), New SyntaxList(Of ElseIfBlockSyntax), elseBlock, SyntaxFactory.EndIfStatement( SyntaxFactory.Token(whitespaceTrivia, SyntaxKind.EndKeyword, {SyntaxFactory.WhitespaceTrivia(" ")}.ToSyntaxTriviaList(), "End"), SyntaxFactory.Token(Nothing, SyntaxKind.IfKeyword, {endOfLine}.ToSyntaxTriviaList(), "If"))) Dim position = If(ifBlock.Statements.Any(), ifBlock.Statements(0).SpanStart, ifBlock.IfStatement.Span.End + _state.NewLineCharacter.Length) Dim ifNodeToken As SyntaxNodeOrToken = ifBlock Return New ReplaceSpanResult(node.FullSpan.ToSnapshotSpan(_subjectBuffer.CurrentSnapshot), ifNodeToken.ToFullString(), position) End Function ''' <summary> ''' Given a separatedSyntaxList of statements separated by colons, converts them to a ''' separate syntax list of statements separated by newlines ''' </summary> ''' <param name="statements">The list of statements to convert.</param> ''' <param name="indentedWhitespace">The whitespace to indent with.</param> Private Function ConvertSingleLineStatementsToMultiLineStatements(statements As SyntaxList(Of StatementSyntax), indentedWhitespace As String) As SyntaxList(Of StatementSyntax) If statements = Nothing OrElse statements.Count = 0 Then ' Return an empty statement with a newline Return SyntaxFactory.List({DirectCast(SyntaxFactory.EmptyStatement(SyntaxFactory.Token(SyntaxKind.EmptyToken, SyntaxFactory.TriviaList(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)))), StatementSyntax)}) End If Dim indentedWhitespaceTrivia = SpecializedCollections.SingletonEnumerable(SyntaxFactory.WhitespaceTrivia(indentedWhitespace)) Dim newList As New List(Of StatementSyntax)(capacity:=statements.Count) Dim triviaLeftForNextStatement As IEnumerable(Of SyntaxTrivia) = New List(Of SyntaxTrivia) ' If the last statement itself is an End If statement, we should skip it Dim lastStatementToProcess = statements.Count - 1 If statements.LastOrDefault().IsKind(SyntaxKind.EndIfStatement) Then lastStatementToProcess = statements.Count - 2 End If For i = 0 To lastStatementToProcess Dim statement = statements(i) ' Add the new whitespace on the start of the statement If statement.Kind <> SyntaxKind.EmptyStatement OrElse statement.HasTrailingTrivia Then Dim leadingTrivia = indentedWhitespaceTrivia.Concat(triviaLeftForNextStatement.Concat(statement.GetLeadingTrivia()).WithoutLeadingWhitespaceOrEndOfLine()) statement = statement.WithLeadingTrivia(leadingTrivia) End If ' We want to drop any whitespace trivia from the ' end Dim trailingTrivia = New List(Of SyntaxTrivia) Dim separator As SyntaxTrivia = Nothing Dim lastToken = statement.GetLastToken(includeZeroWidth:=True) For Each trivia In lastToken.TrailingTrivia If trivia.Kind = SyntaxKind.ColonTrivia Then separator = trivia Exit For End If trailingTrivia.Add(trivia) Next Do While trailingTrivia.Count > 0 AndAlso trailingTrivia.Last().Kind = SyntaxKind.WhitespaceTrivia trailingTrivia.RemoveAt(trailingTrivia.Count - 1) Loop If separator.Kind <> SyntaxKind.None OrElse Not trailingTrivia.Any Then trailingTrivia.Add(SyntaxFactory.EndOfLineTrivia(_state.NewLineCharacter)) End If statement = statement.WithTrailingTrivia(trailingTrivia) newList.Add(statement) triviaLeftForNextStatement = lastToken.TrailingTrivia.SkipWhile(Function(t) t <> separator).Where(Function(t) t.Kind <> SyntaxKind.ColonTrivia) Next Return SyntaxFactory.List(newList) End Function End Class End Namespace
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/ExpressionEvaluator/CSharp/Test/ResultProvider/TypeNameFormatterTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Collections.ObjectModel; using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class TypeNameFormatterTests : CSharpResultProviderTestBase { [Fact] public void Primitives() { Assert.Equal("object", typeof(object).GetTypeName()); Assert.Equal("bool", typeof(bool).GetTypeName()); Assert.Equal("char", typeof(char).GetTypeName()); Assert.Equal("sbyte", typeof(sbyte).GetTypeName()); Assert.Equal("byte", typeof(byte).GetTypeName()); Assert.Equal("short", typeof(short).GetTypeName()); Assert.Equal("ushort", typeof(ushort).GetTypeName()); Assert.Equal("int", typeof(int).GetTypeName()); Assert.Equal("uint", typeof(uint).GetTypeName()); Assert.Equal("long", typeof(long).GetTypeName()); Assert.Equal("ulong", typeof(ulong).GetTypeName()); Assert.Equal("float", typeof(float).GetTypeName()); Assert.Equal("double", typeof(double).GetTypeName()); Assert.Equal("decimal", typeof(decimal).GetTypeName()); Assert.Equal("string", typeof(string).GetTypeName()); } [Fact, WorkItem(1016796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016796")] public void NestedTypes() { var source = @" public class A { public class B { } } namespace N { public class A { public class B { } } public class G1<T> { public class G2<T> { public class G3<U> { } class G4<U, V> { } } } } "; var assembly = GetAssembly(source); Assert.Equal("A", assembly.GetType("A").GetTypeName()); Assert.Equal("A.B", assembly.GetType("A+B").GetTypeName()); Assert.Equal("N.A", assembly.GetType("N.A").GetTypeName()); Assert.Equal("N.A.B", assembly.GetType("N.A+B").GetTypeName()); Assert.Equal("N.G1<int>.G2<float>.G3<double>", assembly.GetType("N.G1`1+G2`1+G3`1").MakeGenericType(typeof(int), typeof(float), typeof(double)).GetTypeName()); Assert.Equal("N.G1<int>.G2<float>.G4<double, ushort>", assembly.GetType("N.G1`1+G2`1+G4`2").MakeGenericType(typeof(int), typeof(float), typeof(double), typeof(ushort)).GetTypeName()); } [Fact] public void GenericTypes() { var source = @" public class A { public class B { } } namespace N { public class C<T, U> { public class D<V, W> { } } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = typeA.GetNestedType("B"); var typeC = assembly.GetType("N.C`2"); var typeD = typeC.GetNestedType("D`2"); var typeInt = typeof(int); var typeString = typeof(string); var typeCIntString = typeC.MakeGenericType(typeInt, typeString); Assert.Equal("N.C<T, U>", typeC.GetTypeName()); Assert.Equal("N.C<int, string>", typeCIntString.GetTypeName()); Assert.Equal("N.C<A, A.B>", typeC.MakeGenericType(typeA, typeB).GetTypeName()); Assert.Equal("N.C<int, string>.D<A, A.B>", typeD.MakeGenericType(typeInt, typeString, typeA, typeB).GetTypeName()); Assert.Equal("N.C<A, N.C<int, string>>.D<N.C<int, string>, A.B>", typeD.MakeGenericType(typeA, typeCIntString, typeCIntString, typeB).GetTypeName()); } [Fact] public void NonGenericInGeneric() { var source = @" public class A<T> { public class B { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A`1"); var typeB = typeA.GetNestedType("B"); Assert.Equal("A<int>.B", typeB.MakeGenericType(typeof(int)).GetTypeName()); } [Fact] public void PrimitiveNullableTypes() { Assert.Equal("int?", typeof(int?).GetTypeName()); Assert.Equal("bool?", typeof(bool?).GetTypeName()); } [Fact] public void NullableTypes() { var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var typeNullable = typeof(System.Nullable<>); var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.Equal("N.C?", typeNullable.MakeGenericType(typeC).GetTypeName()); Assert.Equal("N.A<N.C>?", typeNullable.MakeGenericType(typeA.MakeGenericType(typeC)).GetTypeName()); Assert.Equal("N.A<N.C>.B<N.C>?", typeNullable.MakeGenericType(typeB.MakeGenericType(typeC, typeC)).GetTypeName()); } [Fact] public void PrimitiveArrayTypes() { Assert.Equal("int[]", typeof(int[]).GetTypeName()); Assert.Equal("int[,]", typeof(int[,]).GetTypeName()); Assert.Equal("int[][,]", typeof(int[][,]).GetTypeName()); Assert.Equal("int[,][]", typeof(int[,][]).GetTypeName()); } [Fact] public void ArrayTypes() { var source = @" namespace N { public class A<T> { public class B<U> { } } public class C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.NotEqual(typeC.MakeArrayType(), typeC.MakeArrayType(1)); Assert.Equal("N.C[]", typeC.MakeArrayType().GetTypeName()); Assert.Equal("N.C[]", typeC.MakeArrayType(1).GetTypeName()); // NOTE: Multi-dimensional array that happens to exactly one dimension. Assert.Equal("N.A<N.C>[,]", typeA.MakeGenericType(typeC).MakeArrayType(2).GetTypeName()); Assert.Equal("N.A<N.C[]>.B<N.C>[,,]", typeB.MakeGenericType(typeC.MakeArrayType(), typeC).MakeArrayType(3).GetTypeName()); } [Fact] public void CustomBoundsArrayTypes() { Array instance = Array.CreateInstance(typeof(int), new[] { 1, 2, 3, }, new[] { 4, 5, 6, }); Assert.Equal("int[,,]", instance.GetType().GetTypeName()); Assert.Equal("int[][,,]", instance.GetType().MakeArrayType().GetTypeName()); } [Fact] public void PrimitivePointerTypes() { Assert.Equal("int*", typeof(int).MakePointerType().GetTypeName()); Assert.Equal("int**", typeof(int).MakePointerType().MakePointerType().GetTypeName()); Assert.Equal("int*[]", typeof(int).MakePointerType().MakeArrayType().GetTypeName()); } [Fact] public void PointerTypes() { var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.Equal("N.C*", typeC.MakePointerType().GetTypeName()); Assert.Equal("N.A<N.C>*", typeA.MakeGenericType(typeC).MakePointerType().GetTypeName()); Assert.Equal("N.A<N.C>.B<N.C>*", typeB.MakeGenericType(typeC, typeC).MakePointerType().GetTypeName()); } [Fact] public void Void() { Assert.Equal("void", typeof(void).GetTypeName()); Assert.Equal("void*", typeof(void).MakePointerType().GetTypeName()); } [Fact] public void KeywordIdentifiers() { var source = @" public class @object { public class @true { } } namespace @return { public class @yield<@async> { public class @await { } } namespace @false { public class @null { } } } "; var assembly = GetAssembly(source); var objectType = assembly.GetType("object"); var trueType = objectType.GetNestedType("true"); var nullType = assembly.GetType("return.false.null"); var yieldType = assembly.GetType("return.yield`1"); var constructedYieldType = yieldType.MakeGenericType(nullType); var awaitType = yieldType.GetNestedType("await"); var constructedAwaitType = awaitType.MakeGenericType(nullType); Assert.Equal("object", objectType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("object.true", trueType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.false.null", nullType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<async>", yieldType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<return.false.null>", constructedYieldType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<return.false.null>.await", constructedAwaitType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("@object", objectType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@object.@true", trueType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@false.@null", nullType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@async>", yieldType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@return.@false.@null>", constructedYieldType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@return.@false.@null>.@await", constructedAwaitType.GetTypeName(escapeKeywordIdentifiers: true)); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_KeywordEscaping() { var attributes = new[] { true }; Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(attributes), escapeKeywordIdentifiers: false)); Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(attributes), escapeKeywordIdentifiers: true)); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_Locations() { // Standalone. Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(true))); // Array element type. Assert.Equal("dynamic[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(false, true))); Assert.Equal("dynamic[][]", typeof(object[][]).GetTypeName(MakeCustomTypeInfo(false, false, true))); // Type argument of top-level type. Assert.Equal("System.Func<dynamic>", typeof(Func<object>).GetTypeName(MakeCustomTypeInfo(false, true))); var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeBConstructed = typeB.MakeGenericType(typeof(object), typeof(object)); // Type argument of nested type. Assert.Equal("N.A<object>.B<dynamic>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false, false, true))); Assert.Equal("N.A<dynamic>.B<object>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false, true, false))); Assert.Equal("N.A<dynamic>.B<dynamic>[]", typeBConstructed.MakeArrayType().GetTypeName(MakeCustomTypeInfo(false, false, true, true))); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_InvalidFlags() { // Invalid true. Assert.Equal("int", typeof(int).GetTypeName(MakeCustomTypeInfo(true))); Assert.Equal("dynamic[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(true, true))); // Too many. Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(true, true))); Assert.Equal("object", typeof(object).GetTypeName(MakeCustomTypeInfo(false, true))); // Too few. Assert.Equal("object[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(true))); Assert.Equal("object[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(false))); // Type argument of top-level type. Assert.Equal("System.Func<object>", typeof(Func<object>).GetTypeName(MakeCustomTypeInfo(true))); var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeBConstructed = typeB.MakeGenericType(typeof(object), typeof(object)); // Type argument of nested type. Assert.Equal("N.A<object>.B<object>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false))); Assert.Equal("N.A<dynamic>.B<object>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false, true))); Assert.Equal("N.A<dynamic>.B<object>[]", typeBConstructed.MakeArrayType().GetTypeName(MakeCustomTypeInfo(false, false, true))); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_OtherGuid() { var typeInfo = DkmClrCustomTypeInfo.Create(Guid.NewGuid(), new ReadOnlyCollection<byte>(new byte[] { 1 })); Assert.Equal("object", typeof(object).GetTypeName(typeInfo)); Assert.Equal("object[]", typeof(object[]).GetTypeName(typeInfo)); } [Fact] public void MangledTypeParameterName() { var il = @" .class public auto ansi beforefieldinit Type`1<'<>Mangled'> extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var type = assembly.GetType("Type`1"); var typeName = type.GetTypeName(); Assert.Equal("Type<<>Mangled>", typeName); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation 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.Collections.ObjectModel; using Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Clr; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator.UnitTests { public class TypeNameFormatterTests : CSharpResultProviderTestBase { [Fact] public void Primitives() { Assert.Equal("object", typeof(object).GetTypeName()); Assert.Equal("bool", typeof(bool).GetTypeName()); Assert.Equal("char", typeof(char).GetTypeName()); Assert.Equal("sbyte", typeof(sbyte).GetTypeName()); Assert.Equal("byte", typeof(byte).GetTypeName()); Assert.Equal("short", typeof(short).GetTypeName()); Assert.Equal("ushort", typeof(ushort).GetTypeName()); Assert.Equal("int", typeof(int).GetTypeName()); Assert.Equal("uint", typeof(uint).GetTypeName()); Assert.Equal("long", typeof(long).GetTypeName()); Assert.Equal("ulong", typeof(ulong).GetTypeName()); Assert.Equal("float", typeof(float).GetTypeName()); Assert.Equal("double", typeof(double).GetTypeName()); Assert.Equal("decimal", typeof(decimal).GetTypeName()); Assert.Equal("string", typeof(string).GetTypeName()); } [Fact, WorkItem(1016796, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1016796")] public void NestedTypes() { var source = @" public class A { public class B { } } namespace N { public class A { public class B { } } public class G1<T> { public class G2<T> { public class G3<U> { } class G4<U, V> { } } } } "; var assembly = GetAssembly(source); Assert.Equal("A", assembly.GetType("A").GetTypeName()); Assert.Equal("A.B", assembly.GetType("A+B").GetTypeName()); Assert.Equal("N.A", assembly.GetType("N.A").GetTypeName()); Assert.Equal("N.A.B", assembly.GetType("N.A+B").GetTypeName()); Assert.Equal("N.G1<int>.G2<float>.G3<double>", assembly.GetType("N.G1`1+G2`1+G3`1").MakeGenericType(typeof(int), typeof(float), typeof(double)).GetTypeName()); Assert.Equal("N.G1<int>.G2<float>.G4<double, ushort>", assembly.GetType("N.G1`1+G2`1+G4`2").MakeGenericType(typeof(int), typeof(float), typeof(double), typeof(ushort)).GetTypeName()); } [Fact] public void GenericTypes() { var source = @" public class A { public class B { } } namespace N { public class C<T, U> { public class D<V, W> { } } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A"); var typeB = typeA.GetNestedType("B"); var typeC = assembly.GetType("N.C`2"); var typeD = typeC.GetNestedType("D`2"); var typeInt = typeof(int); var typeString = typeof(string); var typeCIntString = typeC.MakeGenericType(typeInt, typeString); Assert.Equal("N.C<T, U>", typeC.GetTypeName()); Assert.Equal("N.C<int, string>", typeCIntString.GetTypeName()); Assert.Equal("N.C<A, A.B>", typeC.MakeGenericType(typeA, typeB).GetTypeName()); Assert.Equal("N.C<int, string>.D<A, A.B>", typeD.MakeGenericType(typeInt, typeString, typeA, typeB).GetTypeName()); Assert.Equal("N.C<A, N.C<int, string>>.D<N.C<int, string>, A.B>", typeD.MakeGenericType(typeA, typeCIntString, typeCIntString, typeB).GetTypeName()); } [Fact] public void NonGenericInGeneric() { var source = @" public class A<T> { public class B { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("A`1"); var typeB = typeA.GetNestedType("B"); Assert.Equal("A<int>.B", typeB.MakeGenericType(typeof(int)).GetTypeName()); } [Fact] public void PrimitiveNullableTypes() { Assert.Equal("int?", typeof(int?).GetTypeName()); Assert.Equal("bool?", typeof(bool?).GetTypeName()); } [Fact] public void NullableTypes() { var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var typeNullable = typeof(System.Nullable<>); var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.Equal("N.C?", typeNullable.MakeGenericType(typeC).GetTypeName()); Assert.Equal("N.A<N.C>?", typeNullable.MakeGenericType(typeA.MakeGenericType(typeC)).GetTypeName()); Assert.Equal("N.A<N.C>.B<N.C>?", typeNullable.MakeGenericType(typeB.MakeGenericType(typeC, typeC)).GetTypeName()); } [Fact] public void PrimitiveArrayTypes() { Assert.Equal("int[]", typeof(int[]).GetTypeName()); Assert.Equal("int[,]", typeof(int[,]).GetTypeName()); Assert.Equal("int[][,]", typeof(int[][,]).GetTypeName()); Assert.Equal("int[,][]", typeof(int[,][]).GetTypeName()); } [Fact] public void ArrayTypes() { var source = @" namespace N { public class A<T> { public class B<U> { } } public class C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.NotEqual(typeC.MakeArrayType(), typeC.MakeArrayType(1)); Assert.Equal("N.C[]", typeC.MakeArrayType().GetTypeName()); Assert.Equal("N.C[]", typeC.MakeArrayType(1).GetTypeName()); // NOTE: Multi-dimensional array that happens to exactly one dimension. Assert.Equal("N.A<N.C>[,]", typeA.MakeGenericType(typeC).MakeArrayType(2).GetTypeName()); Assert.Equal("N.A<N.C[]>.B<N.C>[,,]", typeB.MakeGenericType(typeC.MakeArrayType(), typeC).MakeArrayType(3).GetTypeName()); } [Fact] public void CustomBoundsArrayTypes() { Array instance = Array.CreateInstance(typeof(int), new[] { 1, 2, 3, }, new[] { 4, 5, 6, }); Assert.Equal("int[,,]", instance.GetType().GetTypeName()); Assert.Equal("int[][,,]", instance.GetType().MakeArrayType().GetTypeName()); } [Fact] public void PrimitivePointerTypes() { Assert.Equal("int*", typeof(int).MakePointerType().GetTypeName()); Assert.Equal("int**", typeof(int).MakePointerType().MakePointerType().GetTypeName()); Assert.Equal("int*[]", typeof(int).MakePointerType().MakeArrayType().GetTypeName()); } [Fact] public void PointerTypes() { var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeC = assembly.GetType("N.C"); Assert.Equal("N.C*", typeC.MakePointerType().GetTypeName()); Assert.Equal("N.A<N.C>*", typeA.MakeGenericType(typeC).MakePointerType().GetTypeName()); Assert.Equal("N.A<N.C>.B<N.C>*", typeB.MakeGenericType(typeC, typeC).MakePointerType().GetTypeName()); } [Fact] public void Void() { Assert.Equal("void", typeof(void).GetTypeName()); Assert.Equal("void*", typeof(void).MakePointerType().GetTypeName()); } [Fact] public void KeywordIdentifiers() { var source = @" public class @object { public class @true { } } namespace @return { public class @yield<@async> { public class @await { } } namespace @false { public class @null { } } } "; var assembly = GetAssembly(source); var objectType = assembly.GetType("object"); var trueType = objectType.GetNestedType("true"); var nullType = assembly.GetType("return.false.null"); var yieldType = assembly.GetType("return.yield`1"); var constructedYieldType = yieldType.MakeGenericType(nullType); var awaitType = yieldType.GetNestedType("await"); var constructedAwaitType = awaitType.MakeGenericType(nullType); Assert.Equal("object", objectType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("object.true", trueType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.false.null", nullType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<async>", yieldType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<return.false.null>", constructedYieldType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("return.yield<return.false.null>.await", constructedAwaitType.GetTypeName(escapeKeywordIdentifiers: false)); Assert.Equal("@object", objectType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@object.@true", trueType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@false.@null", nullType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@async>", yieldType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@return.@false.@null>", constructedYieldType.GetTypeName(escapeKeywordIdentifiers: true)); Assert.Equal("@return.@yield<@return.@false.@null>.@await", constructedAwaitType.GetTypeName(escapeKeywordIdentifiers: true)); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_KeywordEscaping() { var attributes = new[] { true }; Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(attributes), escapeKeywordIdentifiers: false)); Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(attributes), escapeKeywordIdentifiers: true)); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_Locations() { // Standalone. Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(true))); // Array element type. Assert.Equal("dynamic[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(false, true))); Assert.Equal("dynamic[][]", typeof(object[][]).GetTypeName(MakeCustomTypeInfo(false, false, true))); // Type argument of top-level type. Assert.Equal("System.Func<dynamic>", typeof(Func<object>).GetTypeName(MakeCustomTypeInfo(false, true))); var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeBConstructed = typeB.MakeGenericType(typeof(object), typeof(object)); // Type argument of nested type. Assert.Equal("N.A<object>.B<dynamic>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false, false, true))); Assert.Equal("N.A<dynamic>.B<object>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false, true, false))); Assert.Equal("N.A<dynamic>.B<dynamic>[]", typeBConstructed.MakeArrayType().GetTypeName(MakeCustomTypeInfo(false, false, true, true))); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_InvalidFlags() { // Invalid true. Assert.Equal("int", typeof(int).GetTypeName(MakeCustomTypeInfo(true))); Assert.Equal("dynamic[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(true, true))); // Too many. Assert.Equal("dynamic", typeof(object).GetTypeName(MakeCustomTypeInfo(true, true))); Assert.Equal("object", typeof(object).GetTypeName(MakeCustomTypeInfo(false, true))); // Too few. Assert.Equal("object[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(true))); Assert.Equal("object[]", typeof(object[]).GetTypeName(MakeCustomTypeInfo(false))); // Type argument of top-level type. Assert.Equal("System.Func<object>", typeof(Func<object>).GetTypeName(MakeCustomTypeInfo(true))); var source = @" namespace N { public struct A<T> { public struct B<U> { } } public struct C { } } "; var assembly = GetAssembly(source); var typeA = assembly.GetType("N.A`1"); var typeB = typeA.GetNestedType("B`1"); var typeBConstructed = typeB.MakeGenericType(typeof(object), typeof(object)); // Type argument of nested type. Assert.Equal("N.A<object>.B<object>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false))); Assert.Equal("N.A<dynamic>.B<object>", typeBConstructed.GetTypeName(MakeCustomTypeInfo(false, true))); Assert.Equal("N.A<dynamic>.B<object>[]", typeBConstructed.MakeArrayType().GetTypeName(MakeCustomTypeInfo(false, false, true))); } [WorkItem(1087216, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1087216")] [Fact] public void DynamicAttribute_OtherGuid() { var typeInfo = DkmClrCustomTypeInfo.Create(Guid.NewGuid(), new ReadOnlyCollection<byte>(new byte[] { 1 })); Assert.Equal("object", typeof(object).GetTypeName(typeInfo)); Assert.Equal("object[]", typeof(object[]).GetTypeName(typeInfo)); } [Fact] public void MangledTypeParameterName() { var il = @" .class public auto ansi beforefieldinit Type`1<'<>Mangled'> extends [mscorlib]System.Object { .method public hidebysig specialname rtspecialname instance void .ctor() cil managed { ldarg.0 call instance void [mscorlib]System.Object::.ctor() ret } } "; ImmutableArray<byte> assemblyBytes; ImmutableArray<byte> pdbBytes; CSharpTestBase.EmitILToArray(il, appendDefaultHeader: true, includePdb: false, assemblyBytes: out assemblyBytes, pdbBytes: out pdbBytes); var assembly = ReflectionUtilities.Load(assemblyBytes); var type = assembly.GetType("Type`1"); var typeName = type.GetTypeName(); Assert.Equal("Type<<>Mangled>", typeName); } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/VisualBasic/Portable/Symbols/Source/SourceComplexParameterSymbol.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.Text Imports Microsoft.CodeAnalysis.VisualBasic.Binder Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a parameter symbol defined in source. ''' </summary> Friend Class SourceComplexParameterSymbol Inherits SourceParameterSymbol Private ReadOnly _syntaxRef As SyntaxReference Private ReadOnly _flags As SourceParameterFlags ' m_lazyDefaultValue is not readonly because it is lazily computed Private _lazyDefaultValue As ConstantValue Private _lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) #If DEBUG Then Friend Sub AssertAttributesNotValidatedYet() Debug.Assert(_lazyCustomAttributesBag Is Nothing) End Sub #End If ''' <summary> ''' Symbol to copy bound attributes from, or null if the attributes are not shared among multiple source method symbols. ''' </summary> ''' <remarks> ''' Used for partial method parameters: ''' Implementation parameter always copies its attributes from the corresponding definition parameter. ''' Definition is always complex parameter and so it stores the attribute bag. ''' </remarks> Private ReadOnly Property BoundAttributesSource As SourceParameterSymbol Get Dim sourceMethod = TryCast(Me.ContainingSymbol, SourceMemberMethodSymbol) If sourceMethod Is Nothing Then Return Nothing End If Dim impl = sourceMethod.SourcePartialDefinition If impl Is Nothing Then Return Nothing End If Return DirectCast(impl.Parameters(Me.Ordinal), SourceParameterSymbol) End Get End Property Friend Overrides ReadOnly Property AttributeDeclarationList As SyntaxList(Of AttributeListSyntax) Get Return If(Me._syntaxRef Is Nothing, Nothing, DirectCast(Me._syntaxRef.GetSyntax, ParameterSyntax).AttributeLists()) End Get End Property Private Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) Dim attributes = AttributeDeclarationList Dim sourceMethod = TryCast(Me.ContainingSymbol, SourceMemberMethodSymbol) If sourceMethod Is Nothing Then Return OneOrMany.Create(attributes) End If Dim otherAttributes As SyntaxList(Of AttributeListSyntax) ' combine attributes with the corresponding parameter of a partial implementation: Dim otherPart As SourceMemberMethodSymbol = sourceMethod.SourcePartialImplementation If otherPart IsNot Nothing Then otherAttributes = DirectCast(otherPart.Parameters(Me.Ordinal), SourceParameterSymbol).AttributeDeclarationList Else otherAttributes = Nothing End If If attributes.Equals(Nothing) Then Return OneOrMany.Create(otherAttributes) ElseIf otherAttributes.Equals(Nothing) Then Return OneOrMany.Create(attributes) Else Return OneOrMany.Create(ImmutableArray.Create(attributes, otherAttributes)) End If End Function Friend Overrides Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If _lazyCustomAttributesBag Is Nothing OrElse Not _lazyCustomAttributesBag.IsSealed Then Dim copyFrom As SourceParameterSymbol = Me.BoundAttributesSource ' prevent infinite recursion: Debug.Assert(copyFrom IsNot Me) If copyFrom IsNot Nothing Then Dim attributesBag = copyFrom.GetAttributesBag() Interlocked.CompareExchange(_lazyCustomAttributesBag, attributesBag, Nothing) Else Dim attributeSyntax = Me.GetAttributeDeclarations() LoadAndValidateAttributes(attributeSyntax, _lazyCustomAttributesBag) End If End If Return _lazyCustomAttributesBag End Function Friend Overrides Function GetEarlyDecodedWellKnownAttributeData() As ParameterEarlyWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.EarlyDecodedWellKnownAttributeData, ParameterEarlyWellKnownAttributeData) End Function Friend Overrides Function GetDecodedWellKnownAttributeData() As CommonParameterWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonParameterWellKnownAttributeData) End Function Public Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return ExplicitDefaultConstantValue(SymbolsInProgress(Of ParameterSymbol).Empty) IsNot Nothing End Get End Property Friend Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get If _lazyDefaultValue Is ConstantValue.Unset Then Dim diagnostics = BindingDiagnosticBag.GetInstance() If Interlocked.CompareExchange(_lazyDefaultValue, BindDefaultValue(inProgress, diagnostics), ConstantValue.Unset) Is ConstantValue.Unset Then DirectCast(ContainingModule, SourceModuleSymbol).AddDeclarationDiagnostics(diagnostics) End If diagnostics.Free() End If Return _lazyDefaultValue End Get End Property Private Function BindDefaultValue(inProgress As SymbolsInProgress(Of ParameterSymbol), diagnostics As BindingDiagnosticBag) As ConstantValue Dim parameterSyntax = SyntaxNode If parameterSyntax Is Nothing Then Return Nothing End If Dim defaultSyntax = parameterSyntax.[Default] If defaultSyntax Is Nothing Then Return Nothing End If Dim binder As Binder = BinderBuilder.CreateBinderForParameterDefaultValue(DirectCast(ContainingModule, SourceModuleSymbol), _syntaxRef.SyntaxTree, Me, parameterSyntax) ' Before binding the default value, check if we are already in the process of binding it. If so report ' an error and return nothing. If inProgress.Contains(Me) Then Binder.ReportDiagnostic(diagnostics, defaultSyntax.Value, ERRID.ERR_CircularEvaluation1, Me) Return Nothing End If Dim inProgressBinder = New DefaultParametersInProgressBinder(inProgress.Add(Me), binder) Dim constValue As ConstantValue = Nothing inProgressBinder.BindParameterDefaultValue(Me.Type, defaultSyntax, diagnostics, constValue:=constValue) If constValue IsNot Nothing Then VerifyParamDefaultValueMatchesAttributeIfAny(constValue, defaultSyntax.Value, diagnostics) End If Return constValue End Function Friend ReadOnly Property SyntaxNode As ParameterSyntax Get Return If(_syntaxRef Is Nothing, Nothing, DirectCast(_syntaxRef.GetSyntax(), ParameterSyntax)) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get If IsImplicitlyDeclared Then Return ImmutableArray(Of SyntaxReference).Empty ElseIf _syntaxRef IsNot Nothing Then Return GetDeclaringSyntaxReferenceHelper(_syntaxRef) Else Return MyBase.DeclaringSyntaxReferences End If End Get End Property Friend NotOverridable Overrides Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean Return IsDefinedInSourceTree(Me.SyntaxNode, tree, definedWithinSpan, cancellationToken) End Function Public Overrides ReadOnly Property IsOptional As Boolean Get Return (_flags And SourceParameterFlags.Optional) <> 0 End Get End Property Public Overrides ReadOnly Property IsParamArray As Boolean Get If (_flags And SourceParameterFlags.ParamArray) <> 0 Then Return True End If Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasParamArrayAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerLineNumberAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerMemberName As Boolean Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerMemberNameAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerFilePath As Boolean Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerFilePathAttribute End Get End Property Friend Overrides ReadOnly Property CallerArgumentExpressionParameterIndex As Integer Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() If data Is Nothing Then Return -1 End If Return data.CallerArgumentExpressionParameterIndex End Get End Property ''' <summary> ''' Is parameter explicitly declared ByRef. Can be different from IsByRef only for ''' String parameters of Declare methods. ''' </summary> Friend Overrides ReadOnly Property IsExplicitByRef As Boolean Get Return (_flags And SourceParameterFlags.ByRef) <> 0 End Get End Property Private Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, syntaxRef As SyntaxReference, flags As SourceParameterFlags, defaultValueOpt As ConstantValue ) MyBase.New(container, name, ordinal, type, location) _flags = flags _lazyDefaultValue = defaultValueOpt _syntaxRef = syntaxRef End Sub ' Create a simple or complex parameter, as necessary. Friend Shared Function Create(container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, syntaxRef As SyntaxReference, flags As SourceParameterFlags, defaultValueOpt As ConstantValue) As ParameterSymbol ' Note that parameters of partial method declarations should always be complex Dim method = TryCast(container, SourceMethodSymbol) If flags <> 0 OrElse defaultValueOpt IsNot Nothing OrElse syntaxRef IsNot Nothing OrElse (method IsNot Nothing AndAlso method.IsPartial) Then Return New SourceComplexParameterSymbol(container, name, ordinal, type, location, syntaxRef, flags, defaultValueOpt) Else Return New SourceSimpleParameterSymbol(container, name, ordinal, type, location) End If End Function Friend Overrides Function ChangeOwner(newContainingSymbol As Symbol) As ParameterSymbol ' When changing the owner, it is not safe to get the constant value from this parameter symbol (Me.DefaultConstantValue). Default values for source ' parameters are computed after all members have been added to the type. See GenerateAllDeclarationErrors in SourceNamedTypeSymbol. ' Asking for the default value earlier than that can lead to infinite recursion. Instead, pass in the m_lazyDefaultValue. If the value hasn't ' been computed yet, the new symbol will compute it. Return New SourceComplexParameterSymbol(newContainingSymbol, Me.Name, Me.Ordinal, Me.Type, Me.Locations(0), _syntaxRef, _flags, _lazyDefaultValue) End Function ' Create a parameter from syntax. Friend Shared Function CreateFromSyntax(container As Symbol, syntax As ParameterSyntax, name As String, flags As SourceParameterFlags, ordinal As Integer, binder As Binder, checkModifier As CheckParameterModifierDelegate, diagnostics As BindingDiagnosticBag) As ParameterSymbol Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing If binder.OptionStrict = OptionStrict.On Then getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitArgs ElseIf binder.OptionStrict = OptionStrict.Custom Then getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumedVar1_WRN_MissingAsClauseinVarDecl End If Dim paramType = binder.DecodeModifiedIdentifierType(syntax.Identifier, syntax.AsClause, Nothing, getErrorInfo, diagnostics, ModifiedIdentifierTypeDecoderContext.ParameterType) If (flags And SourceParameterFlags.ParamArray) <> 0 AndAlso paramType.TypeKind <> TypeKind.Error Then If paramType.TypeKind <> TypeKind.Array Then ' ParamArray must be of array type. Binder.ReportDiagnostic(diagnostics, syntax.Identifier, ERRID.ERR_ParamArrayNotArray) Else Dim paramTypeAsArray = DirectCast(paramType, ArrayTypeSymbol) If Not paramTypeAsArray.IsSZArray Then ' ParamArray type must be rank-1 array. Binder.ReportDiagnostic(diagnostics, syntax.Identifier.Identifier, ERRID.ERR_ParamArrayRank) End If ' 'touch' the constructor in order to generate proper diagnostics binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_ParamArrayAttribute__ctor, syntax, diagnostics) End If End If Dim syntaxRef As SyntaxReference = Nothing ' Attributes and default values are computed lazily and need access to the parameter's syntax. ' If the parameter syntax includes either of these get a syntax reference and pass it to the parameter symbol. If (syntax.AttributeLists.Count <> 0 OrElse syntax.Default IsNot Nothing) Then syntaxRef = binder.GetSyntaxReference(syntax) End If Dim defaultValue As ConstantValue = Nothing If (flags And SourceParameterFlags.Optional) <> 0 Then ' The default value is computed lazily. If there is default syntax then set the value to ConstantValue.unset to indicate the value needs to ' be computed. If syntax.Default IsNot Nothing Then defaultValue = ConstantValue.Unset End If ' Report diagnostic if constructors for datetime and decimal default values are not available Select Case paramType.SpecialType Case SpecialType.System_DateTime binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, syntax.Default, diagnostics) Case SpecialType.System_Decimal binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor, syntax.Default, diagnostics) End Select End If Return Create(container, name, ordinal, paramType, syntax.Identifier.Identifier.GetLocation(), syntaxRef, flags, defaultValue) End Function Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol If customModifiers.IsEmpty AndAlso refCustomModifiers.IsEmpty Then Return New SourceComplexParameterSymbol(Me.ContainingSymbol, Me.Name, Me.Ordinal, type, Me.Location, _syntaxRef, _flags, _lazyDefaultValue) End If Return New SourceComplexParameterSymbolWithCustomModifiers(Me.ContainingSymbol, Me.Name, Me.Ordinal, type, Me.Location, _syntaxRef, _flags, _lazyDefaultValue, customModifiers, refCustomModifiers) End Function Private Class SourceComplexParameterSymbolWithCustomModifiers Inherits SourceComplexParameterSymbol Private ReadOnly _customModifiers As ImmutableArray(Of CustomModifier) Private ReadOnly _refCustomModifiers As ImmutableArray(Of CustomModifier) Public Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, syntaxRef As SyntaxReference, flags As SourceParameterFlags, defaultValueOpt As ConstantValue, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier) ) MyBase.New(container, name, ordinal, type, location, syntaxRef, flags, defaultValueOpt) Debug.Assert(Not customModifiers.IsEmpty OrElse Not refCustomModifiers.IsEmpty) _customModifiers = customModifiers _refCustomModifiers = refCustomModifiers Debug.Assert(_refCustomModifiers.IsEmpty OrElse IsByRef) End Sub Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return _customModifiers End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return _refCustomModifiers End Get End Property Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Imports System.Collections.Immutable Imports System.Threading Imports Microsoft.CodeAnalysis.Text Imports Microsoft.CodeAnalysis.VisualBasic.Binder Imports Microsoft.CodeAnalysis.VisualBasic.Syntax Namespace Microsoft.CodeAnalysis.VisualBasic.Symbols ''' <summary> ''' Represents a parameter symbol defined in source. ''' </summary> Friend Class SourceComplexParameterSymbol Inherits SourceParameterSymbol Private ReadOnly _syntaxRef As SyntaxReference Private ReadOnly _flags As SourceParameterFlags ' m_lazyDefaultValue is not readonly because it is lazily computed Private _lazyDefaultValue As ConstantValue Private _lazyCustomAttributesBag As CustomAttributesBag(Of VisualBasicAttributeData) #If DEBUG Then Friend Sub AssertAttributesNotValidatedYet() Debug.Assert(_lazyCustomAttributesBag Is Nothing) End Sub #End If ''' <summary> ''' Symbol to copy bound attributes from, or null if the attributes are not shared among multiple source method symbols. ''' </summary> ''' <remarks> ''' Used for partial method parameters: ''' Implementation parameter always copies its attributes from the corresponding definition parameter. ''' Definition is always complex parameter and so it stores the attribute bag. ''' </remarks> Private ReadOnly Property BoundAttributesSource As SourceParameterSymbol Get Dim sourceMethod = TryCast(Me.ContainingSymbol, SourceMemberMethodSymbol) If sourceMethod Is Nothing Then Return Nothing End If Dim impl = sourceMethod.SourcePartialDefinition If impl Is Nothing Then Return Nothing End If Return DirectCast(impl.Parameters(Me.Ordinal), SourceParameterSymbol) End Get End Property Friend Overrides ReadOnly Property AttributeDeclarationList As SyntaxList(Of AttributeListSyntax) Get Return If(Me._syntaxRef Is Nothing, Nothing, DirectCast(Me._syntaxRef.GetSyntax, ParameterSyntax).AttributeLists()) End Get End Property Private Function GetAttributeDeclarations() As OneOrMany(Of SyntaxList(Of AttributeListSyntax)) Dim attributes = AttributeDeclarationList Dim sourceMethod = TryCast(Me.ContainingSymbol, SourceMemberMethodSymbol) If sourceMethod Is Nothing Then Return OneOrMany.Create(attributes) End If Dim otherAttributes As SyntaxList(Of AttributeListSyntax) ' combine attributes with the corresponding parameter of a partial implementation: Dim otherPart As SourceMemberMethodSymbol = sourceMethod.SourcePartialImplementation If otherPart IsNot Nothing Then otherAttributes = DirectCast(otherPart.Parameters(Me.Ordinal), SourceParameterSymbol).AttributeDeclarationList Else otherAttributes = Nothing End If If attributes.Equals(Nothing) Then Return OneOrMany.Create(otherAttributes) ElseIf otherAttributes.Equals(Nothing) Then Return OneOrMany.Create(attributes) Else Return OneOrMany.Create(ImmutableArray.Create(attributes, otherAttributes)) End If End Function Friend Overrides Function GetAttributesBag() As CustomAttributesBag(Of VisualBasicAttributeData) If _lazyCustomAttributesBag Is Nothing OrElse Not _lazyCustomAttributesBag.IsSealed Then Dim copyFrom As SourceParameterSymbol = Me.BoundAttributesSource ' prevent infinite recursion: Debug.Assert(copyFrom IsNot Me) If copyFrom IsNot Nothing Then Dim attributesBag = copyFrom.GetAttributesBag() Interlocked.CompareExchange(_lazyCustomAttributesBag, attributesBag, Nothing) Else Dim attributeSyntax = Me.GetAttributeDeclarations() LoadAndValidateAttributes(attributeSyntax, _lazyCustomAttributesBag) End If End If Return _lazyCustomAttributesBag End Function Friend Overrides Function GetEarlyDecodedWellKnownAttributeData() As ParameterEarlyWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsEarlyDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.EarlyDecodedWellKnownAttributeData, ParameterEarlyWellKnownAttributeData) End Function Friend Overrides Function GetDecodedWellKnownAttributeData() As CommonParameterWellKnownAttributeData Dim attributesBag As CustomAttributesBag(Of VisualBasicAttributeData) = Me._lazyCustomAttributesBag If attributesBag Is Nothing OrElse Not attributesBag.IsDecodedWellKnownAttributeDataComputed Then attributesBag = Me.GetAttributesBag() End If Return DirectCast(attributesBag.DecodedWellKnownAttributeData, CommonParameterWellKnownAttributeData) End Function Public Overrides ReadOnly Property HasExplicitDefaultValue As Boolean Get Return ExplicitDefaultConstantValue(SymbolsInProgress(Of ParameterSymbol).Empty) IsNot Nothing End Get End Property Friend Overrides ReadOnly Property ExplicitDefaultConstantValue(inProgress As SymbolsInProgress(Of ParameterSymbol)) As ConstantValue Get If _lazyDefaultValue Is ConstantValue.Unset Then Dim diagnostics = BindingDiagnosticBag.GetInstance() If Interlocked.CompareExchange(_lazyDefaultValue, BindDefaultValue(inProgress, diagnostics), ConstantValue.Unset) Is ConstantValue.Unset Then DirectCast(ContainingModule, SourceModuleSymbol).AddDeclarationDiagnostics(diagnostics) End If diagnostics.Free() End If Return _lazyDefaultValue End Get End Property Private Function BindDefaultValue(inProgress As SymbolsInProgress(Of ParameterSymbol), diagnostics As BindingDiagnosticBag) As ConstantValue Dim parameterSyntax = SyntaxNode If parameterSyntax Is Nothing Then Return Nothing End If Dim defaultSyntax = parameterSyntax.[Default] If defaultSyntax Is Nothing Then Return Nothing End If Dim binder As Binder = BinderBuilder.CreateBinderForParameterDefaultValue(DirectCast(ContainingModule, SourceModuleSymbol), _syntaxRef.SyntaxTree, Me, parameterSyntax) ' Before binding the default value, check if we are already in the process of binding it. If so report ' an error and return nothing. If inProgress.Contains(Me) Then Binder.ReportDiagnostic(diagnostics, defaultSyntax.Value, ERRID.ERR_CircularEvaluation1, Me) Return Nothing End If Dim inProgressBinder = New DefaultParametersInProgressBinder(inProgress.Add(Me), binder) Dim constValue As ConstantValue = Nothing inProgressBinder.BindParameterDefaultValue(Me.Type, defaultSyntax, diagnostics, constValue:=constValue) If constValue IsNot Nothing Then VerifyParamDefaultValueMatchesAttributeIfAny(constValue, defaultSyntax.Value, diagnostics) End If Return constValue End Function Friend ReadOnly Property SyntaxNode As ParameterSyntax Get Return If(_syntaxRef Is Nothing, Nothing, DirectCast(_syntaxRef.GetSyntax(), ParameterSyntax)) End Get End Property Public Overrides ReadOnly Property DeclaringSyntaxReferences As ImmutableArray(Of SyntaxReference) Get If IsImplicitlyDeclared Then Return ImmutableArray(Of SyntaxReference).Empty ElseIf _syntaxRef IsNot Nothing Then Return GetDeclaringSyntaxReferenceHelper(_syntaxRef) Else Return MyBase.DeclaringSyntaxReferences End If End Get End Property Friend NotOverridable Overrides Function IsDefinedInSourceTree(tree As SyntaxTree, definedWithinSpan As TextSpan?, Optional cancellationToken As CancellationToken = Nothing) As Boolean Return IsDefinedInSourceTree(Me.SyntaxNode, tree, definedWithinSpan, cancellationToken) End Function Public Overrides ReadOnly Property IsOptional As Boolean Get Return (_flags And SourceParameterFlags.Optional) <> 0 End Get End Property Public Overrides ReadOnly Property IsParamArray As Boolean Get If (_flags And SourceParameterFlags.ParamArray) <> 0 Then Return True End If Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasParamArrayAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerLineNumber As Boolean Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerLineNumberAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerMemberName As Boolean Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerMemberNameAttribute End Get End Property Friend Overrides ReadOnly Property IsCallerFilePath As Boolean Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() Return data IsNot Nothing AndAlso data.HasCallerFilePathAttribute End Get End Property Friend Overrides ReadOnly Property CallerArgumentExpressionParameterIndex As Integer Get Dim attributeSource As SourceParameterSymbol = If(Me.BoundAttributesSource, Me) Dim data = attributeSource.GetEarlyDecodedWellKnownAttributeData() If data Is Nothing Then Return -1 End If Return data.CallerArgumentExpressionParameterIndex End Get End Property ''' <summary> ''' Is parameter explicitly declared ByRef. Can be different from IsByRef only for ''' String parameters of Declare methods. ''' </summary> Friend Overrides ReadOnly Property IsExplicitByRef As Boolean Get Return (_flags And SourceParameterFlags.ByRef) <> 0 End Get End Property Private Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, syntaxRef As SyntaxReference, flags As SourceParameterFlags, defaultValueOpt As ConstantValue ) MyBase.New(container, name, ordinal, type, location) _flags = flags _lazyDefaultValue = defaultValueOpt _syntaxRef = syntaxRef End Sub ' Create a simple or complex parameter, as necessary. Friend Shared Function Create(container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, syntaxRef As SyntaxReference, flags As SourceParameterFlags, defaultValueOpt As ConstantValue) As ParameterSymbol ' Note that parameters of partial method declarations should always be complex Dim method = TryCast(container, SourceMethodSymbol) If flags <> 0 OrElse defaultValueOpt IsNot Nothing OrElse syntaxRef IsNot Nothing OrElse (method IsNot Nothing AndAlso method.IsPartial) Then Return New SourceComplexParameterSymbol(container, name, ordinal, type, location, syntaxRef, flags, defaultValueOpt) Else Return New SourceSimpleParameterSymbol(container, name, ordinal, type, location) End If End Function Friend Overrides Function ChangeOwner(newContainingSymbol As Symbol) As ParameterSymbol ' When changing the owner, it is not safe to get the constant value from this parameter symbol (Me.DefaultConstantValue). Default values for source ' parameters are computed after all members have been added to the type. See GenerateAllDeclarationErrors in SourceNamedTypeSymbol. ' Asking for the default value earlier than that can lead to infinite recursion. Instead, pass in the m_lazyDefaultValue. If the value hasn't ' been computed yet, the new symbol will compute it. Return New SourceComplexParameterSymbol(newContainingSymbol, Me.Name, Me.Ordinal, Me.Type, Me.Locations(0), _syntaxRef, _flags, _lazyDefaultValue) End Function ' Create a parameter from syntax. Friend Shared Function CreateFromSyntax(container As Symbol, syntax As ParameterSyntax, name As String, flags As SourceParameterFlags, ordinal As Integer, binder As Binder, checkModifier As CheckParameterModifierDelegate, diagnostics As BindingDiagnosticBag) As ParameterSymbol Dim getErrorInfo As Func(Of DiagnosticInfo) = Nothing If binder.OptionStrict = OptionStrict.On Then getErrorInfo = ErrorFactory.GetErrorInfo_ERR_StrictDisallowsImplicitArgs ElseIf binder.OptionStrict = OptionStrict.Custom Then getErrorInfo = ErrorFactory.GetErrorInfo_WRN_ObjectAssumedVar1_WRN_MissingAsClauseinVarDecl End If Dim paramType = binder.DecodeModifiedIdentifierType(syntax.Identifier, syntax.AsClause, Nothing, getErrorInfo, diagnostics, ModifiedIdentifierTypeDecoderContext.ParameterType) If (flags And SourceParameterFlags.ParamArray) <> 0 AndAlso paramType.TypeKind <> TypeKind.Error Then If paramType.TypeKind <> TypeKind.Array Then ' ParamArray must be of array type. Binder.ReportDiagnostic(diagnostics, syntax.Identifier, ERRID.ERR_ParamArrayNotArray) Else Dim paramTypeAsArray = DirectCast(paramType, ArrayTypeSymbol) If Not paramTypeAsArray.IsSZArray Then ' ParamArray type must be rank-1 array. Binder.ReportDiagnostic(diagnostics, syntax.Identifier.Identifier, ERRID.ERR_ParamArrayRank) End If ' 'touch' the constructor in order to generate proper diagnostics binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_ParamArrayAttribute__ctor, syntax, diagnostics) End If End If Dim syntaxRef As SyntaxReference = Nothing ' Attributes and default values are computed lazily and need access to the parameter's syntax. ' If the parameter syntax includes either of these get a syntax reference and pass it to the parameter symbol. If (syntax.AttributeLists.Count <> 0 OrElse syntax.Default IsNot Nothing) Then syntaxRef = binder.GetSyntaxReference(syntax) End If Dim defaultValue As ConstantValue = Nothing If (flags And SourceParameterFlags.Optional) <> 0 Then ' The default value is computed lazily. If there is default syntax then set the value to ConstantValue.unset to indicate the value needs to ' be computed. If syntax.Default IsNot Nothing Then defaultValue = ConstantValue.Unset End If ' Report diagnostic if constructors for datetime and decimal default values are not available Select Case paramType.SpecialType Case SpecialType.System_DateTime binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DateTimeConstantAttribute__ctor, syntax.Default, diagnostics) Case SpecialType.System_Decimal binder.ReportUseSiteInfoForSynthesizedAttribute(WellKnownMember.System_Runtime_CompilerServices_DecimalConstantAttribute__ctor, syntax.Default, diagnostics) End Select End If Return Create(container, name, ordinal, paramType, syntax.Identifier.Identifier.GetLocation(), syntaxRef, flags, defaultValue) End Function Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return ImmutableArray(Of CustomModifier).Empty End Get End Property Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol If customModifiers.IsEmpty AndAlso refCustomModifiers.IsEmpty Then Return New SourceComplexParameterSymbol(Me.ContainingSymbol, Me.Name, Me.Ordinal, type, Me.Location, _syntaxRef, _flags, _lazyDefaultValue) End If Return New SourceComplexParameterSymbolWithCustomModifiers(Me.ContainingSymbol, Me.Name, Me.Ordinal, type, Me.Location, _syntaxRef, _flags, _lazyDefaultValue, customModifiers, refCustomModifiers) End Function Private Class SourceComplexParameterSymbolWithCustomModifiers Inherits SourceComplexParameterSymbol Private ReadOnly _customModifiers As ImmutableArray(Of CustomModifier) Private ReadOnly _refCustomModifiers As ImmutableArray(Of CustomModifier) Public Sub New( container As Symbol, name As String, ordinal As Integer, type As TypeSymbol, location As Location, syntaxRef As SyntaxReference, flags As SourceParameterFlags, defaultValueOpt As ConstantValue, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier) ) MyBase.New(container, name, ordinal, type, location, syntaxRef, flags, defaultValueOpt) Debug.Assert(Not customModifiers.IsEmpty OrElse Not refCustomModifiers.IsEmpty) _customModifiers = customModifiers _refCustomModifiers = refCustomModifiers Debug.Assert(_refCustomModifiers.IsEmpty OrElse IsByRef) End Sub Public Overrides ReadOnly Property CustomModifiers As ImmutableArray(Of CustomModifier) Get Return _customModifiers End Get End Property Public Overrides ReadOnly Property RefCustomModifiers As ImmutableArray(Of CustomModifier) Get Return _refCustomModifiers End Get End Property Friend Overrides Function WithTypeAndCustomModifiers(type As TypeSymbol, customModifiers As ImmutableArray(Of CustomModifier), refCustomModifiers As ImmutableArray(Of CustomModifier)) As ParameterSymbol Throw ExceptionUtilities.Unreachable End Function End Class End Class End Namespace
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/CSharp/Test/Syntax/Parsing/CSharpParseOptionsTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { public class CSharpParseOptionsTests : CSharpTestBase { private void TestProperty<T>(Func<CSharpParseOptions, T, CSharpParseOptions> factory, Func<CSharpParseOptions, T> getter, T validValue) { var oldOpt1 = CSharpParseOptions.Default; var newOpt1 = factory(oldOpt1, validValue); var newOpt2 = factory(newOpt1, validValue); Assert.Equal(validValue, getter(newOpt1)); Assert.Same(newOpt2, newOpt1); } [Fact] [WorkItem(15358, "https://github.com/dotnet/roslyn/issues/15358")] public void WithDocumentationModeDoesntChangeFeatures() { var kvp = new KeyValuePair<string, string>("IOperation", "true"); var po = new CSharpParseOptions().WithFeatures(new[] { kvp }); Assert.Equal(po.Features.AsSingleton(), kvp); var po2 = po.WithDocumentationMode(DocumentationMode.Diagnose); Assert.Equal(po2.Features.AsSingleton(), kvp); } [Fact] public void WithXxx() { TestProperty((old, value) => old.WithKind(value), opt => opt.Kind, SourceCodeKind.Script); TestProperty((old, value) => old.WithLanguageVersion(value), opt => opt.LanguageVersion, LanguageVersion.CSharp3); TestProperty((old, value) => old.WithDocumentationMode(value), opt => opt.DocumentationMode, DocumentationMode.None); TestProperty((old, value) => old.WithPreprocessorSymbols(value), opt => opt.PreprocessorSymbols, ImmutableArray.Create<string>("A", "B", "C")); Assert.Equal(0, CSharpParseOptions.Default.WithPreprocessorSymbols(ImmutableArray.Create<string>("A", "B")).WithPreprocessorSymbols(default(ImmutableArray<string>)).PreprocessorSymbols.Length); Assert.Equal(0, CSharpParseOptions.Default.WithPreprocessorSymbols(ImmutableArray.Create<string>("A", "B")).WithPreprocessorSymbols((IEnumerable<string>)null).PreprocessorSymbols.Length); Assert.Equal(0, CSharpParseOptions.Default.WithPreprocessorSymbols(ImmutableArray.Create<string>("A", "B")).WithPreprocessorSymbols((string[])null).PreprocessorSymbols.Length); } /// <summary> /// If this test fails, please update the <see cref="CSharpParseOptions.GetHashCode"/> /// and <see cref="CSharpParseOptions.Equals(CSharpParseOptions)"/> methods to /// make sure they are doing the right thing with your new field and then update the baseline /// here. /// </summary> [Fact] public void TestFieldsForEqualsAndGetHashCode() { ReflectionAssert.AssertPublicAndInternalFieldsAndProperties( typeof(CSharpParseOptions), "Features", "Language", "LanguageVersion", "PreprocessorSymbolNames", "PreprocessorSymbols", "SpecifiedLanguageVersion"); } [Fact] public void SpecifiedKindIsMappedCorrectly() { var options = new CSharpParseOptions(); Assert.Equal(SourceCodeKind.Regular, options.Kind); Assert.Equal(SourceCodeKind.Regular, options.SpecifiedKind); options.Errors.Verify(); options = new CSharpParseOptions(kind: SourceCodeKind.Regular); Assert.Equal(SourceCodeKind.Regular, options.Kind); Assert.Equal(SourceCodeKind.Regular, options.SpecifiedKind); options.Errors.Verify(); options = new CSharpParseOptions(kind: SourceCodeKind.Script); Assert.Equal(SourceCodeKind.Script, options.Kind); Assert.Equal(SourceCodeKind.Script, options.SpecifiedKind); options.Errors.Verify(); #pragma warning disable CS0618 // SourceCodeKind.Interactive is obsolete options = new CSharpParseOptions(kind: SourceCodeKind.Interactive); Assert.Equal(SourceCodeKind.Script, options.Kind); Assert.Equal(SourceCodeKind.Interactive, options.SpecifiedKind); #pragma warning restore CS0618 // SourceCodeKind.Interactive is obsolete options.Errors.Verify( // error CS8190: Provided source code kind is unsupported or invalid: 'Interactive'. Diagnostic(ErrorCode.ERR_BadSourceCodeKind).WithArguments("Interactive").WithLocation(1, 1)); options = new CSharpParseOptions(kind: (SourceCodeKind)int.MinValue); Assert.Equal(SourceCodeKind.Regular, options.Kind); Assert.Equal((SourceCodeKind)int.MinValue, options.SpecifiedKind); options.Errors.Verify( // warning CS8190: Provided source code kind is unsupported or invalid: '-2147483648' Diagnostic(ErrorCode.ERR_BadSourceCodeKind).WithArguments("-2147483648").WithLocation(1, 1)); } [Fact] public void TwoOptionsWithDifferentSpecifiedKindShouldNotHaveTheSameHashCodes() { var options1 = new CSharpParseOptions(kind: SourceCodeKind.Script); var options2 = new CSharpParseOptions(kind: SourceCodeKind.Script); Assert.Equal(options1.GetHashCode(), options2.GetHashCode()); // They both map internally to SourceCodeKind.Script #pragma warning disable CS0618 // SourceCodeKind.Interactive is obsolete options1 = new CSharpParseOptions(kind: SourceCodeKind.Script); options2 = new CSharpParseOptions(kind: SourceCodeKind.Interactive); #pragma warning restore CS0618 // SourceCodeKind.Interactive is obsolete Assert.NotEqual(options1.GetHashCode(), options2.GetHashCode()); } [Fact] public void TwoOptionsWithDifferentSpecifiedKindShouldNotBeEqual() { var options1 = new CSharpParseOptions(kind: SourceCodeKind.Script); var options2 = new CSharpParseOptions(kind: SourceCodeKind.Script); Assert.True(options1.Equals(options2)); // They both map internally to SourceCodeKind.Script #pragma warning disable CS0618 // SourceCodeKind.Interactive is obsolete options1 = new CSharpParseOptions(kind: SourceCodeKind.Script); options2 = new CSharpParseOptions(kind: SourceCodeKind.Interactive); #pragma warning restore CS0618 // SourceCodeKind.Interactive is obsolete Assert.False(options1.Equals(options2)); } [Fact] public void BadSourceCodeKindShouldProduceDiagnostics() { #pragma warning disable CS0618 // Type or member is obsolete var options = new CSharpParseOptions(kind: SourceCodeKind.Interactive); #pragma warning restore CS0618 // Type or member is obsolete options.Errors.Verify( // error CS8190: Provided source code kind is unsupported or invalid: 'Interactive'. Diagnostic(ErrorCode.ERR_BadSourceCodeKind).WithArguments("Interactive").WithLocation(1, 1)); } [Fact] public void BadDocumentationModeShouldProduceDiagnostics() { var options = new CSharpParseOptions(documentationMode: unchecked((DocumentationMode)100)); options.Errors.Verify( // error CS8191: Provided documentation mode is unsupported or invalid: '100'. Diagnostic(ErrorCode.ERR_BadDocumentationMode).WithArguments("100").WithLocation(1, 1)); } [Fact] public void BadLanguageVersionShouldProduceDiagnostics() { var options = new CSharpParseOptions(languageVersion: unchecked((LanguageVersion)10000)); options.Errors.Verify( // error CS8191: Provided language version is unsupported or invalid: '10000'. Diagnostic(ErrorCode.ERR_BadLanguageVersion).WithArguments("10000").WithLocation(1, 1)); } [Fact] public void BadPreProcessorSymbolsShouldProduceDiagnostics() { var options = new CSharpParseOptions(preprocessorSymbols: new[] { "test", "1" }); options.Errors.Verify( // error CS8301: Invalid name for a preprocessing symbol; '1' is not a valid identifier Diagnostic(ErrorCode.ERR_InvalidPreprocessingSymbol).WithArguments("1").WithLocation(1, 1)); } [Fact] public void BadSourceCodeKindShouldProduceDiagnostics_WithVariation() { #pragma warning disable CS0618 // Type or member is obsolete var options = new CSharpParseOptions().WithKind(SourceCodeKind.Interactive); #pragma warning restore CS0618 // Type or member is obsolete options.Errors.Verify( // error CS8190: Provided source code kind is unsupported or invalid: 'Interactive'. Diagnostic(ErrorCode.ERR_BadSourceCodeKind).WithArguments("Interactive").WithLocation(1, 1)); } [Fact] public void BadDocumentationModeShouldProduceDiagnostics_WithVariation() { var options = new CSharpParseOptions().WithDocumentationMode(unchecked((DocumentationMode)100)); options.Errors.Verify( // error CS8191: Provided documentation mode is unsupported or invalid: '100'. Diagnostic(ErrorCode.ERR_BadDocumentationMode).WithArguments("100").WithLocation(1, 1)); } [Fact] public void BadLanguageVersionShouldProduceDiagnostics_WithVariation() { var options = new CSharpParseOptions().WithLanguageVersion(unchecked((LanguageVersion)10000)); options.Errors.Verify( // error CS8191: Provided language version is unsupported or invalid: '10000'. Diagnostic(ErrorCode.ERR_BadLanguageVersion).WithArguments("10000").WithLocation(1, 1)); } [Fact] public void BadPreProcessorSymbolsShouldProduceDiagnostics_EmptyString() { var options = new CSharpParseOptions().WithPreprocessorSymbols(new[] { "" }); options.Errors.Verify( // error CS8301: Invalid name for a preprocessing symbol; '' is not a valid identifier Diagnostic(ErrorCode.ERR_InvalidPreprocessingSymbol).WithArguments("").WithLocation(1, 1)); } [Fact] public void BadPreProcessorSymbolsShouldProduceDiagnostics_WhiteSpaceString() { var options = new CSharpParseOptions().WithPreprocessorSymbols(new[] { " " }); options.Errors.Verify( // error CS8301: Invalid name for a preprocessing symbol; ' ' is not a valid identifier Diagnostic(ErrorCode.ERR_InvalidPreprocessingSymbol).WithArguments(" ").WithLocation(1, 1)); } [Fact] public void BadPreProcessorSymbolsShouldProduceDiagnostics_SymbolWithDots() { var options = new CSharpParseOptions().WithPreprocessorSymbols(new[] { "Good", "Bad.Symbol" }); options.Errors.Verify( // error CS8301: Invalid name for a preprocessing symbol; 'Bad.Symbol' is not a valid identifier Diagnostic(ErrorCode.ERR_InvalidPreprocessingSymbol).WithArguments("Bad.Symbol").WithLocation(1, 1)); } [Fact] public void BadPreProcessorSymbolsShouldProduceDiagnostics_SymbolWithSlashes() { var options = new CSharpParseOptions().WithPreprocessorSymbols(new[] { "Good", "Bad\\Symbol" }); options.Errors.Verify( // error CS8301: Invalid name for a preprocessing symbol; 'Bad\Symbol' is not a valid identifier Diagnostic(ErrorCode.ERR_InvalidPreprocessingSymbol).WithArguments("Bad\\Symbol").WithLocation(1, 1)); } [Fact] public void BadPreProcessorSymbolsShouldProduceDiagnostics_NullSymbol() { var options = new CSharpParseOptions().WithPreprocessorSymbols(new[] { "Good", null }); options.Errors.Verify( // error CS8301: Invalid name for a preprocessing symbol; 'null' is not a valid identifier Diagnostic(ErrorCode.ERR_InvalidPreprocessingSymbol).WithArguments("null").WithLocation(1, 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. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.Parsing { public class CSharpParseOptionsTests : CSharpTestBase { private void TestProperty<T>(Func<CSharpParseOptions, T, CSharpParseOptions> factory, Func<CSharpParseOptions, T> getter, T validValue) { var oldOpt1 = CSharpParseOptions.Default; var newOpt1 = factory(oldOpt1, validValue); var newOpt2 = factory(newOpt1, validValue); Assert.Equal(validValue, getter(newOpt1)); Assert.Same(newOpt2, newOpt1); } [Fact] [WorkItem(15358, "https://github.com/dotnet/roslyn/issues/15358")] public void WithDocumentationModeDoesntChangeFeatures() { var kvp = new KeyValuePair<string, string>("IOperation", "true"); var po = new CSharpParseOptions().WithFeatures(new[] { kvp }); Assert.Equal(po.Features.AsSingleton(), kvp); var po2 = po.WithDocumentationMode(DocumentationMode.Diagnose); Assert.Equal(po2.Features.AsSingleton(), kvp); } [Fact] public void WithXxx() { TestProperty((old, value) => old.WithKind(value), opt => opt.Kind, SourceCodeKind.Script); TestProperty((old, value) => old.WithLanguageVersion(value), opt => opt.LanguageVersion, LanguageVersion.CSharp3); TestProperty((old, value) => old.WithDocumentationMode(value), opt => opt.DocumentationMode, DocumentationMode.None); TestProperty((old, value) => old.WithPreprocessorSymbols(value), opt => opt.PreprocessorSymbols, ImmutableArray.Create<string>("A", "B", "C")); Assert.Equal(0, CSharpParseOptions.Default.WithPreprocessorSymbols(ImmutableArray.Create<string>("A", "B")).WithPreprocessorSymbols(default(ImmutableArray<string>)).PreprocessorSymbols.Length); Assert.Equal(0, CSharpParseOptions.Default.WithPreprocessorSymbols(ImmutableArray.Create<string>("A", "B")).WithPreprocessorSymbols((IEnumerable<string>)null).PreprocessorSymbols.Length); Assert.Equal(0, CSharpParseOptions.Default.WithPreprocessorSymbols(ImmutableArray.Create<string>("A", "B")).WithPreprocessorSymbols((string[])null).PreprocessorSymbols.Length); } /// <summary> /// If this test fails, please update the <see cref="CSharpParseOptions.GetHashCode"/> /// and <see cref="CSharpParseOptions.Equals(CSharpParseOptions)"/> methods to /// make sure they are doing the right thing with your new field and then update the baseline /// here. /// </summary> [Fact] public void TestFieldsForEqualsAndGetHashCode() { ReflectionAssert.AssertPublicAndInternalFieldsAndProperties( typeof(CSharpParseOptions), "Features", "Language", "LanguageVersion", "PreprocessorSymbolNames", "PreprocessorSymbols", "SpecifiedLanguageVersion"); } [Fact] public void SpecifiedKindIsMappedCorrectly() { var options = new CSharpParseOptions(); Assert.Equal(SourceCodeKind.Regular, options.Kind); Assert.Equal(SourceCodeKind.Regular, options.SpecifiedKind); options.Errors.Verify(); options = new CSharpParseOptions(kind: SourceCodeKind.Regular); Assert.Equal(SourceCodeKind.Regular, options.Kind); Assert.Equal(SourceCodeKind.Regular, options.SpecifiedKind); options.Errors.Verify(); options = new CSharpParseOptions(kind: SourceCodeKind.Script); Assert.Equal(SourceCodeKind.Script, options.Kind); Assert.Equal(SourceCodeKind.Script, options.SpecifiedKind); options.Errors.Verify(); #pragma warning disable CS0618 // SourceCodeKind.Interactive is obsolete options = new CSharpParseOptions(kind: SourceCodeKind.Interactive); Assert.Equal(SourceCodeKind.Script, options.Kind); Assert.Equal(SourceCodeKind.Interactive, options.SpecifiedKind); #pragma warning restore CS0618 // SourceCodeKind.Interactive is obsolete options.Errors.Verify( // error CS8190: Provided source code kind is unsupported or invalid: 'Interactive'. Diagnostic(ErrorCode.ERR_BadSourceCodeKind).WithArguments("Interactive").WithLocation(1, 1)); options = new CSharpParseOptions(kind: (SourceCodeKind)int.MinValue); Assert.Equal(SourceCodeKind.Regular, options.Kind); Assert.Equal((SourceCodeKind)int.MinValue, options.SpecifiedKind); options.Errors.Verify( // warning CS8190: Provided source code kind is unsupported or invalid: '-2147483648' Diagnostic(ErrorCode.ERR_BadSourceCodeKind).WithArguments("-2147483648").WithLocation(1, 1)); } [Fact] public void TwoOptionsWithDifferentSpecifiedKindShouldNotHaveTheSameHashCodes() { var options1 = new CSharpParseOptions(kind: SourceCodeKind.Script); var options2 = new CSharpParseOptions(kind: SourceCodeKind.Script); Assert.Equal(options1.GetHashCode(), options2.GetHashCode()); // They both map internally to SourceCodeKind.Script #pragma warning disable CS0618 // SourceCodeKind.Interactive is obsolete options1 = new CSharpParseOptions(kind: SourceCodeKind.Script); options2 = new CSharpParseOptions(kind: SourceCodeKind.Interactive); #pragma warning restore CS0618 // SourceCodeKind.Interactive is obsolete Assert.NotEqual(options1.GetHashCode(), options2.GetHashCode()); } [Fact] public void TwoOptionsWithDifferentSpecifiedKindShouldNotBeEqual() { var options1 = new CSharpParseOptions(kind: SourceCodeKind.Script); var options2 = new CSharpParseOptions(kind: SourceCodeKind.Script); Assert.True(options1.Equals(options2)); // They both map internally to SourceCodeKind.Script #pragma warning disable CS0618 // SourceCodeKind.Interactive is obsolete options1 = new CSharpParseOptions(kind: SourceCodeKind.Script); options2 = new CSharpParseOptions(kind: SourceCodeKind.Interactive); #pragma warning restore CS0618 // SourceCodeKind.Interactive is obsolete Assert.False(options1.Equals(options2)); } [Fact] public void BadSourceCodeKindShouldProduceDiagnostics() { #pragma warning disable CS0618 // Type or member is obsolete var options = new CSharpParseOptions(kind: SourceCodeKind.Interactive); #pragma warning restore CS0618 // Type or member is obsolete options.Errors.Verify( // error CS8190: Provided source code kind is unsupported or invalid: 'Interactive'. Diagnostic(ErrorCode.ERR_BadSourceCodeKind).WithArguments("Interactive").WithLocation(1, 1)); } [Fact] public void BadDocumentationModeShouldProduceDiagnostics() { var options = new CSharpParseOptions(documentationMode: unchecked((DocumentationMode)100)); options.Errors.Verify( // error CS8191: Provided documentation mode is unsupported or invalid: '100'. Diagnostic(ErrorCode.ERR_BadDocumentationMode).WithArguments("100").WithLocation(1, 1)); } [Fact] public void BadLanguageVersionShouldProduceDiagnostics() { var options = new CSharpParseOptions(languageVersion: unchecked((LanguageVersion)10000)); options.Errors.Verify( // error CS8191: Provided language version is unsupported or invalid: '10000'. Diagnostic(ErrorCode.ERR_BadLanguageVersion).WithArguments("10000").WithLocation(1, 1)); } [Fact] public void BadPreProcessorSymbolsShouldProduceDiagnostics() { var options = new CSharpParseOptions(preprocessorSymbols: new[] { "test", "1" }); options.Errors.Verify( // error CS8301: Invalid name for a preprocessing symbol; '1' is not a valid identifier Diagnostic(ErrorCode.ERR_InvalidPreprocessingSymbol).WithArguments("1").WithLocation(1, 1)); } [Fact] public void BadSourceCodeKindShouldProduceDiagnostics_WithVariation() { #pragma warning disable CS0618 // Type or member is obsolete var options = new CSharpParseOptions().WithKind(SourceCodeKind.Interactive); #pragma warning restore CS0618 // Type or member is obsolete options.Errors.Verify( // error CS8190: Provided source code kind is unsupported or invalid: 'Interactive'. Diagnostic(ErrorCode.ERR_BadSourceCodeKind).WithArguments("Interactive").WithLocation(1, 1)); } [Fact] public void BadDocumentationModeShouldProduceDiagnostics_WithVariation() { var options = new CSharpParseOptions().WithDocumentationMode(unchecked((DocumentationMode)100)); options.Errors.Verify( // error CS8191: Provided documentation mode is unsupported or invalid: '100'. Diagnostic(ErrorCode.ERR_BadDocumentationMode).WithArguments("100").WithLocation(1, 1)); } [Fact] public void BadLanguageVersionShouldProduceDiagnostics_WithVariation() { var options = new CSharpParseOptions().WithLanguageVersion(unchecked((LanguageVersion)10000)); options.Errors.Verify( // error CS8191: Provided language version is unsupported or invalid: '10000'. Diagnostic(ErrorCode.ERR_BadLanguageVersion).WithArguments("10000").WithLocation(1, 1)); } [Fact] public void BadPreProcessorSymbolsShouldProduceDiagnostics_EmptyString() { var options = new CSharpParseOptions().WithPreprocessorSymbols(new[] { "" }); options.Errors.Verify( // error CS8301: Invalid name for a preprocessing symbol; '' is not a valid identifier Diagnostic(ErrorCode.ERR_InvalidPreprocessingSymbol).WithArguments("").WithLocation(1, 1)); } [Fact] public void BadPreProcessorSymbolsShouldProduceDiagnostics_WhiteSpaceString() { var options = new CSharpParseOptions().WithPreprocessorSymbols(new[] { " " }); options.Errors.Verify( // error CS8301: Invalid name for a preprocessing symbol; ' ' is not a valid identifier Diagnostic(ErrorCode.ERR_InvalidPreprocessingSymbol).WithArguments(" ").WithLocation(1, 1)); } [Fact] public void BadPreProcessorSymbolsShouldProduceDiagnostics_SymbolWithDots() { var options = new CSharpParseOptions().WithPreprocessorSymbols(new[] { "Good", "Bad.Symbol" }); options.Errors.Verify( // error CS8301: Invalid name for a preprocessing symbol; 'Bad.Symbol' is not a valid identifier Diagnostic(ErrorCode.ERR_InvalidPreprocessingSymbol).WithArguments("Bad.Symbol").WithLocation(1, 1)); } [Fact] public void BadPreProcessorSymbolsShouldProduceDiagnostics_SymbolWithSlashes() { var options = new CSharpParseOptions().WithPreprocessorSymbols(new[] { "Good", "Bad\\Symbol" }); options.Errors.Verify( // error CS8301: Invalid name for a preprocessing symbol; 'Bad\Symbol' is not a valid identifier Diagnostic(ErrorCode.ERR_InvalidPreprocessingSymbol).WithArguments("Bad\\Symbol").WithLocation(1, 1)); } [Fact] public void BadPreProcessorSymbolsShouldProduceDiagnostics_NullSymbol() { var options = new CSharpParseOptions().WithPreprocessorSymbols(new[] { "Good", null }); options.Errors.Verify( // error CS8301: Invalid name for a preprocessing symbol; 'null' is not a valid identifier Diagnostic(ErrorCode.ERR_InvalidPreprocessingSymbol).WithArguments("null").WithLocation(1, 1)); } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/Test/Resources/Core/SymbolsTests/RetargetingCycle/V1/ClassB.netmodule
MZ@ !L!This program cannot be run in DOS mode. $PELiL " @@ `@!K@  H.text  `.reloc @@B!HX h( *BSJB v4.0.30319l#~8#Strings@#USH#GUIDX#BlobG%3' P !  !  <Module>mscorlibClassBClassA.ctorClassB.netmodule ś?ɻB͹^Ήz\V4 !! !_CorExeMainmscoree.dll% @ 2
MZ@ !L!This program cannot be run in DOS mode. $PELiL " @@ `@!K@  H.text  `.reloc @@B!HX h( *BSJB v4.0.30319l#~8#Strings@#USH#GUIDX#BlobG%3' P !  !  <Module>mscorlibClassBClassA.ctorClassB.netmodule ś?ɻB͹^Ήz\V4 !! !_CorExeMainmscoree.dll% @ 2
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Compilers/Core/Portable/Operations/ControlFlowGraphBuilder.ImplicitInstanceInfo.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.PooledObjects; namespace Microsoft.CodeAnalysis.FlowAnalysis { internal partial class ControlFlowGraphBuilder { /// <summary> /// Holds the current object being initialized if we're visiting an object initializer. /// Or the current anonymous type object being initialized if we're visiting an anonymous type object initializer. /// Or the target of a VB With statement. /// </summary> private struct ImplicitInstanceInfo { /// <summary> /// Holds the current object instance being initialized if we're visiting an object initializer. /// </summary> public IOperation? ImplicitInstance { get; } /// <summary> /// Holds the current anonymous type instance being initialized if we're visiting an anonymous object initializer. /// </summary> public INamedTypeSymbol? AnonymousType { get; } /// <summary> /// Holds the captured values for initialized anonymous type properties in an anonymous object initializer. /// </summary> public PooledDictionary<IPropertySymbol, IOperation>? AnonymousTypePropertyValues { get; } public ImplicitInstanceInfo(IOperation currentImplicitInstance) { Debug.Assert(currentImplicitInstance != null); ImplicitInstance = currentImplicitInstance; AnonymousType = null; AnonymousTypePropertyValues = null; } public ImplicitInstanceInfo(INamedTypeSymbol currentInitializedAnonymousType) { Debug.Assert(currentInitializedAnonymousType.IsAnonymousType); ImplicitInstance = null; AnonymousType = currentInitializedAnonymousType; AnonymousTypePropertyValues = PooledDictionary<IPropertySymbol, IOperation>.GetInstance(); } public ImplicitInstanceInfo(in Context context) { Debug.Assert(context.ImplicitInstance == null || context.AnonymousType == null); if (context.ImplicitInstance != null) { ImplicitInstance = context.ImplicitInstance; AnonymousType = null; AnonymousTypePropertyValues = null; } else if (context.AnonymousType != null) { ImplicitInstance = null; AnonymousType = context.AnonymousType; AnonymousTypePropertyValues = PooledDictionary<IPropertySymbol, IOperation>.GetInstance(); foreach (KeyValuePair<IPropertySymbol, IOperation> pair in context.AnonymousTypePropertyValues) { AnonymousTypePropertyValues.Add(pair.Key, pair.Value); } } else { ImplicitInstance = null; AnonymousType = null; AnonymousTypePropertyValues = null; } } public void Free() { AnonymousTypePropertyValues?.Free(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.FlowAnalysis { internal partial class ControlFlowGraphBuilder { /// <summary> /// Holds the current object being initialized if we're visiting an object initializer. /// Or the current anonymous type object being initialized if we're visiting an anonymous type object initializer. /// Or the target of a VB With statement. /// </summary> private struct ImplicitInstanceInfo { /// <summary> /// Holds the current object instance being initialized if we're visiting an object initializer. /// </summary> public IOperation? ImplicitInstance { get; } /// <summary> /// Holds the current anonymous type instance being initialized if we're visiting an anonymous object initializer. /// </summary> public INamedTypeSymbol? AnonymousType { get; } /// <summary> /// Holds the captured values for initialized anonymous type properties in an anonymous object initializer. /// </summary> public PooledDictionary<IPropertySymbol, IOperation>? AnonymousTypePropertyValues { get; } public ImplicitInstanceInfo(IOperation currentImplicitInstance) { Debug.Assert(currentImplicitInstance != null); ImplicitInstance = currentImplicitInstance; AnonymousType = null; AnonymousTypePropertyValues = null; } public ImplicitInstanceInfo(INamedTypeSymbol currentInitializedAnonymousType) { Debug.Assert(currentInitializedAnonymousType.IsAnonymousType); ImplicitInstance = null; AnonymousType = currentInitializedAnonymousType; AnonymousTypePropertyValues = PooledDictionary<IPropertySymbol, IOperation>.GetInstance(); } public ImplicitInstanceInfo(in Context context) { Debug.Assert(context.ImplicitInstance == null || context.AnonymousType == null); if (context.ImplicitInstance != null) { ImplicitInstance = context.ImplicitInstance; AnonymousType = null; AnonymousTypePropertyValues = null; } else if (context.AnonymousType != null) { ImplicitInstance = null; AnonymousType = context.AnonymousType; AnonymousTypePropertyValues = PooledDictionary<IPropertySymbol, IOperation>.GetInstance(); foreach (KeyValuePair<IPropertySymbol, IOperation> pair in context.AnonymousTypePropertyValues) { AnonymousTypePropertyValues.Add(pair.Key, pair.Value); } } else { ImplicitInstance = null; AnonymousType = null; AnonymousTypePropertyValues = null; } } public void Free() { AnonymousTypePropertyValues?.Free(); } } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/EditorFeatures/CSharp/AutomaticCompletion/CSharpBraceCompletionServiceFactory.cs
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion { [ExportLanguageService(typeof(IBraceCompletionServiceFactory), LanguageNames.CSharp), Shared] internal class CSharpBraceCompletionServiceFactory : AbstractBraceCompletionServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpBraceCompletionServiceFactory( [ImportMany(LanguageNames.CSharp)] IEnumerable<IBraceCompletionService> braceCompletionServices, IThreadingContext threadingContext) : base(braceCompletionServices, threadingContext) { } } }
// Licensed to the .NET Foundation under one or more agreements. // 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.Composition; using Microsoft.CodeAnalysis.BraceCompletion; using Microsoft.CodeAnalysis.Editor.Implementation.AutomaticCompletion; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Editor.CSharp.AutomaticCompletion { [ExportLanguageService(typeof(IBraceCompletionServiceFactory), LanguageNames.CSharp), Shared] internal class CSharpBraceCompletionServiceFactory : AbstractBraceCompletionServiceFactory { [ImportingConstructor] [Obsolete(MefConstruction.ImportingConstructorMessage, error: true)] public CSharpBraceCompletionServiceFactory( [ImportMany(LanguageNames.CSharp)] IEnumerable<IBraceCompletionService> braceCompletionServices, IThreadingContext threadingContext) : base(braceCompletionServices, threadingContext) { } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/Features/Core/Portable/AddImport/References/Reference.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private abstract class Reference : IEquatable<Reference> { protected readonly AbstractAddImportFeatureService<TSimpleNameSyntax> provider; public readonly SearchResult SearchResult; protected Reference( AbstractAddImportFeatureService<TSimpleNameSyntax> provider, SearchResult searchResult) { this.provider = provider; SearchResult = searchResult; } public int CompareTo(Document document, Reference other) { var diff = ComparerWithState.CompareTo(this, other, document, s_comparers); if (diff != 0) { return diff; } // Both our names need to change. Sort by the name we're // changing to. diff = StringComparer.OrdinalIgnoreCase.Compare( SearchResult.DesiredName, other.SearchResult.DesiredName); if (diff != 0) { return diff; } // If the weights are the same and no names changed, just order // them based on the namespace we're adding an import for. return INamespaceOrTypeSymbolExtensions.CompareNameParts( SearchResult.NameParts, other.SearchResult.NameParts, placeSystemNamespaceFirst: true); } private static readonly ImmutableArray<Func<Reference, Document, IComparable>> s_comparers = ImmutableArray.Create<Func<Reference, Document, IComparable>>( // If references have different weights, order by the ones with lower weight (i.e. // they are better matches). (r, d) => r.SearchResult.Weight, // Prefer the name doesn't need to change. (r, d) => !r.SearchResult.DesiredNameMatchesSourceName(d)); public override bool Equals(object obj) => Equals(obj as Reference); public bool Equals(Reference other) { return other != null && other.SearchResult.NameParts != null && SearchResult.NameParts.SequenceEqual(other.SearchResult.NameParts); } public override int GetHashCode() => Hash.CombineValues(SearchResult.NameParts); protected async Task<(SyntaxNode, Document)> ReplaceNameNodeAsync( SyntaxNode contextNode, Document document, CancellationToken cancellationToken) { if (!SearchResult.DesiredNameDiffersFromSourceName()) { return (contextNode, document); } var identifier = SearchResult.NameNode.GetFirstToken(); var generator = SyntaxGenerator.GetGenerator(document); var newIdentifier = generator.IdentifierName(SearchResult.DesiredName).GetFirstToken().WithTriviaFrom(identifier); var annotation = new SyntaxAnnotation(); var root = contextNode.SyntaxTree.GetRoot(cancellationToken); root = root.ReplaceToken(identifier, newIdentifier.WithAdditionalAnnotations(annotation)); var newDocument = document.WithSyntaxRoot(root); var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newContextNode = newRoot.GetAnnotatedTokens(annotation).First().Parent; return (newContextNode, newDocument); } public abstract Task<AddImportFixData> TryGetFixDataAsync( Document document, SyntaxNode node, bool allowInHiddenRegions, CancellationToken cancellationToken); protected async Task<ImmutableArray<TextChange>> GetTextChangesAsync( Document document, SyntaxNode node, bool allowInHiddenRegions, CancellationToken cancellationToken) { var originalDocument = document; (node, document) = await ReplaceNameNodeAsync( node, document, cancellationToken).ConfigureAwait(false); var newDocument = await provider.AddImportAsync( node, SearchResult.NameParts, document, allowInHiddenRegions, cancellationToken).ConfigureAwait(false); var cleanedDocument = await CodeAction.CleanupDocumentAsync( newDocument, cancellationToken).ConfigureAwait(false); var textChanges = await cleanedDocument.GetTextChangesAsync( originalDocument, cancellationToken).ConfigureAwait(false); return textChanges.ToImmutableArray(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.AddImport { internal abstract partial class AbstractAddImportFeatureService<TSimpleNameSyntax> { private abstract class Reference : IEquatable<Reference> { protected readonly AbstractAddImportFeatureService<TSimpleNameSyntax> provider; public readonly SearchResult SearchResult; protected Reference( AbstractAddImportFeatureService<TSimpleNameSyntax> provider, SearchResult searchResult) { this.provider = provider; SearchResult = searchResult; } public int CompareTo(Document document, Reference other) { var diff = ComparerWithState.CompareTo(this, other, document, s_comparers); if (diff != 0) { return diff; } // Both our names need to change. Sort by the name we're // changing to. diff = StringComparer.OrdinalIgnoreCase.Compare( SearchResult.DesiredName, other.SearchResult.DesiredName); if (diff != 0) { return diff; } // If the weights are the same and no names changed, just order // them based on the namespace we're adding an import for. return INamespaceOrTypeSymbolExtensions.CompareNameParts( SearchResult.NameParts, other.SearchResult.NameParts, placeSystemNamespaceFirst: true); } private static readonly ImmutableArray<Func<Reference, Document, IComparable>> s_comparers = ImmutableArray.Create<Func<Reference, Document, IComparable>>( // If references have different weights, order by the ones with lower weight (i.e. // they are better matches). (r, d) => r.SearchResult.Weight, // Prefer the name doesn't need to change. (r, d) => !r.SearchResult.DesiredNameMatchesSourceName(d)); public override bool Equals(object obj) => Equals(obj as Reference); public bool Equals(Reference other) { return other != null && other.SearchResult.NameParts != null && SearchResult.NameParts.SequenceEqual(other.SearchResult.NameParts); } public override int GetHashCode() => Hash.CombineValues(SearchResult.NameParts); protected async Task<(SyntaxNode, Document)> ReplaceNameNodeAsync( SyntaxNode contextNode, Document document, CancellationToken cancellationToken) { if (!SearchResult.DesiredNameDiffersFromSourceName()) { return (contextNode, document); } var identifier = SearchResult.NameNode.GetFirstToken(); var generator = SyntaxGenerator.GetGenerator(document); var newIdentifier = generator.IdentifierName(SearchResult.DesiredName).GetFirstToken().WithTriviaFrom(identifier); var annotation = new SyntaxAnnotation(); var root = contextNode.SyntaxTree.GetRoot(cancellationToken); root = root.ReplaceToken(identifier, newIdentifier.WithAdditionalAnnotations(annotation)); var newDocument = document.WithSyntaxRoot(root); var newRoot = await newDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var newContextNode = newRoot.GetAnnotatedTokens(annotation).First().Parent; return (newContextNode, newDocument); } public abstract Task<AddImportFixData> TryGetFixDataAsync( Document document, SyntaxNode node, bool allowInHiddenRegions, CancellationToken cancellationToken); protected async Task<ImmutableArray<TextChange>> GetTextChangesAsync( Document document, SyntaxNode node, bool allowInHiddenRegions, CancellationToken cancellationToken) { var originalDocument = document; (node, document) = await ReplaceNameNodeAsync( node, document, cancellationToken).ConfigureAwait(false); var newDocument = await provider.AddImportAsync( node, SearchResult.NameParts, document, allowInHiddenRegions, cancellationToken).ConfigureAwait(false); var cleanedDocument = await CodeAction.CleanupDocumentAsync( newDocument, cancellationToken).ConfigureAwait(false); var textChanges = await cleanedDocument.GetTextChangesAsync( originalDocument, cancellationToken).ConfigureAwait(false); return textChanges.ToImmutableArray(); } } } }
-1
dotnet/roslyn
56,022
Allow null literals to contribute nullability to type inference
Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
RikkiGibson
2021-08-30T23:34:07Z
2021-09-09T22:00:17Z
0ffddc6c7745f0fa12ad134c35505cd0914a5ced
861b4278665672acf6c9c388bbd9e32d8f7657d6
Allow null literals to contribute nullability to type inference. Closes #43536 ~~We skip removing conversions from call arguments when the conversion is predefined and applied to a null literal. Note that other kinds of constant-null expressions we do expect to have a natural type, so we do remove their conversion.~~ Changed approach to instead add special "nullable bounds" to method type inference per https://github.com/dotnet/roslyn/pull/56022#issuecomment-909400174. Will update the PR title prior to merge to avoid messing up email threading.
./src/VisualStudio/Core/Test/CodeModel/AbstractCodeModelObjectTests.CodeTypeRefData.vb
' Licensed to the .NET Foundation under one or more agreements. ' The .NET Foundation licenses this file to you under the MIT license. ' See the LICENSE file in the project root for more information. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class) Protected Class CodeTypeRefData Public Property CodeTypeFullName As String Public Property TypeKind As EnvDTE.vsCMTypeRef = EnvDTE.vsCMTypeRef.vsCMTypeRefOther Public Property AsString As String Public Property AsFullName As String 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. Namespace Microsoft.VisualStudio.LanguageServices.UnitTests.CodeModel Partial Public MustInherit Class AbstractCodeModelObjectTests(Of TCodeModelObject As Class) Protected Class CodeTypeRefData Public Property CodeTypeFullName As String Public Property TypeKind As EnvDTE.vsCMTypeRef = EnvDTE.vsCMTypeRef.vsCMTypeRefOther Public Property AsString As String Public Property AsFullName As String End Class End Class End Namespace
-1
dotnet/roslyn
56,015
Remove obsolete APIs
Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
tmat
2021-08-30T20:53:26Z
2021-09-02T16:56:01Z
bdf1025480ad91f8db054959553257746f58f527
e782ce78f087060a3bc51737d3f07a6d102fb7b1
Remove obsolete APIs. Blocked on https://devdiv.visualstudio.com/DevDiv/_git/VS/pullrequest/347881
./src/VisualStudio/Core/Def/Implementation/Watson/WatsonReporter.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Reflection; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Remote; using Microsoft.VisualStudio.LanguageServices.Telemetry; using Microsoft.VisualStudio.Telemetry; namespace Microsoft.CodeAnalysis.ErrorReporting { internal static class WatsonReporter { private static Dictionary<string, string>? s_capturedFileContent; private static readonly object _guard = new(); private static ImmutableArray<TelemetrySession> s_telemetrySessions = ImmutableArray<TelemetrySession>.Empty; private static ImmutableArray<TraceSource> s_loggers = ImmutableArray<TraceSource>.Empty; public static void InitializeFatalErrorHandlers() { // Set both handlers to non-fatal Watson. Never fail-fast the ServiceHub process. // Any exception that is not recovered from shall be propagated and communicated to the client. var nonFatalHandler = new Action<Exception>(ReportNonFatal); var fatalHandler = nonFatalHandler; FatalError.Handler = fatalHandler; FatalError.NonFatalHandler = nonFatalHandler; // We also must set the handlers for the compiler layer as well. var compilerAssembly = typeof(Compilation).Assembly; var compilerFatalErrorType = compilerAssembly.GetType("Microsoft.CodeAnalysis.FatalError", throwOnError: true)!; var compilerFatalErrorHandlerProperty = compilerFatalErrorType.GetProperty(nameof(FatalError.Handler), BindingFlags.Static | BindingFlags.Public)!; var compilerNonFatalErrorHandlerProperty = compilerFatalErrorType.GetProperty(nameof(FatalError.NonFatalHandler), BindingFlags.Static | BindingFlags.Public)!; compilerFatalErrorHandlerProperty.SetValue(null, fatalHandler); compilerNonFatalErrorHandlerProperty.SetValue(null, nonFatalHandler); } public static void RegisterTelemetrySesssion(TelemetrySession session) { lock (_guard) { s_telemetrySessions = s_telemetrySessions.Add(session); } } public static void UnregisterTelemetrySesssion(TelemetrySession session) { lock (_guard) { s_telemetrySessions = s_telemetrySessions.Remove(session); } } public static void RegisterLogger(TraceSource logger) { lock (_guard) { s_loggers = s_loggers.Add(logger); } } public static void UnregisterLogger(TraceSource logger) { lock (_guard) { s_loggers = s_loggers.Remove(logger); } } /// <summary> /// Report Non-Fatal Watson for a given unhandled exception. /// </summary> /// <param name="exception">Exception that triggered this non-fatal error</param> public static void ReportNonFatal(Exception exception) { try { var emptyCallstack = exception.SetCallstackIfEmpty(); var currentProcess = Process.GetCurrentProcess(); // write the exception to a log file: var logMessage = $"[{currentProcess.ProcessName}:{currentProcess.Id}] Unexpected exception: {exception}"; foreach (var logger in s_loggers) { logger.TraceEvent(TraceEventType.Error, 1, logMessage); } var faultEvent = new FaultEvent( eventName: FunctionId.NonFatalWatson.GetEventName(), description: GetDescription(exception), FaultSeverity.Diagnostic, exceptionObject: exception, gatherEventDetails: faultUtility => { if (faultUtility is FaultEvent { IsIncludedInWatsonSample: true }) { // add ServiceHub log files: foreach (var path in CollectServiceHubLogFilePaths()) { faultUtility.AddFile(path); } } // Returning "0" signals that, if sampled, we should send data to Watson. // Any other value will cancel the Watson report. We never want to trigger a process dump manually, // we'll let TargetedNotifications determine if a dump should be collected. // See https://aka.ms/roslynnfwdocs for more details return 0; }); // add extra bucket parameters to bucket better in NFW // we do it here so that it gets bucketted better in both // watson and telemetry. faultEvent.SetExtraParameters(exception, emptyCallstack); foreach (var session in s_telemetrySessions) { session.PostEvent(faultEvent); } } catch (OutOfMemoryException) { FailFast.OnFatalException(exception); } catch (Exception e) { FailFast.OnFatalException(e); } } private static string GetDescription(Exception exception) { const string CodeAnalysisNamespace = nameof(Microsoft) + "." + nameof(CodeAnalysis); // Be resilient to failing here. If we can't get a suitable name, just fall back to the standard name we // used to report. try { // walk up the stack looking for the first call from a type that isn't in the ErrorReporting namespace. foreach (var frame in new StackTrace(exception).GetFrames()) { var method = frame?.GetMethod(); var methodName = method?.Name; if (methodName == null) continue; var declaringTypeName = method?.DeclaringType?.FullName; if (declaringTypeName == null) continue; if (!declaringTypeName.StartsWith(CodeAnalysisNamespace)) continue; return declaringTypeName + "." + methodName; } } catch { } return "Roslyn NonFatal Watson"; } private static List<string> CollectServiceHubLogFilePaths() { var paths = new List<string>(); try { var logPath = Path.Combine(Path.GetTempPath(), "servicehub", "logs"); if (!Directory.Exists(logPath)) { return paths; } // attach all log files that are modified less than 1 day before. var now = DateTime.UtcNow; var oneDay = TimeSpan.FromDays(1); foreach (var path in Directory.EnumerateFiles(logPath, "*.log")) { try { var name = Path.GetFileNameWithoutExtension(path); // TODO: https://github.com/dotnet/roslyn/issues/42582 // name our services more consistently to simplify filtering // filter logs that are not relevant to Roslyn investigation if (!name.Contains("-" + ServiceDescriptors.ServiceNameTopLevelPrefix) && !name.Contains("-" + RemoteServiceName.Prefix) && !name.Contains("-" + RemoteServiceName.IntelliCodeServiceName) && !name.Contains("-" + RemoteServiceName.RazorServiceName) && !name.Contains("-" + RemoteServiceName.UnitTestingAnalysisServiceName) && !name.Contains("-" + RemoteServiceName.LiveUnitTestingBuildServiceName) && !name.Contains("-" + RemoteServiceName.UnitTestingSourceLookupServiceName) && !name.Contains("-CodeLens") && !name.Contains("-ManagedLanguage.IDE.RemoteHostClient") && !name.Contains("-hub")) { continue; } var lastWrite = File.GetLastWriteTimeUtc(path); if (now - lastWrite > oneDay) { continue; } paths.Add(path); } catch { // ignore file that can't be accessed } } } catch (Exception) { // ignore failures } return paths; } private static void CaptureFilesInMemory(IEnumerable<string> paths) { s_capturedFileContent = new Dictionary<string, string>(); foreach (var path in paths) { try { s_capturedFileContent[path] = File.ReadAllText(path); } catch { // ignore file that can't be read } } } } internal enum WatsonSeverity { /// <summary> /// Indicate that this watson is informative and not urgent /// </summary> Default, /// <summary> /// Indicate that this watson is critical and need to be addressed soon /// </summary> Critical, } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Reflection; using Microsoft.CodeAnalysis.Internal.Log; using Microsoft.CodeAnalysis.Remote; using Microsoft.VisualStudio.LanguageServices.Telemetry; using Microsoft.VisualStudio.Telemetry; namespace Microsoft.CodeAnalysis.ErrorReporting { internal static class WatsonReporter { private static Dictionary<string, string>? s_capturedFileContent; private static readonly object _guard = new(); private static ImmutableArray<TelemetrySession> s_telemetrySessions = ImmutableArray<TelemetrySession>.Empty; private static ImmutableArray<TraceSource> s_loggers = ImmutableArray<TraceSource>.Empty; public static void InitializeFatalErrorHandlers() { // Set both handlers to non-fatal Watson. Never fail-fast the ServiceHub process. // Any exception that is not recovered from shall be propagated and communicated to the client. var nonFatalHandler = new Action<Exception>(ReportNonFatal); var fatalHandler = nonFatalHandler; FatalError.Handler = fatalHandler; FatalError.NonFatalHandler = nonFatalHandler; // We also must set the handlers for the compiler layer as well. var compilerAssembly = typeof(Compilation).Assembly; var compilerFatalErrorType = compilerAssembly.GetType("Microsoft.CodeAnalysis.FatalError", throwOnError: true)!; var compilerFatalErrorHandlerProperty = compilerFatalErrorType.GetProperty(nameof(FatalError.Handler), BindingFlags.Static | BindingFlags.Public)!; var compilerNonFatalErrorHandlerProperty = compilerFatalErrorType.GetProperty(nameof(FatalError.NonFatalHandler), BindingFlags.Static | BindingFlags.Public)!; compilerFatalErrorHandlerProperty.SetValue(null, fatalHandler); compilerNonFatalErrorHandlerProperty.SetValue(null, nonFatalHandler); } public static void RegisterTelemetrySesssion(TelemetrySession session) { lock (_guard) { s_telemetrySessions = s_telemetrySessions.Add(session); } } public static void UnregisterTelemetrySesssion(TelemetrySession session) { lock (_guard) { s_telemetrySessions = s_telemetrySessions.Remove(session); } } public static void RegisterLogger(TraceSource logger) { lock (_guard) { s_loggers = s_loggers.Add(logger); } } public static void UnregisterLogger(TraceSource logger) { lock (_guard) { s_loggers = s_loggers.Remove(logger); } } /// <summary> /// Report Non-Fatal Watson for a given unhandled exception. /// </summary> /// <param name="exception">Exception that triggered this non-fatal error</param> public static void ReportNonFatal(Exception exception) { try { var emptyCallstack = exception.SetCallstackIfEmpty(); var currentProcess = Process.GetCurrentProcess(); // write the exception to a log file: var logMessage = $"[{currentProcess.ProcessName}:{currentProcess.Id}] Unexpected exception: {exception}"; foreach (var logger in s_loggers) { logger.TraceEvent(TraceEventType.Error, 1, logMessage); } var faultEvent = new FaultEvent( eventName: FunctionId.NonFatalWatson.GetEventName(), description: GetDescription(exception), FaultSeverity.Diagnostic, exceptionObject: exception, gatherEventDetails: faultUtility => { if (faultUtility is FaultEvent { IsIncludedInWatsonSample: true }) { // add ServiceHub log files: foreach (var path in CollectServiceHubLogFilePaths()) { faultUtility.AddFile(path); } } // Returning "0" signals that, if sampled, we should send data to Watson. // Any other value will cancel the Watson report. We never want to trigger a process dump manually, // we'll let TargetedNotifications determine if a dump should be collected. // See https://aka.ms/roslynnfwdocs for more details return 0; }); // add extra bucket parameters to bucket better in NFW // we do it here so that it gets bucketted better in both // watson and telemetry. faultEvent.SetExtraParameters(exception, emptyCallstack); foreach (var session in s_telemetrySessions) { session.PostEvent(faultEvent); } } catch (OutOfMemoryException) { FailFast.OnFatalException(exception); } catch (Exception e) { FailFast.OnFatalException(e); } } private static string GetDescription(Exception exception) { const string CodeAnalysisNamespace = nameof(Microsoft) + "." + nameof(CodeAnalysis); // Be resilient to failing here. If we can't get a suitable name, just fall back to the standard name we // used to report. try { // walk up the stack looking for the first call from a type that isn't in the ErrorReporting namespace. foreach (var frame in new StackTrace(exception).GetFrames()) { var method = frame?.GetMethod(); var methodName = method?.Name; if (methodName == null) continue; var declaringTypeName = method?.DeclaringType?.FullName; if (declaringTypeName == null) continue; if (!declaringTypeName.StartsWith(CodeAnalysisNamespace)) continue; return declaringTypeName + "." + methodName; } } catch { } return "Roslyn NonFatal Watson"; } private static List<string> CollectServiceHubLogFilePaths() { var paths = new List<string>(); try { var logPath = Path.Combine(Path.GetTempPath(), "servicehub", "logs"); if (!Directory.Exists(logPath)) { return paths; } // attach all log files that are modified less than 1 day before. var now = DateTime.UtcNow; var oneDay = TimeSpan.FromDays(1); foreach (var path in Directory.EnumerateFiles(logPath, "*.log")) { try { var name = Path.GetFileNameWithoutExtension(path); // TODO: https://github.com/dotnet/roslyn/issues/42582 // name our services more consistently to simplify filtering // filter logs that are not relevant to Roslyn investigation if (!name.Contains("-" + ServiceDescriptors.ServiceNameTopLevelPrefix) && !name.Contains("-" + RemoteServiceName.Prefix) && !name.Contains("-CodeLens") && !name.Contains("-ManagedLanguage.IDE.RemoteHostClient") && !name.Contains("-hub")) { continue; } var lastWrite = File.GetLastWriteTimeUtc(path); if (now - lastWrite > oneDay) { continue; } paths.Add(path); } catch { // ignore file that can't be accessed } } } catch (Exception) { // ignore failures } return paths; } private static void CaptureFilesInMemory(IEnumerable<string> paths) { s_capturedFileContent = new Dictionary<string, string>(); foreach (var path in paths) { try { s_capturedFileContent[path] = File.ReadAllText(path); } catch { // ignore file that can't be read } } } } internal enum WatsonSeverity { /// <summary> /// Indicate that this watson is informative and not urgent /// </summary> Default, /// <summary> /// Indicate that this watson is critical and need to be addressed soon /// </summary> Critical, } }
1